serial-mcp 0.7.2

MCP server for serial port communication. 22 tools (list/open/read/write/subscribe/get_status/reconfigure/list_profiles/open_profile/save_profile/delete_profile/get_log/clear_log/export_log/reconnect/...), resources, prompts, task cancellation, stdio + streamable-HTTP transports.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
//! Per-connection RX session core for unified serial data fanout.
//!
//! Each open serial connection can have at most one [`RxSession`], which owns
//! a single background pump task that reads from the serial port. The pump
//! fans out received bytes to registered consumer channels.
//!
//! PLAN 1a scope:
//! - `RxSessionManager` / `RxSession` lifecycle
//! - one pump task per connection
//! - consumer registration (blocking + streaming primitives)
//! - deterministic shutdown on connection close
//!
//! Not yet in scope:
//! - migrating `read` / `subscribe` / `wait_for` tools onto this core
//! - buffer budgets, silence timeouts, event-context
//!
//! ## Consumer drop policy
//!
//! When the pump calls [`ConsumerRegistry::fanout`], any consumer whose
//! channel is full (slow consumer) or closed (dropped receiver) is silently
//! removed from the registry via `Vec::retain`. This prevents the pump from
//! blocking or buffering indefinitely for lagging consumers.
//!
//! This policy is intentionally simple for PLAN 1a. PLAN 1b/1c must define
//! explicit per-consumer behavior (e.g. backpressure signaling, structured
//! error delivery, or consumer-aware buffer budgets) before migrating the
//! `read` and `subscribe` tools onto this core.

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;

use tokio::sync::mpsc;
use tokio::sync::Mutex as AsyncMutex;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info};

use crate::serial::SerialConnection;

// ---- Events pumped to consumers -------------------------------------------

/// A chunk of data or a lifecycle event pushed to each consumer.
#[derive(Debug)]
pub enum RxEvent {
    Data(Vec<u8>),
    Closed,
    Error(String),
}

impl Clone for RxEvent {
    fn clone(&self) -> Self {
        match self {
            RxEvent::Data(bytes) => RxEvent::Data(bytes.clone()),
            RxEvent::Closed => RxEvent::Closed,
            RxEvent::Error(msg) => RxEvent::Error(msg.clone()),
        }
    }
}

// ---- Consumer channel wrapper ---------------------------------------------

/// A registered consumer that receives [`RxEvent`]s through an mpsc channel.
pub struct RxConsumer {
    tx: mpsc::Sender<RxEvent>,
}

impl RxConsumer {
    fn new(capacity: usize) -> (Self, mpsc::Receiver<RxEvent>) {
        let (tx, rx) = mpsc::channel(capacity);
        (Self { tx }, rx)
    }

    fn try_send(&self, event: RxEvent) -> bool {
        self.tx.try_send(event).is_ok()
    }
}

// ---- Shared consumer registry for pump access -----------------------------

/// Consumer lists shared between `RxSession` and the pump task.
///
/// The pump reads from `connection.read()` and fans out chunks to all
/// registered consumers via `try_send`. Consumers whose channels are full
/// (slow consumer) or closed (dropped receiver) are silently removed from
/// the registry by `retain()`. This is the explicit consumer-drop policy
/// for PLAN 1a; see module-level docs for details.
struct ConsumerRegistry {
    blocking: Vec<RxConsumer>,
    streaming: Vec<RxConsumer>,
}

impl ConsumerRegistry {
    fn new() -> Self {
        Self {
            blocking: Vec::new(),
            streaming: Vec::new(),
        }
    }

    /// Fan out an event to all registered consumers.
    ///
    /// Consumers whose channels are full or closed are silently removed.
    /// This never blocks — `try_send` is used for every consumer.
    fn fanout(&mut self, event: RxEvent) {
        self.blocking.retain(|c| c.try_send(event.clone()));
        self.streaming.retain(|c| c.try_send(event.clone()));
    }

    fn prune_closed(&mut self) {
        self.blocking.retain(|c| !c.tx.is_closed());
        self.streaming.retain(|c| !c.tx.is_closed());
    }

    fn is_empty(&self) -> bool {
        self.blocking.is_empty() && self.streaming.is_empty()
    }
}

