liminal-sdk 0.13.2

Application-facing SDK traits for liminal messaging clients
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
//! Remote participant state, durable client records, and typed transport outcomes.
//!
//! This module owns process mechanics only. Every participant lifecycle and
//! correlation decision is delegated to `liminal-protocol`; the SDK stores the
//! crate aggregate and its sealed one-use authorities without mirroring their
//! rules.

mod recovery;
mod replay_apply;

pub use recovery::{
    CredentialAttachReissueReason, LostCredentialAttachRefusalReason,
    RemoteCredentialAttachRecovery, RemoteDetachReplayOutcome, RemoteExpectedOperationRecovery,
    RemoteLostOperationResolution, RemoteLostReconnectResolution, RemoteReconnectAttemptOutcome,
    RemoteReconnectPermitRecovery, RemoteReplayApplyOutcome, RemoteTransportLossOutcome,
};

use alloc::sync::Arc;
use core::fmt;
use core::time::Duration;

use liminal_protocol::client::{
    ClientCorrelatedInboundDecision, ClientInboundDecision, ClientInboundRefusalReason,
    ClientOperationRecordDecision, ClientOperationRecordRefusalReason, ClientParticipantAggregate,
    ClientResponseCorrelation, ClientResumeRecord, ClientResumeRecordDecodeError,
    ClientResumeRecordEncodeError, ClientResumeRestoreError, ExpectedOperationFateRefusalReason,
    ExpectedOperationTransportFate, ExpectedParticipantOperation, ReconnectPermitDecision,
    decide_correlated_inbound, decide_inbound, record_expected_operation_fate,
    record_transport_fate,
};
use liminal_protocol::outcome::ReconnectDelayResult;
use liminal_protocol::wire::{
    ClientRequest, DeliverySeq, ParticipantFrame, RecordAdmissionEnvelope,
    RecordAdmissionFaultClass, ServerPush, ServerValue, ValidatedFrameLimit, encoded_len,
};
use spin::Mutex;

use crate::SdkError;

use super::protocol::{ParticipantTransportFrame, RemoteTransport};
use super::{RemoteConfig, ServerAddress};

/// Storage boundary for canonical `LPCR` client resume bytes.
///
/// Implementations must replace the previously committed bytes durably before
/// returning `Ok(())`. The SDK calls this boundary after the protocol crate's
/// commit seal and before releasing executable operation authority.
pub trait ParticipantResumeStore: Send {
    /// Durably replaces the stored canonical client resume record.
    ///
    /// # Errors
    ///
    /// Returns [`SdkError::Store`] when the bytes were not durably committed.
    fn persist(&mut self, canonical_lpcr: &[u8]) -> Result<(), SdkError>;
}

/// Transport-layer testimony identifying the connection attempt that delivered a frame.
///
/// This is the sealed transport context anticipated by rationale 15 in
/// `LP-CLIENT-GOAL`. It does not alter the wire format or relax the protocol
/// crate's conservative `RecordAdmission` ambiguity.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ParticipantResponseProvenance {
    connection_id: u64,
    attempt_id: u64,
}

impl ParticipantResponseProvenance {
    #[cfg(feature = "std")]
    pub(super) const fn new(connection_id: u64, attempt_id: u64) -> Self {
        Self {
            connection_id,
            attempt_id,
        }
    }

    /// Returns the local identity of the established socket.
    #[must_use]
    pub const fn connection_id(self) -> u64 {
        self.connection_id
    }

    /// Returns the local identity of the real connection attempt.
    #[must_use]
    pub const fn attempt_id(self) -> u64 {
        self.attempt_id
    }
}

