liminal-protocol 0.2.0

Shared participant-lifecycle protocol types for liminal
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
use crate::outcome::CandidatePhase;
use crate::wire::{
    BindingEpoch, CloseCause, ConversationId, DeliverySeq, DetachedCause, DiedCause, ParticipantId,
    ParticipantIndex, TransactionOrder,
};

/// Stable admission ordering key for one lifecycle candidate.
///
/// The phase is the canonical typed protocol phase rather than a free integer.
/// Binding-terminal transitions below additionally fix it to
/// [`CandidatePhase::BindingTerminal`] and derive the participant index from
/// the participant identifier, which is exactly that permanent index in v1.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct AdmissionOrder {
    transaction_order: TransactionOrder,
    candidate_phase: CandidatePhase,
    participant_index: ParticipantIndex,
}

impl AdmissionOrder {
    /// Creates an order for a typed lifecycle candidate.
    #[must_use]
    pub const fn new(
        transaction_order: TransactionOrder,
        candidate_phase: CandidatePhase,
        participant_index: ParticipantIndex,
    ) -> Self {
        Self {
            transaction_order,
            candidate_phase,
            participant_index,
        }
    }

    /// Creates the only order shape valid for a binding terminal.
    #[must_use]
    pub const fn binding_terminal(
        transaction_order: TransactionOrder,
        participant_id: ParticipantId,
    ) -> Self {
        Self::new(
            transaction_order,
            CandidatePhase::BindingTerminal,
            participant_id,
        )
    }

    /// Returns the conversation transaction-order major.
    #[must_use]
    pub const fn transaction_order(self) -> TransactionOrder {
        self.transaction_order
    }

    /// Returns the canonical candidate phase.
    #[must_use]
    pub const fn candidate_phase(self) -> CandidatePhase {
        self.candidate_phase
    }

    /// Returns the permanent participant-index tie-breaker.
    #[must_use]
    pub const fn participant_index(self) -> ParticipantIndex {
        self.participant_index
    }
}

/// Active binding authority.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ActiveBinding {
    /// Bound participant; in v1 this value is also its permanent participant index.
    pub participant_id: ParticipantId,
    /// Bound conversation.
    pub conversation_id: ConversationId,
    /// Immutable current binding epoch.
    pub binding_epoch: BindingEpoch,
}

/// A durable binding-terminal record was appended in the fate transaction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CommittedBindingTerminalPosition {
    transaction_order: TransactionOrder,
    delivery_seq: DeliverySeq,
}

impl CommittedBindingTerminalPosition {
    /// Creates the assigned major and delivery key for an appended terminal.
    #[must_use]
    pub const fn new(transaction_order: TransactionOrder, delivery_seq: DeliverySeq) -> Self {
        Self {
            transaction_order,
            delivery_seq,
        }
    }

    /// Returns the assigned conversation transaction order.
    #[must_use]
    pub const fn transaction_order(self) -> TransactionOrder {
        self.transaction_order
    }

    /// Returns the committed terminal record's delivery sequence.
    #[must_use]
    pub const fn delivery_seq(self) -> DeliverySeq {
        self.delivery_seq
    }
}

/// A binding fate was durably accepted but its terminal append remains pending.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PendingBindingTerminalPosition {
    transaction_order: TransactionOrder,
}

impl PendingBindingTerminalPosition {
    /// Creates the immutable major reserved for a pending binding terminal.
    #[must_use]
    pub const fn new(transaction_order: TransactionOrder) -> Self {
        Self { transaction_order }
    }

    /// Returns the assigned conversation transaction order.
    #[must_use]
    pub const fn transaction_order(self) -> TransactionOrder {
        self.transaction_order
    }
}

/// Durable placement selected by an unrefusable binding-fate transaction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BindingTerminalDisposition {
    /// The terminal record committed in the source transaction.
    Committed(CommittedBindingTerminalPosition),
    /// The exact terminal remains in the bounded pending binding slot.
    Pending(PendingBindingTerminalPosition),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct BindingTerminalIdentity {
    participant_id: ParticipantId,
    conversation_id: ConversationId,
    binding_epoch: BindingEpoch,
    admission_order: AdmissionOrder,
}

