Restore reliable expiry and snapshot compare-exchange to the Rust core

Two capabilities existed only in Odin's vendored forks, which is why the forks
could not be deleted. Both are ported here with tests so Odin can consume
CultLib instead.

cultnet-rs gains reliable send expiry. A reliable packet may now carry a
deadline; past it the packet is dropped instead of retransmitted, and the count
is reported through session and transport stats. Live media tolerates loss but
not lateness -- a frame retransmitted after its moment has passed is worse than
a missing one -- so the media channel takes a 75ms default while state channels
never expire. Handshake packets never expire either: a dropped connect is not a
late frame.

The deadline is fixed when a send is admitted, so time spent waiting in the
backlog spends it exactly as time spent awaiting an acknowledgement does. This
lineage has a queued_reliable backlog that Odin's does not, and a queued packet
promoted after its moment had passed would be as useless as a retransmitted
one. Expiry runs before the window is measured, so an expiring stream is not
refused for a backlog it no longer owns.

cultcache-rs gains compare_exchange_snapshot and a nonblocking
try_compare_exchange_snapshot. CultLib had neither, despite carrying the larger
body -- the two lineages had diverged in both directions. Contention is returned
as data rather than waited on, so the caller keeps retry and scheduling
authority. This is the primitive an admitted-generation CAS needs.

No wire format changes. Expiry is a sender-side policy and compare-exchange is
local storage, so the other four runtimes stay in agreement without matching
these refusals. They are still worth carrying eventually, and the parity ledger
already tracks that this kind of gap does not announce itself.

cultnet-rs: 106 tests. cultcache-rs: 51 tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-04 03:21:01 +02:00
commit bac5be88b9
7 changed files with 408 additions and 16 deletions

View file