/// Failure at the SDK participant state, codec, storage, or transport boundary.
#[derive(Debug, thiserror::Error)]
pub enum RemoteParticipantError {
    /// A prior commit could not be persisted, so no aggregate authority remains reachable.
    ///
    /// `source` is the RETAINED cause: the exact [`SdkError`] the caller's own
    /// store returned at the seam that bricked the handle. It travels on the
    /// error itself, so a caller who merely CAUGHT this value -- through a `?`,
    /// across a channel, out of a join -- can attribute the hold by matching a
    /// typed value rather than parsing rendered text. It is also this error's
    /// [`source`](core::error::Error::source).
    ///
    /// A `None` means the aggregate is unreachable for a reason that did not
    /// originate in the store. That discrimination is why the field is an
    /// `Option` and not an `SdkError`: there is no store failure to name, so
    /// [`source`](core::error::Error::source) reports `None` rather than
    /// inventing a link, and the rendered message drops the durability clause it
    /// would otherwise be asserting without evidence.
    #[error(
        "participant state is unavailable{}",
        source.as_ref().map_or("", |_| " after an unreleased durability failure")
    )]
    StateUnavailable {
        /// The store failure that made the aggregate unreachable, when that is why.
        #[source]
        source: Option<SdkError>,
    },
    /// The protocol crate could not encode the current aggregate as canonical LPCR.
    #[error("client resume record encode failed: {0:?}")]
    ResumeEncode(ClientResumeRecordEncodeError),
    /// Persisted bytes were not a canonical LPCR record.
    #[error("client resume record decode failed: {0:?}")]
    ResumeDecode(ClientResumeRecordDecodeError),
    /// Canonical facts violated a protocol restore invariant.
    #[error("client resume record restore failed: {0:?}")]
    ResumeRestore(ClientResumeRestoreError),
    /// The caller-owned durable store rejected a canonical record.
    ///
    /// The `SdkError` is exposed as this error's [`source`](core::error::Error::source)
    /// so a caller can walk to the typed store failure instead of matching on
    /// rendered text.
    #[error("client resume record persistence failed: {0}")]
    Storage(#[source] SdkError),
    /// The real transport failed outside a typed fate-reporting operation.
    ///
    /// The `SdkError` is exposed as this error's [`source`](core::error::Error::source),
    /// for the same reason as [`Storage`](RemoteParticipantError::Storage).
    #[error("participant transport failed: {0}")]
    Transport(#[source] SdkError),
    /// A client-to-server request appeared on the SDK receive side.
    #[error("participant transport decoded a request in the client receive direction")]
    InvalidInboundDirection,
    /// No live response correlation exists for a replay-specific input.
    #[error("no live participant response authority is held")]
    ResponseAuthorityUnavailable,
    /// A declared participant frame limit was outside the protocol's bounds.
    #[error("declared participant frame limit {max_frame_bytes} is outside the protocol's bounds")]
    InvalidFrameLimit {
        /// The limit as declared.
        max_frame_bytes: u64,
    },
    /// The request's complete participant frame exceeds the declared frame limit.
    ///
    /// Reported by [`record_operation`](RemoteParticipantHandle::record_operation)
    /// BEFORE any write-ahead authority is spent or any byte reaches the wire, so
    /// the operation that follows is not refused as outstanding. The request comes
    /// back unchanged. Without a declared limit the broker's transport gate would
    /// answer such a frame with a pre-semantic `ParticipantTransportRejected`
    /// (`FrameTooLarge`), which is never an answer to the operation and leaves it
    /// outstanding forever (manifold #session.feed, 2026-09-11 12:57Z).
    #[error(
        "request frame of {complete_frame_bytes} bytes exceeds the declared participant frame limit of {max_frame_bytes} bytes"
    )]
    RequestExceedsFrameLimit {
        /// The request, returned unchanged; nothing was recorded or sent.
        request: ClientRequest,
        /// Header plus payload bytes of the frame the request would have made.
        complete_frame_bytes: u64,
        /// The declared limit it exceeds.
        max_frame_bytes: u64,
    },
}