impl BindingTerminalIdentity {
    const fn from_active(binding: ActiveBinding, transaction_order: TransactionOrder) -> Self {
        Self {
            participant_id: binding.participant_id,
            conversation_id: binding.conversation_id,
            binding_epoch: binding.binding_epoch,
            admission_order: AdmissionOrder::binding_terminal(
                transaction_order,
                binding.participant_id,
            ),
        }
    }
}

/// Appended `Detached` terminal with a cause valid for that record class.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CommittedDetachedTerminal {
    identity: BindingTerminalIdentity,
    cause: DetachedCause,
    delivery_seq: DeliverySeq,
}

impl CommittedDetachedTerminal {
    /// Returns the permanent participant identifier/index.
    #[must_use]
    pub const fn participant_id(self) -> ParticipantId {
        self.identity.participant_id
    }

    /// Returns the owning conversation.
    #[must_use]
    pub const fn conversation_id(self) -> ConversationId {
        self.identity.conversation_id
    }

    /// Returns the exact ended binding epoch.
    #[must_use]
    pub const fn binding_epoch(self) -> BindingEpoch {
        self.identity.binding_epoch
    }

    /// Returns the type-restricted `Detached` cause.
    #[must_use]
    pub const fn cause(self) -> DetachedCause {
        self.cause
    }

    /// Returns the typed binding-terminal admission position.
    #[must_use]
    pub const fn admission_order(self) -> AdmissionOrder {
        self.identity.admission_order
    }

    /// Returns the committed lifecycle delivery sequence.
    #[must_use]
    pub const fn delivery_seq(self) -> DeliverySeq {
        self.delivery_seq
    }
}

/// Appended `Died` terminal with a cause valid for that record class.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CommittedDiedTerminal {
    identity: BindingTerminalIdentity,
    cause: DiedCause,
    delivery_seq: DeliverySeq,
}

impl CommittedDiedTerminal {
    /// Returns the permanent participant identifier/index.
    #[must_use]
    pub const fn participant_id(self) -> ParticipantId {
        self.identity.participant_id
    }

    /// Returns the owning conversation.
    #[must_use]
    pub const fn conversation_id(self) -> ConversationId {
        self.identity.conversation_id
    }

    /// Returns the exact ended binding epoch.
    #[must_use]
    pub const fn binding_epoch(self) -> BindingEpoch {
        self.identity.binding_epoch
    }

    /// Returns the type-restricted `Died` cause.
    #[must_use]
    pub const fn cause(self) -> DiedCause {
        self.cause
    }

    /// Returns the typed binding-terminal admission position.
    #[must_use]
    pub const fn admission_order(self) -> AdmissionOrder {
        self.identity.admission_order
    }

    /// Returns the committed lifecycle delivery sequence.
    #[must_use]
    pub const fn delivery_seq(self) -> DeliverySeq {
        self.delivery_seq
    }
}

/// Cause-partitioned durable binding-terminal record.
///
/// The variant determines the allowed cause domain, so no independent record
/// kind can disagree with the stored cause.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommittedBindingTerminal {
    /// An appended `Detached` terminal.
    Detached(CommittedDetachedTerminal),
    /// An appended `Died` terminal.
    Died(CommittedDiedTerminal),
}

impl CommittedBindingTerminal {
    /// Returns the permanent participant identifier/index.
    #[must_use]
    pub const fn participant_id(self) -> ParticipantId {
        match self {
            Self::Detached(value) => value.participant_id(),
            Self::Died(value) => value.participant_id(),
        }
    }

    /// Returns the owning conversation.
    #[must_use]
    pub const fn conversation_id(self) -> ConversationId {
        match self {
            Self::Detached(value) => value.conversation_id(),
            Self::Died(value) => value.conversation_id(),
        }
    }

    /// Returns the exact ended binding epoch.
    #[must_use]
    pub const fn binding_epoch(self) -> BindingEpoch {
        match self {
            Self::Detached(value) => value.binding_epoch(),
            Self::Died(value) => value.binding_epoch(),
        }
    }