// ---- Per-connection session ------------------------------------------------

/// Manages one pump task and its registered consumers for a single connection.
///
/// The pump task holds an `Arc<StdMutex<ConsumerRegistry>>` so it can
/// fan out data without needing a reference back to this struct.
pub struct RxSession {
    connection_id: String,
    connection: Arc<SerialConnection>,
    consumers: Arc<StdMutex<ConsumerRegistry>>,
    pump_task: StdMutex<Option<JoinHandle<()>>>,
    pump_token: StdMutex<CancellationToken>,
}

impl RxSession {
    const PUMP_READ_SIZE: usize = 4096;
    const CONSUMER_CHANNEL_CAPACITY: usize = 256;

    pub fn new(connection: Arc<SerialConnection>) -> Self {
        let connection_id = connection.id().to_string();
        Self {
            connection_id,
            connection,
            consumers: Arc::new(StdMutex::new(ConsumerRegistry::new())),
            pump_task: StdMutex::new(None),
            pump_token: StdMutex::new(CancellationToken::new()),
        }
    }

    pub fn connection_id(&self) -> &str {
        &self.connection_id
    }

    /// Ensure the pump task is running. Idempotent.
    pub(crate) fn ensure_pump_running(&self) {
        let mut task_slot = self.pump_task.lock().expect("pump_task mutex poisoned");
        if let Some(handle) = task_slot.take() {
            if handle.is_finished() {
                debug!(
                    "rx_session: previous pump for {} finished, restarting",
                    self.connection_id
                );
            } else {
                *task_slot = Some(handle);
                return;
            }
        }
        // If the previous pump was cancelled (e.g., via prune_consumers),
        // the token is stale. Replace with a fresh one.
        {
            let mut token = self.pump_token.lock().expect("pump_token mutex poisoned");
            if token.is_cancelled() {
                *token = CancellationToken::new();
            }
        }
        let connection = Arc::clone(&self.connection);
        let token = self
            .pump_token
            .lock()
            .expect("pump_token mutex poisoned")
            .clone();
        let consumers = Arc::clone(&self.consumers);
        let handle = tokio::spawn(pump_loop(connection, token, consumers));
        *task_slot = Some(handle);
        debug!("rx_session: pump started for {}", self.connection_id);
    }

    /// Register a new blocking consumer and return its receiver.
    ///
    /// The consumer will only see bytes that arrive *after* registration.
    /// Starts the pump if not already running.
    pub fn register_blocking(&self) -> mpsc::Receiver<RxEvent> {
        let (consumer, rx) = RxConsumer::new(Self::CONSUMER_CHANNEL_CAPACITY);
        self.consumers
            .lock()
            .expect("consumers mutex poisoned")
            .blocking
            .push(consumer);
        debug!(
            "rx_session: blocking consumer registered for {}",
            self.connection_id
        );
        self.ensure_pump_running();
        rx
    }

    /// Register a new streaming consumer and return its receiver.
    ///
    /// Same future-only semantics as [`Self::register_blocking`].
    pub fn register_streaming(&self) -> mpsc::Receiver<RxEvent> {
        let (consumer, rx) = RxConsumer::new(Self::CONSUMER_CHANNEL_CAPACITY);
        self.consumers
            .lock()
            .expect("consumers mutex poisoned")
            .streaming
            .push(consumer);
        debug!(
            "rx_session: streaming consumer registered for {}",
            self.connection_id
        );
        self.ensure_pump_running();
        rx
    }

    /// Prune consumers whose receivers have been dropped, and if no
    /// consumers remain, cancel the pump token so it exits promptly.
    ///
    /// Returns `true` if the pump was cancelled because no consumers remain.
    /// In that case the caller should [`Self::join_pump`] to await the pump's
    /// exit before touching the serial port, otherwise a still-running pump
    /// can read (and discard) bytes that later read/wait_for tools need.
    ///
    /// Call this after removing a stream handle (e.g., unsubscribe) so
    /// the pump does not keep reading serial data that other direct-read
    /// tools (read, wait_for) need. Until PLAN 1c/1d migrate those tools
    /// onto RxSession, this avoids RX data starvation.
    pub fn prune_consumers(&self) -> bool {
        let mut reg = self.consumers.lock().expect("consumers mutex poisoned");
        reg.prune_closed();
        if reg.is_empty() {
            self.pump_token
                .lock()
                .expect("pump_token mutex poisoned")
                .cancel();
            debug!(
                "rx_session: pump cancelled for {} (no consumers after prune)",
                self.connection_id
            );
            true
        } else {
            false
        }
    }