/// Opaque one-use operation released only after the SDK persisted sealed LPCR bytes.
#[derive(Debug)]
pub struct RemoteParticipantOperation {
    operation: ExpectedParticipantOperation,
    durability: OperationDurability,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum OperationDurability {
    WriteAhead,
    Continuous,
}

/// Result of admitting an outbound request through the crate write-ahead barrier.
#[derive(Debug)]
pub enum RemoteOperationRecordOutcome {
    /// Canonical LPCR bytes were persisted and one operation may now be sent.
    Recorded(RemoteParticipantOperation),
    /// A continuous acknowledgement bypassed the write-ahead slot by crate rule.
    Continuous(RemoteParticipantOperation),
    /// The crate refused the exact request without changing aggregate state.
    Refused {
        /// Exact refused request.
        request: ClientRequest,
        /// Closed protocol refusal reason.
        reason: ClientOperationRecordRefusalReason,
    },
}

/// Typed operation-domain consequence of an established transport loss.
#[derive(Debug, PartialEq, Eq)]
pub enum RemoteOperationTransportFate {
    /// A non-detach operation's response became unavailable.
    Recorded {
        /// Exact terminalized request.
        request: ClientRequest,
    },
    /// The exact detach was returned to parked replay.
    DetachParked,
    /// The crate retained the live correlation unchanged.
    Refused {
        /// Closed refusal reason from the generic operation-fate gate.
        reason: ExpectedOperationFateRefusalReason,
    },
    /// No response authority was outstanding.
    NotOutstanding,
}

/// Typed reconnect permit returned by a crate-authorized fresh event.
#[derive(Debug)]
pub struct RemoteReconnectPermit {
    pub(super) permit: liminal_protocol::client::ReconnectAttemptPermit,
}

/// Event-driven reconnect permit decision; there is no delay or timer arm.
#[derive(Debug)]
pub enum RemoteReconnectPermitOutcome {
    /// The crate minted one one-use permit.
    Permitted {
        /// Opaque permit for one real connection attempt.
        permit: RemoteReconnectPermit,
        /// Legacy-named crate result whose value is event-only.
        result: ReconnectDelayResult,
    },
    /// Existing authority was retained.
    Refused {
        /// Closed crate refusal reason.
        reason: liminal_protocol::client::ReconnectPermitRefusalReason,
        /// Event-only crate result.
        result: ReconnectDelayResult,
    },
}

/// Result of sending an operation on the participant transport.
#[derive(Debug)]
pub enum RemoteParticipantSendOutcome {
    /// The request bytes were written on this connection attempt.
    Sent {
        /// Sealed transport context for a later response.
        provenance: ParticipantResponseProvenance,
    },
    /// The write failed and both operation and reconnect fates were delegated.
    TransportLost {
        /// Concrete socket failure.
        error: SdkError,
        /// Crate-owned operation-fate result.
        operation_fate: RemoteOperationTransportFate,
        /// Crate-owned reconnect permit result.
        reconnect: RemoteReconnectPermitOutcome,
    },
}

/// Default quiet window for [`RemoteParticipantHandle::try_receive`].
///
/// Deliberately ONE steady-state transport receive window rather than a new
/// number of its own: that is the grain both transports already poll on, and it
/// is the shape consumers' drain loops were written against before a total
/// response deadline was layered above it. A pump that reports quiet after one
/// closed window is the behaviour they expect; the deadline above it is the
/// reply-owed protection they were never asking for.
pub const PARTICIPANT_PUMP_WINDOW: Duration = super::framing::IO_TIMEOUT;

/// Typed result of one decoded participant frame on the real receive path.
#[derive(Debug)]
pub enum RemoteParticipantInbound {
    /// The protocol crate correlated and applied a semantic response.
    Applied {
        /// Exact applied server value.
        value: ServerValue,
        /// Connection/attempt that delivered it.
        provenance: ParticipantResponseProvenance,
    },
    /// The protocol crate retained the response and aggregate unchanged.
    Refused {
        /// Exact refused server value.
        value: ServerValue,
        /// Closed crate refusal reason, including conservative ambiguity.
        reason: ClientInboundRefusalReason,
        /// Connection/attempt that delivered it.
        provenance: ParticipantResponseProvenance,
    },
    /// Server push decoded in the client direction; no correlation rule applies.
    Push {
        /// Exact pushed value.
        value: ServerPush,
        /// Connection/attempt that delivered it.
        provenance: ParticipantResponseProvenance,
    },
}

/// TERMINAL fate of one ordinary record admission, read off the server's own
/// answer.
///
/// ## The contract this exists to state
///
/// A carrier that write-aheads its records needs exactly one bit from every
/// inbound: MAY I CLEAR THE SLOT? Before this type there was no way to ask it.
/// A server refusal arrived as `RemoteParticipantInbound::Applied { value }` —
/// an `Ok`, type-indistinguishable from a commit — and
/// [`committed_delivery_seq`](RemoteParticipantInbound::committed_delivery_seq)
/// folded every refusal into the same `None` as "not a record answer at all".
/// So a carrier could only distinguish them by matching the wire enum itself,
/// and the 2026-08-28 field carrier did the safe thing instead: it treated
/// everything that was not a commit as unknown, kept the slot, and retried
/// forever.
///
/// Terminal means: the answer will not change. Clear the write-ahead slot.
/// [`Committed`](Self::Committed) clears it because the record is durable;
/// [`ProtocolFault`](Self::ProtocolFault) clears it because re-presenting the
/// same bytes will be refused identically on every boot, so the retry is not a
/// recovery, it is the incident.
///
/// Everything that is NOT terminal keeps the slot, and it stays outside this
/// type by construction rather than by a variant a caller could misread:
///
/// - **Transient refusals** (`ObserverBackpressure`,
///   `MarkerSettlementBackpressure`, and the rest) are still
///   [`Applied`](RemoteParticipantInbound::Applied) values, and
///   [`record_admission_fate`](RemoteParticipantInbound::record_admission_fate)
///   answers `None` for them. Their whole `ServerValue` remains available on
///   the inbound for a caller that wants to schedule its retry.
/// - **Connection loss** never produces a `RemoteParticipantInbound` at all: it
///   surfaces on the send side as
///   [`RemoteParticipantSendOutcome::TransportLost`] and on the receive side as
///   `Err(RemoteParticipantError::Transport(..))`. Fate-unknown is a different
///   `Result` position, not a fate.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RecordAdmissionFate {
    /// The record is durable at this delivery sequence.
    Committed {
        /// Echoed common request envelope of the admitted record.
        request: RecordAdmissionEnvelope,
        /// Sequence the server assigned.
        delivery_seq: DeliverySeq,
    },
    /// The spine named an internal protocol fault and terminally refused.
    ///
    /// The class is coarse on purpose — the fault's full detail stays in the
    /// SERVER's log. What reaches here is enough to dead-letter the record and
    /// raise an operator signal, which is the only correct response.
    ProtocolFault {
        /// Echoed common request envelope of the refused record.
        request: RecordAdmissionEnvelope,
        /// Coarse class of the fault the spine named.
        class: RecordAdmissionFaultClass,
    },
}

impl RecordAdmissionFate {
    /// Borrows the echoed request envelope, whichever fate this is.
    #[must_use]
    pub const fn request(&self) -> &RecordAdmissionEnvelope {
        match self {
            Self::Committed { request, .. } | Self::ProtocolFault { request, .. } => request,
        }
    }

    /// Whether the record reached durability.
    ///
    /// Both variants are terminal — that is what makes this type the answer to
    /// "may I clear the slot?" — so `is_committed` is deliberately the question
    /// asked here, and terminality is carried by the `Option` around the fate
    /// rather than by a predicate that would always be `true`.
    #[must_use]
    pub const fn is_committed(&self) -> bool {
        matches!(self, Self::Committed { .. })
    }
}

