serial-mcp 0.9.3

MCP server for serial port communication. 25 tools (list/open/read/write/transact/capture_boot/get_status/reconfigure/list_profiles/open_profile/save_profile/delete_profile/configure/rollback_profile/get_log/clear_log/export_log/reconnect/compute_checksum/...), 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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
//! Per-connection RX session core for unified serial data capture.
//!
//! Each open serial connection has at most one [`RxSession`], which owns
//! a single background pump task that reads from the serial port. The pump
//! appends every received byte to a per-connection `RxRing`.
//!
//! The pump runs from `open` to `close` — bytes are captured regardless of
//! active tool calls. The ring is a budgeted allocation charged at open and
//! released at close.
//!
//! `read` reads from the ring via private or shared cursors. `read` advances a
//! shared cursor; a private cursor mode does not move the shared read cursor.
//!
//! - always-on pump from open to close
//! - RxRing capture (all bytes preserved)
//! - budget reservation for the ring at construction
//! - pause on disconnect, resume on reconnect (same ring, same offsets)

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

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

use crate::buffer_budget::{BufferBudget, BufferReservation};
use crate::resource_events::ResourceEventHub;
use crate::rx_ring::RxRing;
use crate::serial::SerialConnection;

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

/// Manages one pump task, RX ring, and shared read cursor for one connection.
///
/// The `RxRing` captures all RX bytes from open to close. The pump appends
/// to the ring. `read` reads from the ring via cursors.
pub struct RxSession {
    connection_id: String,
    connection: Arc<SerialConnection>,
    pump_task: StdMutex<Option<JoinHandle<()>>>,
    pump_token: StdMutex<CancellationToken>,
    /// Async pump gate: the pump holds this across one complete
    /// read + ring append. `capture_boot` acquires the same gate so its mark
    /// cannot race an in-flight pump read/append — a byte physically read
    /// before the reset can never append after the mark.
    pump_gate: Arc<AsyncMutex<()>>,
    /// Per-connection ring buffer capturing all RX bytes from open to close.
    ring: Arc<RxRing>,
    /// Process-wide resource event hub. The pump publishes connection
    /// detail/raw/log updates AFTER each successful ring append (outside the
    /// pump gate) so a listener woken by the event observes the new bytes.
    hub: Arc<ResourceEventHub>,
    /// Shared read cursor for `read`/`flush`. Absolute u64 offset.
    read_cursor: StdMutex<u64>,
    /// Stored ring capacity so close can release the correct byte count.
    ring_capacity: usize,
    /// RAII reservation for the ring's budget allocation. Dropped at shutdown.
    budget_reservation: StdMutex<Option<Box<dyn BufferReservation>>>,
}

impl RxSession {
    const PUMP_READ_SIZE: usize = 4096;

    /// Create a new RxSession with a budgeted ring buffer.
    ///
    /// The ring captures `ring_capacity` bytes of RX history. Bytes are
    /// charged against `budget` and released at [`shutdown_and_join`](Self::shutdown_and_join).
    ///
    /// Returns `Err` if `ring_capacity` is 0 or the budget cannot be reserved.
    pub fn new(
        connection: Arc<SerialConnection>,
        ring_capacity: usize,
        budget: &Arc<dyn BufferBudget>,
        hub: Arc<ResourceEventHub>,
    ) -> Result<Self, String> {
        if ring_capacity == 0 {
            return Err(format!(
                "open.rx_buffer_size: ring_capacity must be > 0, got {ring_capacity}"
            ));
        }
        let reservation = budget
            .try_reserve(ring_capacity)
            .map_err(|e| crate::tools::helpers::map_budget_err("open.rx_buffer_size", e))?;
        let connection_id = connection.id().to_string();
        Ok(Self {
            connection_id,
            connection,
            pump_task: StdMutex::new(None),
            pump_token: StdMutex::new(CancellationToken::new()),
            pump_gate: Arc::new(AsyncMutex::new(())),
            ring: Arc::new(RxRing::new(ring_capacity)),
            hub,
            read_cursor: StdMutex::new(0),
            ring_capacity,
            budget_reservation: StdMutex::new(Some(reservation)),
        })
    }

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

    // ── Ring + cursor accessors ─────────────────────────────────────────────

    /// Borrow the ring buffer.
    pub(crate) fn ring(&self) -> &RxRing {
        &self.ring
    }

