feat(cluster): RFC 010 c10–c16, follow-ups and Phase 6 (squash of 16ef583..d9c62a8)

Tree snapshot of d9c62a8 (2026-08-18). The 20 source commits between
16ef583 (c9) and d9c62a8 were never pushed and the clone that held them
was lost; this commit carries their combined tree verbatim so the build
history stays auditable from the c1–c9 commits below it. Original
hashes as recorded in the session handoff:

  c10  f03e94d  pid targeting + auto-serialization (RemotePid, D14 name
                on the wire); Phase 3 gate
  c11  7ef4bad  DownReason::Disconnected, wire tag 5
  c12  d124162  remote monitors (Monitor/Demonitor/Down frames)
  c13  9de967b  connection-loss synthesis (A+B: Monitors::teardown +
                unread-command Disconnected); Phase 4 gate
  c14  7e822b7  eager pg eviction (reaper actor, ReaperInboxes)
       dbe1a22  InboundVerdict::label(), trace::Event::ClusterInbound
       31a9877  tests/channel.rs monitor-churn target gated on `go`
       653559e  Discovery::Withdrawn{name, addr}
  c15  b41d76e  distributed pg: Sync on NodeUp, Join/Leave broadcast,
                NodeDown sweep, members_all; PgMsg wire type
  c16  fafa881  pick_any / dispatch_any; Phase 5 complete
  Phase 6 Tier A:
       195c73e  p4  NodeEvent::NodeDown(NodeInfo)
       48fd766  p1  connector Candidate{name, addr, state}
       ce8cf99  p2+p7 conn.rs select arms as Vec<Arm>; Outbound::Drained
       bf24988  p6  RemotePid::from_local -> Option
       9ae0380  p3  PeerStanding{Free, Claimed, Dialing}
       c7d62a1  p11 cluster::Timing knobs, threaded by value
       46f171d  p11 cluster_disconnect un-ignored on SMARM_FAST_TIMING
  Phase 6 Tier B:
       391a9ae  p5  cluster::RemoteDownReason{Local, Disconnected};
                    DownReason::Disconnected removed from core
       7ddd908  p9  pg ctl channel unconditional, one cfg seam at spawn
       d9c62a8      PeerNameMismatch parks the candidate; ClusterDial trace