@ -284,6 +284,16 @@ pub struct PushAllOptions {
pub soft: bool,
}
/// Result of one nonblocking whole-snapshot compare-and-exchange. Contention is
/// reported rather than waited on, so the caller keeps retry and scheduling
/// authority instead of blocking inside the store.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TryCompareExchangeSnapshotOutcome {
Exchanged,
Mismatch,
LockContended,
}
pub trait CacheBackingStore: Send {
fn pull_all(&self) -> Result<Vec<CultCacheEnvelope>>;
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<()>;
@ -687,6 +697,80 @@ impl SingleFileMessagePackBackingStore {
result
}
/// Replaces the whole snapshot only if it still equals `expected`, waiting
/// for the exclusive lock. Returns false when another writer has moved the
/// snapshot on, which is a lost race rather than an error.
pub fn compare_exchange_snapshot(
&self,
expected: &[CultCacheEnvelope],
replacements: &[CultCacheEnvelope],
) -> Result<bool> {
self.with_exclusive_lock(|| self.compare_exchange_snapshot_unlocked(expected, replacements))
}
/// Makes one nonblocking attempt at the same exchange. Once the lock is
/// held, comparison, validation, ordering and persistence are identical to
/// [`Self::compare_exchange_snapshot`].
pub fn try_compare_exchange_snapshot(
&self,
expected: &[CultCacheEnvelope],
replacements: &[CultCacheEnvelope],
) -> Result<TryCompareExchangeSnapshotOutcome> {
let Some(exchanged) = self.try_with_exclusive_lock(|| {
self.compare_exchange_snapshot_unlocked(expected, replacements)
})?
else {
return Ok(TryCompareExchangeSnapshotOutcome::LockContended);
};
Ok(if exchanged {
TryCompareExchangeSnapshotOutcome::Exchanged
} else {
TryCompareExchangeSnapshotOutcome::Mismatch
})
}
fn compare_exchange_snapshot_unlocked(
&self,
expected: &[CultCacheEnvelope],
replacements: &[CultCacheEnvelope],
) -> Result<bool> {
let current = self.read_all_unlocked()?;
if current != expected {
return Ok(false);
}
let mut replacement_ids = BTreeSet::new();
for replacement in replacements {
if replacement.key.trim().is_empty() || replacement.r#type.trim().is_empty() {
return Err(anyhow!("CultCache snapshot replacement identity is empty"));
}
if !replacement_ids.insert(entry_id(replacement)) {
return Err(anyhow!(
"CultCache snapshot replacement contains a duplicate identity"
));
}
}
let mut ordered = replacements.to_vec();
ordered.sort_by_key(entry_id);
self.write_all_unlocked(&ordered)?;
Ok(true)
}
fn try_with_exclusive_lock<T>(&self, action: impl FnOnce() -> Result<T>) -> Result<Option<T>> {
let lock = self.open_lock_file()?;
match fs2::FileExt::try_lock_exclusive(&lock) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => return Ok(None),
Err(error) => {
return Err(error)
.with_context(|| format!("failed to lock {}", self.lock_path().display()));
}
}
let result = action();
fs2::FileExt::unlock(&lock)
.with_context(|| format!("failed to unlock {}", self.lock_path().display()))?;
result.map(Some)
}
fn open_lock_file(&self) -> Result<File> {
let lock_path = self.lock_path();
if let Some(parent) = lock_path.parent() {
@ -3926,4 +4010,82 @@ mod tests {
assert_eq!(reloaded.get_required::<Settings>("primary")?.theme, "light");
Ok(())
}
fn snapshot_envelope(key: &str, payload: &[u8]) -> CultCacheEnvelope {
CultCacheEnvelope {
key: key.to_string(),
r#type: "snapshot.record".to_string(),
payload: payload.to_vec(),
stored_at: "2026-01-01T00:00:00Z".to_string(),
// The store stamps the schema id from the type on write, so a
// fixture that omits it would not survive its own round trip.
schema_id: Some("snapshot.record".to_string()),
}
}
#[test]
fn snapshot_exchange_commits_only_against_the_observed_snapshot() -> Result<()> {
let temp = tempfile::tempdir()?;
let store = SingleFileMessagePackBackingStore::new(temp.path().join("generation.cc"));
let first = vec![snapshot_envelope("admitted", b"one")];
assert!(store.compare_exchange_snapshot(&[], &first)?);
assert_eq!(store.pull_all_read_only_snapshot()?, first);
// A writer holding a stale view loses the race instead of clobbering it.
let stale = vec![snapshot_envelope("admitted", b"stale")];
assert!(!store.compare_exchange_snapshot(&[], &stale)?);
assert_eq!(store.pull_all_read_only_snapshot()?, first);
let second = vec![snapshot_envelope("admitted", b"two")];
assert!(store.compare_exchange_snapshot(&first, &second)?);
assert_eq!(store.pull_all_read_only_snapshot()?, second);
Ok(())
}
#[test]
fn try_snapshot_exchange_separates_a_lost_race_from_a_commit() -> Result<()> {
let temp = tempfile::tempdir()?;
let store = SingleFileMessagePackBackingStore::new(temp.path().join("generation.cc"));
let first = vec![snapshot_envelope("admitted", b"one")];
assert_eq!(
store.try_compare_exchange_snapshot(&[], &first)?,
TryCompareExchangeSnapshotOutcome::Exchanged
);
assert_eq!(
store.try_compare_exchange_snapshot(&[], &first)?,
TryCompareExchangeSnapshotOutcome::Mismatch,
"a stale expectation is a lost race, not contention"
);
assert_eq!(store.pull_all_read_only_snapshot()?, first);
Ok(())
}
#[test]
fn snapshot_exchange_refuses_replacements_that_cannot_be_addressed() -> Result<()> {
let temp = tempfile::tempdir()?;
let store = SingleFileMessagePackBackingStore::new(temp.path().join("generation.cc"));
assert!(
store
.compare_exchange_snapshot(&[], &[snapshot_envelope(" ", b"one")])
.is_err(),
"an unaddressable record must not reach the store"
);
assert!(
store
.compare_exchange_snapshot(
&[],
&[
snapshot_envelope("admitted", b"one"),
snapshot_envelope("admitted", b"two"),
],
)
.is_err(),
"a duplicate identity would make the snapshot ambiguous"
);
assert_eq!(store.pull_all_read_only_snapshot()?, Vec::new());
Ok(())
}
}

View file

@ -1474,6 +1474,7 @@ impl SchemaMessageSender for RudpSessionSender<'_> {
ordered: true,
sequenced: false,
now_ms: rudp_now_ms(),
reliable_expire_after_ms: None,
},
Some(RUDP_INTEROP_MAX_FRAGMENT_BYTES),
)?;

