Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(spaces): mesh reconnects back off with jitter instead of looping (CUA-2276) (#5932)
cua-agents[bot]b12695426c82
diff --git a/libs/cua-spacesd/crates/cua-relay/src/mesh.rs b/libs/cua-spacesd/crates/cua-relay/src/mesh.rsindex 79652c10d5..9800bbe5ac 100644--- a/libs/cua-spacesd/crates/cua-relay/src/mesh.rs+++ b/libs/cua-spacesd/crates/cua-relay/src/mesh.rs@@ -43,7 +43,7 @@//! with backoff. The registry is also soft state: every node registers//! again when it reconnects, so a lost write costs at most a reconnect.-use std::collections::{BTreeSet, HashMap, HashSet};+use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};use std::hash::{Hash as _, Hasher as _};use std::net::SocketAddr;use std::path::PathBuf;@@ -51,7 +51,7 @@ use std::sync::atomic::{AtomicU64, Ordering};use std::sync::{Arc, Mutex, RwLock};use std::time::{Duration, Instant};-use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};+use axum::extract::ws::{CloseFrame, Message, WebSocket, WebSocketUpgrade};use axum::extract::State;use axum::http::{header, HeaderMap, StatusCode};use axum::response::{IntoResponse as _, Response};@@ -91,6 +91,12 @@ const MAX_OPEN_PER_PEER: u32 = 64;/// the machine's map (a retry after that is refused again while over).const DENY_FOR: Duration = Duration::from_secs(30);+/// Connects one node may make per [`CONNECT_WINDOW`] before it is told to+/// retry later (a client stuck in a reconnect loop must not hammer the+/// relay: the node's own backoff keeps well under this).+const MAX_CONNECTS_PER_WINDOW: usize = 10;+const CONNECT_WINDOW: Duration = Duration::from_secs(60);+const ATTRIBUTE_EVERY: Duration = Duration::from_secs(5);/// Relayed packets of a pair are noted at most this often.const PAIR_MARK_EVERY: Duration = Duration::from_secs(1);@@ -261,6 +267,10 @@ pub struct MeshState {denied: Mutex<HashMap<(PublicKey, PublicKey), Instant>>,/// Sessions refused by an enforced plan since start.sessions_refused: AtomicU64,+ /// When each node connected lately (see [`MeshState::admit`]).+ connects: Mutex<HashMap<PublicKey, VecDeque<Instant>>>,+ /// Connects turned away for coming too often since start.+ reconnects_limited: AtomicU64,/// Where write failures are counted and reported.storage: Arc<Storage>,/// Saves asked for (a counter) ...@@ -329,6 +339,8 @@ impl MeshState {metered_streams: AtomicU64::new(0),denied: Mutex::new(HashMap::new()),sessions_refused: AtomicU64::new(0),+ connects: Mutex::default(),+ reconnects_limited: AtomicU64::new(0),storage,save_asked: AtomicU64::new(0),saved: tokio::sync::watch::channel((0, true)).0,@@ -392,7 +404,9 @@ impl MeshState {let mut conns = self.conns.lock().expect("conns");for key in &removed_keys {if let Some(conn) = conns.remove(key) {- let _ = conn.tx.try_send(Message::Close(None));+ let _ = conn+ .tx+ .try_send(close(proto::CLOSE_ERASED, "the account was erased"));}}}@@ -498,7 +512,10 @@ impl MeshState {/// shutdown, or a test standing in for a crash).pub fn disconnect_all(&self) {for (_, conn) in self.conns.lock().expect("conns").drain() {- let _ = conn.tx.try_send(Message::Close(None));+ let _ = conn.tx.try_send(close(+ proto::CLOSE_RELAY_CHANGED,+ "the relay is restarting: reconnect",+ ));}}@@ -521,6 +538,42 @@ impl MeshState {pub fn connected(&self) -> usize {self.conns.lock().expect("conns").len()}++ /// Notes a connect by `node` at `now`, or says how many seconds it must+ /// wait: more than [`MAX_CONNECTS_PER_WINDOW`] connects in+ /// [`CONNECT_WINDOW`] are refused (and not counted, so the wait ends).+ fn admit(&self, node: &PublicKey, now: Instant) -> Result<(), u64> {+ let mut connects = self.connects.lock().expect("connects");+ if connects.len() > 4096 {+ connects.retain(|_, t| {+ t.back()+ .is_some_and(|b| now.duration_since(*b) < CONNECT_WINDOW)+ });+ }+ let times = connects.entry(*node).or_default();+ while times+ .front()+ .is_some_and(|t| now.saturating_duration_since(*t) >= CONNECT_WINDOW)+ {+ times.pop_front();+ }+ if times.len() >= MAX_CONNECTS_PER_WINDOW {+ let oldest = *times.front().expect("a full window has a first");+ let wait = CONNECT_WINDOW.saturating_sub(now.saturating_duration_since(oldest));+ self.reconnects_limited.fetch_add(1, Ordering::Relaxed);+ return Err(wait.as_secs() + 1);+ }+ times.push_back(now);+ Ok(())+ }+}++/// A close frame with one of the [`proto`] codes and a reason.+fn close(code: u16, reason: &str) -> Message {+ Message::Close(Some(CloseFrame {+ code,+ reason: reason.to_owned().into(),+ }))}/// Starts the background tasks: map recomputation and registry saving.@@ -734,11 +787,23 @@ fn recompute(relay: &Relay) {};for (key, conn) in conns.iter_mut() {let Some(node) = nodes.get(key) else { continue };- if matches!(node.owner, Owner::Account { .. })- && (!client_device_ok(relay, node) || conn.since.elapsed() > MAX_ACCOUNT_SESSION)- {- cut.push(*key);- continue;+ if matches!(node.owner, Owner::Account { .. }) {+ if !client_device_ok(relay, node) {+ cut.push((+ *key,+ proto::CLOSE_DEVICE,+ "the device is no longer enrolled or was revoked",+ ));+ continue;+ }+ if conn.since.elapsed() > MAX_ACCOUNT_SESSION {+ cut.push((+ *key,+ proto::CLOSE_SESSION_MAX,+ "the session reached its maximum age: reconnect with a fresh token",+ ));+ continue;+ }}let mut peers = peers_for(relay, node, &nodes, &online, &pairs);// A peer whose new session an enforced plan refused is left out of@@ -759,9 +824,9 @@ fn recompute(relay: &Relay) {let _ = conn.tx.try_send(Message::Text(json.into()));}}- for key in cut {+ for (key, code, reason) in cut {if let Some(conn) = conns.remove(&key) {- let _ = conn.tx.try_send(Message::Close(None));+ let _ = conn.tx.try_send(close(code, reason));}}drop(conns);@@ -1095,6 +1160,17 @@ async fn session(relay: Relay, owner: Owner, socket: WebSocket) {return;}let mesh = &relay.mesh;+ // The key is proven, so this counts one node, not whoever claims it.+ if let Err(wait) = mesh.admit(&node_key, Instant::now()) {+ tracing::warn!(node = %node_key.short(), ?kind, retry_after_s = wait, "mesh node connects too often");+ let _ = sink+ .send(close(+ proto::CLOSE_RATE_LIMITED,+ &proto::retry_after_reason(wait),+ ))+ .await;+ return;+ }let (conflict, fresh) = {let mut nodes = mesh.nodes.lock().expect("nodes");// A key belongs to one owner (a device or a machine) for life.@@ -1213,8 +1289,14 @@ async fn session(relay: Relay, owner: Owner, socket: WebSocket) {netmap_hash: 0,},) {- // The same node reconnected: the newer connection wins.- let _ = old.tx.try_send(Message::Close(None));+ // The same node reconnected: the newer connection wins. A live old+ // connection means a second process holds this node key; it is told+ // so, and a node that keeps hearing it stops reconnecting.+ tracing::info!(node = %node_key.short(), "mesh node replaced its older connection");+ let _ = old.tx.try_send(close(+ proto::CLOSE_REPLACED,+ "replaced: another connection with the same node key took over",+ ));}tracing::info!(node = %node_key.short(), ?kind, "mesh node connected");mesh.changed();@@ -1591,6 +1673,9 @@ pub struct MeshStatus {pub usage_rejected: u64,/// New mesh sessions refused by an enforced plan's cap.pub sessions_refused: u64,+ /// Connects turned away because the node connected too often.+ #[serde(default)]+ pub reconnects_limited: u64,}/// The coordinator's counters.@@ -1611,6 +1696,7 @@ pub fn status(relay: &Relay) -> MeshStatus {usage_reports: mesh.usage_reports.load(Ordering::Relaxed),usage_rejected: mesh.usage_rejected.load(Ordering::Relaxed),sessions_refused: mesh.sessions_refused.load(Ordering::Relaxed),+ reconnects_limited: mesh.reconnects_limited.load(Ordering::Relaxed),}}@@ -1626,6 +1712,32 @@ pub(crate) fn info(relay: &Relay) -> Option<proto::MeshInfo> {mod tests {use super::*;+ #[test]+ fn a_node_connecting_too_often_is_told_when_to_retry() {+ let mesh = MeshState::open(None).unwrap();+ let node = SecretKey::generate().public();+ let other = SecretKey::generate().public();+ let t0 = Instant::now();+ for i in 0..MAX_CONNECTS_PER_WINDOW as u64 {+ assert!(mesh.admit(&node, t0 + Duration::from_secs(i)).is_ok());+ }+ // The 11th within the minute: wait until the oldest leaves the window.+ let now = t0 + Duration::from_secs(20);+ let wait = mesh.admit(&node, now).unwrap_err();+ assert_eq!(wait, 41);+ // Refused attempts are not counted: the wait ends on time ...+ assert!(mesh.admit(&node, now + Duration::from_secs(10)).is_err());+ assert!(mesh.admit(&node, t0 + Duration::from_secs(60)).is_ok());+ // ... and one node's loop never limits another.+ assert!(mesh.admit(&other, now).is_ok());+ assert_eq!(mesh.reconnects_limited.load(Ordering::Relaxed), 2);+ // The reason a node reads back is the number of seconds.+ assert_eq!(+ proto::parse_retry_after(&proto::retry_after_reason(wait)),+ Some(41)+ );+ }+#[test]fn the_registry_is_written_compact_and_read_back_and_temps_are_removed() {let dir = tempfile::tempdir().unwrap();diff --git a/libs/cua/crates/cua-cli/tests/agents_login.rs b/libs/cua/crates/cua-cli/tests/agents_login.rsindex f8cc9bd1e3..d8586d0f6d 100644--- a/libs/cua/crates/cua-cli/tests/agents_login.rs+++ b/libs/cua/crates/cua-cli/tests/agents_login.rs@@ -649,8 +649,15 @@ async fn the_local_cli_leaves_cua_driver_alone_even_when_it_registered_it_first(skill("cua-driver").join("SKILL.md").is_file(),"the released app's cua-driver skill stays");+ // `cua-driver-local` is Cua Driver's own sibling skill+ // (`is_cua_driver_name`), so it stays like `cua-driver`; only Cua Spaces'+ // skill goes.assert!(- !skill("cua-driver-local").exists() && !skill("cua-spaces-local").exists(),+ skill("cua-driver-local").exists(),+ "Cua Driver's Local skill stays"+ );+ assert!(+ !skill("cua-spaces-local").exists(),"Local's own skills went");}diff --git a/libs/cua/crates/cua-mesh/src/coord.rs b/libs/cua/crates/cua-mesh/src/coord.rsindex f8a4695c46..24a0a9e2ad 100644--- a/libs/cua/crates/cua-mesh/src/coord.rs+++ b/libs/cua/crates/cua-mesh/src/coord.rs@@ -18,10 +18,12 @@ use futures_util::{SinkExt as _, StreamExt as _};use tokio::sync::{mpsc, oneshot, watch};use tokio_tungstenite::tungstenite::Message as WsMessage;use tokio_tungstenite::tungstenite::client::IntoClientRequest as _;+use tokio_tungstenite::tungstenite::protocol::CloseFrame;use crate::engine::Engine;use crate::key::{NodeIdentity, PublicKey};use crate::proto::{self, ClientMsg, Mode, NodeKind, PeerUsage, ServerMsg};+use crate::reconnect::{self, Backoff};use crate::{Error, Result};/// Credentials for the coordinator connection, fetched before every@@ -92,6 +94,8 @@ pub(crate) struct ControlConfig {pub approved: Option<Arc<crate::node::Approved>>,/// Forgotten by the coordinator on disconnect.pub ephemeral: bool,+ /// Divides the reconnect wait (tests).+ pub reconnect_speedup: u32,}impl Control {@@ -248,13 +252,57 @@ fn denial(e: &Error) -> Option<String> {}}-fn backoff(attempt: u32) -> Duration {- let base = Duration::from_millis(250)- .saturating_mul(1 << attempt.min(6))- .min(Duration::from_secs(10));- base.mul_f64(rand::random_range(0.5..=1.0))+/// How one coordinator session ended, for the log and for the wait before+/// the next connect.+#[derive(Default)]+struct Ended {+ /// When the coordinator welcomed the node (never, if it did not).+ welcomed: Option<std::time::Instant>,+ /// The WebSocket close the coordinator sent: code and reason.+ close: Option<(u16, String)>,+ /// The last error message the coordinator sent before it ended.+ server_error: Option<String>,+ /// The coordinator ended the session (a close or a dropped+ /// connection after the welcome), as opposed to a failure on this side.+ by_relay: bool,+}++impl Ended {+ /// Notes a close frame and returns the error that ends the session.+ fn closed(&mut self, frame: Option<CloseFrame>) -> Error {+ self.by_relay = true;+ match frame {+ Some(f) => {+ let (code, reason) = (u16::from(f.code), f.reason.to_string());+ self.close = Some((code, reason.clone()));+ Error::Unreachable(format!(+ "coordinator closed the connection ({code}: {reason})"+ ))+ }+ None => Error::Unreachable("coordinator closed the connection".into()),+ }+ }++ fn close_code(&self) -> Option<u16> {+ self.close.as_ref().map(|(c, _)| *c)+ }++ fn retry_after(&self) -> Option<Duration> {+ let (code, reason) = self.close.as_ref()?;+ (*code == proto::CLOSE_RATE_LIMITED)+ .then(|| proto::parse_retry_after(reason))+ .flatten()+ .map(Duration::from_secs)+ }}+/// Consecutive sessions the coordinator ended with "another connection+/// took over" before this node stops reconnecting.+const MAX_TAKEOVERS: u32 = 3;++const TAKEN_OVER: &str = "another copy of Spaces keeps taking over this computer's connection \+ (two copies share one identity). Quit the other copy, then reopen Spaces here.";+pub(crate) async fn run(cfg: ControlConfig,control: Arc<Control>,@@ -262,38 +310,73 @@ pub(crate) async fn run(identity: NodeIdentity,shutdown: tokio_util_cancel::Token,) {- let mut attempt = 0u32;+ let mut backoff = Backoff::default();+ let mut takeovers = 0u32;loop {if shutdown.is_cancelled() {return;}- let started = std::time::Instant::now();- let result = session(&cfg, &control, &engine, &identity, &shutdown).await;+ let mut ended = Ended::default();+ let result = session(&cfg, &control, &engine, &identity, &shutdown, &mut ended).await;engine.set_relay(None);*control.out.lock().expect("out") = None;+ if shutdown.is_cancelled() {+ return;+ }+ // Only the time since the welcome is a healthy session.+ let lived = ended.welcomed.map_or(Duration::ZERO, |t| t.elapsed());+ if ended.close_code() == Some(proto::CLOSE_REPLACED) {+ takeovers += 1;+ } else {+ takeovers = 0;+ }+ let gave_up = takeovers >= MAX_TAKEOVERS;control.state.send_modify(|s| {s.connected = false;s.last_error = result.as_ref().err().map(ToString::to_string);if let Some(reason) = result.as_ref().err().and_then(denial) {s.denied = Some(reason);}+ if gave_up {+ s.denied = Some(TAKEN_OVER.into());+ }if matches!(result, Err(Error::Unsupported(_))) {s.unsupported = true;}});- if let Err(e) = &result {- tracing::info!(error = %e, "mesh coordinator connection ended");- if matches!(e, Error::Refused(_)) {- attempt = attempt.max(5);- }+ if matches!(result, Err(Error::Refused(_))) {+ backoff.at_least(5);}- if started.elapsed() > Duration::from_secs(30) {- attempt = 0;+ let unit = rand::random_range(0.0..=1.0);+ let mut delay = backoff.next(lived, unit);+ // A relay close, or any drop after the welcome (a crashed relay+ // resets the socket without a close frame): all nodes lose it at once.+ let by_relay = ended.by_relay || (ended.welcomed.is_some() && result.is_err());+ if by_relay {+ delay += reconnect::spread(rand::random_range(0.0..=1.0));+ }+ if let Some(wait) = ended.retry_after() {+ delay = delay.max(wait);+ }+ let close = ended.close.as_ref();+ tracing::warn!(+ error = result.as_ref().err().map(ToString::to_string),+ close_code = close.map(|(c, _)| *c),+ close_reason = close.map(|(_, r)| r.as_str()),+ server_error = ended.server_error.as_deref(),+ welcomed = ended.welcomed.is_some(),+ lived_ms = lived.as_millis() as u64,+ by_relay,+ takeovers,+ retry_in_ms = delay.as_millis() as u64,+ "mesh coordinator session ended"+ );+ if gave_up {+ tracing::error!("{TAKEN_OVER} Not reconnecting.");+ return;}- let delay = backoff(attempt);- attempt = attempt.saturating_add(1);tokio::select! {- _ = tokio::time::sleep(delay) => {}+ _ = tokio::time::sleep(delay / cfg.reconnect_speedup.max(1)) => {}_ = shutdown.cancelled() => return,}}@@ -305,6 +388,7 @@ async fn session(engine: &Arc<Engine>,identity: &NodeIdentity,shutdown: &tokio_util_cancel::Token,+ ended: &mut Ended,) -> Result<()> {let url = connect_url(&cfg.url)?;let mut request = url@@ -365,9 +449,13 @@ async fn session(server_key,nonce,}) => (server_key, nonce, version),- Ok(ServerMsg::Error { message }) => return Err(Error::Refused(message)),+ Ok(ServerMsg::Error { message }) => {+ ended.server_error = Some(message.clone());+ return Err(Error::Refused(message));+ }_ => return Err(Error::Protocol("expected a challenge".into())),},+ Some(Ok(WsMessage::Close(frame))) => return Err(ended.closed(frame)),_ => return Err(Error::Protocol("expected a challenge".into())),};if server_version != proto::VERSION {@@ -412,12 +500,17 @@ async fn session(}(mode, stun, version, usage)}- Ok(ServerMsg::Error { message }) => return Err(Error::Refused(message)),+ Ok(ServerMsg::Error { message }) => {+ ended.server_error = Some(message.clone());+ return Err(Error::Refused(message));+ }_ => return Err(Error::Protocol("expected a welcome".into())),},+ Some(Ok(WsMessage::Close(frame))) => return Err(ended.closed(frame)),_ => return Err(Error::Protocol("expected a welcome".into())),};+ ended.welcomed = Some(std::time::Instant::now());let (out_tx, mut out_rx) = mpsc::channel::<ClientMsg>(64);let (relay_tx, mut relay_rx) = mpsc::channel::<(PublicKey, Vec<u8>)>(2048);*control.out.lock().expect("out") = Some(out_tx.clone());@@ -455,14 +548,13 @@ async fn session(}Some(Ok(WsMessage::Text(t))) => {let Ok(msg) = serde_json::from_str::<ServerMsg>(&t) else { continue };- handle(cfg, control, engine, mode, msg, &out_tx);+ handle(cfg, control, engine, mode, msg, &out_tx, ended);}Some(Ok(WsMessage::Ping(p))) => {let _ = sink.send(WsMessage::Pong(p)).await;}- Some(Ok(WsMessage::Close(_))) | None => {- return Err(Error::Unreachable("coordinator closed the connection".into()));- }+ Some(Ok(WsMessage::Close(frame))) => return Err(ended.closed(frame)),+ None => return Err(ended.closed(None)),Some(Ok(_)) => {}Some(Err(e)) => return Err(Error::Unreachable(e.to_string())),}@@ -499,6 +591,7 @@ fn handle(mode: Mode,msg: ServerMsg,out: &mpsc::Sender<ClientMsg>,+ ended: &mut Ended,) {match msg {ServerMsg::Netmap { peers } => {@@ -545,7 +638,10 @@ fn handle(reason,} => control.finish_pair(&machine_id, if ok { Ok(()) } else { Err(reason) }),ServerMsg::Pong | ServerMsg::Challenge { .. } | ServerMsg::Welcome { .. } => {}- ServerMsg::Error { message } => tracing::warn!(%message, "mesh coordinator error"),+ ServerMsg::Error { message } => {+ tracing::warn!(%message, "mesh coordinator error");+ ended.server_error = Some(message);+ }}}@@ -578,6 +674,42 @@ pub(crate) mod tokio_util_cancel {mod tests {use super::*;+ fn frame(code: u16, reason: &str) -> Option<CloseFrame> {+ Some(CloseFrame {+ code: code.into(),+ reason: reason.into(),+ })+ }++ #[test]+ fn a_close_frame_is_recorded_with_its_reason() {+ let mut ended = Ended::default();+ let e = ended.closed(frame(proto::CLOSE_REPLACED, "replaced by a newer session"));+ assert!(ended.by_relay);+ assert_eq!(ended.close_code(), Some(proto::CLOSE_REPLACED));+ let text = e.to_string();+ assert!(text.contains("4001") && text.contains("replaced by a newer session"));+ // A bare close or a dropped connection has no reason but is the relay's.+ let mut bare = Ended::default();+ bare.closed(None);+ assert!(bare.by_relay && bare.close.is_none());+ }++ #[test]+ fn a_rate_limit_close_says_how_long_to_wait() {+ let mut ended = Ended::default();+ ended.closed(frame(+ proto::CLOSE_RATE_LIMITED,+ &proto::retry_after_reason(37),+ ));+ assert_eq!(ended.retry_after(), Some(Duration::from_secs(37)));+ // Another code never carries a wait.+ let mut other = Ended::default();+ other.closed(frame(proto::CLOSE_DEVICE, "retry after 5 s"));+ assert_eq!(other.retry_after(), None);+ assert_eq!(proto::parse_retry_after("nothing here"), None);+ }+fn usage(peer: PublicKey, open: u32) -> Vec<PeerUsage> {vec![PeerUsage {peer,diff --git a/libs/cua/crates/cua-mesh/src/lib.rs b/libs/cua/crates/cua-mesh/src/lib.rsindex c0bc2237e2..dad6c8a722 100644--- a/libs/cua/crates/cua-mesh/src/lib.rs+++ b/libs/cua/crates/cua-mesh/src/lib.rs@@ -42,6 +42,7 @@ pub mod packet;pub mod policy;pub mod proto;pub mod quic;+mod reconnect;pub mod stun;pub mod vnet;diff --git a/libs/cua/crates/cua-mesh/src/node.rs b/libs/cua/crates/cua-mesh/src/node.rsindex ab92abbe3b..7b2938b050 100644--- a/libs/cua/crates/cua-mesh/src/node.rs+++ b/libs/cua/crates/cua-mesh/src/node.rs@@ -69,6 +69,10 @@ pub struct MeshConfig {/// [`Mesh::serve_udp`] on the same number. Default/// [`MEDIA_UDP_PORT`].pub media_udp_port: u16,+ /// Divides the wait before reconnecting to the coordinator (tests+ /// only; leave at 1).+ #[doc(hidden)]+ pub reconnect_speedup: u32,}impl std::fmt::Debug for MeshConfig {@@ -101,6 +105,7 @@ impl MeshConfig {stun: Vec::new(),relay_only: std::env::var("CUA_MESH_RELAY_ONLY").is_ok_and(|v| v == "1"),media_udp_port: MEDIA_UDP_PORT,+ reconnect_speedup: 1,}}}@@ -338,6 +343,7 @@ impl Mesh {pair_verifier: cfg.pair_verifier.clone(),approved,ephemeral: cfg.identity_path.is_none(),+ reconnect_speedup: cfg.reconnect_speedup.max(1),},control,engine.clone(),diff --git a/libs/cua/crates/cua-mesh/src/proto.rs b/libs/cua/crates/cua-mesh/src/proto.rsindex 70cbd1a1aa..a7c05d35fc 100644--- a/libs/cua/crates/cua-mesh/src/proto.rs+++ b/libs/cua/crates/cua-mesh/src/proto.rs@@ -34,6 +34,38 @@ use crate::key::{PublicKey, SecretKey};/// the relay's HTTPS path.pub const VERSION: u32 = 1;+/// WebSocket close codes the coordinator gives when it ends a session+/// itself (the private-use range), so a node can say why it was dropped and+/// whether trying again can help. The close reason is a short English+/// sentence for logs.+///+/// The relay restarts or its state changed: reconnect (spread out).+pub const CLOSE_RELAY_CHANGED: u16 = 4000;+/// Another connection with the same node key took over this one. A node+/// that keeps hearing this shares its identity with another running copy.+pub const CLOSE_REPLACED: u16 = 4001;+/// The device behind this node is no longer enrolled.+pub const CLOSE_DEVICE: u16 = 4002;+/// The session reached its maximum age: reconnect with a fresh token.+pub const CLOSE_SESSION_MAX: u16 = 4003;+/// The account or machine was erased.+pub const CLOSE_ERASED: u16 = 4004;+/// This node connected too often; the reason is `retry after N s`+/// ([`retry_after_reason`], [`parse_retry_after`]).+pub const CLOSE_RATE_LIMITED: u16 = 4029;++/// The close reason that tells a node when it may connect again.+pub fn retry_after_reason(secs: u64) -> String {+ format!("too many reconnects: retry after {secs} s")+}++/// The seconds in a [`retry_after_reason`] (or any `retry after N` text).+pub fn parse_retry_after(reason: &str) -> Option<u64> {+ let rest = reason.split("retry after ").nth(1)?;+ let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();+ digits.parse().ok()+}+/// The coordinator's WebSocket path.pub const CONNECT_PATH: &str = "/v1/mesh/connect";diff --git a/libs/cua/crates/cua-mesh/src/reconnect.rs b/libs/cua/crates/cua-mesh/src/reconnect.rsnew file mode 100644index 0000000000..e380301805--- /dev/null+++ b/libs/cua/crates/cua-mesh/src/reconnect.rs@@ -0,0 +1,167 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 Cua AI, Inc.++//! When the node connects to the coordinator again after a session ends.+//!+//! Exponential backoff with full jitter (a wait drawn uniformly from+//! `0..min(CAP, BASE * 2^attempt)`), so many nodes that lose the relay+//! together do not come back together. The attempt count resets only after+//! a session stayed up for [`HEALTHY`]: a session that is welcomed and then+//! dropped within moments is a failure like a refused connection, so a+//! client the relay keeps dropping slows down instead of retrying at a flat+//! pace. After the relay itself ended a session (a restart, a change), the+//! wait also gets [`spread`], so a fleet told to reconnect at one instant+//! does not do it in the same millisecond.++use std::time::Duration;++/// The window of the first retry.+pub(crate) const BASE: Duration = Duration::from_secs(1);+/// The largest window.+pub(crate) const CAP: Duration = Duration::from_secs(60);+/// A session this long was healthy: the backoff starts over.+pub(crate) const HEALTHY: Duration = Duration::from_secs(60);+/// After a relay-initiated end, the extra random wait is up to this.+pub(crate) const SPREAD: Duration = Duration::from_secs(10);++/// Reconnect pacing for one node.+#[derive(Debug, Default)]+pub(crate) struct Backoff {+ attempt: u32,+}++impl Backoff {+ /// Records that a session ended after `lived` of being welcomed (zero+ /// when it never was) and returns how long to wait before the next+ /// connect. `unit` is a random number in `0.0..=1.0`.+ pub(crate) fn next(&mut self, lived: Duration, unit: f64) -> Duration {+ if lived >= HEALTHY {+ self.attempt = 0;+ }+ let delay = window(self.attempt).mul_f64(unit.clamp(0.0, 1.0));+ self.attempt = self.attempt.saturating_add(1);+ delay+ }++ /// Treats the next retries as at least the `attempt`-th (a refusal is+ /// not worth retrying quickly).+ pub(crate) fn at_least(&mut self, attempt: u32) {+ self.attempt = self.attempt.max(attempt);+ }+}++/// The upper bound of the wait at `attempt` (0 is the first retry).+pub(crate) fn window(attempt: u32) -> Duration {+ BASE.saturating_mul(1u32 << attempt.min(16)).min(CAP)+}++/// The random extra wait after the relay ended a session. `unit` is a+/// random number in `0.0..=1.0`.+pub(crate) fn spread(unit: f64) -> Duration {+ SPREAD.mul_f64(unit.clamp(0.0, 1.0))+}++#[cfg(test)]+mod tests {+ use super::*;++ const SHORT: Duration = Duration::from_millis(800);++ #[test]+ fn the_window_doubles_from_one_second_to_the_cap() {+ let w: Vec<u64> = (0..9).map(|a| window(a).as_secs()).collect();+ assert_eq!(w, [1, 2, 4, 8, 16, 32, 60, 60, 60]);+ assert_eq!(window(u32::MAX), CAP);+ }++ #[test]+ fn the_wait_is_drawn_from_zero_to_the_window() {+ for attempt in 0..8 {+ let mut lo = Backoff { attempt };+ let mut hi = Backoff { attempt };+ assert_eq!(lo.next(SHORT, 0.0), Duration::ZERO);+ assert_eq!(hi.next(SHORT, 1.0), window(attempt));+ let mut mid = Backoff { attempt };+ assert_eq!(mid.next(SHORT, 0.5), window(attempt) / 2);+ }+ // Out-of-range randomness cannot escape the window.+ assert_eq!(Backoff::default().next(SHORT, 7.0), BASE);+ assert_eq!(Backoff::default().next(SHORT, -1.0), Duration::ZERO);+ }++ #[test]+ fn short_sessions_count_as_failures_and_the_wait_keeps_growing() {+ // The client the relay drops 0.8 s after it connects, every time:+ // the worst case waits must grow to the cap, never stay flat.+ let mut b = Backoff::default();+ let worst: Vec<u64> = (0..8).map(|_| b.next(SHORT, 1.0).as_secs()).collect();+ assert_eq!(worst, [1, 2, 4, 8, 16, 32, 60, 60]);+ // Even a session just under the healthy mark does not reset it.+ let mut b = Backoff::default();+ for _ in 0..4 {+ b.next(Duration::from_secs(59), 1.0);+ }+ assert_eq!(+ b.next(Duration::from_secs(59), 1.0),+ Duration::from_secs(16)+ );+ }++ #[test]+ fn a_failed_connect_counts_the_same() {+ let mut b = Backoff::default();+ let worst: Vec<u64> = (0..4)+ .map(|_| b.next(Duration::ZERO, 1.0).as_secs())+ .collect();+ assert_eq!(worst, [1, 2, 4, 8]);+ }++ #[test]+ fn only_a_session_that_stayed_healthy_resets_it() {+ let mut b = Backoff::default();+ for _ in 0..6 {+ b.next(SHORT, 1.0);+ }+ assert_eq!(b.next(HEALTHY, 1.0), BASE);+ // ... and then it grows again from the start.+ assert_eq!(b.next(SHORT, 1.0), Duration::from_secs(2));+ let mut b = Backoff::default();+ for _ in 0..6 {+ b.next(SHORT, 1.0);+ }+ assert_eq!(b.next(Duration::from_secs(3600), 1.0), BASE);+ }++ #[test]+ fn a_refusal_starts_further_up() {+ let mut b = Backoff::default();+ b.at_least(5);+ assert_eq!(b.next(Duration::ZERO, 1.0), Duration::from_secs(32));+ // It never lowers the attempt.+ b.at_least(1);+ assert_eq!(b.next(Duration::ZERO, 1.0), CAP);+ }++ #[test]+ fn relay_ended_sessions_are_spread_over_ten_seconds() {+ assert_eq!(spread(0.0), Duration::ZERO);+ assert_eq!(spread(0.5), Duration::from_secs(5));+ assert_eq!(spread(1.0), SPREAD);+ assert_eq!(spread(9.0), SPREAD);+ }++ #[test]+ fn a_herd_does_not_reconnect_in_one_instant() {+ // 1000 nodes told to reconnect at once: the draws cover 0..10 s+ // evenly enough that no tenth of a second holds more than a few+ // percent of them.+ let mut buckets = [0u32; 100];+ for _ in 0..1000 {+ let d = spread(rand::random_range(0.0..=1.0));+ assert!(d <= SPREAD);+ buckets[((d.as_millis() / 100) as usize).min(99)] += 1;+ }+ assert!(buckets.iter().all(|&n| n < 50), "{buckets:?}");+ assert!(buckets.iter().filter(|&&n| n > 0).count() > 80);+ }+}diff --git a/libs/cua/crates/cua-mesh/src/testing.rs b/libs/cua/crates/cua-mesh/src/testing.rsindex 551757041b..477ca71718 100644--- a/libs/cua/crates/cua-mesh/src/testing.rs+++ b/libs/cua/crates/cua-mesh/src/testing.rs@@ -48,6 +48,10 @@ struct State {/// Account mode: machines also peer with each other (one account's/// hosts, as `cua-relay` does).machine_peering: AtomicBool,+ /// Every welcomed node is closed at once with this WebSocket close.+ close_after_welcome: Mutex<Option<(u16, String)>>,+ /// Nodes welcomed since start.+ welcomes: AtomicU64,}/// See the module docs.@@ -187,6 +191,19 @@ impl FakeCoordinator {push_netmaps(&self.state, self.mode);}+ /// Closes every node right after it is welcomed, with `code` and+ /// `reason` (`None`: stops doing so), as the relay does when it drops+ /// a session for a reason of its own.+ pub fn close_after_welcome(&self, close: Option<(u16, &str)>) {+ *self.state.close_after_welcome.lock().expect("close") =+ close.map(|(c, r)| (c, r.to_owned()));+ }++ /// Nodes welcomed since start.+ pub fn welcomes(&self) -> u64 {+ self.state.welcomes.load(Ordering::SeqCst)+ }+/// Nodes connected right now.pub fn connected(&self) -> usize {self.state.conns.lock().expect("conns").len()@@ -420,6 +437,19 @@ async fn serve(state: Arc<State>, mode: Mode, tcp: tokio::net::TcpStream) {{return;}+ state.welcomes.fetch_add(1, Ordering::SeqCst);+ let close = state.close_after_welcome.lock().expect("close").clone();+ if let Some((code, reason)) = close {+ let _ = sink+ .send(WsMessage::Close(Some(+ tokio_tungstenite::tungstenite::protocol::CloseFrame {+ code: code.into(),+ reason: reason.into(),+ },+ )))+ .await;+ return;+ }let (tx, mut rx) = mpsc::unbounded_channel::<WsMessage>();state.nodes.lock().expect("nodes").insert(node_key, info);statediff --git a/libs/cua/crates/cua-mesh/tests/mesh.rs b/libs/cua/crates/cua-mesh/tests/mesh.rsindex 20d43647dd..85bf1e9ddd 100644--- a/libs/cua/crates/cua-mesh/tests/mesh.rs+++ b/libs/cua/crates/cua-mesh/tests/mesh.rs@@ -790,3 +790,59 @@ async fn a_forward_carries_bulk_traffic_to_a_local_port() {assert_eq!(counted.await.unwrap(), N);println!("256 MiB in {:?}", t.elapsed());}++#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn a_node_the_relay_keeps_replacing_stops_retrying_and_says_why() {+ let dir = tempfile::tempdir().unwrap();+ let coord = FakeCoordinator::start(Mode::Account).await;+ coord.close_after_welcome(Some((+ cua_mesh::proto::CLOSE_REPLACED,+ "replaced: another connection with the same node key took over",+ )));+ let mut cfg = MeshConfig::new(+ coord.url.clone(),+ NodeKind::Client,+ Some(dir.path().join("c.json")),+ static_auth(vec![]),+ );+ cfg.reconnect_speedup = 1000;+ let client = Mesh::start(cfg).await.unwrap();+ let t = std::time::Instant::now();+ let reason = loop {+ if let Some(r) = client.control_state().denied {+ break r;+ }+ assert!(t.elapsed() < Duration::from_secs(20), "it never gave up");+ tokio::time::sleep(Duration::from_millis(20)).await;+ };+ assert!(reason.contains("another copy of Spaces"), "{reason}");+ // It stopped: no connect after the third.+ tokio::time::sleep(Duration::from_millis(300)).await;+ assert_eq!(coord.welcomes(), 3);+ let last = client.control_state().last_error.unwrap();+ assert!(last.contains("4001") && last.contains("replaced"), "{last}");+}++#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn a_node_dropped_for_other_reasons_keeps_reconnecting() {+ let dir = tempfile::tempdir().unwrap();+ let coord = FakeCoordinator::start(Mode::Account).await;+ coord.close_after_welcome(Some((+ cua_mesh::proto::CLOSE_RELAY_CHANGED,+ "relay changed",+ )));+ let mut cfg = MeshConfig::new(+ coord.url.clone(),+ NodeKind::Client,+ Some(dir.path().join("c.json")),+ static_auth(vec![]),+ );+ cfg.reconnect_speedup = 1000;+ let client = Mesh::start(cfg).await.unwrap();+ let t = std::time::Instant::now();+ while coord.welcomes() < 5 {+ assert!(t.elapsed() < Duration::from_secs(20), "it stopped retrying");+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ assert!(client.control_state().denied.is_none());+}