liminal-server 0.25.4

Standalone server for the liminal messaging bus
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
use beamr::native::native_process::{NativeContext, NativeHandler, NativeOutcome};
use beamr::process::ExitReason;
use beamr::scheduler::Interest;
use beamr::term::Term;

use crate::ServerError;
use crate::server::mount::MountKind;
use crate::server::participant::ConnectionFateClass;

use liminal_protocol::wire::ConnectionIncarnation;

use std::io::Write;
use std::net::SocketAddr;
use std::sync::Arc;

#[path = "process/buffer.rs"]
mod buffer;
#[path = "process/close.rs"]
mod close;
#[path = "process/control.rs"]
mod control;
#[path = "process/force_close.rs"]
mod force_close;
#[path = "process/participant_pushes.rs"]
mod participant_pushes;
#[path = "process/slice_readiness.rs"]
mod slice_readiness;
#[path = "process/tcp_transport.rs"]
mod tcp_transport;

use buffer::process_buffer;
use participant_pushes::participant_publication_error;
use tcp_transport::TcpTransport;

use super::delivery::service_subscriptions;
use super::outbound::{DrainOutcome, OutboundWriter};
use super::participant_delivery::has_held_participant_head;
use super::state::{ConnectionProcessState, ProcessStatus};
use super::supervisor::runtime::{ConnectionControl, ConnectionRuntime};

#[cfg(test)]
#[path = "process_teardown_tests.rs"]
mod teardown_tests;

#[cfg(test)]
#[path = "process_fate_tests.rs"]
mod fate_tests;

#[cfg(test)]
#[path = "process_terminal_tests.rs"]
mod terminal_tests;

#[cfg(test)]
#[path = "process_pre_admission_tests.rs"]
mod pre_admission_tests;

#[cfg(test)]
#[path = "process_wake_tests.rs"]
mod wake_tests;

#[cfg(test)]
#[path = "process_readiness_stop_tests.rs"]
pub(super) mod readiness_stop_tests;

/// Per-slice inbound read size, and the per-slice outbound drain budget.
///
/// Shared with the sibling transports so one connection cannot monopolize a
/// scheduler thread on one door and not another.
pub(super) const READ_BUFFER_BYTES: usize = 8192;
/// Application stream id used for server-initiated push frames. Push is an
/// application-stream frame (non-zero stream id), like publish and conversation.
const PUSH_STREAM_ID: u32 = 1;

/// One supervised connection, generic over the transport half it owns.
///
/// EVERYTHING above the read/write halves is here exactly once: the slice
/// ordering, the `apply_frame` seam, the pending-reply table, the delivery and
/// participant-publication pumps, the control vocabulary, the close/fate paths,
/// and the teardown backstop. A sibling transport supplies a
/// [`ConnectionTransport`] and inherits all of it — no second slice loop, no
/// second probe, no second close path to keep in step. That is the design's
/// "third sibling, not a new seam" answer, and it is why the loopback needs no
/// parallel process type.
#[derive(Debug)]
pub(super) struct TransportConnectionProcess<T: ConnectionTransport> {
    runtime: Arc<ConnectionRuntime>,
    peer_addr: Option<SocketAddr>,
    /// The read/write halves and their transport-specific readiness discipline.
    transport: T,
    buffer: Vec<u8>,
    state: ConnectionProcessState,
    /// Per-connection outbound byte buffer. EVERY server-originated frame (acks,
    /// errors, `Push`, `Disconnect`, `Pong`, `Deliver`, ...) is enqueued here and
    /// drained cooperatively on the slice loop with partial-write tracking, so a
    /// frame larger than the socket send buffer streams out across slices instead
    /// of failing a `write_all` on the non-blocking socket (ledger G4).
    outbound: OutboundWriter,
    /// Set once the transport's wake has been installed, so the install runs on
    /// the first serviced slice and never again.
    wake_installed: bool,
    agent_connection: Option<u64>,
    /// Fails the next participant publication pump with a non-capacity fault.
    /// Test-only: the publication teardown, forced.
    #[cfg(test)]
    fail_next_pump: bool,
}