View file

@ -318,6 +318,7 @@ impl CultMesh {
) -> Result<CultNetRudpSocketTransportConnection> {
let socket = bind_rudp_socket(&options)?;
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
media_reliable_expire_after_ms: None,
runtime_id: runtime_id.into(),
socket,
mode: CultNetRudpSocketMode::Server,
@ -341,6 +342,7 @@ impl CultMesh {
) -> Result<CultNetRudpSocketTransportConnection> {
let socket = bind_rudp_socket(&options)?;
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
media_reliable_expire_after_ms: None,
runtime_id: runtime_id.into(),
socket,
mode: CultNetRudpSocketMode::Client,

View file

@ -33,6 +33,10 @@ const RUDP_FIXED_HEADER_BYTES: usize = 36;
pub const CULTNET_RUDP_DEFAULT_MAX_PAYLOAD_BYTES: usize = 16 * 1024 * 1024;
pub const CULTNET_RUDP_RELIABLE_SEND_WINDOW_PACKETS: usize = 32;
const RUDP_RECEIVED_SEQUENCE_WINDOW: usize = 4_096;
/// Live media tolerates loss but not lateness: a frame retransmitted after this
/// long describes a moment that has already passed. State channels never
/// expire, so this default applies only to the media channel.
const DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS: u64 = 75;
/// A peer chooses its own channel ids and its own send order, so the per-channel
/// maps and the out-of-order hold buffer are both attacker-sized unless capped.
const RUDP_MAX_TRACKED_CHANNELS: usize = 64;
@ -114,6 +118,11 @@ pub struct CultNetRudpSendOptions {
pub ordered: bool,
pub sequenced: bool,
pub now_ms: u64,
/// Drop a reliable packet instead of retransmitting it once this many
/// milliseconds have passed since the send call. `None` retransmits until
/// acknowledged, which is correct for state and wrong for live media, where
/// a late frame is worse than a missing one.
pub reliable_expire_after_ms: Option<u64>,
}
/// Identifies every transport packet belonging to one non-expiring reliable
@ -142,6 +151,7 @@ pub enum CultNetRudpReliableSendStatus {
struct PendingReliablePacket {
packet: CultNetRudpPacket,
last_sent_at_ms: u64,
expires_at_ms: Option<u64>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@ -176,7 +186,8 @@ pub struct CultNetRudpSession {
received_sequences: BTreeSet<u32>,
latest_sequenced_by_channel: BTreeMap<String, u32>,
pending_reliable: BTreeMap<u32, PendingReliablePacket>,
queued_reliable: VecDeque<CultNetRudpPacket>,
queued_reliable: VecDeque<(CultNetRudpPacket, Option<u64>)>,
reliable_packets_expired: u64,
ordered_next_sequence_by_channel: BTreeMap<String, u32>,
ordered_buffers: BTreeMap<String, BTreeMap<u32, PendingOrderedFrame>>,
fragment_buffers: BTreeMap<(String, u16), FragmentBuffer>,
@ -202,6 +213,7 @@ impl CultNetRudpSession {
latest_sequenced_by_channel: BTreeMap::new(),
pending_reliable: BTreeMap::new(),
queued_reliable: VecDeque::new(),
reliable_packets_expired: 0,
ordered_next_sequence_by_channel: BTreeMap::new(),
ordered_buffers: BTreeMap::new(),
fragment_buffers: BTreeMap::new(),
@ -229,6 +241,12 @@ impl CultNetRudpSession {
self.pending_reliable.keys().copied().collect()
}
/// Reliable packets dropped by their expiry deadline rather than
/// acknowledged. A rising count means the peer is not keeping up.
pub fn reliable_packets_expired(&self) -> u64 {
self.reliable_packets_expired
}
pub fn queued_reliable_packet_count(&self) -> usize {
self.queued_reliable.len()
}
@ -327,7 +345,7 @@ impl CultNetRudpSession {
true,
false,
);
self.track_reliable(packet.clone(), now_ms);
self.track_reliable(packet.clone(), now_ms, None);
Ok(packet)
}
@ -357,7 +375,7 @@ impl CultNetRudpSession {
true,
false,
);
self.track_reliable(response.clone(), now_ms);
self.track_reliable(response.clone(), now_ms, None);
Ok(response)
}
@ -396,6 +414,12 @@ impl CultNetRudpSession {
return Err(anyhow!("RUDP ordered delivery requires reliability"));
}
self.require_payload_size(payload.len())?;
// Reclaim deadline-passed sends before measuring window capacity, so an
// expiring stream cannot be refused for a backlog it no longer owns.
self.purge_expired_reliable(options.now_ms);
let expires_at_ms = options
.reliable_expire_after_ms
.map(|ttl| options.now_ms.saturating_add(ttl));
if let Some(max_fragment_bytes) = max_fragment_bytes {
if max_fragment_bytes == 0 {
@ -426,7 +450,7 @@ impl CultNetRudpSession {
packets.push(packet);
}
return Ok(if options.reliable {
self.admit_reliable_packets(packets, options.now_ms)
self.admit_reliable_packets(packets, options.now_ms, expires_at_ms)
} else {
packets
});
@ -443,7 +467,7 @@ impl CultNetRudpSession {
options.sequenced,
);
if packet.reliable {
return Ok(self.admit_reliable_packets(vec![packet], options.now_ms));
return Ok(self.admit_reliable_packets(vec![packet], options.now_ms, expires_at_ms));
}
Ok(vec![packet])
}
@ -455,6 +479,7 @@ impl CultNetRudpSession {
) -> Result<CultNetRudpReceiveResult> {
self.require_connection(packet)?;
self.apply_acknowledgements(packet);
self.purge_expired_reliable(now_ms);
let ready_to_send = self.promote_queued_reliable(now_ms);
self.last_received_at_ms = Some(now_ms);
let expected_sequence_if_uninitialized = self
@ -790,30 +815,52 @@ impl CultNetRudpSession {
}
}
fn track_reliable(&mut self, packet: CultNetRudpPacket, now_ms: u64) {
fn track_reliable(
&mut self,
packet: CultNetRudpPacket,
now_ms: u64,
expires_at_ms: Option<u64>,
) {
self.pending_reliable.insert(
packet.sequence,
PendingReliablePacket {
packet,
last_sent_at_ms: now_ms,
expires_at_ms,
},
);
}
/// Drop pending and queued reliable packets past their deadline. The
/// deadline is fixed when the send is admitted, so time spent waiting in
/// the backlog counts against it exactly as time spent awaiting an ACK does.
fn purge_expired_reliable(&mut self, now_ms: u64) {
let before = self.pending_reliable.len() + self.queued_reliable.len();
self.pending_reliable
.retain(|_, pending| pending.expires_at_ms.is_none_or(|at| now_ms <= at));
self.queued_reliable
.retain(|(_, expires_at_ms)| expires_at_ms.is_none_or(|at| now_ms <= at));
let after = self.pending_reliable.len() + self.queued_reliable.len();
self.reliable_packets_expired = self
.reliable_packets_expired
.saturating_add((before - after) as u64);
}
fn admit_reliable_packets(
&mut self,
packets: Vec<CultNetRudpPacket>,
now_ms: u64,
expires_at_ms: Option<u64>,
) -> Vec<CultNetRudpPacket> {
let available =
CULTNET_RUDP_RELIABLE_SEND_WINDOW_PACKETS.saturating_sub(self.pending_reliable.len());
let mut ready = Vec::with_capacity(available.min(packets.len()));
for packet in packets {
if ready.len() < available {
self.track_reliable(packet.clone(), now_ms);
self.track_reliable(packet.clone(), now_ms, expires_at_ms);
ready.push(packet);
} else {
self.queued_reliable.push_back(packet);
self.queued_reliable.push_back((packet, expires_at_ms));
}
}
ready
@ -824,10 +871,10 @@ impl CultNetRudpSession {
CULTNET_RUDP_RELIABLE_SEND_WINDOW_PACKETS.saturating_sub(self.pending_reliable.len());
let mut ready = Vec::with_capacity(available.min(self.queued_reliable.len()));
for _ in 0..available {
let Some(packet) = self.queued_reliable.pop_front() else {
let Some((packet, expires_at_ms)) = self.queued_reliable.pop_front() else {
break;
};
self.track_reliable(packet.clone(), now_ms);
self.track_reliable(packet.clone(), now_ms, expires_at_ms);
ready.push(packet);
}
ready
@ -1162,6 +1209,7 @@ pub struct CultNetRudpSocketTransportOptions {
pub max_fragment_bytes: Option<u32>,
pub max_pending_reliable_packets: Option<u32>,
pub reconnect_policy: Option<CultNetReconnectPolicy>,
pub media_reliable_expire_after_ms: Option<u64>,
}
impl CultNetRudpSocketTransportOptions {
@ -1172,6 +1220,7 @@ impl CultNetRudpSocketTransportOptions {
connection_id: u32,
) -> Self {
Self {
media_reliable_expire_after_ms: Some(DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS),
runtime_id: runtime_id.into(),
socket,
mode: CultNetRudpSocketMode::Client,
@ -1189,6 +1238,7 @@ impl CultNetRudpSocketTransportOptions {
pub fn server(runtime_id: impl Into<String>, socket: UdpSocket, connection_id: u32) -> Self {
Self {
media_reliable_expire_after_ms: Some(DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS),
runtime_id: runtime_id.into(),
socket,
mode: CultNetRudpSocketMode::Server,
@ -1216,6 +1266,7 @@ pub struct CultNetRudpSocketTransportConnection {
max_fragment_bytes: Option<usize>,
disconnect_reason: Option<Vec<u8>>,
pong_payloads: VecDeque<Vec<u8>>,
media_reliable_expire_after_ms: Option<u64>,
}
pub struct CultNetRudpServerHubOptions {
@ -1229,11 +1280,13 @@ pub struct CultNetRudpServerHubOptions {
pub max_fragment_bytes: Option<u32>,
pub max_pending_reliable_packets: Option<u32>,
pub max_peers: usize,
pub media_reliable_expire_after_ms: Option<u64>,
}
impl CultNetRudpServerHubOptions {
pub fn new(runtime_id: impl Into<String>, socket: UdpSocket, connection_id: u32) -> Self {
Self {
media_reliable_expire_after_ms: Some(DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS),
runtime_id: runtime_id.into(),
socket,
connection_id,
@ -1298,6 +1351,7 @@ pub struct CultNetRudpServerHub {
max_payload_bytes: usize,
max_fragment_bytes: Option<usize>,
max_peers: usize,
media_reliable_expire_after_ms: Option<u64>,
next_session_generation: u64,
peers: BTreeMap<SocketAddr, CultNetRudpServerPeer>,
pending_events: VecDeque<CultNetRudpServerEvent>,
@ -1329,6 +1383,7 @@ impl CultNetRudpServerHub {
},
);
Ok(Self {
media_reliable_expire_after_ms: options.media_reliable_expire_after_ms,
socket: options.socket,
connection_id: options.connection_id,
initial_sequence: options.initial_sequence,
@ -1353,7 +1408,13 @@ impl CultNetRudpServerHub {
}
pub fn stats(&self) -> CultNetTransportStats {
self.stats.clone()
let mut stats = self.stats.clone();
stats.reliable_packets_expired = self
.peers
.values()
.map(|peer| peer.session.reliable_packets_expired())
.fold(0_u64, |total, expired| total.saturating_add(expired));
stats
}
pub fn sessions(&self) -> Vec<CultNetRudpServerSessionContext> {
@ -1388,7 +1449,7 @@ impl CultNetRudpServerHub {
peer.session.send_many(
channel_id,
payload,
channel_send_options(channel_id, now_ms()),
channel_send_options(channel_id, now_ms(), self.media_reliable_expire_after_ms),
self.max_fragment_bytes,
)?
};
@ -1627,6 +1688,7 @@ impl CultNetRudpSocketTransportConnection {
});
session.set_max_payload_bytes(max_payload_bytes.map(|value| value as usize));
Ok(Self {
media_reliable_expire_after_ms: options.media_reliable_expire_after_ms,
socket: options.socket,
session,
mode: options.mode,
@ -1645,7 +1707,9 @@ impl CultNetRudpSocketTransportConnection {
}
pub fn stats(&self) -> CultNetTransportStats {
self.stats.clone()
let mut stats = self.stats.clone();
stats.reliable_packets_expired = self.session.reliable_packets_expired();
stats
}
pub fn disconnect_reason(&self) -> Option<&[u8]> {
@ -1667,7 +1731,8 @@ impl CultNetRudpSocketTransportConnection {
}
pub fn send(&mut self, channel_id: &str, payload: Vec<u8>) -> Result<()> {
let options = channel_send_options(channel_id, now_ms());
let options =
channel_send_options(channel_id, now_ms(), self.media_reliable_expire_after_ms);
let packets =
self.session
.send_many(channel_id, payload, options, self.max_fragment_bytes)?;
@ -1683,7 +1748,8 @@ impl CultNetRudpSocketTransportConnection {
channel_id: &str,
payload: Vec<u8>,
) -> Result<CultNetRudpReliableSendReceipt> {
let options = channel_send_options(channel_id, now_ms());
let options =
channel_send_options(channel_id, now_ms(), self.media_reliable_expire_after_ms);
// This lineage has no reliable-expiry concept, so every reliable channel is
// already non-expiring. Restore the expiry half of this guard if one is added.
if !options.reliable {
@ -2158,31 +2224,39 @@ fn packet_type_to_code(packet_type: CultNetRudpPacketType) -> u8 {
}
}
fn channel_send_options(channel_id: &str, now_ms: u64) -> CultNetRudpSendOptions {
fn channel_send_options(
channel_id: &str,
now_ms: u64,
media_reliable_expire_after_ms: Option<u64>,
) -> CultNetRudpSendOptions {
match channel_id {
"schema" => CultNetRudpSendOptions {
reliable: true,
ordered: true,
sequenced: false,
now_ms,
reliable_expire_after_ms: None,
},
"latest" => CultNetRudpSendOptions {
reliable: false,
ordered: false,
sequenced: true,
now_ms,
reliable_expire_after_ms: None,
},
"media" => CultNetRudpSendOptions {
reliable: true,
ordered: false,
sequenced: false,
now_ms,
reliable_expire_after_ms: media_reliable_expire_after_ms,
},
_ => CultNetRudpSendOptions {
reliable: false,
ordered: false,
sequenced: false,
now_ms,
reliable_expire_after_ms: None,
},
}
}

View file

@ -19,6 +19,9 @@ pub struct CultNetTransportStats {
pub bytes_sent: u64,
pub frames_received: u64,
pub frames_sent: u64,
/// Reliable packets dropped by a send-side expiry deadline instead of being
/// retransmitted. Always zero for transports without reliable expiry.
pub reliable_packets_expired: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]

View file

@ -1258,6 +1258,7 @@ fn rudp_socket_transport_handshakes_and_carries_reliable_ordered_schema_frames()
max_fragment_bytes: None,
max_pending_reliable_packets: None,
reconnect_policy: None,
media_reliable_expire_after_ms: None,
})?;
let mut client =
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
@ -1273,6 +1274,7 @@ fn rudp_socket_transport_handshakes_and_carries_reliable_ordered_schema_frames()
max_fragment_bytes: None,
max_pending_reliable_packets: None,
reconnect_policy: None,
media_reliable_expire_after_ms: None,
})?;
client.connect(b"join".to_vec())?;
@ -1348,6 +1350,7 @@ fn rudp_socket_transport_carries_fragmented_reliable_ordered_schema_frames() ->
max_fragment_bytes: Some(8),
max_pending_reliable_packets: None,
reconnect_policy: None,
media_reliable_expire_after_ms: None,
})?;
let mut client =
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
@ -1363,6 +1366,7 @@ fn rudp_socket_transport_carries_fragmented_reliable_ordered_schema_frames() ->
max_fragment_bytes: Some(8),
max_pending_reliable_packets: None,
reconnect_policy: None,
media_reliable_expire_after_ms: None,
})?;
client.connect(b"join".to_vec())?;
@ -1476,6 +1480,7 @@ fn rudp_socket_flush_waits_for_large_fragment_delivery() -> Result<()> {
max_fragment_bytes: Some(8),
max_pending_reliable_packets: None,
reconnect_policy: None,
media_reliable_expire_after_ms: None,
})?;
let mut client =
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
@ -1491,6 +1496,7 @@ fn rudp_socket_flush_waits_for_large_fragment_delivery() -> Result<()> {
max_fragment_bytes: Some(8),
max_pending_reliable_packets: None,
reconnect_policy: None,
media_reliable_expire_after_ms: None,
})?;
client.connect(b"join".to_vec())?;
pump_rudp_handshake(&mut client, &mut server)?;
@ -2672,3 +2678,142 @@ fn tcp_framed_receive_refuses_a_length_beyond_the_advertised_maximum() -> Result
);
Ok(())
}
#[test]
fn rudp_reliable_expiry_drops_late_packets_and_leaves_durable_sends_alone() -> Result<()> {
let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions {
connection_id: 7,
initial_sequence: 10,
resend_delay_ms: 100,
..CultNetRudpSessionOptions::default()
});
accept_rudp_session(&mut sender, 7)?;
let expiring = sender.send(
"media",
b"late".to_vec(),
CultNetRudpSendOptions {
reliable: true,
now_ms: 0,
reliable_expire_after_ms: Some(50),
..CultNetRudpSendOptions::default()
},
)?;
let durable = sender.send(
"schema",
b"state".to_vec(),
CultNetRudpSendOptions {
reliable: true,
now_ms: 0,
..CultNetRudpSendOptions::default()
},
)?;
assert_eq!(sender.pending_reliable_sequences().len(), 2);
assert_eq!(sender.reliable_packets_expired(), 0);
// One millisecond before the deadline nothing is dropped: the boundary is
// inclusive, so a packet is never discarded early.
sender.send(
"schema",
b"tick".to_vec(),
CultNetRudpSendOptions {
reliable: false,
now_ms: 50,
..CultNetRudpSendOptions::default()
},
)?;
assert_eq!(sender.reliable_packets_expired(), 0);
sender.send(
"schema",
b"tick".to_vec(),
CultNetRudpSendOptions {
reliable: false,
now_ms: 51,
..CultNetRudpSendOptions::default()
},
)?;
assert_eq!(sender.reliable_packets_expired(), 1);
assert_eq!(
sender.pending_reliable_sequences(),
vec![durable.sequence],
"a send without an expiry deadline is never dropped"
);
assert_ne!(expiring.sequence, durable.sequence);
Ok(())
}
#[test]
fn rudp_reliable_expiry_also_reclaims_the_send_backlog() -> Result<()> {
let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions {
connection_id: 9,
initial_sequence: 10,
resend_delay_ms: 100,
..CultNetRudpSessionOptions::default()
});
accept_rudp_session(&mut sender, 9)?;
let fragment_count = CULTNET_RUDP_RELIABLE_SEND_WINDOW_PACKETS + 5;
let payload = (0..fragment_count * 8)
.map(|index| (index % 251) as u8)
.collect::<Vec<_>>();
sender.send_many(
"media",
payload,
CultNetRudpSendOptions {
reliable: true,
now_ms: 0,
reliable_expire_after_ms: Some(30),
..CultNetRudpSendOptions::default()
},
Some(8),
)?;
assert_eq!(
sender.pending_reliable_sequences().len(),
CULTNET_RUDP_RELIABLE_SEND_WINDOW_PACKETS
);
assert_eq!(sender.queued_reliable_packet_count(), 5);
// The deadline is fixed at admission, so waiting in the backlog spends it
// exactly as waiting for an acknowledgement does. A queued packet promoted
// after its moment has passed would be as useless as a retransmitted one.
sender.send(
"schema",
b"tick".to_vec(),
CultNetRudpSendOptions {
reliable: false,
now_ms: 31,
..CultNetRudpSendOptions::default()
},
)?;
assert_eq!(sender.pending_reliable_sequences().len(), 0);
assert_eq!(sender.queued_reliable_packet_count(), 0);
assert_eq!(
sender.reliable_packets_expired(),
fragment_count as u64,
"both the in-flight window and the backlog are counted"
);
Ok(())
}
fn accept_rudp_session(session: &mut CultNetRudpSession, connection_id: u32) -> Result<()> {
session.receive(
&CultNetRudpPacket {
packet_type: CultNetRudpPacketType::Accept,
connection_id,
sequence: 0,
ack: 0,
ack_mask: 0,
channel_id: "control".into(),
reliable: false,
ordered: false,
sequenced: false,
fragment_id: 0,
fragment_index: 0,
fragment_count: 0,
payload: Vec::new(),
},
0,
)?;
Ok(())
}

View file

@ -315,6 +315,7 @@ fn exact_reliable_acks_clear_more_than_one_ack_window_of_fragments() -> Result<(
ordered: true,
sequenced: false,
now_ms: 1,
reliable_expire_after_ms: None,
},
Some(1),
)?;
@ -375,6 +376,7 @@ fn session_and_hub_reject_configured_memory_bounds() -> Result<()> {
ordered: true,
sequenced: false,
now_ms: 1,
reliable_expire_after_ms: None,
},
Some(2),
)?;
@ -387,6 +389,7 @@ fn session_and_hub_reject_configured_memory_bounds() -> Result<()> {
ordered: true,
sequenced: false,
now_ms: 2,
reliable_expire_after_ms: None,
};
let first_set = sender.send_many(
"schema",
@ -446,6 +449,7 @@ fn replay_history_is_bounded_and_idle_hub_sessions_expire() -> Result<()> {
ordered: false,
sequenced: false,
now_ms: sequence,
reliable_expire_after_ms: None,
},
)?;
if oldest.is_none() {
@ -477,6 +481,7 @@ fn replay_history_is_bounded_and_idle_hub_sessions_expire() -> Result<()> {
ordered: false,
sequenced: false,
now_ms: step,
reliable_expire_after_ms: None,
},
)?;
if oldest_reliable.is_none() {