From a6f574a159cf1690c8659bc11084b78423ff12da Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 08:44:26 +0100 Subject: [PATCH] cultmesh-rs: subscription tests no longer depend on one goodbye datagram or the process thread count; catalog requests are concurrent and a timeout is not latched Co-Authored-By: Claude Sonnet 5.5 --- packages/cultmesh-rs/src/rudp_subscription.rs | 119 ++++++++---- .../cultmesh-rs/tests/rudp_subscription.rs | 183 ++++++++++++++++-- 2 files changed, 248 insertions(+), 54 deletions(-) diff --git a/packages/cultmesh-rs/src/rudp_subscription.rs b/packages/cultmesh-rs/src/rudp_subscription.rs index 4ff7c7f5..aca2f9d4 100644 --- a/packages/cultmesh-rs/src/rudp_subscription.rs +++ b/packages/cultmesh-rs/src/rudp_subscription.rs @@ -10,7 +10,8 @@ //! //! Bounds: the assembler bounds what it holds of incomplete commits and faults the connection past that. What the //! caller has not drained is bounded too, by [`CultMeshRudpSubscriptionOptions::max_undrained`], counted in -//! documents and changes: a caller that stops draining past it gets a [`SubscriptionEvent::Faulted`], delivery +//! documents and changes, those still waiting in the pump for their rows included: a caller that stops draining +//! past it gets a [`SubscriptionEvent::Faulted`], delivery //! stops, and [`resubscribe_all`](CultMeshRudpSubscriptionClient::resubscribe_all) starts over from fresh //! snapshots. Memory never grows without bound. //! @@ -37,7 +38,7 @@ use std::fmt; use std::net::SocketAddr; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, Weak}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; @@ -62,11 +63,12 @@ pub struct CultMeshRudpSubscriptionOptions { /// fresh one. The C# transport's `CheckTimeout(timeoutMs)` is the same rule, but its caller must drive it and /// no default exists there; this one is stated here. pub idle_timeout: Duration, - /// The most documents and changes that may sit undrained before the subscription faults. A single snapshot - /// larger than this always faults, however promptly it is drained. + /// The most documents and changes that may sit undrained, or wait in the pump for their member rows, before the + /// subscription faults. A single snapshot larger than this always faults, however promptly it is drained. pub max_undrained: usize, /// How long events wait for a catalog answer. Past it the records waiting on it are delivered with - /// [`NoMembersReason::CatalogTimedOut`]. + /// [`NoMembersReason::CatalogTimedOut`], and a later record of the same schema asks again once this long has + /// passed since (a timeout never latches for the session). pub catalog_timeout: Duration, } @@ -225,6 +227,7 @@ pub struct CultMeshRudpSubscriptionClient { commands: Sender, events: Mutex>, undrained: Arc, + pump_alive: Weak<()>, pump: Option>, } @@ -238,6 +241,8 @@ impl CultMeshRudpSubscriptionClient { let (commands, command_rx) = mpsc::channel(); let (event_tx, events) = mpsc::channel(); let undrained = Arc::new(AtomicUsize::new(0)); + let alive = Arc::new(()); + let pump_alive = Arc::downgrade(&alive); let pump = Pump { options, session: Some(session), @@ -245,7 +250,9 @@ impl CultMeshRudpSubscriptionClient { rows: BTreeMap::new(), pending: VecDeque::new(), pending_weight: 0, - awaiting: None, + awaiting: Vec::new(), + backoff: BTreeMap::new(), + alive, subscriptions: BTreeMap::new(), receipts: Vec::new(), epoch: super::fresh_rudp_connection_epoch(), @@ -258,7 +265,13 @@ impl CultMeshRudpSubscriptionClient { let pump = thread::Builder::new() .name("cultmesh-rudp-subscription".into()) .spawn(move || pump.run())?; - Ok(Self { commands, events: Mutex::new(events), undrained, pump: Some(pump) }) + Ok(Self { commands, events: Mutex::new(events), undrained, pump_alive, pump: Some(pump) }) + } + + /// A weak handle that upgrades while this client's own pump thread exists, and never after it has been joined. + /// Tests use it to prove that dropping the client ends its thread. + pub fn pump_liveness(&self) -> Weak<()> { + self.pump_alive.clone() } /// Queues a subscribe with a snapshot and returns; the snapshot arrives as an event. Subscribing an id that is @@ -330,7 +343,14 @@ struct Pump { /// Assembled events whose rows are not all known yet, in arrival order, and their weight. pending: VecDeque, pending_weight: usize, - awaiting: Option, + /// The catalog requests in flight; their keys are not asked for again. + awaiting: Vec, + /// When a pair whose request timed out may be asked for again. Not an absence: the record that arrives after + /// this passes asks afresh. + backoff: BTreeMap, + /// Held for as long as the pump thread runs; see `pump_liveness`. + #[allow(dead_code)] + alive: Arc<()>, /// What `resubscribe_all` resends. The assembler owns what is live; it holds no selections. subscriptions: BTreeMap, receipts: Vec, @@ -432,7 +452,8 @@ impl Pump { self.receipts.clear(); self.pending.clear(); self.pending_weight = 0; - self.awaiting = None; + self.awaiting.clear(); + self.backoff.clear(); self.rows.retain(|_, rows| rows.is_ok()); let ids: Vec<_> = self.subscriptions.keys().cloned().collect(); for id in ids { @@ -475,8 +496,8 @@ impl Pump { if failure.is_none() { failure = self.invalidated(); } - if failure.is_none() && self.awaiting.as_ref().is_some_and(|a| a.sent.elapsed() >= self.options.catalog_timeout) { - self.catalog_unanswered(NoMembersReason::CatalogTimedOut); + if failure.is_none() { + self.expire_requests(); } if let Some(reason) = failure { self.disconnected(reason); @@ -488,16 +509,12 @@ impl Pump { let Ok(message) = decode_cultnet_message_from_slice(payload, CultNetWireContract::CultNetSchemaV0) else { return }; let events = match message { CultNetMessage::SchemaCatalogResponse { message_id, schemas } => { - if self.awaiting.as_ref().is_some_and(|a| a.message_id == message_id) { - self.catalog_answered(schemas); - } + self.catalog_answered(&message_id, schemas); return; } - CultNetMessage::ErrorV1 { error, message_id: Some(id), .. } - if self.awaiting.as_ref().is_some_and(|a| a.message_id == id) => - { + CultNetMessage::ErrorV1 { error, message_id: Some(id), .. } if self.awaiting.iter().any(|a| a.message_id == id) => { let detail = recognised_refusal(&error); - return self.catalog_unanswered(NoMembersReason::CatalogRefused { detail }); + return self.catalog_refused(&id, detail); } CultNetMessage::Error { error, .. } => self.assembler.refused(None, &recognised_refusal(&error)), CultNetMessage::ErrorV1 { error, message_id, .. } => { @@ -524,7 +541,6 @@ impl Pump { ); self.pending.clear(); self.pending_weight = 0; - self.awaiting = None; for fault in self.assembler.latch_fault(reason) { self.pending_weight += event_weight(&fault); self.pending.push_back(fault); @@ -535,14 +551,20 @@ impl Pump { self.pending.push_back(event); } - /// Delivers pending events in order while their rows are known; at the first that needs rows not yet known, - /// sends one catalog request for what that event lacks and waits for its answer. + /// Delivers pending events in order while their rows are known. Whatever the waiting events lack, across all + /// of them and not already asked for, goes out in one catalog request, so that N unseen schemas wait one + /// timeout, not N. fn release(&mut self) { - while self.awaiting.is_none() { - let Some(front) = self.pending.front() else { return }; - let missing: BTreeSet = documents_of(front).into_iter().filter_map(|d| self.lookup(d).err()).collect(); - if !missing.is_empty() { - return self.request_catalog(missing); + let lacking: BTreeSet = + self.pending.iter().flat_map(documents_of).filter_map(|d| self.lookup(d).err()).collect(); + let unasked: BTreeSet = + lacking.into_iter().filter(|key| !self.awaiting.iter().any(|a| a.keys.contains(key))).collect(); + if !unasked.is_empty() { + self.request_catalog(unasked); + } + while let Some(front) = self.pending.front() { + if documents_of(front).into_iter().any(|d| self.lookup(d).is_err()) { + return; } let event = self.pending.pop_front().expect("front was just read"); self.pending_weight -= event_weight(&event); @@ -559,6 +581,9 @@ impl Pump { match self.rows.get(&key) { Some(Ok(rows)) => Ok(MemberRows::Served(rows.clone())), Some(Err(reason)) => Ok(MemberRows::NoMembers(reason.clone())), + None if self.backoff.get(&key).is_some_and(|until| Instant::now() < *until) => { + Ok(MemberRows::NoMembers(NoMembersReason::CatalogTimedOut)) + } None => Err(key), } } @@ -596,7 +621,7 @@ impl Pump { fn request_catalog(&mut self, keys: BTreeSet) { let message_id = self.next_message_id(); let schema_ids: BTreeSet = keys.iter().map(|(id, _)| id.clone()).collect(); - self.awaiting = Some(Awaiting { message_id: message_id.clone(), keys, sent: Instant::now() }); + self.awaiting.push(Awaiting { message_id: message_id.clone(), keys, sent: Instant::now() }); let message = CultNetMessage::SchemaCatalogRequest { message_id, include_schema_json: None, @@ -607,9 +632,11 @@ impl Pump { self.transmit(&message); } - /// The answer: every requested pair is settled, by its rows or by the stated reason it has none. - fn catalog_answered(&mut self, schemas: Vec) { - let Some(awaiting) = self.awaiting.take() else { return }; + /// The answer to a request in flight: every pair it asked for is settled, by its rows or by the stated reason + /// it has none. An answer to nothing in flight is ignored. + fn catalog_answered(&mut self, message_id: &str, schemas: Vec) { + let Some(at) = self.awaiting.iter().position(|a| a.message_id == message_id) else { return }; + let awaiting = self.awaiting.remove(at); for descriptor in &schemas { if let Some(members) = descriptor.members.as_ref().filter(|members| !members.is_empty()) { let key = (descriptor.schema_id.clone(), descriptor.content_hash.clone()); @@ -630,11 +657,28 @@ impl Pump { self.release(); } - /// No answer will come (refused, or too slow): every requested pair is settled as absent for this session. - fn catalog_unanswered(&mut self, reason: NoMembersReason) { - let Some(awaiting) = self.awaiting.take() else { return }; - for key in awaiting.keys { - self.rows.insert(key, Err(reason.clone())); + /// The peer refused the request: its pairs are absent for this session. + fn catalog_refused(&mut self, message_id: &str, detail: String) { + let Some(at) = self.awaiting.iter().position(|a| a.message_id == message_id) else { return }; + for key in self.awaiting.remove(at).keys { + self.rows.insert(key, Err(NoMembersReason::CatalogRefused { detail: detail.clone() })); + } + self.release(); + } + + /// A request past `catalog_timeout` is given up: its records are delivered without rows, and its pairs may be + /// asked for again by a record arriving once the same time has passed. + fn expire_requests(&mut self) { + let timeout = self.options.catalog_timeout; + let (expired, live): (Vec<_>, Vec<_>) = + std::mem::take(&mut self.awaiting).into_iter().partition(|a| a.sent.elapsed() >= timeout); + self.awaiting = live; + if expired.is_empty() { + return; + } + let until = Instant::now() + timeout; + for key in expired.into_iter().flat_map(|a| a.keys) { + self.backoff.insert(key, until); } self.release(); } @@ -645,9 +689,6 @@ impl Pump { if self.pending.len() != before { self.pending_weight = self.pending.iter().map(event_weight).sum(); } - if self.pending.is_empty() { - self.awaiting = None; - } } fn push(&self, event: CultMeshSubscriptionEvent) { @@ -689,7 +730,7 @@ impl Pump { fn disconnected(&mut self, reason: String) { if self.session.take().is_some() { self.receipts.clear(); - self.awaiting = None; + self.awaiting.clear(); // Records already received are delivered, with the stated reason they have no rows, not dropped. while let Some(event) = self.pending.pop_front() { self.pending_weight -= event_weight(&event); diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index 9a6bb7ed..cb1a004c 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -162,6 +162,22 @@ fn options(peer: &Peer) -> CultMeshRudpSubscriptionOptions { options } +/// Options for a test that ends the session. The peer's goodbye is one unreliable datagram that may never arrive, so +/// `Disconnected` must come either from it or from the client's own idle timeout, which these options make short. +fn options_ending_sessions(peer: &Peer) -> CultMeshRudpSubscriptionOptions { + let mut options = options(peer); + options.keepalive_interval = Duration::from_millis(100); + options.idle_timeout = Duration::from_millis(800); + options +} + +fn disconnect_reason(event: &CultMeshSubscriptionEvent) -> &str { + match event { + CultMeshSubscriptionEvent::Disconnected { reason } => reason, + other => panic!("expected a disconnect, got {other:?}"), + } +} + /// The C#-written session, one message per entry: subscribe, snapshot, a single change, a two-change commit (two /// messages), a removal. fn session() -> Vec> { @@ -503,15 +519,13 @@ fn an_error_for_something_else_leaves_the_subscription_alone() { #[test] fn the_peer_going_away_is_one_disconnected_and_resubscribe_all_reconnects() { let peer = Peer::start(); - let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + let client = CultMeshRudpSubscriptionClient::connect(options_ending_sessions(&peer)).unwrap(); subscribed(&peer, &client); peer.disconnect(); let events = drain_events(&client, 1); - assert!( - matches!(&events[0], CultMeshSubscriptionEvent::Disconnected { reason } if reason.contains("scripted-goodbye")), - "{events:?}" - ); + let reason = disconnect_reason(&events[0]); + assert!(reason.contains("scripted-goodbye") || reason.contains("no packet"), "{events:?}"); quiet(&client); // A subscribe while disconnected is kept, not lost and not a hang. client.subscribe("late", vector_selection()).unwrap(); @@ -530,7 +544,7 @@ fn the_peer_going_away_is_one_disconnected_and_resubscribe_all_reconnects() { #[test] fn a_reconnect_to_a_peer_that_is_gone_is_a_disconnected_not_a_hang() { let peer = Peer::start(); - let mut options = options(&peer); + let mut options = options_ending_sessions(&peer); options.connect_timeout = Duration::from_millis(200); let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); client.subscribe("sub-1", vector_selection()).unwrap(); @@ -556,19 +570,14 @@ fn dropping_the_client_unsubscribes_each_live_id_and_stops_its_thread() { // An unsubscribed id is forgotten: not resent, not unsubscribed again. client.resubscribe_all().unwrap(); assert_eq!(peer.subscribe_id().1, "one"); - let before = thread_count(); + let pump = client.pump_liveness(); + assert!(pump.upgrade().is_some(), "the pump thread runs while its handle lives"); let started = Instant::now(); drop(client); assert!(started.elapsed() < Duration::from_secs(2), "drop joins promptly"); assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "one")); assert!(peer.received.recv_timeout(Duration::from_millis(300)).is_err(), "nothing else is sent"); - if cfg!(target_os = "linux") { - assert!(thread_count() < before, "the pump thread is gone with its handle"); - } -} - -fn thread_count() -> usize { - std::fs::read_dir("/proc/self/task").map(|tasks| tasks.count()).unwrap_or(usize::MAX) + assert!(pump.upgrade().is_none(), "the pump thread is gone with its handle"); } #[test] @@ -874,7 +883,7 @@ fn a_record_that_names_no_hash_is_delivered_without_rows_and_asks_for_nothing() #[test] fn records_waiting_for_rows_when_the_session_ends_are_delivered_not_dropped() { let peer = Peer::start(); - let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + let client = CultMeshRudpSubscriptionClient::connect(options_ending_sessions(&peer)).unwrap(); client.subscribe("sub-1", vector_selection()).unwrap(); let (message_id, _) = peer.subscribe_id(); peer.send(&snapshot_answering(&message_id)); @@ -960,3 +969,147 @@ fn a_new_session_asks_again_for_rows_that_were_absent_but_keeps_the_rows_it_has( assert_eq!(drain_events(&client, 1).len(), 1); no_more_requests(&peer); } + +/// Both ways a session ends. A peer's goodbye is one unreliable datagram: when it arrives the client says so at +/// once, however long its idle timeout; when it is lost (here: never sent) the client's own idle timeout ends the +/// session. Neither test needs the other's datagram. +#[test] +fn a_goodbye_that_arrives_ends_the_session_at_once() { + let peer = Peer::start(); + // A goodbye may be lost on a loaded host; the claim is that one which arrives is not waited out, so a lost one is + // tried again on a fresh session, and only five losses in a row fail. + for _ in 0..5 { + let mut options = options(&peer); + options.idle_timeout = Duration::from_secs(30); + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + peer.disconnect(); + let deadline = Instant::now() + Duration::from_secs(2); + let mut events = Vec::new(); + while events.is_empty() && Instant::now() < deadline { + events = client.try_drain(); + thread::sleep(Duration::from_millis(5)); + } + if let Some(event) = events.first() { + assert!(disconnect_reason(event).contains("scripted-goodbye"), "{events:?}"); + return; + } + } + panic!("no goodbye arrived in five sessions"); +} + +#[test] +fn a_goodbye_that_never_arrives_is_the_idle_timeout() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options_ending_sessions(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + peer.stall(); // the peer is gone and said nothing + let started = Instant::now(); + let events = drain_events(&client, 1); + assert!(disconnect_reason(&events[0]).contains("no packet"), "{events:?}"); + assert!(started.elapsed() >= Duration::from_millis(600), "not before the idle timeout: {:?}", started.elapsed()); +} + +/// A change of the vector naming another schema (and the hash of its own). +fn change_for_schema(message_id: &str, schema_id: &str) -> CultNetMessage { + let mut message = change_naming(message_id, None); + let CultNetMessage::DatabaseChangeRaw { document: Some(document), .. } = &mut message else { panic!("{message:?}") }; + document.schema_id = schema_id.into(); + message +} + +#[test] +fn unseen_schemas_behind_a_silent_peer_wait_one_timeout_not_one_each() { + let peer = Peer::start(); + let mut options = options(&peer); + options.catalog_timeout = Duration::from_millis(500); + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + let mut snapshot = snapshot_answering(&message_id); + let CultNetMessage::SnapshotResponseRawV1 { documents, .. } = &mut snapshot else { panic!("{snapshot:?}") }; + for (index, document) in documents.iter_mut().flatten().enumerate() { + document.schema_id = format!("schema-{index}"); + } + let started = Instant::now(); + peer.send(&snapshot); + peer.send(&change_for_schema("later", "schema-9")); + let (_, mut first) = catalog_request(&peer); + first.sort(); + assert_eq!(first, ["schema-0", "schema-1"], "one request lists every unseen schema of the event"); + let (_, second) = catalog_request(&peer); + assert_eq!(second, ["schema-9"], "a later unseen schema is asked for at once, not after the first times out"); + let events = drain_events(&client, 2); + assert!(started.elapsed() < Duration::from_millis(900), "{:?}", started.elapsed()); + let absent = MemberRows::NoMembers(NoMembersReason::CatalogTimedOut); + assert_eq!(snapshot_rows(&events[0]), [&absent, &absent]); + assert_eq!(commit_rows(&events[1]), [&absent]); +} + +#[test] +fn a_catalog_timeout_is_not_latched_a_later_record_asks_again() { + let peer = Peer::start(); + let mut options = options(&peer); + options.catalog_timeout = Duration::from_millis(300); + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&snapshot_answering(&message_id)); + catalog_request(&peer); // never answered + let absent = MemberRows::NoMembers(NoMembersReason::CatalogTimedOut); + assert_eq!(snapshot_rows(&drain_events(&client, 1)[0]), [&absent, &absent]); + // Within the backoff the pair is not asked for again. + peer.send(&change_naming("soon", None)); + assert_eq!(commit_rows(&drain_events(&client, 1)[0]), [&absent]); + no_more_requests(&peer); + // After it a record asks afresh, and the answer is served. + thread::sleep(Duration::from_millis(350)); + peer.send(&change_naming("after", None)); + serve_rows(&peer); + assert_eq!(commit_rows(&drain_events(&client, 1)[0]), [&served(vector_members())]); +} + +#[test] +fn an_error_for_another_request_does_not_release_events_waiting_for_rows() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + peer.send(&snapshot_answering(&message_id)); + let (request_id, _) = catalog_request(&peer); + peer.send(&CultNetMessage::ErrorV1 { error: "x".into(), code: None, details: None, message_id: Some("other".into()) }); + quiet(&client); + let (schema_id, hash) = vector_schema(); + answer_catalog(&peer, &request_id, vec![descriptor(&schema_id, &hash, Some(vector_members()))]); + assert_eq!(snapshot_rows(&drain_events(&client, 1)[0]), [&served(vector_members()), &served(vector_members())]); +} + +#[test] +fn unsubscribing_releases_the_weight_of_the_events_it_forgets() { + let peer = Peer::start(); + let mut options = options(&peer); + options.max_undrained = 3; + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + client.subscribe("one", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + let mut snapshot = snapshot_answering(&message_id); + let CultNetMessage::SnapshotResponseRawV1 { .. } = &snapshot else { panic!() }; + peer.send(&snapshot); // two documents wait for rows + let (request_id, _) = catalog_request(&peer); + client.unsubscribe("one").unwrap(); + assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { .. })); + client.subscribe("two", vector_selection()).unwrap(); + let (message_id, _) = peer.subscribe_id(); + if let CultNetMessage::SnapshotResponseRawV1 { message_id: id, .. } = &mut snapshot { + *id = message_id; + } + peer.send(&snapshot); // two more: with the forgotten two still counted this would be four, past the bound + peer.send(&single_change("c", "two")); // three + let (schema_id, hash) = vector_schema(); + answer_catalog(&peer, &request_id, vec![descriptor(&schema_id, &hash, Some(vector_members()))]); + let events = drain_events(&client, 2); + assert!(matches!(&events[0], CultMeshSubscriptionEvent::Snapshot { subscription_id, .. } if subscription_id == "two"), "{events:?}"); + assert_eq!(keys(&events[1]), ["k"]); +}