impl RemoteParticipantInbound {
    /// The TERMINAL fate of a record admission, when this inbound settles one.
    ///
    /// `Some` exactly for an APPLIED commit or an APPLIED terminal protocol
    /// fault. `None` for every transient refusal, every value answering another
    /// operation, every [`Push`](Self::Push), and — deliberately — for every
    /// [`Refused`](Self::Refused): the crate declined to correlate that value,
    /// so it settles nothing and the carrier's slot stays.
    ///
    /// Transport-agnostic by construction. Both the wire and the in-process
    /// loopback transport decode through the same codec and land in the same
    /// `apply_inbound`, so a carrier written against this reads the same fate
    /// either way.
    #[must_use]
    pub fn record_admission_fate(&self) -> Option<RecordAdmissionFate> {
        let Self::Applied { value, .. } = self else {
            return None;
        };
        match value {
            ServerValue::RecordCommitted(committed) => Some(RecordAdmissionFate::Committed {
                request: committed.request().clone(),
                delivery_seq: committed.delivery_seq(),
            }),
            ServerValue::RecordAdmissionProtocolFault(fault) => {
                Some(RecordAdmissionFate::ProtocolFault {
                    request: fault.request.clone(),
                    class: fault.class,
                })
            }
            _ => None,
        }
    }

    /// The record sequence the server assigned an admitted record, when this
    /// inbound is an APPLIED [`ServerValue::RecordCommitted`].
    ///
    /// This is the answer to a `RecordAdmission`, read off the exact wire value
    /// the protocol crate applied. It saves every caller destructuring the wire
    /// enum to reach the one number a record admission is asked for, without
    /// removing that value: [`Applied`](Self::Applied) still carries the whole
    /// `ServerValue`, so this is purely additive.
    ///
    /// `None` for everything else, and that includes a `RecordCommitted` the
    /// crate REFUSED. A refused commit carries a sequence on the wire while
    /// leaving the aggregate and its correlation untouched -- returning it here
    /// would report a commitment the crate deliberately declined to make. It is
    /// also `None` for a [`Push`](Self::Push), which is a delivery rather than
    /// a correlated response.
    #[must_use]
    pub const fn committed_delivery_seq(&self) -> Option<DeliverySeq> {
        match self {
            Self::Applied {
                value: ServerValue::RecordCommitted(committed),
                ..
            } => Some(committed.delivery_seq()),
            Self::Applied { .. } | Self::Refused { .. } | Self::Push { .. } => None,
        }
    }
}

pub(super) struct RemoteParticipantState<S> {
    pub(super) aggregate: Option<ClientParticipantAggregate>,
    pub(super) correlation: Option<ClientResponseCorrelation>,
    pub(super) reconnect_attempt: Option<liminal_protocol::client::ReconnectInProgressAttempt>,
    /// The caller-declared complete-frame limit every outbound request is
    /// measured against before it is recorded. `None` declares nothing and
    /// leaves the broker's transport gate as the only bound.
    pub(super) frame_limit: Option<ValidatedFrameLimit>,
    pub(super) store: S,
    /// The store failure that made the aggregate unreachable, if that is why.
    ///
    /// The failure itself is returned to whoever made the failing call and to
    /// nobody else. This retains it so the question "why is this handle dead"
    /// has a typed answer for every later caller: `take_aggregate` reads it back
    /// out of here onto the
    /// [`StateUnavailable`](RemoteParticipantError::StateUnavailable) it reports,
    /// and [`unavailability_cause`](RemoteParticipantHandle::unavailability_cause)
    /// answers it without a failing call.
    pub(super) unavailable: Option<SdkError>,
}

impl<S> RemoteParticipantState<S> {
    /// Records a store failure as the reason the aggregate is about to become
    /// unreachable, and names that failure for the caller.
    ///
    /// Every seam that drops the aggregate on a store failure goes through here,
    /// so the retained cause cannot drift from the returned one: they are the
    /// same value.
    pub(super) fn brick(&mut self, error: SdkError) -> RemoteParticipantError {
        self.unavailable = Some(error.clone());
        RemoteParticipantError::Storage(error)
    }
}

/// Remote participant entrypoint backed by protocol-crate state and canonical LPCR storage.
///
/// Records are deliberately not promised as generally successful: the reduced-B1
/// server surface fails fully authorized `RecordAdmission` and `Leave` closed until
/// live claim-frontier acquisition lands (`docs/design/LP-GAP-CLOSURE-GOAL.md:145`).
pub struct RemoteParticipantHandle<S> {
    pub(super) server_address: ServerAddress,
    pub(super) transport: Arc<dyn RemoteTransport>,
    pub(super) state: Mutex<RemoteParticipantState<S>>,
}

impl<S> fmt::Debug for RemoteParticipantHandle<S> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RemoteParticipantHandle")
            .field("server_address", &self.server_address)
            .finish_non_exhaustive()
    }
}

impl<S: ParticipantResumeStore> RemoteParticipantHandle<S> {
    /// Creates and durably checkpoints a fresh unbound participant.
    ///
    /// # Errors
    ///
    /// Returns a typed encode or storage error before the handle is exposed.
    pub fn new(config: &RemoteConfig, store: S) -> Result<Self, RemoteParticipantError> {
        Self::from_aggregate(config, store, ClientParticipantAggregate::new())
    }

    /// Decodes, validates, restores, and durably records crash testimony before exposure.
    ///
    /// # Errors
    ///
    /// Returns typed LPCR decode/restore, encode, or storage errors.
    pub fn restore(
        config: &RemoteConfig,
        store: S,
        canonical_lpcr: &[u8],
    ) -> Result<Self, RemoteParticipantError> {
        let record = ClientResumeRecord::decode_canonical(canonical_lpcr)
            .map_err(RemoteParticipantError::ResumeDecode)?;
        let aggregate = record
            .restore()
            .map_err(RemoteParticipantError::ResumeRestore)?;
        Self::from_aggregate(config, store, aggregate)
    }