    /// Returns the typed binding-terminal admission position.
    #[must_use]
    pub const fn admission_order(self) -> AdmissionOrder {
        match self {
            Self::Detached(value) => value.admission_order(),
            Self::Died(value) => value.admission_order(),
        }
    }

    /// Returns the committed lifecycle delivery sequence.
    #[must_use]
    pub const fn delivery_seq(self) -> DeliverySeq {
        match self {
            Self::Detached(value) => value.delivery_seq(),
            Self::Died(value) => value.delivery_seq(),
        }
    }

    /// Returns the record class derived from the cause-partitioned variant.
    #[must_use]
    pub const fn kind(self) -> BindingTerminalKind {
        match self {
            Self::Detached(_) => BindingTerminalKind::Detached,
            Self::Died(_) => BindingTerminalKind::Died,
        }
    }

    /// Returns the shared seven-class close-cause view.
    #[must_use]
    pub const fn close_cause(self) -> CloseCause {
        match self {
            Self::Detached(value) => value.cause().close_cause(),
            Self::Died(value) => value.cause().close_cause(),
        }
    }

    /// Returns the restricted `Detached` cause, or `None` for a `Died` record.
    #[must_use]
    pub const fn detached_cause(self) -> Option<DetachedCause> {
        match self {
            Self::Detached(value) => Some(value.cause()),
            Self::Died(_) => None,
        }
    }

    /// Returns the restricted `Died` cause, or `None` for a `Detached` record.
    #[must_use]
    pub const fn died_cause(self) -> Option<DiedCause> {
        match self {
            Self::Detached(_) => None,
            Self::Died(value) => Some(value.cause()),
        }
    }
}

impl From<CommittedDetachedTerminal> for CommittedBindingTerminal {
    fn from(value: CommittedDetachedTerminal) -> Self {
        Self::Detached(value)
    }
}

impl From<CommittedDiedTerminal> for CommittedBindingTerminal {
    fn from(value: CommittedDiedTerminal) -> Self {
        Self::Died(value)
    }
}

/// Pending `Detached` terminal with no possible `Died`-only cause.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PendingDetachedFinalization {
    identity: BindingTerminalIdentity,
    cause: DetachedCause,
}

impl PendingDetachedFinalization {
    /// Returns the permanent participant identifier/index.
    #[must_use]
    pub const fn participant_id(self) -> ParticipantId {
        self.identity.participant_id
    }

    /// Returns the owning conversation.
    #[must_use]
    pub const fn conversation_id(self) -> ConversationId {
        self.identity.conversation_id
    }

    /// Returns the exact ended binding epoch.
    #[must_use]
    pub const fn binding_epoch(self) -> BindingEpoch {
        self.identity.binding_epoch
    }

    /// Returns the type-restricted `Detached` cause.
    #[must_use]
    pub const fn cause(self) -> DetachedCause {
        self.cause
    }

    /// Returns the immutable binding-terminal admission position.
    #[must_use]
    pub const fn admission_order(self) -> AdmissionOrder {
        self.identity.admission_order
    }

    /// Commits the exact pending terminal at its assigned delivery sequence.
    #[must_use]
    pub const fn commit(self, delivery_seq: DeliverySeq) -> CommittedDetachedTerminal {
        CommittedDetachedTerminal {
            identity: self.identity,
            cause: self.cause,
            delivery_seq,
        }
    }
}

/// Pending `Died` terminal with no possible `Detached`-only cause.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PendingDiedFinalization {
    identity: BindingTerminalIdentity,
    cause: DiedCause,
}

impl PendingDiedFinalization {
    /// Returns the permanent participant identifier/index.
    #[must_use]
    pub const fn participant_id(self) -> ParticipantId {
        self.identity.participant_id
    }

    /// Returns the owning conversation.
    #[must_use]
    pub const fn conversation_id(self) -> ConversationId {
        self.identity.conversation_id
    }