/// The supervised TCP connection process: the original, and the transport every
/// sibling is measured against.
pub(super) type ConnectionProcess = TransportConnectionProcess<TcpTransport>;

/// Whether a connection slice's socket/inbound servicing leaves the connection
/// running or has already resolved its lifecycle.
enum SliceStep {
    Continue,
    Stop(ExitReason),
}

/// A connection's read and write halves, plus the transport-specific parts of
/// parking: how readiness is armed, how the reader is told, and what a drop of
/// the transport owes the runtime.
///
/// Implementors supply ONLY what genuinely differs between doors. Every
/// transport-neutral decision — when to park, when to requeue, what a close
/// costs, which fate a hangup folds — stays in
/// [`TransportConnectionProcess`], so a new mount cannot accidentally acquire
/// different lifecycle semantics by copying a slice loop slightly wrong.
pub(super) trait ConnectionTransport: Send + 'static {
    /// The door this transport IS (design §10).
    ///
    /// An associated const rather than a constructor argument: the mount fact
    /// is then a property of the transport type itself, so no spawn path can
    /// stamp a mount that disagrees with the halves it actually handed over,
    /// and no runtime value — least of all an inbound byte — can move it.
    const MOUNT: MountKind;

    /// Whether the transport still holds its halves. A transport that has been
    /// released (or never received them) can neither read nor write.
    fn is_connected(&self) -> bool;

    /// Reads whatever is available into `buffer` without blocking.
    ///
    /// # Errors
    /// Returns [`ServerError::ListenerAccept`] on an unrecoverable read
    /// failure; `WouldBlock`/`Interrupted` are reported as
    /// [`ReadStatus::WouldBlock`], not errors.
    fn read_available(&mut self, buffer: &mut Vec<u8>) -> Result<ReadStatus, ServerError>;

    /// The outbound sink, or `None` when the transport has no write half left.
    fn sink(&mut self) -> Option<&mut dyn Write>;

    /// Whether inbound bytes are already waiting, without consuming them.
    ///
    /// A transport with no read half answers `true`: quiescence was never
    /// established, so parking on it would be a claim the probe cannot make.
    ///
    /// # Errors
    /// Returns [`ServerError::ListenerAccept`] when the probe itself fails.
    fn probe_inbound(&self) -> Result<bool, ServerError>;

    /// Arms this transport's readiness interest before the connection parks.
    ///
    /// # Errors
    /// Returns [`ServerError::ListenerAccept`] when the readiness contract
    /// cannot be satisfied.
    fn arm_readiness(
        &mut self,
        pid: u64,
        ctx: &NativeContext<'_>,
        interest: Interest,
        runtime: &ConnectionRuntime,
    ) -> Result<(), ServerError>;

    /// Installs this transport's wake on the connection's first serviced slice,
    /// once the host record exists (so the connection's `READY` waker can be
    /// built). Transports woken by the readiness facility need nothing here.
    ///
    /// # Errors
    /// Returns [`ServerError::ListenerAccept`] when the wake cannot be
    /// installed — for a transport that has no other way to be told, a failed
    /// install is fatal rather than a silently deaf connection.
    fn install_wake(&mut self, pid: u64, runtime: &ConnectionRuntime) -> Result<(), ServerError>;

    /// Drops the transport's halves at an orderly server-forced close, after the
    /// host record has been removed.
    fn release(&mut self);

    /// Observes the transport's halves actually dropping, for the descriptor
    /// allocator boundary tests. Production keeps the ordinary field-drop path.
    #[cfg(test)]
    fn note_process_drop(&mut self, runtime: &ConnectionRuntime);
}