Verified at d9c62a8: default 361/0, cluster 448/0, clippy --lib on
default / cluster / cluster+smarm-trace, fmt, 10x flake on
cluster_dial_mismatch, 5x on cluster_pg.
This commit is contained in:
claude-asm-audit
2026-08-18 16:00:00 +02:00
parent 16ef583455
commit 4c0e42152f
32 changed files with 4202 additions and 578 deletions
+380 -51
View File
@@ -27,21 +27,52 @@
//! drained onto the wire in the same loop — and inbound *interpretation*:
//! `SendNamed` goes to the one resolution seam,
//! [`remote::deliver_named`](crate::cluster::remote::deliver_named).
//! Frames the connection actor has no business with yet (`Send`, `Monitor`,
//! …: c10/c11) are consumed for liveness and otherwise ignored. The outbound
//! `Send` goes to the pid seam (c10). The outbound
//! sender is a separate channel from `cmd_tx` on purpose: closing it is not
//! a stop signal — lifetime authority stays with the [`ConnHandle`] (D9).
//!
//! c12 adds the monitor plane, and it lives *here* on purpose. Two tables,
//! both owned by this actor and dying with the connection:
//!
//! - **outstanding** — monitors *this* node holds on actors at the peer:
//! `monitor_id → (target, Sender<RemoteDown>)`. Fed by
//! [`MonCmd`](crate::cluster::remote::MonCmd) from `monitor_remote`; the
//! actor records the id and *then* emits the `Monitor` frame, so a `Down`
//! frame can never race an entry that isn't there yet. An inbound `Down`
//! removes the entry and delivers.
//! - **watched** — monitors the *peer* holds on actors here: `monitor_id →
//! local Monitor`. An inbound `Monitor` is admitted only for a pid that
//! was exposed or crossed the wire (`is_watchable`, D12): a corpse answers
//! with its recorded terminal reason (RFC §6), an unwatchable or unknown
//! pid with `NoProc` — indistinguishable from dead, so nothing leaks. A
//! live watchable pid gets a local monitor whose `rx` is one more arm of
//! the select; its `Down` goes back as a frame.
//!
//! Because both tables are actor state, connection loss (c13) needs no
//! second bookkeeping owner: this actor's exit is the one place that knows
//! every monitor the link was carrying. `Monitors::teardown` runs on every
//! exit path and answers each outstanding monitor with `Disconnected` —
//! the roadmap's "partition vs. death" contrast: an actor that dies sends
//! its true reason over the link, a link that dies says only that.
use std::collections::HashMap;
use std::time::{Duration, Instant};
use crate::channel::{channel, try_select_timeout, Receiver, Selectable, Sender};
use crate::cluster::envelope::Frame;
use crate::cluster::envelope::{Frame, RemoteDownReason};
use crate::cluster::handshake::Peer;
use crate::cluster::manager::{Call, Registered, Reply, MANAGER};
use crate::cluster::remote::deliver_named;
use crate::cluster::remote::{
deliver_named, deliver_to_pid, InboundVerdict, MonCmd, RemoteDown, RemotePid,
};
use crate::cluster::transport::FramedConn;
use crate::cluster::Timing;
use crate::gen_server;
use crate::pid::Pid;
use crate::monitor::{
demonitor, is_watchable, monitor, terminal_reason, DownReason, Monitor, MonitorId,
};
use crate::pid::{Erased, Pid};
use crate::scheduler::spawn;
/// Commands to a running connection actor.
@@ -57,11 +88,11 @@ enum Cmd {
/// to establish it.
pub struct ConnHandle {
cmd_tx: Sender<Cmd>,
/// The connection's dedicated outbound inbox. The manager moves this
/// into the outbound table on `Register` (see
/// [`take_outbound`](ConnHandle::take_outbound)); a `Duplicate` verdict
/// drops it with the handle.
out_tx: Option<Sender<Frame>>,
/// The connection's dedicated outbound inboxes — frames and monitor
/// commands. The manager moves them into the outbound table on
/// `Register` (see [`take_outbound`](ConnHandle::take_outbound)); a
/// `Duplicate` verdict drops them with the handle.
out_tx: Option<(Sender<Frame>, Sender<MonCmd>)>,
}
impl std::fmt::Debug for ConnHandle {
@@ -78,9 +109,9 @@ impl ConnHandle {
let _ = self.cmd_tx.send(Cmd::Shutdown);
}
/// Manager-only: take the outbound sender to bind into the outbound
/// Manager-only: take the outbound senders to bind into the outbound
/// table. Once, at registration.
pub(crate) fn take_outbound(&mut self) -> Option<Sender<Frame>> {
pub(crate) fn take_outbound(&mut self) -> Option<(Sender<Frame>, Sender<MonCmd>)> {
self.out_tx.take()
}
}
@@ -96,11 +127,16 @@ pub struct RegisterRefused;
/// actor's [`ConnHandle`]; the caller gets only the [`Pid`], because
/// connection lifetime belongs to the table and not to the establishing
/// actor. A refusal has already stopped the actor and closed the socket.
pub fn spawn_established(framed: FramedConn, peer: Peer) -> Result<Pid, RegisterRefused> {
pub fn spawn_established(
framed: FramedConn,
peer: Peer,
timing: Timing,
) -> Result<Pid, RegisterRefused> {
let (cmd_tx, cmd_rx) = channel();
let (out_tx, out_rx) = channel();
let (mon_tx, mon_rx) = channel();
let reg_peer = peer.clone();
let pid = spawn(move || run(framed, peer, cmd_rx, out_rx)).pid();
let pid = spawn(move || run(framed, peer, timing, cmd_rx, out_rx, mon_rx)).pid();
match gen_server::call(
MANAGER,
Call::Register {
@@ -108,7 +144,7 @@ pub fn spawn_established(framed: FramedConn, peer: Peer) -> Result<Pid, Register
pid,
handle: ConnHandle {
cmd_tx,
out_tx: Some(out_tx),
out_tx: Some((out_tx, mon_tx)),
},
},
) {
@@ -120,25 +156,136 @@ pub fn spawn_established(framed: FramedConn, peer: Peer) -> Result<Pid, Register
}
}
/// How often this end emits [`Frame::Heartbeat`] on an idle connection. The
/// first one goes out immediately at spawn, so the peer's liveness window
/// starts fed.
/// Default for [`Timing::heartbeat_interval`]: how often this end emits
/// [`Frame::Heartbeat`] on an idle connection. The first one goes out
/// immediately at spawn, so the peer's liveness window starts fed.
pub const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(1);
/// How long the connection may go without a single inbound frame before it
/// is declared dead and torn down. Any inbound frame resets the window —
/// Default for [`Timing::liveness_timeout`]: how long the connection may go
/// without a single inbound frame before it is declared dead and torn down. Any inbound frame resets the window —
/// heartbeats keep an idle connection alive, and real traffic (c8+) counts
/// for free. Fixed by design (RFC v2 §5): this is the control connection, a
/// heartbeat can never queue behind bulk traffic, so a fixed timeout is an
/// honest detector.
pub const LIVENESS_TIMEOUT: Duration = Duration::from_secs(4);
fn run(mut framed: FramedConn, _peer: Peer, cmd_rx: Receiver<Cmd>, out_rx: Receiver<Frame>) {
fn run(
mut framed: FramedConn,
_peer: Peer,
timing: Timing,
cmd_rx: Receiver<Cmd>,
out_rx: Receiver<Frame>,
mon_rx: Receiver<MonCmd>,
) {
let mut mons = Monitors::default();
match framed.readable_arm() {
Some(arm) => run_live(&mut framed, arm, &cmd_rx, &out_rx),
Some(arm) => run_live(
&mut framed,
arm,
timing,
&cmd_rx,
&out_rx,
&mon_rx,
&mut mons,
),
None => run_inert(&cmd_rx),
}
framed.close();
mons.teardown(&mon_rx);
}
/// The monitor plane's two tables (module docs). Owned by the actor.
#[derive(Default)]
struct Monitors {
/// Monitors this node holds on peer actors: id → (target, delivery).
outstanding: HashMap<MonitorId, (RemotePid<Erased>, Sender<RemoteDown>)>,
/// Monitors the peer holds on local actors: id → the local monitor.
watched: HashMap<MonitorId, Monitor>,
}
impl Monitors {
/// The connection is gone, whatever the exit path (liveness expiry,
/// EOF, wire failure, commanded stop): release the peer's local
/// monitors, and answer every one of ours with `Disconnected` — nothing
/// more can be known about those actors. Commands still sitting in the
/// inbox are folded in first (a `Monitor` handed to us but never
/// processed gets its notice too; a `Demonitor` still cancels), so the
/// only registration that can miss this is one that lands after the
/// drain and before the inbox drops — the reader side backstops that
/// (`RemoteMonitor`). Entries leave the table as they are answered, and
/// this runs once per actor, so no monitor sees two notices.
fn teardown(&mut self, mon_rx: &Receiver<MonCmd>) {
for (_, m) in self.watched.drain() {
let _ = demonitor(&m);
}
while let Ok(Some(cmd)) = mon_rx.try_recv() {
match cmd {
MonCmd::Monitor { id, target, tx } => {
self.outstanding.insert(id, (target, tx));
}
MonCmd::Demonitor { id } => {
self.outstanding.remove(&id);
}
}
}
for (_, (pid, tx)) in self.outstanding.drain() {
let _ = tx.send(RemoteDown {
pid,
reason: RemoteDownReason::Disconnected,
});
}
}
/// Admit a peer's `Monitor` for local `(index, generation)`. Returns
/// the reason to answer with at once, or `None` if a live monitor was
/// installed. Corpse → recorded terminal reason (RFC §6, and only
/// watchable deaths are recorded); live watchable → monitor; anything
/// else → `NoProc`. The check-then-monitor race (dies in between) is
/// closed on the read side: a `NoProc` from a monitor we installed on a
/// live pid is upgraded through `terminal_reason` in `sweep_watched`.
fn admit(&mut self, id: MonitorId, index: u32, generation: u32) -> Option<DownReason> {
let pid = Pid::new(index, generation);
if let Some(reason) = terminal_reason(pid) {
return Some(reason);
}
if !is_watchable(pid) {
return Some(DownReason::NoProc);
}
let m = monitor(pid);
self.watched.insert(id, m);
None
}
fn cancel(&mut self, id: MonitorId) {
if let Some(m) = self.watched.remove(&id) {
let _ = demonitor(&m);
}
}
/// Collect every local `Down` that has arrived for a peer-held monitor.
fn sweep_watched(&mut self) -> Vec<(MonitorId, DownReason)> {
let mut fired = Vec::new();
for (id, m) in self.watched.iter() {
if let Ok(Some(down)) = m.rx.try_recv() {
let reason = match down.reason {
DownReason::NoProc => terminal_reason(m.target).unwrap_or(DownReason::NoProc),
r => r,
};
fired.push((*id, reason));
}
}
for (id, _) in &fired {
self.watched.remove(id);
}
fired
}
/// The peer reports a monitored actor down: deliver locally.
fn down(&mut self, id: MonitorId, reason: RemoteDownReason) {
if let Some((pid, tx)) = self.outstanding.remove(&id) {
let _ = tx.send(RemoteDown { pid, reason });
}
}
}
/// The steady-state loop over an fd-backed connection: one
@@ -148,15 +295,39 @@ fn run(mut framed: FramedConn, _peer: Peer, cmd_rx: Receiver<Cmd>, out_rx: Recei
fn run_live(
framed: &mut FramedConn,
arm: crate::scheduler::FdArm,
timing: Timing,
cmd_rx: &Receiver<Cmd>,
out_rx: &Receiver<Frame>,
mon_rx: &Receiver<MonCmd>,
mons: &mut Monitors,
) {
let mut next_hb = Instant::now();
let mut live_until = Instant::now() + LIVENESS_TIMEOUT;
// The outbound sender lives in the manager's table and is dropped on
// unbind; after that this arm would wake forever, so it drops out of
let mut live_until = Instant::now() + timing.liveness_timeout;
// The outbound senders live in the manager's table and are dropped on
// unbind; after that these arms would wake forever, so they drop out of
// the select (not a stop signal — see the module docs).
let mut out_open = true;
let mut mon_open = true;
// Which wait each select arm stands for. Built in lockstep with the
// `Selectable` vector each iteration, so a wake is decoded by name and
// never by position.
enum Arm {
Cmd,
Fd,
Out,
Mon,
/// A peer-held local monitor (any of them: firing sweeps them all).
Watched,
}
fn push<'s>(
arms: &mut Vec<&'s dyn Selectable>,
what: &mut Vec<Arm>,
s: &'s dyn Selectable,
a: Arm,
) {
arms.push(s);
what.push(a);
}
loop {
let now = Instant::now();
if now >= live_until {
@@ -166,33 +337,57 @@ fn run_live(
if framed.send(&Frame::Heartbeat).is_err() {
break;
}
next_hb = now + HEARTBEAT_INTERVAL;
next_hb = now + timing.heartbeat_interval;
}
let wait = next_hb.min(live_until).saturating_duration_since(now);
// Arm indices: 0 cmd, 1 fd, 2 outbound (when open).
let mut arms: Vec<&dyn Selectable> = vec![cmd_rx, &arm];
let mut arms: Vec<&dyn Selectable> = Vec::new();
let mut what: Vec<Arm> = Vec::new();
push(&mut arms, &mut what, cmd_rx, Arm::Cmd);
push(&mut arms, &mut what, &arm, Arm::Fd);
if out_open {
arms.push(out_rx);
push(&mut arms, &mut what, out_rx, Arm::Out);
}
match try_select_timeout(&arms, wait) {
Ok(Some(0)) => {
if mon_open {
push(&mut arms, &mut what, mon_rx, Arm::Mon);
}
for m in mons.watched.values() {
push(&mut arms, &mut what, &m.rx, Arm::Watched);
}
match try_select_timeout(&arms, wait).map(|i| i.map(|i| &what[i])) {
Ok(Some(Arm::Cmd)) => {
if should_stop(cmd_rx) {
break;
}
}
Ok(Some(1)) => match pump_readable(framed) {
Ok(Some(Arm::Fd)) => match pump_readable(framed, mons) {
Pump::Ended => break,
Pump::Frames(n) => {
if n > 0 {
live_until = Instant::now() + LIVENESS_TIMEOUT;
live_until = Instant::now() + timing.liveness_timeout;
}
}
},
Ok(Some(_)) => match pump_outbound(framed, out_rx) {
Outbound::Sent => {}
Ok(Some(Arm::Out)) => match pump_outbound(framed, out_rx) {
Outbound::Drained => {}
Outbound::Closed => out_open = false,
Outbound::WireFailed => break,
},
Ok(Some(Arm::Mon)) => match pump_moncmds(framed, mon_rx, mons) {
Outbound::Drained => {}
Outbound::Closed => mon_open = false,
Outbound::WireFailed => break,
},
Ok(Some(Arm::Watched)) => {
for (id, reason) in mons.sweep_watched() {
let frame = Frame::Down {
monitor_id: id.0,
reason: reason.into(),
};
if framed.send(&frame).is_err() {
return;
}
}
}
// A deadline passed; the top of the loop acts on whichever.
Ok(None) => {}
// The fd arm failed to register — the connection is gone.
@@ -201,9 +396,42 @@ fn run_live(
}
}
/// What one outbound wake yielded.
/// Drain the monitor-command inbox: record, then emit (module docs).
fn pump_moncmds(
framed: &mut FramedConn,
mon_rx: &Receiver<MonCmd>,
mons: &mut Monitors,
) -> Outbound {
loop {
match mon_rx.try_recv() {
Ok(Some(MonCmd::Monitor { id, target, tx })) => {
let frame = Frame::Monitor {
monitor_id: id.0,
index: target.index(),
generation: target.generation(),
};
mons.outstanding.insert(id, (target, tx));
if framed.send(&frame).is_err() {
return Outbound::WireFailed;
}
}
Ok(Some(MonCmd::Demonitor { id })) => {
if mons.outstanding.remove(&id).is_some()
&& framed.send(&Frame::Demonitor { monitor_id: id.0 }).is_err()
{
return Outbound::WireFailed;
}
}
Ok(None) => return Outbound::Drained,
Err(_) => return Outbound::Closed,
}
}
}
/// What one outbound-side wake (frames or monitor commands) yielded.
enum Outbound {
Sent,
/// Everything queued went onto the wire; the inbox is open and empty.
Drained,
/// The manager unbound this connection's sender; nothing more will come.
Closed,
/// The socket refused a write: the connection is gone.
@@ -219,7 +447,7 @@ fn pump_outbound(framed: &mut FramedConn, out_rx: &Receiver<Frame>) -> Outbound
return Outbound::WireFailed;
}
}
Ok(None) => return Outbound::Sent,
Ok(None) => return Outbound::Drained,
Err(_) => return Outbound::Closed,
}
}
@@ -261,16 +489,26 @@ enum Pump {
Frames(usize),
}
/// Surface an inbound verdict: one `smarm-trace` event, nothing else — it
/// is local knowledge (RFC §3). A no-op without the feature.
fn note_verdict(verdict: InboundVerdict) {
#[cfg(feature = "smarm-trace")]
crate::te!(crate::trace::Event::ClusterInbound(verdict.label()));
#[cfg(not(feature = "smarm-trace"))]
drop(verdict);
}
/// Consume one readable wake: exactly one socket read (which cannot block
/// after a level-triggered readable indication), then drain every complete
/// frame the buffer now holds. A blocking `recv` here would park the actor
/// past its heartbeat and liveness deadlines whenever a frame arrives split.
/// Every consumed frame counts for liveness; `SendNamed` additionally goes
/// to the one inbound resolution seam. Its verdict is local knowledge only
/// — nothing goes back on the wire (RFC §3) — and is currently discarded
/// (a future trace hook is the place to surface it). Frames for later
/// chunks (`Send` c10, `Monitor`/`Down` c11) are consumed and ignored.
fn pump_readable(framed: &mut FramedConn) -> Pump {
/// Every consumed frame counts for liveness; `SendNamed` goes to the one
/// name-resolution seam and `Send` to the pid seam. Verdicts are local
/// knowledge only — nothing goes back on the wire (RFC §3) — and surface
/// as one `smarm-trace` `ClusterInbound` event each (zero cost off).
/// `Monitor`/`Demonitor`/`Down` go to the [`Monitors`] tables; a `Monitor`
/// that can be answered at once is answered inline.
fn pump_readable(framed: &mut FramedConn, mons: &mut Monitors) -> Pump {
let eof = match framed.read_once() {
Ok(n) => n == 0,
Err(_) => return Pump::Ended,
@@ -280,13 +518,43 @@ fn pump_readable(framed: &mut FramedConn) -> Pump {
match framed.next_buffered() {
Ok(Some(frame)) => {
got += 1;
if let Frame::SendNamed {
name,
type_hash,
payload,
} = frame
{
let _verdict = deliver_named(&name, type_hash, &payload);
match frame {
Frame::SendNamed {
name,
type_hash,
payload,
} => {
note_verdict(deliver_named(&name, type_hash, &payload));
}
Frame::Send {
index,
generation,
type_hash,
payload,
} => {
note_verdict(deliver_to_pid(index, generation, type_hash, &payload));
}
Frame::Monitor {
monitor_id,
index,
generation,
} => {
let id = MonitorId(monitor_id);
if let Some(reason) = mons.admit(id, index, generation) {
let frame = Frame::Down {
monitor_id,
reason: reason.into(),
};
if framed.send(&frame).is_err() {
return Pump::Ended;
}
}
}
Frame::Demonitor { monitor_id } => mons.cancel(MonitorId(monitor_id)),
Frame::Down { monitor_id, reason } => mons.down(MonitorId(monitor_id), reason),
// Heartbeat: liveness only. Handshake frames after
// establishment: ignored.
_ => {}
}
}
Ok(None) => break,
@@ -299,3 +567,64 @@ fn pump_readable(framed: &mut FramedConn) -> Pump {
Pump::Frames(got)
}
}
#[cfg(test)]
mod tests {
//! `Monitors::teardown` in isolation: the actor-side half of c13, pinned
//! separately because from the outside it is indistinguishable from the
//! read-side backstop in `RemoteMonitor` (both yield `Disconnected`).
use super::*;
use crate::pg::Incarnation;
fn pid(index: u32) -> RemotePid<Erased> {
RemotePid::from_parts("peer", Incarnation::new(1), index, 1)
}
#[test]
fn teardown_answers_every_outstanding_and_unread_monitor_once() {
crate::run(|| {
let mut mons = Monitors::default();
let (mon_tx, mon_rx) = channel::<MonCmd>();
// Already registered.
let (tx1, rx1) = channel::<RemoteDown>();
mons.outstanding.insert(MonitorId(1), (pid(1), tx1));
// In the inbox, never processed.
let (tx2, rx2) = channel::<RemoteDown>();
mon_tx
.send(MonCmd::Monitor {
id: MonitorId(2),
target: pid(2),
tx: tx2,
})
.ok()
.unwrap();
// Registered, then cancelled in the inbox: silence.
let (tx3, rx3) = channel::<RemoteDown>();
mons.outstanding.insert(MonitorId(3), (pid(3), tx3));
mon_tx
.send(MonCmd::Demonitor { id: MonitorId(3) })
.ok()
.unwrap();
mons.teardown(&mon_rx);
let d1 = rx1.recv().unwrap();
assert_eq!(
(d1.pid, d1.reason),
(pid(1), RemoteDownReason::Disconnected)
);
let d2 = rx2.recv().unwrap();
assert_eq!(
(d2.pid, d2.reason),
(pid(2), RemoteDownReason::Disconnected)
);
// Cancelled: no notice was sent (its sender is dropped, channel
// closed-empty), and nobody got a second one.
assert!(rx3.try_recv().is_err());
assert!(rx1.try_recv().is_err());
assert!(rx2.try_recv().is_err());
assert!(mons.outstanding.is_empty());
});
}
}