    /// Signal the pump to stop and notify all consumers with [`RxEvent::Closed`].
    ///
    /// This only cancels the pump token — it does **not** wait for the pump
    /// task to finish. Call [`Self::join_pump`] after shutdown to await
    /// pump exit. Safe to call multiple times.
    pub fn shutdown(&self) {
        self.pump_token
            .lock()
            .expect("pump_token mutex poisoned")
            .cancel();
        self.consumers
            .lock()
            .expect("consumers mutex poisoned")
            .fanout(RxEvent::Closed);
        info!("rx_session: shut down for {}", self.connection_id);
    }

    /// Wait for the pump task to finish. Call after `shutdown` for
    /// deterministic cleanup.
    pub async fn join_pump(&self) {
        let handle = self
            .pump_task
            .lock()
            .expect("pump_task mutex poisoned")
            .take();
        if let Some(h) = handle {
            let _ = h.await;
        }
    }

    /// Shut down and await pump exit in one step.
    pub async fn shutdown_and_join(&self) {
        self.shutdown();
        self.join_pump().await;
    }
}

// ---- Pump loop (standalone async function, not a method) -------------------

async fn pump_loop(
    connection: Arc<SerialConnection>,
    token: CancellationToken,
    consumers: Arc<StdMutex<ConsumerRegistry>>,
) {
    let conn_id = connection.id().to_string();
    let mut buf = vec![0u8; RxSession::PUMP_READ_SIZE];
    info!("rx_session: pump entered for {conn_id}");

    loop {
        if token.is_cancelled() {
            break;
        }
        let read_result = tokio::select! {
            _ = token.cancelled() => break,
            res = connection.read(&mut buf, Some(100)) => res,
        };
        match read_result {
            Ok(0) | Err(crate::error::SerialError::ReadTimeout) => {
                let mut reg = consumers.lock().expect("consumers mutex poisoned");
                reg.prune_closed();
                if reg.is_empty() {
                    info!("rx_session: pump for {conn_id} exiting (no consumers)");
                    break;
                }
                continue;
            }
            Ok(n) => {
                connection.log().rx_data(n);
                let chunk = buf[..n].to_vec();
                let mut reg = consumers.lock().expect("consumers mutex poisoned");
                reg.fanout(RxEvent::Data(chunk));
                if reg.is_empty() {
                    info!("rx_session: pump for {conn_id} exiting (no consumers)");
                    break;
                }
            }
            Err(e) => {
                error!("rx_session: read error on {conn_id}: {e}");
                // Detect fatal disconnects and update connection state.
                let is_fatal = if let crate::error::SerialError::IoError(ref io_err) = e {
                    crate::serial::is_fatal_disconnect(io_err)
                } else {
                    false
                };
                if is_fatal {
                    connection
                        .mark_disconnected(format!("Read error: {e}"))
                        .await;
                    // Do NOT fanout RxEvent::Error — consumers survive
                    // the disconnect and resume after reconnect.
                    // The read/subscribe loops check connection state
                    // and pause their timeouts during Disconnected.
                } else {
                    consumers
                        .lock()
                        .expect("consumers mutex poisoned")
                        .fanout(RxEvent::Error(e.to_string()));
                }
                break;
            }
        }
    }

    info!("rx_session: pump exiting for {conn_id}");
}

// ---- Session manager -------------------------------------------------------

/// Manages [`RxSession`] instances keyed by connection id.
///
/// One session per connection. Creating a session is idempotent. Removing a
/// session shuts down its pump, awaits pump task exit, and drops consumers
/// deterministically.
pub struct RxSessionManager {
    sessions: AsyncMutex<HashMap<String, Arc<RxSession>>>,
}

impl Default for RxSessionManager {
    fn default() -> Self {
        Self::new()
    }
}

impl RxSessionManager {
    pub fn new() -> Self {
        Self {
            sessions: AsyncMutex::new(HashMap::new()),
        }
    }