impl<T: ConnectionTransport> TransportConnectionProcess<T> {
    /// Builds a connection process over `transport`.
    ///
    /// The ONE construction: pending-reply table sized from the runtime's
    /// configured §5 caps, publication inbox iff a durable incarnation and a
    /// participant service both exist, and the mount stamped from the
    /// transport's own [`ConnectionTransport::MOUNT`]. Every sibling transport
    /// enters here, so none of those decisions can drift per door.
    pub(super) fn over_transport(
        runtime: Arc<ConnectionRuntime>,
        peer_addr: Option<SocketAddr>,
        transport: T,
        connection_incarnation: Option<ConnectionIncarnation>,
    ) -> Self {
        // Build the pending-reply table from the runtime's configured §5 caps
        // (R1(vi), §1.2(3b)). The default table carries the signed defaults; this
        // uses the connection's actual limits.
        let limits = runtime.limits();
        let pending_replies = super::pending_reply::PendingReplyTable::new(
            limits.max_pending_replies_per_conversation,
            limits.max_pending_conversation_replies_per_connection,
            std::time::Duration::from_millis(limits.reply_timeout_ms),
        );
        let participant_publication = connection_incarnation.and_then(|_| {
            runtime
                .participant_service()
                .map(crate::server::participant::InstalledParticipantService::new_publication_inbox)
        });
        let state = ConnectionProcessState {
            connection_incarnation,
            participant_publication,
            pending_replies,
            // Design §10: stamped from the transport TYPE, so the door that
            // handed over the halves is the door on the record.
            mount: T::MOUNT,
            ..ConnectionProcessState::default()
        };
        // The standing bound is the operator's; the test seam overrides it for ONE
        // connection at a time (a fixture needs a small buffer on one peer while
        // its siblings stay normal), which a server-wide setting cannot express.
        #[cfg(test)]
        let outbound = OutboundWriter::with_capacity(
            runtime
                .take_next_outbound_capacity()
                .unwrap_or(limits.max_connection_outbound_bytes),
        );
        #[cfg(not(test))]
        let outbound = OutboundWriter::with_capacity(limits.max_connection_outbound_bytes);
        Self {
            runtime,
            peer_addr,
            transport,
            buffer: Vec::new(),
            state,
            outbound,
            wake_installed: false,
            agent_connection: None,
            #[cfg(test)]
            fail_next_pump: false,
        }
    }

    /// The mount this process's transport stamped onto its connection state.
    ///
    /// The test-side read of the design §10 fact: it proves the door's stamp
    /// arrived on the state `apply_frame` builds the handler context from,
    /// rather than trusting that the constructor passed it along.
    #[cfg(test)]
    pub(super) const fn mount(&self) -> MountKind {
        self.state.mount
    }

