The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(socket): tie emit readiness to the connection's channel (atomic gate)\n\nReview follow-ups (#6084):\n- Bundle per-connection readiness with the emit channel (EmitChannel { tx,\n ready: Arc<AtomicBool> }). emit checks ready UNDER the emit_tx lock, so status\n and channel can't be swapped mid-emit — closing the reconnect TOCTOU where an\n emit could enqueue onto a fresh pre-handshake channel and return Ok\n (CodeRabbit).\n- ready is set true only after the SIO CONNECT ACK and cleared on teardown\n before drain; it is NOT tied to the presentation-layer status, so a server\n 'error' event that leaves the socket live no longer wedges emits forever\n (Codex P1). ws_loop takes the readiness flag; emit_with_ack + #4355 drain\n unchanged. +3 deterministic regression tests.\n
shanu160d6e30bb62
diff --git a/src/openhuman/platform/socket/manager.rs b/src/openhuman/platform/socket/manager.rsindex e5d103d548..1bd7819d48 100644--- a/src/openhuman/platform/socket/manager.rs+++ b/src/openhuman/platform/socket/manager.rs@@ -11,7 +11,7 @@use std::collections::HashMap;use std::sync::{- atomic::{AtomicU64, Ordering},+ atomic::{AtomicBool, AtomicU64, Ordering},Arc, OnceLock,};@@ -64,6 +64,25 @@ pub(super) struct SharedState {pub(super) error: RwLock<Option<String>>,}+/// The outbound emit channel bundled with the readiness flag of the **same**+/// connection that owns it.+///+/// Readiness travels with the channel so `emit` can decide "is this message+/// deliverable?" atomically with picking the channel it would send on: both are+/// read under the single `emit_tx` lock. `spawn_loop` installs a fresh+/// `EmitChannel` (fresh sender + fresh `ready = false` flag) for every+/// connection, and the background loop flips *this connection's* `ready` to+/// `true` only after the Socket.IO CONNECT ACK and back to `false` on teardown.+/// A reconnect therefore swaps the sender and its flag together — an `emit`+/// holding the lock can never pair a live-looking status with a stale+/// pre-handshake channel (the reverse of the TOCTOU the status-only gate had).+pub(super) struct EmitChannel {+ /// Sender into the background loop's outbound queue.+ pub(super) tx: mpsc::UnboundedSender<String>,+ /// `true` only between this connection's CONNECT ACK and its teardown.+ pub(super) ready: Arc<AtomicBool>,+}+pub(super) struct AckRegistry {next_id: AtomicU64,pending: Mutex<HashMap<u64, oneshot::Sender<serde_json::Value>>>,@@ -116,8 +135,10 @@ impl AckRegistry {pub struct SocketManager {/// Shared state accessible from both the manager and the background loop.pub(super) shared: Arc<SharedState>,- /// Channel for sending outgoing messages to the background loop.- emit_tx: tokio::sync::Mutex<Option<mpsc::UnboundedSender<String>>>,+ /// Channel for sending outgoing messages to the background loop, bundled+ /// with the readiness flag of the connection that owns it so `emit` reads+ /// both atomically under one lock (see [`EmitChannel`]).+ emit_tx: tokio::sync::Mutex<Option<EmitChannel>>,/// Channel for signaling the background loop to shut down.shutdown_tx: tokio::sync::Mutex<Option<watch::Sender<bool>>>,/// Join handle for the background connection loop.@@ -264,14 +285,33 @@ impl SocketManager {let internal_tx = emit_tx.clone();let (shutdown_tx, shutdown_rx) = watch::channel(false);- *self.emit_tx.lock().await = Some(emit_tx);+ // Per-connection readiness flag: starts `false` (pre-handshake) and is+ // flipped by `ws_loop` at CONNECT ACK. Bundled with the sender so `emit`+ // reads the flag belonging to exactly this channel, not a flag a later+ // reconnect may have swapped underneath it.+ let emit_ready = Arc::new(AtomicBool::new(false));+ let loop_ready = Arc::clone(&emit_ready);++ *self.emit_tx.lock().await = Some(EmitChannel {+ tx: emit_tx,+ ready: emit_ready,+ });*self.shutdown_tx.lock().await = Some(shutdown_tx);let url = url.to_string();let shared = Arc::clone(&self.shared);let handle = tokio::spawn(async move {- ws_loop(url, provider, shared, emit_rx, shutdown_rx, internal_tx).await;+ ws_loop(+ url,+ provider,+ shared,+ emit_rx,+ shutdown_rx,+ internal_tx,+ loop_ready,+ )+ .await;});*self.loop_handle.lock().await = Some(handle);@@ -299,24 +339,39 @@ impl SocketManager {/// Emit a Socket.IO event to the server.///- /// Gated on connection **readiness**, not merely on the emit channel- /// existing. `spawn_loop` installs `emit_tx` while the status is still- /// `Connecting` (before the Engine.IO / Socket.IO handshake completes), so a- /// channel-only guard would report success for a message that `ws_loop`'s- /// `drain_pending_emits` silently discards if the handshake then fails- /// (#4355). Callers must be told the truth, so an emit before the socket is- /// `Connected` returns the same `"Not connected"` error as an emit before- /// `connect` was ever called.+ /// Gated on the **owning connection's** readiness flag, not on the emit+ /// channel merely existing nor on the presentation-layer `status`. Two races+ /// motivate this:+ ///+ /// - `spawn_loop` installs `emit_tx` while the handshake is still in flight,+ /// so a channel-only guard would report success for a message that+ /// `ws_loop`'s `drain_pending_emits` silently discards if the handshake+ /// then fails (#4355 / #6084 pre-handshake false success).+ /// - Reading `status` and then acquiring the `emit_tx` lock are two separate+ /// steps; a reconnect in between could flip `status` and swap in a fresh+ /// pre-handshake channel, so a `status`-only gate could enqueue onto the+ /// *new* channel and return `Ok` for a message that channel then drops.+ ///+ /// The flag is created with, owned by, and flipped for a single connection,+ /// and it is read here under the same lock that hands us the channel — so+ /// status and channel can never be swapped mid-emit. Because readiness is+ /// cleared only on that connection's teardown (not on a presentation-layer+ /// `error` event that leaves the socket live), a still-connected socket+ /// keeps accepting emits. A pre-handshake or disconnected emit returns the+ /// same `"Not connected"` error as an emit before `connect` was ever called.pub async fn emit(&self, event: &str, data: serde_json::Value) -> Result<(), String> {- if !self.is_connected() {+ let guard = self.emit_tx.lock().await;+ let Some(channel) = guard.as_ref() else {+ return Err("Not connected".to_string());+ };+ if !channel.ready.load(Ordering::Acquire) {return Err("Not connected".to_string());}- if let Some(ref tx) = *self.emit_tx.lock().await {- let msg = encode_sio_event(event, data, None)?;- tx.send(msg).map_err(|_| "Socket not connected".to_string())- } else {- Err("Not connected".to_string())- }+ let msg = encode_sio_event(event, data, None)?;+ channel+ .tx+ .send(msg)+ .map_err(|_| "Socket not connected".to_string())}/// Emit a Socket.IO event and wait for the backend ACK callback.@@ -338,7 +393,8 @@ impl SocketManager {.emit_tx.lock().await- .clone()+ .as_ref()+ .map(|c| c.tx.clone()).ok_or_else(|| "Not connected".to_string())?;let (ack_id, ack_rx) = self.shared.ack_registry.register();let msg = encode_sio_event(event, data, Some(ack_id))?;diff --git a/src/openhuman/platform/socket/manager_tests.rs b/src/openhuman/platform/socket/manager_tests.rsindex c0f98ecadf..319a59ff52 100644--- a/src/openhuman/platform/socket/manager_tests.rs+++ b/src/openhuman/platform/socket/manager_tests.rs@@ -59,11 +59,15 @@ async fn emit_without_connection_errors_without_panic() {#[tokio::test]async fn emit_while_connecting_errors_even_with_emit_channel_present() {// Arrange: mirror `spawn_loop`'s pre-handshake state — the emit channel is- // installed (so the old channel-only guard would pass) but the socket has- // not finished the SIO handshake yet.+ // installed (so the old channel-only guard would pass) but the connection's+ // readiness flag is still `false` because the SIO handshake has not+ // completed.let mgr = SocketManager::new();let (tx, mut rx) = mpsc::unbounded_channel::<String>();- *mgr.emit_tx.lock().await = Some(tx);+ *mgr.emit_tx.lock().await = Some(EmitChannel {+ tx,+ ready: Arc::new(AtomicBool::new(false)),+ });*mgr.shared.status.write() = ConnectionStatus::Connecting;// Act@@ -77,22 +81,26 @@ async fn emit_while_connecting_errors_even_with_emit_channel_present() {assert_eq!(err, "Not connected");assert!(rx.try_recv().is_err(),- "emit must not queue a message before the socket is Connected"+ "emit must not queue a message before the connection is ready");}#[tokio::test]async fn emit_when_connected_queues_the_encoded_event() {- // Arrange+ // Arrange: a handshaked connection — its readiness flag is set, mirroring+ // what `run_connection` does after the SIO CONNECT ACK.let mgr = SocketManager::new();let (tx, mut rx) = mpsc::unbounded_channel::<String>();- *mgr.emit_tx.lock().await = Some(tx);+ *mgr.emit_tx.lock().await = Some(EmitChannel {+ tx,+ ready: Arc::new(AtomicBool::new(true)),+ });*mgr.shared.status.write() = ConnectionStatus::Connected;// Actmgr.emit("test.event", json!({ "k": "v" })).await- .expect("emit must succeed once the socket is Connected");+ .expect("emit must succeed once the connection is ready");// Assert: the encoded Socket.IO event lands on the outbound channel.let queued = rx@@ -101,6 +109,99 @@ async fn emit_when_connected_queues_the_encoded_event() {assert_eq!(queued, r#"42["test.event",{"k":"v"}]"#);}+/// F2 (TOCTOU with reconnect): a reconnect that swaps in a fresh, not-yet-ready+/// channel while an `emit` is in flight must not let that `emit` succeed onto+/// the new pre-handshake channel. The readiness flag travels with the channel,+/// so replacing the channel replaces its flag too — a `status`-only gate would+/// have enqueued onto the new channel and returned `Ok`, then `drain_pending_emits`+/// would have discarded it (the exact false success #6084 targets).+#[tokio::test]+async fn emit_does_not_land_on_a_reconnects_pre_handshake_channel() {+ let mgr = SocketManager::new();++ // Old, live connection: ready channel + Connected status.+ let (_old_tx, mut old_rx) = mpsc::unbounded_channel::<String>();+ *mgr.emit_tx.lock().await = Some(EmitChannel {+ tx: _old_tx,+ ready: Arc::new(AtomicBool::new(true)),+ });+ *mgr.shared.status.write() = ConnectionStatus::Connected;++ // A reconnect begins: `spawn_loop` would flip status→Connecting and install+ // a fresh channel whose readiness flag is still `false` (handshake pending).+ // We reproduce exactly that swap.+ let (new_tx, mut new_rx) = mpsc::unbounded_channel::<String>();+ *mgr.emit_tx.lock().await = Some(EmitChannel {+ tx: new_tx,+ ready: Arc::new(AtomicBool::new(false)),+ });+ // Status may still read Connected in the narrow window before the loop+ // updates it — leaving it Connected here is the adversarial case a+ // `status`-only gate would have failed.+ *mgr.shared.status.write() = ConnectionStatus::Connected;++ // Act+ let err = mgr+ .emit("test.event", json!({ "k": "v" }))+ .await+ .unwrap_err();++ // Assert: rejected, and nothing queued onto either channel.+ assert_eq!(err, "Not connected");+ assert!(+ new_rx.try_recv().is_err(),+ "emit must not enqueue onto a reconnect's pre-handshake channel"+ );+ assert!(+ old_rx.try_recv().is_err(),+ "emit must not enqueue onto the replaced channel either"+ );+}++/// F1 (server `error` on a still-live socket): a server-emitted `error` event+/// flips the presentation status to `Error` but does not tear down the+/// transport, so the connection is still live and its readiness flag is+/// untouched. `emit` must therefore keep succeeding — a gate that rejected on+/// `status != Connected` would wedge every subsequent emit forever.+#[tokio::test]+async fn emit_still_succeeds_after_server_error_on_live_connection() {+ let mgr = SocketManager::new();++ // Live, handshaked connection.+ let (tx, mut rx) = mpsc::unbounded_channel::<String>();+ *mgr.emit_tx.lock().await = Some(EmitChannel {+ tx,+ ready: Arc::new(AtomicBool::new(true)),+ });+ *mgr.shared.status.write() = ConnectionStatus::Connected;++ // Drive the real handler for a server `error` event. It sets status=Error+ // on the same live socket without closing the transport — and has no access+ // to the readiness flag, which is owned by the connection loop.+ let (sink_tx, _sink_rx) = mpsc::unbounded_channel::<String>();+ super::super::event_handlers::handle_sio_event(+ "error",+ json!({ "message": "boom" }),+ &sink_tx,+ &mgr.shared,+ );+ assert_eq!(+ *mgr.shared.status.read(),+ ConnectionStatus::Error,+ "server error event must flip presentation status to Error"+ );++ // Act: the socket is still live, so emit must still be delivered.+ mgr.emit("test.event", json!({ "k": "v" }))+ .await+ .expect("emit must still succeed on a live socket after a server error");++ let queued = rx+ .try_recv()+ .expect("the event must be queued for the live connection");+ assert_eq!(queued, r#"42["test.event",{"k":"v"}]"#);+}+#[tokio::test]async fn emit_with_ack_without_connection_errors_without_waiting() {let mgr = SocketManager::new();@@ -113,9 +214,15 @@ async fn emit_with_ack_without_connection_errors_without_waiting() {#[tokio::test]async fn emit_with_ack_uses_emit_queue_while_connecting() {+ // `emit_with_ack` deliberately does not gate on readiness (its delivery is+ // confirmed by the ack), so a pre-handshake channel (`ready = false`) must+ // still enqueue the frame.let mgr = SocketManager::new();let (tx, mut rx) = mpsc::unbounded_channel::<String>();- *mgr.emit_tx.lock().await = Some(tx);+ *mgr.emit_tx.lock().await = Some(EmitChannel {+ tx,+ ready: Arc::new(AtomicBool::new(false)),+ });*mgr.shared.status.write() = ConnectionStatus::Connecting;let result = mgrdiff --git a/src/openhuman/platform/socket/ws_loop_part_01.rs b/src/openhuman/platform/socket/ws_loop_part_01.rsindex 8c1703a36f..d097513734 100644--- a/src/openhuman/platform/socket/ws_loop_part_01.rs+++ b/src/openhuman/platform/socket/ws_loop_part_01.rs@@ -1,3 +1,4 @@+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;use futures_util::{SinkExt, StreamExt};@@ -68,6 +69,7 @@ pub(super) async fn ws_loop(mut emit_rx: mpsc::UnboundedReceiver<String>,mut shutdown_rx: watch::Receiver<bool>,internal_tx: mpsc::UnboundedSender<String>,+ emit_ready: Arc<AtomicBool>,) {let mut backoff = Duration::from_millis(1000);let max_backoff = Duration::from_secs(30);@@ -152,9 +154,18 @@ pub(super) async fn ws_loop(&mut emit_rx,&mut shutdown_rx,&internal_tx,+ &emit_ready,).await;+ // The connection is over. Clear this connection's readiness flag+ // *before* draining so a concurrent `emit` cannot pass its readiness+ // check and enqueue a message this connection is about to discard.+ // `run_connection` only ever sets it `true` after the CONNECT ACK, so+ // clearing here also covers a connection that never handshook. It is a+ // no-op on a `Failed` attempt that never flipped it.+ emit_ready.store(false, Ordering::Release);+// The connection attempt has ended (lost, failed, or shutdown), so any// in-flight `emit_with_ack` waiter can never receive its ACK now. Cancel// them here — covering server-driven disconnects (`Lost`) and the@@ -449,6 +460,7 @@ async fn run_connection(emit_rx: &mut mpsc::UnboundedReceiver<String>,shutdown_rx: &mut watch::Receiver<bool>,internal_tx: &mpsc::UnboundedSender<String>,+ emit_ready: &AtomicBool,) -> ConnectionOutcome {log::info!("[socket] WS URL: {}", ws_url);@@ -513,9 +525,16 @@ async fn run_connection(.map(String::from);log::info!("[socket] SIO CONNECT ACK: sid={:?}", sio_sid);- // 6. Update state to Connected+ // 6. Update state to Connected and mark this connection ready to emit.+ // The readiness flag is the emit gate (see `SocketManager::emit`): only now,+ // past a completed Socket.IO CONNECT ACK, is a queued message guaranteed to+ // ride *this* live socket rather than be dropped by `drain_pending_emits`.+ // A later server `error` EVENT flips `status` to `Error` for the UI but does+ // not return from this function, so the socket stays live and this flag+ // stays set — emits keep flowing until the connection is actually torn down.*shared.status.write() = ConnectionStatus::Connected;*shared.socket_id.write() = sio_sid;+ emit_ready.store(true, Ordering::Release);emit_state_change(shared);// 7. Main event loopdiff --git a/src/openhuman/platform/socket/ws_loop_tests.rs b/src/openhuman/platform/socket/ws_loop_tests.rsindex 82aab0d313..68d5fa92ed 100644--- a/src/openhuman/platform/socket/ws_loop_tests.rs+++ b/src/openhuman/platform/socket/ws_loop_tests.rs@@ -1,6 +1,6 @@use super::*;use parking_lot::RwLock;-use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use tokio_tungstenite::tungstenite::http::{header::LOCATION, Response, StatusCode};use crate::openhuman::platform::socket::token_provider::{diff --git a/src/openhuman/platform/socket/ws_loop_tests_part_01_tests.rs b/src/openhuman/platform/socket/ws_loop_tests_part_01_tests.rsindex 2fdb83fead..6d5e387a20 100644--- a/src/openhuman/platform/socket/ws_loop_tests_part_01_tests.rs+++ b/src/openhuman/platform/socket/ws_loop_tests_part_01_tests.rs@@ -418,6 +418,7 @@ async fn ws_loop_completes_handshake_and_shuts_down_cleanly() {emit_rx,shutdown_rx,internal_tx,+ Arc::new(AtomicBool::new(false)),).await;});@@ -476,6 +477,7 @@ async fn ws_loop_handles_connect_error_and_shutdown() {emit_rx,shutdown_rx,internal_tx,+ Arc::new(AtomicBool::new(false)),).await;});@@ -510,6 +512,7 @@ async fn ws_loop_handles_bad_eio_open_and_shutdown() {emit_rx,shutdown_rx,internal_tx,+ Arc::new(AtomicBool::new(false)),).await;});@@ -565,6 +568,7 @@ async fn ws_loop_refuses_to_start_with_empty_token() {emit_rx,shutdown_rx,internal_tx,+ Arc::new(AtomicBool::new(false)),).await;});@@ -601,6 +605,7 @@ async fn ws_loop_exits_cleanly_when_provider_returns_error() {emit_rx,shutdown_rx,internal_tx,+ Arc::new(AtomicBool::new(false)),).await;});diff --git a/src/openhuman/platform/socket/ws_loop_tests_part_02_tests.rs b/src/openhuman/platform/socket/ws_loop_tests_part_02_tests.rsindex 7f120d56b9..f6dc3b18a4 100644--- a/src/openhuman/platform/socket/ws_loop_tests_part_02_tests.rs+++ b/src/openhuman/platform/socket/ws_loop_tests_part_02_tests.rs@@ -33,6 +33,7 @@ async fn ws_loop_follows_301_to_working_backend() {emit_rx,shutdown_rx,internal_tx,+ Arc::new(AtomicBool::new(false)),).await;});@@ -146,6 +147,7 @@ async fn ws_loop_calls_provider_before_each_attempt() {emit_rx,shutdown_rx,internal_tx,+ Arc::new(AtomicBool::new(false)),).await;});@@ -201,6 +203,7 @@ async fn ws_loop_escalates_immediately_on_invalid_token_no_refresh() {emit_rx,shutdown_rx,internal_tx,+ Arc::new(AtomicBool::new(false)),).await;});@@ -270,6 +273,7 @@ async fn ws_loop_retries_with_fresh_token_on_invalid_token() {emit_rx,shutdown_rx,internal_tx,+ Arc::new(AtomicBool::new(false)),).await;});@@ -358,6 +362,7 @@ async fn ws_loop_bounds_fresh_token_retries_with_rotating_provider() {emit_rx,shutdown_rx,internal_tx,+ Arc::new(AtomicBool::new(false)),).await;});