    fn from_aggregate(
        config: &RemoteConfig,
        mut store: S,
        aggregate: ClientParticipantAggregate,
    ) -> Result<Self, RemoteParticipantError> {
        persist(&mut store, &aggregate)?;
        Ok(Self {
            server_address: config.server_address.clone(),
            transport: Arc::clone(&config.transport),
            state: Mutex::new(RemoteParticipantState {
                aggregate: Some(aggregate),
                correlation: None,
                reconnect_attempt: None,
                frame_limit: None,
                store,
                unavailable: None,
            }),
        })
    }

    /// Returns the store failure that made this handle unavailable, if that is
    /// why it is unavailable.
    ///
    /// A `Some` names the exact [`SdkError`] the caller's own store returned, so
    /// a hold can be attributed by matching a typed value. A `None` means the
    /// handle is either live or unavailable for a reason that did not originate
    /// in the store — which is itself the discrimination this exists to provide.
    ///
    /// The same retained value is carried on
    /// [`StateUnavailable`](RemoteParticipantError::StateUnavailable) and is that
    /// error's [`source`](core::error::Error::source), so a caller who CAUGHT
    /// that error already holds the cause and does not need this. This accessor
    /// answers the other question — one asked of a handle you still HOLD, rather
    /// than of an error you caught — and it answers it without making a call
    /// that must fail in order to find out. Its `None` therefore covers one case
    /// the variant's `None` cannot: a handle that is simply still live.
    #[must_use]
    pub fn unavailability_cause(&self) -> Option<SdkError> {
        self.state.lock().unavailable.clone()
    }

    /// Runs `record_operation -> commit -> LPCR persist -> into_parts` exactly.
    ///
    /// # Errors
    ///
    /// Returns typed resume encoding or storage failures. A failed post-commit
    /// persistence leaves the handle unavailable and releases no authority.
    pub fn record_operation(
        &self,
        request: ClientRequest,
    ) -> Result<RemoteOperationRecordOutcome, RemoteParticipantError> {
        let mut state = self.state.lock();
        if let Some(limit) = state.frame_limit {
            let complete_frame_bytes = request_frame_bytes(&request)?;
            if complete_frame_bytes > limit.get() {
                return Err(RemoteParticipantError::RequestExceedsFrameLimit {
                    request,
                    complete_frame_bytes,
                    max_frame_bytes: limit.get(),
                });
            }
        }
        let aggregate = take_aggregate(&mut state)?;
        match liminal_protocol::client::record_operation(aggregate, request) {
            ClientOperationRecordDecision::Pending(pending) => {
                let commit = pending.commit();
                let record = commit
                    .resume_record()
                    .map_err(RemoteParticipantError::ResumeEncode)?;
                if let Err(error) = state.store.persist(&record.encode_canonical()) {
                    return Err(state.brick(error));
                }
                let (aggregate, operation) = commit.into_parts();
                state.aggregate = Some(aggregate);
                Ok(RemoteOperationRecordOutcome::Recorded(
                    RemoteParticipantOperation {
                        operation,
                        durability: OperationDurability::WriteAhead,
                    },
                ))
            }
            ClientOperationRecordDecision::Continuous(continuous) => {
                let (aggregate, operation) = continuous.into_parts();
                state.aggregate = Some(aggregate);
                Ok(RemoteOperationRecordOutcome::Continuous(
                    RemoteParticipantOperation {
                        operation,
                        durability: OperationDurability::Continuous,
                    },
                ))
            }
            ClientOperationRecordDecision::Refused(refusal) => {
                let reason = refusal.reason();
                let (aggregate, request) = refusal.into_parts();
                state.aggregate = Some(aggregate);
                Ok(RemoteOperationRecordOutcome::Refused { request, reason })
            }
        }
    }

    /// Declares the complete participant frame limit this handle's requests
    /// must fit inside.
    ///
    /// The broker never announces its participant frame limit (the connect
    /// acknowledgement carries only a capability bitfield), so the caller that
    /// configured the broker declares the same number here. From then on
    /// [`record_operation`](Self::record_operation) refuses a request whose
    /// complete frame would exceed it, typed and before any authority is spent,
    /// instead of letting the broker's transport gate reject the frame after the
    /// write-ahead slot is already taken. `None` withdraws the declaration.
    ///
    /// # Errors
    ///
    /// Returns [`RemoteParticipantError::InvalidFrameLimit`] when the value is
    /// outside the protocol's bounds for a participant frame limit.
    pub fn declare_frame_limit(
        &self,
        max_frame_bytes: Option<u64>,
    ) -> Result<(), RemoteParticipantError> {
        let limit = match max_frame_bytes {
            Some(value) => Some(ValidatedFrameLimit::new(value).map_err(|_| {
                RemoteParticipantError::InvalidFrameLimit {
                    max_frame_bytes: value,
                }
            })?),
            None => None,
        };
        self.state.lock().frame_limit = limit;
        Ok(())
    }

    /// The declared complete participant frame limit, if any.
    #[must_use]
    pub fn frame_limit(&self) -> Option<u64> {
        self.state.lock().frame_limit.map(ValidatedFrameLimit::get)
    }