    /// Runs one connection scheduler slice: service inbound socket/control work,
    /// then service subscriptions into the outbound buffer, then drain the
    /// outbound buffer to the socket.
    ///
    /// The ordering is load-bearing (subscriptions are pumped AFTER socket/control
    /// work), and the whole slice preserves the no-sleep `Continue` discipline: a
    /// slice never parks a scheduler thread, it re-queues the process to poll again.
    fn handle_slice(&mut self, pid: u64, ctx: &mut NativeContext<'_>) -> NativeOutcome {
        self.agent_connection = Some(pid);
        // R7 (§1.2(6)): count this serviced slice. The park-flip's permanent
        // rule-1 quiescence assertion — a parked connection's counter must not
        // advance without an event — reads this; under the busy loop the counter
        // advances every slice, and the instrument proves it counts.
        #[cfg(test)]
        self.runtime.record_slice(pid);
        // `spawn_native` may schedule the first slice before the spawn thread has
        // inserted the host record. Do not mint an unpublishable token; yield once
        // and register after the record exists.
        if !self.runtime.is_registered(pid) {
            return NativeOutcome::Continue;
        }
        if let Err(error) = self.ensure_transport_wake_installed(pid) {
            return self.fail_slice(pid, &error);
        }
        if let Err(error) = self.ensure_participant_publication_registered(pid) {
            return self.fail_slice(pid, &error);
        }
        // ACCESS-005 R6: a revocation is acted on at the connection's own
        // wake even when its control could not be published.
        if self.state.revocation.is_some()
            && let Some(outcome) = self.revocation_sweep(pid)
        {
            return outcome;
        }
        if let Some(outcome) = self.force_close_if_pending(pid) {
            return outcome;
        }
        match self.service_socket(pid) {
            SliceStep::Stop(reason) => return NativeOutcome::Stop(reason),
            SliceStep::Continue => {}
        }
        if let Err(error) = super::supervisor::relay_pump::pump(&self.state, &mut self.outbound) {
            return self.tear_down_outbound(pid, &error, "relay pump failed; tearing down");
        }
        // R1(vi) (§1.2(3b)): service the pending-reply table each slice — expire
        // due deadlines (writing timeout frames) and drain/correlate any replies
        // the participants produced. A fatal outbound condition here tears the
        // connection down, matching the delivery path.
        if let Err(error) = self.service_pending_replies() {
            return self.tear_down_outbound(
                pid,
                &error,
                "conversation replies could not be written or a far call could not be settled; tearing down",
            );
        }
        if let Some(outcome) = self.service_participant_pushes(pid) {
            return outcome;
        }
        // Pump subscriptions into the outbound buffer. An overflow (or an encode
        // fault) is fatal: a dropped or truncated delivery would desync the stream,
        // so the connection is torn down rather than allowed to continue desynced.
        let slice_budget = self.runtime.limits().delivery_slice_budget;
        match service_subscriptions(&mut self.state, &mut self.outbound, slice_budget) {
            Ok(shed) => self.shed_subscriptions(shed),
            Err(error) => {
                return self.tear_down_outbound(
                    pid,
                    &error,
                    "outbound overflow while delivering; tearing down the connection",
                );
            }
        }
        // Drain queued outbound bytes with partial-write tracking. A hard write
        // error (or overflow surfaced here) tears the connection down.
        let drain = match self.drain_outbound() {
            Ok(drain) => drain,
            Err(error) => {
                if let Err(fate_error) =
                    self.complete_connection_fate(ConnectionFateClass::ConnectionLost)
                {
                    tracing::error!(connection_pid = pid, %fate_error, "connection-loss fate fold failed");
                }
                return self.tear_down_outbound(
                    pid,
                    &error,
                    "outbound drain failed; tearing down the connection",
                );
            }
        };
        #[cfg(test)]
        self.report_frames_written(pid, drain);
        self.finish_slice_readiness(pid, ctx, drain)
    }

    /// Installs the transport's wake exactly once, on the first slice that finds
    /// the host record in place.
    ///
    /// The ordering is what closes the lost-wake window for a transport with no
    /// descriptor. The install happens at the TOP of the slice, so it strictly
    /// precedes this slice's [`Self::final_probe`] — and the probe is the only
    /// way to `Wait`. A write that lands before the probe is seen BY the probe
    /// (which requeues); a write that lands after it fires the now-installed
    /// wake. There is no third case, so a parked connection is never a deaf one.
    /// It cannot run earlier than this: the wake names the connection's pid and
    /// its record, and neither exists until the spawn thread has registered.
    fn ensure_transport_wake_installed(&mut self, pid: u64) -> Result<(), ServerError> {
        if self.wake_installed {
            return Ok(());
        }
        self.transport.install_wake(pid, &self.runtime)?;
        self.wake_installed = true;
        Ok(())
    }