    /// Current shared read cursor (absolute u64 offset).
    pub(crate) fn read_cursor(&self) -> u64 {
        *self.read_cursor.lock().expect("read_cursor mutex poisoned")
    }

    /// Set the shared read cursor.
    pub(crate) fn set_read_cursor(&self, off: u64) {
        *self.read_cursor.lock().expect("read_cursor mutex poisoned") = off;
    }

    /// Ring capacity in bytes.
    pub(crate) fn ring_capacity(&self) -> usize {
        self.ring_capacity
    }

    /// Acquire the pump gate: waits for any in-flight pump
    /// read+append to finish, then blocks the pump from reading again until
    /// the returned guard is dropped. `capture_boot` holds this across the
    /// OS-input purge, the live-edge mark, and the reset-line assertion so
    /// bytes predating the mark can never be appended after it.
    pub(crate) async fn pump_gate_guard(&self) -> tokio::sync::MutexGuard<'_, ()> {
        self.pump_gate.lock().await
    }

    /// Ensure the pump task is running. Idempotent.
    ///
    /// Called once at open (via `get_or_create`) and on reconnect. Under the
    /// always-on model the pump is started at open and runs until close;
    /// this method is a no-op if already running and restarts if the previous
    /// pump finished (e.g. after a fatal non-disconnect error).
    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, the token is stale. Replace.
        {
            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 ring = Arc::clone(&self.ring);
        let pump_gate = Arc::clone(&self.pump_gate);
        let hub = Arc::clone(&self.hub);
        let handle = tokio::spawn(pump_loop(connection, token, ring, pump_gate, hub));
        *task_slot = Some(handle);
        debug!("rx_session: pump started for {}", self.connection_id);
    }

    /// Signal the pump to stop.
    ///
    /// 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();
        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, then release the ring
    /// budget reservation.
    pub async fn shutdown_and_join(&self) {
        self.shutdown();
        self.join_pump().await;
        // Release the ring's budget reservation so bytes are available
        // for the next open.
        let reservation = self
            .budget_reservation
            .lock()
            .expect("budget_reservation mutex poisoned")
            .take();
        drop(reservation);
        debug!(
            "rx_session: budget released for {} ({} bytes)",
            self.connection_id, self.ring_capacity
        );
    }
}

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

/// Background task that reads from the serial port and appends to the ring.
///
/// Runs from open to close. On fatal disconnect, pauses (50ms sleep loop)
/// until the connection state returns to `Open` (reconnect succeeded) or
/// `Closed` (reconnect exhausted/disabled). The ring persists across
/// disconnect/reconnect cycles — `end_offset` is monotonic.
///
/// The pump holds `pump_gate` across one complete read + ring append and
/// releases it before the disconnect pause/sleep. `capture_boot` acquires
/// the same gate to establish an atomic live-edge mark: a byte
/// physically read before the mark can never be appended after it.
///
/// After a successful `ring.append`, the gate is released and the pump
/// synchronously publishes the connection detail/raw/log resource hints —
/// AFTER the append and OUTSIDE the gate, so a listener woken by the event
/// immediately observes the advanced ring end offset and the gate invariants
/// (`capture_boot` atomicity) stay untouched. Publication never awaits:
/// notifications are availability hints, not a byte ledger.
async fn pump_loop(
    connection: Arc<SerialConnection>,
    token: CancellationToken,
    ring: Arc<RxRing>,
    pump_gate: Arc<AsyncMutex<()>>,
    hub: Arc<ResourceEventHub>,
) {
    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;
        }
        // Gate held across the read AND the ring append: this is the
        // atomic unit capture_boot waits on.
        let gate = pump_gate.lock().await;
        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) => {
                // No data this cycle. Keep running.
                drop(gate);
                continue;
            }
            Ok(n) => {
                connection.log().rx_data(n);
                let chunk = buf[..n].to_vec();

                // Append to the ring (capture all bytes).
                ring.append(&chunk);
                drop(gate);
                // Publish AFTER the append and OUTSIDE the gate: a listener
                // woken by these hints must be able to observe the new ring
                // end offset immediately. Synchronous, never awaited.
                hub.publish_connection_changed(&conn_id);
            }
            Err(e) => {
                error!("rx_session: read error on {conn_id}: {e}");
                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;
                    // Release the gate before the pause/sleep loop so
                    // capture_boot cannot block behind a paused pump.
                    drop(gate);
                    // Pause: wait for reconnect or close. The ring persists
                    // across disconnect/reconnect — offsets stay monotonic.
                    let pause_start = std::time::Instant::now();
                    debug!("rx_session: pump for {conn_id} pausing (disconnected)");
                    loop {
                        if token.is_cancelled() {
                            info!(
                                "rx_session: pump for {conn_id} exiting during pause (cancelled)"
                            );
                            return;
                        }
                        let state = connection.state();
                        match state {
                            crate::serial::ConnectionState::Open => {
                                info!(
                                    "rx_session: pump for {conn_id} resumed after {:.0?}",
                                    pause_start.elapsed()
                                );
                                break; // resume the outer read loop
                            }
                            crate::serial::ConnectionState::Closed => {
                                info!(
                                    "rx_session: pump for {conn_id} exiting (connection closed during pause)"
                                );
                                return;
                            }
                            _ => {
                                // Disconnected or Reconnecting — keep waiting.
                                tokio::time::sleep(Duration::from_millis(50)).await;
                            }
                        }
                    }
                    // Resume reading from the (now reopened) connection.
                    // The ring's end_offset is where we left off.
                    continue;
                }

                // Non-fatal error: pump exits.
                error!("rx_session: non-fatal read error on {conn_id}, pump exiting: {e}");
                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 releases the ring
