From c9cdad127e811ca29b03bac0e16d0ebfbd0f77dc Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 13:20:41 +0200 Subject: [PATCH 01/44] cultmesh-rs: an application rejection carries a typed reason CultMeshRudpApplicationRejection.reason was a String, so a consumer could only log a refusal, never act on its cause. It is now CultMeshRudpRejectionReason, one variant per refusal the document server makes, with sizes and limits as fields. Display keeps the existing sentences, so `{}` logging reads the same. The snapshot path encodes its response through one helper, which put admission will share. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/src/rudp_document_server.rs | 116 ++++++++++++++---- .../cultmesh-rs/tests/rudp_document_server.rs | 66 +++++++--- 2 files changed, 139 insertions(+), 43 deletions(-) diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index 47348bfe..cbac63ff 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -174,12 +174,67 @@ pub enum CultMeshRudpApplicationOperation { SnapshotRequest, } +/// Why the server refused an application message. +/// +/// `Display` gives the operator-facing sentence; match on the variant to act on +/// the cause. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CultMeshRudpRejectionReason { + /// The caller's sink refused the document. Carries the sink's error text. + SinkRefused(String), + /// The caller's snapshot source failed. Carries its error text. + SnapshotSourceFailed(String), + SnapshotTooManyDocuments { + documents: usize, + max_snapshot_documents: usize, + }, + SnapshotResponseTooLarge { + response_bytes: usize, + max_snapshot_response_bytes: usize, + }, + /// A snapshot response could not be encoded. Carries the encoder's error text. + ResponseEncodingFailed(String), + /// The server's retained payload budget cannot hold the response. + PayloadBudgetFull, + /// The session could not queue the response. Carries the session's error text. + ResponseQueueFailed(String), +} + +impl std::fmt::Display for CultMeshRudpRejectionReason { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::SinkRefused(error) | Self::SnapshotSourceFailed(error) => f.write_str(error), + Self::SnapshotTooManyDocuments { + documents, + max_snapshot_documents, + } => write!( + f, + "snapshot returned {documents} documents; limit is {max_snapshot_documents}" + ), + Self::SnapshotResponseTooLarge { + response_bytes, + max_snapshot_response_bytes, + } => write!( + f, + "snapshot response is {response_bytes} bytes; limit is {max_snapshot_response_bytes}" + ), + Self::ResponseEncodingFailed(error) => { + write!(f, "snapshot response could not be encoded: {error}") + } + Self::PayloadBudgetFull => f.write_str("retained payload budget is full"), + Self::ResponseQueueFailed(error) => { + write!(f, "snapshot response could not be queued: {error}") + } + } + } +} + #[derive(Clone, Debug, PartialEq, Eq)] pub struct CultMeshRudpApplicationRejection { pub session: CultMeshRudpSessionKey, pub operation: CultMeshRudpApplicationOperation, pub message_id: String, - pub reason: String, + pub reason: CultMeshRudpRejectionReason, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -473,6 +528,14 @@ where message_id, document, } => { + let reject = |reason| { + Ok(Some(CultMeshRudpApplicationRejection { + session: key, + operation: CultMeshRudpApplicationOperation::DocumentPutRaw, + message_id: message_id.clone(), + reason, + })) + }; let receipt = CultMeshRudpRawDocumentReceipt { session: key, message_id: message_id.clone(), @@ -481,12 +544,9 @@ where document, }; if let Err(error) = self.sink.accept_raw_document(receipt) { - return Ok(Some(CultMeshRudpApplicationRejection { - session: key, - operation: CultMeshRudpApplicationOperation::DocumentPutRaw, - message_id, - reason: format!("{error:#}"), - })); + return reject(CultMeshRudpRejectionReason::SinkRefused(format!( + "{error:#}" + ))); } } CultNetMessage::SnapshotRequest { @@ -508,7 +568,9 @@ where session: key, operation: CultMeshRudpApplicationOperation::SnapshotRequest, message_id, - reason: format!("{error:#}"), + reason: CultMeshRudpRejectionReason::SnapshotSourceFailed(format!( + "{error:#}" + )), })); } }; @@ -517,28 +579,24 @@ where session: key, operation: CultMeshRudpApplicationOperation::SnapshotRequest, message_id, - reason: format!( - "snapshot returned {} documents; limit is {}", - documents.len(), - self.options.max_snapshot_documents - ), + reason: CultMeshRudpRejectionReason::SnapshotTooManyDocuments { + documents: documents.len(), + max_snapshot_documents: self.options.max_snapshot_documents, + }, })); } let response = CultNetMessage::SnapshotResponseRaw { message_id: message_id.clone(), documents, }; - let payload = match encode_cultnet_message_to_vec( - &response, - CultNetWireContract::CultNetSchemaV0, - ) { + let payload = match encode_snapshot_response(&response) { Ok(payload) => payload, Err(error) => { return Ok(Some(CultMeshRudpApplicationRejection { session: key, operation: CultMeshRudpApplicationOperation::SnapshotRequest, message_id, - reason: format!("snapshot response could not be encoded: {error:#}"), + reason: CultMeshRudpRejectionReason::ResponseEncodingFailed(error), })); } }; @@ -547,11 +605,10 @@ where session: key, operation: CultMeshRudpApplicationOperation::SnapshotRequest, message_id, - reason: format!( - "snapshot response is {} bytes; limit is {}", - payload.len(), - self.options.max_snapshot_response_bytes - ), + reason: CultMeshRudpRejectionReason::SnapshotResponseTooLarge { + response_bytes: payload.len(), + max_snapshot_response_bytes: self.options.max_snapshot_response_bytes, + }, })); } if !self.payload_budget_allows(key, payload.len()) { @@ -559,7 +616,7 @@ where session: key, operation: CultMeshRudpApplicationOperation::SnapshotRequest, message_id, - reason: "retained payload budget is full".into(), + reason: CultMeshRudpRejectionReason::PayloadBudgetFull, })); } let payload_bytes = payload.len(); @@ -585,7 +642,9 @@ where session: key, operation: CultMeshRudpApplicationOperation::SnapshotRequest, message_id, - reason: format!("snapshot response could not be queued: {error:#}"), + reason: CultMeshRudpRejectionReason::ResponseQueueFailed(format!( + "{error:#}" + )), })); } }; @@ -686,6 +745,13 @@ fn validate_options(options: &CultMeshRudpDocumentServerOptions) -> Result<()> { Ok(()) } +/// The one encoder for a snapshot response, shared by the snapshot path and by +/// put admission so the size a put is judged by is the size it would be served at. +fn encode_snapshot_response(response: &CultNetMessage) -> std::result::Result, String> { + encode_cultnet_message_to_vec(response, CultNetWireContract::CultNetSchemaV0) + .map_err(|error| format!("{error:#}")) +} + fn duration_millis(duration: Duration) -> u64 { duration.as_millis().try_into().unwrap_or(u64::MAX) } diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index e43e4e59..1d18028f 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -2,8 +2,8 @@ use anyhow::Result; use cultmesh_rs::{ CultMeshRudpApplicationOperation, CultMeshRudpDocumentServer, CultMeshRudpDocumentServerOptions, CultMeshRudpPollOutcome, CultMeshRudpRawDocumentReceipt, - CultMeshRudpRawDocumentSink, CultMeshRudpServerClock, CultMeshRudpSnapshotQuery, - CultMeshRudpSnapshotSource, + CultMeshRudpRawDocumentSink, CultMeshRudpRejectionReason, CultMeshRudpServerClock, + CultMeshRudpSnapshotQuery, CultMeshRudpSnapshotSource, }; use cultnet_rs::{ CultNetMessage, CultNetRawDocumentRecord, CultNetRawPayloadEncoding, @@ -299,7 +299,8 @@ fn same_connection_id_is_peer_scoped_and_raw_bytes_are_untouched() -> Result<()> } #[test] -fn a_second_connect_from_a_client_replaces_its_session_and_a_fresh_epoch_is_separate() -> Result<()> { +fn a_second_connect_from_a_client_replaces_its_session_and_a_fresh_epoch_is_separate() -> Result<()> +{ let clock = Clock::new(45_000); let sink = Sink::default(); let mut server = server(Default::default(), clock, sink.clone(), Source::default())?; @@ -339,7 +340,12 @@ fn a_second_connect_from_a_client_replaces_its_session_and_a_fresh_epoch_is_sepa #[test] fn a_restarted_client_on_the_same_address_and_connection_id_is_admitted() -> Result<()> { let sink = Sink::default(); - let mut server = server(Default::default(), Clock::new(46_000), sink.clone(), Source::default())?; + let mut server = server( + Default::default(), + Clock::new(46_000), + sink.clone(), + Source::default(), + )?; let target = server.local_addr()?; let shared = UdpSocket::bind("127.0.0.1:0")?; let twin = shared.try_clone()?; @@ -376,7 +382,10 @@ fn a_restarted_client_on_the_same_address_and_connection_id_is_admitted() -> Res } let receipts = sink.0.lock().unwrap(); assert!( - receipts.receipts.iter().any(|r| r.message_id == "after-restart"), + receipts + .receipts + .iter() + .any(|r| r.message_id == "after-restart"), "the restarted client's frame was not delivered" ); Ok(()) @@ -390,11 +399,15 @@ fn a_restarted_client_starts_with_a_fresh_payload_budget() -> Result<()> { message_id: id.into(), document: document("budget", vec![7; 64]), }; - let encoded = encode_cultnet_message_to_vec(&put("put-a"), CultNetWireContract::CultNetSchemaV0)?; + let encoded = + encode_cultnet_message_to_vec(&put("put-a"), CultNetWireContract::CultNetSchemaV0)?; + let budget = encoded + .len() + .max(served_alone_bytes(&document("budget", vec![7; 64]))?); let options = CultMeshRudpDocumentServerOptions { - max_admitted_payload_bytes: encoded.len() * 2, - max_admitted_payload_bytes_per_session: encoded.len(), - max_snapshot_response_bytes: encoded.len(), + max_admitted_payload_bytes: budget * 2, + max_admitted_payload_bytes_per_session: budget, + max_snapshot_response_bytes: budget, ..Default::default() }; let sink = Sink::default(); @@ -460,7 +473,10 @@ fn application_rejection_is_nonfatal_peer_scoped_and_unacknowledged() -> Result< CultMeshRudpApplicationOperation::DocumentPutRaw ); assert_eq!(rejection.message_id, "rejected-put"); - assert!(rejection.reason.contains("injected sink failure")); + assert_eq!( + rejection.reason, + CultMeshRudpRejectionReason::SinkRefused("injected sink failure".into()) + ); assert_eq!(server.session_count(), 2); publisher.receive_once()?; assert_eq!( @@ -485,7 +501,10 @@ fn application_rejection_is_nonfatal_peer_scoped_and_unacknowledged() -> Result< CultMeshRudpApplicationOperation::SnapshotRequest ); assert_eq!(rejection.message_id, "rejected-snapshot"); - assert!(rejection.reason.contains("injected source failure")); + assert_eq!( + rejection.reason, + CultMeshRudpRejectionReason::SnapshotSourceFailed("injected source failure".into()) + ); assert_eq!(server.session_count(), 1); snapshot_client.receive_once()?; assert_eq!( @@ -575,10 +594,13 @@ fn payload_and_snapshot_output_budgets_fail_closed() -> Result<()> { document: document("budget", vec![7; 64]), }; let encoded = encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0)?; + let budget = encoded + .len() + .max(served_alone_bytes(&document("budget", vec![7; 64]))?); let options = CultMeshRudpDocumentServerOptions { - max_admitted_payload_bytes: encoded.len(), - max_admitted_payload_bytes_per_session: encoded.len(), - max_snapshot_response_bytes: encoded.len(), + max_admitted_payload_bytes: budget, + max_admitted_payload_bytes_per_session: budget, + max_snapshot_response_bytes: budget, ..Default::default() }; let mut budget_server = server(options, clock, sink.clone(), Source::default())?; @@ -617,7 +639,13 @@ fn payload_and_snapshot_output_budgets_fail_closed() -> Result<()> { CultMeshRudpApplicationOperation::SnapshotRequest ); assert_eq!(rejection.message_id, "too-large"); - assert!(rejection.reason.contains("snapshot response is")); + assert!(matches!( + rejection.reason, + CultMeshRudpRejectionReason::SnapshotResponseTooLarge { + response_bytes, + max_snapshot_response_bytes: 128, + } if response_bytes > 128 + )); assert_eq!(snapshot_server.session_count(), 0); snapshot_client.receive_once()?; assert_eq!( @@ -656,8 +684,7 @@ fn session_cap_and_expiry_use_monotonic_time() -> Result<()> { #[test] fn a_connect_storm_and_stray_frames_are_dropped_not_fatal() -> Result<()> { use cultnet_rs::{ - CultNetRudpSendOptions, CultNetRudpSession, CultNetRudpSessionOptions, - encode_rudp_packet, + CultNetRudpSendOptions, CultNetRudpSession, CultNetRudpSessionOptions, encode_rudp_packet, }; let clock = Clock::new(60_000); let sink = Sink::default(); @@ -698,7 +725,10 @@ fn a_connect_storm_and_stray_frames_are_dropped_not_fatal() -> Result<()> { reliable: true, ..Default::default() }; - send_raw(&mut server, &unadmitted.send("schema", vec![1], reliable.clone())?)?; + send_raw( + &mut server, + &unadmitted.send("schema", vec![1], reliable.clone())?, + )?; assert_eq!(server.packets_dropped(), 2); // A moved flow re-sends Connect from a socket that never hears the Accept. From 85288a5a47597306dc16e18411db798a789ffebc Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 13:20:55 +0200 Subject: [PATCH 02/44] cultmesh-rs: refuse a put the document server could never serve The server admitted a put up to the 4 MiB per-session budget but serves at most max_snapshot_response_bytes (1 MiB by default), so it could accept a document no snapshot request would ever return. DocumentPutRaw now sizes the snapshot response that carries the document alone under an empty message id, the smallest response that could serve it, with the snapshot path's own encoder. Over max_snapshot_response_bytes it is refused as DocumentUnservable, naming both sizes, before the sink sees it. At the bound it is admitted and served at exactly that size. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/src/rudp_document_server.rs | 41 +++++- .../cultmesh-rs/tests/rudp_document_server.rs | 133 ++++++++++++++++++ 2 files changed, 173 insertions(+), 1 deletion(-) diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index cbac63ff..00dc37db 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -138,6 +138,9 @@ pub struct CultMeshRudpDocumentServerOptions { /// finite without duplicating its fragment/ordering machinery here. pub max_admitted_payload_bytes: usize, pub max_admitted_payload_bytes_per_session: usize, + /// The largest encoded snapshot response the server sends. It also bounds + /// puts: a document whose snapshot response alone would exceed it is + /// refused with `DocumentUnservable`, since no request could return it. pub max_snapshot_response_bytes: usize, pub max_snapshot_documents: usize, pub resend_delay: Duration, @@ -182,6 +185,13 @@ pub enum CultMeshRudpApplicationOperation { pub enum CultMeshRudpRejectionReason { /// The caller's sink refused the document. Carries the sink's error text. SinkRefused(String), + /// The document could never be served: a snapshot response carrying it + /// alone, with an empty message id, would exceed + /// `max_snapshot_response_bytes`. It was not offered to the sink. + DocumentUnservable { + response_bytes: usize, + max_snapshot_response_bytes: usize, + }, /// The caller's snapshot source failed. Carries its error text. SnapshotSourceFailed(String), SnapshotTooManyDocuments { @@ -204,6 +214,13 @@ impl std::fmt::Display for CultMeshRudpRejectionReason { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::SinkRefused(error) | Self::SnapshotSourceFailed(error) => f.write_str(error), + Self::DocumentUnservable { + response_bytes, + max_snapshot_response_bytes, + } => write!( + f, + "document can never be served: its snapshot response is {response_bytes} bytes; limit is {max_snapshot_response_bytes}" + ), Self::SnapshotTooManyDocuments { documents, max_snapshot_documents, @@ -536,12 +553,34 @@ where reason, })) }; + // Admit only what some snapshot request can return: the smallest + // response that could carry this document is the document alone + // under an empty message id, sized by the snapshot path's encoder. + let alone = CultNetMessage::SnapshotResponseRaw { + message_id: String::new(), + documents: vec![document], + }; + let response_bytes = match encode_snapshot_response(&alone) { + Ok(payload) => payload.len(), + Err(error) => { + return reject(CultMeshRudpRejectionReason::ResponseEncodingFailed(error)); + } + }; + if response_bytes > self.options.max_snapshot_response_bytes { + return reject(CultMeshRudpRejectionReason::DocumentUnservable { + response_bytes, + max_snapshot_response_bytes: self.options.max_snapshot_response_bytes, + }); + } + let CultNetMessage::SnapshotResponseRaw { mut documents, .. } = alone else { + unreachable!("constructed as a snapshot response above"); + }; let receipt = CultMeshRudpRawDocumentReceipt { session: key, message_id: message_id.clone(), transport_sequence, received_at_unix_millis: now_unix, - document, + document: documents.remove(0), }; if let Err(error) = self.sink.accept_raw_document(receipt) { return reject(CultMeshRudpRejectionReason::SinkRefused(format!( diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index 1d18028f..2e51cb2d 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -211,6 +211,19 @@ fn connect( anyhow::bail!("client connection timed out") } +/// The encoded size of the snapshot response that carries `document` alone +/// under an empty message id: the smallest response that could ever serve it. +fn served_alone_bytes(document: &CultNetRawDocumentRecord) -> Result { + Ok(encode_cultnet_message_to_vec( + &CultNetMessage::SnapshotResponseRaw { + message_id: String::new(), + documents: vec![document.clone()], + }, + CultNetWireContract::CultNetSchemaV0, + )? + .len()) +} + fn send(client: &mut CultNetRudpSocketTransportConnection, message: &CultNetMessage) -> Result<()> { client.send( "schema", @@ -655,6 +668,126 @@ fn payload_and_snapshot_output_budgets_fail_closed() -> Result<()> { Ok(()) } +/// A put is admitted only if some snapshot request could return it. One byte +/// over the served bound is refused before the sink sees it; exactly at the +/// bound is admitted, and a snapshot then serves it at exactly that size. +#[test] +fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served() -> Result<()> { + let at_bound = document("fit", vec![7; 100]); + let over_bound = document("fit", vec![7; 101]); + let limit = served_alone_bytes(&at_bound)?; + assert_eq!( + served_alone_bytes(&over_bound)?, + limit + 1, + "fixture: the two documents must straddle the bound by one byte" + ); + let options = CultMeshRudpDocumentServerOptions { + max_snapshot_response_bytes: limit, + ..Default::default() + }; + let sink = Sink::default(); + let source = Source::default(); + let mut server = server(options, Clock::new(60_000), sink.clone(), source.clone())?; + let target = server.local_addr()?; + + let mut refused = client(target, 121)?; + let mut writer = client(target, 122)?; + connect(&mut server, &mut [&mut refused, &mut writer])?; + let refused_receipt = send_reliable( + &mut refused, + &CultNetMessage::DocumentPutRaw { + message_id: "put-over".into(), + document: over_bound, + }, + )?; + let CultMeshRudpPollOutcome::ApplicationRejected(rejection) = server.poll_once()? else { + panic!("an unservable put must be refused as an application rejection"); + }; + assert_eq!(rejection.session.connection_id, 121); + assert_eq!( + rejection.operation, + CultMeshRudpApplicationOperation::DocumentPutRaw + ); + assert_eq!(rejection.message_id, "put-over"); + assert_eq!( + rejection.reason, + CultMeshRudpRejectionReason::DocumentUnservable { + response_bytes: limit + 1, + max_snapshot_response_bytes: limit, + } + ); + let sentence = rejection.reason.to_string(); + assert!(sentence.contains(&(limit + 1).to_string()) && sentence.contains(&limit.to_string())); + assert!(sink.0.lock().unwrap().receipts.is_empty()); + assert_eq!(server.session_count(), 1); + refused.receive_once()?; + assert_eq!( + refused.reliable_send_status(&refused_receipt), + CultNetRudpReliableSendStatus::Pending + ); + + send( + &mut writer, + &CultNetMessage::DocumentPutRaw { + message_id: "put-at".into(), + document: at_bound.clone(), + }, + )?; + for _ in 0..500 { + let outcome = server.poll_once()?; + assert!( + !matches!(outcome, CultMeshRudpPollOutcome::ApplicationRejected(_)), + "{outcome:?}" + ); + if !sink.0.lock().unwrap().receipts.is_empty() { + break; + } + thread::sleep(Duration::from_millis(1)); + } + let stored: Vec<_> = sink + .0 + .lock() + .unwrap() + .receipts + .iter() + .map(|receipt| receipt.document.clone()) + .collect(); + assert_eq!(stored, vec![at_bound.clone()]); + source.0.lock().unwrap().documents = stored; + + send( + &mut writer, + &CultNetMessage::SnapshotRequest { + message_id: String::new(), + schema_ids: None, + record_keys: None, + }, + )?; + let mut served = None; + for _ in 0..500 { + let outcome = server.poll_once()?; + assert!( + !matches!(outcome, CultMeshRudpPollOutcome::ApplicationRejected(_)), + "{outcome:?}" + ); + if let Some(frame) = writer.receive_once()? { + served = Some(frame.payload); + break; + } + thread::sleep(Duration::from_millis(1)); + } + let served = served.expect("the admitted document must be served"); + assert_eq!(served.len(), limit); + assert_eq!( + decode_cultnet_message_from_slice(&served, CultNetWireContract::CultNetSchemaV0)?, + CultNetMessage::SnapshotResponseRaw { + message_id: String::new(), + documents: vec![at_bound], + } + ); + Ok(()) +} + #[test] fn session_cap_and_expiry_use_monotonic_time() -> Result<()> { let clock = Clock::new(60_000); From 027bd8aa47ab5db7beb2082be187ffca6a121787 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 13:33:16 +0200 Subject: [PATCH 03/44] cultmesh-rs: size an admitted put under the shortest message id CultNet encodes The served-size check built its response under an empty message id, which the CultNet encoder refuses, so every put was rejected as ResponseEncodingFailed. No snapshot request can carry an id shorter than one character, so a one-character id gives the smallest response that could ever serve the document; that is the size a put is now judged by. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-rs/src/rudp_document_server.rs | 9 ++++++--- packages/cultmesh-rs/tests/rudp_document_server.rs | 9 +++++---- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index 00dc37db..34794fc5 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -11,6 +11,9 @@ use std::net::{SocketAddr, UdpSocket}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; const MAX_UDP_DATAGRAM_BYTES: usize = 65_535; +/// The shortest message id CultNet encodes: one character. A snapshot request +/// can carry no shorter id, so no response to it can be smaller. +const SHORTEST_MESSAGE_ID: &str = "0"; /// The transport identity of one remote CultNet RUDP session. /// @@ -186,7 +189,7 @@ pub enum CultMeshRudpRejectionReason { /// The caller's sink refused the document. Carries the sink's error text. SinkRefused(String), /// The document could never be served: a snapshot response carrying it - /// alone, with an empty message id, would exceed + /// alone, under the shortest message id CultNet allows, would exceed /// `max_snapshot_response_bytes`. It was not offered to the sink. DocumentUnservable { response_bytes: usize, @@ -555,9 +558,9 @@ where }; // Admit only what some snapshot request can return: the smallest // response that could carry this document is the document alone - // under an empty message id, sized by the snapshot path's encoder. + // under the shortest message id CultNet encodes, sized by the snapshot path's encoder. let alone = CultNetMessage::SnapshotResponseRaw { - message_id: String::new(), + message_id: SHORTEST_MESSAGE_ID.into(), documents: vec![document], }; let response_bytes = match encode_snapshot_response(&alone) { diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index 2e51cb2d..1d338058 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -212,11 +212,12 @@ fn connect( } /// The encoded size of the snapshot response that carries `document` alone -/// under an empty message id: the smallest response that could ever serve it. +/// under a one-character message id, the shortest CultNet encodes: the +/// smallest response that could ever serve it. fn served_alone_bytes(document: &CultNetRawDocumentRecord) -> Result { Ok(encode_cultnet_message_to_vec( &CultNetMessage::SnapshotResponseRaw { - message_id: String::new(), + message_id: "r".into(), documents: vec![document.clone()], }, CultNetWireContract::CultNetSchemaV0, @@ -758,7 +759,7 @@ fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served( send( &mut writer, &CultNetMessage::SnapshotRequest { - message_id: String::new(), + message_id: "r".into(), schema_ids: None, record_keys: None, }, @@ -781,7 +782,7 @@ fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served( assert_eq!( decode_cultnet_message_from_slice(&served, CultNetWireContract::CultNetSchemaV0)?, CultNetMessage::SnapshotResponseRaw { - message_id: String::new(), + message_id: "r".into(), documents: vec![at_bound], } ); From fd394d54dba92c8b8ebfed1946a9e17f0b46acc7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 13:41:34 +0200 Subject: [PATCH 04/44] cultmesh-py: refuse a put the local server could never serve With max_snapshot_bytes set, CultMeshLocalServer stored any raw put while refusing every snapshot response over that size, so it could hold a document no request would ever return. _handle_raw_put now asks the database for the snapshot response that would serve the document alone, built from the envelope the put would store (the resolved local schema id, not the put's alias) under an empty message id, the shortest this server answers. It is measured with the snapshot path's own encoder. Over the bound the put is refused before it is stored, as cultnet.error.v0 code document_unservable with responseBytes and maxSnapshotBytes. At the bound it is stored and served at exactly that size. The database's put and snapshot paths share one envelope builder and one served-record builder, so the preview and the stored record cannot drift. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-py/src/cultmesh_py/node.py | 64 +++++++++++----- .../cultmesh-py/src/cultmesh_py/server.py | 24 +++++- packages/cultmesh-py/tests/test_cultmesh.py | 76 +++++++++++++++++++ 3 files changed, 144 insertions(+), 20 deletions(-) diff --git a/packages/cultmesh-py/src/cultmesh_py/node.py b/packages/cultmesh-py/src/cultmesh_py/node.py index 09ac2012..bf092060 100644 --- a/packages/cultmesh-py/src/cultmesh_py/node.py +++ b/packages/cultmesh-py/src/cultmesh_py/node.py @@ -651,6 +651,38 @@ class CultMeshDatabase: return message def apply_raw_put_message(self, message: dict[str, Any]) -> CultMeshDatabaseChange | None: + prepared = self._raw_put_envelope(message) + if prepared is None: + return None + document, envelope = prepared + record_key = envelope.key + previous = self.cache.get(document, record_key) + value = self.cache.put_envelope(document, envelope) + change_kind = "added" if previous is None else "updated" + change = self._publish_local_change(document, record_key, change_kind, value, previous) + self._append_shard_log_put(CultNetMessage( + "cultnet.document_put_raw.v0", + {key: value for key, value in message.items() if key != "schemaVersion"}, + ), change_kind) + return change + + def raw_put_served_alone(self, message: dict[str, Any], *, message_id: str) -> dict[str, Any] | None: + """The snapshot response that would serve this put's document alone, as a wire map. + + It is built from the envelope the put would store, exactly as a snapshot builds it, so a + server can judge a put by the size it would be served at. None when the put would not apply. + """ + prepared = self._raw_put_envelope(message) + if prepared is None: + return None + return CultNetRawSnapshotResponse( + message_id=message_id, + documents=(self._served_record(prepared[1]),), + ).to_wire() + + def _raw_put_envelope( + self, message: dict[str, Any] + ) -> tuple[DocumentDefinition[Any], CultCacheEnvelope] | None: document_record = message.get("document") if not isinstance(document_record, dict): return None @@ -664,24 +696,24 @@ class CultMeshDatabase: ) except KeyError: return None - record_key = str(document_record["recordKey"]) - previous = self.cache.get(document, record_key) - envelope = CultCacheEnvelope( - key=record_key, + return document, CultCacheEnvelope( + key=str(document_record["recordKey"]), type=document.type, schema_id=resolved_schema_id, payload=bytes(document_record["payload"]), stored_at=str(document_record.get("storedAt") or ""), catalog_entry=document.catalog_entry(), ) - value = self.cache.put_envelope(document, envelope) - change_kind = "added" if previous is None else "updated" - change = self._publish_local_change(document, record_key, change_kind, value, previous) - self._append_shard_log_put(CultNetMessage( - "cultnet.document_put_raw.v0", - {key: value for key, value in message.items() if key != "schemaVersion"}, - ), change_kind) - return change + + @staticmethod + def _served_record(envelope: CultCacheEnvelope) -> CultNetRawDocumentRecord: + return CultNetRawDocumentRecord( + schema_id=envelope.schema_id or envelope.type, + record_key=envelope.key, + stored_at=envelope.stored_at, + payload_encoding="messagepack", + payload=envelope.payload, + ) def apply_raw_delete_message(self, message: dict[str, Any]) -> CultMeshDatabaseChange | None: schema_id = str(message.get("schemaId") or "") @@ -774,13 +806,7 @@ class CultMeshDatabase: continue if shard_record_keys is not None and (schema_id, envelope.key) not in shard_record_keys: continue - documents.append(CultNetRawDocumentRecord( - schema_id=schema_id, - record_key=envelope.key, - stored_at=envelope.stored_at, - payload_encoding="messagepack", - payload=envelope.payload, - )) + documents.append(self._served_record(envelope)) return CultNetRawSnapshotResponse( message_id=message_id, diff --git a/packages/cultmesh-py/src/cultmesh_py/server.py b/packages/cultmesh-py/src/cultmesh_py/server.py index fe4edd52..605b5a7e 100644 --- a/packages/cultmesh-py/src/cultmesh_py/server.py +++ b/packages/cultmesh-py/src/cultmesh_py/server.py @@ -24,6 +24,10 @@ from cultnet_py import ( ) from .node import CultMeshNode + +# The shortest message id this server answers a snapshot request under. It takes a +# request's messageId as given, an empty one included, so no response it sends is smaller. +_SHORTEST_SERVED_MESSAGE_ID = "" from cultnet_py.cultmesh_contracts import ( PEER_EXCHANGE_REQUEST, VERSE_CATALOG_REQUEST, @@ -357,6 +361,19 @@ class CultMeshLocalServer: message_id=str(message.get("messageId") or ""), code="malformed_document_put", )] + if self.max_snapshot_bytes is not None: + alone = self.node.database.raw_put_served_alone( + message, message_id=_SHORTEST_SERVED_MESSAGE_ID + ) + response_bytes = None if alone is None else _snapshot_response_bytes(alone) + if response_bytes is not None and response_bytes > self.max_snapshot_bytes: + return [self._error_response( + f"Document can never be served: its snapshot response is {response_bytes} bytes; " + f"limit is {self.max_snapshot_bytes}.", + message_id=str(message.get("messageId") or ""), + code="document_unservable", + details={"responseBytes": response_bytes, "maxSnapshotBytes": self.max_snapshot_bytes}, + )] change = self.node.database.apply_raw_put_message(message) if change is None: return [self._error_response( @@ -559,7 +576,7 @@ class CultMeshLocalServer: details={"documentCount": document_count, "maxSnapshotDocuments": self.max_snapshot_documents}, ) if self.max_snapshot_bytes is not None: - response_bytes = len(msgpack.packb(response, use_bin_type=True)) + response_bytes = _snapshot_response_bytes(response) if response_bytes > self.max_snapshot_bytes: return self._error_response( f"Snapshot byte limit exceeded: {response_bytes} > {self.max_snapshot_bytes}.", @@ -723,3 +740,8 @@ def _infer_schema_name(schema_id: str) -> str | None: return None version = schema_id[marker + 2:] return schema_id[:marker] if version.isdigit() else None + + +def _snapshot_response_bytes(response: dict[str, Any]) -> int: + """The one measure of a snapshot response, shared by the snapshot path and put admission.""" + return len(msgpack.packb(response, use_bin_type=True)) diff --git a/packages/cultmesh-py/tests/test_cultmesh.py b/packages/cultmesh-py/tests/test_cultmesh.py index 9a697370..ddd8e89a 100644 --- a/packages/cultmesh-py/tests/test_cultmesh.py +++ b/packages/cultmesh-py/tests/test_cultmesh.py @@ -14,6 +14,8 @@ from dataclasses import dataclass from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any, Callable + +import msgpack from cultcache_py import ( CultCache, SingleFileMessagePackBackingStore, @@ -4293,6 +4295,80 @@ class CultMeshTests(unittest.TestCase): self.assertEqual(error["details"]["documentCount"], 2) self.assertEqual(error["details"]["maxSnapshotDocuments"], 1) + def test_cultmesh_local_server_refuses_a_put_it_could_never_serve(self) -> None: + # A put is admitted only if some snapshot request could return it. The put arrives under a + # long foreign schema alias and is stored and served under the shorter local schema id, so + # the size that decides is the served one, not the put's own. + document = define_database_entry_type( + "mesh.served_bound_note", + [("schema_version", 0), ("body", 1)], + schema_id="sha256:mesh-served-bound", + schema_name="mesh.served_bound_note", + schema_version="mesh.served_bound_note.v1", + ) + + def put(message_id: str, key: str, body_length: int) -> dict[str, Any]: + return document_put_raw( + message_id=message_id, + key=key, + schema_id="runtime.generated.mesh.served_bound_note.ui.99", + stored_at="2026-09-30T00:00:00Z", + payload=document.encode_payload({ + "schema_version": "mesh.served_bound_note.v1", + "body": "x" * body_length, + }), + ).to_wire() + + def exchange(server: Any, *messages: dict[str, Any]) -> tuple[dict[str, Any], bytes]: + client = CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=2.0) + with client.open_transport() as transport: + for message in messages: + transport.send("schema", msgpack.packb(message, use_bin_type=True)) + payload = transport.receive().payload + return msgpack.unpackb(payload, raw=False), payload + + empty_id_snapshot = snapshot_request(message_id="").to_wire() + + # The bound is what the server actually serves for the at-bound document alone, under the + # shortest message id it answers (an empty one), measured on an unbounded server. + def served_alone_bytes(key: str, body_length: int) -> int: + node = CultMesh.create_node(runtime_id="mesh-served-bound-probe") + node.database.register_document(document) + server = CultMesh.serve_node(node, enable_rudp=False) + try: + response, payload = exchange(server, put("probe", key, body_length), empty_id_snapshot) + finally: + server.stop() + self.assertEqual(response["schemaVersion"], "cultnet.snapshot_response_raw.v0") + self.assertEqual(len(response["documents"]), 1) + return len(payload) + + limit = served_alone_bytes("note:fits", 100) + self.assertEqual(served_alone_bytes("note:over", 101), limit + 1, "fixture: the documents must straddle the bound by one byte") + + node = CultMesh.create_node(runtime_id="mesh-served-bound") + node.database.register_document(document) + server = CultMesh.serve_node(node, max_snapshot_bytes=limit, enable_rudp=False) + try: + refused, _ = exchange(server, put("put-over", "note:over", 101)) + stored_after_refusal = node.database.get(document, "note:over") + served, served_payload = exchange(server, put("put-at", "note:fits", 100), empty_id_snapshot) + finally: + server.stop() + + self.assertEqual(refused["schemaVersion"], "cultnet.error.v0") + self.assertEqual(refused["messageId"], "put-over") + self.assertEqual(refused["code"], "document_unservable") + self.assertEqual(refused["details"], {"responseBytes": limit + 1, "maxSnapshotBytes": limit}) + self.assertIn(str(limit + 1), refused["error"]) + self.assertIn(str(limit), refused["error"]) + self.assertIsNone(stored_after_refusal) + + self.assertEqual(served["schemaVersion"], "cultnet.snapshot_response_raw.v0") + self.assertEqual([record["recordKey"] for record in served["documents"]], ["note:fits"]) + self.assertEqual(served["documents"][0]["schemaId"], document.catalog_entry().schema_id) + self.assertEqual(len(served_payload), limit) + def test_cultmesh_local_server_returns_errors_for_bad_requests(self) -> None: document = define_database_entry_type( "mesh.error_note", From 2cf1e07bac2cc93314db4476f1db267d59ce2d3b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 14:09:50 +0200 Subject: [PATCH 05/44] cultnet-ts: the registry sizes the reply that would serve a raw put CultNetDocumentRegistry.createRawSnapshotResponseForPut(put, messageId) returns the snapshot response that would serve the put's document alone: the envelope applyRawDocumentPutMessage stores, as createRawSnapshotResponse serves it. A server can judge a put by the size it would be served at. applyRawDocumentPutMessage and the new method share one envelope builder, and the served record comes from the snapshot path's own record builder, so the size and the stored record cannot drift. Co-Authored-By: Claude Opus 5.5 --- packages/cultnet-ts/src/replication.ts | 47 +++++++++++++++++++++----- 1 file changed, 38 insertions(+), 9 deletions(-) diff --git a/packages/cultnet-ts/src/replication.ts b/packages/cultnet-ts/src/replication.ts index 77dab70f..a2eda250 100644 --- a/packages/cultnet-ts/src/replication.ts +++ b/packages/cultnet-ts/src/replication.ts @@ -246,17 +246,46 @@ export class CultNetDocumentRegistry { cache: CultCache, message: CultNetDocumentPutRawMessage, ): Promise { + const { binding, envelope } = this.#rawPutEnvelope(message); + return cache.putEnvelope(binding.definition, envelope); + } + + /** + * The snapshot response that would serve this raw put's document alone: the + * record `applyRawDocumentPutMessage` would store, as `createRawSnapshotResponse` + * would serve it. A server uses it to judge a put by the size it would be + * served at. Throws, as the put would, when no binding accepts the document. + */ + createRawSnapshotResponseForPut( + message: CultNetDocumentPutRawMessage, + messageId: string, + ): CultNetSnapshotResponseRawMessage { + const { envelope } = this.#rawPutEnvelope(message); + return { + schemaVersion: "cultnet.snapshot_response_raw.v0", + messageId, + documents: [this.#createRawDocumentRecord(envelope)], + }; + } + + #rawPutEnvelope(message: CultNetDocumentPutRawMessage): { + binding: CultNetDocumentBinding; + envelope: CultCacheEnvelope; + } { const resolution = this.#resolveRawDocumentBinding(message.document); const { binding } = resolution; - return cache.putEnvelope(binding.definition, { - key: message.document.recordKey, - type: binding.definition.type, - schemaId: resolution.preserveIncomingSchemaId - ? message.document.schemaId - : schemaIdForBinding(binding), - payload: new Uint8Array(message.document.payload), - storedAt: message.document.storedAt, - }); + return { + binding, + envelope: { + key: message.document.recordKey, + type: binding.definition.type, + schemaId: resolution.preserveIncomingSchemaId + ? message.document.schemaId + : schemaIdForBinding(binding), + payload: new Uint8Array(message.document.payload), + storedAt: message.document.storedAt, + }, + }; } async applySnapshotResponse( From 0eb7434ab1e893e40c9f1fa787c0e34304842538 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 14:09:50 +0200 Subject: [PATCH 06/44] cultmesh-ts: the RUDP document server fragments its replies and refuses unservable puts The server reassembled fragmented puts but sent every reply as one UDP datagram, ignoring its own maxFragmentBytes and maxPayloadBytes, and a datagram that failed to leave vanished. An 80 KB note put in 1 KiB fragments was admitted and its snapshot never arrived, with no error. Replies now fragment by maxFragmentBytes (default CULTMESH_RUDP_DOCUMENT_SERVER_DEFAULT_MAX_FRAGMENT_BYTES, 1200), and maxPayloadBytes bounds both inbound frames and replies. A put whose served-alone reply (sized by the registry, under the shortest message id, with the send path's encoder) would exceed maxPayloadBytes, 65535 fragments or maxPendingReliablePackets is refused before onDocumentPutRaw: onError receives a CultMeshRudpUnservableDocumentError naming the sizes, and the peer a cultnet.error.v0. Every datagram send reports failure to onError, as does a snapshot reply that cannot be sent. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-ts/src/index.ts | 145 ++++++++++++-- packages/cultmesh-ts/test/cultmesh.test.ts | 213 ++++++++++++++++++++- 2 files changed, 340 insertions(+), 18 deletions(-) diff --git a/packages/cultmesh-ts/src/index.ts b/packages/cultmesh-ts/src/index.ts index b89cd823..72ce43d6 100644 --- a/packages/cultmesh-ts/src/index.ts +++ b/packages/cultmesh-ts/src/index.ts @@ -29,6 +29,7 @@ import { type CultNetOperationResponseMessage, type CultNetRawDocumentRecord, type CultNetReconnectPolicy, + type CultNetRudpPacket, type CultNetSchemaCatalogOptions, type CultNetSnapshotResponseRawMessage, type CultNetWireContract, @@ -4280,6 +4281,17 @@ export interface CultMeshRudpDocumentReceipt Promise | CultCache; @@ -4297,6 +4309,36 @@ export interface CultMeshRudpDocumentServerOptions extends CultMeshRudpSocketOpt sessionTimeoutMs?: number; } +/** Replies larger than one fragment are split into fragments of at most this many bytes. */ +export const CULTMESH_RUDP_DOCUMENT_SERVER_DEFAULT_MAX_FRAGMENT_BYTES = 1200; + +const RUDP_MAX_FRAGMENTS_PER_MESSAGE = 0xffff; + +/** CultNet parses no message id shorter than one character, so no reply is smaller. */ +const SHORTEST_MESSAGE_ID = "0"; + +/** + * A put the document server refused because it could never serve the document: + * the snapshot reply carrying it alone would exceed the server's reply limits. + */ +export class CultMeshRudpUnservableDocumentError extends Error { + constructor( + readonly messageId: string, + readonly recordKey: string, + readonly responseBytes: number, + readonly maxPayloadBytes: number | undefined, + readonly fragmentCount: number, + readonly maxFragmentCount: number, + ) { + super( + `Document ${recordKey} can never be served: its snapshot reply is ${responseBytes} bytes in ` + + `${fragmentCount} fragments; limits are ${maxPayloadBytes ?? "unbounded"} bytes and ` + + `${maxFragmentCount} fragments.`, + ); + this.name = "CultMeshRudpUnservableDocumentError"; + } +} + export interface CultMeshRudpServerSession { readonly sessionId: string; readonly remote: { address: string; family: string; port: number }; @@ -5773,6 +5815,17 @@ export class CultMesh { const resendPollMs = Math.max(10, options.resendPollMs ?? 25); const sessionTimeoutMs = Math.max(1_000, options.sessionTimeoutMs ?? 30_000); const wireContract = options.wireContract ?? "cultnet.schema.v0"; + const maxFragmentBytes = options.maxFragmentBytes ?? CULTMESH_RUDP_DOCUMENT_SERVER_DEFAULT_MAX_FRAGMENT_BYTES; + if (!(maxFragmentBytes > 0)) { + throw new Error("CultMesh RUDP document server maxFragmentBytes must be greater than zero."); + } + const maxPayloadBytes = options.maxPayloadBytes; + // The most fragments one reply can take: the wire's fragment count, and the + // reliable queue a reply must fit into whole. + const maxReplyFragments = Math.min( + RUDP_MAX_FRAGMENTS_PER_MESSAGE, + options.maxPendingReliablePackets ?? RUDP_MAX_FRAGMENTS_PER_MESSAGE, + ); let resendTimer: NodeJS.Timeout | undefined; function reportError(error: unknown): void { @@ -5794,11 +5847,7 @@ export class CultMesh { if (packet.packetType === "connect") { const connectPayload = Uint8Array.from(packet.payload ?? []); if (record?.session.connectRepeats(packet)) { - socket.send( - encodeRudpPacket(record.session.acceptConnect(packet, nowMs)), - remote.port, - remote.address, - ); + sendPacket(record.session.acceptConnect(packet, nowMs), remote); return; } if (record) closeSession(record); @@ -5816,7 +5865,7 @@ export class CultMesh { work: Promise.resolve(), }; sessions.set(key, record); - socket.send(encodeRudpPacket(record.session.acceptConnect(packet, nowMs)), remote.port, remote.address); + sendPacket(record.session.acceptConnect(packet, nowMs), remote); return; } @@ -5826,15 +5875,22 @@ export class CultMesh { const result = record.session.receive(packet, nowMs); if (result.reply) { - socket.send(encodeRudpPacket(result.reply), record.remote.port, record.remote.address); + sendPacket(result.reply, record.remote); } for (const ready of result.readyToSend ?? []) { - socket.send(encodeRudpPacket(ready), record.remote.port, record.remote.address); + sendPacket(ready, record.remote); } for (const frame of result.delivered) { if (frame.channelId !== "schema") { continue; } + if (maxPayloadBytes !== undefined && frame.payload.byteLength > maxPayloadBytes) { + reportError(new Error( + `CultMesh RUDP document server refused a ${frame.payload.byteLength}-byte frame from ` + + `${record.sessionId}; maxPayloadBytes is ${maxPayloadBytes}.`, + )); + continue; + } record.work = record.work .then(() => handleDocumentServerFrame(record, frame.payload)) .catch(reportError); @@ -5845,11 +5901,7 @@ export class CultMesh { return; } if (packet.reliable) { - socket.send( - encodeRudpPacket(record.session.createAckForReceived(packet.sequence)), - record.remote.port, - record.remote.address, - ); + sendPacket(record.session.createAckForReceived(packet.sequence), record.remote); } } catch (error) { reportError(error); @@ -5876,6 +5928,7 @@ export class CultMesh { const cache = await options.getCache(); sendSchemaMessage(record, options.documents.createRawSnapshotResponse(cache, message.messageId, message)); } catch (error) { + reportError(error); sendSchemaMessage(record, { schemaVersion: "cultnet.error.v0", error: error instanceof Error ? error.message : String(error), @@ -5888,6 +5941,12 @@ export class CultMesh { return; case "cultnet.document_put_raw.v0": if (options.onDocumentPutRaw) { + const unservable = unservablePut(message); + if (unservable) { + reportError(unservable); + sendSchemaMessage(record, { schemaVersion: "cultnet.error.v0", error: unservable.message }); + return; + } const receipt = await options.onDocumentPutRaw(normalizeRudpDocumentPut(message, record.remote)); if (receipt) { sendSchemaMessage(record, options.documents.createRawDocumentPutMessage( @@ -5966,16 +6025,70 @@ export class CultMesh { message: CultNetMessage, ): void { if (record.closed) throw new Error(`CultMesh RUDP session ${record.sessionId} is closed.`); - const payload = encode(encodeCultNetMessageForWire(message, wireContract)); + const payload = encodeSchemaMessage(message); + if (maxPayloadBytes !== undefined && payload.byteLength > maxPayloadBytes) { + throw new Error( + `CultMesh RUDP reply ${message.schemaVersion} is ${payload.byteLength} bytes; ` + + `maxPayloadBytes is ${maxPayloadBytes}.`, + ); + } for (const packet of record.session.sendMany("schema", payload, { reliable: true, ordered: true, nowMs: Date.now(), + maxFragmentBytes, })) { - socket.send(encodeRudpPacket(packet), record.remote.port, record.remote.address); + sendPacket(packet, record.remote); } } + /** The one reply encoder, shared by sends and by put admission. */ + function encodeSchemaMessage(message: CultNetMessage): Uint8Array { + return encode(encodeCultNetMessageForWire(message, wireContract)); + } + + /** A datagram that fails to leave reaches onError; nothing vanishes. */ + function sendPacket(packet: CultNetRudpPacket, remote: { address: string; port: number }): void { + socket.send(encodeRudpPacket(packet), remote.port, remote.address, (error) => { + if (error) reportError(error); + }); + } + + /** + * Refuse a put whose document could never be served: the snapshot reply + * carrying it alone, under the shortest message id CultNet parses, sized + * as `sendSchemaMessage` would send it. The document is sized as the + * registry would store and serve it; a document the registry has no + * binding for is sized as received. + */ + function unservablePut(message: CultNetMessage): CultMeshRudpUnservableDocumentError | undefined { + if (message.schemaVersion !== "cultnet.document_put_raw.v0") return undefined; + let reply: CultNetSnapshotResponseRawMessage; + try { + reply = options.documents.createRawSnapshotResponseForPut(message, SHORTEST_MESSAGE_ID); + } catch { + reply = { + schemaVersion: "cultnet.snapshot_response_raw.v0", + messageId: SHORTEST_MESSAGE_ID, + documents: [message.document], + }; + } + const responseBytes = encodeSchemaMessage(reply).byteLength; + const fragmentCount = Math.max(1, Math.ceil(responseBytes / maxFragmentBytes)); + if ((maxPayloadBytes === undefined || responseBytes <= maxPayloadBytes) + && fragmentCount <= maxReplyFragments) { + return undefined; + } + return new CultMeshRudpUnservableDocumentError( + message.messageId, + message.document.recordKey, + responseBytes, + maxPayloadBytes, + fragmentCount, + maxReplyFragments, + ); + } + return { bind, async start(): Promise { @@ -5999,7 +6112,7 @@ export class CultMesh { continue; } for (const packet of record.session.dueResends(nowMs)) { - socket.send(encodeRudpPacket(packet), record.remote.port, record.remote.address); + sendPacket(packet, record.remote); } } }, resendPollMs); diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index 3954c697..f7c4c6c1 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; import assert from "node:assert/strict"; -import { encode } from "@msgpack/msgpack"; +import { decode, encode } from "@msgpack/msgpack"; import { z } from "zod"; import { defineDocumentType } from "@gamecult/cultcache-ts"; import { @@ -11,8 +11,11 @@ import { CultNetPeer, cultNetBuiltinSchemaRegistry, defineCultNetDocumentBinding, + type CultNetDocumentPutRawMessage, + type CultNetMessage, + type CultNetSnapshotResponseRawMessage, } from "cultnet-ts"; -import { CultMesh } from "../src/index"; +import { CultMesh, CultMeshRudpUnservableDocumentError } from "../src/index"; const noteDocument = defineDocumentType({ type: "cultmesh.note", @@ -3223,6 +3226,212 @@ test("CultMesh TS negotiates streaming frame body transports explicitly", () => assert.deepEqual(frameUpdates, [42n]); }); +// A put the RUDP document server admits must be one it can serve. The server +// fragments its replies as its puts are reassembled, and refuses a put whose +// snapshot reply, carrying the document alone under the shortest message id, +// could never be sent within its limits. +type ServedBoundRig = { + server: ReturnType; + peer: CultNetPeer; + admitted: string[]; + errors: Error[]; + messages: CultNetMessage[]; +}; + +const servedBoundRegistry = () => + new CultNetDocumentRegistry([defineCultNetDocumentBinding({ definition: noteDocument })]); + +function notePut(messageId: string, recordKey: string, bodyLength: number): CultNetDocumentPutRawMessage { + return { + schemaVersion: "cultnet.document_put_raw.v0", + messageId, + document: { + schemaId: "cultmesh.note.v0", + recordKey, + storedAt: "2026-09-30T00:00:00.000Z", + payloadEncoding: "messagepack", + payload: encode({ noteId: recordKey, body: "x".repeat(bodyLength) }), + }, + }; +} + +/** The encoded size of the reply that would serve this put's document alone. */ +function servedAloneBytes(put: CultNetDocumentPutRawMessage): number { + return encode(servedBoundRegistry().createRawSnapshotResponseForPut(put, "0")).byteLength; +} + +/** The body length whose served-alone reply is exactly `bytes`, with a guard. */ +function bodyLengthForReplyBytes(recordKey: string, bytes: number): number { + const probe = 8_000; + const length = probe + bytes - servedAloneBytes(notePut("p", recordKey, probe)); + assert.equal(servedAloneBytes(notePut("p", recordKey, length)), bytes, "fixture: reply size is linear in the body"); + return length; +} + +async function withServedBoundRig( + connectionId: number, + serverLimits: { maxFragmentBytes?: number; maxPendingReliablePackets?: number; maxPayloadBytes?: number }, + body: (rig: ServedBoundRig) => Promise, +): Promise { + const node = await CultMesh.startNode( + join(await mkdtemp(join(tmpdir(), "cultmesh-ts-served-bound-")), "node.ccmp"), + { documents: [noteDocument] }, + ); + const registry = servedBoundRegistry(); + const admitted: string[] = []; + const errors: Error[] = []; + const messages: CultNetMessage[] = []; + const server = CultMesh.createRudpDocumentServer("cultmesh-ts-served-bound-server", connectionId, { + documents: registry, + getCache: () => node.cache, + bindHost: "127.0.0.1", + bindPort: 0, + resendDelayMs: 25, + resendPollMs: 5, + ...serverLimits, + // Stored as the registry stores a raw put, so the served record is the one it sizes. + onDocumentPutRaw: async (document) => { + admitted.push(document.recordKey); + await registry.applyRawDocumentPutMessage(node.cache, { + schemaVersion: "cultnet.document_put_raw.v0", + messageId: `store:${document.recordKey}`, + document: { + schemaId: document.schemaId, + recordKey: document.recordKey, + storedAt: document.storedAt, + payloadEncoding: "messagepack", + payload: encode(document.payload), + }, + }); + }, + onError: (error) => errors.push(error), + }); + let peer: CultNetPeer | undefined; + try { + await server.start(); + peer = await CultMesh.createRudpPeer( + "cultmesh-ts-served-bound-client", + connectionId, + `rudp://127.0.0.1:${server.bind.port}`, + { resendDelayMs: 25, resendPollMs: 5, maxFragmentBytes: 1024, maxPendingReliablePackets: 512, connectTimeoutMs: 1_000 }, + ); + peer.on("message", (message: CultNetMessage) => messages.push(message)); + await body({ server, peer, admitted, errors, messages }); + } finally { + peer?.close(); + server.close(); + } +} + +/** Requests `recordKey` under the shortest message id and waits for the reply. */ +async function snapshotUnderShortestId(rig: ServedBoundRig, recordKey: string): Promise { + const before = rig.messages.length; + rig.peer.sendSnapshotRequest({ schemaVersion: "cultnet.snapshot_request.v0", messageId: "0", recordKeys: [recordKey] }); + const startedAt = Date.now(); + while (Date.now() - startedAt < 3_000) { + const reply = rig.messages.slice(before).find((message) => + message.schemaVersion === "cultnet.snapshot_response_raw.v0" && message.messageId === "0"); + if (reply) return reply; + await delay(5); + } + throw new Error(`Timed out waiting for the snapshot of ${recordKey}; server errors: ${rig.errors.map(e => e.message).join("; ")}`); +} + +function servedBodies(reply: CultNetMessage): Array<[string, number]> { + assert.equal(reply.schemaVersion, "cultnet.snapshot_response_raw.v0"); + return (reply as CultNetSnapshotResponseRawMessage).documents.map((document) => [ + document.recordKey, + (decode(document.payload) as { body: string }).body.length, + ]); +} + +async function waitForAdmission(rig: ServedBoundRig, recordKey: string): Promise { + const startedAt = Date.now(); + while (!rig.admitted.includes(recordKey) && Date.now() - startedAt < 3_000) await delay(5); + assert.ok(rig.admitted.includes(recordKey), `${recordKey} was not admitted; server errors: ${rig.errors.map(e => e.message).join("; ")}`); +} + +async function waitForError(rig: ServedBoundRig, description: string): Promise { + const startedAt = Date.now(); + while (rig.errors.length === 0 && Date.now() - startedAt < 3_000) await delay(5); + assert.ok(rig.errors.length > 0, `no server error for ${description}`); + return rig.errors[0]!; +} + +test("CultMesh TS RUDP document server serves an 80 KB note put in 1 KiB fragments", async () => { + await withServedBoundRig(0x10203060, { maxFragmentBytes: 1024, maxPendingReliablePackets: 512 }, async (rig) => { + rig.peer.send(notePut("put-large", "note:large", 80_000)); + await waitForAdmission(rig, "note:large"); + assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:large")), [["note:large", 80_000]]); + assert.deepEqual(rig.errors, []); + }); +}); + +test("CultMesh TS RUDP document server refuses a put whose reply would overflow its reliable queue", async () => { + // Eight 1 KiB fragments fit the queue, nine do not. + const atBound = bodyLengthForReplyBytes("note:at", 8 * 1024); + const overBound = bodyLengthForReplyBytes("note:ov", 8 * 1024 + 1); + await withServedBoundRig(0x10203061, { maxFragmentBytes: 1024, maxPendingReliablePackets: 8 }, async (rig) => { + rig.peer.send(notePut("put-over", "note:ov", overBound)); + const refusal = await waitForError(rig, "the over-bound put"); + assert.ok(refusal instanceof CultMeshRudpUnservableDocumentError, refusal.message); + assert.equal(refusal.messageId, "put-over"); + assert.equal(refusal.recordKey, "note:ov"); + assert.equal(refusal.responseBytes, 8 * 1024 + 1); + assert.equal(refusal.fragmentCount, 9); + assert.equal(refusal.maxFragmentCount, 8); + assert.equal(refusal.maxPayloadBytes, undefined); + assert.match(refusal.message, /8193 bytes in 9 fragments/); + assert.deepEqual(rig.admitted, []); + + rig.peer.send(notePut("put-at", "note:at", atBound)); + await waitForAdmission(rig, "note:at"); + assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:at")), [["note:at", atBound]]); + assert.equal(rig.errors.length, 1); + }); +}); + +test("CultMesh TS RUDP document server honours maxPayloadBytes for replies, puts and inbound frames", async () => { + const limit = 4_000; + const atBound = bodyLengthForReplyBytes("note:at", limit); + const overBound = bodyLengthForReplyBytes("note:ov", limit + 1); + await withServedBoundRig(0x10203062, { maxFragmentBytes: 1024, maxPayloadBytes: limit }, async (rig) => { + rig.peer.send(notePut("put-over", "note:ov", overBound)); + const refusal = await waitForError(rig, "the over-bound put"); + assert.ok(refusal instanceof CultMeshRudpUnservableDocumentError, refusal.message); + assert.equal(refusal.responseBytes, limit + 1); + assert.equal(refusal.maxPayloadBytes, limit); + assert.equal(refusal.fragmentCount, 4); + assert.deepEqual(rig.admitted, []); + + rig.peer.send(notePut("put-at", "note:at", atBound)); + await waitForAdmission(rig, "note:at"); + assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:at")), [["note:at", atBound]]); + assert.equal(rig.errors.length, 1); + + // A frame over the limit is refused on arrival and never offered as a put. + rig.peer.send(notePut("put-huge", "note:huge", 2 * limit)); + await delay(50); + const startedAt = Date.now(); + while (rig.errors.length < 2 && Date.now() - startedAt < 3_000) await delay(5); + assert.equal(rig.errors.length, 2); + assert.ok(!(rig.errors[1] instanceof CultMeshRudpUnservableDocumentError)); + assert.match(rig.errors[1]!.message, /maxPayloadBytes is 4000/); + assert.deepEqual(rig.admitted, ["note:at"]); + }); +}); + +test("CultMesh TS RUDP document server reports a datagram that fails to leave", async () => { + // Fragments larger than any UDP datagram: the reply's one packet cannot be sent. + await withServedBoundRig(0x10203063, { maxFragmentBytes: 100_000, maxPendingReliablePackets: 512 }, async (rig) => { + rig.peer.send(notePut("put-large", "note:large", 80_000)); + await waitForAdmission(rig, "note:large"); + rig.peer.sendSnapshotRequest({ schemaVersion: "cultnet.snapshot_request.v0", messageId: "0", recordKeys: ["note:large"] }); + const failure = await waitForError(rig, "the oversized datagram"); + assert.match(failure.message, /EMSGSIZE|message too long/i); + }); +}); + function delay(milliseconds: number): Promise { return new Promise(resolve => setTimeout(resolve, milliseconds)); } From 4b668002aa6bd5f4ee3a094fd8240508dff10e90 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 14:15:49 +0200 Subject: [PATCH 07/44] cultmesh-ts: pin each served-bound limit with a fixture that can tell the rules apart The queue-bound puts carry a source runtime id, which the registry does not store, so sizing the record as received instead of as served is caught. The test states the served record's shape itself rather than asking the registry, so a registry that served a different record is caught too. A two-document snapshot over maxPayloadBytes proves a reply that cannot be sent reaches onError. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-ts/test/cultmesh.test.ts | 35 ++++++++++++++++++---- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index f7c4c6c1..5d79dacc 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -3241,7 +3241,12 @@ type ServedBoundRig = { const servedBoundRegistry = () => new CultNetDocumentRegistry([defineCultNetDocumentBinding({ definition: noteDocument })]); -function notePut(messageId: string, recordKey: string, bodyLength: number): CultNetDocumentPutRawMessage { +function notePut( + messageId: string, + recordKey: string, + bodyLength: number, + sourceRuntimeId?: string, +): CultNetDocumentPutRawMessage { return { schemaVersion: "cultnet.document_put_raw.v0", messageId, @@ -3251,13 +3256,23 @@ function notePut(messageId: string, recordKey: string, bodyLength: number): Cult storedAt: "2026-09-30T00:00:00.000Z", payloadEncoding: "messagepack", payload: encode({ noteId: recordKey, body: "x".repeat(bodyLength) }), + ...(sourceRuntimeId ? { sourceRuntimeId } : {}), }, }; } -/** The encoded size of the reply that would serve this put's document alone. */ +/** + * The encoded size of the reply that would serve this put's document alone, + * under the shortest message id: the record as a snapshot serves it, which + * keeps no source fields. + */ function servedAloneBytes(put: CultNetDocumentPutRawMessage): number { - return encode(servedBoundRegistry().createRawSnapshotResponseForPut(put, "0")).byteLength; + const { schemaId, recordKey, storedAt, payloadEncoding, payload } = put.document; + return encode({ + schemaVersion: "cultnet.snapshot_response_raw.v0", + messageId: "0", + documents: [{ schemaId, recordKey, storedAt, payloadEncoding, payload }], + }).byteLength; } /** The body length whose served-alone reply is exactly `bytes`, with a guard. */ @@ -3372,7 +3387,8 @@ test("CultMesh TS RUDP document server refuses a put whose reply would overflow const atBound = bodyLengthForReplyBytes("note:at", 8 * 1024); const overBound = bodyLengthForReplyBytes("note:ov", 8 * 1024 + 1); await withServedBoundRig(0x10203061, { maxFragmentBytes: 1024, maxPendingReliablePackets: 8 }, async (rig) => { - rig.peer.send(notePut("put-over", "note:ov", overBound)); + // The puts carry a source the registry does not store, so only the served record is the right size. + rig.peer.send(notePut("put-over", "note:ov", overBound, "cultmesh-ts-served-bound-client")); const refusal = await waitForError(rig, "the over-bound put"); assert.ok(refusal instanceof CultMeshRudpUnservableDocumentError, refusal.message); assert.equal(refusal.messageId, "put-over"); @@ -3384,7 +3400,7 @@ test("CultMesh TS RUDP document server refuses a put whose reply would overflow assert.match(refusal.message, /8193 bytes in 9 fragments/); assert.deepEqual(rig.admitted, []); - rig.peer.send(notePut("put-at", "note:at", atBound)); + rig.peer.send(notePut("put-at", "note:at", atBound, "cultmesh-ts-served-bound-client")); await waitForAdmission(rig, "note:at"); assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:at")), [["note:at", atBound]]); assert.equal(rig.errors.length, 1); @@ -3418,6 +3434,15 @@ test("CultMesh TS RUDP document server honours maxPayloadBytes for replies, puts assert.ok(!(rig.errors[1] instanceof CultMeshRudpUnservableDocumentError)); assert.match(rig.errors[1]!.message, /maxPayloadBytes is 4000/); assert.deepEqual(rig.admitted, ["note:at"]); + + // Two servable documents make a reply over the limit: it is not sent, and onError hears why. + rig.peer.send(notePut("put-second", "note:a2", atBound)); + await waitForAdmission(rig, "note:a2"); + rig.peer.sendSnapshotRequest({ schemaVersion: "cultnet.snapshot_request.v0", messageId: "0", recordKeys: ["note:at", "note:a2"] }); + const replyStartedAt = Date.now(); + while (rig.errors.length < 3 && Date.now() - replyStartedAt < 3_000) await delay(5); + assert.equal(rig.errors.length, 3); + assert.match(rig.errors[2]!.message, /reply cultnet\.snapshot_response_raw\.v0 is \d+ bytes; maxPayloadBytes is 4000/); }); }); From a2e0748ab5f3ab6ea44d9213c72517fbccf460c4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 14:29:30 +0200 Subject: [PATCH 08/44] cultmesh-ts: the second at-bound put fits the inbound limit Its ten-character message id made its own frame one byte over maxPayloadBytes, so the inbound cap refused it before admission was asked. The id is now as short as the first put's. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-ts/test/cultmesh.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index 5d79dacc..5aa0cdf7 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -3411,6 +3411,8 @@ test("CultMesh TS RUDP document server honours maxPayloadBytes for replies, puts const limit = 4_000; const atBound = bodyLengthForReplyBytes("note:at", limit); const overBound = bodyLengthForReplyBytes("note:ov", limit + 1); + // A put's own frame is only a few bytes under its reply, so a long message id would push an + // at-bound put over the inbound limit before admission is asked. Keep these ids short. await withServedBoundRig(0x10203062, { maxFragmentBytes: 1024, maxPayloadBytes: limit }, async (rig) => { rig.peer.send(notePut("put-over", "note:ov", overBound)); const refusal = await waitForError(rig, "the over-bound put"); @@ -3436,7 +3438,7 @@ test("CultMesh TS RUDP document server honours maxPayloadBytes for replies, puts assert.deepEqual(rig.admitted, ["note:at"]); // Two servable documents make a reply over the limit: it is not sent, and onError hears why. - rig.peer.send(notePut("put-second", "note:a2", atBound)); + rig.peer.send(notePut("put-a2", "note:a2", atBound)); await waitForAdmission(rig, "note:a2"); rig.peer.sendSnapshotRequest({ schemaVersion: "cultnet.snapshot_request.v0", messageId: "0", recordKeys: ["note:at", "note:a2"] }); const replyStartedAt = Date.now(); From 9118be879d981c3edf91c939258dc5f209a4422c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 15:28:55 +0200 Subject: [PATCH 09/44] cultmesh-rs: admission sizes the record as served, in the fragments it is sent in A served record carries no source provenance: the server now clears source_runtime_id, source_agent_id, source_role and tags from every record it sends in a snapshot response, as the TypeScript and Python servers already serve only what their stores keep. Put admission sizes that served record, so provenance that makes a put larger only in its received form no longer refuses it; the sink still receives the record as it was sent. Admission also counts the response's fragments: a put whose served-alone response would take more fragments of max_fragment_bytes than max_pending_reliable_packets_per_session or 65535 is refused with DocumentUnservable, which now names the fragment count and its limit. Construction refuses options that could not carry an empty snapshot response, in bytes or in fragments. The payload-budget fixture sets both budgets to exactly the put's frame, so a charge equal to a limit must fit. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/src/rudp_document_server.rs | 87 +++++- .../cultmesh-rs/tests/rudp_document_server.rs | 276 +++++++++++++++++- 2 files changed, 339 insertions(+), 24 deletions(-) diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index 34794fc5..4a3ec060 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -11,6 +11,8 @@ use std::net::{SocketAddr, UdpSocket}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; const MAX_UDP_DATAGRAM_BYTES: usize = 65_535; +/// The most fragments one RUDP message can carry: its fragment count is a u16. +const MAX_FRAGMENTS_PER_MESSAGE: usize = u16::MAX as usize; /// The shortest message id CultNet encodes: one character. A snapshot request /// can carry no shorter id, so no response to it can be smaller. const SHORTEST_MESSAGE_ID: &str = "0"; @@ -66,8 +68,11 @@ where /// Caller-owned catalog port for serving raw snapshot requests. /// -/// The caller decides which records the requester may see. CultMesh preserves +/// The caller decides which records the requester may see. CultMesh serves /// those records as raw CultNet documents and does not interpret their schemas. +/// A served record carries no source provenance: the server clears +/// `source_runtime_id`, `source_agent_id`, `source_role` and `tags` before it +/// sizes or sends a response, as every CultMesh runtime's server does. pub trait CultMeshRudpSnapshotSource { fn raw_snapshot( &mut self, @@ -142,7 +147,8 @@ pub struct CultMeshRudpDocumentServerOptions { pub max_admitted_payload_bytes: usize, pub max_admitted_payload_bytes_per_session: usize, /// The largest encoded snapshot response the server sends. It also bounds - /// puts: a document whose snapshot response alone would exceed it is + /// puts: a document whose snapshot response alone would exceed it, or would + /// take more fragments than one message or the reliable queue can hold, is /// refused with `DocumentUnservable`, since no request could return it. pub max_snapshot_response_bytes: usize, pub max_snapshot_documents: usize, @@ -189,11 +195,16 @@ pub enum CultMeshRudpRejectionReason { /// The caller's sink refused the document. Carries the sink's error text. SinkRefused(String), /// The document could never be served: a snapshot response carrying it - /// alone, under the shortest message id CultNet allows, would exceed - /// `max_snapshot_response_bytes`. It was not offered to the sink. + /// alone, as served and under the shortest message id CultNet allows, would + /// exceed `max_snapshot_response_bytes`, or would take more than + /// `max_fragment_count` fragments of `max_fragment_bytes`: the lesser of + /// 65535 and `max_pending_reliable_packets_per_session`. It was not offered + /// to the sink. DocumentUnservable { response_bytes: usize, max_snapshot_response_bytes: usize, + fragment_count: usize, + max_fragment_count: usize, }, /// The caller's snapshot source failed. Carries its error text. SnapshotSourceFailed(String), @@ -220,9 +231,11 @@ impl std::fmt::Display for CultMeshRudpRejectionReason { Self::DocumentUnservable { response_bytes, max_snapshot_response_bytes, + fragment_count, + max_fragment_count, } => write!( f, - "document can never be served: its snapshot response is {response_bytes} bytes; limit is {max_snapshot_response_bytes}" + "document can never be served: its snapshot response is {response_bytes} bytes in {fragment_count} fragments; limits are {max_snapshot_response_bytes} bytes and {max_fragment_count} fragments" ), Self::SnapshotTooManyDocuments { documents, @@ -557,11 +570,12 @@ where })) }; // Admit only what some snapshot request can return: the smallest - // response that could carry this document is the document alone - // under the shortest message id CultNet encodes, sized by the snapshot path's encoder. + // response that could carry this document is the record as served, + // alone, under the shortest message id CultNet encodes, sized by the + // snapshot path's encoder and fragmented as the snapshot path sends it. let alone = CultNetMessage::SnapshotResponseRaw { message_id: SHORTEST_MESSAGE_ID.into(), - documents: vec![document], + documents: vec![served_record(document.clone())], }; let response_bytes = match encode_snapshot_response(&alone) { Ok(payload) => payload.len(), @@ -569,21 +583,24 @@ where return reject(CultMeshRudpRejectionReason::ResponseEncodingFailed(error)); } }; - if response_bytes > self.options.max_snapshot_response_bytes { + let fragment_count = self.fragments_for(response_bytes); + let max_fragment_count = self.max_fragments_per_response(); + if response_bytes > self.options.max_snapshot_response_bytes + || fragment_count > max_fragment_count + { return reject(CultMeshRudpRejectionReason::DocumentUnservable { response_bytes, max_snapshot_response_bytes: self.options.max_snapshot_response_bytes, + fragment_count, + max_fragment_count, }); } - let CultNetMessage::SnapshotResponseRaw { mut documents, .. } = alone else { - unreachable!("constructed as a snapshot response above"); - }; let receipt = CultMeshRudpRawDocumentReceipt { session: key, message_id: message_id.clone(), transport_sequence, received_at_unix_millis: now_unix, - document: documents.remove(0), + document, }; if let Err(error) = self.sink.accept_raw_document(receipt) { return reject(CultMeshRudpRejectionReason::SinkRefused(format!( @@ -629,7 +646,7 @@ where } let response = CultNetMessage::SnapshotResponseRaw { message_id: message_id.clone(), - documents, + documents: documents.into_iter().map(served_record).collect(), }; let payload = match encode_snapshot_response(&response) { Ok(payload) => payload, @@ -711,6 +728,17 @@ where self.send_packet(key.remote_addr, &goodbye) } + /// The fragments `send_many` splits a response of `bytes` into. + fn fragments_for(&self, bytes: usize) -> usize { + bytes.div_ceil(self.options.max_fragment_bytes).max(1) + } + + /// The most fragments one response can take: one message's fragment count, + /// and the reliable queue it must fit into whole. + fn max_fragments_per_response(&self) -> usize { + MAX_FRAGMENTS_PER_MESSAGE.min(self.options.max_pending_reliable_packets_per_session) + } + fn payload_budget_allows(&self, key: CultMeshRudpSessionKey, bytes: usize) -> bool { let Some(session_bytes) = self .sessions @@ -784,9 +812,40 @@ fn validate_options(options: &CultMeshRudpDocumentServerOptions) -> Result<()> { if options.max_fragment_bytes == 0 { return Err(anyhow!("max_fragment_bytes must be greater than zero")); } + // The limits must leave room for the smallest response the server sends, an + // empty snapshot: a server that could answer nothing is misconfigured. + let empty = encode_snapshot_response(&CultNetMessage::SnapshotResponseRaw { + message_id: SHORTEST_MESSAGE_ID.into(), + documents: Vec::new(), + }) + .map_err(|error| anyhow!(error))? + .len(); + if empty > options.max_snapshot_response_bytes { + return Err(anyhow!( + "max_snapshot_response_bytes cannot hold an empty snapshot response" + )); + } + let max_fragments = + MAX_FRAGMENTS_PER_MESSAGE.min(options.max_pending_reliable_packets_per_session); + if empty.div_ceil(options.max_fragment_bytes) > max_fragments { + return Err(anyhow!( + "max_fragment_bytes and max_pending_reliable_packets_per_session cannot carry an empty snapshot response" + )); + } Ok(()) } +/// The record as the server serves it: without source provenance. What a peer +/// says about its own runtime, agent, role and tags is receipt data for the +/// sink, not part of the served document. +fn served_record(mut document: CultNetRawDocumentRecord) -> CultNetRawDocumentRecord { + document.source_runtime_id = None; + document.source_agent_id = None; + document.source_role = None; + document.tags = None; + document +} + /// The one encoder for a snapshot response, shared by the snapshot path and by /// put admission so the size a put is judged by is the size it would be served at. fn encode_snapshot_response(response: &CultNetMessage) -> std::result::Result, String> { diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index 1d338058..df4164fe 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -211,20 +211,92 @@ fn connect( anyhow::bail!("client connection timed out") } -/// The encoded size of the snapshot response that carries `document` alone -/// under a one-character message id, the shortest CultNet encodes: the +/// The record as a server serves it: the record the peer sent, without the +/// source provenance a peer reports about itself. Spelled out here rather than +/// asked of the server, so a server that served another shape is caught. +fn as_served(document: &CultNetRawDocumentRecord) -> CultNetRawDocumentRecord { + CultNetRawDocumentRecord { + source_runtime_id: None, + source_agent_id: None, + source_role: None, + tags: None, + ..document.clone() + } +} + +/// `document` with every source provenance field filled, so its received form +/// is larger than its served form. +fn with_provenance(mut document: CultNetRawDocumentRecord) -> CultNetRawDocumentRecord { + document.source_runtime_id = Some("provenance-runtime-that-is-not-served".into()); + document.source_agent_id = Some("provenance-agent".into()); + document.source_role = Some("provenance-role".into()); + document.tags = Some(vec!["provenance".into(), "tags".into()]); + document +} + +/// The encoded size of the snapshot response that carries `document` alone, as +/// served, under a one-character message id, the shortest CultNet encodes: the /// smallest response that could ever serve it. fn served_alone_bytes(document: &CultNetRawDocumentRecord) -> Result { Ok(encode_cultnet_message_to_vec( &CultNetMessage::SnapshotResponseRaw { message_id: "r".into(), - documents: vec![document.clone()], + documents: vec![as_served(document)], }, CultNetWireContract::CultNetSchemaV0, )? .len()) } +/// A document keyed `key` whose served-alone response is exactly `bytes`. +fn document_served_at(key: &str, bytes: usize) -> Result { + let probe = bytes / 2; + let base = served_alone_bytes(&document(key, vec![7; probe]))?; + let fitted = document(key, vec![7; probe + bytes - base]); + assert_eq!( + served_alone_bytes(&fitted)?, + bytes, + "fixture: the served size is linear in the payload" + ); + Ok(fitted) +} + +/// Polls the server and client until the client receives a frame. +fn serve_until_frame( + server: &mut Server, + client: &mut CultNetRudpSocketTransportConnection, +) -> Result> { + for _ in 0..2_000 { + let outcome = server.poll_once()?; + assert!( + !matches!(outcome, CultMeshRudpPollOutcome::ApplicationRejected(_)), + "{outcome:?}" + ); + if let Some(frame) = client.receive_once()? { + return Ok(frame.payload); + } + thread::sleep(Duration::from_millis(1)); + } + anyhow::bail!("the client received no frame") +} + +/// Polls the server until it returns a rejection or the sink holds `receipts`. +fn poll_until_rejected_or_stored( + server: &mut Server, + sink: &Sink, + receipts: usize, +) -> Result> { + for _ in 0..5_000 { + if let CultMeshRudpPollOutcome::ApplicationRejected(rejection) = server.poll_once()? { + return Ok(Some(rejection.reason)); + } + if sink.0.lock().unwrap().receipts.len() >= receipts { + return Ok(None); + } + } + anyhow::bail!("the put was neither refused nor stored") +} + fn send(client: &mut CultNetRudpSocketTransportConnection, message: &CultNetMessage) -> Result<()> { client.send( "schema", @@ -608,9 +680,13 @@ fn payload_and_snapshot_output_budgets_fail_closed() -> Result<()> { document: document("budget", vec![7; 64]), }; let encoded = encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0)?; - let budget = encoded - .len() - .max(served_alone_bytes(&document("budget", vec![7; 64]))?); + // The put's frame is exactly both budgets, so the first put is admitted only + // if a charge equal to a limit fits it. + let budget = encoded.len(); + assert!( + served_alone_bytes(&document("budget", vec![7; 64]))? <= budget, + "fixture: the snapshot limit must admit the put" + ); let options = CultMeshRudpDocumentServerOptions { max_admitted_payload_bytes: budget, max_admitted_payload_bytes_per_session: budget, @@ -671,10 +747,12 @@ fn payload_and_snapshot_output_budgets_fail_closed() -> Result<()> { /// A put is admitted only if some snapshot request could return it. One byte /// over the served bound is refused before the sink sees it; exactly at the -/// bound is admitted, and a snapshot then serves it at exactly that size. +/// bound is admitted, and a snapshot then serves it at exactly that size. The +/// bound is the record as served: provenance that makes the received record +/// larger than the bound neither refuses it nor reaches the snapshot. #[test] fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served() -> Result<()> { - let at_bound = document("fit", vec![7; 100]); + let at_bound = with_provenance(document("fit", vec![7; 100])); let over_bound = document("fit", vec![7; 101]); let limit = served_alone_bytes(&at_bound)?; assert_eq!( @@ -682,6 +760,18 @@ fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served( limit + 1, "fixture: the two documents must straddle the bound by one byte" ); + let received_alone = encode_cultnet_message_to_vec( + &CultNetMessage::SnapshotResponseRaw { + message_id: "r".into(), + documents: vec![at_bound.clone()], + }, + CultNetWireContract::CultNetSchemaV0, + )? + .len(); + assert!( + received_alone > limit + 1, + "fixture: the at-bound put is over the bound in its received form" + ); let options = CultMeshRudpDocumentServerOptions { max_snapshot_response_bytes: limit, ..Default::default() @@ -715,6 +805,8 @@ fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served( CultMeshRudpRejectionReason::DocumentUnservable { response_bytes: limit + 1, max_snapshot_response_bytes: limit, + fragment_count: 1, + max_fragment_count: 1024, } ); let sentence = rejection.reason.to_string(); @@ -753,7 +845,11 @@ fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served( .iter() .map(|receipt| receipt.document.clone()) .collect(); - assert_eq!(stored, vec![at_bound.clone()]); + assert_eq!( + stored, + vec![at_bound.clone()], + "the sink receives the record as it was sent" + ); source.0.lock().unwrap().documents = stored; send( @@ -783,12 +879,172 @@ fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served( decode_cultnet_message_from_slice(&served, CultNetWireContract::CultNetSchemaV0)?, CultNetMessage::SnapshotResponseRaw { message_id: "r".into(), - documents: vec![at_bound], + documents: vec![as_served(&at_bound)], } ); Ok(()) } +/// A put is admitted only if its served response fits the fragments one +/// response may take: here eight of 100 bytes, the reliable queue, although the +/// byte limit is far larger. Eight fragments are admitted and served; nine are +/// refused, and so is Soul's 2000-byte probe, each naming its sizes. +#[test] +fn a_put_whose_response_would_overflow_the_reliable_queue_is_refused() -> Result<()> { + let options = CultMeshRudpDocumentServerOptions { + max_fragment_bytes: 100, + max_pending_reliable_packets_per_session: 8, + max_snapshot_response_bytes: 8192, + ..Default::default() + }; + let sink = Sink::default(); + let source = Source::default(); + let mut server = server(options, Clock::new(61_000), sink.clone(), source.clone())?; + let target = server.local_addr()?; + let unservable = |response_bytes, fragment_count| { + Some(CultMeshRudpRejectionReason::DocumentUnservable { + response_bytes, + max_snapshot_response_bytes: 8192, + fragment_count, + max_fragment_count: 8, + }) + }; + + for (id, bytes, fragments) in [(131, 2000, 20), (132, 801, 9)] { + let mut refused = client(target, id)?; + connect(&mut server, &mut [&mut refused])?; + send( + &mut refused, + &CultNetMessage::DocumentPutRaw { + message_id: "put-over".into(), + document: document_served_at("queue", bytes)?, + }, + )?; + let reason = poll_until_rejected_or_stored(&mut server, &sink, 1)?; + assert_eq!(reason, unservable(bytes, fragments)); + let sentence = reason.unwrap().to_string(); + assert!( + sentence.contains(&format!("{bytes} bytes in {fragments} fragments")) + && sentence.contains("8 fragments"), + "{sentence}" + ); + } + assert!(sink.0.lock().unwrap().receipts.is_empty()); + + let at_bound = document_served_at("queue", 800)?; + let mut writer = client(target, 133)?; + connect(&mut server, &mut [&mut writer])?; + send( + &mut writer, + &CultNetMessage::DocumentPutRaw { + message_id: "put-at".into(), + document: at_bound.clone(), + }, + )?; + assert_eq!(poll_until_rejected_or_stored(&mut server, &sink, 1)?, None); + source.0.lock().unwrap().documents = vec![at_bound.clone()]; + send( + &mut writer, + &CultNetMessage::SnapshotRequest { + message_id: "r".into(), + schema_ids: None, + record_keys: None, + }, + )?; + let served = serve_until_frame(&mut server, &mut writer)?; + assert_eq!(served.len(), 800); + assert_eq!( + decode_cultnet_message_from_slice(&served, CultNetWireContract::CultNetSchemaV0)?, + CultNetMessage::SnapshotResponseRaw { + message_id: "r".into(), + documents: vec![as_served(&at_bound)], + } + ); + Ok(()) +} + +/// One message carries at most 65535 fragments, however deep the reliable +/// queue: a response of 65536 one-byte fragments is refused, one of 65535 is not. +#[test] +fn a_put_whose_response_needs_more_than_65535_fragments_is_refused() -> Result<()> { + let options = CultMeshRudpDocumentServerOptions { + max_fragment_bytes: 1, + max_pending_reliable_packets_per_session: 100_000, + max_snapshot_response_bytes: 70_000, + ..Default::default() + }; + let sink = Sink::default(); + let mut server = server(options, Clock::new(62_000), sink.clone(), Source::default())?; + let target = server.local_addr()?; + + let mut refused = client(target, 141)?; + connect(&mut server, &mut [&mut refused])?; + send( + &mut refused, + &CultNetMessage::DocumentPutRaw { + message_id: "put-over".into(), + document: document_served_at("wide", 65_536)?, + }, + )?; + assert_eq!( + poll_until_rejected_or_stored(&mut server, &sink, 1)?, + Some(CultMeshRudpRejectionReason::DocumentUnservable { + response_bytes: 65_536, + max_snapshot_response_bytes: 70_000, + fragment_count: 65_536, + max_fragment_count: 65_535, + }) + ); + + let mut writer = client(target, 142)?; + connect(&mut server, &mut [&mut writer])?; + send( + &mut writer, + &CultNetMessage::DocumentPutRaw { + message_id: "put-at".into(), + document: document_served_at("wide", 65_535)?, + }, + )?; + assert_eq!(poll_until_rejected_or_stored(&mut server, &sink, 1)?, None); + Ok(()) +} + +/// The limits must leave room for an empty snapshot response, the smallest the +/// server sends; exactly enough room is accepted. +#[test] +fn options_that_cannot_carry_an_empty_snapshot_response_are_refused() -> Result<()> { + let empty = encode_cultnet_message_to_vec( + &CultNetMessage::SnapshotResponseRaw { + message_id: "r".into(), + documents: Vec::new(), + }, + CultNetWireContract::CultNetSchemaV0, + )? + .len(); + let build = |options: CultMeshRudpDocumentServerOptions| { + server(options, Clock::new(63_000), Sink::default(), Source::default()).map(|_| ()) + }; + let bytes = |max_snapshot_response_bytes| CultMeshRudpDocumentServerOptions { + max_snapshot_response_bytes, + ..Default::default() + }; + let fragments = |max_pending_reliable_packets_per_session| CultMeshRudpDocumentServerOptions { + max_fragment_bytes: 1, + max_pending_reliable_packets_per_session, + ..Default::default() + }; + build(bytes(empty))?; + let error = build(bytes(empty - 1)).unwrap_err().to_string(); + assert!(error.contains("max_snapshot_response_bytes"), "{error}"); + build(fragments(empty))?; + let error = build(fragments(empty - 1)).unwrap_err().to_string(); + assert!( + error.contains("max_pending_reliable_packets_per_session"), + "{error}" + ); + Ok(()) +} + #[test] fn session_cap_and_expiry_use_monotonic_time() -> Result<()> { let clock = Clock::new(60_000); From b1d7d31f598d88cd506aa5495c105ac7bd5e1c89 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 15:37:34 +0200 Subject: [PATCH 10/44] cultmesh-rs: the snapshot source keeps owning the served record's provenance The previous commit cleared source provenance from every served record. Odin's snapshot source serves runtime-presence records with provenance it authors itself (source_runtime_id, source_agent_id, source_role and an odin-observed tag), and a crate test pins that a raw response is served as the source returned it. The server does not own that shape, so it no longer rewrites it, and admission again sizes the record as received. Which rule a Rust server should size by is reported as a fork. The fragment-count admission, the construction cross-check and the exact payload-budget fixture stand. The budget fixture's put carries a longer message id so its frame, the exact budget, is at least its served-alone response. Polling for a refusal sleeps when the server is idle, so a put of many fragments has time to arrive. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/src/rudp_document_server.rs | 32 ++++----- .../cultmesh-rs/tests/rudp_document_server.rs | 69 +++++-------------- 2 files changed, 29 insertions(+), 72 deletions(-) diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index 4a3ec060..fd671e95 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -68,11 +68,8 @@ where /// Caller-owned catalog port for serving raw snapshot requests. /// -/// The caller decides which records the requester may see. CultMesh serves +/// The caller decides which records the requester may see. CultMesh preserves /// those records as raw CultNet documents and does not interpret their schemas. -/// A served record carries no source provenance: the server clears -/// `source_runtime_id`, `source_agent_id`, `source_role` and `tags` before it -/// sizes or sends a response, as every CultMesh runtime's server does. pub trait CultMeshRudpSnapshotSource { fn raw_snapshot( &mut self, @@ -195,7 +192,7 @@ pub enum CultMeshRudpRejectionReason { /// The caller's sink refused the document. Carries the sink's error text. SinkRefused(String), /// The document could never be served: a snapshot response carrying it - /// alone, as served and under the shortest message id CultNet allows, would + /// alone, as received and under the shortest message id CultNet allows, would /// exceed `max_snapshot_response_bytes`, or would take more than /// `max_fragment_count` fragments of `max_fragment_bytes`: the lesser of /// 65535 and `max_pending_reliable_packets_per_session`. It was not offered @@ -570,12 +567,14 @@ where })) }; // Admit only what some snapshot request can return: the smallest - // response that could carry this document is the record as served, - // alone, under the shortest message id CultNet encodes, sized by the + // response that could carry this document is the document alone, as + // received, under the shortest message id CultNet encodes, sized by the // snapshot path's encoder and fragmented as the snapshot path sends it. + // The snapshot source owns the served record's shape, so the record + // as received is the server's measure of it. let alone = CultNetMessage::SnapshotResponseRaw { message_id: SHORTEST_MESSAGE_ID.into(), - documents: vec![served_record(document.clone())], + documents: vec![document], }; let response_bytes = match encode_snapshot_response(&alone) { Ok(payload) => payload.len(), @@ -595,12 +594,15 @@ where max_fragment_count, }); } + let CultNetMessage::SnapshotResponseRaw { mut documents, .. } = alone else { + unreachable!("constructed as a snapshot response above"); + }; let receipt = CultMeshRudpRawDocumentReceipt { session: key, message_id: message_id.clone(), transport_sequence, received_at_unix_millis: now_unix, - document, + document: documents.remove(0), }; if let Err(error) = self.sink.accept_raw_document(receipt) { return reject(CultMeshRudpRejectionReason::SinkRefused(format!( @@ -646,7 +648,7 @@ where } let response = CultNetMessage::SnapshotResponseRaw { message_id: message_id.clone(), - documents: documents.into_iter().map(served_record).collect(), + documents, }; let payload = match encode_snapshot_response(&response) { Ok(payload) => payload, @@ -835,16 +837,6 @@ fn validate_options(options: &CultMeshRudpDocumentServerOptions) -> Result<()> { Ok(()) } -/// The record as the server serves it: without source provenance. What a peer -/// says about its own runtime, agent, role and tags is receipt data for the -/// sink, not part of the served document. -fn served_record(mut document: CultNetRawDocumentRecord) -> CultNetRawDocumentRecord { - document.source_runtime_id = None; - document.source_agent_id = None; - document.source_role = None; - document.tags = None; - document -} /// The one encoder for a snapshot response, shared by the snapshot path and by /// put admission so the size a put is judged by is the size it would be served at. diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index df4164fe..1aa24211 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -211,37 +211,14 @@ fn connect( anyhow::bail!("client connection timed out") } -/// The record as a server serves it: the record the peer sent, without the -/// source provenance a peer reports about itself. Spelled out here rather than -/// asked of the server, so a server that served another shape is caught. -fn as_served(document: &CultNetRawDocumentRecord) -> CultNetRawDocumentRecord { - CultNetRawDocumentRecord { - source_runtime_id: None, - source_agent_id: None, - source_role: None, - tags: None, - ..document.clone() - } -} - -/// `document` with every source provenance field filled, so its received form -/// is larger than its served form. -fn with_provenance(mut document: CultNetRawDocumentRecord) -> CultNetRawDocumentRecord { - document.source_runtime_id = Some("provenance-runtime-that-is-not-served".into()); - document.source_agent_id = Some("provenance-agent".into()); - document.source_role = Some("provenance-role".into()); - document.tags = Some(vec!["provenance".into(), "tags".into()]); - document -} - -/// The encoded size of the snapshot response that carries `document` alone, as -/// served, under a one-character message id, the shortest CultNet encodes: the +/// The encoded size of the snapshot response that carries `document` alone +/// under a one-character message id, the shortest CultNet encodes: the /// smallest response that could ever serve it. fn served_alone_bytes(document: &CultNetRawDocumentRecord) -> Result { Ok(encode_cultnet_message_to_vec( &CultNetMessage::SnapshotResponseRaw { message_id: "r".into(), - documents: vec![as_served(document)], + documents: vec![document.clone()], }, CultNetWireContract::CultNetSchemaV0, )? @@ -287,8 +264,12 @@ fn poll_until_rejected_or_stored( receipts: usize, ) -> Result> { for _ in 0..5_000 { - if let CultMeshRudpPollOutcome::ApplicationRejected(rejection) = server.poll_once()? { - return Ok(Some(rejection.reason)); + match server.poll_once()? { + CultMeshRudpPollOutcome::ApplicationRejected(rejection) => { + return Ok(Some(rejection.reason)); + } + CultMeshRudpPollOutcome::Idle => thread::sleep(Duration::from_millis(1)), + _ => {} } if sink.0.lock().unwrap().receipts.len() >= receipts { return Ok(None); @@ -675,8 +656,10 @@ fn snapshot_response_resends_until_acknowledged() -> Result<()> { fn payload_and_snapshot_output_budgets_fail_closed() -> Result<()> { let clock = Clock::new(55_000); let sink = Sink::default(); + // The message id is long enough that the put's frame is at least its + // served-alone response, so the snapshot limit below admits it. let message = CultNetMessage::DocumentPutRaw { - message_id: "budget".into(), + message_id: "budget-exact".into(), document: document("budget", vec![7; 64]), }; let encoded = encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0)?; @@ -747,12 +730,10 @@ fn payload_and_snapshot_output_budgets_fail_closed() -> Result<()> { /// A put is admitted only if some snapshot request could return it. One byte /// over the served bound is refused before the sink sees it; exactly at the -/// bound is admitted, and a snapshot then serves it at exactly that size. The -/// bound is the record as served: provenance that makes the received record -/// larger than the bound neither refuses it nor reaches the snapshot. +/// bound is admitted, and a snapshot then serves it at exactly that size. #[test] fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served() -> Result<()> { - let at_bound = with_provenance(document("fit", vec![7; 100])); + let at_bound = document("fit", vec![7; 100]); let over_bound = document("fit", vec![7; 101]); let limit = served_alone_bytes(&at_bound)?; assert_eq!( @@ -760,18 +741,6 @@ fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served( limit + 1, "fixture: the two documents must straddle the bound by one byte" ); - let received_alone = encode_cultnet_message_to_vec( - &CultNetMessage::SnapshotResponseRaw { - message_id: "r".into(), - documents: vec![at_bound.clone()], - }, - CultNetWireContract::CultNetSchemaV0, - )? - .len(); - assert!( - received_alone > limit + 1, - "fixture: the at-bound put is over the bound in its received form" - ); let options = CultMeshRudpDocumentServerOptions { max_snapshot_response_bytes: limit, ..Default::default() @@ -845,11 +814,7 @@ fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served( .iter() .map(|receipt| receipt.document.clone()) .collect(); - assert_eq!( - stored, - vec![at_bound.clone()], - "the sink receives the record as it was sent" - ); + assert_eq!(stored, vec![at_bound.clone()]); source.0.lock().unwrap().documents = stored; send( @@ -879,7 +844,7 @@ fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served( decode_cultnet_message_from_slice(&served, CultNetWireContract::CultNetSchemaV0)?, CultNetMessage::SnapshotResponseRaw { message_id: "r".into(), - documents: vec![as_served(&at_bound)], + documents: vec![at_bound], } ); Ok(()) @@ -957,7 +922,7 @@ fn a_put_whose_response_would_overflow_the_reliable_queue_is_refused() -> Result decode_cultnet_message_from_slice(&served, CultNetWireContract::CultNetSchemaV0)?, CultNetMessage::SnapshotResponseRaw { message_id: "r".into(), - documents: vec![as_served(&at_bound)], + documents: vec![at_bound], } ); Ok(()) From 6cf19b136ae217ca5c21fa519430f348ffc519d0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 15:37:54 +0200 Subject: [PATCH 11/44] cultmesh-ts: judge a put by what serving it sends, and tell the peer every refusal The document server refused any delivered frame larger than maxPayloadBytes, reporting it only to onError: the peer's put, already acknowledged by the transport, vanished. The frame had been reassembled by then, so the check protected no memory; it only refused puts whose frame was over the limit because of provenance or a long message id although their served reply fit. It is gone. maxPayloadBytes bounds what the server sends; a put is judged by its served reply, and every refusal reaches the peer as a cultnet.error.v0. A stored put whose receipt cannot be sent (a receipt from onDocumentPutRaw larger than maxPayloadBytes) now tells the peer so with a cultnet.error.v0, as well as onError. The unservable refusal names sizes only, never the record key, so a long key cannot make the refusal itself too large to send. The options document states that the served-size judgement is exact only for an application that stores through the registry it was given. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-ts/src/index.ts | 62 ++++++++++++-------- packages/cultmesh-ts/test/cultmesh.test.ts | 68 ++++++++++++++++++---- 2 files changed, 95 insertions(+), 35 deletions(-) diff --git a/packages/cultmesh-ts/src/index.ts b/packages/cultmesh-ts/src/index.ts index 72ce43d6..6da497e7 100644 --- a/packages/cultmesh-ts/src/index.ts +++ b/packages/cultmesh-ts/src/index.ts @@ -4285,12 +4285,23 @@ export interface CultMeshRudpDocumentReceipt maxPayloadBytes) { - reportError(new Error( - `CultMesh RUDP document server refused a ${frame.payload.byteLength}-byte frame from ` - + `${record.sessionId}; maxPayloadBytes is ${maxPayloadBytes}.`, - )); - continue; - } record.work = record.work .then(() => handleDocumentServerFrame(record, frame.payload)) .catch(reportError); @@ -5949,15 +5955,24 @@ export class CultMesh { } const receipt = await options.onDocumentPutRaw(normalizeRudpDocumentPut(message, record.remote)); if (receipt) { - sendSchemaMessage(record, options.documents.createRawDocumentPutMessage( - receipt.binding, receipt.messageId ?? message.messageId, receipt.recordKey, receipt.value, - { - sourceRuntimeId: receipt.sourceRuntimeId ?? runtimeId, - sourceAgentId: receipt.sourceAgentId, - sourceRole: receipt.sourceRole ?? "provider", - tags: receipt.tags ?? ["receipt"], - }, - )); + try { + sendSchemaMessage(record, options.documents.createRawDocumentPutMessage( + receipt.binding, receipt.messageId ?? message.messageId, receipt.recordKey, receipt.value, + { + sourceRuntimeId: receipt.sourceRuntimeId ?? runtimeId, + sourceAgentId: receipt.sourceAgentId, + sourceRole: receipt.sourceRole ?? "provider", + tags: receipt.tags ?? ["receipt"], + }, + )); + } catch (error) { + // The put is stored: the peer must hear that its receipt is not coming. + reportError(error); + sendSchemaMessage(record, { + schemaVersion: "cultnet.error.v0", + error: `CultMesh RUDP document server stored a put but could not send its receipt.`, + }); + } } } return; @@ -6058,8 +6073,9 @@ export class CultMesh { * Refuse a put whose document could never be served: the snapshot reply * carrying it alone, under the shortest message id CultNet parses, sized * as `sendSchemaMessage` would send it. The document is sized as the - * registry would store and serve it; a document the registry has no - * binding for is sized as received. + * registry would store and serve it, which is exact only when the + * application stores through the registry; a document the registry has + * no binding for is sized as received. */ function unservablePut(message: CultNetMessage): CultMeshRudpUnservableDocumentError | undefined { if (message.schemaVersion !== "cultnet.document_put_raw.v0") return undefined; diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index 5aa0cdf7..6f24bdff 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -3287,6 +3287,7 @@ async function withServedBoundRig( connectionId: number, serverLimits: { maxFragmentBytes?: number; maxPendingReliablePackets?: number; maxPayloadBytes?: number }, body: (rig: ServedBoundRig) => Promise, + handler: { echoReceipt?: boolean } = {}, ): Promise { const node = await CultMesh.startNode( join(await mkdtemp(join(tmpdir(), "cultmesh-ts-served-bound-")), "node.ccmp"), @@ -3318,6 +3319,9 @@ async function withServedBoundRig( payload: encode(document.payload), }, }); + return handler.echoReceipt + ? { binding: defineCultNetDocumentBinding({ definition: noteDocument }), recordKey: document.recordKey, value: document.payload as { noteId: string; body: string } } + : undefined; }, onError: (error) => errors.push(error), }); @@ -3407,12 +3411,10 @@ test("CultMesh TS RUDP document server refuses a put whose reply would overflow }); }); -test("CultMesh TS RUDP document server honours maxPayloadBytes for replies, puts and inbound frames", async () => { +test("CultMesh TS RUDP document server honours maxPayloadBytes for replies and judges puts by what it would serve", async () => { const limit = 4_000; const atBound = bodyLengthForReplyBytes("note:at", limit); const overBound = bodyLengthForReplyBytes("note:ov", limit + 1); - // A put's own frame is only a few bytes under its reply, so a long message id would push an - // at-bound put over the inbound limit before admission is asked. Keep these ids short. await withServedBoundRig(0x10203062, { maxFragmentBytes: 1024, maxPayloadBytes: limit }, async (rig) => { rig.peer.send(notePut("put-over", "note:ov", overBound)); const refusal = await waitForError(rig, "the over-bound put"); @@ -3421,20 +3423,24 @@ test("CultMesh TS RUDP document server honours maxPayloadBytes for replies, puts assert.equal(refusal.maxPayloadBytes, limit); assert.equal(refusal.fragmentCount, 4); assert.deepEqual(rig.admitted, []); + // The peer hears the refusal, and it names sizes, never the record. + assert.deepEqual(await waitForPeerErrors(rig, 1), [refusal.message]); + assert.ok(!refusal.message.includes("note:ov"), refusal.message); - rig.peer.send(notePut("put-at", "note:at", atBound)); + // A put whose own frame is over the limit only by the provenance and message id it carries + // is served at the bound, so it is admitted and served. + const carried = notePut(`put-at-${"m".repeat(200)}`, "note:at", atBound, `runtime-${"r".repeat(200)}`); + assert.ok(encode(carried).byteLength > limit, "fixture: the put's frame is over the limit"); + rig.peer.send(carried); await waitForAdmission(rig, "note:at"); assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:at")), [["note:at", atBound]]); assert.equal(rig.errors.length, 1); - // A frame over the limit is refused on arrival and never offered as a put. - rig.peer.send(notePut("put-huge", "note:huge", 2 * limit)); - await delay(50); - const startedAt = Date.now(); - while (rig.errors.length < 2 && Date.now() - startedAt < 3_000) await delay(5); - assert.equal(rig.errors.length, 2); - assert.ok(!(rig.errors[1] instanceof CultMeshRudpUnservableDocumentError)); - assert.match(rig.errors[1]!.message, /maxPayloadBytes is 4000/); + // A record key longer than the limit: the refusal is still small enough to reach the peer. + const longKey = `note:${"k".repeat(2 * limit)}`; + rig.peer.send(notePut("put-long-key", longKey, 10)); + assert.equal((await waitForPeerErrors(rig, 2))[1], rig.errors[1]!.message); + assert.ok(rig.errors[1] instanceof CultMeshRudpUnservableDocumentError, rig.errors[1]!.message); assert.deepEqual(rig.admitted, ["note:at"]); // Two servable documents make a reply over the limit: it is not sent, and onError hears why. @@ -3448,6 +3454,44 @@ test("CultMesh TS RUDP document server honours maxPayloadBytes for replies, puts }); }); +test("CultMesh TS RUDP document server tells the peer when a stored put's receipt cannot be sent", async () => { + const limit = 4_000; + const small = bodyLengthForReplyBytes("note:small", 1_000); + const atBound = bodyLengthForReplyBytes("note:at", limit); + await withServedBoundRig(0x10203064, { maxFragmentBytes: 1024, maxPayloadBytes: limit }, async (rig) => { + rig.peer.send(notePut("put-small", "note:small", small)); + await waitForAdmission(rig, "note:small"); + const startedAt = Date.now(); + while (!rig.messages.some(isDocumentPut) && Date.now() - startedAt < 3_000) await delay(5); + assert.ok(rig.messages.some(isDocumentPut), "a receipt that fits is sent"); + + // Served at the bound, the put is admitted and stored; its echoed receipt carries the + // server's provenance and so is over the limit. The peer hears that it is not coming. + rig.peer.send(notePut("put-at", "note:at", atBound)); + await waitForAdmission(rig, "note:at"); + const [refusal] = await waitForPeerErrors(rig, 1); + assert.match(refusal!, /stored a put but could not send its receipt/); + assert.equal(rig.errors.length, 1); + assert.match(rig.errors[0]!.message, /reply cultnet\.document_put_raw\.v0 is \d+ bytes; maxPayloadBytes is 4000/); + assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:at")), [["note:at", atBound]]); + }, { echoReceipt: true }); +}); + +function isDocumentPut(message: CultNetMessage): boolean { + return message.schemaVersion === "cultnet.document_put_raw.v0"; +} + +/** Waits until the peer has received `count` cultnet.error.v0 replies, and returns their text. */ +async function waitForPeerErrors(rig: ServedBoundRig, count: number): Promise { + const errors = () => rig.messages + .filter((message) => message.schemaVersion === "cultnet.error.v0") + .map((message) => (message as { error: string }).error); + const startedAt = Date.now(); + while (errors().length < count && Date.now() - startedAt < 3_000) await delay(5); + assert.equal(errors().length, count, `peer errors: ${errors().join("; ")}`); + return errors(); +} + test("CultMesh TS RUDP document server reports a datagram that fails to leave", async () => { // Fragments larger than any UDP datagram: the reply's one packet cannot be sent. await withServedBoundRig(0x10203063, { maxFragmentBytes: 100_000, maxPendingReliablePackets: 512 }, async (rig) => { From 83be3bd90ff08b8e411bd182b712b41353c7e319 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 15:37:55 +0200 Subject: [PATCH 12/44] cultmesh-py: RUDP replies go in fragments, and a send failure ends no thread The local server sent every RUDP reply as one datagram, so a snapshot of a 100 KB put raised EMSGSIZE inside _rudp_loop and ended the RUDP thread for every peer. Replies are now fragmented by rudp_max_fragment_bytes (default CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES, 1200, as in the Rust and TypeScript servers), and each peer's reliable queue is bounded by rudp_max_pending_reliable_packets; serve_node takes both. A put arriving over RUDP whose served-alone reply would take more fragments than one message (65535) or the peer's reliable queue can hold is refused as document_unservable, with fragmentCount and maxFragmentCount in its details. A datagram that cannot leave, or a reply the peer's queue cannot take, is counted in rudp_send_failures and never raised out of the loop. This overlaps hands/ack-cutD (not yet on main), which classifies send failures and ends only the affected peer's session; its counter has the same name, and its classifier should replace the plain count here when it merges. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-py/src/cultmesh_py/__init__.py | 3 +- .../cultmesh-py/src/cultmesh_py/facade.py | 6 +- .../cultmesh-py/src/cultmesh_py/server.py | 111 ++++++++++--- packages/cultmesh-py/tests/test_cultmesh.py | 156 ++++++++++++++++++ 4 files changed, 252 insertions(+), 24 deletions(-) diff --git a/packages/cultmesh-py/src/cultmesh_py/__init__.py b/packages/cultmesh-py/src/cultmesh_py/__init__.py index af4da272..f2dc6b28 100644 --- a/packages/cultmesh-py/src/cultmesh_py/__init__.py +++ b/packages/cultmesh-py/src/cultmesh_py/__init__.py @@ -24,7 +24,7 @@ from .node import ( CultMeshReactiveDocumentReconciliation, create_node, ) -from .server import CultMeshLocalServer +from .server import CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES, CultMeshLocalServer from .session import ( CultMeshGameSession, CultMeshGameSessionOptions, @@ -79,6 +79,7 @@ __all__ = [ "CultMeshReactiveDocumentReconciliation", "CultMeshGameSession", "CultMeshGameSessionOptions", + "CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES", "CultMeshLocalServer", "CultMeshPeerCard", "CultMeshPeerCatalog", diff --git a/packages/cultmesh-py/src/cultmesh_py/facade.py b/packages/cultmesh-py/src/cultmesh_py/facade.py index 626b1dc7..c6b781c2 100644 --- a/packages/cultmesh-py/src/cultmesh_py/facade.py +++ b/packages/cultmesh-py/src/cultmesh_py/facade.py @@ -31,7 +31,7 @@ from .node import ( CultMeshPublicationDocumentBinding, create_node, ) -from .server import CultMeshLocalServer +from .server import CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES, CultMeshLocalServer from .session import CultMeshGameSession, CultMeshGameSessionOptions from .simulation import CultMeshSimulationFactCommitter from cultnet_py.cultmesh_contracts import ( @@ -404,6 +404,8 @@ class CultMesh: enable_rudp: bool = True, rudp_connection_id: int = 0x43554C54, rudp_resend_delay_ms: int = 25, + rudp_max_fragment_bytes: int = CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES, + rudp_max_pending_reliable_packets: int | None = None, ) -> CultMeshLocalServer: return CultMeshLocalServer( node=node, @@ -418,6 +420,8 @@ class CultMesh: enable_rudp=enable_rudp, rudp_connection_id=rudp_connection_id, rudp_resend_delay_ms=rudp_resend_delay_ms, + rudp_max_fragment_bytes=rudp_max_fragment_bytes, + rudp_max_pending_reliable_packets=rudp_max_pending_reliable_packets, ).start() @staticmethod diff --git a/packages/cultmesh-py/src/cultmesh_py/server.py b/packages/cultmesh-py/src/cultmesh_py/server.py index 605b5a7e..daf0ed6c 100644 --- a/packages/cultmesh-py/src/cultmesh_py/server.py +++ b/packages/cultmesh-py/src/cultmesh_py/server.py @@ -28,6 +28,11 @@ from .node import CultMeshNode # The shortest message id this server answers a snapshot request under. It takes a # request's messageId as given, an empty one included, so no response it sends is smaller. _SHORTEST_SERVED_MESSAGE_ID = "" +# The most fragments one RUDP message can carry: its fragment count is a u16. +_MAX_FRAGMENTS_PER_MESSAGE = 0xFFFF +# Replies larger than one fragment are split into fragments of at most this many bytes, +# as the Rust and TypeScript document servers do by default. +CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES = 1200 from cultnet_py.cultmesh_contracts import ( PEER_EXCHANGE_REQUEST, VERSE_CATALOG_REQUEST, @@ -72,17 +77,35 @@ class CultMeshLocalServer: enable_rudp: bool = True rudp_connection_id: int = 0x43554C54 rudp_resend_delay_ms: int = 25 + # RUDP replies are fragmented by rudp_max_fragment_bytes, and each peer's reliable queue + # holds at most rudp_max_pending_reliable_packets (None: only the 65535 fragments one + # message can carry). A put arriving over RUDP whose served reply could not fit them is + # refused as document_unservable. + rudp_max_fragment_bytes: int = CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES + rudp_max_pending_reliable_packets: int | None = None _socket: socket.socket | None = field(default=None, init=False, repr=False) _rudp_socket: socket.socket | None = field(default=None, init=False, repr=False) _stop: threading.Event = field(default_factory=threading.Event, init=False, repr=False) _thread: threading.Thread | None = field(default=None, init=False, repr=False) _rudp_thread: threading.Thread | None = field(default=None, init=False, repr=False) + _rudp_send_failures: int = field(default=0, init=False, repr=False) + + @property + def rudp_send_failures(self) -> int: + """RUDP replies and datagrams that could not be sent to a peer. Each is that peer's + loss: a reliable packet already queued stays pending and is resent, and no other + peer is affected.""" + return self._rudp_send_failures def __post_init__(self) -> None: if self.max_snapshot_documents is not None and self.max_snapshot_documents < 0: raise ValueError("max_snapshot_documents must be non-negative") if self.max_snapshot_bytes is not None and self.max_snapshot_bytes < 0: raise ValueError("max_snapshot_bytes must be non-negative") + if self.rudp_max_fragment_bytes <= 0: + raise ValueError("rudp_max_fragment_bytes must be greater than zero") + if self.rudp_max_pending_reliable_packets is not None and self.rudp_max_pending_reliable_packets <= 0: + raise ValueError("rudp_max_pending_reliable_packets must be greater than zero") def start(self) -> "CultMeshLocalServer": if self._socket is not None: @@ -237,6 +260,7 @@ class CultMeshLocalServer: CultNetRudpSessionOptions( connection_id=self.rudp_connection_id, resend_delay_ms=self.rudp_resend_delay_ms, + max_pending_reliable_packets=self.rudp_max_pending_reliable_packets, ) ) ) @@ -267,7 +291,7 @@ class CultMeshLocalServer: continue if not isinstance(message, dict): continue - responses = self._handle_connection_message(message, peer.subscriptions) + responses = self._handle_connection_message(message, peer.subscriptions, over_rudp=True) for response in responses: self._send_rudp_schema_frame( rudp_socket, @@ -299,25 +323,40 @@ class CultMeshLocalServer: session: CultNetRudpSession, payload: bytes, ) -> None: - for packet in session.send_many( - "schema", - payload, - CultNetRudpSendOptions(reliable=True, ordered=True, now_ms=_now_ms()), - ): + try: + packets = session.send_many( + "schema", + payload, + CultNetRudpSendOptions(reliable=True, ordered=True, now_ms=_now_ms()), + max_fragment_bytes=self.rudp_max_fragment_bytes, + ) + except ValueError: + # The peer's reliable queue cannot take this reply now. It is that peer's loss, + # never the thread's. + self._rudp_send_failures += 1 + return + for packet in packets: self._send_rudp_packet(rudp_socket, remote_addr, packet) - @staticmethod def _send_rudp_packet( + self, rudp_socket: socket.socket, remote_addr: tuple[str, int], packet: CultNetRudpPacket, ) -> None: - rudp_socket.sendto(encode_rudp_packet(packet), remote_addr) + # A datagram that cannot leave is that peer's lost datagram: counted, never raised + # (raising here ended the RUDP thread for every peer). A reliable one is resent. + try: + rudp_socket.sendto(encode_rudp_packet(packet), remote_addr) + except OSError: + self._rudp_send_failures += 1 def _handle_connection_message( self, message: dict[str, Any], subscriptions: dict[str, _DatabaseSubscription], + *, + over_rudp: bool = False, ) -> list[dict[str, Any]]: schema_version = message.get("schemaVersion") if schema_version == "cultnet.database_subscribe.v0": @@ -341,7 +380,7 @@ class CultMeshLocalServer: subscriptions.pop(str(message.get("subscriptionId") or ""), None) return [] if schema_version == "cultnet.document_put_raw.v0": - return self._handle_raw_put(message, subscriptions) + return self._handle_raw_put(message, subscriptions, over_rudp=over_rudp) if schema_version == "cultnet.document_delete.v0": return self._handle_raw_delete(message, subscriptions) if schema_version == "cultnet.simulation_observation.v0": @@ -353,6 +392,8 @@ class CultMeshLocalServer: self, message: dict[str, Any], subscriptions: dict[str, _DatabaseSubscription], + *, + over_rudp: bool = False, ) -> list[dict[str, Any]]: document_record = message.get("document") if not isinstance(document_record, dict): @@ -361,19 +402,9 @@ class CultMeshLocalServer: message_id=str(message.get("messageId") or ""), code="malformed_document_put", )] - if self.max_snapshot_bytes is not None: - alone = self.node.database.raw_put_served_alone( - message, message_id=_SHORTEST_SERVED_MESSAGE_ID - ) - response_bytes = None if alone is None else _snapshot_response_bytes(alone) - if response_bytes is not None and response_bytes > self.max_snapshot_bytes: - return [self._error_response( - f"Document can never be served: its snapshot response is {response_bytes} bytes; " - f"limit is {self.max_snapshot_bytes}.", - message_id=str(message.get("messageId") or ""), - code="document_unservable", - details={"responseBytes": response_bytes, "maxSnapshotBytes": self.max_snapshot_bytes}, - )] + unservable = self._unservable_put(message, over_rudp=over_rudp) + if unservable is not None: + return [unservable] change = self.node.database.apply_raw_put_message(message) if change is None: return [self._error_response( @@ -586,6 +617,42 @@ class CultMeshLocalServer: ) return response + def _unservable_put(self, message: dict[str, Any], *, over_rudp: bool) -> dict[str, Any] | None: + """The refusal for a put this server could never serve, or None. The document alone, + as a snapshot would serve it under the shortest message id, must fit max_snapshot_bytes; + a put arriving over RUDP must also fit, as fragments of rudp_max_fragment_bytes, in one + message and the peer's reliable queue.""" + if self.max_snapshot_bytes is None and not over_rudp: + return None + alone = self.node.database.raw_put_served_alone(message, message_id=_SHORTEST_SERVED_MESSAGE_ID) + if alone is None: + return None + response_bytes = _snapshot_response_bytes(alone) + details: dict[str, Any] = {"responseBytes": response_bytes, "maxSnapshotBytes": self.max_snapshot_bytes} + fits = self.max_snapshot_bytes is None or response_bytes <= self.max_snapshot_bytes + limits = f"limit is {self.max_snapshot_bytes}" + if over_rudp: + fragment_count = max(1, -(-response_bytes // self.rudp_max_fragment_bytes)) + max_fragment_count = min( + _MAX_FRAGMENTS_PER_MESSAGE, + self.rudp_max_pending_reliable_packets or _MAX_FRAGMENTS_PER_MESSAGE, + ) + details |= {"fragmentCount": fragment_count, "maxFragmentCount": max_fragment_count} + fits = fits and fragment_count <= max_fragment_count + limits = ( + f"it takes {fragment_count} fragments; limits are " + f"{'unbounded' if self.max_snapshot_bytes is None else self.max_snapshot_bytes} bytes " + f"and {max_fragment_count} fragments" + ) + if fits: + return None + return self._error_response( + f"Document can never be served: its snapshot response is {response_bytes} bytes; {limits}.", + message_id=str(message.get("messageId") or ""), + code="document_unservable", + details=details, + ) + @staticmethod def _error_response( error: str, diff --git a/packages/cultmesh-py/tests/test_cultmesh.py b/packages/cultmesh-py/tests/test_cultmesh.py index ddd8e89a..51398c89 100644 --- a/packages/cultmesh-py/tests/test_cultmesh.py +++ b/packages/cultmesh-py/tests/test_cultmesh.py @@ -53,6 +53,7 @@ from cultnet_py import ( CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, apply_shard_log_response, + create_rudp_schema_transport, document_delete, document_put_raw, hello, @@ -4369,6 +4370,161 @@ class CultMeshTests(unittest.TestCase): self.assertEqual(served["documents"][0]["schemaId"], document.catalog_entry().schema_id) self.assertEqual(len(served_payload), limit) + def _rudp_bound_note(self) -> Any: + return define_database_entry_type( + "mesh.rudp_bound_note", + [("schema_version", 0), ("body", 1)], + schema_id="sha256:mesh-rudp-bound", + schema_name="mesh.rudp_bound_note", + schema_version="mesh.rudp_bound_note.v1", + ) + + @staticmethod + def _rudp_note_put(document: Any, message_id: str, key: str, body_length: int) -> dict[str, Any]: + return document_put_raw( + message_id=message_id, + key=key, + schema_id=document.catalog_entry().schema_id, + stored_at="2026-09-30T00:00:00Z", + payload=document.encode_payload({"schema_version": "mesh.rudp_bound_note.v1", "body": "x" * body_length}), + ).to_wire() + + @staticmethod + def _rudp_exchange(server: Any, *messages: dict[str, Any]) -> tuple[dict[str, Any], bytes]: + """Sends each message over RUDP in 1200-byte fragments; returns the first reply.""" + transport = create_rudp_schema_transport( + host="127.0.0.1", + port=server.port, + connection_id=server.rudp_connection_id, + timeout_seconds=4.0, + max_fragment_bytes=1200, + ) + try: + for message in messages: + transport.send("schema", msgpack.packb(message, use_bin_type=True)) + payload = transport.receive(timeout_seconds=4.0).payload + finally: + transport.close() + return msgpack.unpackb(payload, raw=False), payload + + def test_cultmesh_local_server_serves_a_100_kb_put_over_rudp_in_fragments(self) -> None: + # The reply is larger than any one UDP datagram: it arrives only because it is sent + # in fragments, and the RUDP thread serves on afterwards. + document = self._rudp_bound_note() + node = CultMesh.create_node(runtime_id="mesh-rudp-large") + node.database.register_document(document) + server = CultMesh.serve_node(node) + try: + served, payload = self._rudp_exchange( + server, + self._rudp_note_put(document, "put-large", "note:large", 100_000), + snapshot_request(message_id="large").to_wire(), + ) + again, _ = self._rudp_exchange(server, snapshot_request(message_id="again").to_wire()) + alive = server._rudp_thread is not None and server._rudp_thread.is_alive() + finally: + server.stop() + self.assertEqual(served["schemaVersion"], "cultnet.snapshot_response_raw.v0") + self.assertEqual([record["recordKey"] for record in served["documents"]], ["note:large"]) + self.assertGreater(len(served["documents"][0]["payload"]), 100_000) + self.assertGreater(len(payload), 65_507, "fixture: the reply cannot be one UDP datagram") + self.assertEqual(again["messageId"], "again") + self.assertTrue(alive) + self.assertEqual(server.rudp_send_failures, 0) + + def test_cultmesh_local_server_refuses_a_rudp_put_whose_reply_would_overflow_the_reliable_queue(self) -> None: + # Replies go in fragments of 100 bytes and a peer's reliable queue holds 8: a put over RUDP + # whose served reply takes 8 fragments is admitted and served, 9 or 20 are refused. + document = self._rudp_bound_note() + + # The served size of a document alone under the empty message id, measured on an + # unbounded server: the bytes a snapshot actually sends. + def served_alone_bytes(body_length: int) -> int: + node = CultMesh.create_node(runtime_id="mesh-rudp-bound-probe") + node.database.register_document(document) + server = CultMesh.serve_node(node) + try: + _, payload = self._rudp_exchange( + server, self._rudp_note_put(document, "probe", "note:q", body_length), + snapshot_request(message_id="").to_wire(), + ) + finally: + server.stop() + return len(payload) + + probe = served_alone_bytes(500) + + def body_for(served_bytes: int) -> int: + body_length = 500 + served_bytes - probe + self.assertEqual(served_alone_bytes(body_length), served_bytes, "fixture: served size is linear in the body") + return body_length + + node = CultMesh.create_node(runtime_id="mesh-rudp-bound") + node.database.register_document(document) + server = CultMesh.serve_node(node, rudp_max_fragment_bytes=100, rudp_max_pending_reliable_packets=8) + try: + refusals = [ + self._rudp_exchange(server, self._rudp_note_put(document, f"put-{served}", "note:q", body_for(served)))[0] + for served in (2000, 801) + ] + stored_after_refusals = node.database.get(document, "note:q") + served, served_payload = self._rudp_exchange( + server, + self._rudp_note_put(document, "put-at", "note:q", body_for(800)), + snapshot_request(message_id="").to_wire(), + ) + alive = server._rudp_thread is not None and server._rudp_thread.is_alive() + finally: + server.stop() + + for refusal, (served_bytes, fragments) in zip(refusals, ((2000, 20), (801, 9))): + self.assertEqual(refusal["schemaVersion"], "cultnet.error.v0") + self.assertEqual(refusal["messageId"], f"put-{served_bytes}") + self.assertEqual(refusal["code"], "document_unservable") + self.assertEqual(refusal["details"], { + "responseBytes": served_bytes, + "maxSnapshotBytes": None, + "fragmentCount": fragments, + "maxFragmentCount": 8, + }) + self.assertIn(f"{served_bytes} bytes; it takes {fragments} fragments", refusal["error"]) + self.assertNotIn("note:q", refusal["error"]) + self.assertIsNone(stored_after_refusals) + self.assertEqual(served["schemaVersion"], "cultnet.snapshot_response_raw.v0") + self.assertEqual([record["recordKey"] for record in served["documents"]], ["note:q"]) + self.assertEqual(len(served_payload), 800) + self.assertTrue(alive) + + def test_cultmesh_local_server_rudp_thread_survives_a_datagram_that_cannot_leave(self) -> None: + # Fragments larger than any UDP datagram: the reply's one packet cannot be sent. That + # peer's loss is counted; the thread serves the next peer. + document = self._rudp_bound_note() + node = CultMesh.create_node(runtime_id="mesh-rudp-emsgsize") + node.database.register_document(document) + server = CultMesh.serve_node(node, rudp_max_fragment_bytes=200_000) + try: + transport = create_rudp_schema_transport( + host="127.0.0.1", port=server.port, connection_id=server.rudp_connection_id, + timeout_seconds=4.0, max_fragment_bytes=1200, + ) + try: + transport.send("schema", msgpack.packb(self._rudp_note_put(document, "put-large", "note:big", 80_000), use_bin_type=True)) + transport.send("schema", msgpack.packb(snapshot_request(message_id="big").to_wire(), use_bin_type=True)) + deadline = time.monotonic() + 4.0 + while server.rudp_send_failures == 0 and time.monotonic() < deadline: + transport.receive_once() + time.sleep(0.005) + finally: + transport.close() + failures = server.rudp_send_failures + hello_reply, _ = self._rudp_exchange(server, hello(runtime_id="after").to_wire()) + alive = server._rudp_thread is not None and server._rudp_thread.is_alive() + finally: + server.stop() + self.assertGreaterEqual(failures, 1) + self.assertEqual(hello_reply["schemaVersion"], "cultnet.hello.v0") + self.assertTrue(alive) + def test_cultmesh_local_server_returns_errors_for_bad_requests(self) -> None: document = define_database_entry_type( "mesh.error_note", From 66e439f4c8e2e452580b7f21951a8017fbe60dd2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 15:47:09 +0200 Subject: [PATCH 13/44] cultmesh-rs: the fragment-bound tests pump the client while they wait A put of 55 fragments leaves the client in flow-window steps, so the server hears it only while the client reads acknowledgements and resends. The helper that waits for a refusal or a stored put now pumps the client. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/tests/rudp_document_server.rs | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index 1aa24211..5465fbf3 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -257,13 +257,17 @@ fn serve_until_frame( anyhow::bail!("the client received no frame") } -/// Polls the server until it returns a rejection or the sink holds `receipts`. +/// Polls the server, and the client so its sends progress, until the server +/// returns a rejection or the sink holds `receipts`. fn poll_until_rejected_or_stored( server: &mut Server, + client: &mut CultNetRudpSocketTransportConnection, sink: &Sink, receipts: usize, ) -> Result> { for _ in 0..5_000 { + client.receive_once()?; + client.poll_resends()?; match server.poll_once()? { CultMeshRudpPollOutcome::ApplicationRejected(rejection) => { return Ok(Some(rejection.reason)); @@ -885,7 +889,7 @@ fn a_put_whose_response_would_overflow_the_reliable_queue_is_refused() -> Result document: document_served_at("queue", bytes)?, }, )?; - let reason = poll_until_rejected_or_stored(&mut server, &sink, 1)?; + let reason = poll_until_rejected_or_stored(&mut server, &mut refused, &sink, 1)?; assert_eq!(reason, unservable(bytes, fragments)); let sentence = reason.unwrap().to_string(); assert!( @@ -906,7 +910,10 @@ fn a_put_whose_response_would_overflow_the_reliable_queue_is_refused() -> Result document: at_bound.clone(), }, )?; - assert_eq!(poll_until_rejected_or_stored(&mut server, &sink, 1)?, None); + assert_eq!( + poll_until_rejected_or_stored(&mut server, &mut writer, &sink, 1)?, + None + ); source.0.lock().unwrap().documents = vec![at_bound.clone()]; send( &mut writer, @@ -952,7 +959,7 @@ fn a_put_whose_response_needs_more_than_65535_fragments_is_refused() -> Result<( }, )?; assert_eq!( - poll_until_rejected_or_stored(&mut server, &sink, 1)?, + poll_until_rejected_or_stored(&mut server, &mut refused, &sink, 1)?, Some(CultMeshRudpRejectionReason::DocumentUnservable { response_bytes: 65_536, max_snapshot_response_bytes: 70_000, @@ -970,7 +977,10 @@ fn a_put_whose_response_needs_more_than_65535_fragments_is_refused() -> Result<( document: document_served_at("wide", 65_535)?, }, )?; - assert_eq!(poll_until_rejected_or_stored(&mut server, &sink, 1)?, None); + assert_eq!( + poll_until_rejected_or_stored(&mut server, &mut writer, &sink, 1)?, + None + ); Ok(()) } From c5de65b875526f1bfedb62d7e890a4f3ff9419fa Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 15:47:10 +0200 Subject: [PATCH 14/44] cultmesh-ts: observe the peer's refusal as the frame it cannot yet parse A TypeScript peer refuses the two-key cultnet.error.v0 this server sends (missing routingHint, code and details; docs/cultnet-error-contract-cut.md), so it arrives as an invalidMessage, never a message. The served-bound rig records those, the refusal tests count them, and the refusal's text is asserted through onError, which receives the same error. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-ts/test/cultmesh.test.ts | 35 +++++++++++++--------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index 6f24bdff..006f6d83 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -3236,6 +3236,8 @@ type ServedBoundRig = { admitted: string[]; errors: Error[]; messages: CultNetMessage[]; + /** Why each frame the peer could not parse was refused. */ + unparsed: Error[]; }; const servedBoundRegistry = () => @@ -3297,6 +3299,7 @@ async function withServedBoundRig( const admitted: string[] = []; const errors: Error[] = []; const messages: CultNetMessage[] = []; + const unparsed: Error[] = []; const server = CultMesh.createRudpDocumentServer("cultmesh-ts-served-bound-server", connectionId, { documents: registry, getCache: () => node.cache, @@ -3335,7 +3338,8 @@ async function withServedBoundRig( { resendDelayMs: 25, resendPollMs: 5, maxFragmentBytes: 1024, maxPendingReliablePackets: 512, connectTimeoutMs: 1_000 }, ); peer.on("message", (message: CultNetMessage) => messages.push(message)); - await body({ server, peer, admitted, errors, messages }); + peer.on("invalidMessage", (error: Error) => unparsed.push(error)); + await body({ server, peer, admitted, errors, messages, unparsed }); } finally { peer?.close(); server.close(); @@ -3423,8 +3427,8 @@ test("CultMesh TS RUDP document server honours maxPayloadBytes for replies and j assert.equal(refusal.maxPayloadBytes, limit); assert.equal(refusal.fragmentCount, 4); assert.deepEqual(rig.admitted, []); - // The peer hears the refusal, and it names sizes, never the record. - assert.deepEqual(await waitForPeerErrors(rig, 1), [refusal.message]); + // The peer is sent the refusal, and it names sizes, never the record. + await waitForPeerErrors(rig, 1); assert.ok(!refusal.message.includes("note:ov"), refusal.message); // A put whose own frame is over the limit only by the provenance and message id it carries @@ -3439,8 +3443,9 @@ test("CultMesh TS RUDP document server honours maxPayloadBytes for replies and j // A record key longer than the limit: the refusal is still small enough to reach the peer. const longKey = `note:${"k".repeat(2 * limit)}`; rig.peer.send(notePut("put-long-key", longKey, 10)); - assert.equal((await waitForPeerErrors(rig, 2))[1], rig.errors[1]!.message); + await waitForPeerErrors(rig, 2); assert.ok(rig.errors[1] instanceof CultMeshRudpUnservableDocumentError, rig.errors[1]!.message); + assert.equal(rig.errors.length, 2, "the refusal itself was sent"); assert.deepEqual(rig.admitted, ["note:at"]); // Two servable documents make a reply over the limit: it is not sent, and onError hears why. @@ -3469,8 +3474,7 @@ test("CultMesh TS RUDP document server tells the peer when a stored put's receip // server's provenance and so is over the limit. The peer hears that it is not coming. rig.peer.send(notePut("put-at", "note:at", atBound)); await waitForAdmission(rig, "note:at"); - const [refusal] = await waitForPeerErrors(rig, 1); - assert.match(refusal!, /stored a put but could not send its receipt/); + await waitForPeerErrors(rig, 1); assert.equal(rig.errors.length, 1); assert.match(rig.errors[0]!.message, /reply cultnet\.document_put_raw\.v0 is \d+ bytes; maxPayloadBytes is 4000/); assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:at")), [["note:at", atBound]]); @@ -3481,15 +3485,18 @@ function isDocumentPut(message: CultNetMessage): boolean { return message.schemaVersion === "cultnet.document_put_raw.v0"; } -/** Waits until the peer has received `count` cultnet.error.v0 replies, and returns their text. */ -async function waitForPeerErrors(rig: ServedBoundRig, count: number): Promise { - const errors = () => rig.messages - .filter((message) => message.schemaVersion === "cultnet.error.v0") - .map((message) => (message as { error: string }).error); +/** + * Waits until the peer has been sent `count` cultnet.error.v0 replies. A TypeScript peer cannot + * yet parse the two-key error this server sends (docs/cultnet-error-contract-cut.md: + * "TypeScript cannot parse the errors TypeScript sends"), + * so each arrives as an unparsed cultnet.error.v0 frame; its text is asserted through onError. + */ +async function waitForPeerErrors(rig: ServedBoundRig, count: number): Promise { + const errors = () => rig.unparsed.filter((error) => /cultnet\.error\.v0/.test(error.message)).length + + rig.messages.filter((message) => message.schemaVersion === "cultnet.error.v0").length; const startedAt = Date.now(); - while (errors().length < count && Date.now() - startedAt < 3_000) await delay(5); - assert.equal(errors().length, count, `peer errors: ${errors().join("; ")}`); - return errors(); + while (errors() < count && Date.now() - startedAt < 3_000) await delay(5); + assert.equal(errors(), count, `peer errors: ${rig.unparsed.map((error) => error.message).join("; ")}`); } test("CultMesh TS RUDP document server reports a datagram that fails to leave", async () => { From 36cd169cd65ea4469ea6458d1e39f8f5e0c5b35b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 15:48:09 +0200 Subject: [PATCH 15/44] cultmesh-py: pin the 65535-fragment bound and a reply the queue cannot take A put over RUDP whose served reply needs 65536 one-byte fragments is refused and one that needs 65535 is stored. A snapshot of two documents each admitted at the queue's bound needs twice the queue: it is counted in rudp_send_failures, not sent, and the thread serves the next request. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-py/tests/test_cultmesh.py | 71 +++++++++++++++++++-- 1 file changed, 64 insertions(+), 7 deletions(-) diff --git a/packages/cultmesh-py/tests/test_cultmesh.py b/packages/cultmesh-py/tests/test_cultmesh.py index 51398c89..8e0eaaf1 100644 --- a/packages/cultmesh-py/tests/test_cultmesh.py +++ b/packages/cultmesh-py/tests/test_cultmesh.py @@ -4432,20 +4432,17 @@ class CultMeshTests(unittest.TestCase): self.assertTrue(alive) self.assertEqual(server.rudp_send_failures, 0) - def test_cultmesh_local_server_refuses_a_rudp_put_whose_reply_would_overflow_the_reliable_queue(self) -> None: - # Replies go in fragments of 100 bytes and a peer's reliable queue holds 8: a put over RUDP - # whose served reply takes 8 fragments is admitted and served, 9 or 20 are refused. - document = self._rudp_bound_note() + def _rudp_body_for(self, document: Any, key: str) -> Callable[[int], int]: + """The body length whose document, keyed `key`, is served alone under the empty message + id in exactly the given bytes, measured on an unbounded server: what a snapshot sends.""" - # The served size of a document alone under the empty message id, measured on an - # unbounded server: the bytes a snapshot actually sends. def served_alone_bytes(body_length: int) -> int: node = CultMesh.create_node(runtime_id="mesh-rudp-bound-probe") node.database.register_document(document) server = CultMesh.serve_node(node) try: _, payload = self._rudp_exchange( - server, self._rudp_note_put(document, "probe", "note:q", body_length), + server, self._rudp_note_put(document, "probe", key, body_length), snapshot_request(message_id="").to_wire(), ) finally: @@ -4459,6 +4456,16 @@ class CultMeshTests(unittest.TestCase): self.assertEqual(served_alone_bytes(body_length), served_bytes, "fixture: served size is linear in the body") return body_length + return body_for + + def test_cultmesh_local_server_refuses_a_rudp_put_whose_reply_would_overflow_the_reliable_queue(self) -> None: + # Replies go in fragments of 100 bytes and a peer's reliable queue holds 8: a put over RUDP + # whose served reply takes 8 fragments is admitted and served, 9 or 20 are refused. A + # snapshot of two such documents needs 16 and cannot be queued: that peer's loss, counted, + # and the thread serves on. + document = self._rudp_bound_note() + body_for = self._rudp_body_for(document, "note:q") + node = CultMesh.create_node(runtime_id="mesh-rudp-bound") node.database.register_document(document) server = CultMesh.serve_node(node, rudp_max_fragment_bytes=100, rudp_max_pending_reliable_packets=8) @@ -4473,6 +4480,22 @@ class CultMeshTests(unittest.TestCase): self._rudp_note_put(document, "put-at", "note:q", body_for(800)), snapshot_request(message_id="").to_wire(), ) + failures_before = server.rudp_send_failures + transport = create_rudp_schema_transport( + host="127.0.0.1", port=server.port, connection_id=server.rudp_connection_id, + timeout_seconds=4.0, max_fragment_bytes=1200, + ) + try: + transport.send("schema", msgpack.packb(self._rudp_note_put(document, "put-r", "note:r", body_for(800)), use_bin_type=True)) + transport.send("schema", msgpack.packb(snapshot_request(message_id="both").to_wire(), use_bin_type=True)) + deadline = time.monotonic() + 4.0 + while server.rudp_send_failures == failures_before and time.monotonic() < deadline: + transport.receive_once() + time.sleep(0.005) + finally: + transport.close() + failures_after = server.rudp_send_failures + hello_reply, _ = self._rudp_exchange(server, hello(runtime_id="after-queue").to_wire()) alive = server._rudp_thread is not None and server._rudp_thread.is_alive() finally: server.stop() @@ -4493,8 +4516,42 @@ class CultMeshTests(unittest.TestCase): self.assertEqual(served["schemaVersion"], "cultnet.snapshot_response_raw.v0") self.assertEqual([record["recordKey"] for record in served["documents"]], ["note:q"]) self.assertEqual(len(served_payload), 800) + self.assertEqual(failures_before, 0) + self.assertEqual(failures_after, 1) + self.assertEqual(hello_reply["schemaVersion"], "cultnet.hello.v0") self.assertTrue(alive) + def test_cultmesh_local_server_refuses_a_rudp_put_whose_reply_needs_more_than_65535_fragments(self) -> None: + # One message carries at most 65535 fragments, however deep the queue: with one-byte + # fragments a put served in 65536 bytes is refused, one served in 65535 is stored. + document = self._rudp_bound_note() + body_for = self._rudp_body_for(document, "note:w") + node = CultMesh.create_node(runtime_id="mesh-rudp-wide") + node.database.register_document(document) + server = CultMesh.serve_node(node, rudp_max_fragment_bytes=1) + try: + transport = create_rudp_schema_transport( + host="127.0.0.1", port=server.port, connection_id=server.rudp_connection_id, + timeout_seconds=4.0, max_fragment_bytes=1200, + ) + try: + transport.send("schema", msgpack.packb(self._rudp_note_put(document, "put-over", "note:w", body_for(65_536)), use_bin_type=True)) + refusal = msgpack.unpackb(transport.receive(timeout_seconds=8.0).payload, raw=False) + transport.send("schema", msgpack.packb(self._rudp_note_put(document, "put-at", "note:w", body_for(65_535)), use_bin_type=True)) + deadline = time.monotonic() + 4.0 + while node.database.get(document, "note:w") is None and time.monotonic() < deadline: + transport.receive_once() + time.sleep(0.005) + finally: + transport.close() + stored = node.database.get(document, "note:w") + finally: + server.stop() + self.assertEqual(refusal["code"], "document_unservable") + self.assertEqual(refusal["details"]["fragmentCount"], 65_536) + self.assertEqual(refusal["details"]["maxFragmentCount"], 65_535) + self.assertIsNotNone(stored) + def test_cultmesh_local_server_rudp_thread_survives_a_datagram_that_cannot_leave(self) -> None: # Fragments larger than any UDP datagram: the reply's one packet cannot be sent. That # peer's loss is counted; the thread serves the next peer. From 3cc081db0f6ca0427c9f0f89b819ec0e983f39ab Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 15:51:06 +0200 Subject: [PATCH 16/44] cultmesh-py: keep the generation test's replies whole; probe the small queue with an empty snapshot The generation test reads each server packet as one message, so its server now fragments only above 60000 bytes. The queue test's liveness probe is an empty snapshot: a hello reply needs more fragments than its eight-packet queue holds. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-py/tests/test_cultmesh.py | 7 +++++-- packages/cultmesh-py/tests/test_rudp_server_generation.py | 3 ++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/cultmesh-py/tests/test_cultmesh.py b/packages/cultmesh-py/tests/test_cultmesh.py index 8e0eaaf1..29e2b201 100644 --- a/packages/cultmesh-py/tests/test_cultmesh.py +++ b/packages/cultmesh-py/tests/test_cultmesh.py @@ -4495,7 +4495,10 @@ class CultMeshTests(unittest.TestCase): finally: transport.close() failures_after = server.rudp_send_failures - hello_reply, _ = self._rudp_exchange(server, hello(runtime_id="after-queue").to_wire()) + # An empty snapshot fits the small queue; a hello reply would not. + after_reply, _ = self._rudp_exchange( + server, snapshot_request(message_id="after-queue", record_keys=["note:none"]).to_wire() + ) alive = server._rudp_thread is not None and server._rudp_thread.is_alive() finally: server.stop() @@ -4518,7 +4521,7 @@ class CultMeshTests(unittest.TestCase): self.assertEqual(len(served_payload), 800) self.assertEqual(failures_before, 0) self.assertEqual(failures_after, 1) - self.assertEqual(hello_reply["schemaVersion"], "cultnet.hello.v0") + self.assertEqual(after_reply["messageId"], "after-queue") self.assertTrue(alive) def test_cultmesh_local_server_refuses_a_rudp_put_whose_reply_needs_more_than_65535_fragments(self) -> None: diff --git a/packages/cultmesh-py/tests/test_rudp_server_generation.py b/packages/cultmesh-py/tests/test_rudp_server_generation.py index 967a03c2..cd84c908 100644 --- a/packages/cultmesh-py/tests/test_rudp_server_generation.py +++ b/packages/cultmesh-py/tests/test_rudp_server_generation.py @@ -48,7 +48,8 @@ class RudpServerGenerationTests(unittest.TestCase): def setUp(self) -> None: node = create_node(runtime_id="rudp-generation") node.database.register_document(NOTE) - self.server = CultMeshLocalServer(node=node, rudp_connection_id=CONNECTION_ID) + # Replies stay whole datagrams here, so each server packet the pump reads is one message. + self.server = CultMeshLocalServer(node=node, rudp_connection_id=CONNECTION_ID, rudp_max_fragment_bytes=60_000) self.server.start() self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(("127.0.0.1", 0)) From ee593f392ead47a95b85bda66e9bec66874c3f92 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 16:02:16 +0200 Subject: [PATCH 17/44] cultmesh-rs: the snapshot source says what it would serve for a put CultMeshRudpSnapshotSource gains served_record: the record the source would serve for a received put's document. Admission sizes that record, so a source that serves another shape than it receives (dropping provenance, or adding its own, as Odin's presence records do) keeps admission exact by overriding it. The default serves the record as received, so existing sources, closures included, are unchanged. A source that fails to answer refuses the put as SnapshotSourceFailed. Tests: a stripping source admits a put that is over the bound only as received and serves it at exactly the bound; the existing at-bound fixture stays as the default-method test; a failing served_record refuses the put. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/src/rudp_document_server.rs | 41 +++-- .../cultmesh-rs/tests/rudp_document_server.rs | 165 +++++++++++++++++- 2 files changed, 192 insertions(+), 14 deletions(-) diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index fd671e95..24add376 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -75,6 +75,20 @@ pub trait CultMeshRudpSnapshotSource { &mut self, query: &CultMeshRudpSnapshotQuery, ) -> Result>; + + /// The record this source would serve for a received put's `document`. + /// + /// The server admits a put only if a snapshot response carrying this record + /// alone fits its limits, so a source that serves a different shape than it + /// receives (dropping provenance, or adding its own) overrides this to keep + /// admission exact. The default serves the record as received. An error + /// refuses the put as `SnapshotSourceFailed`. + fn served_record( + &mut self, + document: &CultNetRawDocumentRecord, + ) -> Result { + Ok(document.clone()) + } } impl CultMeshRudpSnapshotSource for F @@ -192,7 +206,8 @@ pub enum CultMeshRudpRejectionReason { /// The caller's sink refused the document. Carries the sink's error text. SinkRefused(String), /// The document could never be served: a snapshot response carrying it - /// alone, as received and under the shortest message id CultNet allows, would + /// alone, as the snapshot source would serve it (`served_record`) and under + /// the shortest message id CultNet allows, would /// exceed `max_snapshot_response_bytes`, or would take more than /// `max_fragment_count` fragments of `max_fragment_bytes`: the lesser of /// 65535 and `max_pending_reliable_packets_per_session`. It was not offered @@ -567,14 +582,21 @@ where })) }; // Admit only what some snapshot request can return: the smallest - // response that could carry this document is the document alone, as - // received, under the shortest message id CultNet encodes, sized by the - // snapshot path's encoder and fragmented as the snapshot path sends it. - // The snapshot source owns the served record's shape, so the record - // as received is the server's measure of it. + // response that could carry this document is the record the snapshot + // source would serve for it, alone, under the shortest message id + // CultNet encodes, sized by the snapshot path's encoder and fragmented + // as the snapshot path sends it. + let served = match self.snapshot_source.served_record(&document) { + Ok(served) => served, + Err(error) => { + return reject(CultMeshRudpRejectionReason::SnapshotSourceFailed( + format!("{error:#}"), + )); + } + }; let alone = CultNetMessage::SnapshotResponseRaw { message_id: SHORTEST_MESSAGE_ID.into(), - documents: vec![document], + documents: vec![served], }; let response_bytes = match encode_snapshot_response(&alone) { Ok(payload) => payload.len(), @@ -594,15 +616,12 @@ where max_fragment_count, }); } - let CultNetMessage::SnapshotResponseRaw { mut documents, .. } = alone else { - unreachable!("constructed as a snapshot response above"); - }; let receipt = CultMeshRudpRawDocumentReceipt { session: key, message_id: message_id.clone(), transport_sequence, received_at_unix_millis: now_unix, - document: documents.remove(0), + document, }; if let Err(error) = self.sink.accept_raw_document(receipt) { return reject(CultMeshRudpRejectionReason::SinkRefused(format!( diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index 5465fbf3..e3e9385a 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -53,6 +53,10 @@ struct SourceState { documents: Vec, failures_remaining: usize, calls: usize, + /// Serves records without source provenance, and says so to admission. + strips_provenance: bool, + /// Refuses to say what it would serve. + served_record_fails: bool, } #[derive(Clone, Default)] @@ -70,9 +74,27 @@ impl Source { Self(Arc::new(Mutex::new(SourceState { documents, failures_remaining: 1, - calls: 0, + ..Default::default() }))) } + + fn stripping() -> Self { + Self(Arc::new(Mutex::new(SourceState { + strips_provenance: true, + ..Default::default() + }))) + } +} + +/// `document` without the source provenance a peer reports about itself. +fn stripped(document: &CultNetRawDocumentRecord) -> CultNetRawDocumentRecord { + CultNetRawDocumentRecord { + source_runtime_id: None, + source_agent_id: None, + source_role: None, + tags: None, + ..document.clone() + } } impl CultMeshRudpSnapshotSource for Source { @@ -86,7 +108,27 @@ impl CultMeshRudpSnapshotSource for Source { state.failures_remaining -= 1; anyhow::bail!("injected source failure"); } - Ok(state.documents.clone()) + let documents = state.documents.clone(); + Ok(if state.strips_provenance { + documents.iter().map(stripped).collect() + } else { + documents + }) + } + + fn served_record( + &mut self, + document: &CultNetRawDocumentRecord, + ) -> Result { + let state = self.0.lock().unwrap(); + if state.served_record_fails { + anyhow::bail!("injected served-record failure"); + } + Ok(if state.strips_provenance { + stripped(document) + } else { + document.clone() + }) } } @@ -734,7 +776,8 @@ fn payload_and_snapshot_output_budgets_fail_closed() -> Result<()> { /// A put is admitted only if some snapshot request could return it. One byte /// over the served bound is refused before the sink sees it; exactly at the -/// bound is admitted, and a snapshot then serves it at exactly that size. +/// bound is admitted, and a snapshot then serves it at exactly that size. The +/// source keeps the default `served_record`, so the record is sized as received. #[test] fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served() -> Result<()> { let at_bound = document("fit", vec![7; 100]); @@ -854,6 +897,122 @@ fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served( Ok(()) } +/// A source that serves records without provenance says so through +/// `served_record`, and admission sizes that: a put over the bound only in its +/// received form is admitted and served at exactly the bound. +#[test] +fn a_put_is_sized_as_its_source_would_serve_it() -> Result<()> { + let provenance = |mut document: CultNetRawDocumentRecord| { + document.source_agent_id = Some("provenance-agent-that-is-not-served".into()); + document.source_role = Some("provenance-role".into()); + document.tags = Some(vec!["provenance".into(), "tags".into()]); + document + }; + let at_bound = provenance(document("fit", vec![7; 100])); + let over_bound = provenance(document("fit", vec![7; 101])); + let limit = served_alone_bytes(&stripped(&at_bound))?; + assert_eq!( + served_alone_bytes(&stripped(&over_bound))?, + limit + 1, + "fixture: the two documents must straddle the bound by one byte as served" + ); + assert!( + served_alone_bytes(&at_bound)? > limit + 1, + "fixture: the at-bound put is over the bound as received" + ); + let options = CultMeshRudpDocumentServerOptions { + max_snapshot_response_bytes: limit, + ..Default::default() + }; + let sink = Sink::default(); + let source = Source::stripping(); + let mut server = server(options, Clock::new(64_000), sink.clone(), source.clone())?; + let target = server.local_addr()?; + + let mut refused = client(target, 151)?; + connect(&mut server, &mut [&mut refused])?; + send( + &mut refused, + &CultNetMessage::DocumentPutRaw { + message_id: "put-over".into(), + document: over_bound, + }, + )?; + assert_eq!( + poll_until_rejected_or_stored(&mut server, &mut refused, &sink, 1)?, + Some(CultMeshRudpRejectionReason::DocumentUnservable { + response_bytes: limit + 1, + max_snapshot_response_bytes: limit, + fragment_count: 1, + max_fragment_count: 1024, + }) + ); + + let mut writer = client(target, 152)?; + connect(&mut server, &mut [&mut writer])?; + send( + &mut writer, + &CultNetMessage::DocumentPutRaw { + message_id: "put-at".into(), + document: at_bound.clone(), + }, + )?; + assert_eq!( + poll_until_rejected_or_stored(&mut server, &mut writer, &sink, 1)?, + None + ); + assert_eq!( + sink.0.lock().unwrap().receipts[0].document, + at_bound, + "the sink receives the record as it was sent" + ); + source.0.lock().unwrap().documents = vec![at_bound.clone()]; + send( + &mut writer, + &CultNetMessage::SnapshotRequest { + message_id: "r".into(), + schema_ids: None, + record_keys: None, + }, + )?; + let served = serve_until_frame(&mut server, &mut writer)?; + assert_eq!(served.len(), limit); + assert_eq!( + decode_cultnet_message_from_slice(&served, CultNetWireContract::CultNetSchemaV0)?, + CultNetMessage::SnapshotResponseRaw { + message_id: "r".into(), + documents: vec![stripped(&at_bound)], + } + ); + Ok(()) +} + +/// A source that cannot say what it would serve refuses the put. +#[test] +fn a_put_whose_served_record_the_source_cannot_give_is_refused() -> Result<()> { + let sink = Sink::default(); + let source = Source::default(); + source.0.lock().unwrap().served_record_fails = true; + let mut server = server(Default::default(), Clock::new(65_000), sink.clone(), source)?; + let mut refused = client(server.local_addr()?, 161)?; + connect(&mut server, &mut [&mut refused])?; + send( + &mut refused, + &CultNetMessage::DocumentPutRaw { + message_id: "put".into(), + document: document("unsized", vec![1, 2, 3]), + }, + )?; + assert_eq!( + poll_until_rejected_or_stored(&mut server, &mut refused, &sink, 1)?, + Some(CultMeshRudpRejectionReason::SnapshotSourceFailed( + "injected served-record failure".into() + )) + ); + assert!(sink.0.lock().unwrap().receipts.is_empty()); + Ok(()) +} + /// A put is admitted only if its served response fits the fragments one /// response may take: here eight of 100 bytes, the reliable queue, although the /// byte limit is far larger. Eight fragments are admitted and served; nine are From 6861b55db369567418c5d988c56722e6b1c5b547 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 16:04:01 +0200 Subject: [PATCH 18/44] cultnet-ts: the registry decodes the value a raw put would store CultNetDocumentRegistry.decodeRawDocumentPut returns the binding and value applyRawDocumentPutMessage would store for a raw put, so a server can build the receipt that would acknowledge a put before storing it. It throws, as the put would, when no binding accepts the document. Co-Authored-By: Claude Opus 5.5 --- packages/cultnet-ts/src/replication.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/cultnet-ts/src/replication.ts b/packages/cultnet-ts/src/replication.ts index a2eda250..6de103b6 100644 --- a/packages/cultnet-ts/src/replication.ts +++ b/packages/cultnet-ts/src/replication.ts @@ -268,6 +268,20 @@ export class CultNetDocumentRegistry { }; } + /** + * The binding and value `applyRawDocumentPutMessage` would store for this raw + * put, decoded as that binding reads it. A server uses it to build the reply + * that would acknowledge the put before storing it. Throws, as the put would, + * when no binding accepts the document. + */ + decodeRawDocumentPut(message: CultNetDocumentPutRawMessage): { + binding: CultNetDocumentBinding; + value: unknown; + } { + const { binding, envelope } = this.#rawPutEnvelope(message); + return { binding, value: decodeDocumentValue(binding.definition, envelope.payload) }; + } + #rawPutEnvelope(message: CultNetDocumentPutRawMessage): { binding: CultNetDocumentBinding; envelope: CultCacheEnvelope; From 9757ed54a58e46b3e58eb62ff505f1e2dde52aab Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 16:04:01 +0200 Subject: [PATCH 19/44] cultmesh-ts: a put is refused unless its receipt could be sent Admission now sizes two replies built from the record the registry would store: the snapshot reply serving it alone and the receipt echoing its value under the put's message id with the server's default provenance, through the one receipt builder the send path uses. A put whose larger reply exceeds maxPayloadBytes, 65535 fragments or the reliable queue is refused before onDocumentPutRaw, so a stored put always gets its receipt when the application stores through the registry and echoes that value. The existing fallback (a receipt that cannot be sent all the same reaches onError, and the peer a cultnet.error.v0) stays for handlers that acknowledge something larger. The served-bound fixtures carry a long storedAt, which the served record keeps and the receipt replaces, so they still pin the served bound; a new test pins the receipt bound: one byte over is refused, exactly at the limit is stored and receipted. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-ts/src/index.ts | 83 +++++++++------ packages/cultmesh-ts/test/cultmesh.test.ts | 114 +++++++++++++++++---- 2 files changed, 142 insertions(+), 55 deletions(-) diff --git a/packages/cultmesh-ts/src/index.ts b/packages/cultmesh-ts/src/index.ts index 6da497e7..d3972cac 100644 --- a/packages/cultmesh-ts/src/index.ts +++ b/packages/cultmesh-ts/src/index.ts @@ -4289,19 +4289,22 @@ export interface CultMeshRudpDocumentReceipt encodeSchemaMessage(reply).byteLength)); const fragmentCount = Math.max(1, Math.ceil(responseBytes / maxFragmentBytes)); if ((maxPayloadBytes === undefined || responseBytes <= maxPayloadBytes) && fragmentCount <= maxReplyFragments) { diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index 006f6d83..8167e41d 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -3243,11 +3243,21 @@ type ServedBoundRig = { const servedBoundRegistry = () => new CultNetDocumentRegistry([defineCultNetDocumentBinding({ definition: noteDocument })]); +/** + * A put's own storedAt, kept by the served record and replaced in the receipt by the server's + * 24-character clock. It is long enough that the snapshot reply is always the larger reply, so + * fixtures built with it pin the served bound; `RECEIPT_STORED_AT` puts pin the receipt bound. + */ +const SERVED_STORED_AT = `2026-09-30T00:00:00.000Z${"~".repeat(200)}`; +const RECEIPT_STORED_AT = "2026-09-30T00:00:00.000Z"; +const SERVED_BOUND_SERVER = "cultmesh-ts-served-bound-server"; + function notePut( messageId: string, recordKey: string, bodyLength: number, sourceRuntimeId?: string, + storedAt = SERVED_STORED_AT, ): CultNetDocumentPutRawMessage { return { schemaVersion: "cultnet.document_put_raw.v0", @@ -3255,7 +3265,7 @@ function notePut( document: { schemaId: "cultmesh.note.v0", recordKey, - storedAt: "2026-09-30T00:00:00.000Z", + storedAt, payloadEncoding: "messagepack", payload: encode({ noteId: recordKey, body: "x".repeat(bodyLength) }), ...(sourceRuntimeId ? { sourceRuntimeId } : {}), @@ -3277,11 +3287,46 @@ function servedAloneBytes(put: CultNetDocumentPutRawMessage): number { }).byteLength; } -/** The body length whose served-alone reply is exactly `bytes`, with a guard. */ +/** + * The encoded size of the receipt that would acknowledge this put by echoing its value: the + * put's message id, the server's clock and its default provenance. Spelled out here rather than + * asked of the server, so a server that sized another receipt is caught. + */ +function echoReceiptBytes(put: CultNetDocumentPutRawMessage): number { + return encode({ + schemaVersion: "cultnet.document_put_raw.v0", + messageId: put.messageId, + document: { + schemaId: "cultmesh.note.v0", + recordKey: put.document.recordKey, + storedAt: new Date().toISOString(), + payloadEncoding: "messagepack", + payload: encode(decode(put.document.payload)), + sourceRuntimeId: SERVED_BOUND_SERVER, + sourceAgentId: undefined, + sourceRole: "provider", + tags: ["receipt"], + }, + }).byteLength; +} + +/** The body length whose served-alone reply is exactly `bytes`, and the larger reply. */ function bodyLengthForReplyBytes(recordKey: string, bytes: number): number { const probe = 8_000; const length = probe + bytes - servedAloneBytes(notePut("p", recordKey, probe)); - assert.equal(servedAloneBytes(notePut("p", recordKey, length)), bytes, "fixture: reply size is linear in the body"); + const put = notePut("p", recordKey, length); + assert.equal(servedAloneBytes(put), bytes, "fixture: reply size is linear in the body"); + assert.ok(echoReceiptBytes(put) < bytes, "fixture: the snapshot reply is the larger reply"); + return length; +} + +/** The body length whose echoed receipt, under `messageId`, is exactly `bytes`, and the larger reply. */ +function bodyLengthForReceiptBytes(messageId: string, recordKey: string, bytes: number): number { + const put = (body: number) => notePut(messageId, recordKey, body, undefined, RECEIPT_STORED_AT); + const probe = 2_000; + const length = probe + bytes - echoReceiptBytes(put(probe)); + assert.equal(echoReceiptBytes(put(length)), bytes, "fixture: receipt size is linear in the body"); + assert.ok(servedAloneBytes(put(length)) < bytes, "fixture: the receipt is the larger reply"); return length; } @@ -3289,7 +3334,7 @@ async function withServedBoundRig( connectionId: number, serverLimits: { maxFragmentBytes?: number; maxPendingReliablePackets?: number; maxPayloadBytes?: number }, body: (rig: ServedBoundRig) => Promise, - handler: { echoReceipt?: boolean } = {}, + handler: { receipt?: "echo" | "oversized" } = {}, ): Promise { const node = await CultMesh.startNode( join(await mkdtemp(join(tmpdir(), "cultmesh-ts-served-bound-")), "node.ccmp"), @@ -3300,7 +3345,7 @@ async function withServedBoundRig( const errors: Error[] = []; const messages: CultNetMessage[] = []; const unparsed: Error[] = []; - const server = CultMesh.createRudpDocumentServer("cultmesh-ts-served-bound-server", connectionId, { + const server = CultMesh.createRudpDocumentServer(SERVED_BOUND_SERVER, connectionId, { documents: registry, getCache: () => node.cache, bindHost: "127.0.0.1", @@ -3322,9 +3367,15 @@ async function withServedBoundRig( payload: encode(document.payload), }, }); - return handler.echoReceipt - ? { binding: defineCultNetDocumentBinding({ definition: noteDocument }), recordKey: document.recordKey, value: document.payload as { noteId: string; body: string } } - : undefined; + if (!handler.receipt) return undefined; + // An echo acknowledges the stored value, as admission sizes it; an oversized receipt + // carries more than admission could know of. + return { + binding: defineCultNetDocumentBinding({ definition: noteDocument }), + recordKey: document.recordKey, + value: document.payload as { noteId: string; body: string }, + ...(handler.receipt === "oversized" ? { tags: ["x".repeat(8_000)] } : {}), + }; }, onError: (error) => errors.push(error), }); @@ -3431,9 +3482,9 @@ test("CultMesh TS RUDP document server honours maxPayloadBytes for replies and j await waitForPeerErrors(rig, 1); assert.ok(!refusal.message.includes("note:ov"), refusal.message); - // A put whose own frame is over the limit only by the provenance and message id it carries - // is served at the bound, so it is admitted and served. - const carried = notePut(`put-at-${"m".repeat(200)}`, "note:at", atBound, `runtime-${"r".repeat(200)}`); + // A put whose own frame is over the limit only by the provenance it carries is served at the + // bound, so it is admitted and served. + const carried = notePut("put-at", "note:at", atBound, `runtime-${"r".repeat(200)}`); assert.ok(encode(carried).byteLength > limit, "fixture: the put's frame is over the limit"); rig.peer.send(carried); await waitForAdmission(rig, "note:at"); @@ -3459,26 +3510,45 @@ test("CultMesh TS RUDP document server honours maxPayloadBytes for replies and j }); }); +test("CultMesh TS RUDP document server refuses a put whose receipt could not be sent", async () => { + // The receipt is the larger reply here: a put whose receipt is one byte over the limit is + // refused before it is stored; one whose receipt is exactly at the limit is stored and gets it. + const limit = 4_000; + const overBound = bodyLengthForReceiptBytes("put-ov", "note:ro", limit + 1); + const atBound = bodyLengthForReceiptBytes("put-at", "note:ra", limit); + await withServedBoundRig(0x10203065, { maxFragmentBytes: 1024, maxPayloadBytes: limit }, async (rig) => { + rig.peer.send(notePut("put-ov", "note:ro", overBound, undefined, RECEIPT_STORED_AT)); + const refusal = await waitForError(rig, "the put whose receipt is over the limit"); + assert.ok(refusal instanceof CultMeshRudpUnservableDocumentError, refusal.message); + assert.equal(refusal.responseBytes, limit + 1); + assert.equal(refusal.maxPayloadBytes, limit); + assert.deepEqual(rig.admitted, []); + await waitForPeerErrors(rig, 1); + + rig.peer.send(notePut("put-at", "note:ra", atBound, undefined, RECEIPT_STORED_AT)); + await waitForAdmission(rig, "note:ra"); + const startedAt = Date.now(); + while (!rig.messages.some(isDocumentPut) && Date.now() - startedAt < 3_000) await delay(5); + const receipt = rig.messages.find(isDocumentPut) as CultNetDocumentPutRawMessage | undefined; + assert.equal(receipt?.messageId, "put-at", "the stored put gets its receipt"); + assert.equal(rig.errors.length, 1); + }, { receipt: "echo" }); +}); + test("CultMesh TS RUDP document server tells the peer when a stored put's receipt cannot be sent", async () => { + // A handler whose receipt is larger than the echo admission sized: the put is stored, the + // receipt cannot be sent, and the peer hears that it is not coming. const limit = 4_000; const small = bodyLengthForReplyBytes("note:small", 1_000); - const atBound = bodyLengthForReplyBytes("note:at", limit); await withServedBoundRig(0x10203064, { maxFragmentBytes: 1024, maxPayloadBytes: limit }, async (rig) => { rig.peer.send(notePut("put-small", "note:small", small)); await waitForAdmission(rig, "note:small"); - const startedAt = Date.now(); - while (!rig.messages.some(isDocumentPut) && Date.now() - startedAt < 3_000) await delay(5); - assert.ok(rig.messages.some(isDocumentPut), "a receipt that fits is sent"); - - // Served at the bound, the put is admitted and stored; its echoed receipt carries the - // server's provenance and so is over the limit. The peer hears that it is not coming. - rig.peer.send(notePut("put-at", "note:at", atBound)); - await waitForAdmission(rig, "note:at"); await waitForPeerErrors(rig, 1); assert.equal(rig.errors.length, 1); assert.match(rig.errors[0]!.message, /reply cultnet\.document_put_raw\.v0 is \d+ bytes; maxPayloadBytes is 4000/); - assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:at")), [["note:at", atBound]]); - }, { echoReceipt: true }); + assert.ok(!rig.messages.some(isDocumentPut)); + assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:small")), [["note:small", small]]); + }, { receipt: "oversized" }); }); function isDocumentPut(message: CultNetMessage): boolean { From 5ab0f9d337fb10e1c05b515b52542ad3e145eecb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 16:11:15 +0200 Subject: [PATCH 20/44] cultmesh-rs: the at-bound fixture exercises the default served_record The test Source overrode served_record in both modes, so no test ran the trait's default and a default that stripped provenance survived. Source now keeps the default, which the at-bound fixture pins (the record as received); a separate StrippingSource overrides it for the stripping and failing-source tests. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/tests/rudp_document_server.rs | 81 +++++++++++-------- 1 file changed, 47 insertions(+), 34 deletions(-) diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index e3e9385a..c8ae3273 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -53,10 +53,6 @@ struct SourceState { documents: Vec, failures_remaining: usize, calls: usize, - /// Serves records without source provenance, and says so to admission. - strips_provenance: bool, - /// Refuses to say what it would serve. - served_record_fails: bool, } #[derive(Clone, Default)] @@ -77,13 +73,6 @@ impl Source { ..Default::default() }))) } - - fn stripping() -> Self { - Self(Arc::new(Mutex::new(SourceState { - strips_provenance: true, - ..Default::default() - }))) - } } /// `document` without the source provenance a peer reports about itself. @@ -108,30 +97,52 @@ impl CultMeshRudpSnapshotSource for Source { state.failures_remaining -= 1; anyhow::bail!("injected source failure"); } - let documents = state.documents.clone(); - Ok(if state.strips_provenance { - documents.iter().map(stripped).collect() - } else { - documents - }) + Ok(state.documents.clone()) + } +} + +/// A source that serves `Source`'s records without source provenance, and says +/// so to admission through `served_record`. `Source` keeps the default. +#[derive(Clone, Default)] +struct StrippingSource { + inner: Source, + /// Refuses to say what it would serve. + served_record_fails: bool, +} + +impl CultMeshRudpSnapshotSource for StrippingSource { + fn raw_snapshot( + &mut self, + query: &CultMeshRudpSnapshotQuery, + ) -> Result> { + Ok(self.inner.raw_snapshot(query)?.iter().map(stripped).collect()) } fn served_record( &mut self, document: &CultNetRawDocumentRecord, ) -> Result { - let state = self.0.lock().unwrap(); - if state.served_record_fails { + if self.served_record_fails { anyhow::bail!("injected served-record failure"); } - Ok(if state.strips_provenance { - stripped(document) - } else { - document.clone() - }) + Ok(stripped(document)) } } +fn stripping_server( + options: CultMeshRudpDocumentServerOptions, + sink: Sink, + source: StrippingSource, +) -> Result> { + CultMeshRudpDocumentServer::new( + UdpSocket::bind("127.0.0.1:0")?, + sink, + source, + Clock::new(64_000), + options, + ) +} + #[derive(Clone)] struct Clock { unix: Arc, @@ -281,8 +292,8 @@ fn document_served_at(key: &str, bytes: usize) -> Result( + server: &mut CultMeshRudpDocumentServer, client: &mut CultNetRudpSocketTransportConnection, ) -> Result> { for _ in 0..2_000 { @@ -301,8 +312,8 @@ fn serve_until_frame( /// Polls the server, and the client so its sends progress, until the server /// returns a rejection or the sink holds `receipts`. -fn poll_until_rejected_or_stored( - server: &mut Server, +fn poll_until_rejected_or_stored( + server: &mut CultMeshRudpDocumentServer, client: &mut CultNetRudpSocketTransportConnection, sink: &Sink, receipts: usize, @@ -925,8 +936,8 @@ fn a_put_is_sized_as_its_source_would_serve_it() -> Result<()> { ..Default::default() }; let sink = Sink::default(); - let source = Source::stripping(); - let mut server = server(options, Clock::new(64_000), sink.clone(), source.clone())?; + let source = StrippingSource::default(); + let mut server = stripping_server(options, sink.clone(), source.clone())?; let target = server.local_addr()?; let mut refused = client(target, 151)?; @@ -966,7 +977,7 @@ fn a_put_is_sized_as_its_source_would_serve_it() -> Result<()> { at_bound, "the sink receives the record as it was sent" ); - source.0.lock().unwrap().documents = vec![at_bound.clone()]; + source.inner.0.lock().unwrap().documents = vec![at_bound.clone()]; send( &mut writer, &CultNetMessage::SnapshotRequest { @@ -991,9 +1002,11 @@ fn a_put_is_sized_as_its_source_would_serve_it() -> Result<()> { #[test] fn a_put_whose_served_record_the_source_cannot_give_is_refused() -> Result<()> { let sink = Sink::default(); - let source = Source::default(); - source.0.lock().unwrap().served_record_fails = true; - let mut server = server(Default::default(), Clock::new(65_000), sink.clone(), source)?; + let source = StrippingSource { + served_record_fails: true, + ..Default::default() + }; + let mut server = stripping_server(Default::default(), sink.clone(), source)?; let mut refused = client(server.local_addr()?, 161)?; connect(&mut server, &mut [&mut refused])?; send( From d9d4b32ded7943b7b16e8ecd9d3645693beb8f10 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 16:20:22 +0200 Subject: [PATCH 21/44] cultmesh-rs: connect() takes a server over any snapshot source The previous commit's tests did not compile: connect() was typed to the default Source. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-rs/tests/rudp_document_server.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index c8ae3273..1a726570 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -241,8 +241,8 @@ fn client_on( }) } -fn connect( - server: &mut Server, +fn connect( + server: &mut CultMeshRudpDocumentServer, clients: &mut [&mut CultNetRudpSocketTransportConnection], ) -> Result<()> { for client in &mut *clients { From d04d71e8988bce42f5f0e8049a5d2fc10b24e3c1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 17:41:19 +0200 Subject: [PATCH 22/44] cultmesh-py: refuse options that could answer nothing, as Rust does With one-byte fragments and a reliable queue of 16, even an empty snapshot can never be queued: every reply vanished while rudp_send_failures counted, and the peer timed out. Rust refuses such a configuration at startup in validate_options; Python's __post_init__ accepted it. __post_init__ now applies Rust's rules to every option the two servers share, in Rust's order: max_snapshot_bytes, max_snapshot_documents, rudp_resend_delay_ms, rudp_max_pending_reliable_packets and rudp_max_fragment_bytes must be greater than zero (the first two when set; zero was accepted before), max_snapshot_bytes must hold an empty snapshot response, and an empty snapshot response in fragments of rudp_max_fragment_bytes, counted rounding up, must fit the lesser of 65535 and the reliable queue. Rust's session, lifetime and payload-budget rules have no Python option to apply to. The test measures the empty snapshot the server actually sends, pins each rule at its boundary, and shows the configuration at the bound does answer. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-py/src/cultmesh_py/server.py | 42 ++++++++++---- packages/cultmesh-py/tests/test_cultmesh.py | 55 +++++++++++++++++++ 2 files changed, 87 insertions(+), 10 deletions(-) diff --git a/packages/cultmesh-py/src/cultmesh_py/server.py b/packages/cultmesh-py/src/cultmesh_py/server.py index daf0ed6c..4165577b 100644 --- a/packages/cultmesh-py/src/cultmesh_py/server.py +++ b/packages/cultmesh-py/src/cultmesh_py/server.py @@ -9,6 +9,7 @@ from typing import Any import msgpack from cultnet_py import ( + CultNetRawSnapshotResponse, CultNetSimulationObservationHub, CultNetRudpPacket, CultNetRudpPacketType, @@ -98,14 +99,38 @@ class CultMeshLocalServer: return self._rudp_send_failures def __post_init__(self) -> None: - if self.max_snapshot_documents is not None and self.max_snapshot_documents < 0: - raise ValueError("max_snapshot_documents must be non-negative") - if self.max_snapshot_bytes is not None and self.max_snapshot_bytes < 0: - raise ValueError("max_snapshot_bytes must be non-negative") - if self.rudp_max_fragment_bytes <= 0: - raise ValueError("rudp_max_fragment_bytes must be greater than zero") + # The Rust document server's option rules (validate_options), for each option this + # server shares with it: every limit is greater than zero, and the limits leave room for + # the smallest response the server sends, an empty snapshot. A server that could answer + # nothing is misconfigured. + if self.max_snapshot_bytes is not None and self.max_snapshot_bytes <= 0: + raise ValueError("max_snapshot_bytes must be greater than zero") + if self.max_snapshot_documents is not None and self.max_snapshot_documents <= 0: + raise ValueError("max_snapshot_documents must be greater than zero") + if self.rudp_resend_delay_ms <= 0: + raise ValueError("rudp_resend_delay_ms must be greater than zero") if self.rudp_max_pending_reliable_packets is not None and self.rudp_max_pending_reliable_packets <= 0: raise ValueError("rudp_max_pending_reliable_packets must be greater than zero") + if self.rudp_max_fragment_bytes <= 0: + raise ValueError("rudp_max_fragment_bytes must be greater than zero") + empty = _snapshot_response_bytes( + CultNetRawSnapshotResponse(message_id=_SHORTEST_SERVED_MESSAGE_ID, documents=()).to_wire() + ) + if self.max_snapshot_bytes is not None and empty > self.max_snapshot_bytes: + raise ValueError("max_snapshot_bytes cannot hold an empty snapshot response") + if -(-empty // self.rudp_max_fragment_bytes) > self._max_rudp_reply_fragments(): + raise ValueError( + "rudp_max_fragment_bytes and rudp_max_pending_reliable_packets cannot carry an empty " + "snapshot response" + ) + + def _max_rudp_reply_fragments(self) -> int: + """The most fragments one RUDP reply can take: one message's fragment count, and the + peer's reliable queue it must fit into whole.""" + return min( + _MAX_FRAGMENTS_PER_MESSAGE, + self.rudp_max_pending_reliable_packets or _MAX_FRAGMENTS_PER_MESSAGE, + ) def start(self) -> "CultMeshLocalServer": if self._socket is not None: @@ -633,10 +658,7 @@ class CultMeshLocalServer: limits = f"limit is {self.max_snapshot_bytes}" if over_rudp: fragment_count = max(1, -(-response_bytes // self.rudp_max_fragment_bytes)) - max_fragment_count = min( - _MAX_FRAGMENTS_PER_MESSAGE, - self.rudp_max_pending_reliable_packets or _MAX_FRAGMENTS_PER_MESSAGE, - ) + max_fragment_count = self._max_rudp_reply_fragments() details |= {"fragmentCount": fragment_count, "maxFragmentCount": max_fragment_count} fits = fits and fragment_count <= max_fragment_count limits = ( diff --git a/packages/cultmesh-py/tests/test_cultmesh.py b/packages/cultmesh-py/tests/test_cultmesh.py index 29e2b201..52191292 100644 --- a/packages/cultmesh-py/tests/test_cultmesh.py +++ b/packages/cultmesh-py/tests/test_cultmesh.py @@ -4585,6 +4585,61 @@ class CultMeshTests(unittest.TestCase): self.assertEqual(hello_reply["schemaVersion"], "cultnet.hello.v0") self.assertTrue(alive) + def test_cultmesh_local_server_refuses_options_that_could_answer_nothing(self) -> None: + # The Rust document server's option rules: every limit is greater than zero, and the limits + # leave room for an empty snapshot, the smallest response the server sends. One-byte + # fragments and a queue of 16 could never carry one, so no reply would ever be sent. + node = CultMesh.create_node(runtime_id="mesh-rudp-options") + probe = CultMesh.serve_node(node) + try: + _, empty_payload = self._rudp_exchange(probe, snapshot_request(message_id="").to_wire()) + finally: + probe.stop() + empty = len(empty_payload) + self.assertGreater(empty, 16, "fixture: an empty snapshot takes more than 16 one-byte fragments") + self.assertNotEqual(empty % (empty - 1), 0, "fixture: empty - 1 byte fragments leave a remainder") + + def refused(**options: Any) -> str: + server = None + try: + with self.assertRaises(ValueError, msg=str(options)) as raised: + server = CultMesh.serve_node(node, **options) + finally: + if server is not None: + server.stop() + return str(raised.exception) + + def accepted(**options: Any) -> None: + CultMesh.serve_node(node, **options).stop() + + carry = "cannot carry an empty snapshot response" + self.assertIn(carry, refused(rudp_max_fragment_bytes=1, rudp_max_pending_reliable_packets=16)) + self.assertIn(carry, refused(rudp_max_fragment_bytes=1, rudp_max_pending_reliable_packets=empty - 1)) + accepted(rudp_max_fragment_bytes=1, rudp_max_pending_reliable_packets=empty) + # Fragments are counted rounding up: empty - 1 bytes a fragment takes two. + self.assertIn(carry, refused(rudp_max_fragment_bytes=empty - 1, rudp_max_pending_reliable_packets=1)) + accepted(rudp_max_fragment_bytes=empty - 1, rudp_max_pending_reliable_packets=2) + self.assertIn("cannot hold an empty snapshot response", refused(max_snapshot_bytes=empty - 1)) + accepted(max_snapshot_bytes=empty) + self.assertIn("greater than zero", refused(max_snapshot_bytes=0)) + self.assertIn("greater than zero", refused(max_snapshot_documents=0)) + accepted(max_snapshot_documents=1) + self.assertIn("greater than zero", refused(rudp_resend_delay_ms=0)) + accepted(rudp_resend_delay_ms=1) + self.assertIn("greater than zero", refused(rudp_max_fragment_bytes=0)) + self.assertIn("greater than zero", refused(rudp_max_pending_reliable_packets=0)) + + # The configuration at the bound does answer: an empty snapshot in one-byte fragments, + # exactly as many as the queue holds. + server = CultMesh.serve_node(node, rudp_max_fragment_bytes=1, rudp_max_pending_reliable_packets=empty) + try: + served, payload = self._rudp_exchange(server, snapshot_request(message_id="").to_wire()) + finally: + server.stop() + self.assertEqual(served["documents"], []) + self.assertEqual(len(payload), empty) + self.assertEqual(server.rudp_send_failures, 0) + def test_cultmesh_local_server_returns_errors_for_bad_requests(self) -> None: document = define_database_entry_type( "mesh.error_note", From 1a173f60008f3f040e2ae83c5cb6d3cd3dc11449 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 17:42:43 +0200 Subject: [PATCH 23/44] cultmesh-py: a put that could never be stored is refused, not raised _unservable_put sized a put by building the envelope it would store, and that read document["recordKey"] and document["payload"] directly: a put over RUDP with no recordKey raised KeyError out of the RUDP loop and ended the thread for every peer. A string payload raised TypeError the same way. _unservable_put now refuses a put whose document lacks a string recordKey or a binary payload as malformed_document_put, the code the server already uses for a put with no document map, before any sizing reads it and before its early return, so the TCP path refuses it too instead of raising in apply_raw_put_message. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-py/src/cultmesh_py/server.py | 14 +++++++- packages/cultmesh-py/tests/test_cultmesh.py | 35 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/packages/cultmesh-py/src/cultmesh_py/server.py b/packages/cultmesh-py/src/cultmesh_py/server.py index 4165577b..591a6f46 100644 --- a/packages/cultmesh-py/src/cultmesh_py/server.py +++ b/packages/cultmesh-py/src/cultmesh_py/server.py @@ -646,7 +646,19 @@ class CultMeshLocalServer: """The refusal for a put this server could never serve, or None. The document alone, as a snapshot would serve it under the shortest message id, must fit max_snapshot_bytes; a put arriving over RUDP must also fit, as fragments of rudp_max_fragment_bytes, in one - message and the peer's reliable queue.""" + message and the peer's reliable queue. A put whose document has no string recordKey or + binary payload could never be stored or served, and is refused as malformed.""" + document_record = message.get("document") + if not ( + isinstance(document_record, dict) + and isinstance(document_record.get("recordKey"), str) + and isinstance(document_record.get("payload"), (bytes, bytearray)) + ): + return self._error_response( + "Raw put documents must carry a string recordKey and a binary payload.", + message_id=str(message.get("messageId") or ""), + code="malformed_document_put", + ) if self.max_snapshot_bytes is None and not over_rudp: return None alone = self.node.database.raw_put_served_alone(message, message_id=_SHORTEST_SERVED_MESSAGE_ID) diff --git a/packages/cultmesh-py/tests/test_cultmesh.py b/packages/cultmesh-py/tests/test_cultmesh.py index 52191292..95bc7d9a 100644 --- a/packages/cultmesh-py/tests/test_cultmesh.py +++ b/packages/cultmesh-py/tests/test_cultmesh.py @@ -4585,6 +4585,41 @@ class CultMeshTests(unittest.TestCase): self.assertEqual(hello_reply["schemaVersion"], "cultnet.hello.v0") self.assertTrue(alive) + def test_cultmesh_local_server_refuses_a_malformed_put_over_rudp_and_serves_on(self) -> None: + # A put whose document has no string recordKey or no binary payload could never be stored + # or served: it is refused as malformed before any sizing reads it, and the RUDP thread + # serves the next peer. + document = self._rudp_bound_note() + node = CultMesh.create_node(runtime_id="mesh-rudp-malformed") + node.database.register_document(document) + server = CultMesh.serve_node(node) + try: + refusals = [] + for field_name, value in ( + ("recordKey", None), + ("recordKey", 5), + ("payload", None), + ("payload", "not binary"), + ): + put = self._rudp_note_put(document, f"bad-{field_name}-{value}", "note:bad", 10) + if value is None: + del put["document"][field_name] + else: + put["document"][field_name] = value + refusal, _ = self._rudp_exchange(server, put) + refusals.append((put["messageId"], refusal)) + after, _ = self._rudp_exchange(server, snapshot_request(message_id="after").to_wire()) + alive = server._rudp_thread is not None and server._rudp_thread.is_alive() + finally: + server.stop() + for message_id, refusal in refusals: + self.assertEqual(refusal["schemaVersion"], "cultnet.error.v0", message_id) + self.assertEqual(refusal["messageId"], message_id) + self.assertEqual(refusal["code"], "malformed_document_put", message_id) + self.assertEqual(after["messageId"], "after") + self.assertEqual(after["documents"], []) + self.assertTrue(alive) + def test_cultmesh_local_server_refuses_options_that_could_answer_nothing(self) -> None: # The Rust document server's option rules: every limit is greater than zero, and the limits # leave room for an empty snapshot, the smallest response the server sends. One-byte From d465845516ae8894bc98d414432e7b303d105c03 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 17:42:44 +0200 Subject: [PATCH 24/44] cultmesh-rs: a rejected peer is told why, and nothing it sent is acknowledged Every application rejection, DocumentUnservable included, ended with self.sessions.remove(&key): no refusal and no goodbye. The peer could not tell a refusal from packet loss, and a publisher timed out and retried the same put. The session still ends, but the peer is now sent the refusal as a cultnet.error.v0 carrying the reason's text (no code or details, as the TypeScript server's refusals carry none), then the session's goodbye. The refusal is built before the reset and carries the goodbye's emptied acknowledgement fields, so it never acknowledges the refused message: publish_cultnet_message_to_rudp_catalog reads that acknowledgement as admission. A refusal that cannot be encoded or queued is not sent; the goodbye still is. publish_cultnet_message_to_rudp_catalog now returns a catalog's refusal as an error naming it, instead of waiting out its flush deadline. Tests read the refusal from the client side: the refusal text, the put still pending after it, and the goodbye invalidating it; and a publisher refused by a sink hears the sink's reason well inside its deadline. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-rs/src/lib.rs | 36 ++++++++-- .../cultmesh-rs/src/rudp_document_server.rs | 48 ++++++++++++- .../cultmesh-rs/tests/rudp_document_server.rs | 72 +++++++++++++++---- 3 files changed, 132 insertions(+), 24 deletions(-) diff --git a/packages/cultmesh-rs/src/lib.rs b/packages/cultmesh-rs/src/lib.rs index 9c3e4d90..83b713ad 100644 --- a/packages/cultmesh-rs/src/lib.rs +++ b/packages/cultmesh-rs/src/lib.rs @@ -866,7 +866,8 @@ fn unix_millis() -> u128 { /// Publish one raw CultNet schema message to a RUDP catalog. /// /// Each call owns a fresh connection epoch and returns only after the catalog -/// acknowledges reliable application admission. +/// acknowledges reliable application admission. A catalog that refuses the +/// message answers with a `cultnet.error.v0`, returned as an error naming it. pub fn publish_cultnet_message_to_rudp_catalog( message: &cultnet_rs::CultNetMessage, options: CultMeshRudpDocumentPublishOptions, @@ -887,7 +888,22 @@ pub fn publish_cultnet_message_to_rudp_catalog( let receipt = client.send_reliable("schema", payload)?; let flush_deadline = Instant::now() + options.flush_timeout; while Instant::now() < flush_deadline { - let _ = client.receive_once()?; + if let Some(frame) = client.receive_once()? { + if frame.channel_id == "schema" { + if let Ok(cultnet_rs::CultNetMessage::Error { error, .. }) = + decode_cultnet_message_from_slice( + &frame.payload, + CultNetWireContract::CultNetSchemaV0, + ) + { + let _ = client.disconnect(b"document-refused".to_vec()); + anyhow::bail!( + "CultMesh RUDP catalog {} refused the message: {error}", + options.target + ); + } + } + } match client.reliable_send_status(&receipt) { cultnet_rs::CultNetRudpReliableSendStatus::Acknowledged => { let _ = client.disconnect(b"document-acknowledged".to_vec()); @@ -1280,7 +1296,7 @@ mod tests { } #[test] - fn document_publish_requires_application_acknowledgement() -> Result<()> { + fn a_refused_publish_fails_with_the_catalogs_reason_not_a_timeout() -> Result<()> { let temp = tempfile::tempdir()?; let node = CultMesh::create_node( temp.path().join("cultmesh.cc"), @@ -1308,6 +1324,7 @@ mod tests { Ok(()) }); + let started = Instant::now(); let error = node .publish_document_to_rudp_catalog( "note", @@ -1317,16 +1334,23 @@ mod tests { CultMeshRudpDocumentPublishOptions { target, connect_timeout: Duration::from_millis(100), - flush_timeout: Duration::from_millis(50), + flush_timeout: Duration::from_secs(10), poll_interval: Duration::from_millis(2), resend_delay_ms: 5, ..CultMeshRudpDocumentPublishOptions::default() }, ) - .expect_err("unacknowledged document must fail closed"); + .expect_err("a refused document must fail closed"); + let waited = started.elapsed(); stop.store(true, std::sync::atomic::Ordering::SeqCst); server.join().expect("server thread should not panic")?; - assert!(error.to_string().contains("reliable acknowledgement")); + // The publisher hears the refusal and its reason, long before its flush + // deadline: a refusal is not mistaken for loss. + assert!( + error.to_string().contains("refused the message: injected durable sink failure"), + "{error:#}" + ); + assert!(waited < Duration::from_secs(5), "waited {waited:?}"); Ok(()) } diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index 24add376..4d9c8a3f 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -358,8 +358,10 @@ where /// Poll transport maintenance and receive at most one UDP datagram. /// /// Application rejection invalidates only the responsible peer session and - /// is returned as data so a daemon can log it and keep serving. Local - /// socket and server-state failures remain errors. + /// is returned as data so a daemon can log it and keep serving. The peer is + /// sent the refusal as a `cultnet.error.v0` carrying the reason's text, then + /// a goodbye; neither acknowledges the refused message. Local socket and + /// server-state failures remain errors. pub fn poll_once(&mut self) -> Result { self.maintain()?; let mut wire = vec![0_u8; MAX_UDP_DATAGRAM_BYTES]; @@ -458,7 +460,7 @@ where now_unix, now_monotonic, )? { - self.sessions.remove(&key); + self.end_rejected_session(key, rejection.reason.to_string())?; return Ok(CultMeshRudpPollOutcome::ApplicationRejected(rejection)); } } @@ -749,6 +751,46 @@ where self.send_packet(key.remote_addr, &goodbye) } + /// The server refused a peer's message: the session ends, and the peer is + /// sent the refusal before the goodbye, so it can tell a refusal from loss. + /// The refusal carries the goodbye's acknowledgement fields, which the reset + /// has emptied: it must not acknowledge the refused message, because a + /// publisher reads that acknowledgement as admission. A refusal that cannot + /// be encoded or queued is not sent; the goodbye still is. + fn end_rejected_session(&mut self, key: CultMeshRudpSessionKey, reason: String) -> Result<()> { + let Some(mut entry) = self.sessions.remove(&key) else { + return Ok(()); + }; + let refusal = CultNetMessage::Error { + error: reason, + code: None, + details: None, + }; + let packets = encode_cultnet_message_to_vec(&refusal, CultNetWireContract::CultNetSchemaV0) + .and_then(|payload| { + entry.session.send_many( + "schema", + payload, + CultNetRudpSendOptions { + reliable: true, + ordered: true, + sequenced: false, + now_ms: self.clock.now_monotonic_millis(), + reliable_expire_after_ms: None, + }, + Some(self.options.max_fragment_bytes), + ) + }) + .unwrap_or_default(); + let goodbye = entry.session.end_refused_session(); + for mut packet in packets { + packet.ack = goodbye.ack; + packet.ack_mask = goodbye.ack_mask; + self.send_packet(key.remote_addr, &packet)?; + } + self.send_packet(key.remote_addr, &goodbye) + } + /// The fragments `send_many` splits a response of `bytes` into. fn fragments_for(&self, bytes: usize) -> usize { bytes.div_ceil(self.options.max_fragment_bytes).max(1) diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index 1a726570..33a5df78 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -335,6 +335,53 @@ fn poll_until_rejected_or_stored( anyhow::bail!("the put was neither refused nor stored") } +/// What a refused peer is sent: a `cultnet.error.v0`, then the goodbye. The +/// refused message is never acknowledged, so its receipt stays pending until the +/// goodbye invalidates it. Returns the refusal's text. +fn refusal_seen_by( + client: &mut CultNetRudpSocketTransportConnection, + receipt: &CultNetRudpReliableSendReceipt, +) -> Result { + let mut refusal = None; + for _ in 0..2_000 { + if let Some(frame) = client.receive_once()? { + refusal = Some(decode_cultnet_message_from_slice( + &frame.payload, + CultNetWireContract::CultNetSchemaV0, + )?); + break; + } + thread::sleep(Duration::from_millis(1)); + } + let Some(CultNetMessage::Error { + error, + code, + details, + }) = refusal + else { + panic!("the refused peer was sent no refusal: {refusal:?}"); + }; + assert_eq!((code, details), (None, None)); + assert_eq!( + client.reliable_send_status(receipt), + CultNetRudpReliableSendStatus::Pending, + "a refusal must not acknowledge the refused message" + ); + for _ in 0..2_000 { + client.receive_once()?; + if !client.connected() { + break; + } + thread::sleep(Duration::from_millis(1)); + } + assert!(!client.connected(), "the refusal is followed by a goodbye"); + assert_eq!( + client.reliable_send_status(receipt), + CultNetRudpReliableSendStatus::Invalidated + ); + Ok(error) +} + fn send(client: &mut CultNetRudpSocketTransportConnection, message: &CultNetMessage) -> Result<()> { client.send( "schema", @@ -562,7 +609,7 @@ fn a_restarted_client_starts_with_a_fresh_payload_budget() -> Result<()> { } #[test] -fn application_rejection_is_nonfatal_peer_scoped_and_unacknowledged() -> Result<()> { +fn application_rejection_is_nonfatal_peer_scoped_refused_to_the_peer_and_unacknowledged() -> Result<()> { let clock = Clock::new(48_000); let sink = Sink::fail_once(); let source = Source::fail_once(vec![document("snapshot", vec![4, 5, 6])]); @@ -602,10 +649,9 @@ fn application_rejection_is_nonfatal_peer_scoped_and_unacknowledged() -> Result< CultMeshRudpRejectionReason::SinkRefused("injected sink failure".into()) ); assert_eq!(server.session_count(), 2); - publisher.receive_once()?; assert_eq!( - publisher.reliable_send_status(&publish_receipt), - CultNetRudpReliableSendStatus::Pending + refusal_seen_by(&mut publisher, &publish_receipt)?, + "injected sink failure" ); let snapshot_receipt = send_reliable( @@ -630,10 +676,9 @@ fn application_rejection_is_nonfatal_peer_scoped_and_unacknowledged() -> Result< CultMeshRudpRejectionReason::SnapshotSourceFailed("injected source failure".into()) ); assert_eq!(server.session_count(), 1); - snapshot_client.receive_once()?; assert_eq!( - snapshot_client.reliable_send_status(&snapshot_receipt), - CultNetRudpReliableSendStatus::Pending + refusal_seen_by(&mut snapshot_client, &snapshot_receipt)?, + "injected source failure" ); let survivor_receipt = send_reliable( @@ -777,10 +822,9 @@ fn payload_and_snapshot_output_budgets_fail_closed() -> Result<()> { } if response_bytes > 128 )); assert_eq!(snapshot_server.session_count(), 0); - snapshot_client.receive_once()?; assert_eq!( - snapshot_client.reliable_send_status(&receipt), - CultNetRudpReliableSendStatus::Pending + refusal_seen_by(&mut snapshot_client, &receipt)?, + rejection.reason.to_string() ); Ok(()) } @@ -840,11 +884,9 @@ fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served( assert!(sentence.contains(&(limit + 1).to_string()) && sentence.contains(&limit.to_string())); assert!(sink.0.lock().unwrap().receipts.is_empty()); assert_eq!(server.session_count(), 1); - refused.receive_once()?; - assert_eq!( - refused.reliable_send_status(&refused_receipt), - CultNetRudpReliableSendStatus::Pending - ); + // The peer hears the refusal and why, rather than waiting on a put that + // will never be acknowledged. + assert_eq!(refusal_seen_by(&mut refused, &refused_receipt)?, sentence); send( &mut writer, From 835bee3ae075f47e4e5dc92108e3b6dbf35ca8e6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 17:48:40 +0200 Subject: [PATCH 25/44] cultmesh-py: the daemon refuses a snapshot document limit of zero The daemon test ran with --max-snapshot-documents 0 to make every snapshot a peer error. A limit of zero is now refused at startup, as the Rust document server refuses it, so the test pins what the daemon does with it: it exits non-zero naming the rule and never writes its ready file. The limit's enforcement as a peer error stays pinned in process by test_cultmesh_local_server_rejects_oversized_snapshot_responses. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-py/tests/test_cultmesh.py | 29 ++++++++------------- 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/packages/cultmesh-py/tests/test_cultmesh.py b/packages/cultmesh-py/tests/test_cultmesh.py index 95bc7d9a..ba1cc635 100644 --- a/packages/cultmesh-py/tests/test_cultmesh.py +++ b/packages/cultmesh-py/tests/test_cultmesh.py @@ -3720,7 +3720,11 @@ class CultMeshTests(unittest.TestCase): finally: self._terminate_process(process) - def test_cultmesh_daemon_enforces_snapshot_document_limit_as_peer_error(self) -> None: + def test_cultmesh_daemon_refuses_a_snapshot_document_limit_of_zero_at_startup(self) -> None: + # A limit of zero is a server that could answer no snapshot, which the Rust document + # server's options also refuse; the daemon passes the flag to the server, and exits + # naming the rule instead of serving. The limit's enforcement as a peer error is pinned + # in process by test_cultmesh_local_server_rejects_oversized_snapshot_responses. with tempfile.TemporaryDirectory() as temp: ready_path = Path(temp) / "ready.json" package_src = Path(__file__).resolve().parents[1] / "src" @@ -3731,7 +3735,7 @@ class CultMeshTests(unittest.TestCase): if not existing_pythonpath else f"{package_src}{os.pathsep}{existing_pythonpath}" ) - process = subprocess.Popen( + completed = subprocess.run( [ sys.executable, "-m", @@ -3746,25 +3750,14 @@ class CultMeshTests(unittest.TestCase): "--ready-file", str(ready_path), ], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, + capture_output=True, text=True, env=env, + timeout=30, ) - try: - ready = self._wait_for_ready_file(process, ready_path) - self.assertEqual(ready["snapshotLimits"], {"maxSnapshotBytes": None, "maxSnapshotDocuments": 0}) - client = CultMesh.create_client("127.0.0.1", int(ready["port"]), timeout_seconds=2.0) - - with self.assertRaisesRegex(CultNetPeerError, "Snapshot document limit exceeded") as raised: - client.fetch_snapshot_response(schema_ids=["cultcache.interop-note"]) - - self.assertEqual(raised.exception.response["schemaVersion"], "cultnet.error.v0") - self.assertEqual(raised.exception.response["code"], "snapshot_document_limit_exceeded") - self.assertEqual(raised.exception.response["details"]["documentCount"], 1) - self.assertEqual(raised.exception.response["details"]["maxSnapshotDocuments"], 0) - finally: - self._terminate_process(process) + self.assertNotEqual(completed.returncode, 0) + self.assertIn("max_snapshot_documents must be greater than zero", completed.stderr) + self.assertFalse(ready_path.exists()) def test_cultmesh_daemon_serves_opt_in_simulation_observations(self) -> None: with tempfile.TemporaryDirectory() as temp: From 25b075a4732f5a4a48b4b8d0ccb187b1a8396366 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 17:52:27 +0200 Subject: [PATCH 26/44] cultmesh-rs: the rejection test reads the refused peer's acknowledgement before going on A refused peer now acknowledges its refusal, and that datagram reaches the server after the session has ended. The test took the next poll to be the second client's request and failed on the dropped acknowledgement instead. It drains the server until idle after each refusal is read. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/tests/rudp_document_server.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index 33a5df78..45a8eb39 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -382,6 +382,21 @@ fn refusal_seen_by( Ok(error) } +/// Reads every datagram waiting at the server, such as a refused peer's +/// acknowledgement of its refusal, which reaches no session and is dropped. +fn drain_until_idle( + server: &mut CultMeshRudpDocumentServer, +) -> Result<()> { + for _ in 0..100 { + match server.poll_once()? { + CultMeshRudpPollOutcome::Idle => return Ok(()), + CultMeshRudpPollOutcome::Handled => {} + rejected => panic!("draining must not reject: {rejected:?}"), + } + } + anyhow::bail!("the server never went idle") +} + fn send(client: &mut CultNetRudpSocketTransportConnection, message: &CultNetMessage) -> Result<()> { client.send( "schema", @@ -653,6 +668,7 @@ fn application_rejection_is_nonfatal_peer_scoped_refused_to_the_peer_and_unackno refusal_seen_by(&mut publisher, &publish_receipt)?, "injected sink failure" ); + drain_until_idle(&mut server)?; let snapshot_receipt = send_reliable( &mut snapshot_client, @@ -680,6 +696,7 @@ fn application_rejection_is_nonfatal_peer_scoped_refused_to_the_peer_and_unackno refusal_seen_by(&mut snapshot_client, &snapshot_receipt)?, "injected source failure" ); + drain_until_idle(&mut server)?; let survivor_receipt = send_reliable( &mut survivor, From 38000efab281bbf4b783e8c841664f9cefe99d72 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 17:55:30 +0200 Subject: [PATCH 27/44] cultmesh-rs: rustfmt the refusal tests Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-rs/src/lib.rs | 4 +++- packages/cultmesh-rs/tests/rudp_document_server.rs | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/cultmesh-rs/src/lib.rs b/packages/cultmesh-rs/src/lib.rs index 83b713ad..631e1c2f 100644 --- a/packages/cultmesh-rs/src/lib.rs +++ b/packages/cultmesh-rs/src/lib.rs @@ -1347,7 +1347,9 @@ mod tests { // The publisher hears the refusal and its reason, long before its flush // deadline: a refusal is not mistaken for loss. assert!( - error.to_string().contains("refused the message: injected durable sink failure"), + error + .to_string() + .contains("refused the message: injected durable sink failure"), "{error:#}" ); assert!(waited < Duration::from_secs(5), "waited {waited:?}"); diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index 45a8eb39..b30f1c14 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -624,7 +624,8 @@ fn a_restarted_client_starts_with_a_fresh_payload_budget() -> Result<()> { } #[test] -fn application_rejection_is_nonfatal_peer_scoped_refused_to_the_peer_and_unacknowledged() -> Result<()> { +fn application_rejection_is_nonfatal_peer_scoped_refused_to_the_peer_and_unacknowledged() +-> Result<()> { let clock = Clock::new(48_000); let sink = Sink::fail_once(); let source = Source::fail_once(vec![document("snapshot", vec![4, 5, 6])]); From a1065cabe03e1b5f6c655c3e21015fa0b19a70c1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 18:37:40 +0200 Subject: [PATCH 28/44] cultmesh-ts: admission sizes only the served reply, never a receipt Admission sized the larger of the snapshot reply and a receipt echoing the put, so a put servable at the bound was refused, within 89-125 bytes of it, for a receipt an application that sends none never sends. Whether a receipt is sent is onDocumentPutRaw's to decide after it stores the put, so admission cannot know it (ruling: Self, fork A option a). Admission now sizes only the snapshot reply serving the document alone. A receipt that cannot be sent takes the existing path: onError hears why and the peer is told with a cultnet.error.v0 that it is not coming. This removes the receipt bound of 9757ed54 and its test. The new test pins the band at its boundary with puts whose echoed receipt is over the limit: exactly at the limit is admitted and served, with no receipt and with an echoed one, and one byte over is refused. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-ts/src/index.ts | 63 ++++++++----------- packages/cultmesh-ts/test/cultmesh.test.ts | 71 ++++++++++++---------- 2 files changed, 66 insertions(+), 68 deletions(-) diff --git a/packages/cultmesh-ts/src/index.ts b/packages/cultmesh-ts/src/index.ts index d3972cac..689fbed2 100644 --- a/packages/cultmesh-ts/src/index.ts +++ b/packages/cultmesh-ts/src/index.ts @@ -4289,22 +4289,21 @@ export interface CultMeshRudpDocumentReceipt encodeSchemaMessage(reply).byteLength)); + const responseBytes = encodeSchemaMessage(reply).byteLength; const fragmentCount = Math.max(1, Math.ceil(responseBytes / maxFragmentBytes)); if ((maxPayloadBytes === undefined || responseBytes <= maxPayloadBytes) && fragmentCount <= maxReplyFragments) { diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index 8167e41d..78c83864 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -3246,7 +3246,7 @@ const servedBoundRegistry = () => /** * A put's own storedAt, kept by the served record and replaced in the receipt by the server's * 24-character clock. It is long enough that the snapshot reply is always the larger reply, so - * fixtures built with it pin the served bound; `RECEIPT_STORED_AT` puts pin the receipt bound. + * fixtures built with it pin the served bound; `RECEIPT_STORED_AT` puts make the receipt the larger reply. */ const SERVED_STORED_AT = `2026-09-30T00:00:00.000Z${"~".repeat(200)}`; const RECEIPT_STORED_AT = "2026-09-30T00:00:00.000Z"; @@ -3320,16 +3320,6 @@ function bodyLengthForReplyBytes(recordKey: string, bytes: number): number { return length; } -/** The body length whose echoed receipt, under `messageId`, is exactly `bytes`, and the larger reply. */ -function bodyLengthForReceiptBytes(messageId: string, recordKey: string, bytes: number): number { - const put = (body: number) => notePut(messageId, recordKey, body, undefined, RECEIPT_STORED_AT); - const probe = 2_000; - const length = probe + bytes - echoReceiptBytes(put(probe)); - assert.equal(echoReceiptBytes(put(length)), bytes, "fixture: receipt size is linear in the body"); - assert.ok(servedAloneBytes(put(length)) < bytes, "fixture: the receipt is the larger reply"); - return length; -} - async function withServedBoundRig( connectionId: number, serverLimits: { maxFragmentBytes?: number; maxPendingReliablePackets?: number; maxPayloadBytes?: number }, @@ -3510,29 +3500,46 @@ test("CultMesh TS RUDP document server honours maxPayloadBytes for replies and j }); }); -test("CultMesh TS RUDP document server refuses a put whose receipt could not be sent", async () => { - // The receipt is the larger reply here: a put whose receipt is one byte over the limit is - // refused before it is stored; one whose receipt is exactly at the limit is stored and gets it. +test("CultMesh TS RUDP document server admits a put served at the bound, whatever receipt its handler returns", async () => { + // These puts keep a short storedAt, so the receipt echoing one is larger than its served reply, + // and over the limit. Admission sizes only the served reply: exactly at the limit is admitted + // with or without a receipt, one byte over is refused. An echoed receipt that cannot be sent + // goes the way of any unsendable receipt: the put is stored and the peer is told. const limit = 4_000; - const overBound = bodyLengthForReceiptBytes("put-ov", "note:ro", limit + 1); - const atBound = bodyLengthForReceiptBytes("put-at", "note:ra", limit); - await withServedBoundRig(0x10203065, { maxFragmentBytes: 1024, maxPayloadBytes: limit }, async (rig) => { - rig.peer.send(notePut("put-ov", "note:ro", overBound, undefined, RECEIPT_STORED_AT)); - const refusal = await waitForError(rig, "the put whose receipt is over the limit"); - assert.ok(refusal instanceof CultMeshRudpUnservableDocumentError, refusal.message); - assert.equal(refusal.responseBytes, limit + 1); - assert.equal(refusal.maxPayloadBytes, limit); - assert.deepEqual(rig.admitted, []); - await waitForPeerErrors(rig, 1); + const put = (messageId: string, recordKey: string, body: number) => + notePut(messageId, recordKey, body, undefined, RECEIPT_STORED_AT); + const bodyServedAt = (messageId: string, recordKey: string, bytes: number): number => { + const probe = 2_000; + const length = probe + bytes - servedAloneBytes(put(messageId, recordKey, probe)); + assert.equal(servedAloneBytes(put(messageId, recordKey, length)), bytes, "fixture: reply size is linear in the body"); + assert.ok(echoReceiptBytes(put(messageId, recordKey, length)) > limit, "fixture: the echoed receipt is over the limit"); + return length; + }; + const atBound = bodyServedAt("put-at", "note:at", limit); + const overBound = bodyServedAt("put-ov", "note:ov", limit + 1); + for (const [connectionId, receipt] of [[0x10203066, undefined], [0x10203067, "echo"]] as const) { + await withServedBoundRig(connectionId, { maxFragmentBytes: 1024, maxPayloadBytes: limit }, async (rig) => { + rig.peer.send(put("put-at", "note:at", atBound)); + await waitForAdmission(rig, "note:at"); + if (receipt === "echo") { + const failure = await waitForError(rig, "the echoed receipt"); + assert.match(failure.message, /reply cultnet\.document_put_raw\.v0 is \d+ bytes; maxPayloadBytes is 4000/); + await waitForPeerErrors(rig, 1); + assert.ok(!rig.messages.some(isDocumentPut)); + } + assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:at")), [["note:at", atBound]]); + const errorsBefore = rig.errors.length; + assert.equal(errorsBefore, receipt === "echo" ? 1 : 0, rig.errors.map((error) => error.message).join("; ")); - rig.peer.send(notePut("put-at", "note:ra", atBound, undefined, RECEIPT_STORED_AT)); - await waitForAdmission(rig, "note:ra"); - const startedAt = Date.now(); - while (!rig.messages.some(isDocumentPut) && Date.now() - startedAt < 3_000) await delay(5); - const receipt = rig.messages.find(isDocumentPut) as CultNetDocumentPutRawMessage | undefined; - assert.equal(receipt?.messageId, "put-at", "the stored put gets its receipt"); - assert.equal(rig.errors.length, 1); - }, { receipt: "echo" }); + rig.peer.send(put("put-ov", "note:ov", overBound)); + const startedAt = Date.now(); + while (rig.errors.length === errorsBefore && Date.now() - startedAt < 3_000) await delay(5); + const refusal = rig.errors[errorsBefore]; + assert.ok(refusal instanceof CultMeshRudpUnservableDocumentError, refusal?.message); + assert.equal(refusal.responseBytes, limit + 1); + assert.deepEqual(rig.admitted, ["note:at"]); + }, receipt ? { receipt } : {}); + } }); test("CultMesh TS RUDP document server tells the peer when a stored put's receipt cannot be sent", async () => { From e4e2a0b9d7332b8fa1b93ef97eccd0bfdf21e5b2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 18:37:41 +0200 Subject: [PATCH 29/44] cultnet-ts: drop decodeRawDocumentPut, which only receipt admission used The registry method existed on this branch only to size a receipt at put admission in cultmesh-ts, which no longer does. It never reached main. Co-Authored-By: Claude Opus 5.5 --- packages/cultnet-ts/src/replication.ts | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/packages/cultnet-ts/src/replication.ts b/packages/cultnet-ts/src/replication.ts index 6de103b6..a2eda250 100644 --- a/packages/cultnet-ts/src/replication.ts +++ b/packages/cultnet-ts/src/replication.ts @@ -268,20 +268,6 @@ export class CultNetDocumentRegistry { }; } - /** - * The binding and value `applyRawDocumentPutMessage` would store for this raw - * put, decoded as that binding reads it. A server uses it to build the reply - * that would acknowledge the put before storing it. Throws, as the put would, - * when no binding accepts the document. - */ - decodeRawDocumentPut(message: CultNetDocumentPutRawMessage): { - binding: CultNetDocumentBinding; - value: unknown; - } { - const { binding, envelope } = this.#rawPutEnvelope(message); - return { binding, value: decodeDocumentValue(binding.definition, envelope.payload) }; - } - #rawPutEnvelope(message: CultNetDocumentPutRawMessage): { binding: CultNetDocumentBinding; envelope: CultCacheEnvelope; From d655f7585bcd20d314935f56877b06ee2870a070 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 19:36:24 +0200 Subject: [PATCH 30/44] cultmesh-ts: the served-bound test comments stop saying admission sizes receipts Admission has sized only the served reply since a1065cab; three comments and one fixture assertion still described the receipt bound. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-ts/test/cultmesh.test.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index 78c83864..9281355c 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -3245,8 +3245,9 @@ const servedBoundRegistry = () => /** * A put's own storedAt, kept by the served record and replaced in the receipt by the server's - * 24-character clock. It is long enough that the snapshot reply is always the larger reply, so - * fixtures built with it pin the served bound; `RECEIPT_STORED_AT` puts make the receipt the larger reply. + * 24-character clock. `SERVED_STORED_AT` is long, so an echoed receipt is smaller than the served + * reply; `RECEIPT_STORED_AT` is short, so an echoed receipt is the larger reply, which shows that + * admission sizes only the served reply. */ const SERVED_STORED_AT = `2026-09-30T00:00:00.000Z${"~".repeat(200)}`; const RECEIPT_STORED_AT = "2026-09-30T00:00:00.000Z"; @@ -3310,13 +3311,12 @@ function echoReceiptBytes(put: CultNetDocumentPutRawMessage): number { }).byteLength; } -/** The body length whose served-alone reply is exactly `bytes`, and the larger reply. */ +/** The body length whose served-alone reply is exactly `bytes`. */ function bodyLengthForReplyBytes(recordKey: string, bytes: number): number { const probe = 8_000; const length = probe + bytes - servedAloneBytes(notePut("p", recordKey, probe)); const put = notePut("p", recordKey, length); assert.equal(servedAloneBytes(put), bytes, "fixture: reply size is linear in the body"); - assert.ok(echoReceiptBytes(put) < bytes, "fixture: the snapshot reply is the larger reply"); return length; } @@ -3358,8 +3358,8 @@ async function withServedBoundRig( }, }); if (!handler.receipt) return undefined; - // An echo acknowledges the stored value, as admission sizes it; an oversized receipt - // carries more than admission could know of. + // An echo acknowledges the stored value; an oversized receipt carries a tag larger than + // maxPayloadBytes. Admission sizes neither: receipts are the handler's choice. return { binding: defineCultNetDocumentBinding({ definition: noteDocument }), recordKey: document.recordKey, @@ -3543,8 +3543,8 @@ test("CultMesh TS RUDP document server admits a put served at the bound, whateve }); test("CultMesh TS RUDP document server tells the peer when a stored put's receipt cannot be sent", async () => { - // A handler whose receipt is larger than the echo admission sized: the put is stored, the - // receipt cannot be sent, and the peer hears that it is not coming. + // A handler whose receipt is larger than maxPayloadBytes: admission does not size receipts, so + // the put is stored, the receipt cannot be sent, and the peer hears that it is not coming. const limit = 4_000; const small = bodyLengthForReplyBytes("note:small", 1_000); await withServedBoundRig(0x10203064, { maxFragmentBytes: 1024, maxPayloadBytes: limit }, async (rig) => { From 699432128b7291de4f913d6500937c7df0886819 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 19:38:20 +0200 Subject: [PATCH 31/44] cultmesh-py: a put the store cannot take is refused to its peer, never raised A well-formed put still killed the RUDP thread: _handle_raw_put called apply_raw_put_message unguarded, and cache.put_envelope raises for a blank recordKey, a payload that is not MessagePack or does not decode to its schema, a global document under another key, or anything a document's own decoder or validator raises. Over TCP it ended the connection. The apply site now refuses any put the store cannot take to the peer that sent it, as malformed_document_put, over RUDP and TCP alike, and logs the error's type. Neither the refusal nor the log quotes the error, which can quote the put. No new shape checks: the store decides what it can take. The test sends each shape over RUDP and over TCP and shows the RUDP thread alive, the TCP connection serving its next message, and other peers served. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-py/src/cultmesh_py/server.py | 17 ++++- packages/cultmesh-py/tests/test_cultmesh.py | 63 +++++++++++++++++++ 2 files changed, 79 insertions(+), 1 deletion(-) diff --git a/packages/cultmesh-py/src/cultmesh_py/server.py b/packages/cultmesh-py/src/cultmesh_py/server.py index 591a6f46..25deefd7 100644 --- a/packages/cultmesh-py/src/cultmesh_py/server.py +++ b/packages/cultmesh-py/src/cultmesh_py/server.py @@ -1,5 +1,6 @@ from __future__ import annotations +import logging import socket import threading import time @@ -41,6 +42,8 @@ from cultnet_py.cultmesh_contracts import ( CultMeshVerseCatalog, ) +_LOGGER = logging.getLogger(__name__) + @dataclass(frozen=True) class _DatabaseSubscription: @@ -430,7 +433,19 @@ class CultMeshLocalServer: unservable = self._unservable_put(message, over_rudp=over_rudp) if unservable is not None: return [unservable] - change = self.node.database.apply_raw_put_message(message) + try: + change = self.node.database.apply_raw_put_message(message) + except Exception as error: # noqa: BLE001 - a put the store cannot take is that peer's refusal + # The store refused the put: a blank key, a payload its schema cannot decode, a global + # document under another key, or anything a document's own decoder or validator + # raises. It is refused to the peer that sent it; no thread and no other peer is + # affected. Neither the refusal nor the log quotes the error, which can quote the put. + _LOGGER.warning("CultMesh server refused a raw put the store could not take (%s).", type(error).__name__) + return [self._error_response( + "Raw put document could not be stored.", + message_id=str(message.get("messageId") or ""), + code="malformed_document_put", + )] if change is None: return [self._error_response( "Raw put message did not apply to a registered document.", diff --git a/packages/cultmesh-py/tests/test_cultmesh.py b/packages/cultmesh-py/tests/test_cultmesh.py index ba1cc635..163e08be 100644 --- a/packages/cultmesh-py/tests/test_cultmesh.py +++ b/packages/cultmesh-py/tests/test_cultmesh.py @@ -4613,6 +4613,69 @@ class CultMeshTests(unittest.TestCase): self.assertEqual(after["documents"], []) self.assertTrue(alive) + def test_cultmesh_local_server_refuses_a_put_its_store_cannot_take_and_serves_on(self) -> None: + # Well-formed puts the store refuses: a blank key, a payload that is not MessagePack, a + # payload its schema cannot decode, a global document under another key. Each is refused + # to the peer that sent it, over RUDP and over TCP; the RUDP thread lives, the TCP + # connection serves its next message, and other peers are served. + document = self._rudp_bound_note() + global_document = define_database_entry_type( + "mesh.rudp_global_note", + [("schema_version", 0), ("body", 1)], + schema_id="sha256:mesh-rudp-global", + schema_name="mesh.rudp_global_note", + schema_version="mesh.rudp_global_note.v1", + global_document=True, + ) + + def cases() -> list[dict[str, Any]]: + puts = [] + for name, field_name, value in ( + ("empty-key", "recordKey", ""), + ("blank-key", "recordKey", " "), + ("garbage-payload", "payload", bytes([0xC1])), + ("int-payload", "payload", msgpack.packb(5)), + ): + put = self._rudp_note_put(document, name, "note:ok", 10) + put["document"][field_name] = value + puts.append(put) + puts.append(self._rudp_note_put(global_document, "global-wrong-key", "not-global", 10)) + return puts + + node = CultMesh.create_node(runtime_id="mesh-unstorable-put") + node.database.register_document(document) + node.database.register_document(global_document) + server = CultMesh.serve_node(node) + try: + rudp_refusals = [(put["messageId"], self._rudp_exchange(server, put)[0]) for put in cases()] + rudp_after, _ = self._rudp_exchange(server, hello(runtime_id="rudp-after").to_wire()) + rudp_alive = server._rudp_thread is not None and server._rudp_thread.is_alive() + + tcp_refusals = [] + with CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=4.0).open_transport() as transport: + for put in cases(): + transport.send("schema", msgpack.packb(put, use_bin_type=True)) + tcp_refusals.append((put["messageId"], msgpack.unpackb(transport.receive().payload, raw=False))) + transport.send("schema", msgpack.packb(hello(runtime_id="same-connection").to_wire(), use_bin_type=True)) + same_connection = msgpack.unpackb(transport.receive().payload, raw=False) + other_connection = CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=4.0).request( + hello(runtime_id="other-connection").to_wire(), expected_schema_version="cultnet.hello.v0" + ) + finally: + server.stop() + self.assertEqual(len(rudp_refusals), 5) + for message_id, refusal in rudp_refusals + tcp_refusals: + self.assertEqual(refusal["schemaVersion"], "cultnet.error.v0", message_id) + self.assertEqual(refusal["messageId"], message_id) + self.assertEqual(refusal["code"], "malformed_document_put", message_id) + self.assertNotIn("note:ok", refusal["error"], message_id) + self.assertEqual(len(tcp_refusals), 5) + self.assertEqual(rudp_after["schemaVersion"], "cultnet.hello.v0") + self.assertTrue(rudp_alive) + self.assertEqual(same_connection["schemaVersion"], "cultnet.hello.v0") + self.assertEqual(other_connection["schemaVersion"], "cultnet.hello.v0") + self.assertIsNone(node.database.get(document, "note:ok")) + def test_cultmesh_local_server_refuses_options_that_could_answer_nothing(self) -> None: # The Rust document server's option rules: every limit is greater than zero, and the limits # leave room for an empty snapshot, the smallest response the server sends. One-byte From ead1a25aff8f10063836e2f865a19be1fe5f962a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 19:38:20 +0200 Subject: [PATCH 32/44] cultmesh-py: RUDP option rules apply only to a RUDP server; the daemon reports a refused limit as a usage error The RUDP option rules refused a TCP-only server (enable_rudp=False) for RUDP limits it never uses. Rust checks those options only for the RUDP server they configure, so Python now checks rudp_resend_delay_ms, rudp_max_pending_reliable_packets, rudp_max_fragment_bytes and the empty snapshot's fragment rule only when enable_rudp is true. The snapshot limits still apply to every server. The daemon turned --max-snapshot-documents 0 into a traceback. The server still owns the rule; the daemon reports its refusal through parser.error: exit status 2 and the rule named, no traceback. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-py/src/cultmesh_py/daemon.py | 30 +++++++++++-------- .../cultmesh-py/src/cultmesh_py/server.py | 18 ++++++----- packages/cultmesh-py/tests/test_cultmesh.py | 20 ++++++++++--- 3 files changed, 43 insertions(+), 25 deletions(-) diff --git a/packages/cultmesh-py/src/cultmesh_py/daemon.py b/packages/cultmesh-py/src/cultmesh_py/daemon.py index d21d42d8..c98063f7 100644 --- a/packages/cultmesh-py/src/cultmesh_py/daemon.py +++ b/packages/cultmesh-py/src/cultmesh_py/daemon.py @@ -50,7 +50,7 @@ def main(argv: list[str] | None = None) -> int: stop = threading.Event() install_signal_handlers(stop) - server = start_server(args) + server = start_server(args, parser) try: ready = daemon_ready_document(server) publish_ready(ready, ready_file=args.ready_file) @@ -61,7 +61,7 @@ def main(argv: list[str] | None = None) -> int: return 0 -def start_server(args: argparse.Namespace) -> CultMeshLocalServer: +def start_server(args: argparse.Namespace, parser: argparse.ArgumentParser) -> CultMeshLocalServer: node = CultMesh.create_node( args.cache_file, runtime_id=args.runtime_id, @@ -98,17 +98,21 @@ def start_server(args: argparse.Namespace) -> CultMeshLocalServer: quorum_ratio=args.simulation_quorum_ratio, ) ) - server = CultMesh.serve_node( - node, - verse_catalog=verse_catalog, - peer_catalog=peer_catalog, - observation_hub=observation_hub, - host=args.host, - port=args.port, - display_name=args.display_name, - max_snapshot_documents=args.max_snapshot_documents, - max_snapshot_bytes=args.max_snapshot_bytes, - ) + try: + server = CultMesh.serve_node( + node, + verse_catalog=verse_catalog, + peer_catalog=peer_catalog, + observation_hub=observation_hub, + host=args.host, + port=args.port, + display_name=args.display_name, + max_snapshot_documents=args.max_snapshot_documents, + max_snapshot_bytes=args.max_snapshot_bytes, + ) + except ValueError as error: + # The server owns its option rules; a limit it refuses is a usage error, not a crash. + parser.error(str(error)) advertise_self(server, verse_catalog, peer_catalog, args) return server diff --git a/packages/cultmesh-py/src/cultmesh_py/server.py b/packages/cultmesh-py/src/cultmesh_py/server.py index 25deefd7..f6453d23 100644 --- a/packages/cultmesh-py/src/cultmesh_py/server.py +++ b/packages/cultmesh-py/src/cultmesh_py/server.py @@ -105,23 +105,25 @@ class CultMeshLocalServer: # The Rust document server's option rules (validate_options), for each option this # server shares with it: every limit is greater than zero, and the limits leave room for # the smallest response the server sends, an empty snapshot. A server that could answer - # nothing is misconfigured. + # nothing is misconfigured. The RUDP options are checked only when RUDP is served, as + # Rust checks them only for the RUDP server they configure. if self.max_snapshot_bytes is not None and self.max_snapshot_bytes <= 0: raise ValueError("max_snapshot_bytes must be greater than zero") if self.max_snapshot_documents is not None and self.max_snapshot_documents <= 0: raise ValueError("max_snapshot_documents must be greater than zero") - if self.rudp_resend_delay_ms <= 0: - raise ValueError("rudp_resend_delay_ms must be greater than zero") - if self.rudp_max_pending_reliable_packets is not None and self.rudp_max_pending_reliable_packets <= 0: - raise ValueError("rudp_max_pending_reliable_packets must be greater than zero") - if self.rudp_max_fragment_bytes <= 0: - raise ValueError("rudp_max_fragment_bytes must be greater than zero") + if self.enable_rudp: + if self.rudp_resend_delay_ms <= 0: + raise ValueError("rudp_resend_delay_ms must be greater than zero") + if self.rudp_max_pending_reliable_packets is not None and self.rudp_max_pending_reliable_packets <= 0: + raise ValueError("rudp_max_pending_reliable_packets must be greater than zero") + if self.rudp_max_fragment_bytes <= 0: + raise ValueError("rudp_max_fragment_bytes must be greater than zero") empty = _snapshot_response_bytes( CultNetRawSnapshotResponse(message_id=_SHORTEST_SERVED_MESSAGE_ID, documents=()).to_wire() ) if self.max_snapshot_bytes is not None and empty > self.max_snapshot_bytes: raise ValueError("max_snapshot_bytes cannot hold an empty snapshot response") - if -(-empty // self.rudp_max_fragment_bytes) > self._max_rudp_reply_fragments(): + if self.enable_rudp and -(-empty // self.rudp_max_fragment_bytes) > self._max_rudp_reply_fragments(): raise ValueError( "rudp_max_fragment_bytes and rudp_max_pending_reliable_packets cannot carry an empty " "snapshot response" diff --git a/packages/cultmesh-py/tests/test_cultmesh.py b/packages/cultmesh-py/tests/test_cultmesh.py index 163e08be..cb4b767d 100644 --- a/packages/cultmesh-py/tests/test_cultmesh.py +++ b/packages/cultmesh-py/tests/test_cultmesh.py @@ -3722,8 +3722,8 @@ class CultMeshTests(unittest.TestCase): def test_cultmesh_daemon_refuses_a_snapshot_document_limit_of_zero_at_startup(self) -> None: # A limit of zero is a server that could answer no snapshot, which the Rust document - # server's options also refuse; the daemon passes the flag to the server, and exits - # naming the rule instead of serving. The limit's enforcement as a peer error is pinned + # server's options also refuse; the daemon passes the flag to the server, and exits with + # a usage error naming the rule instead of serving. The limit's enforcement as a peer error is pinned # in process by test_cultmesh_local_server_rejects_oversized_snapshot_responses. with tempfile.TemporaryDirectory() as temp: ready_path = Path(temp) / "ready.json" @@ -3755,8 +3755,10 @@ class CultMeshTests(unittest.TestCase): env=env, timeout=30, ) - self.assertNotEqual(completed.returncode, 0) - self.assertIn("max_snapshot_documents must be greater than zero", completed.stderr) + # A usage error from argparse: exit status 2, the rule named, no traceback. + self.assertEqual(completed.returncode, 2, completed.stderr) + self.assertIn("error: max_snapshot_documents must be greater than zero", completed.stderr) + self.assertNotIn("Traceback", completed.stderr) self.assertFalse(ready_path.exists()) def test_cultmesh_daemon_serves_opt_in_simulation_observations(self) -> None: @@ -4719,6 +4721,16 @@ class CultMeshTests(unittest.TestCase): accepted(rudp_resend_delay_ms=1) self.assertIn("greater than zero", refused(rudp_max_fragment_bytes=0)) self.assertIn("greater than zero", refused(rudp_max_pending_reliable_packets=0)) + # The RUDP options configure only the RUDP server: without one, none of them is checked. + accepted(enable_rudp=False, rudp_max_fragment_bytes=1, rudp_max_pending_reliable_packets=16) + accepted( + enable_rudp=False, + rudp_max_fragment_bytes=0, + rudp_max_pending_reliable_packets=0, + rudp_resend_delay_ms=0, + ) + self.assertIn("greater than zero", refused(enable_rudp=False, max_snapshot_documents=0)) + self.assertIn("cannot hold an empty snapshot response", refused(enable_rudp=False, max_snapshot_bytes=empty - 1)) # The configuration at the bound does answer: an empty snapshot in one-byte fragments, # exactly as many as the queue holds. From b3176de1f8eea3fa61d9696e0c83a298bea87d1d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 19:41:35 +0200 Subject: [PATCH 33/44] cultmesh-rs: a refusal carries fixed text, never a sink's or source's error The refusal sent to a rejected peer carried the rejection's Display text, which for SinkRefused and SnapshotSourceFailed is the sink's or source's own error. Odin's sink formats the peer-supplied document type into its error, so a peer's input came back on the wire. The refusal now carries fixed text per rejection variant (REFUSAL_TEXTS). The rejection returned from poll_once still carries the detail for the caller; the server itself logs nothing. publish_cultnet_message_to_rudp_catalog no longer quotes a catalog's text unfiltered: it reports "refused the put", quoting the text only when it is one of the fixed refusals. The test fixtures' sink and source errors carry a canary; the refused peer's text is the fixed one and never contains it. A fake catalog that refuses with a canary of its own shows the publisher's error stays fixed. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-rs/src/lib.rs | 119 ++++++++++++++++-- .../cultmesh-rs/src/rudp_document_server.rs | 44 ++++++- .../cultmesh-rs/tests/rudp_document_server.rs | 24 ++-- 3 files changed, 165 insertions(+), 22 deletions(-) diff --git a/packages/cultmesh-rs/src/lib.rs b/packages/cultmesh-rs/src/lib.rs index 631e1c2f..8494e57d 100644 --- a/packages/cultmesh-rs/src/lib.rs +++ b/packages/cultmesh-rs/src/lib.rs @@ -867,7 +867,8 @@ fn unix_millis() -> u128 { /// /// Each call owns a fresh connection epoch and returns only after the catalog /// acknowledges reliable application admission. A catalog that refuses the -/// message answers with a `cultnet.error.v0`, returned as an error naming it. +/// message answers with a `cultnet.error.v0`, returned as an error that names +/// the refusal when it is one of the fixed texts a CultMesh catalog sends. pub fn publish_cultnet_message_to_rudp_catalog( message: &cultnet_rs::CultNetMessage, options: CultMeshRudpDocumentPublishOptions, @@ -897,10 +898,15 @@ pub fn publish_cultnet_message_to_rudp_catalog( ) { let _ = client.disconnect(b"document-refused".to_vec()); - anyhow::bail!( - "CultMesh RUDP catalog {} refused the message: {error}", - options.target - ); + // The catalog's text is quoted only when it is one of the + // fixed refusals: any other text could carry anything. + if REFUSAL_TEXTS.contains(&error.as_str()) { + anyhow::bail!( + "CultMesh RUDP catalog {} refused the put: {error}", + options.target + ); + } + anyhow::bail!("CultMesh RUDP catalog {} refused the put", options.target); } } } @@ -1311,7 +1317,7 @@ mod tests { let mut server = CultMeshRudpDocumentServer::new( socket, |_receipt: CultMeshRudpRawDocumentReceipt| { - anyhow::bail!("injected durable sink failure") + anyhow::bail!("injected durable sink failure CANARY-7f3a") }, |_query: &CultMeshRudpSnapshotQuery| Ok(Vec::new()), CultMeshSystemClock::default(), @@ -1349,13 +1355,112 @@ mod tests { assert!( error .to_string() - .contains("refused the message: injected durable sink failure"), + .ends_with("refused the put: the catalog refused the document"), "{error:#}" ); + assert!(!error.to_string().contains("CANARY"), "{error:#}"); assert!(waited < Duration::from_secs(5), "waited {waited:?}"); Ok(()) } + /// A catalog's refusal text is quoted only when it is one of the fixed + /// refusals a CultMesh catalog sends. Any other text, which could carry + /// anything, stays out of the publisher's error. + #[test] + fn a_publisher_never_quotes_a_refusal_it_does_not_recognise() -> Result<()> { + use cultnet_rs::{ + CultNetRudpPacketType, CultNetRudpSendOptions, CultNetRudpSession, + CultNetRudpSessionOptions, decode_rudp_packet, encode_rudp_packet, + }; + let temp = tempfile::tempdir()?; + let node = CultMesh::create_node( + temp.path().join("cultmesh.cc"), + TestDocuments, + Default::default(), + )?; + let socket = UdpSocket::bind("127.0.0.1:0")?; + socket.set_read_timeout(Some(Duration::from_millis(5)))?; + let target = socket.local_addr()?; + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let catalog_stop = stop.clone(); + // A catalog that answers any put with a refusal of its own wording. + let catalog = thread::spawn(move || -> Result<()> { + let mut session: Option = None; + let mut wire = vec![0_u8; 65_535]; + while !catalog_stop.load(std::sync::atomic::Ordering::SeqCst) { + let Ok((bytes, peer)) = socket.recv_from(&mut wire) else { + continue; + }; + let Ok(packet) = decode_rudp_packet(&wire[..bytes]) else { + continue; + }; + if packet.packet_type == CultNetRudpPacketType::Connect { + let mut accepted = CultNetRudpSession::new(CultNetRudpSessionOptions { + connection_id: packet.connection_id, + initial_sequence: None, + resend_delay_ms: 10_000, + max_pending_reliable_packets: Some(64), + }); + let accept = accepted.accept_connect(&packet, 0, Vec::new())?; + socket.send_to(&encode_rudp_packet(&accept)?, peer)?; + session = Some(accepted); + continue; + } + let Some(session) = session.as_mut() else { + continue; + }; + let Ok(received) = session.receive(&packet, 1) else { + continue; + }; + for _put in received.delivered { + let refusal = encode_cultnet_message_to_vec( + &cultnet_rs::CultNetMessage::Error { + error: "no such tenant: CANARY-7f3a".into(), + code: None, + details: None, + }, + CultNetWireContract::CultNetSchemaV0, + )?; + let options = CultNetRudpSendOptions { + reliable: false, + ordered: false, + sequenced: false, + now_ms: 2, + reliable_expire_after_ms: None, + }; + for packet in session.send_many("schema", refusal, options, Some(1200))? { + socket.send_to(&encode_rudp_packet(&packet)?, peer)?; + } + } + } + Ok(()) + }); + + let error = node + .publish_document_to_rudp_catalog( + "note", + &Note { + body: "refused by a stranger".into(), + }, + CultMeshRudpDocumentPublishOptions { + target, + connect_timeout: Duration::from_secs(2), + flush_timeout: Duration::from_secs(10), + poll_interval: Duration::from_millis(2), + resend_delay_ms: 5, + ..CultMeshRudpDocumentPublishOptions::default() + }, + ) + .expect_err("a refused document must fail closed"); + stop.store(true, std::sync::atomic::Ordering::SeqCst); + catalog.join().expect("catalog thread should not panic")?; + assert_eq!( + error.to_string(), + format!("CultMesh RUDP catalog {target} refused the put") + ); + Ok(()) + } + #[test] fn raw_snapshot_preserves_caller_challenge_and_raw_response() -> Result<()> { let expected = cultnet_rs::CultNetRawDocumentRecord { diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index 4d9c8a3f..1a1ef50b 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -274,6 +274,36 @@ impl std::fmt::Display for CultMeshRudpRejectionReason { } } +/// The texts a refused peer is sent, one per rejection variant. They are fixed: +/// a sink's or source's error text can quote what a peer sent, so it stays with +/// the caller that receives the rejection and never reaches the wire. +pub(crate) const REFUSAL_TEXTS: [&str; 8] = [ + "the catalog refused the document", + "the document can never be served", + "the snapshot source failed", + "the snapshot has too many documents", + "the snapshot response is too large", + "the snapshot response could not be encoded", + "the retained payload budget is full", + "the snapshot response could not be queued", +]; + +impl CultMeshRudpRejectionReason { + /// The fixed text the refused peer is sent for this variant. + fn refusal_text(&self) -> &'static str { + REFUSAL_TEXTS[match self { + Self::SinkRefused(_) => 0, + Self::DocumentUnservable { .. } => 1, + Self::SnapshotSourceFailed(_) => 2, + Self::SnapshotTooManyDocuments { .. } => 3, + Self::SnapshotResponseTooLarge { .. } => 4, + Self::ResponseEncodingFailed(_) => 5, + Self::PayloadBudgetFull => 6, + Self::ResponseQueueFailed(_) => 7, + }] + } +} + #[derive(Clone, Debug, PartialEq, Eq)] pub struct CultMeshRudpApplicationRejection { pub session: CultMeshRudpSessionKey, @@ -359,9 +389,11 @@ where /// /// Application rejection invalidates only the responsible peer session and /// is returned as data so a daemon can log it and keep serving. The peer is - /// sent the refusal as a `cultnet.error.v0` carrying the reason's text, then - /// a goodbye; neither acknowledges the refused message. Local socket and - /// server-state failures remain errors. + /// sent the refusal as a `cultnet.error.v0` carrying fixed text for the + /// rejection's variant, then a goodbye; neither acknowledges the refused + /// message. The rejection's own detail, which can quote a sink's or + /// source's error, stays with the caller. Local socket and server-state + /// failures remain errors. pub fn poll_once(&mut self) -> Result { self.maintain()?; let mut wire = vec![0_u8; MAX_UDP_DATAGRAM_BYTES]; @@ -460,7 +492,7 @@ where now_unix, now_monotonic, )? { - self.end_rejected_session(key, rejection.reason.to_string())?; + self.end_rejected_session(key, rejection.reason.refusal_text())?; return Ok(CultMeshRudpPollOutcome::ApplicationRejected(rejection)); } } @@ -757,12 +789,12 @@ where /// has emptied: it must not acknowledge the refused message, because a /// publisher reads that acknowledgement as admission. A refusal that cannot /// be encoded or queued is not sent; the goodbye still is. - fn end_rejected_session(&mut self, key: CultMeshRudpSessionKey, reason: String) -> Result<()> { + fn end_rejected_session(&mut self, key: CultMeshRudpSessionKey, reason: &str) -> Result<()> { let Some(mut entry) = self.sessions.remove(&key) else { return Ok(()); }; let refusal = CultNetMessage::Error { - error: reason, + error: reason.into(), code: None, details: None, }; diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index b30f1c14..d166d546 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -41,7 +41,7 @@ impl CultMeshRudpRawDocumentSink for Sink { let mut state = self.0.lock().unwrap(); if state.failures_remaining > 0 { state.failures_remaining -= 1; - anyhow::bail!("injected sink failure"); + anyhow::bail!("injected sink failure CANARY-7f3a"); } state.receipts.push(receipt); Ok(()) @@ -95,7 +95,7 @@ impl CultMeshRudpSnapshotSource for Source { state.calls += 1; if state.failures_remaining > 0 { state.failures_remaining -= 1; - anyhow::bail!("injected source failure"); + anyhow::bail!("injected source failure CANARY-7f3a"); } Ok(state.documents.clone()) } @@ -335,7 +335,8 @@ fn poll_until_rejected_or_stored( anyhow::bail!("the put was neither refused nor stored") } -/// What a refused peer is sent: a `cultnet.error.v0`, then the goodbye. The +/// What a refused peer is sent: a `cultnet.error.v0` carrying fixed text, never +/// a sink's or source's error (the fixtures' errors carry a canary), then the goodbye. The /// refused message is never acknowledged, so its receipt stays pending until the /// goodbye invalidates it. Returns the refusal's text. fn refusal_seen_by( @@ -362,6 +363,7 @@ fn refusal_seen_by( panic!("the refused peer was sent no refusal: {refusal:?}"); }; assert_eq!((code, details), (None, None)); + assert!(!error.contains("CANARY"), "a sink's or source's text reached the peer: {error}"); assert_eq!( client.reliable_send_status(receipt), CultNetRudpReliableSendStatus::Pending, @@ -662,12 +664,13 @@ fn application_rejection_is_nonfatal_peer_scoped_refused_to_the_peer_and_unackno assert_eq!(rejection.message_id, "rejected-put"); assert_eq!( rejection.reason, - CultMeshRudpRejectionReason::SinkRefused("injected sink failure".into()) + CultMeshRudpRejectionReason::SinkRefused("injected sink failure CANARY-7f3a".into()) ); assert_eq!(server.session_count(), 2); + // The caller keeps the sink's text; the peer is sent fixed text, never it. assert_eq!( refusal_seen_by(&mut publisher, &publish_receipt)?, - "injected sink failure" + "the catalog refused the document" ); drain_until_idle(&mut server)?; @@ -690,12 +693,12 @@ fn application_rejection_is_nonfatal_peer_scoped_refused_to_the_peer_and_unackno assert_eq!(rejection.message_id, "rejected-snapshot"); assert_eq!( rejection.reason, - CultMeshRudpRejectionReason::SnapshotSourceFailed("injected source failure".into()) + CultMeshRudpRejectionReason::SnapshotSourceFailed("injected source failure CANARY-7f3a".into()) ); assert_eq!(server.session_count(), 1); assert_eq!( refusal_seen_by(&mut snapshot_client, &snapshot_receipt)?, - "injected source failure" + "the snapshot source failed" ); drain_until_idle(&mut server)?; @@ -842,7 +845,7 @@ fn payload_and_snapshot_output_budgets_fail_closed() -> Result<()> { assert_eq!(snapshot_server.session_count(), 0); assert_eq!( refusal_seen_by(&mut snapshot_client, &receipt)?, - rejection.reason.to_string() + "the snapshot response is too large" ); Ok(()) } @@ -904,7 +907,10 @@ fn a_put_the_server_could_never_serve_is_refused_and_one_at_the_bound_is_served( assert_eq!(server.session_count(), 1); // The peer hears the refusal and why, rather than waiting on a put that // will never be acknowledged. - assert_eq!(refusal_seen_by(&mut refused, &refused_receipt)?, sentence); + assert_eq!( + refusal_seen_by(&mut refused, &refused_receipt)?, + "the document can never be served" + ); send( &mut writer, From abc847337d9948f05f679017b3d58c2bb9eea36b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 19:41:35 +0200 Subject: [PATCH 34/44] cultmesh-rs: the refusal is sent unreliable and unordered The refusal went reliable and ordered, but the session ends with it, so it is never resent: a peer missing any earlier reliable packet from the server held it behind that gap forever. It now goes unreliable and unordered, so it is delivered on arrival whatever the peer is missing. The test drops the server's snapshot reply before the refused put: the refusal still arrives, followed by the goodbye. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/src/rudp_document_server.rs | 14 +-- .../cultmesh-rs/tests/rudp_document_server.rs | 102 ++++++++++++++++++ 2 files changed, 110 insertions(+), 6 deletions(-) diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index 1a1ef50b..8a2706fd 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -785,10 +785,12 @@ where /// The server refused a peer's message: the session ends, and the peer is /// sent the refusal before the goodbye, so it can tell a refusal from loss. - /// The refusal carries the goodbye's acknowledgement fields, which the reset - /// has emptied: it must not acknowledge the refused message, because a - /// publisher reads that acknowledgement as admission. A refusal that cannot - /// be encoded or queued is not sent; the goodbye still is. + /// The refusal is unreliable and unordered: the session ends with it, so it + /// is never resent, and a gap in what the peer has received must not hold + /// it back. It carries the goodbye's acknowledgement fields, which the + /// reset has emptied: it must not acknowledge the refused message, because + /// a publisher reads that acknowledgement as admission. A refusal that + /// cannot be encoded is not sent; the goodbye still is. fn end_rejected_session(&mut self, key: CultMeshRudpSessionKey, reason: &str) -> Result<()> { let Some(mut entry) = self.sessions.remove(&key) else { return Ok(()); @@ -804,8 +806,8 @@ where "schema", payload, CultNetRudpSendOptions { - reliable: true, - ordered: true, + reliable: false, + ordered: false, sequenced: false, now_ms: self.clock.now_monotonic_millis(), reliable_expire_after_ms: None, diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index d166d546..348bc67a 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -1385,3 +1385,105 @@ fn a_connect_storm_and_stray_frames_are_dropped_not_fatal() -> Result<()> { assert_eq!(sink.0.lock().unwrap().receipts.len(), 1); Ok(()) } + +/// The refusal is unreliable and unordered: a peer missing an earlier reliable +/// packet from the server still receives it. An ordered refusal would wait +/// behind the gap for a resend that never comes, because the session ends with it. +#[test] +fn a_refusal_reaches_a_peer_missing_an_earlier_packet() -> Result<()> { + use cultnet_rs::{ + CultNetRudpPacket, CultNetRudpPacketType, CultNetRudpSendOptions, CultNetRudpSession, + CultNetRudpSessionOptions, decode_rudp_packet, encode_rudp_packet, + }; + let mut server = server( + Default::default(), + Clock::new(71_000), + Sink::fail_once(), + Source::documents(vec![document("held", vec![1, 2, 3])]), + )?; + let target = server.local_addr()?; + let peer = UdpSocket::bind("127.0.0.1:0")?; + peer.set_read_timeout(Some(Duration::from_millis(50)))?; + let received = || -> Option { + let mut wire = vec![0_u8; 65_535]; + let (bytes, _) = peer.recv_from(&mut wire).ok()?; + decode_rudp_packet(&wire[..bytes]).ok() + }; + let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions { + connection_id: 78, + initial_sequence: Some(100), + resend_delay_ms: 10_000, + max_pending_reliable_packets: Some(64), + }); + peer.send_to(&encode_rudp_packet(&session.create_connect(0, Vec::new())?)?, target)?; + server.poll_once()?; + let accept = received().expect("the server accepts the connect"); + assert_eq!(accept.packet_type, CultNetRudpPacketType::Accept); + session.receive(&accept, 1)?; + let reliable = CultNetRudpSendOptions { + reliable: true, + ordered: true, + sequenced: false, + now_ms: 2, + reliable_expire_after_ms: None, + }; + let send = |session: &mut CultNetRudpSession, message: &CultNetMessage| -> Result<()> { + let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?; + for packet in session.send_many("schema", payload, reliable.clone(), Some(1200))? { + peer.send_to(&encode_rudp_packet(&packet)?, target)?; + } + Ok(()) + }; + + // The snapshot reply is lost: the peer never sees it, so its ordered + // stream from the server has a gap. + send( + &mut session, + &CultNetMessage::SnapshotRequest { + message_id: "lost".into(), + schema_ids: None, + record_keys: None, + }, + )?; + assert_eq!(server.poll_once()?, CultMeshRudpPollOutcome::Handled); + let mut lost = 0; + while received().is_some() { + lost += 1; + } + assert!(lost > 0, "fixture: the server sent the reply that is lost"); + + send( + &mut session, + &CultNetMessage::DocumentPutRaw { + message_id: "refused".into(), + document: document("refused", vec![4, 5, 6]), + }, + )?; + assert!(matches!( + server.poll_once()?, + CultMeshRudpPollOutcome::ApplicationRejected(_) + )); + let mut delivered = Vec::new(); + let mut disconnected = false; + while let Some(packet) = received() { + let result = session.receive(&packet, 3)?; + delivered.extend(result.delivered); + disconnected |= result.disconnected; + } + let refusals: Vec<_> = delivered + .iter() + .map(|frame| { + decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0) + }) + .collect::>()?; + assert_eq!( + refusals, + vec![CultNetMessage::Error { + error: "the catalog refused the document".into(), + code: None, + details: None, + }] + ); + assert!(disconnected, "the refusal is followed by a goodbye"); + Ok(()) +} From ddf24ad1ec0ca4d866039539079467c9e4359f78 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 20:01:21 +0200 Subject: [PATCH 35/44] cultmesh-rs: rustfmt the canary assertions Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-rs/tests/rudp_document_server.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index 348bc67a..a3f5abcc 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -363,7 +363,10 @@ fn refusal_seen_by( panic!("the refused peer was sent no refusal: {refusal:?}"); }; assert_eq!((code, details), (None, None)); - assert!(!error.contains("CANARY"), "a sink's or source's text reached the peer: {error}"); + assert!( + !error.contains("CANARY"), + "a sink's or source's text reached the peer: {error}" + ); assert_eq!( client.reliable_send_status(receipt), CultNetRudpReliableSendStatus::Pending, @@ -693,7 +696,9 @@ fn application_rejection_is_nonfatal_peer_scoped_refused_to_the_peer_and_unackno assert_eq!(rejection.message_id, "rejected-snapshot"); assert_eq!( rejection.reason, - CultMeshRudpRejectionReason::SnapshotSourceFailed("injected source failure CANARY-7f3a".into()) + CultMeshRudpRejectionReason::SnapshotSourceFailed( + "injected source failure CANARY-7f3a".into() + ) ); assert_eq!(server.session_count(), 1); assert_eq!( From 2ee707d05e660dc0f9fb30be6ecce3fc495ec114 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 20:50:43 +0200 Subject: [PATCH 36/44] cultmesh-rs: no permanent send failure is dropped when a rejection ends the session A reply sent earlier in the same poll could fail permanently and then be dropped when a rejection returned first; and a refusal fragment that can never be sent must end the session naming its error. Both now reach end_session as the unsendable end. The test makes the refusal itself unsendable: the peer's goodbye names the error, nothing is counted as a lost datagram, and the other peer is served. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/src/rudp_document_server.rs | 11 ++++-- .../send_failure_tests.rs | 37 +++++++++++++++++++ 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index 6c2bf639..afdfeea6 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -546,11 +546,14 @@ where now_unix, now_monotonic, )? { - let end = match rejection.reason { - CultMeshRudpRejectionReason::ResponseSendFailed(kind) => { - SessionEnd::Unsendable(std::io::Error::from(kind)) + // A reply that already failed permanently this poll is not dropped: + // the session ends over it. + let end = match (unsendable.take(), &rejection.reason) { + (Some(error), _) => SessionEnd::Unsendable(error), + (None, CultMeshRudpRejectionReason::ResponseSendFailed(kind)) => { + SessionEnd::Unsendable(std::io::Error::from(*kind)) } - ref reason => SessionEnd::Rejected(reason.refusal_text()), + (None, reason) => SessionEnd::Rejected(reason.refusal_text()), }; self.end_session(key, end)?; return Ok(CultMeshRudpPollOutcome::ApplicationRejected(rejection)); diff --git a/packages/cultmesh-rs/src/rudp_document_server/send_failure_tests.rs b/packages/cultmesh-rs/src/rudp_document_server/send_failure_tests.rs index 8c48a092..dd6b0069 100644 --- a/packages/cultmesh-rs/src/rudp_document_server/send_failure_tests.rs +++ b/packages/cultmesh-rs/src/rudp_document_server/send_failure_tests.rs @@ -456,3 +456,40 @@ fn a_reset_reported_by_a_receive_is_idle_not_an_error() { } assert_eq!(received.lock().unwrap().as_slice(), ["y-put"]); } + +#[test] +fn a_refusal_that_can_never_be_sent_ends_the_session_naming_the_error() { + let (mut server, _clock, received, (mut x, x_addr), (mut y, _)) = two_peers(); + // Any document is now unservable, so X's put is refused; the refusal is + // the first datagram X is owed, and it can never be sent as built. + server.options.max_snapshot_response_bytes = 16; + server.unsendable_after.insert(x_addr, 0); + send(&mut x, &put("x-put")); + let mut rejected = false; + for _ in 0..10 { + rejected |= matches!( + server.poll_once().unwrap(), + CultMeshRudpPollOutcome::ApplicationRejected(_) + ); + } + assert!(rejected); + assert!(received.lock().unwrap().is_empty()); + assert_eq!(server.session_count(), 1); + // The failure is not dropped: the goodbye names it, where a refusal's + // goodbye would say the session refused a packet. + assert!(is_unsendable_reason(&goodbye_reason(&mut x))); + assert_eq!(server.send_failures(), 0); + server.options.max_snapshot_response_bytes = + CultMeshRudpDocumentServerOptions::default().max_snapshot_response_bytes; + send(&mut y, &snapshot("y-snapshot")); + let mut served = false; + for _ in 0..50 { + server.poll_once().unwrap(); + if y.receive_once().unwrap().is_some() { + served = true; + break; + } + thread::sleep(Duration::from_millis(1)); + } + assert!(served, "the other peer is still served"); +} From fa34b68593bcd520caa8eee85532e59d13d6b893 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 21:05:45 +0200 Subject: [PATCH 37/44] cultmesh-rs: drop the unreachable earlier-failure arm; rustfmt the resolution receive() returns a reply only for a Ping, answered with a Pong, and a Ping delivers no frame, so no rejection can follow an earlier send in the same poll. The arm that carried such a failure into the rejection's end was dead code; its mutant survived for that reason. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/src/rudp_document_server.rs | 17 ++++++++++------- .../rudp_document_server/send_failure_tests.rs | 9 +++++++-- .../cultmesh-rs/tests/rudp_document_server.rs | 5 ++++- 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index afdfeea6..ad66148b 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -546,14 +546,13 @@ where now_unix, now_monotonic, )? { - // A reply that already failed permanently this poll is not dropped: - // the session ends over it. - let end = match (unsendable.take(), &rejection.reason) { - (Some(error), _) => SessionEnd::Unsendable(error), - (None, CultMeshRudpRejectionReason::ResponseSendFailed(kind)) => { + // The only reply `receive` returns is a Pong, which delivers no + // frame, so no earlier send of this poll can precede a rejection. + let end = match &rejection.reason { + CultMeshRudpRejectionReason::ResponseSendFailed(kind) => { SessionEnd::Unsendable(std::io::Error::from(*kind)) } - (None, reason) => SessionEnd::Rejected(reason.refusal_text()), + reason => SessionEnd::Rejected(reason.refusal_text()), }; self.end_session(key, end)?; return Ok(CultMeshRudpPollOutcome::ApplicationRejected(rejection)); @@ -896,7 +895,11 @@ where } /// The refusal a rejected peer is sent, as unreliable, unordered packets. - fn refusal_packets(&self, session: &mut CultNetRudpSession, text: &str) -> Vec { + fn refusal_packets( + &self, + session: &mut CultNetRudpSession, + text: &str, + ) -> Vec { let refusal = CultNetMessage::Error { error: text.into(), code: None, diff --git a/packages/cultmesh-rs/src/rudp_document_server/send_failure_tests.rs b/packages/cultmesh-rs/src/rudp_document_server/send_failure_tests.rs index dd6b0069..9479ee36 100644 --- a/packages/cultmesh-rs/src/rudp_document_server/send_failure_tests.rs +++ b/packages/cultmesh-rs/src/rudp_document_server/send_failure_tests.rs @@ -299,8 +299,13 @@ fn a_permanent_failure_sending_a_snapshot_response_rejects_it_and_sends_no_refus } thread::sleep(Duration::from_millis(2)); } - assert!(frames.is_empty(), "no refusal is sent to an unreachable peer: {frames:?}"); - assert!(is_unsendable_reason(&reason.expect("the client was told the session ended"))); + assert!( + frames.is_empty(), + "no refusal is sent to an unreachable peer: {frames:?}" + ); + assert!(is_unsendable_reason( + &reason.expect("the client was told the session ended") + )); } #[test] diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index 596c08ba..7cb02938 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -1420,7 +1420,10 @@ fn a_refusal_reaches_a_peer_missing_an_earlier_packet() -> Result<()> { resend_delay_ms: 10_000, max_pending_reliable_packets: Some(64), }); - peer.send_to(&encode_rudp_packet(&session.create_connect(0, Vec::new())?)?, target)?; + peer.send_to( + &encode_rudp_packet(&session.create_connect(0, Vec::new())?)?, + target, + )?; server.poll_once()?; let accept = received().expect("the server accepts the connect"); assert_eq!(accept.packet_type, CultNetRudpPacketType::Accept); From 5ef988b1d065367868b04b6623f55feb874aa2b4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 23:01:33 +0200 Subject: [PATCH 38/44] cultnet-rs, cultmesh-rs: an unsendable goodbye names the failure by a fixed code end_unsendable_session put the io::Error's Display on the wire: the platform's wording, which differs by OS and by which packet failed. cultnet-rs gains send_error_code, the fixed name of a failed send's cause (EMSGSIZE, EINVAL, EAFNOSUPPORT, or UNKNOWN), matching the codes the TypeScript goodbye already carries; is_permanent_send_error is now "has a known code". The goodbye reads "packet could not be sent: CODE". ResponseSendFailed carried an ErrorKind, which lost the cause (EMSGSIZE has no kind and read as Uncategorized). It now carries the same fixed code, and the session ends where the send failed, over the real error, so the goodbye and the caller's rejection name the same failure. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/src/rudp_document_server.rs | 32 ++++--- .../send_failure_tests.rs | 10 +- packages/cultnet-rs/src/rudp.rs | 94 ++++++++++++------- .../cultnet-rs/src/rudp/send_failure_tests.rs | 29 ++++++ 4 files changed, 114 insertions(+), 51 deletions(-) diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index ad66148b..09c31adf 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -3,7 +3,7 @@ use cultnet_rs::{ CultNetMessage, CultNetRawDocumentRecord, CultNetRudpPacket, CultNetRudpPacketType, CultNetRudpSendOptions, CultNetRudpSession, CultNetRudpSessionOptions, CultNetWireContract, decode_cultnet_message_from_slice, decode_rudp_packet, encode_cultnet_message_to_vec, - encode_rudp_packet, is_permanent_send_error, + encode_rudp_packet, is_permanent_send_error, send_error_code, }; use std::collections::BTreeMap; #[cfg(test)] @@ -237,9 +237,10 @@ pub enum CultMeshRudpRejectionReason { /// The session could not queue the response. Carries the session's error text. ResponseQueueFailed(String), /// A packet of the response can never be sent to the peer as built - /// (`is_permanent_send_error`). The session ends with a goodbye naming the - /// error, and no refusal: the server knows the peer cannot be reached. - ResponseSendFailed(std::io::ErrorKind), + /// (`is_permanent_send_error`). Carries the failure's fixed name + /// (`send_error_code`). The session has ended with a goodbye carrying the + /// same name, and no refusal: the server knows the peer cannot be reached. + ResponseSendFailed(&'static str), } impl std::fmt::Display for CultMeshRudpRejectionReason { @@ -276,8 +277,8 @@ impl std::fmt::Display for CultMeshRudpRejectionReason { Self::ResponseQueueFailed(error) => { write!(f, "snapshot response could not be queued: {error}") } - Self::ResponseSendFailed(kind) => { - write!(f, "snapshot response could not be sent: {kind}") + Self::ResponseSendFailed(code) => { + write!(f, "snapshot response could not be sent: {code}") } } } @@ -548,13 +549,14 @@ where )? { // The only reply `receive` returns is a Pong, which delivers no // frame, so no earlier send of this poll can precede a rejection. - let end = match &rejection.reason { - CultMeshRudpRejectionReason::ResponseSendFailed(kind) => { - SessionEnd::Unsendable(std::io::Error::from(*kind)) - } - reason => SessionEnd::Rejected(reason.refusal_text()), - }; - self.end_session(key, end)?; + // A response that could not be sent ended its session where the + // send failed, over the real error. + if !matches!( + rejection.reason, + CultMeshRudpRejectionReason::ResponseSendFailed(_) + ) { + self.end_session(key, SessionEnd::Rejected(rejection.reason.refusal_text()))?; + } return Ok(CultMeshRudpPollOutcome::ApplicationRejected(rejection)); } } @@ -840,11 +842,13 @@ where entry.admitted_payload_bytes.saturating_add(payload_bytes); for packet in &packets { if let Some(error) = self.send_packet(key.remote_addr, packet)? { + let code = send_error_code(&error); + self.end_session(key, SessionEnd::Unsendable(error))?; return Ok(Some(CultMeshRudpApplicationRejection { session: key, operation: CultMeshRudpApplicationOperation::SnapshotRequest, message_id, - reason: CultMeshRudpRejectionReason::ResponseSendFailed(error.kind()), + reason: CultMeshRudpRejectionReason::ResponseSendFailed(code), })); } } diff --git a/packages/cultmesh-rs/src/rudp_document_server/send_failure_tests.rs b/packages/cultmesh-rs/src/rudp_document_server/send_failure_tests.rs index 9479ee36..bbf3dee1 100644 --- a/packages/cultmesh-rs/src/rudp_document_server/send_failure_tests.rs +++ b/packages/cultmesh-rs/src/rudp_document_server/send_failure_tests.rs @@ -282,7 +282,7 @@ fn a_permanent_failure_sending_a_snapshot_response_rejects_it_and_sends_no_refus assert_eq!(rejection.message_id, "x-snapshot"); assert_eq!( rejection.reason, - CultMeshRudpRejectionReason::ResponseSendFailed(ErrorKind::InvalidInput) + CultMeshRudpRejectionReason::ResponseSendFailed("EINVAL") ); assert_eq!(server.session_count(), 1); // The server knows X cannot be reached: X is sent no refusal, only the @@ -303,9 +303,11 @@ fn a_permanent_failure_sending_a_snapshot_response_rejects_it_and_sends_no_refus frames.is_empty(), "no refusal is sent to an unreachable peer: {frames:?}" ); - assert!(is_unsendable_reason( - &reason.expect("the client was told the session ended") - )); + // The goodbye names the failure by its fixed name, never the error's text. + assert_eq!( + reason.expect("the client was told the session ended"), + b"packet could not be sent: EINVAL" + ); } #[test] diff --git a/packages/cultnet-rs/src/rudp.rs b/packages/cultnet-rs/src/rudp.rs index f91a3f1e..37bf73d8 100644 --- a/packages/cultnet-rs/src/rudp.rs +++ b/packages/cultnet-rs/src/rudp.rs @@ -472,10 +472,16 @@ impl CultNetRudpSession { /// built (see `is_permanent_send_error`). Resending it would fail forever, /// and dropping it would leave a reliable sequence the peer waits on for /// good, so the session cannot be kept. Returns the goodbye for the peer; - /// its reason names the error. + /// its reason names the failure by its fixed name (`send_error_code`). pub fn end_unsendable_session(&mut self, error: &std::io::Error) -> CultNetRudpPacket { self.reset_peer_state(); - self.create_disconnect(format!("{RUDP_UNSENDABLE_PACKET_REASON}: {error}").into_bytes()) + self.create_disconnect( + format!( + "{RUDP_UNSENDABLE_PACKET_REASON}: {}", + send_error_code(error) + ) + .into_bytes(), + ) } /// Undoes a send that never reached the wire: every packet it created at @@ -2599,7 +2605,7 @@ where const RUDP_REFUSED_PACKET_REASON: &[u8] = b"session refused a packet"; const SESSION_TIMED_OUT_REASON: &[u8] = b"session timed out"; /// Prefix of the goodbye reason for a session that owed a packet which can -/// never be sent; the error's own description follows it. +/// never be sent; the failure's fixed name (`send_error_code`) follows it. const RUDP_UNSENDABLE_PACKET_REASON: &str = "packet could not be sent"; /// Whether a failed `send_to` can never succeed for the datagram as built, so @@ -2610,37 +2616,59 @@ const RUDP_UNSENDABLE_PACKET_REASON: &str = "packet could not be sent"; /// call) is a property of the path or the moment and may pass, so it is a lost /// datagram, not a reason to end a session. pub fn is_permanent_send_error(error: &std::io::Error) -> bool { - // `EMSGSIZE` and `EAFNOSUPPORT`, or their Winsock equivalents. - #[cfg(any(target_os = "linux", target_os = "android"))] - const PERMANENT_OS_ERRORS: [i32; 2] = [90, 97]; - #[cfg(any( - target_os = "macos", - target_os = "ios", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd", - target_os = "dragonfly" - ))] - const PERMANENT_OS_ERRORS: [i32; 2] = [40, 47]; - #[cfg(windows)] - const PERMANENT_OS_ERRORS: [i32; 2] = [10040, 10047]; - #[cfg(not(any( - target_os = "linux", - target_os = "android", - target_os = "macos", - target_os = "ios", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd", - target_os = "dragonfly", - windows - )))] - const PERMANENT_OS_ERRORS: [i32; 0] = []; + send_error_code(error) != UNKNOWN_SEND_ERROR +} + +const UNKNOWN_SEND_ERROR: &str = "UNKNOWN"; + +// `EMSGSIZE` and `EAFNOSUPPORT`, or their Winsock equivalents. +#[cfg(any(target_os = "linux", target_os = "android"))] +const PERMANENT_OS_ERRORS: Option<(i32, i32)> = Some((90, 97)); +#[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + target_os = "dragonfly" +))] +const PERMANENT_OS_ERRORS: Option<(i32, i32)> = Some((40, 47)); +#[cfg(windows)] +const PERMANENT_OS_ERRORS: Option<(i32, i32)> = Some((10040, 10047)); +#[cfg(not(any( + target_os = "linux", + target_os = "android", + target_os = "macos", + target_os = "ios", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + target_os = "dragonfly", + windows +)))] +const PERMANENT_OS_ERRORS: Option<(i32, i32)> = None; + +/// The fixed name of a failed send's cause: `EMSGSIZE`, `EINVAL` or +/// `EAFNOSUPPORT` for a failure that can never pass +/// (`is_permanent_send_error`), `UNKNOWN` for anything else. An unsendable +/// session's goodbye carries this name, never the error's own text, which is +/// the platform's wording and can differ by the packet that failed. +pub fn send_error_code(error: &std::io::Error) -> &'static str { + if let (Some(code), Some((message_size, address_family))) = + (error.raw_os_error(), PERMANENT_OS_ERRORS) + { + if code == message_size { + return "EMSGSIZE"; + } + if code == address_family { + return "EAFNOSUPPORT"; + } + } // `InvalidInput` is `EINVAL` and `WSAEINVAL`. - error.kind() == ErrorKind::InvalidInput - || error - .raw_os_error() - .is_some_and(|code| PERMANENT_OS_ERRORS.contains(&code)) + if error.kind() == ErrorKind::InvalidInput { + return "EINVAL"; + } + UNKNOWN_SEND_ERROR } /// A session cannot admit a Connect when its sequence space starts exhausted or diff --git a/packages/cultnet-rs/src/rudp/send_failure_tests.rs b/packages/cultnet-rs/src/rudp/send_failure_tests.rs index 4bff8cf9..4ea521c3 100644 --- a/packages/cultnet-rs/src/rudp/send_failure_tests.rs +++ b/packages/cultnet-rs/src/rudp/send_failure_tests.rs @@ -500,3 +500,32 @@ fn a_send_refused_at_any_fragment_delivers_nothing_of_it() { } } } + +#[test] +fn a_send_failure_is_named_by_a_fixed_code_never_its_text() { + use std::io::{Error, ErrorKind}; + let named = |error: Error| (send_error_code(&error), is_permanent_send_error(&error)); + assert_eq!( + named(Error::new(ErrorKind::InvalidInput, "CANARY-7f3a")), + ("EINVAL", true) + ); + assert_eq!( + named(Error::new(ErrorKind::ConnectionRefused, "CANARY-7f3a")), + ("UNKNOWN", false) + ); + #[cfg(any(target_os = "linux", target_os = "android"))] + { + assert_eq!(named(Error::from_raw_os_error(90)), ("EMSGSIZE", true)); + assert_eq!(named(Error::from_raw_os_error(97)), ("EAFNOSUPPORT", true)); + assert_eq!(named(Error::from_raw_os_error(111)), ("UNKNOWN", false)); + } + let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions { + connection_id: 1, + initial_sequence: None, + resend_delay_ms: 10, + max_pending_reliable_packets: None, + }); + let goodbye = + session.end_unsendable_session(&Error::new(ErrorKind::InvalidInput, "CANARY-7f3a")); + assert_eq!(goodbye.payload, b"packet could not be sent: EINVAL"); +} From b8f754c898cc2b40ed40d6ef03a9f3f45eb5e791 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 23:01:33 +0200 Subject: [PATCH 39/44] cultmesh-rs: the snapshot client quotes only a refusal it recognises; the publisher doc says what holds request_raw_snapshot_from_rudp_catalog put a catalog's error text into its own error unfiltered. It now reports "refused the snapshot", naming the refusal only when it is one of the fixed CultMesh refusal texts, as the publisher does; both share recognised_refusal. The publisher's doc claimed any refusing catalog is reported as a refusal. That holds against a Rust catalog, which never acknowledges a message it refuses; a catalog that acknowledges on receipt and refuses afterwards (the TypeScript document server) is reported as having admitted it. The doc now says so. A fake catalog refusing with a canary is shared by the publisher test and a new snapshot-client test. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-rs/src/lib.rs | 108 ++++++++++++++++++++++++-------- 1 file changed, 81 insertions(+), 27 deletions(-) diff --git a/packages/cultmesh-rs/src/lib.rs b/packages/cultmesh-rs/src/lib.rs index 8494e57d..1af0d906 100644 --- a/packages/cultmesh-rs/src/lib.rs +++ b/packages/cultmesh-rs/src/lib.rs @@ -822,7 +822,11 @@ pub fn request_raw_snapshot_from_rudp_catalog( } cultnet_rs::CultNetMessage::Error { error, .. } => { let _ = client.disconnect(b"snapshot-error".to_vec()); - anyhow::bail!("CultMesh RUDP snapshot failed: {error}"); + anyhow::bail!( + "CultMesh RUDP catalog {} refused the snapshot{}", + options.target, + recognised_refusal(error) + ); } _ => {} } @@ -856,6 +860,17 @@ pub fn request_raw_snapshot_from_rudp_catalog( ) } +/// A catalog's refusal text, quoted (`": text"`) only when it is one of the +/// fixed refusals a CultMesh catalog sends; any other text could carry +/// anything, so it is left out. +fn recognised_refusal(text: &str) -> String { + if REFUSAL_TEXTS.contains(&text) { + format!(": {text}") + } else { + String::new() + } +} + fn unix_millis() -> u128 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -866,9 +881,12 @@ fn unix_millis() -> u128 { /// Publish one raw CultNet schema message to a RUDP catalog. /// /// Each call owns a fresh connection epoch and returns only after the catalog -/// acknowledges reliable application admission. A catalog that refuses the -/// message answers with a `cultnet.error.v0`, returned as an error that names -/// the refusal when it is one of the fixed texts a CultMesh catalog sends. +/// acknowledges reliable application admission. Against a Rust CultMesh +/// catalog, which never acknowledges a message it refuses, a refusal is +/// returned as an error, naming the refusal when it is one of the fixed texts +/// such a catalog sends. A catalog that acknowledges a message on receipt and +/// refuses it afterwards (the TypeScript document server does) is reported as +/// having admitted it: the acknowledgement arrives first. pub fn publish_cultnet_message_to_rudp_catalog( message: &cultnet_rs::CultNetMessage, options: CultMeshRudpDocumentPublishOptions, @@ -898,15 +916,11 @@ pub fn publish_cultnet_message_to_rudp_catalog( ) { let _ = client.disconnect(b"document-refused".to_vec()); - // The catalog's text is quoted only when it is one of the - // fixed refusals: any other text could carry anything. - if REFUSAL_TEXTS.contains(&error.as_str()) { - anyhow::bail!( - "CultMesh RUDP catalog {} refused the put: {error}", - options.target - ); - } - anyhow::bail!("CultMesh RUDP catalog {} refused the put", options.target); + anyhow::bail!( + "CultMesh RUDP catalog {} refused the put{}", + options.target, + recognised_refusal(&error) + ); } } } @@ -1363,27 +1377,24 @@ mod tests { Ok(()) } - /// A catalog's refusal text is quoted only when it is one of the fixed - /// refusals a CultMesh catalog sends. Any other text, which could carry - /// anything, stays out of the publisher's error. - #[test] - fn a_publisher_never_quotes_a_refusal_it_does_not_recognise() -> Result<()> { + /// A catalog that answers every message with a refusal of its own wording, + /// never acknowledging it. Stops when the flag is set. + fn refusing_catalog( + text: &'static str, + ) -> Result<( + SocketAddr, + std::sync::Arc, + thread::JoinHandle>, + )> { use cultnet_rs::{ CultNetRudpPacketType, CultNetRudpSendOptions, CultNetRudpSession, CultNetRudpSessionOptions, decode_rudp_packet, encode_rudp_packet, }; - let temp = tempfile::tempdir()?; - let node = CultMesh::create_node( - temp.path().join("cultmesh.cc"), - TestDocuments, - Default::default(), - )?; let socket = UdpSocket::bind("127.0.0.1:0")?; socket.set_read_timeout(Some(Duration::from_millis(5)))?; let target = socket.local_addr()?; let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let catalog_stop = stop.clone(); - // A catalog that answers any put with a refusal of its own wording. let catalog = thread::spawn(move || -> Result<()> { let mut session: Option = None; let mut wire = vec![0_u8; 65_535]; @@ -1412,10 +1423,10 @@ mod tests { let Ok(received) = session.receive(&packet, 1) else { continue; }; - for _put in received.delivered { + for _message in received.delivered { let refusal = encode_cultnet_message_to_vec( &cultnet_rs::CultNetMessage::Error { - error: "no such tenant: CANARY-7f3a".into(), + error: text.into(), code: None, details: None, }, @@ -1435,7 +1446,21 @@ mod tests { } Ok(()) }); + Ok((target, stop, catalog)) + } + /// A catalog's refusal text is quoted only when it is one of the fixed + /// refusals a CultMesh catalog sends. Any other text, which could carry + /// anything, stays out of the publisher's error. + #[test] + fn a_publisher_never_quotes_a_refusal_it_does_not_recognise() -> Result<()> { + let temp = tempfile::tempdir()?; + let node = CultMesh::create_node( + temp.path().join("cultmesh.cc"), + TestDocuments, + Default::default(), + )?; + let (target, stop, catalog) = refusing_catalog("no such tenant: CANARY-7f3a")?; let error = node .publish_document_to_rudp_catalog( "note", @@ -1461,6 +1486,35 @@ mod tests { Ok(()) } + /// The snapshot client filters a catalog's refusal the same way: a fixed + /// refusal is named, any other text is left out. + #[test] + fn a_snapshot_client_quotes_only_a_refusal_it_recognises() -> Result<()> { + for (text, expected) in [ + ("no such tenant: CANARY-7f3a", ""), + ("the snapshot source failed", ": the snapshot source failed"), + ] { + let (target, stop, catalog) = refusing_catalog(text)?; + let error = request_raw_snapshot_from_rudp_catalog(CultMeshRudpSnapshotOptions { + target, + message_id: "refused".into(), + connect_timeout: Duration::from_secs(2), + response_timeout: Duration::from_secs(10), + poll_interval: Duration::from_millis(2), + resend_delay_ms: 5, + ..CultMeshRudpSnapshotOptions::default() + }) + .expect_err("a refused snapshot must fail"); + stop.store(true, std::sync::atomic::Ordering::SeqCst); + catalog.join().expect("catalog thread should not panic")?; + assert_eq!( + error.to_string(), + format!("CultMesh RUDP catalog {target} refused the snapshot{expected}") + ); + } + Ok(()) + } + #[test] fn raw_snapshot_preserves_caller_challenge_and_raw_response() -> Result<()> { let expected = cultnet_rs::CultNetRawDocumentRecord { From a71f62e99739151d06b774c9432e51b188bd9e46 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 23:01:33 +0200 Subject: [PATCH 40/44] cultmesh-rs: pin the refusal at a queue full to the brim, and a real EMSGSIZE The queue-full test used an empty queue, so a reliable refusal fitted and the reliable-refusal mutant lived. The new test fills a queue of 8 exactly with a reply the peer never acknowledges; the next reply cannot be queued, and its refusal must still arrive, acknowledging nothing the peer sent. A RawPeer helper drives the peer packet by packet; the gap test uses it too. A response too large for any datagram fails with the kernel's EMSGSIZE: the rejection is ResponseSendFailed("EMSGSIZE"), the goodbye is exactly "packet could not be sent: EMSGSIZE", and no refusal is sent. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/tests/rudp_document_server.rs | 298 ++++++++++++++---- 1 file changed, 236 insertions(+), 62 deletions(-) diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index 7cb02938..30fe4678 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -1391,90 +1391,128 @@ fn a_connect_storm_and_stray_frames_are_dropped_not_fatal() -> Result<()> { Ok(()) } +/// A peer driven packet by packet, so a test decides what it receives and what +/// it acknowledges. +struct RawPeer { + socket: UdpSocket, + target: SocketAddr, + session: cultnet_rs::CultNetRudpSession, +} + +impl RawPeer { + fn connect( + server: &mut CultMeshRudpDocumentServer, + connection_id: u32, + ) -> Result { + let socket = UdpSocket::bind("127.0.0.1:0")?; + socket.set_read_timeout(Some(Duration::from_millis(50)))?; + let mut peer = Self { + socket, + target: server.local_addr()?, + session: cultnet_rs::CultNetRudpSession::new(cultnet_rs::CultNetRudpSessionOptions { + connection_id, + initial_sequence: Some(100), + resend_delay_ms: 10_000, + max_pending_reliable_packets: Some(64), + }), + }; + let connect = peer.session.create_connect(0, Vec::new())?; + peer.send_packet(&connect)?; + server.poll_once()?; + let accept = peer.receive().expect("the server accepts the connect"); + assert_eq!( + accept.packet_type, + cultnet_rs::CultNetRudpPacketType::Accept + ); + peer.session.receive(&accept, 1)?; + Ok(peer) + } + + fn send_packet(&self, packet: &cultnet_rs::CultNetRudpPacket) -> Result<()> { + self.socket + .send_to(&cultnet_rs::encode_rudp_packet(packet)?, self.target)?; + Ok(()) + } + + /// Sends `message` reliably and in order; returns its sequences. + fn send(&mut self, message: &CultNetMessage) -> Result> { + let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?; + let options = cultnet_rs::CultNetRudpSendOptions { + reliable: true, + ordered: true, + sequenced: false, + now_ms: 2, + reliable_expire_after_ms: None, + }; + let packets = self + .session + .send_many("schema", payload, options, Some(1200))?; + for packet in &packets { + self.send_packet(packet)?; + } + Ok(packets.iter().map(|packet| packet.sequence).collect()) + } + + fn receive(&self) -> Option { + let mut wire = vec![0_u8; 65_535]; + let (bytes, _) = self.socket.recv_from(&mut wire).ok()?; + cultnet_rs::decode_rudp_packet(&wire[..bytes]).ok() + } + + /// Every packet waiting, none of them processed or acknowledged. + fn drain(&self) -> Vec { + std::iter::from_fn(|| self.receive()).collect() + } +} + +/// Whether `packet`'s acknowledgement fields cover `sequence`. +fn acknowledges(packet: &cultnet_rs::CultNetRudpPacket, sequence: u32) -> bool { + packet.ack == sequence + || (0..32).any(|bit| { + packet.ack_mask & (1 << bit) != 0 + && packet.ack > bit + && packet.ack - bit - 1 == sequence + }) +} + /// The refusal is unreliable and unordered: a peer missing an earlier reliable /// packet from the server still receives it. An ordered refusal would wait /// behind the gap for a resend that never comes, because the session ends with it. #[test] fn a_refusal_reaches_a_peer_missing_an_earlier_packet() -> Result<()> { - use cultnet_rs::{ - CultNetRudpPacket, CultNetRudpPacketType, CultNetRudpSendOptions, CultNetRudpSession, - CultNetRudpSessionOptions, decode_rudp_packet, encode_rudp_packet, - }; let mut server = server( Default::default(), Clock::new(71_000), Sink::fail_once(), Source::documents(vec![document("held", vec![1, 2, 3])]), )?; - let target = server.local_addr()?; - let peer = UdpSocket::bind("127.0.0.1:0")?; - peer.set_read_timeout(Some(Duration::from_millis(50)))?; - let received = || -> Option { - let mut wire = vec![0_u8; 65_535]; - let (bytes, _) = peer.recv_from(&mut wire).ok()?; - decode_rudp_packet(&wire[..bytes]).ok() - }; - let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: 78, - initial_sequence: Some(100), - resend_delay_ms: 10_000, - max_pending_reliable_packets: Some(64), - }); - peer.send_to( - &encode_rudp_packet(&session.create_connect(0, Vec::new())?)?, - target, - )?; - server.poll_once()?; - let accept = received().expect("the server accepts the connect"); - assert_eq!(accept.packet_type, CultNetRudpPacketType::Accept); - session.receive(&accept, 1)?; - let reliable = CultNetRudpSendOptions { - reliable: true, - ordered: true, - sequenced: false, - now_ms: 2, - reliable_expire_after_ms: None, - }; - let send = |session: &mut CultNetRudpSession, message: &CultNetMessage| -> Result<()> { - let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?; - for packet in session.send_many("schema", payload, reliable.clone(), Some(1200))? { - peer.send_to(&encode_rudp_packet(&packet)?, target)?; - } - Ok(()) - }; + let mut peer = RawPeer::connect(&mut server, 78)?; // The snapshot reply is lost: the peer never sees it, so its ordered // stream from the server has a gap. - send( - &mut session, - &CultNetMessage::SnapshotRequest { - message_id: "lost".into(), - schema_ids: None, - record_keys: None, - }, - )?; + peer.send(&CultNetMessage::SnapshotRequest { + message_id: "lost".into(), + schema_ids: None, + record_keys: None, + })?; assert_eq!(server.poll_once()?, CultMeshRudpPollOutcome::Handled); - let mut lost = 0; - while received().is_some() { - lost += 1; - } - assert!(lost > 0, "fixture: the server sent the reply that is lost"); + assert!( + !peer.drain().is_empty(), + "fixture: the server sent the reply that is lost" + ); - send( - &mut session, - &CultNetMessage::DocumentPutRaw { - message_id: "refused".into(), - document: document("refused", vec![4, 5, 6]), - }, - )?; + peer.send(&CultNetMessage::DocumentPutRaw { + message_id: "refused".into(), + document: document("refused", vec![4, 5, 6]), + })?; assert!(matches!( server.poll_once()?, CultMeshRudpPollOutcome::ApplicationRejected(_) )); let mut delivered = Vec::new(); let mut disconnected = false; - while let Some(packet) = received() { - let result = session.receive(&packet, 3)?; + for packet in peer.drain() { + let result = peer.session.receive(&packet, 3)?; delivered.extend(result.delivered); disconnected |= result.disconnected; } @@ -1496,6 +1534,92 @@ fn a_refusal_reaches_a_peer_missing_an_earlier_packet() -> Result<()> { Ok(()) } +/// The peer's reliable queue is full to the brim: an 8-fragment reply the peer +/// never acknowledges fills a queue of 8 exactly. The next reply cannot be +/// queued, and its refusal still reaches the peer, because it takes no room in +/// that queue; it acknowledges nothing the peer sent. +#[test] +fn a_refusal_reaches_a_peer_whose_queue_is_full_to_the_brim() -> Result<()> { + let options = CultMeshRudpDocumentServerOptions { + max_fragment_bytes: 100, + max_pending_reliable_packets_per_session: 8, + max_snapshot_response_bytes: 8192, + ..Default::default() + }; + let source = Source::documents(vec![document_served_at("q1", 800)?]); + let mut server = server(options, Clock::new(74_000), Sink::default(), source)?; + let mut peer = RawPeer::connect(&mut server, 79)?; + peer.send(&CultNetMessage::SnapshotRequest { + message_id: "a".into(), + schema_ids: None, + record_keys: None, + })?; + assert_eq!(server.poll_once()?, CultMeshRudpPollOutcome::Handled); + let unacknowledged = peer + .drain() + .into_iter() + .filter(|packet| packet.packet_type == cultnet_rs::CultNetRudpPacketType::Data) + .count(); + assert_eq!( + unacknowledged, 8, + "fixture: the first reply fills the queue exactly" + ); + + let refused = peer.send(&CultNetMessage::SnapshotRequest { + message_id: "b".into(), + schema_ids: None, + record_keys: None, + })?; + let CultMeshRudpPollOutcome::ApplicationRejected(rejection) = server.poll_once()? else { + panic!("the second reply cannot be queued"); + }; + assert!( + matches!( + rejection.reason, + CultMeshRudpRejectionReason::ResponseQueueFailed(_) + ), + "{:?}", + rejection.reason + ); + let arrived = peer.drain(); + let mut parts: Vec<_> = arrived + .iter() + .filter(|packet| { + packet.packet_type == cultnet_rs::CultNetRudpPacketType::Data + && packet.channel_id == "schema" + && !packet.reliable + }) + .collect(); + assert!(!parts.is_empty(), "the refusal reaches the peer"); + for part in &parts { + assert!( + refused + .iter() + .all(|sequence| !acknowledges(part, *sequence)), + "the refusal acknowledges the refused request: ack {} mask {:#x}", + part.ack, + part.ack_mask + ); + } + parts.sort_by_key(|part| part.fragment_index); + let payload: Vec = parts.iter().flat_map(|part| part.payload.clone()).collect(); + assert_eq!( + decode_cultnet_message_from_slice(&payload, CultNetWireContract::CultNetSchemaV0)?, + CultNetMessage::Error { + error: "the snapshot response could not be queued".into(), + code: None, + details: None, + } + ); + assert!( + arrived + .iter() + .any(|packet| packet.packet_type == cultnet_rs::CultNetRudpPacketType::Disconnect), + "the refusal is followed by a goodbye" + ); + Ok(()) +} + /// A snapshot the reliable queue cannot take is answered with a refusal, not /// left to time out: the refusal needs no room in that queue. #[test] @@ -1545,3 +1669,53 @@ fn a_snapshot_the_queue_cannot_take_is_answered() -> Result<()> { ); Ok(()) } + +/// A response too large for any datagram fails with the kernel's EMSGSIZE. The +/// caller's rejection and the peer's goodbye both carry its fixed name, never +/// the platform's text, and the peer is sent no refusal. +#[test] +fn a_response_that_is_too_large_to_send_is_named_emsgsize() -> Result<()> { + let options = CultMeshRudpDocumentServerOptions { + max_fragment_bytes: 70_000, + ..Default::default() + }; + let source = Source::documents(vec![document("big", vec![7; 66_000])]); + let mut server = server(options, Clock::new(73_000), Sink::default(), source)?; + let mut client = client(server.local_addr()?, 152)?; + connect(&mut server, &mut [&mut client])?; + send_reliable( + &mut client, + &CultNetMessage::SnapshotRequest { + message_id: "big".into(), + schema_ids: None, + record_keys: None, + }, + )?; + let mut rejection = None; + for _ in 0..100 { + if let CultMeshRudpPollOutcome::ApplicationRejected(found) = server.poll_once()? { + rejection = Some(found); + break; + } + } + assert_eq!( + rejection.expect("the response can never be sent").reason, + CultMeshRudpRejectionReason::ResponseSendFailed("EMSGSIZE") + ); + let mut frames = 0; + for _ in 0..500 { + if client.receive_once()?.is_some() { + frames += 1; + } + if !client.connected() { + break; + } + thread::sleep(Duration::from_millis(1)); + } + assert_eq!(frames, 0, "no refusal is sent to an unreachable peer"); + assert_eq!( + client.disconnect_reason(), + Some(&b"packet could not be sent: EMSGSIZE"[..]) + ); + Ok(()) +} From c3cc2b49c45325cad8d4e0fe6c20d3f8833f3718 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 23:04:07 +0200 Subject: [PATCH 41/44] cultnet-py: an unsendable goodbye names the failure by a fixed code end_unsendable_session put the OSError's text on the wire, which is the platform's wording and can quote an address. send_error_code names a permanent failure EMSGSIZE, EINVAL or EAFNOSUPPORT (Winsock equivalents included), anything else UNKNOWN, as the Rust and TypeScript goodbyes do; is_permanent_send_error is now "has a known code". Co-Authored-By: Claude Opus 5.5 --- .../cultnet-py/src/cultnet_py/__init__.py | 2 + .../cultnet-py/src/cultnet_py/transport.py | 37 ++++++++++++------- packages/cultnet-py/tests/test_cultnet.py | 12 ++++++ 3 files changed, 38 insertions(+), 13 deletions(-) diff --git a/packages/cultnet-py/src/cultnet_py/__init__.py b/packages/cultnet-py/src/cultnet_py/__init__.py index 3344f438..e8b939c6 100644 --- a/packages/cultnet-py/src/cultnet_py/__init__.py +++ b/packages/cultnet-py/src/cultnet_py/__init__.py @@ -124,6 +124,7 @@ from .transport import ( compute_reconnect_delay_ms, create_reconnect_policy, is_permanent_send_error, + send_error_code, create_rudp_transport_profile, create_tcp_framed_transport_profile, decode_rudp_packet, @@ -211,6 +212,7 @@ __all__ = [ "CultNetRudpSendOptions", "CultNetRudpSession", "is_permanent_send_error", + "send_error_code", "CultNetRudpSessionOptions", "CultNetRudpSocketMode", "CultNetRudpReconnectLoop", diff --git a/packages/cultnet-py/src/cultnet_py/transport.py b/packages/cultnet-py/src/cultnet_py/transport.py index 78ae9542..76b38bf5 100644 --- a/packages/cultnet-py/src/cultnet_py/transport.py +++ b/packages/cultnet-py/src/cultnet_py/transport.py @@ -438,18 +438,28 @@ def create_rudp_transport_profile( UNSENDABLE_PACKET_REASON = "packet could not be sent" -_PERMANENT_SEND_ERRNOS = frozenset( - code - for code in ( - errno.EMSGSIZE, - errno.EINVAL, - errno.EAFNOSUPPORT, - getattr(errno, "WSAEMSGSIZE", None), - getattr(errno, "WSAEINVAL", None), - getattr(errno, "WSAEAFNOSUPPORT", None), +# The fixed name of each permanent send failure, keyed by errno, Winsock equivalents included. +_PERMANENT_SEND_ERROR_CODES = { + code: name + for code, name in ( + (errno.EMSGSIZE, "EMSGSIZE"), + (errno.EINVAL, "EINVAL"), + (errno.EAFNOSUPPORT, "EAFNOSUPPORT"), + (getattr(errno, "WSAEMSGSIZE", None), "EMSGSIZE"), + (getattr(errno, "WSAEINVAL", None), "EINVAL"), + (getattr(errno, "WSAEAFNOSUPPORT", None), "EAFNOSUPPORT"), ) if code is not None -) +} +_UNKNOWN_SEND_ERROR = "UNKNOWN" + + +def send_error_code(error: OSError) -> str: + """The fixed name of a failed send's cause: EMSGSIZE, EINVAL or EAFNOSUPPORT for a + failure that can never pass (`is_permanent_send_error`), UNKNOWN for anything else. An + unsendable session's goodbye carries this name, never the error's own text, which is the + platform's wording and can quote an address.""" + return _PERMANENT_SEND_ERROR_CODES.get(error.errno, _UNKNOWN_SEND_ERROR) def is_permanent_send_error(error: OSError) -> bool: @@ -459,7 +469,7 @@ def is_permanent_send_error(error: OSError) -> bool: Winsock equivalents. Everything else (no route, full buffers, firewall drops, a refusal reported for an earlier datagram, an interrupted call) is a property of the path or the moment and may pass, so it is a lost datagram, not a reason to end a session.""" - return error.errno in _PERMANENT_SEND_ERRNOS + return send_error_code(error) != _UNKNOWN_SEND_ERROR class CultNetRudpSession: @@ -872,9 +882,10 @@ class CultNetRudpSession: """Ends a session that owes its peer a packet that can never be sent as built (see `is_permanent_send_error`). Resending it would fail forever, and dropping it would leave a reliable sequence the peer waits on for good, so the session cannot - be kept. Returns the goodbye for the peer; its reason names the error.""" + be kept. Returns the goodbye for the peer; its reason names the failure by its fixed + name (`send_error_code`), never the error's text.""" self.reset_peer_state() - return self.create_disconnect(f"{UNSENDABLE_PACKET_REASON}: {error}".encode("utf-8")) + return self.create_disconnect(f"{UNSENDABLE_PACKET_REASON}: {send_error_code(error)}".encode("utf-8")) def create_disconnect(self, reason: bytes = b"") -> CultNetRudpPacket: self._end_session() diff --git a/packages/cultnet-py/tests/test_cultnet.py b/packages/cultnet-py/tests/test_cultnet.py index 765f5c37..3c5793c1 100644 --- a/packages/cultnet-py/tests/test_cultnet.py +++ b/packages/cultnet-py/tests/test_cultnet.py @@ -901,6 +901,18 @@ class CultNetTests(unittest.TestCase): self.assertFalse(is_permanent_send_error(OSError(code, "transient")), errno.errorcode[code]) self.assertFalse(is_permanent_send_error(OSError("no errno"))) + def test_cultnet_rudp_an_unsendable_goodbye_names_the_failure_by_a_fixed_code(self) -> None: + import errno + + from cultnet_py import send_error_code + + for code, name in ((errno.EMSGSIZE, "EMSGSIZE"), (errno.EINVAL, "EINVAL"), (errno.EAFNOSUPPORT, "EAFNOSUPPORT")): + self.assertEqual(send_error_code(OSError(code, "CANARY-7f3a")), name) + self.assertEqual(send_error_code(OSError(errno.ECONNREFUSED, "CANARY-7f3a")), "UNKNOWN") + session = CultNetRudpSession(CultNetRudpSessionOptions(connection_id=1)) + goodbye = session.end_unsendable_session(OSError(errno.EMSGSIZE, "Message too long CANARY-7f3a")) + self.assertEqual(bytes(goodbye.payload), b"packet could not be sent: EMSGSIZE") + # The sender's flow window: a reliable packet goes on the wire only while its sequence is at most 1,023 above # the lowest unacked one and the payload above that sequence stays within 4 MiB. FLOW_CONNECTION_ID = 0x464C4F57 From d541e9eb35733eb6cd121ff25aa853f097ce82b5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 23:04:07 +0200 Subject: [PATCH 42/44] cultmesh-py: a refusal acknowledges nothing and names its own send failure; TCP handling refuses instead of dying; the daemon checks its port Queue-full refusal (findings 2 and 6). The refusal was built in _send_rudp_schema_frame before _end_refused_peer reset the session, so its ack fields covered the refused request (ack=102 mask=0x3). A reply the queue cannot take now raises _ReplyUnqueueable; the loop ends the peer through _end_refused_peer, which builds the refusal before the reset, gives it ack fields built after it (acknowledging nothing, like the goodbye and like Rust's refusal), sends it unreliable and unordered, then the goodbye. A refusal fragment that can never be sent is not dropped: the goodbye names its failure ("packet could not be sent: EMSGSIZE"), where it used to say the session refused a packet. Queue full to the brim (item 1). The tests fill a queue of 8 exactly with a reply the peer never acknowledges, then show the next reply is answered with response_unqueueable, acknowledging nothing, followed by the goodbye; and that a refusal whose fragment cannot be sent ends the session with a goodbye naming EMSGSIZE. TCP (finding 8). A message whose handling raised (snapshot recordKeys as an int, a shard-log afterSequence that is not a number, subscribe, schema-catalog and verse requests with int fields) killed the connection's thread with a traceback that could quote the peer. The TCP handler now refuses such a message with fixed text (message_unhandled), logs the error type only, and serves the connection's next message. Daemon (finding 10). --port 99999 is an argparse error (exit 2), not a traceback. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-py/src/cultmesh_py/daemon.py | 10 +- .../cultmesh-py/src/cultmesh_py/server.py | 87 ++++++-- packages/cultmesh-py/tests/test_cultmesh.py | 198 ++++++++++++++++++ 3 files changed, 272 insertions(+), 23 deletions(-) diff --git a/packages/cultmesh-py/src/cultmesh_py/daemon.py b/packages/cultmesh-py/src/cultmesh_py/daemon.py index c98063f7..5b127008 100644 --- a/packages/cultmesh-py/src/cultmesh_py/daemon.py +++ b/packages/cultmesh-py/src/cultmesh_py/daemon.py @@ -24,10 +24,18 @@ from cultnet_py.cultmesh_contracts import ( READY_SCHEMA_VERSION = "cultmesh.daemon_ready.v0" +def _port(value: str) -> int: + """A TCP/UDP port: 0 (any free port) through 65535.""" + port = int(value) + if not 0 <= port <= 65535: + raise argparse.ArgumentTypeError("port must be between 0 and 65535") + return port + + def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="cultmesh-py-daemon") parser.add_argument("--host", default="127.0.0.1") - parser.add_argument("--port", type=int, default=3075) + parser.add_argument("--port", type=_port, default=3075) parser.add_argument("--runtime-id", default="python-runtime") parser.add_argument("--display-name") parser.add_argument("--cache-file") diff --git a/packages/cultmesh-py/src/cultmesh_py/server.py b/packages/cultmesh-py/src/cultmesh_py/server.py index d9f4c349..e50def4d 100644 --- a/packages/cultmesh-py/src/cultmesh_py/server.py +++ b/packages/cultmesh-py/src/cultmesh_py/server.py @@ -4,7 +4,7 @@ import logging import socket import threading import time -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from typing import Any import msgpack @@ -39,6 +39,8 @@ CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES = 1200 # The answer to a request whose reply the peer's reliable queue cannot take. Fixed text: it # never quotes the reply or the queue's error. _REPLY_UNQUEUEABLE = "The reply could not be queued for this peer." +# The answer to a message the server could not handle. Fixed text: it never quotes the message. +_MESSAGE_UNHANDLED = "The message could not be handled." from cultnet_py.cultmesh_contracts import ( PEER_EXCHANGE_REQUEST, VERSE_CATALOG_REQUEST, @@ -49,6 +51,15 @@ from cultnet_py.cultmesh_contracts import ( _LOGGER = logging.getLogger(__name__) +class _ReplyUnqueueable(Exception): + """A reply the peer's reliable queue cannot take. The peer's session ends, and the peer is + answered first with a small cultnet.error.v0 under the request's message id.""" + + def __init__(self, message_id: str) -> None: + super().__init__("reply could not be queued") + self.message_id = message_id + + @dataclass(frozen=True) class _DatabaseSubscription: subscription_id: str @@ -259,7 +270,22 @@ class CultMeshLocalServer: return if not isinstance(message, dict): continue - responses = self._handle_connection_message(message, subscriptions) + try: + responses = self._handle_connection_message(message, subscriptions) + except Exception as error: # noqa: BLE001 - one message never ends the connection + # Whatever a peer's message makes the handling raise is that peer's failure: + # it is refused with fixed text and the connection serves on. The log names + # the error type only, because the error's own message can quote the peer. + _LOGGER.warning( + "CultMesh server could not handle a peer's message (%s); it was refused.", + type(error).__name__, + ) + message_id = message.get("messageId") + responses = [self._error_response( + _MESSAGE_UNHANDLED, + message_id=message_id if isinstance(message_id, str) else "", + code="message_unhandled", + )] for response in responses: transport.send("schema", msgpack.packb(response, use_bin_type=True)) @@ -361,7 +387,14 @@ class CultMeshLocalServer: "CultMesh RUDP server could not handle a peer's message (%s); that peer's session ended.", type(error).__name__, ) - self._end_refused_peer(rudp_socket, peers, remote_addr) + refusal = None + if isinstance(error, _ReplyUnqueueable): + refusal = self._error_response( + _REPLY_UNQUEUEABLE, + message_id=error.message_id, + code="response_unqueueable", + ) + self._end_refused_peer(rudp_socket, peers, remote_addr, refusal=refusal) continue if unsendable is None and ( packet.reliable or packet.packet_type == CultNetRudpPacketType.DATA or result.delivered @@ -405,23 +438,8 @@ class CultMeshLocalServer: ) except ValueError: # The peer's reliable queue cannot take this reply. The peer is answered, not left - # to time out: a small cultnet.error.v0 goes unreliable and unordered, so it needs - # no room in the queue that just refused. Then the error ends the session, as any - # message the handling cannot serve does. - refusal = self._error_response( - _REPLY_UNQUEUEABLE, - message_id=message_id, - code="response_unqueueable", - ) - for packet in session.send_many( - "schema", - msgpack.packb(refusal, use_bin_type=True), - CultNetRudpSendOptions(reliable=False, ordered=False, now_ms=_now_ms()), - max_fragment_bytes=self.rudp_max_fragment_bytes, - ): - if self._send_rudp_packet(rudp_socket, remote_addr, packet) is not None: - break - raise + # to time out, and its session ends: see _end_refused_peer. + raise _ReplyUnqueueable(message_id) from None for packet in packets: unsendable = self._send_rudp_packet(rudp_socket, remote_addr, packet) if unsendable is not None: @@ -452,11 +470,36 @@ class CultMeshLocalServer: rudp_socket: socket.socket, peers: dict[tuple[str, int], _RudpPeerConnection], remote_addr: tuple[str, int], + *, + refusal: dict[str, Any] | None = None, ) -> None: + """Ends a peer's session that refused one of its messages, and says goodbye. A + refusal, when there is one, goes first, unreliable and unordered: the session ends + with it, so it is never resent and needs no room in the reliable queue. It is built + before the reset and carries acknowledgement fields built after it, which acknowledge + nothing, like the goodbye: the ack would otherwise cover the very frame refused. A + refusal fragment that can never be sent is not dropped: the goodbye names its failure.""" peer = peers.pop(remote_addr) - # The goodbye is built after the reset, or its ack field would acknowledge the - # very frame the session refused. + packets: list[CultNetRudpPacket] = [] + if refusal is not None: + try: + packets = peer.session.send_many( + "schema", + msgpack.packb(refusal, use_bin_type=True), + CultNetRudpSendOptions(reliable=False, ordered=False, now_ms=_now_ms()), + max_fragment_bytes=self.rudp_max_fragment_bytes, + ) + except ValueError: + packets = [] peer.session.reset_peer_state() + nothing = peer.session.create_ack() + for packet in packets: + unsendable = self._send_rudp_packet( + rudp_socket, remote_addr, replace(packet, ack=nothing.ack, ack_mask=nothing.ack_mask) + ) + if unsendable is not None: + self._send_rudp_packet(rudp_socket, remote_addr, peer.session.end_unsendable_session(unsendable)) + return goodbye = peer.session.create_disconnect(b"session refused a packet") self._send_rudp_packet(rudp_socket, remote_addr, goodbye) diff --git a/packages/cultmesh-py/tests/test_cultmesh.py b/packages/cultmesh-py/tests/test_cultmesh.py index 18e13b0b..cdf2c965 100644 --- a/packages/cultmesh-py/tests/test_cultmesh.py +++ b/packages/cultmesh-py/tests/test_cultmesh.py @@ -51,6 +51,9 @@ from cultnet_py import ( CultNetSimulationObservation, CultNetSimulationObservationHub, CultNetRudpPacketType, + CultNetRudpSendOptions, + CultNetRudpSession, + CultNetRudpSessionOptions, CultNetRudpSocketMode, CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, @@ -59,10 +62,12 @@ from cultnet_py import ( decode_rudp_packet, document_delete, document_put_raw, + encode_rudp_packet, hello, simulation_observation, snapshot_request, ) +from cultnet_py.cultmesh_contracts import VERSE_CATALOG_REQUEST from cultmesh_py import create_node from cultmesh_py import ( CultMesh, @@ -3794,6 +3799,17 @@ class CultMeshTests(unittest.TestCase): self.assertIn("error: max_snapshot_documents must be greater than zero", completed.stderr) self.assertNotIn("Traceback", completed.stderr) self.assertFalse(ready_path.exists()) + # A port no socket can bind is a usage error too. + completed = subprocess.run( + [sys.executable, "-m", "cultmesh_py.daemon", "--port", "99999"], + capture_output=True, + text=True, + env=env, + timeout=30, + ) + self.assertEqual(completed.returncode, 2, completed.stderr) + self.assertIn("port must be between 0 and 65535", completed.stderr) + self.assertNotIn("Traceback", completed.stderr) def test_cultmesh_daemon_serves_opt_in_simulation_observations(self) -> None: with tempfile.TemporaryDirectory() as temp: @@ -4547,6 +4563,188 @@ class CultMeshTests(unittest.TestCase): self.assertEqual(after_reply["messageId"], "after-queue") self.assertTrue(alive) + class _RawPeer: + """A peer driven packet by packet, so a test decides what it acknowledges: nothing.""" + + def __init__(self, server: Any) -> None: + self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self.sock.bind(("127.0.0.1", 0)) + self.sock.settimeout(0.05) + self.address = self.sock.getsockname()[:2] + self.target = ("127.0.0.1", server.port) + self.session = CultNetRudpSession( + CultNetRudpSessionOptions( + connection_id=server.rudp_connection_id, initial_sequence=100, resend_delay_ms=100_000 + ) + ) + self.sock.sendto(encode_rudp_packet(self.session.create_connect(0)), self.target) + accept = self.receive(1.0) + assert accept is not None and accept.packet_type == CultNetRudpPacketType.ACCEPT, accept + self.session.receive(accept, 1) + + def receive(self, timeout: float = 0.3) -> Any: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + wire, _ = self.sock.recvfrom(65535) + except (TimeoutError, socket.timeout): + continue + return decode_rudp_packet(wire) + return None + + def drain(self, timeout: float = 0.5) -> list[Any]: + # Bounded overall: the server resends what the peer never acknowledges. + packets = [] + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + packet = self.receive(0.05) + if packet is not None: + packets.append(packet) + return packets + + def send(self, message: dict[str, Any]) -> list[int]: + packets = self.session.send_many( + "schema", + msgpack.packb(message, use_bin_type=True), + CultNetRudpSendOptions(reliable=True, ordered=True, now_ms=2), + max_fragment_bytes=1200, + ) + for packet in packets: + self.sock.sendto(encode_rudp_packet(packet), self.target) + return [packet.sequence for packet in packets] + + def close(self) -> None: + self.sock.close() + + @staticmethod + def _acknowledges(packet: Any, sequence: int) -> bool: + return packet.ack == sequence or any( + packet.ack_mask & (1 << bit) and packet.ack > bit and packet.ack - bit - 1 == sequence + for bit in range(32) + ) + + def _brim_server(self) -> tuple[Any, Any]: + """A server whose peer's reliable queue (8) is filled exactly by an 8-fragment reply the + peer never acknowledges, and the peer.""" + document = self._rudp_bound_note() + node = CultMesh.create_node(runtime_id="mesh-rudp-brim") + node.database.register_document(document) + server = CultMesh.serve_node(node, rudp_max_fragment_bytes=100, rudp_max_pending_reliable_packets=8) + + def served(body: int) -> int: + put = self._rudp_note_put(document, "p", "note:q", body) + return len(msgpack.packb(node.database.raw_put_served_alone(put, message_id=""), use_bin_type=True)) + + body = 400 + 800 - served(400) + self.assertEqual(served(body), 800, "fixture: served size is linear in the body") + node.database.apply_raw_put_message(self._rudp_note_put(document, "p", "note:q", body)) + peer = self._RawPeer(server) + peer.send(snapshot_request(message_id="", record_keys=["note:q"]).to_wire()) + first = {p.sequence for p in peer.drain(0.3) if p.packet_type == CultNetRudpPacketType.DATA} + self.assertEqual(len(first), 8, "fixture: the first reply fills the queue exactly") + return server, peer + + def test_cultmesh_local_server_answers_a_peer_whose_queue_is_full_to_the_brim(self) -> None: + # The next reply cannot be queued. The peer is answered with a cultnet.error.v0 that takes + # no room in the full queue and acknowledges nothing the peer sent, then its session ends. + server, peer = self._brim_server() + try: + refused = peer.send(snapshot_request(message_id="b", record_keys=["note:none"]).to_wire()) + packets = peer.drain(0.5) + alive = server._rudp_thread is not None and server._rudp_thread.is_alive() + finally: + peer.close() + server.stop() + parts = sorted( + ( + p for p in packets + if p.packet_type == CultNetRudpPacketType.DATA and p.channel_id == "schema" and not p.reliable + ), + key=lambda p: p.fragment_index, + ) + self.assertTrue(parts, "the refusal reaches the peer") + for part in parts: + self.assertFalse( + any(self._acknowledges(part, sequence) for sequence in refused), + f"the refusal acknowledges the refused request: ack={part.ack} mask={part.ack_mask:#x}", + ) + refusal = msgpack.unpackb(b"".join(bytes(p.payload) for p in parts), raw=False) + self.assertEqual(refusal["schemaVersion"], "cultnet.error.v0") + self.assertEqual(refusal["messageId"], "b") + self.assertEqual(refusal["code"], "response_unqueueable") + goodbyes = [bytes(p.payload) for p in packets if p.packet_type == CultNetRudpPacketType.DISCONNECT] + self.assertEqual(goodbyes, [b"session refused a packet"], "then the session ends") + self.assertTrue(alive) + + def test_cultmesh_local_server_names_a_refusal_that_can_never_be_sent_in_the_goodbye(self) -> None: + # The refusal's own fragment fails permanently: the failure is not dropped, the goodbye + # names it by its fixed code, never the error's text. + import errno + + server, peer = self._brim_server() + original_sendto = socket.socket.sendto + + def sendto(sock: socket.socket, data: bytes, *args: Any) -> int: + packet = decode_rudp_packet(data) + if ( + args and tuple(args[-1]) == tuple(peer.address) + and packet.packet_type == CultNetRudpPacketType.DATA and not packet.reliable + ): + raise OSError(errno.EMSGSIZE, "Message too long CANARY-7f3a") + return original_sendto(sock, data, *args) + + try: + with patch.object(socket.socket, "sendto", sendto): + peer.send(snapshot_request(message_id="b", record_keys=["note:none"]).to_wire()) + packets = peer.drain(0.5) + alive = server._rudp_thread is not None and server._rudp_thread.is_alive() + finally: + peer.close() + server.stop() + self.assertFalse( + [p for p in packets if p.packet_type == CultNetRudpPacketType.DATA and not p.reliable], + "the refusal could not be sent", + ) + goodbyes = [bytes(p.payload) for p in packets if p.packet_type == CultNetRudpPacketType.DISCONNECT] + self.assertEqual(goodbyes, [b"packet could not be sent: EMSGSIZE"]) + self.assertTrue(alive) + + def test_cultmesh_local_server_refuses_a_tcp_message_it_cannot_handle_and_serves_on(self) -> None: + # Messages whose handling raises: the TCP peer is refused with fixed text, the log names + # the error type only, and the connection's thread serves its next message. + shapes = [ + {"schemaVersion": "cultnet.snapshot_request.v0", "messageId": "snapshot", "recordKeys": 5}, + {"schemaVersion": "cultnet.shard_log_request.v0", "messageId": "shard-log", "shardId": "a", "afterSequence": "CANARY-7f3a"}, + {"schemaVersion": "cultnet.database_subscribe.v0", "messageId": "subscribe", "subscriptionId": "s", "schemaIds": 5}, + {"schemaVersion": "cultnet.schema_catalog_request.v0", "messageId": "catalog", "schemaIds": 5}, + {"schemaVersion": VERSE_CATALOG_REQUEST, "messageId": "verse", "verseIds": 5}, + ] + deaths: list[str] = [] + original_hook = threading.excepthook + threading.excepthook = lambda args: deaths.append(f"{args.exc_type.__name__}") + server = CultMesh.serve_node(CultMesh.create_node(runtime_id="mesh-tcp-shapes")) + try: + with self.assertLogs("cultmesh_py.server", level="WARNING") as logs: + with CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=4.0).open_transport() as transport: + refusals = [] + for shape in shapes: + transport.send("schema", msgpack.packb(shape, use_bin_type=True)) + refusals.append((shape["messageId"], msgpack.unpackb(transport.receive().payload, raw=False))) + transport.send("schema", msgpack.packb(hello(runtime_id="same-connection").to_wire(), use_bin_type=True)) + after = msgpack.unpackb(transport.receive().payload, raw=False) + finally: + server.stop() + threading.excepthook = original_hook + for message_id, refusal in refusals: + self.assertEqual(refusal["schemaVersion"], "cultnet.error.v0", message_id) + self.assertEqual(refusal["messageId"], message_id) + self.assertEqual(refusal["code"], "message_unhandled", message_id) + self.assertEqual(refusal["error"], "The message could not be handled.", message_id) + self.assertEqual(after["schemaVersion"], "cultnet.hello.v0") + self.assertEqual(deaths, []) + self.assertEqual(len(logs.output), len(shapes)) + self.assertFalse([line for line in logs.output if "CANARY" in line]) + def test_cultmesh_local_server_refuses_a_rudp_put_whose_reply_needs_more_than_65535_fragments(self) -> None: # One message carries at most 65535 fragments, however deep the queue: with one-byte # fragments a put served in 65536 bytes is refused, one served in 65535 is stored. From e1bdf92321f044d7b37193a7abd219c4129a02b9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 23:04:40 +0200 Subject: [PATCH 43/44] C#: an unsendable goodbye names the failure by a fixed code EndUnsendable put the SocketException's message on the wire, the platform's wording. SendErrorCode names a permanent failure EMSGSIZE, EINVAL or EAFNOSUPPORT, anything else UNKNOWN, so every runtime's unsendable goodbye reads "packet could not be sent: CODE" with the same codes. Co-Authored-By: Claude Opus 5.5 --- src/GameCult.Networking/CultNetTransport.cs | 19 +++++++++++++++++-- .../CultNetRudpSendFailureTests.cs | 12 ++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/GameCult.Networking/CultNetTransport.cs b/src/GameCult.Networking/CultNetTransport.cs index a6102de3..ac2c2952 100644 --- a/src/GameCult.Networking/CultNetTransport.cs +++ b/src/GameCult.Networking/CultNetTransport.cs @@ -1490,15 +1490,30 @@ namespace GameCult.Networking internal const string UnsendablePacketReason = "packet could not be sent"; + /// + /// The fixed name of a failed send's cause: EMSGSIZE, EINVAL or EAFNOSUPPORT for a failure + /// that can never pass (), UNKNOWN for anything else, as + /// every runtime's goodbye names it. Never the error's own message, which is the platform's + /// wording. + /// + internal static string SendErrorCode(SocketException error) => error.SocketErrorCode switch + { + SocketError.MessageSize => "EMSGSIZE", + SocketError.InvalidArgument => "EINVAL", + SocketError.AddressFamilyNotSupported => "EAFNOSUPPORT", + _ => "UNKNOWN", + }; + /// /// Ends a session that owes its peer a packet that can never be sent as built. Resending it /// would fail forever, and dropping it would leave a reliable sequence the peer waits on for - /// good, so the session cannot be kept. The goodbye's reason names the error. + /// good, so the session cannot be kept. The goodbye's reason names the failure by its fixed + /// name (). /// internal CultNetRudpPacket EndUnsendable(SocketException error) { ResetPeerState(); - return CreateDisconnect(Encoding.UTF8.GetBytes(UnsendablePacketReason + ": " + error.Message)); + return CreateDisconnect(Encoding.UTF8.GetBytes(UnsendablePacketReason + ": " + SendErrorCode(error))); } internal uint NextSequence => _nextSequence; diff --git a/tests/GameCult.Networking.Tests/CultNetRudpSendFailureTests.cs b/tests/GameCult.Networking.Tests/CultNetRudpSendFailureTests.cs index 81d255f7..3decfa46 100644 --- a/tests/GameCult.Networking.Tests/CultNetRudpSendFailureTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetRudpSendFailureTests.cs @@ -137,6 +137,18 @@ namespace GameCult.Networking.Tests // caller-directed send throws it and queues nothing; inside a poll it ends that peer's // session and never the poll. + [Test] + public void An_unsendable_goodbye_names_the_failure_by_a_fixed_code_never_its_message() + { + var session = new CultNetRudpSession(new CultNetRudpSessionOptions { ConnectionId = 1 }); + Assert.That( + Encoding.UTF8.GetString(session.EndUnsendable(new SocketException((int)SocketError.MessageSize)).Payload!), + Is.EqualTo("packet could not be sent: EMSGSIZE")); + Assert.That(CultNetRudpSession.SendErrorCode(new SocketException((int)SocketError.InvalidArgument)), Is.EqualTo("EINVAL")); + Assert.That(CultNetRudpSession.SendErrorCode(new SocketException((int)SocketError.AddressFamilyNotSupported)), Is.EqualTo("EAFNOSUPPORT")); + Assert.That(CultNetRudpSession.SendErrorCode(new SocketException((int)SocketError.ConnectionRefused)), Is.EqualTo("UNKNOWN")); + } + private static bool IsUnsendableReason(byte[]? reason) { var text = Encoding.UTF8.GetString(reason ?? Array.Empty()); From 8b8f8436cc029db1602abebda71a63bbd1d37f0d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 30 Sep 2026 23:06:03 +0200 Subject: [PATCH 44/44] cultmesh-ts: a snapshot refusal carries fixed text and acknowledges nothing The snapshot fallback sent the caught error's message to the peer, and errors from getCache or the registry went the same way, so a message the application or a peer supplied could reach the wire. Its ack fields also covered the refused request. The snapshot path now refuses per case with fixed text (the snapshot source failed / the snapshot response is too large / the snapshot response could not be queued) through refuse(), which sends unreliable and unordered, so it needs no room in a full queue, with ack fields that acknowledge nothing, as every runtime's refusal does. onError keeps the detail. Tests, with a raw peer that acknowledges nothing: a queue of 8 filled exactly by an unacknowledged 8-fragment reply, then a refusal that still arrives and acknowledges nothing; and a getCache failure carrying a canary, refused with "the snapshot source failed". Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-ts/src/index.ts | 46 ++++++-- packages/cultmesh-ts/test/cultmesh.test.ts | 124 +++++++++++++++++++++ 2 files changed, 160 insertions(+), 10 deletions(-) diff --git a/packages/cultmesh-ts/src/index.ts b/packages/cultmesh-ts/src/index.ts index 245e8aa6..36a5ae88 100644 --- a/packages/cultmesh-ts/src/index.ts +++ b/packages/cultmesh-ts/src/index.ts @@ -5965,17 +5965,25 @@ export class CultMesh { }); return; } + let reply: CultNetMessage; try { const cache = await options.getCache(); - sendSchemaMessage(record, options.documents.createRawSnapshotResponse(cache, message.messageId, message)); + reply = options.documents.createRawSnapshotResponse(cache, message.messageId, message); } catch (error) { reportError(error); - // Unreliable and unordered: when the reply could not be queued, the answer must not - // need room in the queue that just refused it. - sendSchemaMessage(record, { - schemaVersion: "cultnet.error.v0", - error: error instanceof Error ? error.message : String(error), - }, { reliable: false }); + refuse(record, "the snapshot source failed"); + return; + } + try { + sendSchemaMessage(record, reply); + } catch (error) { + reportError(error); + refuse( + record, + maxPayloadBytes !== undefined && encodeSchemaMessage(reply).byteLength > maxPayloadBytes + ? "the snapshot response is too large" + : "the snapshot response could not be queued", + ); } return; } @@ -6088,7 +6096,6 @@ export class CultMesh { function sendSchemaMessage( record: SessionRecord, message: CultNetMessage, - { reliable = true }: { reliable?: boolean } = {}, ): void { if (record.closed) throw new Error(`CultMesh RUDP session ${record.sessionId} is closed.`); const payload = encodeSchemaMessage(message); @@ -6099,8 +6106,8 @@ export class CultMesh { ); } for (const packet of record.session.sendMany("schema", payload, { - reliable, - ordered: reliable, + reliable: true, + ordered: true, nowMs: Date.now(), maxFragmentBytes, })) { @@ -6108,6 +6115,25 @@ export class CultMesh { } } + /** + * Answers a request the server cannot serve with fixed text, never an error's message, + * which can quote what a peer or the application supplied. The answer is unreliable and + * unordered, so it needs no room in a reliable queue that may just have refused the reply, + * and its acknowledgement fields acknowledge nothing, as every runtime's refusal does. + */ + function refuse(record: SessionRecord, text: string): void { + if (record.closed) return; + const payload = encodeSchemaMessage({ schemaVersion: "cultnet.error.v0", error: text }); + for (const packet of record.session.sendMany("schema", payload, { + reliable: false, + ordered: false, + nowMs: Date.now(), + maxFragmentBytes, + })) { + sendPacket(record, { ...packet, ack: 0, ackMask: 0 }); + } + } + /** The one reply encoder, shared by sends and by put admission. */ function encodeSchemaMessage(message: CultNetMessage): Uint8Array { return encode(encodeCultNetMessageForWire(message, wireContract)); diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index 7f4ee959..5ec961a5 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -1,3 +1,4 @@ +import { createSocket } from "node:dgram"; import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -9,9 +10,13 @@ import { defineDocumentType } from "@gamecult/cultcache-ts"; import { CultNetDocumentRegistry, CultNetPeer, + CultNetRudpSession, cultNetBuiltinSchemaRegistry, + decodeRudpPacket, defineCultNetDocumentBinding, + encodeRudpPacket, type CultNetDocumentPutRawMessage, + type CultNetRudpPacket, type CultNetMessage, type CultNetSnapshotResponseRawMessage, } from "cultnet-ts"; @@ -3512,6 +3517,125 @@ test("CultMesh TS RUDP document server answers a snapshot its reliable queue can }); }); +/** + * A document server over a node that already holds `stored`, and a peer driven packet by packet + * that acknowledges nothing, so a test fills the server's reliable queue at will. + */ +async function withRawPeerRig( + connectionId: number, + serverLimits: { maxFragmentBytes?: number; maxPendingReliablePackets?: number }, + stored: CultNetDocumentPutRawMessage[], + getCache: ((cache: unknown) => unknown) | undefined, + body: (rig: { + errors: Error[]; + inbox: CultNetRudpPacket[]; + request: (messageId: string, recordKeys: string[]) => number[]; + }) => Promise, +): Promise { + const node = await CultMesh.startNode( + join(await mkdtemp(join(tmpdir(), "cultmesh-ts-raw-peer-")), "node.ccmp"), + { documents: [noteDocument] }, + ); + const registry = servedBoundRegistry(); + for (const put of stored) await registry.applyRawDocumentPutMessage(node.cache, put); + const errors: Error[] = []; + const server = CultMesh.createRudpDocumentServer(SERVED_BOUND_SERVER, connectionId, { + documents: registry, + getCache: () => (getCache ? getCache(node.cache) : node.cache) as typeof node.cache, + bindHost: "127.0.0.1", + bindPort: 0, + resendDelayMs: 100_000, + resendPollMs: 5, + ...serverLimits, + onError: (error) => errors.push(error), + }); + await server.start(); + const socket = createSocket("udp4"); + try { + await new Promise((resolve) => socket.bind(0, "127.0.0.1", () => resolve())); + const inbox: CultNetRudpPacket[] = []; + socket.on("message", (wire) => inbox.push(decodeRudpPacket(wire))); + const session = new CultNetRudpSession({ connectionId, initialSequence: 100, resendDelayMs: 100_000, maxPendingReliablePackets: 64 }); + const send = (packet: CultNetRudpPacket) => socket.send(encodeRudpPacket(packet), server.bind.port, "127.0.0.1"); + send(session.createConnect(0)); + const startedAt = Date.now(); + while (!inbox.some((packet) => packet.packetType === "accept") && Date.now() - startedAt < 2_000) await delay(5); + const accept = inbox.find((packet) => packet.packetType === "accept"); + assert.ok(accept, "the server accepts the connect"); + session.receive(accept, 1); + inbox.length = 0; + const request = (messageId: string, recordKeys: string[]): number[] => { + const packets = session.sendMany( + "schema", + encode({ schemaVersion: "cultnet.snapshot_request.v0", messageId, recordKeys }), + { reliable: true, ordered: true, nowMs: 2, maxFragmentBytes: 1200 }, + ); + packets.forEach(send); + return packets.map((packet) => packet.sequence); + }; + await body({ errors, inbox, request }); + } finally { + socket.close(); + server.close(); + } +} + +/** The refusal among `packets`: its unreliable fragments, reassembled, and the fragments. */ +function refusalIn(packets: CultNetRudpPacket[]): { message: Record; parts: CultNetRudpPacket[] } | undefined { + const parts = packets + .filter((packet) => packet.packetType === "data" && packet.channelId === "schema" && !packet.reliable) + .sort((a, b) => (a.fragmentIndex ?? 0) - (b.fragmentIndex ?? 0)); + if (parts.length === 0) return undefined; + const message = decode(Buffer.concat(parts.map((part) => Buffer.from(part.payload ?? new Uint8Array())))) as Record; + return { message, parts }; +} + +function acknowledges(packet: CultNetRudpPacket, sequence: number): boolean { + if (packet.ack === sequence) return true; + for (let bit = 0; bit < 32; bit += 1) { + if ((packet.ackMask & (1 << bit)) !== 0 && packet.ack - bit - 1 === sequence) return true; + } + return false; +} + +test("CultMesh TS RUDP document server answers a peer whose reliable queue is full to the brim", async () => { + // An 8-fragment reply the peer never acknowledges fills a queue of 8 exactly. The next reply + // cannot be queued; the peer is still answered, with fixed text that takes no room in that + // queue and acknowledges nothing the peer sent. + const body = bodyLengthForReplyBytes("q1", 800); + await withRawPeerRig(0x10203069, { maxFragmentBytes: 100, maxPendingReliablePackets: 8 }, [notePut("s", "q1", body)], undefined, async (rig) => { + rig.request("0", ["q1"]); + await delay(300); + const first = new Set(rig.inbox.filter((packet) => packet.packetType === "data" && packet.reliable).map((packet) => packet.sequence)); + assert.equal(first.size, 8, "fixture: the first reply fills the queue exactly"); + rig.inbox.length = 0; + const refused = rig.request("b", ["none"]); + const startedAt = Date.now(); + while (!refusalIn(rig.inbox) && Date.now() - startedAt < 3_000) await delay(5); + const refusal = refusalIn(rig.inbox); + assert.ok(refusal, "the refusal reaches the peer"); + assert.deepEqual(refusal.message, { schemaVersion: "cultnet.error.v0", error: "the snapshot response could not be queued" }); + for (const part of refusal.parts) { + assert.ok(refused.every((sequence) => !acknowledges(part, sequence)), `ack ${part.ack} mask ${part.ackMask}`); + } + assert.equal(rig.errors.length, 1); + }); +}); + +test("CultMesh TS RUDP document server refuses a snapshot with fixed text, never an error's message", async () => { + // The cache the snapshot needs fails with a message a peer must not see: the peer is told + // only that the snapshot source failed; onError keeps the detail. + await withRawPeerRig(0x1020306a, {}, [], () => { throw new Error("no such tenant CANARY-7f3a"); }, async (rig) => { + rig.request("0", ["q1"]); + const startedAt = Date.now(); + while (!refusalIn(rig.inbox) && Date.now() - startedAt < 3_000) await delay(5); + const refusal = refusalIn(rig.inbox); + assert.ok(refusal, "the refusal reaches the peer"); + assert.deepEqual(refusal.message, { schemaVersion: "cultnet.error.v0", error: "the snapshot source failed" }); + assert.match(rig.errors[0]?.message ?? "", /CANARY-7f3a/); + }); +}); + test("CultMesh TS RUDP document server honours maxPayloadBytes for replies and judges puts by what it would serve", async () => { const limit = 4_000; const atBound = bodyLengthForReplyBytes("note:at", limit);