    /// Services the inbound half of a slice: reads available bytes and applies any
    /// complete frames, enqueuing responses into the outbound buffer.
    fn service_socket(&mut self, pid: u64) -> SliceStep {
        if let Some(outcome) = self.force_close_if_pending(pid) {
            return match outcome {
                NativeOutcome::Stop(reason) => SliceStep::Stop(reason),
                _ => SliceStep::Continue,
            };
        }
        if !self.transport.is_connected() {
            self.release_conversations();
            self.runtime
                .mark_crashed(pid, ExitReason::Error, self.peer_addr);
            return SliceStep::Stop(ExitReason::Error);
        }
        let read = self.transport.read_available(&mut self.buffer);
        if let Some(outcome) = self.force_close_if_pending(pid) {
            return match outcome {
                NativeOutcome::Stop(reason) => SliceStep::Stop(reason),
                _ => SliceStep::Continue,
            };
        }
        match read {
            Ok(ReadStatus::Closed) => {
                crate::agents::runtime::connection_closed(
                    self.runtime.services(),
                    pid,
                    "transport_eof",
                );
                // Best-effort flush of anything still queued (e.g. WouldBlock residue
                // from earlier slices to a half-closed peer) before we let the stream
                // drop, mirroring the ForceClose drain. The buffered-writer refactor
                // removed this on the EOF path; without it, queued responses are lost.
                //
                // The drain error is only debug-logged, and what is lost with it is the
                // residue this call could not write — the peer never sees those
                // frames. That is accepted because the peer has already closed
                // its write half, so the residue had nowhere to go regardless,
                // and this path is past the close decision: retrying or sleeping
                // to shrink the window is forbidden here.
                if let Err(error) = self.drain_outbound() {
                    tracing::debug!(connection_pid = pid, %error, "the close path's best-effort drain did not finish; the peer's half-close ends it");
                }
                if let Err(error) =
                    self.complete_connection_fate(ConnectionFateClass::ConnectionLost)
                {
                    return self.fail_fate(pid, &error);
                }
                self.release_conversations();
                self.runtime.finish(pid);
                return SliceStep::Stop(ExitReason::Normal);
            }
            Ok(ReadStatus::WouldBlock) => {
                // No bytes ready on this non-blocking socket right now. Do NOT
                // sleep: that would block a beamr scheduler worker thread (the
                // supervisor runs `CONNECTION_SCHEDULER_THREADS`) on every idle
                // poll and starve every other connection process sharing it. The
                // caller returns `NativeOutcome::Continue` (mapping to
                // `SliceOutcome::Requeue`), which re-queues this pid behind every
                // other runnable process (cooperative round-robin) and reschedules
                // us to poll — and, crucially, to drain any queued outbound bytes —
                // without parking. `Wait` is wrong here: it parks until a *message*
                // arrives, but socket readiness does not enqueue a message, so the
                // connection would hang forever.
                return SliceStep::Continue;
            }
            Ok(ReadStatus::Read) => {}
            Err(error) => {
                tracing::warn!(connection_pid = pid, %error, "connection read failed");
                if let Err(fate_error) =
                    self.complete_connection_fate(ConnectionFateClass::ConnectionLost)
                {
                    return self.fail_fate(pid, &fate_error);
                }
                self.release_conversations();
                self.runtime
                    .mark_crashed(pid, ExitReason::Error, self.peer_addr);
                return SliceStep::Stop(ExitReason::Error);
            }
        }
        match process_buffer(
            pid,
            &self.runtime,
            &mut self.state,
            &mut self.buffer,
            &mut self.outbound,
        ) {
            Ok(ProcessStatus::Continue) => SliceStep::Continue,
            Ok(ProcessStatus::Close) => self.finish_normal_close(pid),
            Ok(ProcessStatus::CloseWithFate(ConnectionFateClass::ServerShutdown)) => {
                self.runtime.take_force_close(pid);
                match self.handle_control(pid, ConnectionControl::ForceClose) {
                    Some(NativeOutcome::Stop(reason)) => SliceStep::Stop(reason),
                    _ => SliceStep::Continue,
                }
            }
            Ok(ProcessStatus::CloseWithFate(class)) => self.finish_fate_close(pid, class),
            Err(error) => {
                tracing::warn!(connection_pid = pid, %error, "connection process failed");
                self.release_conversations();
                self.runtime
                    .mark_crashed(pid, ExitReason::Error, self.peer_addr);
                SliceStep::Stop(ExitReason::Error)
            }
        }
    }