    /// Returns the exact ended binding epoch.
    #[must_use]
    pub const fn binding_epoch(self) -> BindingEpoch {
        self.identity.binding_epoch
    }

    /// Returns the type-restricted `Died` cause.
    #[must_use]
    pub const fn cause(self) -> DiedCause {
        self.cause
    }

    /// Returns the immutable binding-terminal admission position.
    #[must_use]
    pub const fn admission_order(self) -> AdmissionOrder {
        self.identity.admission_order
    }

    /// Commits the exact pending terminal at its assigned delivery sequence.
    #[must_use]
    pub const fn commit(self, delivery_seq: DeliverySeq) -> CommittedDiedTerminal {
        CommittedDiedTerminal {
            identity: self.identity,
            cause: self.cause,
            delivery_seq,
        }
    }
}

/// Binding-terminal lifecycle record kind, derived from cause-partitioned state.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BindingTerminalKind {
    /// Clean/supersession/shutdown `Detached` record.
    Detached,
    /// Unexpected `Died` record.
    Died,
}

/// Binding authority ended, but its terminal record awaits durable append.
///
/// Both variants have private, transition-derived fields. Consequently a
/// `Detached` finalization cannot carry `ConnectionLost`, `ProcessKilled`,
/// `ProtocolError`, or `UncleanServerRestart`, and a `Died` finalization cannot
/// carry `CleanDeregister`, `Superseded`, or `ServerShutdown`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PendingFinalization {
    /// A pending `Detached` record and its restricted cause.
    Detached(PendingDetachedFinalization),
    /// A pending `Died` record and its restricted cause.
    Died(PendingDiedFinalization),
}

impl PendingFinalization {
    /// Returns the permanent participant identifier/index.
    #[must_use]
    pub const fn participant_id(self) -> ParticipantId {
        match self {
            Self::Detached(value) => value.participant_id(),
            Self::Died(value) => value.participant_id(),
        }
    }

    /// Returns the owning conversation.
    #[must_use]
    pub const fn conversation_id(self) -> ConversationId {
        match self {
            Self::Detached(value) => value.conversation_id(),
            Self::Died(value) => value.conversation_id(),
        }
    }

    /// Returns the exact ended binding epoch.
    #[must_use]
    pub const fn binding_epoch(self) -> BindingEpoch {
        match self {
            Self::Detached(value) => value.binding_epoch(),
            Self::Died(value) => value.binding_epoch(),
        }
    }

    /// Returns the immutable binding-terminal admission position.
    #[must_use]
    pub const fn admission_order(self) -> AdmissionOrder {
        match self {
            Self::Detached(value) => value.admission_order(),
            Self::Died(value) => value.admission_order(),
        }
    }

    /// Returns the record class derived from the cause-partitioned variant.
    #[must_use]
    pub const fn kind(self) -> BindingTerminalKind {
        match self {
            Self::Detached(_) => BindingTerminalKind::Detached,
            Self::Died(_) => BindingTerminalKind::Died,
        }
    }

    /// Returns the shared seven-class close-cause view.
    #[must_use]
    pub const fn close_cause(self) -> CloseCause {
        match self {
            Self::Detached(value) => value.cause().close_cause(),
            Self::Died(value) => value.cause().close_cause(),
        }
    }

    /// Returns the restricted `Detached` cause, or `None` for a `Died` state.
    #[must_use]
    pub const fn detached_cause(self) -> Option<DetachedCause> {
        match self {
            Self::Detached(value) => Some(value.cause()),
            Self::Died(_) => None,
        }
    }

    /// Returns the restricted `Died` cause, or `None` for a `Detached` state.
    #[must_use]
    pub const fn died_cause(self) -> Option<DiedCause> {
        match self {
            Self::Detached(_) => None,
            Self::Died(value) => Some(value.cause()),
        }
    }

    /// Commits the exact pending terminal without changing cause, epoch, or order.
    #[must_use]
    pub const fn commit(self, delivery_seq: DeliverySeq) -> CommittedBindingTerminal {
        match self {
            Self::Detached(value) => CommittedBindingTerminal::Detached(value.commit(delivery_seq)),
            Self::Died(value) => CommittedBindingTerminal::Died(value.commit(delivery_seq)),
        }
    }
}