    /// Persists issued state, writes the exact operation, and retains correlation.
    ///
    /// # Errors
    ///
    /// Returns typed state, LPCR, or storage failures. Transport failures are
    /// returned as a typed outcome after crate fate delegation.
    pub fn send_operation(
        &self,
        operation: RemoteParticipantOperation,
    ) -> Result<RemoteParticipantSendOutcome, RemoteParticipantError> {
        let mut state = self.state.lock();
        let mut aggregate = take_aggregate(&mut state)?;
        if operation.durability == OperationDurability::WriteAhead {
            aggregate = persist_retaining(&mut state, aggregate)?;
        }
        let (request, correlation) = operation.operation.into_request();
        match self
            .transport
            .send_participant(&self.server_address, &request)
        {
            Ok(provenance) => {
                if operation.durability == OperationDurability::WriteAhead {
                    state.correlation = Some(correlation);
                }
                state.aggregate = Some(aggregate);
                Ok(RemoteParticipantSendOutcome::Sent { provenance })
            }
            Err(error) => {
                let operation_fate = if operation.durability == OperationDurability::WriteAhead {
                    record_operation_transport_fate(&mut state, aggregate, correlation)
                } else {
                    state.aggregate = Some(aggregate);
                    RemoteOperationTransportFate::NotOutstanding
                };
                let reconnect = record_connection_fate(&mut state)?;
                Ok(RemoteParticipantSendOutcome::TransportLost {
                    error,
                    operation_fate,
                    reconnect,
                })
            }
        }
    }

    /// Receives one real participant frame and delegates every `ServerValue` to the crate.
    ///
    /// # The contract, and why it is this one
    ///
    /// THIS IS THE REPLY-OWED DOOR. It blocks for up to the transport's full
    /// response deadline (60 s), because the caller it is written for has just
    /// sent a request and is waiting for the correlated answer — and there, a
    /// quiet connection means a slow server, not a dead one. Ending that wait
    /// early is the 2026-08-10 outage's client-side mechanism, so this method
    /// keeps the deadline unchanged and unconditionally.
    ///
    /// A consumer PUMPING an idle connection — looping to collect whatever the
    /// server pushes next, where silence is a normal state rather than a fault
    /// — must use [`receive_within`](Self::receive_within) or
    /// [`try_receive`](Self::try_receive) instead. That is not a preference: a
    /// drain loop built on this method waits out the full deadline on every
    /// quiet read, which is how a 30 s boot gate blows on a healthy server.
    ///
    /// The split is by CALLER INTENT and cannot be anything else. At a clean
    /// frame boundary with an empty buffer, a pump read and an outage-shaped
    /// reply-owed read are byte-for-byte identical states; only the caller
    /// knows which one it is making, so only the caller's choice of method can
    /// carry it. Inferring it from buffered bytes, or from whether an operation
    /// is outstanding, would silently shorten the deadline for some class of
    /// genuinely reply-owed read and re-open the outage for it.
    ///
    /// Pushed deliveries are at-least-once: the same
    /// `(conversation_id, delivery_seq)` may arrive more than once on one
    /// healthy connection, byte-identical each time — deduplicate on the pair
    /// (participant contract R-C3, amendment A3).
    ///
    /// # Errors
    ///
    /// Returns transport, direction, LPCR encoding, or storage failures.
    pub fn receive(&self) -> Result<RemoteParticipantInbound, RemoteParticipantError> {
        let frame = self
            .transport
            .receive_participant(&self.server_address)
            .map_err(RemoteParticipantError::Transport)?;
        self.classify_inbound(frame)
    }

    /// Receives one participant frame if one arrives within `budget`, reporting
    /// a quiet connection as `Ok(None)` instead of an error.
    ///
    /// THE PUMP DOOR — the lawful read for a consumer that is owed nothing.
    /// `Ok(None)` means "no frame within this window", which is a normal state
    /// on a healthy connection and never a fault; a real transport failure
    /// still returns `Err`, and a quiet window never surfaces a raw errno.
    ///
    /// `budget` is the CALLER'S bound and is spent across as many transport
    /// read windows as it takes. It never shortens anything else: a caller that
    /// uses this method to await a correlated answer simply names its own
    /// deadline, and passing one at or above the transport's 60 s response
    /// deadline reproduces [`receive`](Self::receive)'s patience with a typed
    /// silence at the end instead of an error.
    ///
    /// `Duration::ZERO` polls only what has already decoded, without arming a
    /// read. Bytes of a partly-arrived frame stay buffered across an
    /// `Ok(None)`, so a frame that was mid-flight when the budget expired is
    /// never lost — the next call resumes on it.
    ///
    /// # Errors
    ///
    /// Returns transport, direction, LPCR encoding, or storage failures. A
    /// quiet window is NOT one of them.
    pub fn receive_within(
        &self,
        budget: Duration,
    ) -> Result<Option<RemoteParticipantInbound>, RemoteParticipantError> {
        let Some(frame) = self
            .transport
            .receive_participant_within(&self.server_address, budget)
            .map_err(RemoteParticipantError::Transport)?
        else {
            return Ok(None);
        };
        self.classify_inbound(frame).map(Some)
    }