    /// R1(vi) (§1.2(3b)): services the pending-reply table for this slice.
    ///
    /// 1. DEADLINE-CHECK SEAM: expire every pending entry whose deadline passed,
    ///    tombstoning it and enqueuing its timeout error frame. Under the busy loop
    ///    this runs every slice; PARK-FLIP adds a timer-driven `READY` wake at each
    ///    entry's deadline (contract R1(vi) as amended) so a parked connection with
    ///    zero other traffic still wakes to write the timeout — that wake feeds this
    ///    same seam.
    /// 2. Drain and correlate: for each conversation still awaiting a reply, pull
    ///    buffered participant replies non-blocking and match them FIFO, enqueuing
    ///    each correlated reply frame. A conversation gone from the map (closed) is
    ///    swept from the table so its entries do not linger.
    ///
    /// # Errors
    /// Returns [`OutboundError`](super::outbound::OutboundError) when a reply or
    /// timeout frame cannot be enqueued (a fatal outbound condition).
    fn service_pending_replies(&mut self) -> Result<(), super::outbound::OutboundError> {
        let frames = super::reply_service::settled_frames(&mut self.state, &self.runtime)
            .map_err(super::outbound::OutboundError::LinkCalls)?;
        for frame in frames {
            self.outbound.enqueue_frame(&frame)?;
        }
        Ok(())
    }

    /// Removes and releases subscriptions the delivery pump shed on inbox overflow
    /// (§5). The pump has already enqueued each subscription's typed `SubscribeError`
    /// frame; here the subscription is dropped from connection state (its
    /// delivery-sequence counter and any held frame with it, so a re-subscribe that
    /// reuses the id starts clean) and released through the services adapter, the
    /// same teardown path an explicit `Unsubscribe` uses. A slow consumer thus sheds
    /// its own subscription without growing server memory or tearing down the
    /// connection's other streams.
    fn shed_subscriptions(&mut self, shed: Vec<u64>) {
        for subscription_id in shed {
            self.state.delivery_seqs.remove(&subscription_id);
            self.state.held_deliveries.remove(&subscription_id);
            if let Some(subscription) = self.state.subscriptions.remove(&subscription_id) {
                if let Err(error) = self.runtime.services().unsubscribe(subscription) {
                    tracing::warn!(
                        subscription_id,
                        %error,
                        "releasing a shed (inbox-overflowed) subscription failed"
                    );
                }
            }
        }
    }

    fn drain_outbound(
        &mut self,
    ) -> Result<super::outbound::DrainOutcome, super::outbound::OutboundError> {
        let Some(sink) = self.transport.sink() else {
            return Ok(super::outbound::DrainOutcome::Drained);
        };
        self.outbound.drain(sink, Some(READ_BUFFER_BYTES))
    }

    /// Makes one unbudgeted, nonblocking attempt to flush terminal output.
    ///
    /// The outbound queue is bounded, so removing the normal slice budget cannot
    /// create unbounded work. A full socket can still return
    /// [`DrainOutcome::WouldBlockWithResidue`]; terminal delivery is best-effort
    /// at that transport boundary and this method never waits or retries.
    fn drain_outbound_for_close(
        &mut self,
    ) -> Result<super::outbound::DrainOutcome, super::outbound::OutboundError> {
        let Some(sink) = self.transport.sink() else {
            return Ok(super::outbound::DrainOutcome::Drained);
        };
        self.outbound.drain(sink, None)
    }