/// budget.
pub struct RxSessionManager {
    sessions: AsyncMutex<HashMap<String, Arc<RxSession>>>,
    budget: Arc<dyn BufferBudget>,
    hub: Arc<ResourceEventHub>,
}

impl RxSessionManager {
    pub fn new(budget: Arc<dyn BufferBudget>, hub: Arc<ResourceEventHub>) -> Self {
        Self {
            sessions: AsyncMutex::new(HashMap::new()),
            budget,
            hub,
        }
    }

    /// Get an existing session or create one for the given connection.
    ///
    /// The session is created with a budgeted ring of `ring_capacity` bytes.
    /// The pump is started automatically on first creation. Returns the
    /// existing session if one is already registered (ring_capacity is
    /// ignored in that case — the ring was already allocated at open time).
    ///
    /// Returns `Err(String)` if ring budget reservation fails.
    pub async fn get_or_create(
        &self,
        connection: Arc<SerialConnection>,
        ring_capacity: usize,
    ) -> Result<Arc<RxSession>, String> {
        let conn_id = connection.id().to_string();
        let mut sessions = self.sessions.lock().await;
        if let Some(existing) = sessions.get(&conn_id) {
            return Ok(Arc::clone(existing));
        }
        let session = Arc::new(RxSession::new(
            connection,
            ring_capacity,
            &self.budget,
            Arc::clone(&self.hub),
        )?);
        session.ensure_pump_running();
        sessions.insert(conn_id, Arc::clone(&session));
        debug!(
            "rx_session: created new session for connection {}",
            session.connection_id()
        );
        Ok(session)
    }