    /// Get an existing session or create one for the given connection.
    ///
    /// Returns the existing session if one is already registered for this
    /// connection id, ensuring idempotent creation.
    pub async fn get_or_create(&self, connection: Arc<SerialConnection>) -> Arc<RxSession> {
        let conn_id = connection.id().to_string();
        let mut sessions = self.sessions.lock().await;
        if let Some(existing) = sessions.get(&conn_id) {
            return Arc::clone(existing);
        }
        let session = Arc::new(RxSession::new(connection));
        sessions.insert(conn_id, Arc::clone(&session));
        debug!(
            "rx_session: created new session for connection {}",
            session.connection_id()
        );
        session
    }

    /// Remove and shut down a session by connection id.
    ///
    /// Cancels the pump, sends [`RxEvent::Closed`] to consumers, and awaits
    /// pump task exit. Does nothing if no session exists for the given id.
    pub async fn remove(&self, connection_id: &str) {
        let session = {
            let mut sessions = self.sessions.lock().await;
            sessions.remove(connection_id)
        };
        if let Some(session) = session {
            session.shutdown_and_join().await;
            info!("rx_session: removed session for connection {connection_id}");
        }
    }

    /// Number of active sessions.
    pub async fn count(&self) -> usize {
        self.sessions.lock().await.len()
    }

    /// Look up an existing session by connection id, if one exists.
    pub async fn get(&self, connection_id: &str) -> Option<Arc<RxSession>> {
        self.sessions.lock().await.get(connection_id).cloned()
    }
}