impl From<PendingDetachedFinalization> for PendingFinalization {
    fn from(value: PendingDetachedFinalization) -> Self {
        Self::Detached(value)
    }
}

impl From<PendingDiedFinalization> for PendingFinalization {
    fn from(value: PendingDiedFinalization) -> Self {
        Self::Died(value)
    }
}

/// Result of a fate that records a `Detached` lifecycle terminal.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DetachedBindingTransition {
    /// Terminal record committed with its durable delivery key.
    Committed(CommittedDetachedTerminal),
    /// Authority ended and the exact terminal remains bounded-pending.
    Pending(PendingDetachedFinalization),
}

impl DetachedBindingTransition {
    /// Returns the post-transition binding slot.
    #[must_use]
    pub const fn binding_state(self) -> BindingState {
        match self {
            Self::Committed(_) => BindingState::Detached,
            Self::Pending(value) => {
                BindingState::PendingFinalization(PendingFinalization::Detached(value))
            }
        }
    }
}

/// Result of a fate that records a `Died` lifecycle terminal.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DiedBindingTransition {
    /// Terminal record committed with its durable delivery key.
    Committed(CommittedDiedTerminal),
    /// Authority ended and the exact terminal remains bounded-pending.
    Pending(PendingDiedFinalization),
}

impl DiedBindingTransition {
    /// Projects a committed Died terminal; pending finalization has no progress yet.
    #[must_use]
    pub const fn observer_progress_projection(&self) -> Option<super::ObserverProgressProjection> {
        let Self::Committed(terminal) = self else {
            return None;
        };
        Some(super::ObserverProgressProjection::new(
            terminal.conversation_id(),
            terminal.delivery_seq(),
        ))
    }

    /// Returns the post-transition binding slot.
    #[must_use]
    pub const fn binding_state(self) -> BindingState {
        match self {
            Self::Committed(_) => BindingState::Detached,
            Self::Pending(value) => {
                BindingState::PendingFinalization(PendingFinalization::Died(value))
            }
        }
    }
}

impl ActiveBinding {
    const fn finish_detached(
        self,
        cause: DetachedCause,
        disposition: BindingTerminalDisposition,
    ) -> DetachedBindingTransition {
        match disposition {
            BindingTerminalDisposition::Committed(position) => {
                DetachedBindingTransition::Committed(CommittedDetachedTerminal {
                    identity: BindingTerminalIdentity::from_active(
                        self,
                        position.transaction_order,
                    ),
                    cause,
                    delivery_seq: position.delivery_seq,
                })
            }
            BindingTerminalDisposition::Pending(position) => {
                DetachedBindingTransition::Pending(PendingDetachedFinalization {
                    identity: BindingTerminalIdentity::from_active(
                        self,
                        position.transaction_order,
                    ),
                    cause,
                })
            }
        }
    }

    const fn finish_died(
        self,
        cause: DiedCause,
        disposition: BindingTerminalDisposition,
    ) -> DiedBindingTransition {
        match disposition {
            BindingTerminalDisposition::Committed(position) => {
                DiedBindingTransition::Committed(CommittedDiedTerminal {
                    identity: BindingTerminalIdentity::from_active(
                        self,
                        position.transaction_order,
                    ),
                    cause,
                    delivery_seq: position.delivery_seq,
                })
            }
            BindingTerminalDisposition::Pending(position) => {
                DiedBindingTransition::Pending(PendingDiedFinalization {
                    identity: BindingTerminalIdentity::from_active(
                        self,
                        position.transaction_order,
                    ),
                    cause,
                })
            }
        }
    }

    /// Ends authority for explicit detach or clean protocol Disconnect.
    #[must_use]
    pub const fn clean_deregister(
        self,
        disposition: BindingTerminalDisposition,
    ) -> DetachedBindingTransition {
        self.finish_detached(DetachedCause::CleanDeregister, disposition)
    }

