From b500efdfc69a6ef3f94d39f8b6dfac14b057470b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 12:58:08 +0100 Subject: [PATCH 1/5] cultmesh-rs: close and Drop interrupt a reconnect in progress (close-drop-block-in-reconnect) The pump's reconnect waited out connect_timeout inline, so close() gave up at its reply bound and then joined anyway, and Drop joined the whole wait. close and Drop now set a closing flag the connect loop polls; the reconnect ends within one poll. The test proves the pump is inside open() (the silent peer has seen its Connect). Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-rs/src/lib.rs | 6 ++ packages/cultmesh-rs/src/rudp_subscription.rs | 19 ++-- .../cultmesh-rs/tests/rudp_subscription.rs | 89 ++++++++++++++++++- 3 files changed, 106 insertions(+), 8 deletions(-) diff --git a/packages/cultmesh-rs/src/lib.rs b/packages/cultmesh-rs/src/lib.rs index 987f2dc4..61728331 100644 --- a/packages/cultmesh-rs/src/lib.rs +++ b/packages/cultmesh-rs/src/lib.rs @@ -819,6 +819,7 @@ pub fn request_raw_snapshot_from_rudp_catalog( options.resend_delay_ms, "cultmesh-rudp-snapshot-client", None, + &|| false, )?; let request = cultnet_rs::CultNetMessage::SnapshotRequest { @@ -944,6 +945,7 @@ pub fn publish_cultnet_messages_to_rudp_catalog( options.resend_delay_ms, "cultmesh-rudp-document-publisher", None, + &|| false, )?; let mut receipts = Vec::with_capacity(messages.len()); @@ -1012,6 +1014,7 @@ fn connect_rudp_client( resend_delay_ms: u64, transport_id: &str, connection_id: Option, + cancelled: &dyn Fn() -> bool, ) -> Result { let bind_addr = if target.is_ipv4() { SocketAddr::from(([0, 0, 0, 0], 0)) @@ -1040,6 +1043,9 @@ fn connect_rudp_client( client.connect(Vec::new())?; let connect_deadline = Instant::now() + connect_timeout; while !client.connected() && Instant::now() < connect_deadline { + if cancelled() { + anyhow::bail!("connecting CultMesh RUDP client {runtime_id} to {target} was cancelled"); + } let _ = client.receive_once()?; client.poll_resends()?; thread::sleep(poll_interval); diff --git a/packages/cultmesh-rs/src/rudp_subscription.rs b/packages/cultmesh-rs/src/rudp_subscription.rs index 3db8fc22..aa4f38c0 100644 --- a/packages/cultmesh-rs/src/rudp_subscription.rs +++ b/packages/cultmesh-rs/src/rudp_subscription.rs @@ -36,7 +36,7 @@ use cultnet_rs::{ use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::fmt; use std::net::SocketAddr; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError}; use std::sync::{Arc, Mutex, Weak}; use std::thread::{self, JoinHandle}; @@ -222,6 +222,7 @@ pub struct CultMeshRudpSubscriptionClient { events: Mutex>, undrained: Arc, pump_alive: Weak<()>, + closing: Arc, pump: Option>, } @@ -231,13 +232,15 @@ impl CultMeshRudpSubscriptionClient { if options.runtime_id.trim().is_empty() { return Err(anyhow!("runtime_id must be non-empty")); } - let session = open(&options)?; + let session = open(&options, &|| false)?; + let closing = Arc::new(AtomicBool::new(false)); 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 { + closing: closing.clone(), options, session: Some(session), assembler: SubscriptionAssembler::new(), @@ -259,7 +262,7 @@ 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_alive, pump: Some(pump) }) + Ok(Self { commands, events: Mutex::new(events), undrained, pump_alive, closing, pump: Some(pump) }) } /// A weak handle that upgrades while this client's own pump thread exists, and never after it has been joined. @@ -305,6 +308,7 @@ impl CultMeshRudpSubscriptionClient { /// session and joins the pump thread. Returns whether the acknowledgement arrived; `false` says the peer may /// still hold the subscriptions until its own idle timeout. pub fn close(mut self) -> bool { + self.closing.store(true, Ordering::SeqCst); let (reply, answer) = mpsc::channel(); let sent = self.commands.send(Command::Close { reply: Some(reply) }).is_ok(); let acknowledged = sent && answer.recv_timeout(CLOSE_ACK_WAIT * 2).unwrap_or(false); @@ -319,6 +323,7 @@ impl CultMeshRudpSubscriptionClient { /// [`close`](CultMeshRudpSubscriptionClient::close) to learn whether the peer acknowledged. impl Drop for CultMeshRudpSubscriptionClient { fn drop(&mut self) { + self.closing.store(true, Ordering::SeqCst); let _ = self.commands.send(Command::Close { reply: None }); if let Some(pump) = self.pump.take() { let _ = pump.join(); @@ -326,7 +331,7 @@ impl Drop for CultMeshRudpSubscriptionClient { } } -fn open(options: &CultMeshRudpSubscriptionOptions) -> Result { +fn open(options: &CultMeshRudpSubscriptionOptions, cancelled: &dyn Fn() -> bool) -> Result { connect_rudp_client( options.target, &options.runtime_id, @@ -335,6 +340,7 @@ fn open(options: &CultMeshRudpSubscriptionOptions) -> Result, options: CultMeshRudpSubscriptionOptions, /// `None` after the session ended: the pump reads nothing and waits for a command. session: Option, @@ -450,7 +459,7 @@ impl Pump { self.session = None; } if self.session.is_none() { - match open(&self.options) { + match open(&self.options, &|| self.closing.load(Ordering::SeqCst)) { Ok(session) => { self.session = Some(session); self.last_ping = Instant::now(); diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index ecf005aa..ce00e02f 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -22,14 +22,27 @@ enum PeerCommand { Disconnect, /// Reads nothing and answers nothing (no pong, no ack) until `Disconnect`: a peer that died without a goodbye. Stall, + /// Between sessions, reads and answers no Connect, but reports each one it sees, until `Disconnect`: a peer that + /// is unreachable while a client tries to reconnect. + Refuse, Stop, } +/// What the peer's thread says about itself, so a test waits for a fact and not for a sleep. +#[derive(Debug, PartialEq, Eq)] +enum PeerEvent { + /// `Refuse` has taken effect: no Connect sent from now on is answered. + Refusing, + /// A Connect arrived while refusing. + ConnectSeen, +} + /// A peer that accepts RUDP connects on a loopback socket and reports every schema message it receives. struct Peer { addr: SocketAddr, commands: Sender, received: Receiver, + events: Receiver, thread: Option>, } @@ -39,8 +52,9 @@ impl Peer { let addr = socket.local_addr().unwrap(); let (commands, command_rx) = mpsc::channel(); let (received_tx, received) = mpsc::channel(); - let thread = thread::spawn(move || serve(socket, command_rx, received_tx)); - Self { addr, commands, received, thread: Some(thread) } + let (event_tx, events) = mpsc::channel(); + let thread = thread::spawn(move || serve(socket, command_rx, received_tx, event_tx)); + Self { addr, commands, received, events, thread: Some(thread) } } fn send(&self, message: &CultNetMessage) { @@ -56,6 +70,17 @@ impl Peer { self.commands.send(PeerCommand::Stall).unwrap(); } + fn expect(&self, expected: PeerEvent) { + let event = self.events.recv_timeout(Duration::from_secs(5)).expect("the peer reported an event"); + assert_eq!(event, expected); + } + + /// Returns once the peer is refusing Connects, so none sent after it returns is answered. + fn refuse_connects(&self) { + self.commands.send(PeerCommand::Refuse).unwrap(); + self.expect(PeerEvent::Refusing); + } + fn disconnect(&self) { self.commands.send(PeerCommand::Disconnect).unwrap(); } @@ -84,7 +109,12 @@ impl Drop for Peer { } } -fn serve(socket: UdpSocket, commands: Receiver, received: Sender) { +fn serve( + socket: UdpSocket, + commands: Receiver, + received: Sender, + events: Sender, +) { socket.set_read_timeout(Some(Duration::from_millis(2))).unwrap(); 'sessions: loop { // The client's connection id is its own epoch: read it from the Connect before the session exists. @@ -92,6 +122,23 @@ fn serve(socket: UdpSocket, commands: Receiver, received: Sender return, + Ok(PeerCommand::Refuse) => { + let _ = events.send(PeerEvent::Refusing); + loop { + match commands.try_recv() { + Ok(PeerCommand::Stop) | Err(mpsc::TryRecvError::Disconnected) => return, + Ok(PeerCommand::Disconnect) => continue 'sessions, + _ => {} + } + if let Ok((length, _)) = socket.recv_from(&mut wire) { + if decode_rudp_packet(&wire[..length]) + .is_ok_and(|packet| packet.packet_type == cultnet_rs::CultNetRudpPacketType::Connect) + { + let _ = events.send(PeerEvent::ConnectSeen); + } + } + } + } _ => {} } if let Ok(found) = socket.peek_from(&mut wire) { @@ -140,6 +187,7 @@ fn serve(socket: UdpSocket, commands: Receiver, received: Sender {} } }, + PeerCommand::Refuse => {} PeerCommand::Stop => return, } } @@ -1143,3 +1191,38 @@ fn drop_does_not_wait_for_a_peer_that_acknowledges_nothing() { assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed()); assert!(pump.upgrade().is_none(), "the thread still stops"); } + +/// A client whose session ended and whose `resubscribe_all` is inside its reconnect to a peer that answers nothing, +/// proven so: the peer has seen the client's Connect, and the client would wait out `connect_timeout` (3 s) for an +/// answer that never comes. +fn reconnecting_to_a_silent_peer() -> (Peer, CultMeshRudpSubscriptionClient) { + let peer = Peer::start(); + let mut options = options_ending_sessions(&peer); + options.connect_timeout = Duration::from_secs(3); + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + subscribed(&peer, &client); + peer.disconnect(); + drain_events(&client, 1); + peer.refuse_connects(); + client.resubscribe_all().unwrap(); + peer.expect(PeerEvent::ConnectSeen); + (peer, client) +} + +#[test] +fn close_stays_within_its_bound_while_the_pump_reconnects_to_a_silent_peer() { + let (_peer, client) = reconnecting_to_a_silent_peer(); + let started = Instant::now(); + assert!(!client.close(), "there is no session whose unsubscribes could have been acknowledged"); + assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed()); +} + +#[test] +fn drop_does_not_wait_for_a_reconnect_to_a_silent_peer() { + let (_peer, client) = reconnecting_to_a_silent_peer(); + let pump = client.pump_liveness(); + let started = Instant::now(); + drop(client); + assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed()); + assert!(pump.upgrade().is_none(), "the thread still stops"); +} -- 2.47.3 From 1e309f02706e2c997a77f6ef1d77626f9a6fb727 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 12:58:48 +0100 Subject: [PATCH 2/5] cultmesh-rs tests: the scripted peer reports that it has stalled (stall-proven-by-sleep) peer.stall() now returns once the peer's thread has entered the stall, so the close and Drop tests meet a peer proven silent; the two 100 ms sleeps that stood in for that proof are gone. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/tests/rudp_subscription.rs | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index ce00e02f..ec646e47 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -31,6 +31,8 @@ enum PeerCommand { /// What the peer's thread says about itself, so a test waits for a fact and not for a sleep. #[derive(Debug, PartialEq, Eq)] enum PeerEvent { + /// `Stall` has taken effect: the peer reads nothing from now on. + Stalled, /// `Refuse` has taken effect: no Connect sent from now on is answered. Refusing, /// A Connect arrived while refusing. @@ -66,8 +68,11 @@ impl Peer { self.commands.send(PeerCommand::Send(payload)).unwrap(); } + /// Returns once the peer's thread has entered the stall, so what the test does next meets a peer that is + /// silent, not one that has not yet read the command. fn stall(&self) { self.commands.send(PeerCommand::Stall).unwrap(); + self.expect(PeerEvent::Stalled); } fn expect(&self, expected: PeerEvent) { @@ -180,13 +185,16 @@ fn serve( session.disconnect(b"scripted-goodbye".to_vec()).unwrap(); continue 'sessions; } - PeerCommand::Stall => loop { - match commands.recv() { - Ok(PeerCommand::Disconnect) => continue 'sessions, - Ok(PeerCommand::Stop) | Err(_) => return, - Ok(_) => {} + PeerCommand::Stall => { + let _ = events.send(PeerEvent::Stalled); + loop { + match commands.recv() { + Ok(PeerCommand::Disconnect) => continue 'sessions, + Ok(PeerCommand::Stop) | Err(_) => return, + Ok(_) => {} + } } - }, + } PeerCommand::Refuse => {} PeerCommand::Stop => return, } @@ -1168,8 +1176,7 @@ fn close_waits_for_the_acknowledgement_and_says_when_it_does_not_come() { let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); client.subscribe("sub-1", vector_selection()).unwrap(); peer.subscribe_id(); - peer.stall(); // reads nothing, acknowledges nothing - thread::sleep(Duration::from_millis(100)); // the peer thread has taken the stall before the client closes + peer.stall(); // returns once the peer reads nothing and acknowledges nothing let started = Instant::now(); assert!(!client.close(), "no acknowledgement came"); let waited = started.elapsed(); @@ -1184,7 +1191,6 @@ fn drop_does_not_wait_for_a_peer_that_acknowledges_nothing() { client.subscribe("sub-1", vector_selection()).unwrap(); peer.subscribe_id(); peer.stall(); - thread::sleep(Duration::from_millis(100)); let pump = client.pump_liveness(); let started = Instant::now(); drop(client); -- 2.47.3 From 8d87ea2ec153390bd13163d01d01758be56183f7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 12:58:48 +0100 Subject: [PATCH 3/5] cultmesh-rs tests: Drop sends an unsubscribe for each live id (drop-unsubscribes-untested) A live peer observes the unsubscribes a dropped client sends, one per live id and none for an id already unsubscribed. Co-Authored-By: Claude Opus 5.5 --- .../cultmesh-rs/tests/rudp_subscription.rs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index ec646e47..dde78d97 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -1232,3 +1232,27 @@ fn drop_does_not_wait_for_a_reconnect_to_a_silent_peer() { assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed()); assert!(pump.upgrade().is_none(), "the thread still stops"); } + +#[test] +fn drop_sends_an_unsubscribe_for_each_live_id() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("one", vector_selection()).unwrap(); + client.subscribe("two", vector_selection()).unwrap(); + client.subscribe("gone", vector_selection()).unwrap(); + client.unsubscribe("gone").unwrap(); + for _ in 0..3 { + peer.subscribe_id(); + } + assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "gone")); + drop(client); + let mut unsubscribed: Vec = (0..2) + .map(|_| match peer.next() { + CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } => subscription_id, + other => panic!("expected an unsubscribe, got {other:?}"), + }) + .collect(); + unsubscribed.sort(); + assert_eq!(unsubscribed, ["one", "two"]); + assert!(peer.received.recv_timeout(Duration::from_millis(300)).is_err(), "nothing else is sent"); +} -- 2.47.3 From 1d06c3bdf8e2c57bc47c932b513eb692d10ac9af Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 13:00:45 +0100 Subject: [PATCH 4/5] cultmesh-rs: close's result is the pump's; pin close and drain weight; docs; test seam off the API - close() takes the acknowledgement from the pump thread's join result: no reply channel, no second 1 s give-up, and returning before the pump ended is not expressible (close-survivors-untested). Tests pin the early return on acknowledgement, the goodbye, the join, and false after the session ended. - A test pins that try_drain releases the weight of each event (drain-weight-untested) and that a refused subscribe is a fault while a catalog request is in flight (refusal-during-wait-untested). - The module Lifetime paragraph names close() and Drop's best effort; the struct doc no longer says methods never block on the network (module-doc-omits-close). - pump_liveness is behind the crate's own test-hooks feature, enabled for its tests by a dev-dependency on itself, so a consumer's API does not carry it (pump-liveness-public-hook). Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-rs/Cargo.lock | 1 + packages/cultmesh-rs/Cargo.toml | 6 ++ packages/cultmesh-rs/src/rudp_subscription.rs | 83 +++++++++++-------- .../cultmesh-rs/tests/rudp_subscription.rs | 71 +++++++++++++++- 4 files changed, 125 insertions(+), 36 deletions(-) diff --git a/packages/cultmesh-rs/Cargo.lock b/packages/cultmesh-rs/Cargo.lock index c45da112..6f4518c7 100644 --- a/packages/cultmesh-rs/Cargo.lock +++ b/packages/cultmesh-rs/Cargo.lock @@ -235,6 +235,7 @@ dependencies = [ "anyhow", "base64", "cultcache-rs", + "cultmesh-rs", "cultnet-rs", "p256", "pretty_assertions", diff --git a/packages/cultmesh-rs/Cargo.toml b/packages/cultmesh-rs/Cargo.toml index 984b74ab..08239721 100644 --- a/packages/cultmesh-rs/Cargo.toml +++ b/packages/cultmesh-rs/Cargo.toml @@ -9,6 +9,10 @@ publish = false name = "cultmesh_rs" path = "src/lib.rs" +[features] +# Seams only this crate's own tests use; not part of the API a consumer builds against. +test-hooks = [] + [dependencies] anyhow = "1" cultcache-rs = { path = "../cultcache-rs" } @@ -18,6 +22,8 @@ p256 = { version = "0.13", default-features = false, features = ["ecdsa", "std"] serde = { version = "1", features = ["derive"] } [dev-dependencies] +# The tests enable the crate's own `test-hooks` feature. +cultmesh-rs = { path = ".", features = ["test-hooks"] } pretty_assertions = "1.4.1" rmp-serde = "1" serde_json = "1" diff --git a/packages/cultmesh-rs/src/rudp_subscription.rs b/packages/cultmesh-rs/src/rudp_subscription.rs index aa4f38c0..4ba6dc50 100644 --- a/packages/cultmesh-rs/src/rudp_subscription.rs +++ b/packages/cultmesh-rs/src/rudp_subscription.rs @@ -4,8 +4,11 @@ //! only queues commands and drains events. RUDP acknowledgements and resends keep their cadence while the caller is //! idle, which is why this is a thread and not a method the caller must tick. //! -//! Lifetime: dropping the client unsubscribes each live id, disconnects and joins the thread, so no thread outlives -//! its handle. A closed or failed session is an event ([`CultMeshSubscriptionEvent::Disconnected`]), never a hang; +//! Lifetime: [`close`](CultMeshRudpSubscriptionClient::close) unsubscribes each live id, waits up to 500 ms for the +//! peer to acknowledge, disconnects, joins the thread and returns whether the acknowledgement arrived. Dropping the +//! client does the same without the wait: best effort, the unsubscribes are sent and the peer's answer is not +//! awaited. Either way no thread outlives its handle, and a reconnect in progress is abandoned at its next poll +//! instead of waiting out `connect_timeout`. A closed or failed session is an event ([`CultMeshSubscriptionEvent::Disconnected`]), never a hang; //! after it the thread reads nothing and waits for `resubscribe_all` or the drop. //! //! Bounds: the assembler bounds what it holds of incomplete commits and faults the connection past that. What the @@ -38,7 +41,7 @@ use std::fmt; use std::net::SocketAddr; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError}; -use std::sync::{Arc, Mutex, Weak}; +use std::sync::{Arc, Mutex}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; @@ -211,19 +214,21 @@ enum Command { Subscribe(String, Selection), Unsubscribe(String), Resubscribe, - /// Ends the session. With a `reply`, waits (bounded) for the unsubscribes to be acknowledged and says whether - /// they were; without one, sends them and goes. - Close { reply: Option> }, + /// Ends the session. With `wait`, first waits (bounded) for the unsubscribes to be acknowledged; without it, + /// sends them and goes. The pump thread's result says whether they were acknowledged. + Close { wait: bool }, } -/// A live subscription connection. Methods never block on the network. +/// A live subscription connection. Methods return without waiting on the peer, except `connect`, which waits up to +/// `connect_timeout`, and `close`, which waits up to 500 ms for the unsubscribes to be acknowledged. pub struct CultMeshRudpSubscriptionClient { commands: Sender, events: Mutex>, undrained: Arc, - pump_alive: Weak<()>, + #[cfg(feature = "test-hooks")] + pump_alive: std::sync::Weak<()>, closing: Arc, - pump: Option>, + pump: Option>, } impl CultMeshRudpSubscriptionClient { @@ -237,7 +242,9 @@ impl CultMeshRudpSubscriptionClient { let (commands, command_rx) = mpsc::channel(); let (event_tx, events) = mpsc::channel(); let undrained = Arc::new(AtomicUsize::new(0)); + #[cfg(feature = "test-hooks")] let alive = Arc::new(()); + #[cfg(feature = "test-hooks")] let pump_alive = Arc::downgrade(&alive); let pump = Pump { closing: closing.clone(), @@ -249,6 +256,7 @@ impl CultMeshRudpSubscriptionClient { pending_weight: 0, awaiting: Vec::new(), backoff: BTreeMap::new(), + #[cfg(feature = "test-hooks")] alive, subscriptions: BTreeMap::new(), receipts: Vec::new(), @@ -262,12 +270,22 @@ 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_alive, closing, pump: Some(pump) }) + Ok(Self { + commands, + events: Mutex::new(events), + undrained, + #[cfg(feature = "test-hooks")] + pump_alive, + closing, + 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<()> { + /// Only under the `test-hooks` feature, which this crate's own tests enable: not part of the API a consumer + /// builds against. + #[cfg(feature = "test-hooks")] + pub fn pump_liveness(&self) -> std::sync::Weak<()> { self.pump_alive.clone() } @@ -306,16 +324,12 @@ impl CultMeshRudpSubscriptionClient { impl CultMeshRudpSubscriptionClient { /// The explicit shutdown: unsubscribes each live id, waits up to 500 ms for the peer to acknowledge, ends the /// session and joins the pump thread. Returns whether the acknowledgement arrived; `false` says the peer may - /// still hold the subscriptions until its own idle timeout. + /// still hold the subscriptions until its own idle timeout. A reconnect in progress is abandoned at once, and + /// then there is nothing to acknowledge. pub fn close(mut self) -> bool { self.closing.store(true, Ordering::SeqCst); - let (reply, answer) = mpsc::channel(); - let sent = self.commands.send(Command::Close { reply: Some(reply) }).is_ok(); - let acknowledged = sent && answer.recv_timeout(CLOSE_ACK_WAIT * 2).unwrap_or(false); - if let Some(pump) = self.pump.take() { - let _ = pump.join(); - } - acknowledged + let _ = self.commands.send(Command::Close { wait: true }); + self.pump.take().is_some_and(|pump| pump.join().unwrap_or(false)) } } @@ -324,7 +338,7 @@ impl CultMeshRudpSubscriptionClient { impl Drop for CultMeshRudpSubscriptionClient { fn drop(&mut self) { self.closing.store(true, Ordering::SeqCst); - let _ = self.commands.send(Command::Close { reply: None }); + let _ = self.commands.send(Command::Close { wait: false }); if let Some(pump) = self.pump.take() { let _ = pump.join(); } @@ -371,7 +385,7 @@ struct Pump { /// this passes asks afresh. backoff: BTreeMap, /// Held for as long as the pump thread runs; see `pump_liveness`. - #[allow(dead_code)] + #[cfg(feature = "test-hooks")] alive: Arc<()>, /// What `resubscribe_all` resends. The assembler owns what is live; it holds no selections. subscriptions: BTreeMap, @@ -385,23 +399,24 @@ struct Pump { } impl Pump { - fn run(mut self) { + /// Returns whether `close` found every unsubscribe acknowledged; `false` when it was not asked to wait. + fn run(mut self) -> bool { loop { let command = if self.session.is_some() { match self.commands.try_recv() { Ok(command) => Some(command), Err(TryRecvError::Empty) => None, - Err(TryRecvError::Disconnected) => Some(Command::Close { reply: None }), + Err(TryRecvError::Disconnected) => Some(Command::Close { wait: false }), } } else { match self.commands.recv_timeout(Duration::from_secs(3600)) { Ok(command) => Some(command), Err(RecvTimeoutError::Timeout) => None, - Err(RecvTimeoutError::Disconnected) => Some(Command::Close { reply: None }), + Err(RecvTimeoutError::Disconnected) => Some(Command::Close { wait: false }), } }; match command { - Some(Command::Close { reply }) => return self.close(reply), + Some(Command::Close { wait }) => return self.close(wait), Some(command) => self.apply(command), None => self.service(), } @@ -763,29 +778,27 @@ impl Pump { } } - /// Unsubscribes every live id and ends the session. With `reply`, first waits up to `CLOSE_ACK_WAIT` for every - /// outstanding reliable send to be acknowledged (resending a lost one), since nothing resends after the goodbye, - /// and tells whether they all were. - fn close(&mut self, reply: Option>) { + /// Unsubscribes every live id and ends the session. With `wait`, first waits up to `CLOSE_ACK_WAIT` for every + /// outstanding reliable send to be acknowledged (resending a lost one), since nothing resends after the goodbye. + /// Says whether they all were; with no wait, `false`. + fn close(&mut self, wait: bool) -> bool { let ids: Vec<_> = self.subscriptions.keys().cloned().collect(); for id in ids { let message = CultNetMessage::DatabaseUnsubscribe { message_id: self.next_message_id(), subscription_id: id }; self.transmit(&message); } - if reply.is_some() { + if wait { let deadline = Instant::now() + CLOSE_ACK_WAIT; while self.session.is_some() && !self.receipts.is_empty() && Instant::now() < deadline { self.service(); thread::sleep(self.options.poll_interval); } } - let acknowledged = self.session.is_some() && self.receipts.is_empty(); + let acknowledged = wait && self.session.is_some() && self.receipts.is_empty(); if let Some(session) = self.session.as_mut() { let _ = session.disconnect(b"subscription-closed".to_vec()); } - if let Some(reply) = reply { - let _ = reply.send(acknowledged); - } + acknowledged } } diff --git a/packages/cultmesh-rs/tests/rudp_subscription.rs b/packages/cultmesh-rs/tests/rudp_subscription.rs index dde78d97..bdc23809 100644 --- a/packages/cultmesh-rs/tests/rudp_subscription.rs +++ b/packages/cultmesh-rs/tests/rudp_subscription.rs @@ -37,6 +37,8 @@ enum PeerEvent { Refusing, /// A Connect arrived while refusing. ConnectSeen, + /// The client ended the session and said why. + Goodbye(Vec), } /// A peer that accepts RUDP connects on a loopback socket and reports every schema message it receives. @@ -175,6 +177,7 @@ fn serve( reconnect_policy: None, }) .unwrap(); + let mut said_goodbye = false; loop { while let Ok(command) = commands.try_recv() { match command { @@ -206,6 +209,10 @@ fn serve( } } } + if let Some(reason) = session.disconnect_reason().filter(|_| !said_goodbye) { + said_goodbye = true; + let _ = events.send(PeerEvent::Goodbye(reason.to_vec())); + } session.poll_resends().unwrap(); } } @@ -631,9 +638,9 @@ fn dropping_the_client_unsubscribes_each_live_id_and_stops_its_thread() { let started = Instant::now(); assert!(client.close(), "a live peer acknowledges the unsubscribe"); assert!(started.elapsed() < Duration::from_secs(2), "close returns promptly"); + assert!(pump.upgrade().is_none(), "close has joined the pump thread when it returns"); 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"); - assert!(pump.upgrade().is_none(), "the pump thread is gone with its handle"); } #[test] @@ -1254,5 +1261,67 @@ fn drop_sends_an_unsubscribe_for_each_live_id() { .collect(); unsubscribed.sort(); assert_eq!(unsubscribed, ["one", "two"]); + peer.expect(PeerEvent::Goodbye(b"subscription-closed".to_vec())); assert!(peer.received.recv_timeout(Duration::from_millis(300)).is_err(), "nothing else is sent"); } + +#[test] +fn close_returns_when_the_acknowledgement_arrives_and_says_goodbye() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + peer.subscribe_id(); + let started = Instant::now(); + assert!(client.close()); + assert!(started.elapsed() < Duration::from_millis(450), "it does not wait out its 500 ms: {:?}", started.elapsed()); + assert!(matches!(peer.next(), CultNetMessage::DatabaseUnsubscribe { subscription_id, .. } if subscription_id == "sub-1")); + peer.expect(PeerEvent::Goodbye(b"subscription-closed".to_vec())); +} + +#[test] +fn close_reports_false_once_the_session_has_ended() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options_ending_sessions(&peer)).unwrap(); + subscribed(&peer, &client); + peer.disconnect(); + drain_events(&client, 1); + let started = Instant::now(); + assert!(!client.close(), "no peer holds a session whose unsubscribes could be acknowledged"); + assert!(started.elapsed() < Duration::from_millis(300), "{:?}", started.elapsed()); +} + +#[test] +fn draining_releases_the_weight_of_every_document_in_an_event() { + let peer = Peer::start(); + let mut options = options(&peer); + options.max_undrained = 3; + let client = CultMeshRudpSubscriptionClient::connect(options).unwrap(); + subscribed(&peer, &client); + // A two-change commit weighs two. If draining released one per event, each round would leave one more + // counted and the third would pass the bound of three. + for round in 0..4 { + peer.send(&change_part(&format!("a{round}"), "sub-1", &format!("c{round}"))); + peer.send(&change_part(&format!("b{round}"), "sub-1", &format!("c{round}"))); + assert_eq!(keys(&drain_events(&client, 1)[0]), ["k", "k"], "round {round}"); + } +} + +#[test] +fn a_refused_subscribe_is_a_fault_while_a_catalog_request_is_in_flight() { + let peer = Peer::start(); + let client = CultMeshRudpSubscriptionClient::connect(options(&peer)).unwrap(); + client.subscribe("sub-1", vector_selection()).unwrap(); + client.subscribe("sub-2", vector_selection()).unwrap(); + let mut ids = [peer.subscribe_id(), peer.subscribe_id()]; + ids.sort_by(|a, b| a.1.cmp(&b.1)); + peer.send(&snapshot_answering(&ids[0].0)); + let (request_id, _) = catalog_request(&peer); // in flight, not yet answered + peer.send(&CultNetMessage::ErrorV1 { error: "x".into(), code: None, details: None, message_id: Some(ids[1].0.clone()) }); + // The fault queues behind the snapshot that waits for its rows. + quiet(&client); + 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 == "sub-1"), "{events:?}"); + assert_eq!(faulted(&events[1]), "CultNet subscription 'sub-2' was refused by the peer."); +} -- 2.47.3 From 00200222e3d37858eff8c6bfcba2dbde9190a715 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 13:23:08 +0100 Subject: [PATCH 5/5] cultmesh-rs: the pump's liveness guard is _alive, so test-hooks builds don't warn it is never read Closes cultlib-gaps:finding:cut-rs-subscribe-members.s4.alive-dead-code-warning. Co-Authored-By: Claude Opus 5.5 --- packages/cultmesh-rs/src/rudp_subscription.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/cultmesh-rs/src/rudp_subscription.rs b/packages/cultmesh-rs/src/rudp_subscription.rs index 4ba6dc50..1cda8563 100644 --- a/packages/cultmesh-rs/src/rudp_subscription.rs +++ b/packages/cultmesh-rs/src/rudp_subscription.rs @@ -257,7 +257,7 @@ impl CultMeshRudpSubscriptionClient { awaiting: Vec::new(), backoff: BTreeMap::new(), #[cfg(feature = "test-hooks")] - alive, + _alive: alive, subscriptions: BTreeMap::new(), receipts: Vec::new(), epoch: super::fresh_rudp_connection_epoch(), @@ -386,7 +386,7 @@ struct Pump { backoff: BTreeMap, /// Held for as long as the pump thread runs; see `pump_liveness`. #[cfg(feature = "test-hooks")] - alive: Arc<()>, + _alive: Arc<()>, /// What `resubscribe_all` resends. The assembler owns what is live; it holds no selections. subscriptions: BTreeMap, receipts: Vec, -- 2.47.3