    /// One [`PARTICIPANT_PUMP_WINDOW`] of patience, then `Ok(None)`.
    ///
    /// The drain-loop convenience over [`receive_within`](Self::receive_within):
    /// a consumer that wants "give me the next frame, or tell me the connection
    /// is quiet" without choosing a number. Loop it until it answers `Ok(None)`
    /// and the backlog is drained.
    ///
    /// # Errors
    ///
    /// As [`receive_within`](Self::receive_within).
    pub fn try_receive(&self) -> Result<Option<RemoteParticipantInbound>, RemoteParticipantError> {
        self.receive_within(PARTICIPANT_PUMP_WINDOW)
    }

    /// Routes one decoded transport frame into the crate's inbound decisions.
    ///
    /// Shared by [`receive`](Self::receive) and
    /// [`receive_within`](Self::receive_within) so the two doors differ ONLY in
    /// how long they wait for a frame. Every correlation, application, and
    /// refusal rule below is reached identically by both — a pump read that
    /// does find a frame applies it exactly as a reply-owed read would.
    fn classify_inbound(
        &self,
        frame: ParticipantTransportFrame,
    ) -> Result<RemoteParticipantInbound, RemoteParticipantError> {
        let ParticipantTransportFrame { frame, provenance } = frame;
        match frame {
            ParticipantFrame::ServerPush(value) => {
                Ok(RemoteParticipantInbound::Push { value, provenance })
            }
            ParticipantFrame::ClientRequest(_) => {
                Err(RemoteParticipantError::InvalidInboundDirection)
            }
            ParticipantFrame::ServerValue(value) => self.apply_inbound(value, provenance),
        }
    }

    fn apply_inbound(
        &self,
        value: ServerValue,
        provenance: ParticipantResponseProvenance,
    ) -> Result<RemoteParticipantInbound, RemoteParticipantError> {
        let mut state = self.state.lock();
        let aggregate = take_aggregate(&mut state)?;
        if let Some(correlation) = state.correlation.take() {
            match decide_correlated_inbound(aggregate, value, correlation) {
                ClientCorrelatedInboundDecision::Applied(applied) => {
                    let (aggregate, value) = applied.into_parts();
                    let aggregate = persist_retaining(&mut state, aggregate)?;
                    state.aggregate = Some(aggregate);
                    Ok(RemoteParticipantInbound::Applied { value, provenance })
                }
                ClientCorrelatedInboundDecision::AppliedRetaining(retained) => {
                    // The value applied without answering the outstanding
                    // operation, so its response authority is kept until the
                    // actual answer arrives. Seated before the persist so a
                    // failed persist bricks the handle with the authority in
                    // place rather than silently spent.
                    let (aggregate, value, correlation) = retained.into_parts();
                    state.correlation = Some(correlation);
                    let aggregate = persist_retaining(&mut state, aggregate)?;
                    state.aggregate = Some(aggregate);
                    Ok(RemoteParticipantInbound::Applied { value, provenance })
                }
                ClientCorrelatedInboundDecision::Refused(refusal) => {
                    let reason = refusal.reason();
                    let (aggregate, value, correlation) = refusal.into_parts();
                    state.aggregate = Some(aggregate);
                    state.correlation = Some(correlation);
                    Ok(RemoteParticipantInbound::Refused {
                        value,
                        reason,
                        provenance,
                    })
                }
            }
        } else {
            match decide_inbound(aggregate, value) {
                ClientInboundDecision::Applied(applied) => {
                    let (aggregate, value) = applied.into_parts();
                    let aggregate = persist_retaining(&mut state, aggregate)?;
                    state.aggregate = Some(aggregate);
                    Ok(RemoteParticipantInbound::Applied { value, provenance })
                }
                ClientInboundDecision::Refused(refusal) => {
                    let reason = refusal.reason();
                    let (aggregate, value) = refusal.into_parts();
                    state.aggregate = Some(aggregate);
                    Ok(RemoteParticipantInbound::Refused {
                        value,
                        reason,
                        provenance,
                    })
                }
            }
        }
    }
}

/// Header plus payload bytes of the participant frame `request` encodes to:
/// the same number the broker's transport gate measures as the declared
/// complete frame.
fn request_frame_bytes(request: &ClientRequest) -> Result<u64, RemoteParticipantError> {
    let frame = ParticipantFrame::ClientRequest(request.clone());
    let needed = encoded_len(&frame).map_err(|error| {
        RemoteParticipantError::Transport(SdkError::Protocol {
            description: alloc::format!("participant request frame could not be sized: {error:?}"),
        })
    })?;
    u64::try_from(needed).map_err(|_| {
        RemoteParticipantError::Transport(SdkError::Protocol {
            description: alloc::format!(
                "participant request frame length {needed} does not fit the wire's u64"
            ),
        })
    })
}

pub(super) fn take_aggregate<S>(
    state: &mut RemoteParticipantState<S>,
) -> Result<ClientParticipantAggregate, RemoteParticipantError> {
    let aggregate = state.aggregate.take();
    aggregate.ok_or_else(|| RemoteParticipantError::StateUnavailable {
        source: state.unavailable.clone(),
    })
}

pub(super) fn persist<S: ParticipantResumeStore>(
    store: &mut S,
    aggregate: &ClientParticipantAggregate,
) -> Result<(), RemoteParticipantError> {
    let record = aggregate
        .resume_record()
        .map_err(RemoteParticipantError::ResumeEncode)?;
    store
        .persist(&record.encode_canonical())
        .map_err(RemoteParticipantError::Storage)
}