    /// Commits an explicit detach terminal at its assigned durable position.
    #[must_use]
    pub const fn commit_clean_deregister(
        self,
        position: CommittedBindingTerminalPosition,
    ) -> CommittedDetachedTerminal {
        CommittedDetachedTerminal {
            identity: BindingTerminalIdentity::from_active(self, position.transaction_order),
            cause: DetachedCause::CleanDeregister,
            delivery_seq: position.delivery_seq,
        }
    }

    /// Ends explicit-detach authority while retaining its exact pending terminal.
    #[must_use]
    pub const fn pending_clean_deregister(
        self,
        position: PendingBindingTerminalPosition,
    ) -> PendingDetachedFinalization {
        PendingDetachedFinalization {
            identity: BindingTerminalIdentity::from_active(self, position.transaction_order),
            cause: DetachedCause::CleanDeregister,
        }
    }

    /// Ends every binding still active when a clean protocol Disconnect arrives.
    #[must_use]
    pub const fn clean_disconnect(
        self,
        disposition: BindingTerminalDisposition,
    ) -> DetachedBindingTransition {
        self.clean_deregister(disposition)
    }

    /// Commits the old terminal in an authorized superseding attach handoff.
    ///
    /// Supersession is an optional new-major producer and cannot leave only the
    /// old terminal pending; the enclosing attach transaction either appends
    /// the ordered `Detached(Superseded)`/`Attached` pair or commits nothing.
    #[must_use]
    pub const fn superseded(
        self,
        position: CommittedBindingTerminalPosition,
    ) -> CommittedDetachedTerminal {
        CommittedDetachedTerminal {
            identity: BindingTerminalIdentity::from_active(self, position.transaction_order),
            cause: DetachedCause::Superseded,
            delivery_seq: position.delivery_seq,
        }
    }

    /// Ends authority during an orderly server shutdown.
    #[must_use]
    pub const fn server_shutdown(
        self,
        disposition: BindingTerminalDisposition,
    ) -> DetachedBindingTransition {
        self.finish_detached(DetachedCause::ServerShutdown, disposition)
    }

    /// Ends authority after TCP/keepalive/read/write connection loss.
    #[must_use]
    pub const fn connection_lost(
        self,
        disposition: BindingTerminalDisposition,
    ) -> DiedBindingTransition {
        self.finish_died(DiedCause::ConnectionLost, disposition)
    }

    /// Ends authority after trapped linked-EXIT or known forced termination.
    #[must_use]
    pub const fn process_killed(
        self,
        disposition: BindingTerminalDisposition,
    ) -> DiedBindingTransition {
        self.finish_died(DiedCause::ProcessKilled, disposition)
    }

    /// Ends authority after a terminating decode or protocol-state refusal.
    #[must_use]
    pub const fn protocol_error(
        self,
        disposition: BindingTerminalDisposition,
    ) -> DiedBindingTransition {
        self.finish_died(DiedCause::ProtocolError, disposition)
    }

    /// Recovers a durably active epoch owned by a prior server incarnation.
    ///
    /// The prior incarnation in the `Died` cause is derived from the exact old
    /// binding epoch, so callers cannot pair the state with a different value.
    #[must_use]
    pub const fn unclean_server_restart(
        self,
        disposition: BindingTerminalDisposition,
    ) -> DiedBindingTransition {
        self.finish_died(
            DiedCause::UncleanServerRestart {
                prior_server_incarnation: self
                    .binding_epoch
                    .connection_incarnation
                    .server_incarnation,
            },
            disposition,
        )
    }
}

/// Binding-slot state; pending finalization carries no live authority.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BindingState {
    /// No binding or pending terminal exists.
    Detached,
    /// Current live binding authority.
    Bound(ActiveBinding),
    /// Authority ended and a cause-partitioned terminal record is pending.
    PendingFinalization(PendingFinalization),
}