// ---- Tests -----------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::serial::test_support::loopback_connection;
    use std::time::Duration;
    use tokio::io::AsyncWriteExt;

    fn collect_events(rx: &mut mpsc::Receiver<RxEvent>) -> Vec<RxEvent> {
        let mut events = Vec::new();
        while let Ok(event) = rx.try_recv() {
            events.push(event);
        }
        events
    }

    #[test]
    fn rx_event_clone_copies_data() {
        let event = RxEvent::Data(b"hello".to_vec());
        let cloned = event.clone();
        assert!(matches!(cloned, RxEvent::Data(ref b) if b == b"hello"));
    }

    #[tokio::test]
    async fn manager_get_or_create_returns_same_session() {
        let (conn, _peer) = loopback_connection("test-idem");
        let conn = Arc::new(conn);
        let mgr = RxSessionManager::new();
        let s1 = mgr.get_or_create(Arc::clone(&conn)).await;
        let s2 = mgr.get_or_create(Arc::clone(&conn)).await;
        assert!(Arc::ptr_eq(&s1, &s2));
        assert_eq!(mgr.count().await, 1);
    }

    #[tokio::test]
    async fn manager_remove_awaits_pump_exit() {
        let (conn, _peer) = loopback_connection("test-remove-await");
        let conn = Arc::new(conn);
        let mgr = RxSessionManager::new();
        let session = mgr.get_or_create(Arc::clone(&conn)).await;
        let id = session.connection_id().to_string();
        let _rx = session.register_blocking();
        assert!(!session
            .pump_token
            .lock()
            .expect("pump_token")
            .is_cancelled());
        mgr.remove(&id).await;
        assert_eq!(mgr.count().await, 0);
        assert!(session
            .pump_token
            .lock()
            .expect("pump_token")
            .is_cancelled());
        assert!(
            session.pump_task.lock().expect("pump_task").is_none(),
            "pump task handle should be consumed after join"
        );
    }

    #[tokio::test]
    async fn manager_remove_nonexistent_is_noop() {
        let mgr = RxSessionManager::new();
        mgr.remove("does-not-exist").await;
        assert_eq!(mgr.count().await, 0);
    }

    #[tokio::test]
    async fn session_register_blocking_starts_pump() {
        let (conn, _peer) = loopback_connection("test-pump-start");
        let conn = Arc::new(conn);
        let session = RxSession::new(conn);
        assert!(session.pump_task.lock().expect("pump_task").is_none());
        let _rx = session.register_blocking();
        assert!(session.pump_task.lock().expect("pump_task").is_some());
    }

    #[tokio::test]
    async fn session_shutdown_cancels_pump_token() {
        let (conn, _peer) = loopback_connection("test-shutdown");
        let conn = Arc::new(conn);
        let session = RxSession::new(conn);
        let _rx = session.register_blocking();
        assert!(!session
            .pump_token
            .lock()
            .expect("pump_token")
            .is_cancelled());
        session.shutdown();
        assert!(session
            .pump_token
            .lock()
            .expect("pump_token")
            .is_cancelled());
    }

    #[tokio::test]
    async fn consumer_receives_data_after_registration() {
        let (conn, mut peer) = loopback_connection("test-fanout-data");
        let conn = Arc::new(conn);
        let session = RxSession::new(Arc::clone(&conn));

        let mut rx = session.register_blocking();

        peer.write_all(b"hello").await.unwrap();

        tokio::time::sleep(Duration::from_millis(300)).await;
        session.shutdown();

        let received = collect_events(&mut rx);
        let has_data = received.iter().any(|e| matches!(e, RxEvent::Data(_)));
        assert!(
            has_data,
            "consumer should have received at least one Data event"
        );
    }

    #[tokio::test]
    async fn two_consumers_both_receive_future_data() {
        let (conn, mut peer) = loopback_connection("test-two-consumers");
        let conn = Arc::new(conn);
        let session = RxSession::new(Arc::clone(&conn));

        let mut rx1 = session.register_blocking();
        let mut rx2 = session.register_streaming();

        peer.write_all(b"abc").await.unwrap();

        tokio::time::sleep(Duration::from_millis(300)).await;
        session.shutdown();

        let events1 = collect_events(&mut rx1);
        let events2 = collect_events(&mut rx2);

        let has_data1 = events1.iter().any(|e| matches!(e, RxEvent::Data(_)));
        let has_data2 = events2.iter().any(|e| matches!(e, RxEvent::Data(_)));
        assert!(has_data1, "blocking consumer should have received data");
        assert!(has_data2, "streaming consumer should have received data");
    }

    #[tokio::test]
    async fn removing_session_awaits_pump_and_drops_consumers() {
        let (conn, _peer) = loopback_connection("test-remove-lifecycle");
        let conn = Arc::new(conn);
        let mgr = RxSessionManager::new();
        let session = mgr.get_or_create(Arc::clone(&conn)).await;
        let conn_id = session.connection_id().to_string();
        let _rx = session.register_blocking();
        assert!(!session
            .pump_token
            .lock()
            .expect("pump_token")
            .is_cancelled());
        mgr.remove(&conn_id).await;
        assert!(session
            .pump_token
            .lock()
            .expect("pump_token")
            .is_cancelled());
        assert_eq!(mgr.count().await, 0);
        assert!(
            session.pump_task.lock().expect("pump_task").is_none(),
            "pump handle should be consumed after remove"
        );
    }

    #[tokio::test]
    async fn connection_close_causes_pump_exit() {
        let (conn, mut peer) = loopback_connection("test-close-exit");
        let conn = Arc::new(conn);
        let session = RxSession::new(Arc::clone(&conn));
        let mut rx = session.register_blocking();

        peer.write_all(b"bye").await.unwrap();
        tokio::time::sleep(Duration::from_millis(100)).await;
        conn.close().await.unwrap();

        tokio::time::sleep(Duration::from_millis(300)).await;

        let events = collect_events(&mut rx);
        let has_closed_or_error = events
            .iter()
            .any(|e| matches!(e, RxEvent::Closed | RxEvent::Error(_)));
        assert!(
            has_closed_or_error,
            "consumer should receive Closed or Error event when connection closes"
        );
    }

    #[tokio::test]
    async fn pump_exits_cleanly_on_shutdown_without_hanging() {
        let (conn, _peer) = loopback_connection("test-pump-clean-exit");
        let conn = Arc::new(conn);
        let session = RxSession::new(Arc::clone(&conn));
        let _rx = session.register_blocking();

        session.shutdown_and_join().await;

        assert!(
            session.pump_task.lock().expect("pump_task").is_none(),
            "pump task handle should be consumed after join"
        );
    }

    #[tokio::test]
    async fn no_consumers_means_no_pump() {
        let (conn, _peer) = loopback_connection("test-no-pump");
        let conn = Arc::new(conn);
        let session = RxSession::new(conn);
        assert!(session.pump_task.lock().expect("pump_task").is_none());
    }

    #[tokio::test]
    async fn shutdown_is_idempotent() {
        let (conn, _peer) = loopback_connection("test-shutdown-idem");
        let conn = Arc::new(conn);
        let session = RxSession::new(conn);
        let mut rx = session.register_blocking();
        session.shutdown();
        session.shutdown();
        session.shutdown();
        assert!(session
            .pump_token
            .lock()
            .expect("pump_token")
            .is_cancelled());
        let events = collect_events(&mut rx);
        let closed_count = events
            .iter()
            .filter(|e| matches!(e, RxEvent::Closed))
            .count();
        assert!(closed_count >= 1, "at least one Closed event expected");
    }

    #[tokio::test]
    async fn repeated_create_remove_no_leaked_pump_tasks() {
        let iterations = 10;
        for i in 0..iterations {
            let port_name = format!("test-stress-{i}");
            let (conn, _peer) = loopback_connection(&port_name);
            let conn = Arc::new(conn);
            let mgr = RxSessionManager::new();
            let session = mgr.get_or_create(Arc::clone(&conn)).await;
            let conn_id = session.connection_id().to_string();
            let _rx = session.register_blocking();

            // Verify pump is running
            assert!(
                session.pump_task.lock().expect("pump_task").is_some(),
                "pump should be running on iteration {i}"
            );

            mgr.remove(&conn_id).await;

            // Verify pump task handle was consumed
            assert!(
                session.pump_task.lock().expect("pump_task").is_none(),
                "pump handle should be consumed after remove on iteration {i}"
            );
            assert!(
                session
                    .pump_token
                    .lock()
                    .expect("pump_token")
                    .is_cancelled(),
                "pump token should be cancelled after remove on iteration {i}"
            );
            assert_eq!(mgr.count().await, 0);
        }
    }

    #[tokio::test]
    async fn full_consumer_is_dropped_from_registry() {
        let (conn, mut peer) = loopback_connection("test-full-consumer");
        let conn = Arc::new(conn);
        let session = RxSession::new(Arc::clone(&conn));

        // Register a consumer with a tiny channel capacity to force overflow.
        // We'll use the normal register path but just not drain the receiver.
        let mut rx = session.register_blocking();

        // Send enough data to exceed the channel capacity (256 events).
        // Each byte chunk becomes a Data event, so send many small writes.
        for _ in 0..300 {
            peer.write_all(b"x").await.unwrap();
            // Small sleep to let the pump process each chunk
            tokio::time::sleep(Duration::from_millis(2)).await;
        }

        tokio::time::sleep(Duration::from_millis(200)).await;
        session.shutdown();

        // Consumer was dropped from registry when its channel filled up.
        // The receiver should still work for whatever was buffered, but the
        // key behavior is: the pump did NOT hang or panic.
        let events = collect_events(&mut rx);
        // We got *some* data before being dropped, and may or may not get Closed
        // (since the consumer may have been removed from registry before shutdown).
        assert!(
            !events.is_empty(),
            "should have received some events before consumer was dropped"
        );
    }

    #[tokio::test]
    async fn dropped_receiver_removed_from_registry() {
        let (conn, _peer) = loopback_connection("test-dropped-receiver");
        let conn = Arc::new(conn);
        let session = RxSession::new(Arc::clone(&conn));

        // Register a consumer, then drop the receiver.
        let rx = session.register_blocking();
        let consumer_count_before = {
            let registry = session.consumers.lock().expect("consumers");
            registry.blocking.len() + registry.streaming.len()
        };
        assert_eq!(consumer_count_before, 1);

        drop(rx);

        // Send data — pump will try to fanout, find the consumer's channel
        // closed, and remove it via retain().
        // We need to trigger a read from the port. Since no peer writes data,
        // the pump won't get any Data events. Instead, trigger via shutdown.
        session.shutdown();

        let consumer_count_after = {
            let registry = session.consumers.lock().expect("consumers");
            registry.blocking.len() + registry.streaming.len()
        };
        assert_eq!(
            consumer_count_after, 0,
            "dropped receiver should be removed from registry after fanout attempt"
        );
    }
}