Limit per-stream buffering in the Noise relay (#64540)

## Why

When the shared WebSocket writer stalls, a burst from one stream can fill
the outgoing queue. If a handshake reply arrives while the queue is full,
the relay can disconnect and interrupt existing streams.

## What changed

Allow each stream to queue one data record while the writer flushes the
current frame. Keep data and control frames in the same FIFO to preserve
their order. If the queue is full when a handshake reply is ready, decline
the new stream and keep the connection open so existing streams can drain.

## Testing

Add a regression test that stalls the writer during a burst and verifies
that a second stream's handshake reply arrives after at most two data
records and that the burst drains in order.

GitOrigin-RevId: f0e4225bccb63d021c09718e5c43df3f4c4a6745
This commit is contained in:
alishobeiri-oai
2026-11-29 03:42:13 +00:00
committed by copyberry
parent dfd76bb740
commit 8b2a4a40a9
6 changed files with 159 additions and 22 deletions
@@ -4,8 +4,10 @@
//! `NoiseTransport` because its send and receive nonces live in the same value;
//! the mutex is never held across `.await`.
use crate::relay::OutgoingFrame;
use std::sync::Arc;
use std::sync::Mutex;
use tokio::sync::Semaphore;
use tokio::sync::mpsc;
use tokio::sync::watch;
@@ -90,7 +92,7 @@ pub(crate) fn spawn_noise_virtual_stream<H: NoiseStreamHandler>(
instance: ClosedNoiseVirtualStream,
tasks: Option<&TaskTracker>,
handler: H,
physical_outgoing_tx: mpsc::Sender<Vec<u8>>,
physical_outgoing_tx: mpsc::Sender<OutgoingFrame>,
closed_stream_tx: mpsc::Sender<ClosedNoiseVirtualStream>,
transport: NoiseTransport,
executor_registration: Option<Arc<ExecutorRegistration>>,
@@ -105,6 +107,9 @@ pub(crate) fn spawn_noise_virtual_stream<H: NoiseStreamHandler>(
let owner_closed_stream_tx = closed_stream_tx.clone();
let writer_stream_id = instance.stream_id;
let writer_task = tokio::spawn(async move {
// Queue at most one data record per stream in the shared FIFO.
// The next record can be prepared while the socket flushes this one.
let slot = Arc::new(Semaphore::new(1));
let mut next_seq = 0u32;
'writer: while let Some(message) = outgoing_rx.recv().await {
let message = match H::encode(message) {
@@ -143,11 +148,14 @@ pub(crate) fn spawn_noise_virtual_stream<H: NoiseStreamHandler>(
ciphertext,
trace.take(),
);
if physical_outgoing_tx
.send(encode_relay_message_frame(&frame))
.await
.is_err()
{
let Ok(permit) = Arc::clone(&slot).acquire_owned().await else {
break 'writer;
};
let outgoing = OutgoingFrame {
encoded: encode_relay_message_frame(&frame),
slot: Some(permit),
};
if physical_outgoing_tx.send(outgoing).await.is_err() {
break 'writer;
}
}
@@ -91,7 +91,7 @@ async fn forwards_opaque_noise_payloads_and_drains_before_closing() -> Result<()
tokio::select! {
biased;
Some(encoded) = physical_outgoing_rx.recv() => {
let frame = decode_relay_message_frame(&encoded)?;
let frame = decode_relay_message_frame(&encoded.encoded)?;
assert_eq!(frame.stream_id, "stream-1");
let data = frame.into_data()?;
assert_eq!(data.seq, next_seq);
+21 -11
View File
@@ -54,6 +54,8 @@ use tokio_util::task::TaskTracker;
#[path = "relay_writer.rs"]
mod writer;
pub(crate) use writer::OutgoingFrame;
const RELAY_MESSAGE_FRAME_VERSION: u32 = 1;
const MAX_ACTIVE_NOISE_RELAY_STREAMS: usize = 128;
const MAX_FAILED_NOISE_HANDSHAKES: usize = 8;
@@ -535,7 +537,8 @@ where
ExecutorRegistration::new(environment_id.clone(), executor_registration_id.clone())
.map(Arc::new);
let (websocket_sink, mut websocket_stream) = stream.split();
let (physical_outgoing_tx, physical_outgoing_rx) = mpsc::channel::<Vec<u8>>(CHANNEL_CAPACITY);
let (physical_outgoing_tx, physical_outgoing_rx) =
mpsc::channel::<OutgoingFrame>(CHANNEL_CAPACITY);
let (closed_stream_tx, mut closed_stream_rx) =
mpsc::channel::<ClosedNoiseVirtualStream>(MAX_ACTIVE_NOISE_RELAY_STREAMS);
let (pong_tx, pong_rx) = mpsc::channel(1);
@@ -663,7 +666,7 @@ where
response,
);
let _ = physical_outgoing_tx.try_send(
encode_relay_message_frame(&frame),
OutgoingFrame::control(encode_relay_message_frame(&frame)),
);
} else {
send_reset(&physical_outgoing_tx, validation_result.stream_id);
@@ -703,13 +706,19 @@ where
);
// Do not leave a half-open stream if the handshake reply
// cannot be queued immediately.
if let Err(error) = physical_outgoing_tx.try_send(encode_relay_message_frame(&response)) {
let reason = match error {
mpsc::error::TrySendError::Full(_) => "response_queue_full",
mpsc::error::TrySendError::Closed(_) => "response_queue_closed",
};
record_diagnostic(&validation_result.stream_id, reason, None);
break;
let frame = OutgoingFrame::control(encode_relay_message_frame(&response));
match physical_outgoing_tx.try_send(frame) {
Ok(()) => {}
Err(mpsc::error::TrySendError::Full(_)) => {
// Decline this stream before activation. Existing streams
// can still drain as soon as the socket becomes writable.
record_diagnostic(&validation_result.stream_id, "response_queue_full", None);
continue;
}
Err(mpsc::error::TrySendError::Closed(_)) => {
record_diagnostic(&validation_result.stream_id, "response_queue_closed", None);
break;
}
}
info!(
noise_event = "handshake",
@@ -1100,9 +1109,10 @@ fn classify_harness_key_validation_error(error: &ExecServerError) -> (&'static s
/// Queue a best-effort reset without blocking the shared websocket loop.
/// Reset reasons are relay control data and are not treated as trusted text.
fn send_reset(physical_outgoing_tx: &mpsc::Sender<Vec<u8>>, stream_id: String) {
fn send_reset(physical_outgoing_tx: &mpsc::Sender<OutgoingFrame>, stream_id: String) {
let reset = RelayMessageFrame::reset(stream_id, NOISE_RELAY_RESET_REASON.to_string());
let _ = physical_outgoing_tx.try_send(encode_relay_message_frame(&reset));
let _ =
physical_outgoing_tx.try_send(OutgoingFrame::control(encode_relay_message_frame(&reset)));
}
#[cfg(test)]
@@ -938,3 +938,98 @@ async fn early_data_during_validation_pauses_admission_without_disconnecting() -
);
Ok(())
}
type Harness = WebSocketStream<tokio::io::DuplexStream>;
async fn start_stream(
socket: &mut Harness,
stream: &str,
identity: &NoiseChannelIdentity,
validator: &Notify,
) -> Result<InitiatorHandshake> {
let prologue = noise_channel_prologue(ENVIRONMENT_ID, EXECUTOR_REGISTRATION_ID, stream);
let (handshake, request) = InitiatorHandshake::start(
&NoiseChannelIdentity::generate()?,
&identity.public_key(),
&prologue,
b"authorization",
)?;
validator.notify_one();
let frame = RelayMessageFrame::handshake(stream.to_owned(), request);
socket
.send(Message::Binary(encode_relay_message_frame(&frame).into()))
.await?;
Ok(handshake)
}
#[tokio::test(start_paused = true)]
async fn a_burst_on_one_stream_leaves_room_for_a_new_handshake() -> Result<()> {
// Each echo fits in one Noise record but exceeds the pipe capacity. With
// the reader paused, the first echo stalls in the physical writer.
let (client, server) = tokio::io::duplex(512);
let ((mut socket, _), executor) = tokio::try_join!(
tokio_tungstenite::client_async("ws://localhost", client),
accept_async(server),
)?;
let identity = NoiseChannelIdentity::generate()?;
let release = Arc::new(Notify::new());
let _task = AbortOnDropHandle::new(tokio::spawn(run_multiplexed_environment(
executor,
EchoMessages,
ENVIRONMENT_ID.to_string(),
EXECUTOR_REGISTRATION_ID.to_string(),
identity.clone(),
BlockingValidator {
calls: Arc::new(AtomicUsize::new(0)),
release: release.clone(),
},
/*admission*/ None,
)));
let handshake = start_stream(&mut socket, "busy", &identity, &release).await?;
let mut busy = handshake.finish(
&next_relay_frame(&mut socket)
.await?
.into_handshake_payload()?,
)?;
let payload = frame_jsonrpc_message(&JSONRPCMessage::Response(JSONRPCResponse {
id: RequestId::Integer(1),
result: serde_json::Value::String("x".repeat(1024)),
}))?;
let count = crate::connection::CHANNEL_CAPACITY as u32 + 2;
for seq in 0..count {
let frame = RelayMessageFrame::data(
"busy".to_string(),
seq,
busy.encrypt(&payload)?,
/*trace*/ None,
);
socket
.send(Message::Binary(encode_relay_message_frame(&frame).into()))
.await?;
}
// Advance paused time only after all runnable tasks have yielded on I/O.
tokio::time::sleep(Duration::from_millis(1)).await;
let mut joining = Some(start_stream(&mut socket, "joining", &identity, &release).await?);
tokio::time::sleep(Duration::from_millis(1)).await;
let mut received = 0;
while received < count || joining.is_some() {
let frame = timeout(Duration::from_secs(1), next_relay_frame(&mut socket)).await??;
if frame.stream_id == "joining" {
// At most one record being flushed and one waiting in the FIFO.
assert!(received <= 2, "handshake waited behind {received} records");
joining
.take()
.expect("one handshake")
.finish(&frame.into_handshake_payload()?)?;
} else {
assert_eq!(frame.stream_id, "busy");
let data = frame.into_data()?;
assert_eq!(data.seq, received);
assert_eq!(busy.decrypt(&data.payload)?, payload);
received += 1;
}
}
assert_eq!(received, count);
Ok(())
}
+20 -2
View File
@@ -12,9 +12,26 @@ use crate::relay::RendezvousDisconnectReason;
use crate::websocket_pong_watchdog::WEBSOCKET_PONG_TIMEOUT;
use crate::websocket_pong_watchdog::WebSocketPongWatchdog;
/// Keep the stream's slot until its record reaches the socket writer.
/// Control frames share the FIFO to preserve handshake/data/reset ordering.
#[derive(Debug)]
pub(crate) struct OutgoingFrame {
pub(crate) encoded: Vec<u8>,
pub(crate) slot: Option<tokio::sync::OwnedSemaphorePermit>,
}
impl OutgoingFrame {
pub(super) fn control(encoded: Vec<u8>) -> Self {
Self {
encoded,
slot: None,
}
}
}
pub(super) async fn run<S, E>(
mut sink: S,
mut outgoing_rx: mpsc::Receiver<Vec<u8>>,
mut outgoing_rx: mpsc::Receiver<OutgoingFrame>,
mut pong_rx: mpsc::Receiver<()>,
) -> RendezvousDisconnectReason
where
@@ -39,9 +56,10 @@ where
Message::Ping(Vec::new().into())
}
encoded = outgoing_rx.recv() => {
let Some(encoded) = encoded else {
let Some(OutgoingFrame { encoded, slot }) = encoded else {
return RendezvousDisconnectReason::LocalShutdown;
};
drop(slot);
Message::Binary(encoded.into())
}
};
@@ -34,7 +34,10 @@ async fn pong_during_write_clears_only_the_pong_deadline() {
let task = AbortOnDropHandle::new(tokio::spawn(run(Box::pin(sink), outgoing_rx, pong_rx)));
assert!(matches!(observed_rx.recv().await, Some(Message::Ping(_))));
tokio::time::advance(WEBSOCKET_PONG_TIMEOUT * 3 / 4).await;
outgoing_tx.send(vec![42]).await.unwrap();
outgoing_tx
.send(OutgoingFrame::control(vec![42]))
.await
.unwrap();
assert_eq!(
observed_rx.recv().await,
Some(Message::Binary(vec![42].into()))
@@ -78,7 +81,10 @@ async fn missing_pong_times_out_during_a_blocked_write() {
let task = AbortOnDropHandle::new(tokio::spawn(run(Box::pin(sink), outgoing_rx, pong_rx)));
assert!(matches!(observed_rx.recv().await, Some(Message::Ping(_))));
tokio::time::advance(WEBSOCKET_PONG_TIMEOUT * 3 / 4).await;
outgoing_tx.send(vec![42]).await.unwrap();
outgoing_tx
.send(OutgoingFrame::control(vec![42]))
.await
.unwrap();
assert_eq!(
observed_rx.recv().await,
Some(Message::Binary(vec![42].into()))