feat(exec-server): use selective ACK bits

This commit is contained in:
Anton Panasenko
2026-07-07 17:23:50 -07:00
parent e99be8cf65
commit f666e10042
10 changed files with 393 additions and 98 deletions
+8 -8
View File
@@ -61,7 +61,7 @@ version
stream_id
body // handshake | data | ack_frame | resume | reset | heartbeat
ack // highest contiguous peer segment seq received; 0 means none
ack_bits // reserved in v1; must be 0
ack_bits // bit i acknowledges peer seq = ack + 1 + i
seq // data only: segment sequence number
segment_index // data only: 0-based index within message
segment_count // data only: number of segments in message
@@ -99,19 +99,19 @@ segment_count = 1
unsplit messages, `message_start_seq == seq`, `segment_index == 0`, and
`segment_count == 1`.
V1 uses cumulative `ack` and reserves `ack_bits` for a later selective-ack
extension:
V1 uses cumulative `ack` plus a fixed-width selective acknowledgement mask:
```text
ack = 0 when no segment has been received contiguously
ack = highest contiguous received segment seq otherwise
ack_bits = 0
bit i in ack_bits acknowledges seq = ack + 1 + i
```
Send `ack` and zero `ack_bits` redundantly on every outbound frame. Acks are
not themselves acked. Acks, retries, duplicate suppression, segmentation, and
reassembly are endpoint responsibilities; rendezvous only routes relay frames
by `stream_id`.
The 32-segment receive window uses `u32 ack_bits`.
Bit zero is canonically clear because receiving `ack + 1` advances the cumulative `ack`.
Send `ack` and `ack_bits` redundantly on every outbound frame.
Acks are not themselves acked.
Acks, retries, duplicate suppression, segmentation, and reassembly are endpoint responsibilities; rendezvous only routes relay frames by `stream_id`.
## Lifecycle
@@ -6,8 +6,6 @@
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicU32;
use std::sync::atomic::Ordering;
use std::time::Duration;
use tokio::sync::Notify;
@@ -29,6 +27,7 @@ use crate::noise_relay::ordered_ciphertext::OrderedCiphertextFrames;
use crate::noise_relay::reliable_stream::MAX_UNACKED_BYTES;
use crate::noise_relay::reliable_stream::MAX_UNACKED_SEGMENTS;
use crate::noise_relay::reliable_stream::ReliableSender;
use crate::relay::RelayAckState;
use crate::relay::encode_relay_message_frame;
use crate::relay_proto::RelayData;
use crate::relay_proto::RelayMessageFrame;
@@ -48,6 +47,12 @@ pub(crate) struct ClosedNoiseVirtualStream {
pub(crate) instance_id: u64,
}
#[derive(Default)]
struct InboundAckState {
latest: RelayAckState,
pending: Option<RelayAckState>,
}
/// One authenticated JSON-RPC stream carried by the executor's physical relay.
///
/// Inbound delivery is intentionally nonblocking. An overloaded or abandoned
@@ -58,8 +63,7 @@ pub(crate) struct NoiseVirtualStream {
disconnected_tx: watch::Sender<bool>,
transport: Arc<Mutex<NoiseTransport>>,
reliable_sender: Arc<Mutex<ReliableSender>>,
inbound_ack: Arc<AtomicU32>,
pending_ack: Arc<Mutex<Option<u32>>>,
inbound_ack_state: Arc<Mutex<InboundAckState>>,
writer_wakeup: Arc<Notify>,
inbound_ciphertexts: OrderedCiphertextFrames,
inbound_decoder: JsonRpcMessageDecoder,
@@ -75,13 +79,13 @@ impl NoiseVirtualStream {
}
/// Apply ack metadata from one post-handshake peer frame and wake the
/// writer if the cumulative prefix opened send-window capacity.
pub(crate) fn process_peer_ack(&self, ack: u32, ack_bits: u32) -> Result<(), ExecServerError> {
/// writer if it opened sequence or byte send capacity.
pub(crate) fn process_peer_ack(&self, ack_state: RelayAckState) -> Result<(), ExecServerError> {
let mut reliable_sender = self
.reliable_sender
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
reliable_sender.process_peer_ack(ack, ack_bits)?;
reliable_sender.process_peer_ack(ack_state)?;
drop(reliable_sender);
self.writer_wakeup.notify_one();
Ok(())
@@ -110,12 +114,14 @@ impl NoiseVirtualStream {
})?;
}
}
let ack = self.inbound_ciphertexts.cumulative_ack();
self.inbound_ack.store(ack, Ordering::Relaxed);
*self
.pending_ack
let ack_state = self.inbound_ciphertexts.ack_state();
let mut inbound_ack_state = self
.inbound_ack_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(ack);
.unwrap_or_else(std::sync::PoisonError::into_inner);
inbound_ack_state.latest = ack_state;
inbound_ack_state.pending = Some(ack_state);
drop(inbound_ack_state);
self.writer_wakeup.notify_one();
Ok(())
}
@@ -138,13 +144,11 @@ pub(crate) fn spawn_noise_virtual_stream(
let (disconnected_tx, disconnected_rx) = watch::channel(false);
let transport = Arc::new(Mutex::new(transport));
let reliable_sender = Arc::new(Mutex::new(ReliableSender::default()));
let inbound_ack = Arc::new(AtomicU32::new(0));
let pending_ack = Arc::new(Mutex::new(None));
let inbound_ack_state = Arc::new(Mutex::new(InboundAckState::default()));
let writer_wakeup = Arc::new(Notify::new());
let writer_transport = Arc::clone(&transport);
let writer_reliable_sender = Arc::clone(&reliable_sender);
let writer_inbound_ack = Arc::clone(&inbound_ack);
let writer_pending_ack = Arc::clone(&pending_ack);
let writer_inbound_ack_state = Arc::clone(&inbound_ack_state);
let writer_wakeup_task = Arc::clone(&writer_wakeup);
let writer_physical_outgoing_tx = physical_outgoing_tx;
let processor_stream_id = stream_id.clone();
@@ -163,9 +167,10 @@ pub(crate) fn spawn_noise_virtual_stream(
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.can_admit_ciphertext(MAX_RELIABLE_CIPHERTEXT_BYTES);
let has_pending_ack = writer_pending_ack
let has_pending_ack = writer_inbound_ack_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.pending
.is_some();
tokio::select! {
maybe_message = json_outgoing_rx.recv(), if pending_outbound.is_none() => {
@@ -205,11 +210,11 @@ pub(crate) fn spawn_noise_virtual_stream(
}
(ciphertext, next_offset, next_offset == framed.len())
};
let (outbound, ack) = {
let outbound = {
let mut reliable_sender = writer_reliable_sender
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let outbound = match reliable_sender
match reliable_sender
.admit_ciphertext(ciphertext, tokio::time::Instant::now())
{
Ok(outbound) => outbound,
@@ -217,12 +222,15 @@ pub(crate) fn spawn_noise_virtual_stream(
warn!("failed to admit Noise reliable ciphertext: {error}");
break 'writer;
}
};
(outbound, writer_inbound_ack.load(Ordering::Relaxed))
}
};
let ack_state = writer_inbound_ack_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.latest;
let frame = RelayMessageFrame::reliable_data(
writer_stream_id.clone(),
ack,
ack_state,
outbound.seq,
outbound.payload,
);
@@ -240,17 +248,20 @@ pub(crate) fn spawn_noise_virtual_stream(
}
}
_ = retry_tick.tick() => {
let (retry, ack) = {
let retry = {
let mut reliable_sender = writer_reliable_sender
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let retry = reliable_sender.next_retry_due(tokio::time::Instant::now());
(retry, writer_inbound_ack.load(Ordering::Relaxed))
reliable_sender.next_retry_due(tokio::time::Instant::now())
};
if let Some(outbound) = retry {
let ack_state = writer_inbound_ack_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.latest;
let frame = RelayMessageFrame::reliable_data(
writer_stream_id.clone(),
ack,
ack_state,
outbound.seq,
outbound.payload,
);
@@ -264,14 +275,15 @@ pub(crate) fn spawn_noise_virtual_stream(
}
}
_ = std::future::ready(()), if has_pending_ack => {
let ack = writer_pending_ack
let ack_state = writer_inbound_ack_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.pending
.take();
let Some(ack) = ack else {
let Some(ack_state) = ack_state else {
continue;
};
let frame = RelayMessageFrame::ack(writer_stream_id.clone(), ack);
let frame = RelayMessageFrame::ack(writer_stream_id.clone(), ack_state);
if writer_physical_outgoing_tx
.send(encode_relay_message_frame(&frame))
.await
@@ -319,8 +331,7 @@ pub(crate) fn spawn_noise_virtual_stream(
disconnected_tx,
transport,
reliable_sender,
inbound_ack,
pending_ack,
inbound_ack_state,
writer_wakeup,
inbound_ciphertexts: OrderedCiphertextFrames::default(),
inbound_decoder: JsonRpcMessageDecoder::default(),
@@ -1,4 +1,3 @@
use std::sync::atomic::Ordering;
use std::time::Duration;
use anyhow::Result;
@@ -17,6 +16,7 @@ use crate::noise_channel::NoiseChannelIdentity;
use crate::noise_channel::NoiseTransport;
use crate::noise_channel::PendingResponderHandshake;
use crate::noise_relay::message_framing::frame_jsonrpc_message;
use crate::relay::RelayAckState;
use crate::relay::RelayFrameBodyKind;
use crate::relay::decode_relay_message_frame;
use crate::relay_proto::RelayData;
@@ -85,22 +85,59 @@ async fn full_physical_queue_defers_ack_without_resetting_stream() -> Result<()>
result: serde_json::Value::Null,
});
let framed = frame_jsonrpc_message(&message)?;
let ciphertext = harness_transport.encrypt(&framed[..1])?;
let first_ciphertext = harness_transport.encrypt(&framed[..1])?;
let second_ciphertext = harness_transport.encrypt(&framed[1..2])?;
stream.receive_data(RelayData {
seq: 1,
seq: 2,
segment_index: 0,
segment_count: 1,
payload: ciphertext,
payload: second_ciphertext,
})?;
assert_eq!(stream.inbound_ack.load(Ordering::Relaxed), 1);
assert_eq!(
stream
.inbound_ack_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.latest,
RelayAckState {
ack: 0,
ack_bits: 0b10,
}
);
assert_eq!(physical_outgoing_rx.try_recv()?, vec![0x5a]);
let ack = timeout(Duration::from_secs(1), physical_outgoing_rx.recv())
.await?
.expect("virtual stream writer should send the deferred ack");
let ack = decode_relay_message_frame(&ack)?;
assert_eq!(ack.validate()?, RelayFrameBodyKind::Ack);
assert_eq!(ack.ack, 1);
assert_eq!(ack.ack, 0);
assert_eq!(ack.ack_bits, 0b10);
stream.receive_data(RelayData {
seq: 1,
segment_index: 0,
segment_count: 1,
payload: first_ciphertext,
})?;
assert_eq!(
stream
.inbound_ack_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.latest,
RelayAckState {
ack: 2,
ack_bits: 0,
}
);
let ack = timeout(Duration::from_secs(1), physical_outgoing_rx.recv())
.await?
.expect("virtual stream writer should send the cumulative ack");
let ack = decode_relay_message_frame(&ack)?;
assert_eq!(ack.validate()?, RelayFrameBodyKind::Ack);
assert_eq!(ack.ack, 2);
assert_eq!(ack.ack_bits, 0);
Ok(())
}
@@ -395,7 +395,7 @@ where
};
let frame = RelayMessageFrame::reliable_data(
stream_id.clone(),
inbound_ciphertexts.cumulative_ack(),
inbound_ciphertexts.ack_state(),
outbound.seq,
outbound.payload,
);
@@ -423,7 +423,7 @@ where
if let Some(outbound) = reliable_sender.next_retry_due(tokio::time::Instant::now()) {
let frame = RelayMessageFrame::reliable_data(
stream_id.clone(),
inbound_ciphertexts.cumulative_ack(),
inbound_ciphertexts.ack_state(),
outbound.seq,
outbound.payload,
);
@@ -440,10 +440,10 @@ where
}
}
_ = std::future::ready(()), if pending_ack.is_some() && !force_incoming && !pong_deadline_expired => {
let Some(ack) = pending_ack.take() else {
let Some(ack_state) = pending_ack.take() else {
continue;
};
let frame = RelayMessageFrame::ack(stream_id.clone(), ack);
let frame = RelayMessageFrame::ack(stream_id.clone(), ack_state);
if let Err(error) = send_websocket_message(
&mut websocket,
Message::Binary(encode_relay_message_frame(&frame).into()),
@@ -506,7 +506,7 @@ where
};
if !matches!(kind, RelayFrameBodyKind::Handshake)
&& let Err(error) =
reliable_sender.process_peer_ack(frame.ack, frame.ack_bits)
reliable_sender.process_peer_ack(frame.ack_state())
{
send_malformed(&incoming_tx, error.to_string());
break;
@@ -536,7 +536,7 @@ where
send_malformed(&incoming_tx, error.to_string());
break;
}
pending_ack = Some(inbound_ciphertexts.cumulative_ack());
pending_ack = Some(inbound_ciphertexts.ack_state());
}
RelayFrameBodyKind::Reset => {
let _ = incoming_tx.try_send(
@@ -31,6 +31,7 @@ use crate::connection::JsonRpcConnectionEvent;
use crate::noise_channel::NoiseTransport;
use crate::noise_channel::PendingResponderHandshake;
use crate::noise_relay::reliable_stream::RESEND_AFTER;
use crate::relay::RelayAckState;
const ENVIRONMENT_ID: &str = "environment-1";
const EXECUTOR_REGISTRATION_ID: &str = "registration-1";
@@ -111,7 +112,14 @@ async fn dropped_data_is_retried_with_identical_ciphertext_until_cumulative_ack(
drain_outbound_control(&mut outbound_rx, &control).await?;
control.send_inbound(Message::Binary(
encode_relay_message_frame(&RelayMessageFrame::ack(stream_id, /*ack*/ 1)).into(),
encode_relay_message_frame(&RelayMessageFrame::ack(
stream_id,
RelayAckState {
ack: 1,
ack_bits: 0,
},
))
.into(),
))?;
tokio::task::yield_now().await;
drain_outbound_control(&mut outbound_rx, &control).await?;
@@ -144,8 +152,15 @@ async fn queued_pong_is_drained_before_deferred_ack_write() -> Result<()> {
result: serde_json::Value::Null,
}))?;
let ciphertext = executor_transport.encrypt(&framed[..1])?;
let data =
RelayMessageFrame::reliable_data(stream_id, /*ack*/ 0, /*seq*/ 1, ciphertext);
let data = RelayMessageFrame::reliable_data(
stream_id,
RelayAckState {
ack: 0,
ack_bits: 0,
},
/*seq*/ 2,
ciphertext,
);
control.send_inbound(Message::Binary(encode_relay_message_frame(&data).into()))?;
control.send_inbound(Message::Pong(ping_payload))?;
@@ -170,7 +185,8 @@ async fn queued_pong_is_drained_before_deferred_ack_write() -> Result<()> {
};
let ack = decode_relay_message_frame(ack_payload.as_ref())?;
assert_eq!(ack.validate()?, RelayFrameBodyKind::Ack);
assert_eq!(ack.ack, 1);
assert_eq!(ack.ack, 0);
assert_eq!(ack.ack_bits, 0b10);
for task in &connection.task_handles {
task.abort();
}
@@ -1,6 +1,7 @@
use std::collections::BTreeMap;
use crate::ExecServerError;
use crate::relay::RelayAckState;
// A receive window of 32 includes the next expected sequence itself, so only
// 31 later records can wait behind one gap.
@@ -27,9 +28,20 @@ impl Default for OrderedCiphertextFrames {
}
impl OrderedCiphertextFrames {
/// Highest contiguous sequence released for decryption.
pub(crate) fn cumulative_ack(&self) -> u32 {
self.next_seq - 1
/// Current cumulative/selective acknowledgement state.
///
/// Pending ciphertexts are always later than `next_seq` and bounded to
/// the 32-record receive window, so they map directly to bits 1..31.
pub(crate) fn ack_state(&self) -> RelayAckState {
let ack_bits = self.pending.keys().fold(0, |ack_bits, seq| {
let bit = seq - self.next_seq;
debug_assert!(bit < u32::BITS);
ack_bits | (1u32 << bit)
});
RelayAckState {
ack: self.next_seq - 1,
ack_bits,
}
}
/// Accept one relay record and return the newly contiguous ciphertext run.
@@ -2,6 +2,7 @@ use pretty_assertions::assert_eq;
use super::MAX_PENDING_BYTES;
use super::OrderedCiphertextFrames;
use crate::relay::RelayAckState;
#[test]
fn releases_ciphertexts_only_in_nonce_order() {
@@ -11,12 +12,24 @@ fn releases_ciphertexts_only_in_nonce_order() {
frames.push(/*seq*/ 2, b"second".to_vec()).unwrap(),
Vec::<Vec<u8>>::new()
);
assert_eq!(frames.cumulative_ack(), 0);
assert_eq!(
frames.ack_state(),
RelayAckState {
ack: 0,
ack_bits: 0b10,
}
);
assert_eq!(
frames.push(/*seq*/ 1, b"first".to_vec()).unwrap(),
vec![b"first".to_vec(), b"second".to_vec()]
);
assert_eq!(frames.cumulative_ack(), 2);
assert_eq!(
frames.ack_state(),
RelayAckState {
ack: 2,
ack_bits: 0,
}
);
}
#[test]
@@ -31,6 +44,13 @@ fn ignores_duplicate_ciphertexts_without_replacing_buffered_record() {
frames.push(/*seq*/ 2, b"replacement".to_vec()).unwrap(),
Vec::<Vec<u8>>::new()
);
assert_eq!(
frames.ack_state(),
RelayAckState {
ack: 0,
ack_bits: 0b10,
}
);
assert_eq!(
frames.push(/*seq*/ 1, b"one".to_vec()).unwrap(),
vec![b"one".to_vec(), b"first copy".to_vec()]
@@ -41,6 +61,51 @@ fn ignores_duplicate_ciphertexts_without_replacing_buffered_record() {
);
}
#[test]
fn selective_ack_bits_shift_after_a_gap_closes() {
let mut frames = OrderedCiphertextFrames::default();
assert_eq!(
frames.push(/*seq*/ 2, b"two".to_vec()).unwrap(),
Vec::<Vec<u8>>::new()
);
assert_eq!(
frames.push(/*seq*/ 4, b"four".to_vec()).unwrap(),
Vec::<Vec<u8>>::new()
);
assert_eq!(
frames.ack_state(),
RelayAckState {
ack: 0,
ack_bits: 0b1010,
}
);
assert_eq!(
frames.push(/*seq*/ 1, b"one".to_vec()).unwrap(),
vec![b"one".to_vec(), b"two".to_vec()]
);
assert_eq!(
frames.ack_state(),
RelayAckState {
ack: 2,
ack_bits: 0b10,
}
);
assert_eq!(
frames.push(/*seq*/ 3, b"three".to_vec()).unwrap(),
vec![b"three".to_vec(), b"four".to_vec()]
);
assert_eq!(
frames.ack_state(),
RelayAckState {
ack: 4,
ack_bits: 0,
}
);
}
#[test]
fn rejects_unbounded_reordering() {
let mut frames = OrderedCiphertextFrames::default();
@@ -61,5 +126,11 @@ fn buffers_the_full_receive_window_behind_one_gap() {
for seq in 2..=32 {
assert!(frames.push(seq, vec![0; 64 * 1024]).is_ok());
}
assert_eq!(frames.cumulative_ack(), 0);
assert_eq!(
frames.ack_state(),
RelayAckState {
ack: 0,
ack_bits: u32::MAX - 1,
}
);
}
@@ -4,12 +4,11 @@ use std::time::Duration;
use tokio::time::Instant;
use crate::ExecServerError;
use crate::relay::RelayAckState;
/// Maximum number of encrypted records retained until the peer cumulatively
/// acknowledges them.
/// Maximum number of encrypted records retained awaiting peer acknowledgement.
pub(crate) const MAX_UNACKED_SEGMENTS: usize = 32;
/// Maximum encrypted bytes retained until the peer cumulatively acknowledges
/// them.
/// Maximum encrypted bytes retained awaiting peer acknowledgement.
pub(crate) const MAX_UNACKED_BYTES: usize = 2 * 1024 * 1024;
/// How long an encrypted record may remain unacknowledged before it is retried.
pub(crate) const RESEND_AFTER: Duration = Duration::from_millis(500);
@@ -34,12 +33,13 @@ struct UnackedCiphertext {
///
/// The receive frontier stays in `OrderedCiphertextFrames`, which already owns
/// the bounded reorder buffer needed before Noise decryption. This type only
/// allocates send sequences, applies peer cumulative acks, and retains exact
/// ciphertext for retries.
/// allocates send sequences, applies peer acknowledgement state, and retains
/// exact ciphertext for retries.
#[derive(Debug)]
pub(crate) struct ReliableSender {
next_seq: u32,
highest_sent_seq: u32,
peer_cumulative_ack: u32,
resend_cursor: u32,
unacked: BTreeMap<u32, UnackedCiphertext>,
unacked_bytes: usize,
@@ -52,6 +52,7 @@ impl Default for ReliableSender {
// nothing has been received contiguously yet.
next_seq: 1,
highest_sent_seq: 0,
peer_cumulative_ack: 0,
resend_cursor: 1,
unacked: BTreeMap::new(),
unacked_bytes: 0,
@@ -60,6 +61,12 @@ impl Default for ReliableSender {
}
impl ReliableSender {
fn send_window_has_space(&self) -> bool {
self.next_seq
.checked_sub(self.peer_cumulative_ack)
.is_some_and(|span| span <= MAX_UNACKED_SEGMENTS as u32)
}
/// Whether one newly encrypted payload can be retained in the send window.
///
/// Callers must check this before consuming another Noise send nonce.
@@ -67,6 +74,7 @@ impl ReliableSender {
ciphertext_len > 0
&& ciphertext_len <= MAX_UNACKED_BYTES
&& self.unacked.len() < MAX_UNACKED_SEGMENTS
&& self.send_window_has_space()
&& self
.unacked_bytes
.checked_add(ciphertext_len)
@@ -95,6 +103,11 @@ impl ReliableSender {
"Noise reliable segment send window is full".to_string(),
));
}
if !self.send_window_has_space() {
return Err(ExecServerError::Protocol(
"Noise reliable cumulative send window is full".to_string(),
));
}
let unacked_bytes = self
.unacked_bytes
.checked_add(payload.len())
@@ -118,36 +131,57 @@ impl ReliableSender {
Ok(OutboundCiphertext { seq, payload })
}
/// Apply cumulative peer acknowledgement metadata.
/// Apply cumulative and selective peer acknowledgement metadata.
///
/// ack = 0 is the reserved empty state. PR1 rejects nonzero selective bits
/// so they cannot silently alter delivery semantics before PR2.
/// Selective acknowledgement frees cached ciphertext for retry and byte
/// accounting, but only the cumulative frontier slides the sequence window.
pub(crate) fn process_peer_ack(
&mut self,
ack: u32,
ack_bits: u32,
ack_state: RelayAckState,
) -> Result<(), ExecServerError> {
if ack_bits != 0 {
return Err(ExecServerError::Protocol(format!(
"Noise reliable selective ack bits are unsupported in PR1: {ack_bits}"
)));
}
if ack == 0 {
return Ok(());
}
let RelayAckState { ack, ack_bits } = ack_state;
if ack > self.highest_sent_seq {
return Err(ExecServerError::Protocol(format!(
"Noise reliable peer ack {ack} exceeds highest sent sequence {}",
self.highest_sent_seq
)));
}
if ack_bits & 1 != 0 {
return Err(ExecServerError::Protocol(
"Noise reliable selective ack bit zero is inconsistent with cumulative ack"
.to_string(),
));
}
let mut selective_acks = Vec::new();
let mut remaining_ack_bits = ack_bits;
while remaining_ack_bits != 0 {
let bit = remaining_ack_bits.trailing_zeros();
let seq = ack
.checked_add(1)
.and_then(|seq| seq.checked_add(bit))
.ok_or_else(|| {
ExecServerError::Protocol(
"Noise reliable selective ack sequence overflow".to_string(),
)
})?;
if seq > self.highest_sent_seq {
return Err(ExecServerError::Protocol(format!(
"Noise reliable selective ack seq {seq} exceeds highest sent sequence {}",
self.highest_sent_seq
)));
}
selective_acks.push(seq);
remaining_ack_bits &= remaining_ack_bits - 1;
}
self.peer_cumulative_ack = self.peer_cumulative_ack.max(ack);
let acknowledged = self
.unacked
.range(..=ack)
.map(|(seq, _pending)| *seq)
.collect::<Vec<_>>();
for seq in acknowledged {
for seq in acknowledged.into_iter().chain(selective_acks) {
if let Some(pending) = self.unacked.remove(&seq) {
self.unacked_bytes -= pending.payload.len();
}
@@ -8,6 +8,7 @@ use super::MAX_UNACKED_SEGMENTS;
use super::OutboundCiphertext;
use super::RESEND_AFTER;
use super::ReliableSender;
use crate::relay::RelayAckState;
#[test]
fn starts_at_sequence_one() {
@@ -32,29 +33,119 @@ fn cumulative_ack_zero_clears_nothing_and_positive_ack_releases_prefix() {
sender.admit_ciphertext(b"first".to_vec(), now).unwrap();
sender.admit_ciphertext(b"second".to_vec(), now).unwrap();
sender.process_peer_ack(/*ack*/ 0, /*ack_bits*/ 0).unwrap();
sender
.process_peer_ack(RelayAckState {
ack: 0,
ack_bits: 0,
})
.unwrap();
assert_eq!(sender.unacked.len(), 2);
sender.process_peer_ack(/*ack*/ 1, /*ack_bits*/ 0).unwrap();
sender
.process_peer_ack(RelayAckState {
ack: 1,
ack_bits: 0,
})
.unwrap();
assert_eq!(sender.unacked.len(), 1);
assert_eq!(sender.unacked_bytes, b"second".len());
sender.process_peer_ack(/*ack*/ 2, /*ack_bits*/ 0).unwrap();
sender
.process_peer_ack(RelayAckState {
ack: 2,
ack_bits: 0,
})
.unwrap();
assert_eq!(sender.unacked.len(), 0);
assert_eq!(sender.unacked_bytes, 0);
}
#[test]
fn rejects_selective_bits_and_ack_beyond_highest_sent_sequence() {
fn selective_ack_releases_out_of_order_cached_ciphertext() {
let now = Instant::now();
let mut sender = ReliableSender::default();
let first = sender.admit_ciphertext(b"first".to_vec(), now).unwrap();
sender.admit_ciphertext(b"second".to_vec(), now).unwrap();
let third = sender.admit_ciphertext(b"third".to_vec(), now).unwrap();
sender.admit_ciphertext(b"fourth".to_vec(), now).unwrap();
let ack_state = RelayAckState {
ack: 0,
ack_bits: 0b1010,
};
sender.process_peer_ack(ack_state).unwrap();
sender.process_peer_ack(ack_state).unwrap();
assert_eq!(
sender.unacked.keys().copied().collect::<Vec<_>>(),
vec![1, 3]
);
assert_eq!(sender.next_retry_due(now + RESEND_AFTER), Some(first));
assert_eq!(sender.next_retry_due(now + RESEND_AFTER), Some(third));
assert_eq!(sender.next_retry_due(now + RESEND_AFTER), None);
}
#[test]
fn rejects_inconsistent_or_unsent_ack_metadata() {
let now = Instant::now();
let mut sender = ReliableSender::default();
sender
.admit_ciphertext(b"ciphertext".to_vec(), now)
.unwrap();
assert!(sender.process_peer_ack(/*ack*/ 0, /*ack_bits*/ 1).is_err());
assert!(sender.process_peer_ack(/*ack*/ 2, /*ack_bits*/ 0).is_err());
assert!(
sender
.process_peer_ack(RelayAckState {
ack: 0,
ack_bits: 1,
})
.is_err()
);
assert!(
sender
.process_peer_ack(RelayAckState {
ack: 0,
ack_bits: 0b100,
})
.is_err()
);
assert!(
sender
.process_peer_ack(RelayAckState {
ack: 2,
ack_bits: 0,
})
.is_err()
);
assert_eq!(sender.unacked.len(), 1);
}
#[test]
fn selective_acks_do_not_slide_the_cumulative_send_window() {
let now = Instant::now();
let mut sender = ReliableSender::default();
for _ in 0..MAX_UNACKED_SEGMENTS {
sender.admit_ciphertext(vec![0x5a], now).unwrap();
}
sender
.process_peer_ack(RelayAckState {
ack: 0,
ack_bits: u32::MAX - 1,
})
.unwrap();
assert_eq!(sender.unacked.keys().copied().collect::<Vec<_>>(), vec![1]);
assert!(!sender.can_admit_ciphertext(/*ciphertext_len*/ 1));
assert!(sender.admit_ciphertext(vec![0x5a], now).is_err());
sender
.process_peer_ack(RelayAckState {
ack: 1,
ack_bits: 0,
})
.unwrap();
assert!(sender.can_admit_ciphertext(/*ciphertext_len*/ 1));
}
#[test]
fn retries_exact_cached_ciphertext_after_deadline() {
let now = Instant::now();
+34 -11
View File
@@ -87,6 +87,17 @@ pub(crate) enum RelayFrameBodyKind {
Handshake,
}
/// One coherent cumulative/selective acknowledgement snapshot.
///
/// Bit `i` acknowledges sequence `ack + 1 + i`. Reliable Noise endpoints
/// pass this value as one unit so concurrent readers and writers cannot pair a
/// newer cumulative frontier with stale selective bits.
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
pub(crate) struct RelayAckState {
pub(crate) ack: u32,
pub(crate) ack_bits: u32,
}
impl RelayMessageFrame {
pub(crate) fn data(stream_id: String, seq: u32, payload: Vec<u8>) -> Self {
Self {
@@ -103,28 +114,41 @@ impl RelayMessageFrame {
}
}
/// Build one reliable Noise data frame with the receiver's cumulative ack.
/// Build one reliable Noise data frame with the receiver's ack state.
///
/// The legacy plaintext relay still uses [`Self::data`] and keeps its old
/// sequence behavior. Noise reliability owns its own sequence and ack
/// invariants, so keep that policy at the Noise call sites.
pub(crate) fn reliable_data(stream_id: String, ack: u32, seq: u32, payload: Vec<u8>) -> Self {
pub(crate) fn reliable_data(
stream_id: String,
ack_state: RelayAckState,
seq: u32,
payload: Vec<u8>,
) -> Self {
let mut frame = Self::data(stream_id, seq, payload);
frame.ack = ack;
frame.ack = ack_state.ack;
frame.ack_bits = ack_state.ack_bits;
frame
}
/// Build an unsequenced cumulative acknowledgement for a reliable stream.
pub(crate) fn ack(stream_id: String, ack: u32) -> Self {
/// Build an unsequenced acknowledgement for a reliable stream.
pub(crate) fn ack(stream_id: String, ack_state: RelayAckState) -> Self {
Self {
version: RELAY_MESSAGE_FRAME_VERSION,
stream_id,
ack,
ack_bits: 0,
ack: ack_state.ack,
ack_bits: ack_state.ack_bits,
body: Some(relay_message_frame::Body::AckFrame(RelayAck {})),
}
}
pub(crate) fn ack_state(&self) -> RelayAckState {
RelayAckState {
ack: self.ack,
ack_bits: self.ack_bits,
}
}
pub(crate) fn resume(stream_id: String) -> Self {
Self {
version: RELAY_MESSAGE_FRAME_VERSION,
@@ -870,8 +894,7 @@ where
});
}
RelayFrameBodyKind::Data => {
let peer_ack = frame.ack;
let peer_ack_bits = frame.ack_bits;
let peer_ack = frame.ack_state();
// Removing pending state also makes any in-flight validation stale.
let Some(stream) = streams.get_mut(&stream_id) else {
let canceled_pending_handshake =
@@ -885,7 +908,7 @@ where
}
continue;
};
if let Err(error) = stream.process_peer_ack(peer_ack, peer_ack_bits) {
if let Err(error) = stream.process_peer_ack(peer_ack) {
warn!("failed to process Noise relay peer ack: {error}");
streams.remove(&stream_id);
retire_noise_stream_id(
@@ -937,7 +960,7 @@ where
| RelayFrameBodyKind::Resume
| RelayFrameBodyKind::Heartbeat => {
if let Some(stream) = streams.get(&stream_id)
&& let Err(error) = stream.process_peer_ack(frame.ack, frame.ack_bits)
&& let Err(error) = stream.process_peer_ack(frame.ack_state())
{
warn!("failed to process Noise relay peer ack: {error}");
streams.remove(&stream_id);