Merge pull request 'Rust RUDP server: pin blank schemaId/recordKey refusal, decide sequenced refusal per frame' (#63) from libby/rs-receipt-key-tests-per-frame into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled

This commit is contained in:
Libby 2026-11-09 14:15:49 +00:00
commit 5ba3e9e2aa
4 changed files with 370 additions and 2 deletions

View file

@ -38,7 +38,7 @@ A connection is receipt-capable when its `cultnet.hello.v0` (sent before its fir
- **Limit refusals are remembered.** A `limit_reached` refusal is remembered like any other: a resend of the same id and content hash replays `limit_reached`. No slot is freed mid-session, so an id refused at a bound never becomes admitted later in that session (a server at the cap keeps the refused digest pair in a bounded refusal set of at most 1024 per session, outside the entry budget; past it, a further new write is refused `limit_reached` without being remembered, and the session refuses every id it has not seen for the rest of its life, even if a server-wide budget has since freed, so a refusal that was not remembered is never followed by an admission of the same id). The client mints a new id on a new session.
- **Required fields.** A put or delete whose document or `schemaId` is null or missing is refused `message_invalid` with `details.field` `"document"` or `"schemaId"` (the first missing in that order) and fixed text; the write is not applied. A put or delete that is present but names nothing is not "missing": the write is refused `message_invalid` exactly as a frame that does not read, with `details.field` `"message"`, the fixed unreadable text and the write's id (vector `error_v1_empty_schema_id_is_unreadable_and_names_the_write`), and is never applied; a server must not hand it to its store. Names nothing means, on a put or delete, a `schemaId` or `recordKey` that is blank; on a put's document, also a `storedAt` that is blank, a `payload` of zero bytes (a MessagePack value is at least one byte, so an empty payload is no document), a `sourceRuntimeId`, `sourceAgentId` or `sourceRole` that is present and blank, and a `tags` entry that is blank. **Blank** means empty or made only of Unicode White_Space code points (the PropList property) and nothing else, in every runtime, whatever its platform's own whitespace test says. The set is exactly U+0009 to U+000D, U+0020, U+0085, U+00A0, U+1680, U+2000 to U+200A, U+2028, U+2029, U+202F, U+205F and U+3000. U+200B, U+200C, U+200D, U+2060, U+FEFF, U+180E and U+001C to U+001F are not White_Space (some platforms' whitespace tests accept U+001C to U+001F or U+180E, for example Java's `Character.isWhitespace` and older .NET, so a runtime must check the list, not its platform test): a string of them names something. The vectors list both sets (`whiteSpaceCodePoints`, `notWhiteSpaceCodePoints`) and a runtime checks every code point in every covered field. Absent or nil source ids and tags, and an empty `tags` list, are valid. The rule holds on every connection, receipt-capable or not (a legacy connection is refused with the `error.v0` of the same code, details and text); the vectors' `blankFields` section lists each case.
- **Fixed texts.** The `error` string of these refusals is fixed, so vectors can compare it: `message_invalid: messageId exceeds 256 bytes`, `message_invalid: document is required`, `message_invalid: schemaId is required`, `message_invalid: the message could not be read` (a frame that does not decode, or a write that names nothing; the text is the same for both and never carries a decoder's own wording), `message_invalid: receipt sessions require the reliable channel`, `limit_reached: the session's remembered-write limit is full`.
- **Reliable channel only.** A write is accepted on a receipt session only on a channel that is reliable and not sequenced (reliable ordered and reliable unordered both qualify; a sequenced channel drops superseded packets, so a write on it can vanish without trace). A write arriving on any other channel is refused `message_invalid` with `details.field: "channel"` (the transport profile's word for it) and fixed text. Receipts and refusals travel the reliable channel; a write that could be lost without trace cannot be answered once.
- **Reliable channel only.** A write is accepted on a receipt session only on a channel that is reliable and not sequenced (reliable ordered and reliable unordered both qualify; a sequenced channel drops superseded packets, so a write on it can vanish without trace). A write arriving on any other channel is refused `message_invalid` with `details.field: "channel"` (the transport profile's word for it) and fixed text. Receipts and refusals travel the reliable channel; a write that could be lost without trace cannot be answered once. The server refuses a sequenced write whenever it can read the write's id: from the delivered frame, and from a superseded packet that carries its whole frame. A write sent as several fragments whose frame is superseded is dropped whole and may go unanswered; the client's unconfirmed outcome covers it. A repeat of a packet the server already took, or a packet too far ahead to be taken, draws no further answer (rule 1).
- Past the session (or a server's longer retention, if it keeps one) a resend is a new write.
6. **Forwarded writes.** A server that forwards a non-primary write answers the original peer only with what the primary answered: the primary's receipt becomes `write_admitted` with the original id, its refusal becomes `error.v1` with the original id. If the forward gets no answer the server relays nothing: no receipt, no error, no synthesized refusal. The client's own rule below then reports the write as unconfirmed. A forwarder never turns an absent or ambiguous primary answer into an admission.
7. **Looks alike.** An admitted and a refused write differ in `schemaVersion`; a receipt has no `error`, an `error.v1` has no admission. A transport ack is neither.

View file

@ -780,6 +780,13 @@ where
return Ok(CultMeshRudpPollOutcome::Handled);
}
// Whether this packet is the first the session takes for its sequence: a repeat of an answered write, or a
// packet too far ahead to be remembered, is not, and the write is not answered for it again.
let first_receipt = packet.reliable
&& self
.sessions
.get(&key)
.is_some_and(|entry| !entry.session.has_received(packet.sequence));
let result = {
let entry = self
.sessions
@ -821,11 +828,28 @@ where
}
let mut kept_rejection = None;
// A superseded packet delivers no frame, yet it was acknowledged and will not be resent, so its write would
// go unanswered. A packet that carries its whole frame is answered from its own payload. A superseded
// fragment cannot be: the write's id may lie in a fragment this packet does not hold.
if refuse_sequenced
&& first_receipt
&& self.sessions.get(&key).is_some_and(|entry| entry.session.has_received(packet.sequence))
&& packet.fragment_count == 0
&& !result.delivered.iter().any(|frame| frame.channel_id == "schema" && frame.sequence == packet.sequence)
{
if let CultMeshRudpPollOutcome::ApplicationRejected(rejection) =
self.refuse_unreliable_write(key, &packet.payload)?
{
kept_rejection = Some(rejection);
}
}
for frame in result.delivered {
if frame.channel_id != "schema" {
continue;
}
if refuse_sequenced {
// `delivered` also holds the ordered frames this packet's arrival released from the hold; those were
// not sent on the sequenced channel. They sit above the packet's own sequence, its own frame at or below.
if refuse_sequenced && sequence_at_or_before(frame.sequence, packet.sequence) {
if let CultMeshRudpPollOutcome::ApplicationRejected(rejection) =
self.refuse_unreliable_write(key, &frame.payload)?
{
@ -1814,6 +1838,13 @@ where
#[cfg(test)]
mod send_failure_tests;
/// Whether `sequence` is at or before `mark` in serial order (RFC 1982): the 32-bit space is compared modulo 2^32,
/// so a frame that began before the wrap and a packet after it still order correctly. The receive window of
/// `cultnet_rs`' duplicate test does not belong here: a frame's first fragment may lie any distance back.
fn sequence_at_or_before(sequence: u32, mark: u32) -> bool {
mark.wrapping_sub(sequence) < 1 << 31
}
fn validate_options(options: &CultMeshRudpDocumentServerOptions) -> Result<()> {
if options.max_sessions == 0 {
return Err(anyhow!("max_sessions must be greater than zero"));
@ -1929,4 +1960,17 @@ mod tests {
.unwrap();
assert_eq!(hex(&bytes), MESSAGE_INVALID_HEX);
}
#[test]
fn sequence_order_holds_across_the_wrap_and_beyond_the_receive_window() {
assert!(sequence_at_or_before(7, 7));
assert!(sequence_at_or_before(100, 5_200), "further back than the receive window");
assert!(!sequence_at_or_before(5_200, 100));
assert!(sequence_at_or_before(u32::MAX - 1, 1), "begun before the wrap, ended after it");
assert!(!sequence_at_or_before(1, u32::MAX - 1), "after the wrap is later than before it");
assert!(sequence_at_or_before(u32::MAX, 0), "the wrap itself");
assert!(!sequence_at_or_before(0, u32::MAX));
assert!(sequence_at_or_before(0, (1 << 31) - 1), "just inside half the space");
assert!(!sequence_at_or_before(0, 1 << 31), "half the space away is not before");
}
}

View file

@ -2983,6 +2983,324 @@ fn only_reliable_non_sequenced_writes_are_accepted_on_a_receipt_session() -> Res
Ok(())
}
/// `bytes` with the MessagePack fixstr `from` replaced by the fixstr `to`, which may be blank.
fn swap_fixstr(bytes: &[u8], from: &str, to: &str) -> Vec<u8> {
assert!(from.len() < 32 && to.len() < 32);
let mut needle = vec![0xa0 | from.len() as u8];
needle.extend_from_slice(from.as_bytes());
let at = bytes.windows(needle.len()).position(|window| window == needle).expect("marker is in the frame");
let mut out = bytes[..at].to_vec();
out.push(0xa0 | to.len() as u8);
out.extend_from_slice(to.as_bytes());
out.extend_from_slice(&bytes[at + needle.len()..]);
out
}
/// A `schemaId` or `recordKey` that is present but empty or only whitespace names nothing: the write is refused
/// `message_invalid` like a frame that does not read (field "message", the write's id), never reaches the store,
/// and the session goes on (write-receipt.md, rule 5; vector `error_v1_empty_schema_id_is_unreadable_and_names_the_write`).
#[test]
fn a_write_whose_schema_id_or_record_key_names_nothing_is_refused_and_never_handed_to_the_store() -> Result<()> {
let blanks = ["", " ", "\t \n"];
let mut connection_id = 300;
for blank in blanks {
for blank_field in ["schemaId", "recordKey"] {
for operation in ["put", "delete"] {
connection_id += 1;
let (schema_id, record_key) = match blank_field {
"schemaId" => (blank, "note:1"),
_ => ("test.raw.v1", blank),
};
// The encoder refuses a blank field, so encode a marker and swap the blank into the bytes.
let bad = if operation == "put" {
let mut record = document("zz-key-zz", vec![1, 2, 3]);
record.schema_id = "zz-schema-zz".into();
encode_cultnet_message_to_vec(
&CultNetMessage::DocumentPutRaw { message_id: "bad-1".into(), document: record },
CultNetWireContract::CultNetSchemaV0,
)?
} else {
encode_cultnet_message_to_vec(
&CultNetMessage::DocumentDelete {
message_id: "bad-1".into(),
schema_id: "zz-schema-zz".into(),
record_key: "zz-key-zz".into(),
},
CultNetWireContract::CultNetSchemaV0,
)?
};
let bad = swap_fixstr(&bad, "zz-schema-zz", schema_id);
let bad = swap_fixstr(&bad, "zz-key-zz", record_key);
let label = format!("{operation} with {blank_field} {blank:?}");
let sink = Sink::default();
let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?;
let mut peer = client(server.local_addr()?, connection_id)?;
connect(&mut server, &mut [&mut peer])?;
send_reliable(&mut peer, &receipt_hello())?;
peer.send_reliable("schema", bad)?;
send_reliable(&mut peer, &put("good-1", "note:2", vec![1]))?;
let answers = answers_after(&mut server, &mut peer, 2)?;
assert_eq!(refusal_of(&answers[0]), (Some(CultNetErrorCode::MessageInvalid), Some("bad-1".into())), "{label}");
assert_eq!(error_text_and_field(&answers[0]).1, Some("message".into()), "{label}");
assert_eq!(answers[1], admitted("good-1", "note:2"), "{label}: the session goes on");
let state = sink.0.lock().unwrap();
assert_eq!(state.authorized, vec!["good-1".to_string()], "{label}: the store was never asked about the blank write");
assert_eq!(state.receipts.len(), 1, "{label}: only the good write was applied");
}
}
}
Ok(())
}
/// The sequenced-channel refusal belongs to the frame that arrived sequenced. A reliable-sequenced packet that
/// fills the gap an earlier ordered packet was held behind delivers both frames in one go: the sequenced write is
/// refused, the ordered write it released is admitted.
#[test]
fn a_sequenced_packet_releasing_a_held_ordered_write_refuses_only_its_own() -> Result<()> {
let sink = Sink::default();
let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?;
let mut peer = RawPeer::connect(&mut server, 250)?;
peer.send(&receipt_hello())?;
server.poll_once()?;
let mut packet_for = |peer: &mut RawPeer, id: &str, ordered: bool, sequenced: bool| -> Result<Vec<cultnet_rs::CultNetRudpPacket>> {
let payload = encode_cultnet_message_to_vec(&put(id, &format!("note:{id}"), vec![1]), CultNetWireContract::CultNetSchemaV0)?;
peer.session.send_many(
"schema",
payload,
cultnet_rs::CultNetRudpSendOptions { reliable: true, ordered, sequenced, now_ms: 3, reliable_expire_after_ms: None },
Some(1200),
)
};
let sequenced = packet_for(&mut peer, "s1", false, true)?;
let ordered = packet_for(&mut peer, "o1", true, false)?;
// The ordered write arrives first, one sequence ahead of the gap, and is held.
for packet in &ordered {
peer.send_packet(packet)?;
}
server.poll_once()?;
assert_eq!(sink.0.lock().unwrap().receipts.len(), 0, "the ordered write waits behind the gap");
for packet in &sequenced {
peer.send_packet(packet)?;
}
server.poll_once()?;
let mut answers = Vec::new();
for packet in peer.drain() {
for frame in peer.session.receive(&packet, 4)?.delivered {
answers.push(decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0)?);
}
}
let refusals: Vec<_> = answers.iter().filter(|a| matches!(a, CultNetMessage::ErrorV1 { .. })).collect();
assert_eq!(refusals.len(), 1, "only the sequenced write is refused: {answers:?}");
assert_eq!(refusal_of(refusals[0]), (Some(CultNetErrorCode::MessageInvalid), Some("s1".into())));
assert!(answers.contains(&admitted("o1", "note:o1")), "the released ordered write is admitted: {answers:?}");
assert_eq!(sink.0.lock().unwrap().receipts.len(), 1, "and applied");
Ok(())
}
/// The refusal of a write on a sequenced channel does not depend on the packet being the newest. A reliable-sequenced
/// packet that arrives after a newer one on its channel is superseded: the session delivers no frame for it, yet
/// the packet was acknowledged and will not be resent, so the server answers it from the packet's own payload.
#[test]
fn a_superseded_sequenced_write_is_still_refused() -> Result<()> {
let sink = Sink::default();
let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?;
let mut peer = RawPeer::connect(&mut server, 253)?;
peer.send(&receipt_hello())?;
server.poll_once()?;
let packet_for = |peer: &mut RawPeer, id: &str| -> Result<Vec<cultnet_rs::CultNetRudpPacket>> {
let payload = encode_cultnet_message_to_vec(&put(id, &format!("note:{id}"), vec![1]), CultNetWireContract::CultNetSchemaV0)?;
peer.session.send_many(
"schema",
payload,
cultnet_rs::CultNetRudpSendOptions { reliable: true, ordered: false, sequenced: true, now_ms: 3, reliable_expire_after_ms: None },
Some(1200),
)
};
let older = packet_for(&mut peer, "old")?;
let newer = packet_for(&mut peer, "new")?;
let mut refused_ids = Vec::new();
for packets in [&newer, &older] {
for packet in packets {
peer.send_packet(packet)?;
}
server.poll_once()?;
for packet in peer.drain() {
for frame in peer.session.receive(&packet, 4)?.delivered {
let answer = decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0)?;
if matches!(answer, CultNetMessage::ErrorV1 { .. }) {
refused_ids.push(refusal_of(&answer).1.expect("a refusal names its write"));
}
}
}
}
assert_eq!(refused_ids, vec!["new".to_string(), "old".to_string()], "the superseded write is answered too");
assert_eq!(sink.0.lock().unwrap().receipts.len(), 0, "and nothing was applied");
Ok(())
}
/// One answer per write (write-receipt.md, rule 1): a sequenced packet the server already answered is answered
/// once, however often the peer sends it again, and a packet too far ahead to be received draws nothing until it
/// is received (the peer resends it, and the answer comes then).
#[test]
fn a_repeated_or_far_ahead_sequenced_write_draws_one_answer_not_one_per_send() -> Result<()> {
let sink = Sink::default();
let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?;
let mut peer = RawPeer::connect(&mut server, 256)?;
peer.send(&receipt_hello())?;
server.poll_once()?;
let packet_for = |peer: &mut RawPeer, id: &str| -> Result<Vec<cultnet_rs::CultNetRudpPacket>> {
let payload = encode_cultnet_message_to_vec(&put(id, &format!("note:{id}"), vec![1]), CultNetWireContract::CultNetSchemaV0)?;
peer.session.send_many(
"schema",
payload,
cultnet_rs::CultNetRudpSendOptions { reliable: true, ordered: false, sequenced: true, now_ms: 3, reliable_expire_after_ms: None },
Some(1200),
)
};
let refusals_of = |peer: &mut RawPeer| -> Result<Vec<String>> {
let mut ids = Vec::new();
for packet in peer.drain() {
for frame in peer.session.receive(&packet, 4)?.delivered {
let answer = decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0)?;
if matches!(answer, CultNetMessage::ErrorV1 { .. }) {
ids.push(refusal_of(&answer).1.expect("a refusal names its write"));
}
}
}
Ok(ids)
};
// The same packet, sent three times (a resend whose acknowledgement was lost), is refused once.
let once = packet_for(&mut peer, "dup")?;
let mut refused = Vec::new();
for _ in 0..3 {
for packet in &once {
peer.send_packet(packet)?;
}
server.poll_once()?;
refused.extend(refusals_of(&mut peer)?);
}
assert_eq!(refused, vec!["dup".to_string()], "a repeat of an answered write is not answered again");
// A packet far past the receive window is not received: no answer yet, and none per resend.
let ahead = packet_for(&mut peer, "ahead")?;
let mut far = ahead[0].clone();
far.sequence = once[0].sequence + 5_000;
let mut refused = Vec::new();
for _ in 0..3 {
peer.send_packet(&far)?;
server.poll_once()?;
refused.extend(refusals_of(&mut peer)?);
}
assert_eq!(refused, Vec::<String>::new(), "an unreceived packet draws no answer");
assert_eq!(sink.0.lock().unwrap().receipts.len(), 0);
Ok(())
}
/// A superseded sequenced packet is answered even when its arrival fills a gap and releases another write: the
/// frames that arrive with it do not stand in for its own.
#[test]
fn a_superseded_sequenced_write_is_refused_while_it_releases_a_held_ordered_write() -> Result<()> {
let sink = Sink::default();
let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?;
let mut peer = RawPeer::connect(&mut server, 255)?;
peer.send(&receipt_hello())?;
server.poll_once()?;
let packet_for = |peer: &mut RawPeer, id: &str, ordered: bool, sequenced: bool| -> Result<Vec<cultnet_rs::CultNetRudpPacket>> {
let payload = encode_cultnet_message_to_vec(&put(id, &format!("note:{id}"), vec![1]), CultNetWireContract::CultNetSchemaV0)?;
peer.session.send_many(
"schema",
payload,
cultnet_rs::CultNetRudpSendOptions { reliable: true, ordered, sequenced, now_ms: 3, reliable_expire_after_ms: None },
Some(1200),
)
};
let older = packet_for(&mut peer, "old", false, true)?;
let ordered = packet_for(&mut peer, "o1", true, false)?;
let newer = packet_for(&mut peer, "new", false, true)?;
let mut answers = Vec::new();
for packets in [&newer, &ordered, &older] {
for packet in packets {
peer.send_packet(packet)?;
}
server.poll_once()?;
for packet in peer.drain() {
for frame in peer.session.receive(&packet, 4)?.delivered {
answers.push(decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0)?);
}
}
}
let mut refused: Vec<String> = answers
.iter()
.filter(|a| matches!(a, CultNetMessage::ErrorV1 { .. }))
.map(|a| refusal_of(a).1.expect("a refusal names its write"))
.collect();
refused.sort();
assert_eq!(refused, vec!["new".to_string(), "old".to_string()], "{answers:?}");
assert!(answers.contains(&admitted("o1", "note:o1")), "the released ordered write is admitted: {answers:?}");
Ok(())
}
/// The refusal reaches a sequenced write however far apart its fragments' sequences sit: other traffic can take the
/// sequences between the first fragment and the last, further back than the duplicate test's receive window.
#[test]
fn a_sequenced_write_whose_fragments_span_more_than_the_receive_window_is_refused() -> Result<()> {
let sink = Sink::default();
let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?;
let mut peer = RawPeer::connect(&mut server, 254)?;
peer.send(&receipt_hello())?;
server.poll_once()?;
let payload = encode_cultnet_message_to_vec(&put("far", "note:far", vec![1; 64]), CultNetWireContract::CultNetSchemaV0)?;
let mut packets = peer.session.send_many(
"schema",
payload,
cultnet_rs::CultNetRudpSendOptions { reliable: true, ordered: false, sequenced: true, now_ms: 3, reliable_expire_after_ms: None },
Some(32),
)?;
let last = packets.pop().expect("the write is fragmented");
assert!(!packets.is_empty());
let mut next = last.sequence;
let mut refused_ids = Vec::new();
for packet in &packets {
peer.send_packet(packet)?;
server.poll_once()?;
}
// 5,000 reliable packets on another channel, in order, take the sequences between the fragments.
for count in 0..5_000 {
let mut filler = packets[0].clone();
filler.channel_id = "filler".into();
filler.sequenced = false;
filler.fragment_id = 0;
filler.fragment_index = 0;
filler.fragment_count = 0;
filler.payload = vec![0];
filler.sequence = next;
next += 1;
peer.send_packet(&filler)?;
server.poll_once()?;
if count % 100 == 99 {
// Read what the server sent, so the socket buffer never holds back the refusal.
for packet in peer.drain() {
peer.session.receive(&packet, 4)?;
}
}
}
let mut last = last;
last.sequence = next;
peer.send_packet(&last)?;
server.poll_once()?;
for packet in peer.drain() {
for frame in peer.session.receive(&packet, 4)?.delivered {
let answer = decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0)?;
if matches!(answer, CultNetMessage::ErrorV1 { .. }) {
refused_ids.push(refusal_of(&answer).1.expect("a refusal names its write"));
}
}
}
assert_eq!(refused_ids, vec!["far".to_string()]);
assert_eq!(sink.0.lock().unwrap().receipts.len(), 0, "and nothing was applied");
Ok(())
}
/// A refused write is traffic: the peer that sends it is not idle, so its session outlives the idle timeout measured
/// from the refusal and not from the packet before it.
#[test]

View file

@ -1277,6 +1277,12 @@ impl CultNetRudpSession {
}
}
/// Whether `receive` has taken this reliable sequence: delivered, held, superseded or a duplicate. A packet
/// `receive` refused unremembered (too far ahead, or before the handshake) is not, and its sender resends it.
pub fn has_received(&self, sequence: u32) -> bool {
self.was_received(sequence)
}
/// The one duplicate test: true for a sequence in the window that was
/// received, for one below the window, and for one at or before the
/// watermark. The watermark starts at the handshake's seed, so a frame the