    fn arm_readiness(
        &mut self,
        pid: u64,
        ctx: &NativeContext<'_>,
        interest: Interest,
    ) -> Result<(), ServerError> {
        self.transport
            .arm_readiness(pid, ctx, interest, &self.runtime)
    }

    fn sync_deadline_timers(
        &mut self,
        pid: u64,
        ctx: &mut NativeContext<'_>,
    ) -> Result<(), ServerError> {
        for timer in self.state.pending_replies.take_retired_timers() {
            ctx.cancel_timer(timer);
        }
        for (op_id, delay) in self
            .state
            .pending_replies
            .timers_to_arm(std::time::Instant::now())
        {
            let timer = ctx
                .send_after(delay, pid, Term::atom(self.runtime.ready_atom()))
                .ok_or_else(|| ServerError::ListenerAccept {
                    message: "connection scheduler has no timer facility for reply deadlines"
                        .to_owned(),
                })?;
            if !self.state.pending_replies.install_timer(op_id, timer) {
                ctx.cancel_timer(timer);
            }
        }
        Ok(())
    }

    /// Post-arm C1/C4 barrier. Each query is nonblocking and non-consuming,
    /// including the native mailbox so READY enqueued by this slice cannot be
    /// mistaken for quiescence after its inbox work was already consumed.
    fn final_probe(&self, pid: u64, ctx: &NativeContext<'_>) -> Result<bool, ServerError> {
        let socket_ready = self.transport.probe_inbound()?;
        let subscription_ready = !self.state.held_deliveries.is_empty()
            || self
                .state
                .subscriptions
                .values()
                .any(|subscription| subscription.is_overflowed() || subscription.has_pending());
        let participant_ready = if self.state.held_pushes.capacity_refused()
            && has_held_participant_head(&self.state)
        {
            false
        } else {
            match self.state.participant_publication.as_ref() {
                Some(inbox) => inbox.has_pending().map_err(participant_publication_error)?,
                None => false,
            }
        };
        let reply_ready = self
            .state
            .pending_replies
            .has_due(std::time::Instant::now())
            || self
                .state
                .pending_replies
                .conversations_with_entries()
                .into_iter()
                .filter_map(|id| self.state.conversations.get(&id))
                .any(super::conversation::ConnectionConversation::has_pending_reply);
        Ok(socket_ready
            || subscription_ready
            || participant_ready
            || reply_ready
            || super::supervisor::relay_pump::has_ready(&self.state, &self.outbound)?
            || self.runtime.has_control(pid)
            || self.runtime.ready_pending(pid)
            || ctx.has_messages())
    }

    /// Drains queued outbound bytes to the socket, if the stream is still present.
    ///
    /// Returns the [`DrainOutcome`](super::outbound::DrainOutcome) tri-state. Under
    /// the busy loop every caller ignores the distinction and re-services on the
    /// next slice; the value is reported so the seam is honest.
    ///
    /// PARK-FLIP SEAM (R2, §1.2(1)): when this returns
    /// `Ok(DrainOutcome::WouldBlockWithResidue)` the park-flip commit arms writable
    /// readiness interest for this connection's socket (and only then), so the
    /// connection re-wakes when the kernel send buffer drains instead of parking
    /// with unflushed residue. `Drained`/`Progress` arm nothing. The current live
    /// slice uses the fixed read-buffer budget; terminal close uses
    /// [`Self::drain_outbound_for_close`] instead.
    /// R3b F8, ruling 2a: once the buffer is empty, every frame enqueued
    /// since the last report has been written to the transport. Test-only.
    #[cfg(test)]
    fn report_frames_written(&mut self, pid: u64, drain: DrainOutcome) {
        if drain == DrainOutcome::Drained && self.outbound.queued_len() == 0 {
            self.runtime
                .record_frames_written(pid, self.outbound.take_enqueued());
        }
    }
}

