Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(socket): serialize emit send with teardown drain (no stale cross-session emit)\n\nReview follow-up (#6084, CodeRabbit): the emit channel + readiness flag are\nreused across reconnects within one ws_loop, so a bare emit that observed\nready==true could tx.send AFTER teardown cleared ready and drained emit_rx —\nreturning Ok for a message the next session's receiver would forward on a fresh\nsid. Make emit's (check ready + send) mutually exclusive with teardown's (clear\nready + drain) by turning readiness into Arc<parking_lot::Mutex<bool>>\n(EmitReady): emit holds ready across the check+send under the emit_tx lock;\nteardown clears+drains under the same ready guard. Lock order emit_tx -> ready\n(leaf), never nested the other way; ready is never held across .await. #6084\npre-handshake gate + #4355 drain + emit_with_ack preserved. Barrier test added.\n

shanu31bd0ba1f4a8
diff --git a/src/openhuman/platform/socket/manager.rs b/src/openhuman/platform/socket/manager.rs
index 1bd7819d48..093bb41d3c 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::{AtomicBool, AtomicU64, Ordering},
+ atomic::{AtomicU64, Ordering},
Arc, OnceLock,
};
@@ -64,6 +64,22 @@ pub(super) struct SharedState {
pub(super) error: RwLock<Option<String>>,
}
+/// The connection's readiness flag, guarded by a lock so a reader can hold the
+/// flag `true` across the send it authorises.
+///
+/// A bare `AtomicBool` cannot express that: `emit` would load `true`, and the
+/// background loop's teardown could then clear the flag *and* drain the emit
+/// queue in the gap before `emit`'s `tx.send` runs, so the message lands in the
+/// just-drained channel and rides the *next* reconnect's socket (a fresh sid
+/// whose roster the backend has already cleared). Both critical sections —
+/// `emit`'s "is-ready? then send" and teardown's "clear then drain" — take this
+/// lock, so they are mutually exclusive and that interleaving cannot happen. The
+/// guard is a leaf: it is only ever held for a synchronous flag read/write plus
+/// a non-blocking channel `send`/`try_recv`, never across an `.await` and never
+/// while another socket lock is held, so it introduces no lock-ordering hazard
+/// with `emit_tx` or the `status` `RwLock`.
+pub(super) type EmitReady = Arc<Mutex<bool>>;
+
/// The outbound emit channel bundled with the readiness flag of the **same**
/// connection that owns it.
///
@@ -76,11 +92,16 @@ pub(super) struct SharedState {
/// 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).
+///
+/// `ready` is additionally the serialization point between `emit` and teardown:
+/// see [`EmitReady`] for why the flag is a `Mutex<bool>` rather than an atomic.
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>,
+ /// `true` only between this connection's CONNECT ACK and its teardown, and
+ /// the lock that makes `emit`'s check+send exclusive with teardown's
+ /// clear+drain (see [`EmitReady`]).
+ pub(super) ready: EmitReady,
}
pub(super) struct AckRegistry {
@@ -136,8 +157,11 @@ 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, bundled
- /// with the readiness flag of the connection that owns it so `emit` reads
- /// both atomically under one lock (see [`EmitChannel`]).
+ /// with the readiness flag of the connection that owns it. `emit` selects the
+ /// channel under this lock, then gates its check+send on the channel's own
+ /// `ready` lock, so a reconnect can never swap the channel out mid-emit nor
+ /// let teardown drain between the readiness check and the send
+ /// (see [`EmitChannel`] and [`EmitReady`]).
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>>>,
@@ -288,8 +312,10 @@ impl SocketManager {
// 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));
+ // reconnect may have swapped underneath it. It is a `Mutex<bool>` rather
+ // than an atomic so `emit`'s check+send and the loop's clear+drain can be
+ // made mutually exclusive (see [`EmitReady`]).
+ let emit_ready: EmitReady = Arc::new(Mutex::new(false));
let loop_ready = Arc::clone(&emit_ready);
*self.emit_tx.lock().await = Some(EmitChannel {
@@ -359,15 +385,29 @@ impl SocketManager {
/// `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.
+ ///
+ /// The readiness check and the `tx.send` it authorises are performed under
+ /// the `ready` lock (see [`EmitReady`]), so the background loop's teardown
+ /// cannot clear the flag and drain the queue in the gap between them — which
+ /// would otherwise let this method return `Ok(())` for a message that lands
+ /// in the just-drained channel and rides the *next* reconnect's socket.
pub async fn emit(&self, event: &str, data: serde_json::Value) -> Result<(), String> {
+ // Encode outside the readiness lock: it is fallible and touches neither
+ // the flag nor the channel, so there is no reason to widen the critical
+ // section around it.
+ let msg = encode_sio_event(event, data, None)?;
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) {
+ // Hold `ready` across the check *and* the send so teardown's clear+drain
+ // (which takes the same lock) cannot interleave between them. `send` on an
+ // unbounded channel does not block, so this leaf lock is never held over
+ // an `.await`.
+ let ready = channel.ready.lock();
+ if !*ready {
return Err("Not connected".to_string());
}
- let msg = encode_sio_event(event, data, None)?;
channel
.tx
.send(msg)
diff --git a/src/openhuman/platform/socket/manager_tests.rs b/src/openhuman/platform/socket/manager_tests.rs
index 319a59ff52..41ab5b8814 100644
--- a/src/openhuman/platform/socket/manager_tests.rs
+++ b/src/openhuman/platform/socket/manager_tests.rs
@@ -66,7 +66,7 @@ async fn emit_while_connecting_errors_even_with_emit_channel_present() {
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
*mgr.emit_tx.lock().await = Some(EmitChannel {
tx,
- ready: Arc::new(AtomicBool::new(false)),
+ ready: Arc::new(Mutex::new(false)),
});
*mgr.shared.status.write() = ConnectionStatus::Connecting;
@@ -93,7 +93,7 @@ async fn emit_when_connected_queues_the_encoded_event() {
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
*mgr.emit_tx.lock().await = Some(EmitChannel {
tx,
- ready: Arc::new(AtomicBool::new(true)),
+ ready: Arc::new(Mutex::new(true)),
});
*mgr.shared.status.write() = ConnectionStatus::Connected;
@@ -123,7 +123,7 @@ async fn emit_does_not_land_on_a_reconnects_pre_handshake_channel() {
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)),
+ ready: Arc::new(Mutex::new(true)),
});
*mgr.shared.status.write() = ConnectionStatus::Connected;
@@ -133,7 +133,7 @@ async fn emit_does_not_land_on_a_reconnects_pre_handshake_channel() {
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)),
+ ready: Arc::new(Mutex::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
@@ -171,7 +171,7 @@ async fn emit_still_succeeds_after_server_error_on_live_connection() {
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
*mgr.emit_tx.lock().await = Some(EmitChannel {
tx,
- ready: Arc::new(AtomicBool::new(true)),
+ ready: Arc::new(Mutex::new(true)),
});
*mgr.shared.status.write() = ConnectionStatus::Connected;
@@ -202,6 +202,82 @@ async fn emit_still_succeeds_after_server_error_on_live_connection() {
assert_eq!(queued, r#"42["test.event",{"k":"v"}]"#);
}
+/// Teardown-vs-emit interleaving (the CodeRabbit Major on #6103): the
+/// background loop clears the readiness flag and drains the emit queue on
+/// teardown, and `emit` checks the flag then sends. If those two are not
+/// mutually exclusive, an `emit` that observed `ready == true` can have its
+/// `tx.send` land *after* the drain — leaving a stale message in the channel
+/// that the next reconnect (a fresh sid whose roster the backend cleared)
+/// forwards. This is the exact race `medulla::workflows::with_live_connection`
+/// already guards for the medulla handlers; the bare `emit` path is closed by
+/// making both critical sections take the connection's `ready` lock.
+///
+/// The barrier: the test task takes the `ready` lock (standing in for teardown
+/// holding the gate) *before* clearing it, then spawns an `emit`. If `emit` and
+/// teardown share the lock, `emit` blocks at its readiness check and cannot
+/// complete while the guard is held — proven by the pending-while-locked
+/// assertion. Teardown then runs under the held lock (clear + drain) exactly as
+/// `ws_loop` does, releases, and only then does `emit` resume — observing
+/// `ready == false` and enqueuing nothing. Reverting the flag to a bare
+/// `AtomicBool` (no shared lock) removes the block, so `emit` would slip its
+/// send past the drain and this test's guarantees would no longer hold.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn emit_cannot_send_past_a_concurrent_teardown_drain() {
+ let mgr = Arc::new(SocketManager::new());
+
+ // A live, handshaked connection. Keep a clone of its readiness gate and its
+ // receiver so the test can drive teardown's clear+drain directly.
+ let (tx, mut rx) = mpsc::unbounded_channel::<String>();
+ let gate = Arc::new(Mutex::new(true));
+ *mgr.emit_tx.lock().await = Some(EmitChannel {
+ tx,
+ ready: Arc::clone(&gate),
+ });
+ *mgr.shared.status.write() = ConnectionStatus::Connected;
+
+ // Teardown begins: take the gate before clearing it, mirroring `ws_loop`'s
+ // "clear the flag and drain under the same lock" critical section.
+ let mut teardown_guard = gate.lock();
+
+ // A concurrent emit starts while teardown holds the gate.
+ let emit_mgr = Arc::clone(&mgr);
+ let mut emit_task =
+ tokio::spawn(async move { emit_mgr.emit("test.event", json!({ "k": "v" })).await });
+
+ // While the gate is held, `emit` must not be able to complete: it is blocked
+ // at its readiness check on the same lock teardown holds. A bare atomic flag
+ // would let it read `true` and send here, past the drain below.
+ assert!(
+ tokio::time::timeout(Duration::from_millis(200), &mut emit_task)
+ .await
+ .is_err(),
+ "emit must block on the readiness gate while teardown holds it"
+ );
+
+ // Teardown's clear + drain, under the held lock. `drain_pending_emits` lives
+ // in the sibling `ws_loop` module; the loop replicates its try_recv sweep.
+ *teardown_guard = false;
+ let mut drained = 0usize;
+ while rx.try_recv().is_ok() {
+ drained += 1;
+ }
+ assert_eq!(drained, 0, "nothing was queued before teardown began");
+ drop(teardown_guard);
+
+ // With the gate released and cleared, the previously-blocked emit resumes,
+ // sees `ready == false`, and rejects — enqueuing nothing onto the channel
+ // the next reconnect would forward from.
+ let result = tokio::time::timeout(Duration::from_secs(1), emit_task)
+ .await
+ .expect("emit must resume once teardown releases the gate")
+ .expect("emit task must not panic");
+ assert_eq!(result.unwrap_err(), "Not connected");
+ assert!(
+ rx.try_recv().is_err(),
+ "emit must not send past the teardown drain — a message here rides the next reconnect"
+ );
+}
+
#[tokio::test]
async fn emit_with_ack_without_connection_errors_without_waiting() {
let mgr = SocketManager::new();
@@ -221,7 +297,7 @@ async fn emit_with_ack_uses_emit_queue_while_connecting() {
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
*mgr.emit_tx.lock().await = Some(EmitChannel {
tx,
- ready: Arc::new(AtomicBool::new(false)),
+ ready: Arc::new(Mutex::new(false)),
});
*mgr.shared.status.write() = ConnectionStatus::Connecting;
diff --git a/src/openhuman/platform/socket/ws_loop_part_01.rs b/src/openhuman/platform/socket/ws_loop_part_01.rs
index d097513734..b1ce3cf8a3 100644
--- a/src/openhuman/platform/socket/ws_loop_part_01.rs
+++ b/src/openhuman/platform/socket/ws_loop_part_01.rs
@@ -1,6 +1,7 @@
-use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
+use parking_lot::Mutex;
+
use futures_util::{SinkExt, StreamExt};
use serde_json::json;
use tokio::sync::{mpsc, watch};
@@ -69,7 +70,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>,
+ emit_ready: Arc<Mutex<bool>>,
) {
let mut backoff = Duration::from_millis(1000);
let max_backoff = Duration::from_secs(30);
@@ -158,13 +159,29 @@ pub(super) async fn ws_loop(
)
.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 is over. Clear this connection's readiness flag and
+ // drain whatever is still queued, both under the `emit_ready` lock so a
+ // concurrent `emit` cannot slip between them: without the shared lock,
+ // `emit` could observe `ready == true`, this teardown could clear+drain,
+ // and `emit`'s `tx.send` could then land a message in the just-emptied
+ // channel — where the next reconnect (a fresh sid, whose roster the
+ // backend has cleared) would forward it. `emit` takes the same lock
+ // across its check+send, so that interleaving cannot occur.
+ //
+ // Clearing also covers a connection that never handshook (`run_connection`
+ // only sets `true` after the CONNECT ACK), and draining is the backstop
+ // for anything already queued: `emit_rx` is owned by this loop, not by
+ // the connection, so a leftover message would otherwise be flushed onto
+ // the next socket. It is a no-op on a `Failed` attempt that never flipped
+ // the flag or queued anything.
+ let dropped = {
+ let mut ready = emit_ready.lock();
+ *ready = false;
+ drain_pending_emits(&mut emit_rx)
+ };
+ if dropped > 0 {
+ log::warn!("[socket] Dropped {dropped} queued emit(s) on disconnect");
+ }
// The connection attempt has ended (lost, failed, or shutdown), so any
// in-flight `emit_with_ack` waiter can never receive its ACK now. Cancel
@@ -174,18 +191,6 @@ pub(super) async fn ws_loop(
shared.ack_registry.cancel_all();
super::medulla::workflows::end_connection_generation();
- // Backstop for anything that was already queued when the connection
- // ended. `emit_rx` is owned by this loop, not by the connection, so
- // without this a message sitting in the channel is flushed onto the
- // *next* socket — a different sid, whose roster the backend has already
- // cleared. The per-handler guard in `event_handlers` closes the common
- // case; this covers the window between an emit being queued and the
- // generation being cancelled.
- let dropped = drain_pending_emits(&mut emit_rx);
- if dropped > 0 {
- log::warn!("[socket] Dropped {dropped} queued emit(s) on disconnect");
- }
-
match outcome {
ConnectionOutcome::Shutdown => {
log::info!("[socket] Clean shutdown");
@@ -460,7 +465,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,
+ emit_ready: &Mutex<bool>,
) -> ConnectionOutcome {
log::info!("[socket] WS URL: {}", ws_url);
@@ -534,7 +539,7 @@ async fn run_connection(
// 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_ready.lock() = true;
emit_state_change(shared);
// 7. Main event loop
diff --git a/src/openhuman/platform/socket/ws_loop_tests.rs b/src/openhuman/platform/socket/ws_loop_tests.rs
index 68d5fa92ed..d85a28c7da 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::{AtomicBool, AtomicUsize, Ordering};
+use parking_lot::{Mutex, RwLock};
+use std::sync::atomic::{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.rs
index 6d5e387a20..cfd6fd8377 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,7 +418,7 @@ async fn ws_loop_completes_handshake_and_shuts_down_cleanly() {
emit_rx,
shutdown_rx,
internal_tx,
- Arc::new(AtomicBool::new(false)),
+ Arc::new(Mutex::new(false)),
)
.await;
});
@@ -477,7 +477,7 @@ async fn ws_loop_handles_connect_error_and_shutdown() {
emit_rx,
shutdown_rx,
internal_tx,
- Arc::new(AtomicBool::new(false)),
+ Arc::new(Mutex::new(false)),
)
.await;
});
@@ -512,7 +512,7 @@ async fn ws_loop_handles_bad_eio_open_and_shutdown() {
emit_rx,
shutdown_rx,
internal_tx,
- Arc::new(AtomicBool::new(false)),
+ Arc::new(Mutex::new(false)),
)
.await;
});
@@ -568,7 +568,7 @@ async fn ws_loop_refuses_to_start_with_empty_token() {
emit_rx,
shutdown_rx,
internal_tx,
- Arc::new(AtomicBool::new(false)),
+ Arc::new(Mutex::new(false)),
)
.await;
});
@@ -605,7 +605,7 @@ async fn ws_loop_exits_cleanly_when_provider_returns_error() {
emit_rx,
shutdown_rx,
internal_tx,
- Arc::new(AtomicBool::new(false)),
+ Arc::new(Mutex::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.rs
index f6dc3b18a4..daf12ecf32 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,7 +33,7 @@ async fn ws_loop_follows_301_to_working_backend() {
emit_rx,
shutdown_rx,
internal_tx,
- Arc::new(AtomicBool::new(false)),
+ Arc::new(Mutex::new(false)),
)
.await;
});
@@ -147,7 +147,7 @@ async fn ws_loop_calls_provider_before_each_attempt() {
emit_rx,
shutdown_rx,
internal_tx,
- Arc::new(AtomicBool::new(false)),
+ Arc::new(Mutex::new(false)),
)
.await;
});
@@ -203,7 +203,7 @@ async fn ws_loop_escalates_immediately_on_invalid_token_no_refresh() {
emit_rx,
shutdown_rx,
internal_tx,
- Arc::new(AtomicBool::new(false)),
+ Arc::new(Mutex::new(false)),
)
.await;
});
@@ -273,7 +273,7 @@ async fn ws_loop_retries_with_fresh_token_on_invalid_token() {
emit_rx,
shutdown_rx,
internal_tx,
- Arc::new(AtomicBool::new(false)),
+ Arc::new(Mutex::new(false)),
)
.await;
});
@@ -362,7 +362,7 @@ async fn ws_loop_bounds_fresh_token_retries_with_rotating_provider() {
emit_rx,
shutdown_rx,
internal_tx,
- Arc::new(AtomicBool::new(false)),
+ Arc::new(Mutex::new(false)),
)
.await;
});