/// Persists `aggregate`, returning it to the caller on success and RE-SEATING it
/// in `state` when encoding refused.
///
/// The two failure modes are not alike, and the difference is durability
/// ambiguity:
///
/// * [`RemoteParticipantError::Storage`] means the store was asked to commit
///   bytes and did not say it succeeded. Whether those bytes landed is unknown,
///   so no further authority may be released from this aggregate. The handle
///   is deliberately left bricked and the next call reports
///   [`StateUnavailable`](RemoteParticipantError::StateUnavailable) -- the
///   contract documented on that variant.
/// * [`RemoteParticipantError::ResumeEncode`] means `resume_record`, a pure
///   function of the aggregate, refused. Nothing was written and no authority
///   was released, so there is nothing ambiguous to protect. Dropping the
///   aggregate here converts a typed, catchable refusal into a permanently dead
///   participant.
///
/// The re-seat lives in this function rather than at each seam on purpose: the
/// SDK has ten `take_aggregate` -> persist -> re-seat sites, the `?` skips the
/// re-seat at every one of them, and a new seam would inherit the same bug.
/// Here it cannot be forgotten.
///
/// A caller that still needs the aggregate takes it back from the `Ok`; a
/// caller that does not re-seats it itself. On the `ResumeEncode` path the
/// aggregate is already seated, so callers must not seat it again.
pub(super) fn persist_retaining<S: ParticipantResumeStore>(
    state: &mut RemoteParticipantState<S>,
    aggregate: ClientParticipantAggregate,
) -> Result<ClientParticipantAggregate, RemoteParticipantError> {
    match aggregate.resume_record() {
        Ok(record) => match state.store.persist(&record.encode_canonical()) {
            Ok(()) => Ok(aggregate),
            // The aggregate is deliberately NOT re-seated: whether the bytes
            // landed is unknown, so no further authority may be released. The
            // cause is retained on the way past, because it is about to be the
            // only thing that could ever explain the `StateUnavailable` every
            // later call will report.
            Err(error) => Err(state.brick(error)),
        },
        Err(error) => {
            state.aggregate = Some(aggregate);
            Err(RemoteParticipantError::ResumeEncode(error))
        }
    }
}

fn record_operation_transport_fate<S: ParticipantResumeStore>(
    state: &mut RemoteParticipantState<S>,
    aggregate: ClientParticipantAggregate,
    correlation: ClientResponseCorrelation,
) -> RemoteOperationTransportFate {
    match record_expected_operation_fate(
        aggregate,
        correlation,
        ExpectedOperationTransportFate::ResponseUnavailable,
    ) {
        liminal_protocol::client::ExpectedOperationFateDecision::Recorded {
            aggregate,
            request,
            ..
        } => {
            state.aggregate = Some(aggregate);
            RemoteOperationTransportFate::Recorded { request }
        }
        liminal_protocol::client::ExpectedOperationFateDecision::Refused {
            aggregate,
            correlation,
            reason: ExpectedOperationFateRefusalReason::DetachUsesReplayFate,
            ..
        } => match liminal_protocol::client::transport_fate(
            aggregate,
            correlation,
            liminal_protocol::client::DetachTransportFate::ResponseUnavailable,
        ) {
            liminal_protocol::client::DetachTransportFateDecision::Parked(applied) => {
                state.aggregate = Some(applied.into_aggregate());
                RemoteOperationTransportFate::DetachParked
            }
            liminal_protocol::client::DetachTransportFateDecision::Refused(refusal) => {
                let (aggregate, (correlation, _)) = refusal.into_parts();
                state.aggregate = Some(aggregate);
                state.correlation = Some(correlation);
                RemoteOperationTransportFate::Refused {
                    reason: ExpectedOperationFateRefusalReason::DetachUsesReplayFate,
                }
            }
        },
        liminal_protocol::client::ExpectedOperationFateDecision::Refused {
            aggregate,
            correlation,
            reason,
            ..
        } => {
            state.aggregate = Some(aggregate);
            state.correlation = Some(correlation);
            RemoteOperationTransportFate::Refused { reason }
        }
    }
}

pub(super) fn record_connection_fate<S: ParticipantResumeStore>(
    state: &mut RemoteParticipantState<S>,
) -> Result<RemoteReconnectPermitOutcome, RemoteParticipantError> {
    let aggregate = take_aggregate(state)?;
    let (aggregate, outcome) = match record_transport_fate(
        aggregate,
        liminal_protocol::client::EstablishedConnectionTransportFate::Lost,
    ) {
        ReconnectPermitDecision::Permitted {
            aggregate,
            permit,
            result,
        } => (
            aggregate,
            RemoteReconnectPermitOutcome::Permitted {
                permit: RemoteReconnectPermit { permit },
                result,
            },
        ),
        ReconnectPermitDecision::Refused(refusal) => {
            let reason = refusal.reason();
            let result = refusal.result();
            let (aggregate, _) = refusal.into_parts();
            (
                aggregate,
                RemoteReconnectPermitOutcome::Refused { reason, result },
            )
        }
    };
    let aggregate = persist_retaining(state, aggregate)?;
    state.aggregate = Some(aggregate);
    Ok(outcome)
}

#[cfg(test)]
mod tests;