Files
buzz/crates/buzz-relay-mesh/src/lib.rs
Luke Tornquist 7ce422417b fix(mesh): expire dead peer records and instrument mesh boot (#8503)
## Summary

Relay pods can stall in the `mesh_boot` startup step, and the mesh peer
table grows without limit. One prod pod held 7,793 peer records. Most of
those records belong to pods that no longer exist.

**Cause.** Every boot gets a fresh runtime id, so a restarted pod leaves
its old record behind. Nothing ever removed records, and scuttlebutt
gossip kept spreading the dead ones around the fleet. Each reconcile
pass, including the first one inside `boot_mesh`, then dials every
record one at a time.

This PR makes dead records expire. It also adds the measurements we need
to see the next stall directly.

### Peer-table lifetime (`crates/buzz-relay-mesh/src/membership.rs`)
- A peer record expires 5 minutes after its last heartbeat
(`DEFAULT_PEER_RECORD_TTL`). For comparison, live runtimes refresh every
2s, and the Redis ready registry expires a silent runtime after 45s.
- What happens to expired records:
- They are **rejected on arrival**, so peers that haven't been upgraded
can't re-add them.
  - They are **left out** of digests, deltas, and dial candidates.
  - They are **pruned** at the start of each reconcile pass.
- Between prunes, they are not admitted (`has_peer`) and not routed
(`peers`, `peer_has_capability`).
- An expired entry that hasn't been pruned yet counts as absent, so any
fresh record replaces it whatever its version. That lets a live peer's
v1 Redis hint re-admit it before the next prune.
- **The TTL never prunes or hides a peer with a live connection**, even
if its heartbeat is stale. Its gossip can stop arriving while the
transport stays up: a dead control stream, or a clock behind by more
than the TTL. The connection proves the runtime is alive. Its stale
record is still kept out of digests and dials. (The existing phi filter
in `peers()` still drops a connected peer once its gossip stalls; this
PR doesn't change that.)
- **`Connected` tracks the transport map.** Because the TTL exemption
trusts that flag, `install_peer` and `remove_peer` write it while
holding the peers lock, so a connection that closes during install
always ends `Disconnected`. A dial's `Connecting`/`Disconnected` writes
are skipped when a connection is already installed, so a failed outbound
dial can't overwrite a live inbound connection. Each reconcile pass also
re-syncs the state from the transport map.
- **Gossip no longer sets connection state.** Before, any gossiped
record was marked `Connected`, even if this pod had never dialed it.
That inflated the `/_mesh` counts. Now a record learned from gossip or
the ready registry enters as `Disconnected`. Only the real connect and
disconnect paths change the state.
- Before building its candidate list, reconcile now skips peers that are
already connected. A pass dials serially, and a dial to a dead runtime
can take about a minute, so `dial_peer` re-reads the record before every
address attempt. It stops once the record has expired or started
draining, or once a connection has landed.

### Instrumentation
- **`mesh_boot` sub-steps** use the existing startup-step gauges:
`mesh_bind`, `mesh_publish`, and `mesh_initial_reconcile`. A pod stuck
in `mesh_boot` now also shows which await it is stuck on.
- **New metrics** (`crates/buzz-relay-mesh/src/telemetry.rs`):

  | Metric | Shows |
  |---|---|
| `buzz_mesh_dial_total{outcome}` / `buzz_mesh_dial_duration_seconds` |
Cost of each dial |
  | `buzz_mesh_reconcile_pass_seconds` | Full pass time |
| `buzz_mesh_reconcile_candidates` | Dials planned for this pass (set
after the registry scan) |
  | `buzz_mesh_peer_records{state,draining}` | Table size |
  | `buzz_mesh_peer_record_max_age_seconds` | Oldest heartbeat |
| `buzz_mesh_peer_records_expired_total{reason=pruned\|rejected}` |
Expiry activity |

- The dial and pass histograms get buckets up to 600s. The default
`_seconds` buckets stop at 5s, which would hide exactly the stall these
metrics are meant to show.

### CI
The `buzz-relay-mesh` tests and the `buzz-relay` `mesh_boot::tests` did
not run in any CI lane. This PR adds both to `just test-unit`, and adds
the matching stanzas to `scripts/run-tests.sh`.

### What got simpler
- The peer table now has a defined size, about one record per live pod,
where before it grew forever.
- One wrong state write was deleted (gossip marking records
`Connected`).
- Two test suites that silently never ran now run.

### Rollout notes
- Rejecting expired records works one pod at a time. During a rollout,
pods that haven't been upgraded keep gossiping dead records. Upgraded
pods reject them, which shows up as `reason="rejected"` on the expired
counter.
- A pod whose clock runs more than 5 minutes behind has all of its
gossip rejected. It stays reachable through its Redis ready record and
any live connection. A `reason="rejected"` count that keeps climbing
outside a rollout points to that skew.
- Upgraded pods leave expired records out of their digests. Pods that
haven't been upgraded therefore resend the whole ghost set (about 7.8k
records, roughly 1 MB) on every 2s gossip tick, on each old↔new
connection. So during the rollout, `reason="rejected"` will climb by
about the ghost count per tick per connection. This is expected and
stops when the rollout finishes.

### Not in this PR
The boot dial itself is still unbounded: it runs serially, has no
per-dial timeout, and dials gossip-learned records. Bounding it changes
how a pod joins the mesh, so it goes in a separate PR, and these metrics
will measure it.

### Related issue
None found.

### Testing
- New tests:
- `membership::tests`: expired gossip is rejected; prune drops only
expired records; prune keeps a connected peer with a stale heartbeat;
expired unconnected records are neither admitted nor routed before a
prune; a fresh record replaces an expired, unpruned entry whatever its
version; expired records are neither dialed nor gossiped before a prune;
gossip never sets connection state; table stats.
- `runtime::tests::reconcile_pass_publishes_dial_and_peer_table_metrics`
- `runtime::tests::reconcile_pass_prunes_expired_peer_records` (binds
the prune to the reconcile pass)
-
`runtime::tests::dial_skips_candidate_that_expired_after_the_pass_snapshot`
-
`runtime::tests::finishing_dial_does_not_overwrite_a_connection_that_landed`
-
`runtime::tests::connection_closed_during_install_ends_disconnected_and_expires`
-
`runtime::tests::reconcile_pass_resyncs_connection_state_from_transport`
  - `mesh_boot::tests::mesh_boot_sub_steps_name_the_step_that_failed`
- Blox at `e06f55a4` (tree `866add1c`): `just fmt-check`, `just clippy`,
`buzz-relay-mesh` nextest 3x, and the `buzz-relay`
`mesh_boot`/`startup_steps`/`metrics` tests all pass. Three of the new
tests fail against a mutant that removes the fix they pin (dial ignores
expiry; dial state writes ignore the transport map; no reconcile
resync).

---------

Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
2026-10-26 09:47:30 -04:00

234 lines
9.5 KiB
Rust

//! buzz-relay-mesh — the inter-relay QUIC mesh.
//!
//! One iroh endpoint per relay runtime (identity = a boot-unique mesh
//! keypair, attested by the relay's signing key — see [`wire::RuntimeId`]),
//! a warm full mesh of authenticated connections, scuttlebutt membership
//! gossip on a control substream, and a fenced wire contract that carries
//! tunnel traffic (reliable streams + realtime datagrams) between pods.
//!
//! The relay consumes this crate exclusively through two seams:
//!
//! - [`RelayMeshMembership`] — "who is alive / draining / dialable?"
//! - [`RelayPeerTransport`] — "move these bytes to that runtime."
//!
//! The seams are what keep single-instance deployments and same-pod sessions
//! mesh-free: when `BUZZ_MESH=off` or no peers exist, the relay never
//! constructs a mesh and the in-process fast path is untouched.
//!
//! **The law:** mesh membership is a hint; the Redis fenced generation is the
//! arbiter. Nothing in this crate grants ownership — see [`wire::FencedHeader`].
pub mod endpoint;
pub mod gossip;
pub mod membership;
pub mod peer;
pub mod registry;
pub mod runtime;
pub mod status;
pub mod telemetry;
pub mod wire;
// Lane modules — one owner per file (see the mesh thread for lane map):
// endpoint.rs, peer.rs — Mari (transport core)
// registry.rs, gossip.rs,
// membership.rs, status.rs,
// telemetry.rs — Max (membership + /_mesh + metrics)
// Session directory + tunnel routing live relay-side (Perci), consuming the
// seams below; huddle fan-out lives in buzz-relay's audio module (Dawn).
use std::future::Future;
use std::pin::Pin;
use bytes::Bytes;
pub use gossip::{GossipDigestEntry, GossipMessage, GossipRecord, GossipState, PhiAccrual};
pub use membership::MeshMembership;
pub use registry::{ReadyHeartbeat, ReadyRecord, ReadyRegistry, RuntimeAttestation};
pub use runtime::MeshRuntime;
pub use status::{ConnectionState, MeshCounters, MeshPeerCounters, MeshPeerStatus, MeshStatus};
pub use wire::{
FencedHeader, GoodbyeReason, MeshDatagram, MeshStreamFrame, Profile, RuntimeId, StreamHello,
StreamRole, ALPN, WIRE_VERSION,
};
/// Mesh configuration, resolved from env by the relay.
#[derive(Clone, Debug)]
pub struct MeshConfig {
/// `BUZZ_MESH` — `on` (default when replicas can exist) | `off` kill
/// switch. When off, the relay must behave exactly like single-instance.
pub enabled: bool,
/// UDP bind for the iroh endpoint (`BUZZ_MESH_BIND_ADDR`, default
/// `0.0.0.0:3478`). Excluded from istio sidecar capture in k8s.
pub bind_addr: std::net::SocketAddr,
/// Ready-registry heartbeat refresh (default 15s; expiry is 3x).
pub registry_refresh: std::time::Duration,
}
#[derive(Debug, thiserror::Error)]
pub enum MeshError {
#[error("frame encode: {0}")]
Encode(#[source] postcard::Error),
#[error("frame decode: {0}")]
Decode(#[source] postcard::Error),
#[error("unknown wire version {0}")]
UnknownWireVersion(u8),
#[error("empty frame")]
EmptyFrame,
#[error("frame exceeds max size ({size} > {max})")]
FrameTooLarge { size: usize, max: usize },
#[error("datagram exceeds connection max_datagram_size ({size} > {max})")]
DatagramTooLarge { size: usize, max: usize },
#[error("peer {0} not connected")]
PeerNotConnected(RuntimeId),
#[error("peer {0} is draining")]
PeerDraining(RuntimeId),
#[error("stale generation for session {session_id}: frame {frame_generation} < known {known_generation}")]
StaleGeneration {
session_id: uuid::Uuid,
frame_generation: u64,
known_generation: u64,
},
// The three variants below complete the fence-rejection taxonomy alongside
// `StaleGeneration` (Wren's chaos-gate ruling: every fence-visible reject
// is a typed variant, never a generic `Transport`, so live kill-9 /
// partition / replay evidence is unambiguous). Counter surface:
// `mesh_fence_rejections_total{reason=...}` with reasons
// `stale_generation` | `no_active_lease` | `owner_mismatch` |
// `future_generation`. None of these are serialized — the wire-level fence
// signal remains `GoodbyeReason::StaleGeneration`.
#[error("no active lease for session {session_id}: frame generation {frame_generation}, known generation {known_generation}, claimed owner {frame_owner_runtime_id}")]
NoActiveLease {
session_id: uuid::Uuid,
frame_generation: u64,
known_generation: u64,
/// The owner the *frame* claimed — there is no current owner by
/// definition when no live lease exists.
frame_owner_runtime_id: RuntimeId,
},
#[error("owner mismatch for session {session_id} generation {generation}: frame owner {frame_owner_runtime_id} != current owner {current_owner_runtime_id}")]
OwnerMismatch {
session_id: uuid::Uuid,
generation: u64,
frame_owner_runtime_id: RuntimeId,
current_owner_runtime_id: RuntimeId,
},
#[error("future generation for session {session_id}: frame {frame_generation} > known {known_generation}")]
FutureGeneration {
session_id: uuid::Uuid,
frame_generation: u64,
known_generation: u64,
},
#[error("mesh is disabled (BUZZ_MESH=off)")]
Disabled,
#[error("transport: {0}")]
Transport(String),
#[error("redis: {0}")]
Redis(#[from] redis::RedisError),
}
/// A peer as membership sees it. Everything here is a routing HINT.
#[derive(Clone, Debug)]
pub struct PeerInfo {
pub runtime_id: RuntimeId,
pub draining: bool,
/// Phi-accrual suspicion; `None` until enough heartbeats observed.
pub phi: Option<f64>,
/// Advisory load factor gossiped by the peer (0.0..).
pub load: f32,
}
/// Boxed future used across the seam traits. Public because implementors of
/// [`StreamSendHalf`]/[`StreamRecvHalf`]/[`RelayPeerTransport`] outside this
/// crate must name it.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
/// Seam 1: membership. Answers "who can I route to?" — never "who owns what."
pub trait RelayMeshMembership: Send + Sync + 'static {
/// Live, non-suspect peers (self excluded).
fn peers(&self) -> Vec<PeerInfo>;
/// This runtime's mesh identity.
fn local_runtime_id(&self) -> RuntimeId;
/// Begin drain: gossip `draining=true`, stop accepting new sessions.
fn begin_drain(&self);
/// Whether the record for exactly `runtime_id` advertises `capability`.
/// Runtime ids are boot-unique, so a positive answer describes that very
/// process. Unknown peers — and implementations without records — say no.
fn peer_has_capability(&self, _runtime_id: RuntimeId, _capability: &str) -> bool {
false
}
}
/// Seam 2: transport. Moves fenced bytes to a specific runtime.
///
/// Implementations perform the datagram-size and wire-version checks; they do
/// NOT perform generation fencing — that belongs to the session layer on both
/// ends (fencing at every hop means every consumer checks, not the pipe).
pub trait RelayPeerTransport: Send + Sync + 'static {
/// Fire-and-forget realtime datagram (drop-on-full, never blocks on old
/// audio). Errors only for disconnected peer / oversize frame.
fn send_datagram(&self, to: RuntimeId, dgram: MeshDatagram) -> Result<(), MeshError>;
/// Open a reliable bi-stream to a peer for a session (`ReliableStream`
/// or `HuddleControl` profile). Sends the `Hello` before returning.
fn open_session_stream(
&self,
to: RuntimeId,
hello: StreamHello,
) -> BoxFuture<'_, Result<MeshStream, MeshError>>;
/// Register the handler invoked for inbound datagrams / session streams.
/// Called once at relay startup.
fn set_inbound(&self, handler: Box<dyn InboundHandler>);
}
/// Inbound mesh traffic, delivered after wire decode + Hello validation.
pub trait InboundHandler: Send + Sync + 'static {
fn on_datagram(&self, from: RuntimeId, dgram: MeshDatagram);
fn on_session_stream(&self, from: RuntimeId, hello: StreamHello, stream: MeshStream);
}
/// A reliable mesh stream: length-delimited `MeshStreamFrame`s over QUIC.
/// Concrete type (not a trait) so lanes share one framing implementation.
pub struct MeshStream {
// Mari: wrap iroh SendStream/RecvStream with the u32-LE length framing
// from `wire`. Placeholder halves keep the seam compilable pre-transport.
pub(crate) send: Box<dyn StreamSendHalf>,
pub(crate) recv: Box<dyn StreamRecvHalf>,
}
pub trait StreamSendHalf: Send + 'static {
fn send_frame(&mut self, frame: MeshStreamFrame) -> BoxFuture<'_, Result<(), MeshError>>;
fn finish(&mut self) -> Result<(), MeshError>;
}
pub trait StreamRecvHalf: Send + 'static {
fn recv_frame(&mut self) -> BoxFuture<'_, Result<Option<MeshStreamFrame>, MeshError>>;
}
impl MeshStream {
pub fn send_frame(&mut self, frame: MeshStreamFrame) -> BoxFuture<'_, Result<(), MeshError>> {
self.send.send_frame(frame)
}
pub fn recv_frame(&mut self) -> BoxFuture<'_, Result<Option<MeshStreamFrame>, MeshError>> {
self.recv.recv_frame()
}
pub fn finish(&mut self) -> Result<(), MeshError> {
self.send.finish()
}
}
/// Raw bytes helper used by transport internals.
pub fn encode_datagram_checked(
dgram: &MeshDatagram,
max_datagram_size: usize,
) -> Result<Bytes, MeshError> {
let bytes = wire::encode(dgram)?;
if bytes.len() > max_datagram_size {
return Err(MeshError::DatagramTooLarge {
size: bytes.len(),
max: max_datagram_size,
});
}
Ok(Bytes::from(bytes))
}