impl<T: ConnectionTransport> NativeHandler for TransportConnectionProcess<T> {
    fn handle(&mut self, ctx: &mut NativeContext<'_>) -> NativeOutcome {
        let pid = ctx.self_pid();
        // FIX A-ii: the moment this connection is scheduled it is executing, so it
        // is no longer delivery-quiescent. Marked BEFORE the mailbox drain and
        // `acknowledge_ready` below, so the shutdown flush barrier can never sample
        // this connection as parked-with-no-pending-READY in the window between a
        // fan-out wake clearing `ready_pending` and its delivering slice starting.
        self.runtime.mark_running(pid);
        if let Some(outcome) = self.force_close_if_pending(pid) {
            return outcome;
        }
        // Registration is owned solely by the spawn thread (`SupervisorInner::
        // spawn_connection` calls `runtime.register` before returning the
        // handle), so the handler never writes the registry — it only reads its
        // record via `mark_crashed`/`finish`. This removes the previous
        // double-write (spawn-thread `insert` racing a handler `or_insert`) and
        // its lost-update/duplicate-record hazard.
        while let Some(message) = ctx.recv() {
            if let Some(outcome) = self.handle_message(pid, message) {
                return outcome;
            }
        }
        self.runtime.acknowledge_ready(pid);
        self.handle_slice(pid, ctx)
    }
}

impl<T: ConnectionTransport> Drop for TransportConnectionProcess<T> {
    fn drop(&mut self) {
        if let Some(pid) = self.agent_connection {
            crate::agents::runtime::connection_closed(
                self.runtime.services(),
                pid,
                "transport_drop",
            );
        }
        // Backstop for termination paths that never run another handler slice:
        // external termination (killed via the scheduler) and scheduler shutdown
        // drop the handler directly. This drop does NOT reclaim the host record;
        // W4 leg 1 delivers that reclamation TOLD, the instant beamr publishes
        // the process's exit event, through the supervisor's exit-event reactor
        // into the ordinary `remove()` funnel (replacing the retired per-accept
        // `reap_crashed` scan for this class). On the explicit in-handler teardown
        // paths the conversation map is already drained, so this is a no-op there.
        self.release_conversations();
        let timers = self.state.pending_replies.take_retired_timers();
        self.runtime.cancel_deadline_timers(timers);
        #[cfg(test)]
        {
            let runtime = Arc::clone(&self.runtime);
            self.transport.note_process_drop(&runtime);
        }
    }
}

/// A connection's read half, asked whether inbound bytes are already waiting.
///
/// [`ConnectionProcess::final_probe`] answers "is there inbound work pending"
/// before the connection parks, and that one term of the probe is a transport
/// fact rather than a connection fact: a socket answers with a non-consuming
/// `peek`, a transport with no socket answers from its own queued bytes. The
/// remaining terms (subscriptions, participant publications, reply deadlines,
/// control, mailbox) are shared across transports unchanged, so a sibling
/// process type replaces only this answer.
pub(super) trait InboundPending {
    /// Whether readable bytes are already waiting, without consuming them.
    ///
    /// `Interrupted` reports pending (the probe never ran, so quiescence is not
    /// established); `WouldBlock` is the honest "nothing waiting".
    ///
    /// # Errors
    /// Returns [`ServerError::ListenerAccept`] when the read half fails the
    /// probe with anything other than `WouldBlock` or `Interrupted`.
    fn inbound_pending(&self) -> Result<bool, ServerError>;
}

/// What one non-blocking inbound read found.
///
/// Shared across transports so every door's hangup, idle, and progress answers
/// select the SAME lifecycle branch in [`TransportConnectionProcess::
/// service_socket`] — a sibling cannot map its own end of file onto a different
/// fate by classifying it differently.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ReadStatus {
    /// Bytes were appended to the buffer.
    Read,
    /// Nothing is available right now; the peer is still there.
    WouldBlock,
    /// End of file: the peer hung up and the read half is drained.
    Closed,
}