pub(super) const fn restore_pending_finalization(
    binding: ActiveBinding,
    cause: CloseCause,
    transaction_order: TransactionOrder,
) -> Option<PendingFinalization> {
    let position =
        BindingTerminalDisposition::Pending(PendingBindingTerminalPosition::new(transaction_order));
    match cause {
        CloseCause::CleanDeregister => match binding.clean_deregister(position) {
            DetachedBindingTransition::Pending(value) => Some(PendingFinalization::Detached(value)),
            DetachedBindingTransition::Committed(_) => None,
        },
        CloseCause::ServerShutdown => match binding.server_shutdown(position) {
            DetachedBindingTransition::Pending(value) => Some(PendingFinalization::Detached(value)),
            DetachedBindingTransition::Committed(_) => None,
        },
        // Supersession is an indivisible committed handoff and can never be pending.
        CloseCause::Superseded => None,
        CloseCause::ConnectionLost => match binding.connection_lost(position) {
            DiedBindingTransition::Pending(value) => Some(PendingFinalization::Died(value)),
            DiedBindingTransition::Committed(_) => None,
        },
        CloseCause::ProcessKilled => match binding.process_killed(position) {
            DiedBindingTransition::Pending(value) => Some(PendingFinalization::Died(value)),
            DiedBindingTransition::Committed(_) => None,
        },
        CloseCause::ProtocolError => match binding.protocol_error(position) {
            DiedBindingTransition::Pending(value) => Some(PendingFinalization::Died(value)),
            DiedBindingTransition::Committed(_) => None,
        },
        CloseCause::UncleanServerRestart {
            prior_server_incarnation,
        } => {
            if binding
                .binding_epoch
                .connection_incarnation
                .server_incarnation
                != prior_server_incarnation
            {
                return None;
            }
            match binding.unclean_server_restart(position) {
                DiedBindingTransition::Pending(value) => Some(PendingFinalization::Died(value)),
                DiedBindingTransition::Committed(_) => None,
            }
        }
    }
}

pub(super) const fn restore_committed_terminal(
    binding: ActiveBinding,
    cause: CloseCause,
    transaction_order: TransactionOrder,
    delivery_seq: DeliverySeq,
) -> Option<CommittedBindingTerminal> {
    let position = BindingTerminalDisposition::Committed(CommittedBindingTerminalPosition::new(
        transaction_order,
        delivery_seq,
    ));
    match cause {
        CloseCause::CleanDeregister => match binding.clean_deregister(position) {
            DetachedBindingTransition::Committed(value) => {
                Some(CommittedBindingTerminal::Detached(value))
            }
            DetachedBindingTransition::Pending(_) => None,
        },
        CloseCause::Superseded => Some(CommittedBindingTerminal::Detached(binding.superseded(
            CommittedBindingTerminalPosition::new(transaction_order, delivery_seq),
        ))),
        CloseCause::ServerShutdown => match binding.server_shutdown(position) {
            DetachedBindingTransition::Committed(value) => {
                Some(CommittedBindingTerminal::Detached(value))
            }
            DetachedBindingTransition::Pending(_) => None,
        },
        CloseCause::ConnectionLost => match binding.connection_lost(position) {
            DiedBindingTransition::Committed(value) => Some(CommittedBindingTerminal::Died(value)),
            DiedBindingTransition::Pending(_) => None,
        },
        CloseCause::ProcessKilled => match binding.process_killed(position) {
            DiedBindingTransition::Committed(value) => Some(CommittedBindingTerminal::Died(value)),
            DiedBindingTransition::Pending(_) => None,
        },
        CloseCause::ProtocolError => match binding.protocol_error(position) {
            DiedBindingTransition::Committed(value) => Some(CommittedBindingTerminal::Died(value)),
            DiedBindingTransition::Pending(_) => None,
        },
        CloseCause::UncleanServerRestart {
            prior_server_incarnation,
        } => {
            if binding
                .binding_epoch
                .connection_incarnation
                .server_incarnation
                != prior_server_incarnation
            {
                return None;
            }
            match binding.unclean_server_restart(position) {
                DiedBindingTransition::Committed(value) => {
                    Some(CommittedBindingTerminal::Died(value))
                }
                DiedBindingTransition::Pending(_) => None,
            }
        }
    }
}