cultmesh-rs: server-wide remembered-write budget is a maintained counter; a session whose refusal set overflowed refuses unseen ids after the budget frees
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m35s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m1s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Libby 2026-11-08 16:36:10 +00:00
commit 1a05df2524
2 changed files with 177 additions and 12 deletions

View file

@ -580,6 +580,10 @@ struct SessionEntry {
/// Writes refused `limit_reached`, kept so their resend replays the refusal. A bounded set outside the
/// entry budget (`MAX_REMEMBERED_WRITES_PER_SESSION`); past it a new write is refused unremembered.
limit_refusals: HashMap<[u8; 32], [u8; 32]>,
/// A limit refusal was answered that `limit_refusals` had no room to remember. That id's resend cannot be
/// told from a new write, so the session refuses every id it has not seen for the rest of its life, even once
/// the server-wide budget has freed: an id refused at a bound is never admitted later.
limit_overflowed: bool,
}
/// What the server remembers of a write it answered: digests only, so an entry costs
@ -619,6 +623,9 @@ pub struct CultMeshRudpDocumentServer<S, Q, C> {
snapshot_source: Q,
clock: C,
options: CultMeshRudpDocumentServerOptions,
/// Entries remembered across all live sessions (`answered_writes`), kept in step by `remember` and
/// `drop_session`, so the server-wide budget is a comparison, not a sum over sessions per write.
remembered_writes: usize,
packets_dropped: u64,
send_failures: u64,
/// Peers whose every datagram fails to send, standing in for an unroutable
@ -655,6 +662,7 @@ where
snapshot_source,
clock,
options,
remembered_writes: 0,
packets_dropped: 0,
send_failures: 0,
#[cfg(test)]
@ -803,7 +811,7 @@ where
};
if result.disconnected {
self.sessions.remove(&key);
self.drop_session(key);
return Ok(CultMeshRudpPollOutcome::Handled);
}
@ -1037,10 +1045,16 @@ where
let idle_timeout_ms = duration_millis(self.options.session_idle_timeout);
let lifetime_ms = duration_millis(self.options.session_max_lifetime);
let before = self.sessions.len();
let mut freed = 0;
self.sessions.retain(|_, entry| {
now.saturating_sub(entry.last_activity_monotonic_millis) <= idle_timeout_ms
&& now.saturating_sub(entry.created_at_monotonic_millis) <= lifetime_ms
let live = now.saturating_sub(entry.last_activity_monotonic_millis) <= idle_timeout_ms
&& now.saturating_sub(entry.created_at_monotonic_millis) <= lifetime_ms;
if !live {
freed += entry.answered_writes.len();
}
live
});
self.remembered_writes -= freed;
let expired = before - self.sessions.len();
self.end_answered_sessions()?;
@ -1106,7 +1120,7 @@ where
.get(&key)
.is_some_and(|entry| !entry.session.connect_repeats(packet))
{
self.sessions.remove(&key);
self.drop_session(key);
}
let reply = match self.sessions.get_mut(&key) {
Some(entry) => {
@ -1146,6 +1160,7 @@ where
capability_settled: false,
answered_writes: HashMap::new(),
limit_refusals: HashMap::new(),
limit_overflowed: false,
},
);
accept
@ -1455,7 +1470,8 @@ where
/// (rebuilt from this resend, whose content hash is the original's), a repeat with other content is
/// `MessageIdReused`. A first sighting past the session table or the server-wide budget is refused
/// `limit_reached` for that write alone, and that refusal is remembered (`limit_refusals`) so its resend
/// replays it; no slot is freed, so the id is never admitted later in the session.
/// replays it; no slot is freed, so the id is never admitted later in the session. A refusal the bounded set had no
/// room for sets `limit_overflowed`, after which the session refuses every unseen id, budget or no budget.
fn seen_write(
&mut self,
key: CultMeshRudpSessionKey,
@ -1476,8 +1492,8 @@ where
});
let session_full = entry.answered_writes.len() >= MAX_REMEMBERED_WRITES_PER_SESSION;
let refusal_room = entry.limit_refusals.len() < MAX_REMEMBERED_WRITES_PER_SESSION;
let remembered_total: usize = self.sessions.values().map(|entry| entry.answered_writes.len()).sum();
let budget_full = remembered_total
let overflowed = entry.limit_overflowed;
let budget_full = self.remembered_writes
.checked_add(1)
.and_then(|entries| entries.checked_mul(CultMeshRudpDocumentServerOptions::REMEMBERED_ENTRY_BYTES))
.is_none_or(|bytes| bytes > self.options.max_remembered_write_bytes);
@ -1492,10 +1508,12 @@ where
self.answer_sent(key, now, &answer, rejection)?
}
Some(_) => Some(rejection(CultMeshRudpRejectionReason::MessageIdReused)),
None if session_full || budget_full => {
if refusal_room {
if let Some(entry) = self.sessions.get_mut(&key) {
None if session_full || budget_full || overflowed => {
if let Some(entry) = self.sessions.get_mut(&key) {
if refusal_room {
entry.limit_refusals.insert(id_digest, content_hash);
} else {
entry.limit_overflowed = true;
}
}
Some(rejection(CultMeshRudpRejectionReason::WriteLimitReached))
@ -1506,10 +1524,20 @@ where
fn remember(&mut self, key: CultMeshRudpSessionKey, id_digest: [u8; 32], content_hash: [u8; 32], answer: StoredAnswer) {
if let Some(entry) = self.sessions.get_mut(&key) {
entry.answered_writes.insert(id_digest, RememberedWrite { content_hash, answer });
if entry.answered_writes.insert(id_digest, RememberedWrite { content_hash, answer }).is_none() {
self.remembered_writes += 1;
}
}
}
/// Removes a session for good and gives its remembered writes back to the server-wide budget. A session taken
/// out and put back within one call is not dropped.
fn drop_session(&mut self, key: CultMeshRudpSessionKey) -> Option<SessionEntry> {
let entry = self.sessions.remove(&key)?;
self.remembered_writes -= entry.answered_writes.len();
Some(entry)
}
/// Sends the answer owed a write. An answer that cannot be queued or sent would leave the write
/// unanswered, and a different answer would contradict what the sink did; so the session ends instead,
/// and the peer's write settles as unconfirmed (`session_ended`). The answer stays remembered.
@ -1637,7 +1665,7 @@ where
/// that can never be sent as built is not dropped: the goodbye names its
/// error instead. A refusal that cannot be encoded is not sent.
fn end_session(&mut self, key: CultMeshRudpSessionKey, end: SessionEnd) -> Result<()> {
let Some(mut entry) = self.sessions.remove(&key) else {
let Some(mut entry) = self.drop_session(key) else {
return Ok(());
};
let local_failure = matches!(end, SessionEnd::LocalFailure);

View file

@ -2785,6 +2785,143 @@ fn limit_refusals_are_remembered_in_a_bounded_set() -> Result<()> {
Ok(())
}
/// A refusal the bounded set could not hold is still the session's first answer for that id: when the budget
/// frees (another session ends), the id is not admitted later in the session, and neither is any id the session
/// has not been seen to use, because the refusal that was not remembered cannot be told from a new write.
#[test]
fn a_session_whose_limit_refusals_overflowed_refuses_new_ids_after_the_budget_frees() -> Result<()> {
let clock = Clock::new(70_000);
let options = CultMeshRudpDocumentServerOptions {
max_remembered_write_bytes: 65,
session_max_lifetime: Duration::from_millis(100),
..Default::default()
};
let sink = Sink::default();
let mut server = server(options, clock.clone(), sink.clone(), Source::default())?;
let mut holder = client(server.local_addr()?, 240)?;
connect(&mut server, &mut [&mut holder])?;
send_reliable(&mut holder, &receipt_hello())?;
send_reliable(&mut holder, &put("held", "note:held", vec![1]))?;
assert_eq!(frames_after(&mut server, &mut holder, 2)?[1], admitted("held", "note:held"), "after the server's hello");
clock.set_monotonic(70_050);
let mut peer = client(server.local_addr()?, 241)?;
connect(&mut server, &mut [&mut peer])?;
send_reliable(&mut peer, &receipt_hello())?;
for index in 0..1024 {
send_reliable(&mut peer, &put(&format!("r{index}"), "note:r", vec![1]))?;
if index % 16 == 15 {
for _ in 0..40 {
server.poll_once()?;
peer.poll_resends()?;
while peer.receive_once()?.is_some() {}
}
}
}
send_reliable(&mut peer, &put("over", "note:over", vec![1]))?;
let answers = frames_after(&mut server, &mut peer, 1)?;
assert_eq!(refusal_of(&answers[0]), (Some(CultNetErrorCode::LimitReached), Some("over".into())));
clock.set_monotonic(70_101);
assert_eq!(server.maintain()?.sessions_expired, 1, "the holder ended and freed the budget");
assert_eq!(server.session_count(), 1);
send_reliable(&mut peer, &put("over", "note:over", vec![1]))?;
send_reliable(&mut peer, &put("fresh", "note:fresh", vec![1]))?;
let answers = frames_after(&mut server, &mut peer, 2)?;
assert_eq!(refusal_of(&answers[0]), (Some(CultNetErrorCode::LimitReached), Some("over".into())), "never admitted later");
assert_eq!(refusal_of(&answers[1]), (Some(CultNetErrorCode::LimitReached), Some("fresh".into())));
assert_eq!(sink.0.lock().unwrap().receipts.len(), 1, "only the holder's write was applied");
Ok(())
}
/// A session that ends gives its remembered entries back to the server-wide budget, whichever way it ends.
#[test]
fn a_session_that_ends_frees_its_remembered_writes_from_the_budget() -> Result<()> {
let clock = Clock::new(70_000);
let options = CultMeshRudpDocumentServerOptions {
max_remembered_write_bytes: 65,
session_max_lifetime: Duration::from_millis(100),
..Default::default()
};
let sink = Sink::default();
let mut server = server(options, clock.clone(), sink.clone(), Source::default())?;
let mut first = client(server.local_addr()?, 242)?;
connect(&mut server, &mut [&mut first])?;
send_reliable(&mut first, &receipt_hello())?;
send_reliable(&mut first, &put("a", "note:a", vec![1]))?;
assert_eq!(frames_after(&mut server, &mut first, 2)?[1], admitted("a", "note:a"), "after the server's hello");
clock.set_monotonic(70_050);
let mut second = client(server.local_addr()?, 243)?;
connect(&mut server, &mut [&mut second])?;
send_reliable(&mut second, &receipt_hello())?;
send_reliable(&mut second, &put("b", "note:b", vec![1]))?;
assert_eq!(refusal_of(&frames_after(&mut server, &mut second, 2)?[1]).0, Some(CultNetErrorCode::LimitReached));
clock.set_monotonic(70_101);
assert_eq!(server.maintain()?.sessions_expired, 1);
send_reliable(&mut second, &put("c", "note:c", vec![1]))?;
assert_eq!(frames_after(&mut server, &mut second, 1)?, vec![admitted("c", "note:c")], "the ended session's entry was freed");
clock.set_monotonic(70_152);
assert_eq!(server.maintain()?.sessions_expired, 1);
assert_eq!(server.session_count(), 0);
let mut third = client(server.local_addr()?, 244)?;
connect(&mut server, &mut [&mut third])?;
send_reliable(&mut third, &receipt_hello())?;
send_reliable(&mut third, &put("d", "note:d", vec![1]))?;
assert_eq!(frames_after(&mut server, &mut third, 2)?[1], admitted("d", "note:d"), "and so was the second's");
Ok(())
}
/// Whichever way a session ends, its remembered writes go back to the budget: here the peer says goodbye, and
/// here the server ends it itself (an unreliable write whose refusal the reliable queue cannot take).
#[test]
fn a_disconnected_or_server_ended_session_frees_its_remembered_writes() -> Result<()> {
let options = CultMeshRudpDocumentServerOptions {
max_remembered_write_bytes: 65,
max_pending_reliable_packets_per_session: 3,
..Default::default()
};
let mut server = server(options, Clock::new(70_000), Sink::default(), Source::default())?;
let mut first = client(server.local_addr()?, 245)?;
connect(&mut server, &mut [&mut first])?;
send_reliable(&mut first, &receipt_hello())?;
send_reliable(&mut first, &put("a", "note:a", vec![1]))?;
assert_eq!(frames_after(&mut server, &mut first, 2)?[1], admitted("a", "note:a"));
first.disconnect(Vec::new())?;
for _ in 0..20 {
server.poll_once()?;
}
assert_eq!(server.session_count(), 0, "the goodbye ended the session");
// The budget holds one entry. A raw peer is admitted into it, then ended by the server.
let mut second = RawPeer::connect(&mut server, 246)?;
second.send(&receipt_hello())?;
second.send(&put("b", "note:b", vec![1]))?;
server.poll_once()?;
for index in 0..8 {
let payload = encode_cultnet_message_to_vec(&put(&format!("u{index}"), "note:1", vec![1]), CultNetWireContract::CultNetSchemaV0)?;
let packets = second.session.send_many(
"schema",
payload,
cultnet_rs::CultNetRudpSendOptions { reliable: false, ordered: false, sequenced: false, now_ms: 3, reliable_expire_after_ms: None },
Some(1200),
)?;
for packet in &packets {
second.send_packet(packet)?;
}
server.poll_once()?;
}
assert_eq!(server.session_count(), 0, "the server ended the session");
let mut third = client(server.local_addr()?, 247)?;
connect(&mut server, &mut [&mut third])?;
send_reliable(&mut third, &receipt_hello())?;
send_reliable(&mut third, &put("c", "note:c", vec![1]))?;
assert_eq!(frames_after(&mut server, &mut third, 2)?[1], admitted("c", "note:c"), "both ended sessions' entries were freed");
Ok(())
}
/// A session that never declared the capability gets no refusal for an unreliable write: it is dropped as before.
#[test]
fn an_unreliable_write_on_a_legacy_session_is_dropped_silently() -> Result<()> {