    /// Remove and shut down a session by connection id.
    ///
    /// Cancels the pump 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::buffer_budget::AtomicBudget;
    use crate::serial::test_support::loopback_connection;
    use crate::serial::{FlowControl, FlushTarget, SerialIo};
    use std::pin::Pin;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::task::{Context, Poll};
    use std::time::Duration;
    use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, ReadBuf};
    use tokio::sync::Notify;

    /// Convenience: an unlimited budget for tests where budget isn't under test.
    fn test_budget() -> Arc<dyn BufferBudget> {
        Arc::new(AtomicBudget::new(1024 * 1024 * 1024, 1024 * 1024 * 1024))
    }

    /// Convenience: a process-local hub for tests.
    fn test_hub() -> Arc<ResourceEventHub> {
        Arc::new(ResourceEventHub::new(64))
    }

    /// Convenience: create an RxSession directly with a 1024-byte ring.
    fn test_session(conn: Arc<SerialConnection>) -> RxSession {
        let budget = test_budget();
        RxSession::new(conn, 1024, &budget, test_hub()).expect("test session creation")
    }

    /// Convenience: create an RxSessionManager with a test budget.
    fn test_manager() -> RxSessionManager {
        RxSessionManager::new(test_budget(), test_hub())
    }

    // ── Manager idempotency ────────────────────────────────────────────────

    #[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 = test_manager();
        let s1 = mgr.get_or_create(Arc::clone(&conn), 1024).await.unwrap();
        let s2 = mgr.get_or_create(Arc::clone(&conn), 2048).await.unwrap();
        assert!(Arc::ptr_eq(&s1, &s2));
        assert_eq!(mgr.count().await, 1);
    }

    // ── Manager remove ─────────────────────────────────────────────────────

    #[tokio::test]
    async fn manager_remove_awaits_pump_exit() {
        let (conn, _peer) = loopback_connection("test-remove-await");
        let conn = Arc::new(conn);
        let mgr = test_manager();
        let session = mgr.get_or_create(Arc::clone(&conn), 1024).await.unwrap();
        let id = session.connection_id().to_string();
        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 = test_manager();
        mgr.remove("does-not-exist").await;
        assert_eq!(mgr.count().await, 0);
    }

    // ── Pump lifecycle (always-on model) ───────────────────────────────────

    #[tokio::test]
    async fn get_or_create_starts_pump() {
        let (conn, _peer) = loopback_connection("test-pump-start");
        let conn = Arc::new(conn);
        let mgr = test_manager();
        let session = mgr.get_or_create(Arc::clone(&conn), 1024).await.unwrap();
        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 = test_session(conn);
        session.ensure_pump_running();
        assert!(!session
            .pump_token
            .lock()
            .expect("pump_token")
            .is_cancelled());
        session.shutdown();
        assert!(session
            .pump_token
            .lock()
            .expect("pump_token")
            .is_cancelled());
    }

    // ── Remove lifecycle ───────────────────────────────────────────────────

    #[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 = test_manager();
        let session = mgr.get_or_create(Arc::clone(&conn), 1024).await.unwrap();
        let conn_id = session.connection_id().to_string();
        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"
        );
    }

    // ── Close causes pump exit ─────────────────────────────────────────────

    #[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 = test_session(Arc::clone(&conn));
        session.ensure_pump_running();

        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;

        // After close, the pump should have exited. Verify by checking the
        // pump task handle is consumed.
        assert!(
            session.pump_task.lock().expect("pump_task").is_none()
                || session
                    .pump_task
                    .lock()
                    .expect("pump_task")
                    .as_ref()
                    .map(|h| h.is_finished())
                    .unwrap_or(true),
            "pump should finish after connection close"
        );
    }

    // ── Shutdown clean exit ────────────────────────────────────────────────

    #[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 = test_session(Arc::clone(&conn));
        session.ensure_pump_running();

        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 shutdown_is_idempotent() {
        let (conn, _peer) = loopback_connection("test-shutdown-idem");
        let conn = Arc::new(conn);
        let session = test_session(conn);
        session.ensure_pump_running();
        session.shutdown();
        session.shutdown();
        session.shutdown();
        assert!(session
            .pump_token
            .lock()
            .expect("pump_token")
            .is_cancelled());
    }

    // ── Stress: repeated create + remove ──────────────────────────────────

    #[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 = test_manager();
            let session = mgr.get_or_create(Arc::clone(&conn), 1024).await.unwrap();
            let conn_id = session.connection_id().to_string();

            // 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);
        }
    }

    // ── NEW: Ring capture without consumers ────────────────────────────────

    #[tokio::test]
    async fn ring_captures_bytes_without_consumers() {
        let (conn, mut peer) = loopback_connection("test-ring-no-consumers");
        let conn = Arc::new(conn);
        let session = test_session(Arc::clone(&conn));
        session.ensure_pump_running();

        // No consumers registered. Write data; the pump must still capture to ring.
        peer.write_all(b"hi").await.unwrap();

        // Wait for pump to process the bytes.
        tokio::time::sleep(Duration::from_millis(200)).await;

        let end = session.ring().end_offset();
        assert_eq!(end, 2, "ring should have captured 2 bytes");
        let slice = session.ring().read_from(0, 10);
        assert_eq!(slice.bytes, b"hi");
        assert_eq!(slice.bytes_lost, 0);

        session.shutdown_and_join().await;
    }

    // ── NEW: Pump continues without consumers ─────────────────────────────

    #[tokio::test]
    async fn pump_keeps_running_when_no_consumers() {
        let (conn, mut peer) = loopback_connection("test-pump-no-consumers");
        let conn = Arc::new(conn);
        let session = test_session(Arc::clone(&conn));
        session.ensure_pump_running();

        // No consumers registered. Write some data.
        peer.write_all(b"before").await.unwrap();
        tokio::time::sleep(Duration::from_millis(200)).await;

        let end_before = session.ring().end_offset();
        assert_eq!(end_before, 6, "ring should have 'before'");

        // Pump must keep running — write more data.
        peer.write_all(b"after").await.unwrap();
        tokio::time::sleep(Duration::from_millis(200)).await;

        let end_after = session.ring().end_offset();
        assert_eq!(end_after, 11, "ring should have 'before'+'after'");
        let slice = session.ring().read_from(0, 20);
        assert_eq!(&slice.bytes[..6], b"before");
        assert_eq!(&slice.bytes[6..], b"after");

        session.shutdown_and_join().await;
    }

    // ── NEW: Budget charged at open, released at close ────────────────────

    #[tokio::test]
    async fn budget_charged_at_open_released_at_close() {
        let budget: Arc<dyn BufferBudget> = Arc::new(AtomicBudget::new(4096, 4096));
        let avail_before = budget.available();
        assert_eq!(avail_before, 4096);

        let (conn, _peer) = loopback_connection("test-budget-lifecycle");
        let conn = Arc::new(conn);
        let session = RxSession::new(conn, 1024, &budget, test_hub()).expect("session create");

        let avail_after_open = budget.available();
        assert_eq!(avail_after_open, 4096 - 1024);

        // Ring accessor works.
        assert_eq!(session.ring_capacity(), 1024);
        assert_eq!(session.read_cursor(), 0);

        session.shutdown_and_join().await;

        let avail_after_close = budget.available();
        assert_eq!(avail_after_close, 4096);
    }

    #[tokio::test]
    async fn budget_open_fails_if_insufficient() {
        // program_limit=512, tool_limit=1024 so request of 768 passes tool check
        // but exceeds program budget.
        let budget: Arc<dyn BufferBudget> = Arc::new(AtomicBudget::new(1024, 1024));
        // Consume some budget first so available < requested.
        let _hold = budget.try_reserve(900).expect("pre-reserve");
        let result = RxSession::new(
            Arc::new(loopback_connection("test-budget-fail").0),
            200,
            &budget,
            test_hub(),
        );
        match result {
            Err(e) => assert!(
                e.contains("insufficient program buffer budget"),
                "expected budget exhaustion error, got: {e}"
            ),
            Ok(_) => panic!("expected error for insufficient budget"),
        }
    }

    #[tokio::test]
    async fn budget_open_fails_if_zero_capacity() {
        let budget = test_budget();
        let result = RxSession::new(
            Arc::new(loopback_connection("test-zero-capacity").0),
            0,
            &budget,
            test_hub(),
        );
        match result {
            Err(e) => assert!(
                e.contains("ring_capacity must be > 0"),
                "expected zero capacity error, got: {e}"
            ),
            Ok(_) => panic!("expected error for zero capacity"),
        }
    }

    // ── NEW: Read cursor accessors ─────────────────────────────────────────

    #[tokio::test]
    async fn read_cursor_starts_at_zero() {
        let (conn, _peer) = loopback_connection("test-cursor-zero");
        let conn = Arc::new(conn);
        let session = test_session(conn);
        assert_eq!(session.read_cursor(), 0);
    }

    #[tokio::test]
    async fn set_read_cursor_updates_value() {
        let (conn, _peer) = loopback_connection("test-cursor-set");
        let conn = Arc::new(conn);
        let session = test_session(conn);
        session.set_read_cursor(42);
        assert_eq!(session.read_cursor(), 42);
        session.set_read_cursor(0);
        assert_eq!(session.read_cursor(), 0);
    }

    // ── NEW: ensure_pump_running is idempotent ─────────────────────────────

    #[tokio::test]
    async fn ensure_pump_running_is_idempotent() {
        let (conn, _peer) = loopback_connection("test-pump-idem");
        let conn = Arc::new(conn);
        let session = test_session(Arc::clone(&conn));

        assert!(session.pump_task.lock().expect("pump_task").is_none());
        session.ensure_pump_running();
        assert!(session.pump_task.lock().expect("pump_task").is_some());

        // Call again — verify pump is still running (not restarted).
        session.ensure_pump_running();
        assert!(session.pump_task.lock().expect("pump_task").is_some());
        assert!(!session
            .pump_token
            .lock()
            .expect("pump_token")
            .is_cancelled());

        session.shutdown_and_join().await;
    }

    // Verify ensure_pump_running starts a new pump if previous one completed.
    #[tokio::test]
    async fn ensure_pump_running_restarts_after_pump_finishes() {
        let (conn, _peer) = loopback_connection("test-pump-restart");
        let conn = Arc::new(conn);
        let session = test_session(Arc::clone(&conn));

        session.ensure_pump_running();
        // Cancel to simulate pump finishing abnormally.
        session.shutdown();
        session.join_pump().await;

        // Pump handle was taken by join_pump.
        assert!(session.pump_task.lock().expect("pump_task").is_none());

        // Calling ensure_pump_running again should start a new pump.
        session.ensure_pump_running();
        assert!(session.pump_task.lock().expect("pump_task").is_some());

        session.shutdown_and_join().await;
    }

    // ── Pump gate barrier (deterministic) ──────────────────────────────────

    /// Controlled [`SerialIo`] backend for the pump-gate barrier test.
    ///
    /// The payload is pre-loaded but held back: `poll_read` parks the pump's
    /// read (`Pending`) until [`PumpGateState::release`] delivers the exact
    /// bytes. Two explicit event-driven synchronization points expose the
    /// pump's progress without any wall-clock assumption:
    ///
    /// - `read_started`: fired on the first `poll_read` — the pump's read is
    ///   in flight and the pump holds `pump_gate` (it acquires the gate
    ///   before calling `read`).
    /// - `consumed`: fired when `poll_read` delivers the payload — the read
    ///   has returned with the bytes; the pump's ring append is the next
    ///   step, still under the gate.
    ///
    /// The pump's read has a 100ms budget and may time out and cycle while
    /// parked, but the payload is only ever delivered by `release`, so the
    /// ring cannot change before release no matter how the pump cycles.
    struct PumpGateState {
        /// Payload delivered to the pump's read once `released` is set.
        payload: StdMutex<Option<Vec<u8>>>,
        released: AtomicBool,
        /// Waker for the pump's parked read, woken on `release`.
        waker: StdMutex<Option<std::task::Waker>>,
        /// Fired on every `poll_read`; the test waits for the first fire.
        /// `notify_one` retains a permit when no waiter is registered yet,
        /// so the signal cannot be lost to a pump that polls before the
        /// test registers its wait.
        read_started: Notify,
        /// Fired when the payload is delivered to the pump's read.
        consumed: Notify,
    }

    impl PumpGateState {
        fn new(payload: &[u8]) -> Self {
            Self {
                payload: StdMutex::new(Some(payload.to_vec())),
                released: AtomicBool::new(false),
                waker: StdMutex::new(None),
                read_started: Notify::new(),
                consumed: Notify::new(),
            }
        }

        /// Deliver the exact payload to the pump's parked read and wake it.
        fn release(&self) {
            self.released.store(true, Ordering::SeqCst);
            if let Some(w) = self.waker.lock().expect("waker poisoned").take() {
                w.wake();
            }
        }
    }

    struct PumpGateIo {
        state: Arc<PumpGateState>,
    }

    impl AsyncRead for PumpGateIo {
        fn poll_read(
            self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &mut ReadBuf<'_>,
        ) -> Poll<std::io::Result<()>> {
            *self.state.waker.lock().expect("waker poisoned") = Some(cx.waker().clone());
            // `notify_one` (not `notify_waiters`): the retained permit makes
            // the read-start signal order-independent — it survives even if
            // the pump polls before the test registers `read_started.notified()`.
            self.state.read_started.notify_one();
            if !self.state.released.load(Ordering::SeqCst) {
                return Poll::Pending;
            }
            let mut payload = self.state.payload.lock().expect("payload poisoned");
            if let Some(bytes) = payload.take() {
                let n = buf.initialize_unfilled().len().min(bytes.len());
                let unfilled = buf.initialize_unfilled();
                unfilled[..n].copy_from_slice(&bytes[..n]);
                buf.advance(n);
                self.state.consumed.notify_waiters();
                Poll::Ready(Ok(()))
            } else {
                Poll::Pending
            }
        }
    }

    impl AsyncWrite for PumpGateIo {
        fn poll_write(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buf: &[u8],
        ) -> Poll<std::io::Result<usize>> {
            Poll::Ready(Ok(buf.len()))
        }

        fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
            Poll::Ready(Ok(()))
        }

        fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
            Poll::Ready(Ok(()))
        }
    }

    impl SerialIo for PumpGateIo {
        fn clear_os_buffers(&self, _target: FlushTarget) -> std::io::Result<()> {
            Ok(())
        }
        fn set_dtr_rts(&mut self, _dtr: bool, _rts: bool) -> std::io::Result<()> {
            Ok(())
        }
        fn set_flow_control(&mut self, _flow_control: FlowControl) -> std::io::Result<()> {
            Ok(())
        }
        fn set_break_state(&self, _asserted: bool) -> std::io::Result<()> {
            Ok(())
        }
    }

    /// The pump holds `pump_gate` across one complete read + ring append.
    ///
    /// While the pump's read is in flight the gate cannot be acquired and
    /// the ring stays empty; after the exact payload is released, a gate
    /// acquisition succeeds only once the ring contains the payload at the
    /// expected offsets. This is the atomic unit `capture_boot` waits on for
    /// its live-edge mark: a byte physically read before the mark can never
    /// append after it.
    ///
    /// All synchronization is event-driven (wakers + `Notify`), never
    /// wall-clock: the pump's 100ms read budget may elapse and the pump may
    /// cycle any number of times, but every assertion is on a state that
    /// holds regardless of timing. Bounded timeouts only guard against hangs.
    #[tokio::test]
    async fn pump_holds_gate_across_inflight_read_and_ring_append() {
        const PAYLOAD: &[u8] = b"INFLIGHT";

        let state = Arc::new(PumpGateState::new(PAYLOAD));
        let conn = Arc::new(SerialConnection::from_io(
            "test-pump-gate".to_string(),
            Box::new(PumpGateIo {
                state: Arc::clone(&state),
            }),
        ));
        let session = test_session(Arc::clone(&conn));

        // Register the read-start wait BEFORE the pump can possibly run
        // (registration happens at `notified()` creation). Combined with the
        // backend's `notify_one`, the signal is order-independent: a pump
        // that polls before this line still leaves a retained permit.
        let read_started = state.read_started.notified();
        session.ensure_pump_running();

        // Wait for the pump's first read to be in flight. The pump acquires
        // the gate before it ever reaches `poll_read`, so when this fires
        // the gate is held by the pump.
        tokio::time::timeout(Duration::from_secs(5), read_started)
            .await
            .expect("pump read must start within the hang guard");

        // Nothing can be appended before release: the payload is held back,
        // so every pump cycle reads nothing, regardless of timing.
        assert_eq!(
            session.ring().end_offset(),
            0,
            "ring must be empty while the pump's read is in flight"
        );

        // The gate cannot be acquired while the read is in flight. The
        // pump's read budget is 100ms: on timeout the gate is dropped and
        // immediately re-acquired between cycles, so a `try_lock` at that
        // exact instant can (benignly) succeed once. Yield so a runnable
        // pump re-locks, then require the gate held — a pump that reads
        // outside the gate (regression) fails every attempt.
        let mut gate_held = false;
        for _ in 0..3 {
            if session.pump_gate.try_lock().is_err() {
                gate_held = true;
                break;
            }
            tokio::task::yield_now().await;
        }
        assert!(
            gate_held,
            "pump must hold pump_gate while its read is in flight"
        );

        // Release the exact payload. The in-flight read completes with it,
        // the append lands while the gate is still held, and only then is
        // the gate released. `consumed` fires inside the read, so queuing
        // the acquisition afterwards still registers while the append is
        // the pump's next step under the gate.
        //
        // Ordering safety: the wait is registered (notified()) BEFORE
        // `release()`, and delivery can only happen after release (the
        // backend holds the payload until then). `notify_waiters` is
        // received when it happens after future creation, so the signal
        // cannot be lost here — unlike `read_started` above, no retained
        // permit is needed.
        let consumed = state.consumed.notified();
        state.release();
        tokio::time::timeout(Duration::from_secs(5), consumed)
            .await
            .expect("pump must consume the released payload within the hang guard");

        // A gate acquisition now succeeds only after the append: the pump
        // releases the gate after `ring.append`, so at acquisition time the
        // ring already contains the exact payload at the expected offsets.
        let guard = session.pump_gate_guard().await;
        assert_eq!(
            session.ring().end_offset(),
            PAYLOAD.len() as u64,
            "payload must be appended before the gate is released"
        );
        let slice = session.ring().read_from(0, PAYLOAD.len());
        assert_eq!(slice.bytes, PAYLOAD);
        assert_eq!(slice.bytes_lost, 0);
        assert_eq!(slice.from_offset, 0);
        assert_eq!(slice.next_offset, PAYLOAD.len() as u64);
        drop(guard);

        // Cleanup: cancel and join the pump task.
        session.shutdown_and_join().await;
    }

    // ── Pump publishes resource hints only after ring append ──────────────

    /// The pump publishes connection detail/raw/log resource hints AFTER the
    /// ring append and OUTSIDE the pump gate.
    ///
    /// All synchronization is event-driven with the same [`PumpGateIo`]
    /// backend as the gate test: while the pump's read is in flight (payload
    /// held back) no event can arrive and the ring stays empty; after the
    /// payload is released, the first event arrives only once the ring
    /// contains the bytes, and receiving it sees the advanced end offset.
    /// The gate is demonstrably released (a bounded acquisition succeeds),
    /// so publication never extends the `capture_boot` atomic unit.
    #[tokio::test]
    async fn pump_publishes_resource_hints_only_after_ring_append() {
        const PAYLOAD: &[u8] = b"INFLIGHT";

        let hub = Arc::new(crate::resource_events::ResourceEventHub::new(64));
        let mut rx = hub.subscribe();

        let state = Arc::new(PumpGateState::new(PAYLOAD));
        let conn = Arc::new(SerialConnection::from_io(
            "test-pump-publish".to_string(),
            Box::new(PumpGateIo {
                state: Arc::clone(&state),
            }),
        ));
        let conn_id = conn.id().to_string();
        let budget = test_budget();
        let session =
            RxSession::new(Arc::clone(&conn), 1024, &budget, hub).expect("session creation");

        // Wait for the pump's read to be in flight (gate held, ring empty).
        let read_started = state.read_started.notified();
        session.ensure_pump_running();
        tokio::time::timeout(Duration::from_secs(5), read_started)
            .await
            .expect("pump read must start within the hang guard");

        // A subscriber must NOT receive an update before the bytes are in
        // the ring.
        assert_eq!(
            session.ring().end_offset(),
            0,
            "ring must be empty while the pump's read is in flight"
        );
        assert!(
            matches!(
                rx.try_recv(),
                Err(tokio::sync::broadcast::error::TryRecvError::Empty)
            ),
            "no resource hint may arrive before the ring append"
        );

        // Release the payload; the pump appends and then publishes.
        let consumed = state.consumed.notified();
        state.release();
        tokio::time::timeout(Duration::from_secs(5), consumed)
            .await
            .expect("pump must consume the released payload within the hang guard");

        // The first hint is the detail URI; receipt sees the advanced end
        // offset and the exact bytes in the ring.
        let event = tokio::time::timeout(Duration::from_secs(5), rx.recv())
            .await
            .expect("detail hint within the hang guard")
            .expect("hub not closed");
        assert_eq!(
            event,
            crate::resource_events::ResourceEvent::Updated(
                crate::resource_events::detail_uri(&conn_id).expect("detail uri")
            ),
            "first published hint must be the connection detail URI"
        );
        assert_eq!(
            session.ring().end_offset(),
            PAYLOAD.len() as u64,
            "bytes must be appended before the hint is delivered"
        );
        let slice = session.ring().read_from(0, PAYLOAD.len());
        assert_eq!(slice.bytes, PAYLOAD);
        assert_eq!(slice.bytes_lost, 0);

        // The raw and log hints follow.
        let raw_event = tokio::time::timeout(Duration::from_secs(5), rx.recv())
            .await
            .expect("raw hint within the hang guard")
            .expect("hub not closed");
        assert_eq!(
            raw_event,
            crate::resource_events::ResourceEvent::Updated(
                crate::resource_events::raw_uri(&conn_id).expect("raw uri")
            )
        );
        let log_event = tokio::time::timeout(Duration::from_secs(5), rx.recv())
            .await
            .expect("log hint within the hang guard")
            .expect("hub not closed");
        assert_eq!(
            log_event,
            crate::resource_events::ResourceEvent::Updated(
                crate::resource_events::log_uri(&conn_id).expect("log uri")
            )
        );

        // The gate was released before publication: a bounded acquisition
        // succeeds (the pump only re-acquires it for its next parked read).
        let gate_guard = tokio::time::timeout(Duration::from_secs(1), session.pump_gate_guard())
            .await
            .expect("pump gate must be acquirable after publication");
        drop(gate_guard);

        // Cleanup: cancel and join the pump task.
        session.shutdown_and_join().await;
    }
}