liminal-protocol 0.2.1

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
use super::{ClientParticipantAggregate, ClientResponseCorrelation};
use crate::wire::{
    AttachBound, DetachCommitted, DetachEnvelope, DetachInProgress, LeaveCommitted,
    TerminalizedDetachCell,
};

/// Closed, lossless detach replay status vocabulary.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DetachReplayStatus {
    /// The exact detach is durably parked for a transport attempt.
    Parked,
    /// A transport attempt is outstanding.
    InFlight,
    /// A matching newer attach permanently superseded the old detach.
    Superseded,
    /// A matching durable Leave permanently superseded the old detach.
    LeaveSuperseded,
    /// A typed server result terminalized replay.
    Terminal(DetachReplayTerminal),
}

/// Typed terminal detach replay outcomes retained without projection.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DetachReplayTerminal {
    /// Exact committed detach result.
    DetachCommitted(DetachCommitted),
    /// Exact competing-pending result.
    DetachInProgress(DetachInProgress),
    /// Exact terminalized old-cell authority result.
    TerminalizedDetachCell(TerminalizedDetachCell),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum DetachReplayState {
    Empty,
    Recorded {
        request: DetachEnvelope,
        status: DetachReplayStatus,
    },
}

/// Non-cloneable owner of the exact detach replay envelope and lifecycle.
#[derive(Debug, PartialEq, Eq)]
pub struct SdkDetachReplayAggregate {
    pub(super) state: DetachReplayState,
}

impl SdkDetachReplayAggregate {
    pub(super) const fn new() -> Self {
        Self {
            state: DetachReplayState::Empty,
        }
    }

    /// Borrows the exact retained detach request, absent only before first record.
    #[must_use]
    pub const fn request(&self) -> Option<&DetachEnvelope> {
        match &self.state {
            DetachReplayState::Empty => None,
            DetachReplayState::Recorded { request, .. } => Some(request),
        }
    }

    /// Borrows the lossless replay status, absent only before first record.
    #[must_use]
    pub const fn status(&self) -> Option<&DetachReplayStatus> {
        match &self.state {
            DetachReplayState::Empty => None,
            DetachReplayState::Recorded { status, .. } => Some(status),
        }
    }

    pub(super) const fn mark_initial_attempt_started(&mut self) {
        if let DetachReplayState::Recorded { status, .. } = &mut self.state {
            if matches!(status, DetachReplayStatus::Parked) {
                *status = DetachReplayStatus::InFlight;
            }
        }
    }

    pub(super) fn can_replace_with(&self, request: &DetachEnvelope) -> bool {
        match &self.state {
            DetachReplayState::Recorded {
                request: retained,
                status,
            } => {
                retained.conversation_id == request.conversation_id
                    && retained.participant_id == request.participant_id
                    && request.capability_generation > retained.capability_generation
                    && matches!(
                        status,
                        DetachReplayStatus::Superseded | DetachReplayStatus::Terminal(_)
                    )
            }
            DetachReplayState::Empty => false,
        }
    }

    pub(super) fn apply_attach(&mut self, attach: &AttachBound) -> bool {
        let DetachReplayState::Recorded { request, status } = &mut self.state else {
            return false;
        };
        if attach.conversation_id() == request.conversation_id
            && attach.participant_id() == request.participant_id
            && attach.request_generation() == request.capability_generation
            && attach.capability_generation() > request.capability_generation
        {
            *status = DetachReplayStatus::Superseded;
            true
        } else {
            false
        }
    }

    pub(super) fn apply_leave(&mut self, leave: &LeaveCommitted) -> bool {
        let DetachReplayState::Recorded { request, status } = &mut self.state else {
            return false;
        };
        if leave.conversation_id() == request.conversation_id
            && leave.participant_id() == request.participant_id
            && leave.presented_generation() == request.capability_generation
        {
            *status = DetachReplayStatus::LeaveSuperseded;
            true
        } else {
            false
        }
    }

    pub(super) fn apply_retired(
        &mut self,
        conversation_id: u64,
        participant_id: u64,
        retired_generation: crate::wire::Generation,
    ) -> bool {
        let DetachReplayState::Recorded { request, status } = &mut self.state else {
            return false;
        };
        if request.conversation_id == conversation_id
            && request.participant_id == participant_id
            && retired_generation >= request.capability_generation
        {
            *status = DetachReplayStatus::LeaveSuperseded;
            true
        } else {
            false
        }
    }

    pub(super) fn apply_detach_committed(&mut self, value: &DetachCommitted) -> bool {
        let DetachReplayState::Recorded { request, status } = &mut self.state else {
            return false;
        };
        if detach_committed_matches(request, value) {
            *status =
                DetachReplayStatus::Terminal(DetachReplayTerminal::DetachCommitted(value.clone()));
            true
        } else {
            false
        }
    }

    pub(super) fn apply_detach_in_progress(&mut self, value: &DetachInProgress) -> bool {
        let DetachReplayState::Recorded { request, status } = &mut self.state else {
            return false;
        };
        if detach_in_progress_matches(request, value) {
            *status =
                DetachReplayStatus::Terminal(DetachReplayTerminal::DetachInProgress(value.clone()));
            true
        } else {
            false
        }
    }

    pub(super) fn apply_terminalized_detach_cell(
        &mut self,
        value: &TerminalizedDetachCell,
    ) -> bool {
        let DetachReplayState::Recorded { request, status } = &mut self.state else {
            return false;
        };
        if terminalized_matches(request, value) {
            *status = DetachReplayStatus::Terminal(DetachReplayTerminal::TerminalizedDetachCell(
                value.clone(),
            ));
            true
        } else {
            false
        }
    }
}

/// Reason a detach replay input was refused unchanged.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DetachReplayRefusalReason {
    /// Replay is already active and cannot be silently replaced.
    AlreadyRecorded,
    /// The requested transition is not legal in the current replay status.
    InvalidStatus,
    /// The typed input does not match the retained exact detach request.
    ForeignInput,
    /// A restore already testified the in-flight send authority destroyed;
    /// only the pending testimony can resolve it (r2, 2026-07-18).
    LostAuthorityPending,
}

/// Applied detach replay transition.
#[derive(Debug, PartialEq, Eq)]
pub struct DetachReplayApplied {
    aggregate: ClientParticipantAggregate,
}

impl DetachReplayApplied {
    /// Releases the resulting client aggregate.
    #[must_use]
    pub fn into_aggregate(self) -> ClientParticipantAggregate {
        self.aggregate
    }
}

/// Refused detach replay transition with unchanged aggregate and input.
#[derive(Debug, PartialEq, Eq)]
pub struct DetachReplayRefusal<T> {
    aggregate: ClientParticipantAggregate,
    input: T,
    reason: DetachReplayRefusalReason,
}

impl<T> DetachReplayRefusal<T> {
    /// Returns the closed refusal reason.
    #[must_use]
    pub const fn reason(&self) -> DetachReplayRefusalReason {
        self.reason
    }

    /// Releases the unchanged aggregate and refused typed input.
    #[must_use]
    pub fn into_parts(self) -> (ClientParticipantAggregate, T) {
        (self.aggregate, self.input)
    }
}

/// Sealed effect authorizing one transport send of the exact detach.
#[derive(Debug, PartialEq, Eq)]
pub struct DetachTransportAttempt {
    request: DetachEnvelope,
    authorization: u64,
}

impl DetachTransportAttempt {
    /// Borrows the exact detach to send.
    #[must_use]
    pub const fn request(&self) -> &DetachEnvelope {
        &self.request
    }

    /// Consumes this one-use send effect into the exact wire envelope and its
    /// lifecycle correlation. The correlation must be consumed by outcome,
    /// transport fate, or typed abandonment before another attempt can start.
    #[must_use]
    pub const fn into_request(self) -> (DetachEnvelope, ClientResponseCorrelation) {
        (
            self.request,
            ClientResponseCorrelation {
                authorization: self.authorization,
            },
        )
    }
}

/// Decision for starting a detach transport attempt.
#[derive(Debug, PartialEq, Eq)]
pub enum DetachTransportAttemptDecision {
    /// Replay moved from parked to in-flight and released one send effect.
    Started {
        /// Resulting aggregate.
        aggregate: ClientParticipantAggregate,
        /// One-use exact send effect.
        attempt: DetachTransportAttempt,
    },
    /// Replay stayed unchanged.
    Refused(DetachReplayRefusal<()>),
}

/// Moves a parked detach to in-flight and releases its exact send effect.
///
/// If the matching committed expected detach was still unissued, this path
/// atomically marks it issued. Consequently the inverse restore order
/// (`transport_attempt_started` before `recover_expected_operation`) cannot
/// release a second initial-send authority.
#[must_use]
pub fn transport_attempt_started(
    mut aggregate: ClientParticipantAggregate,
) -> DetachTransportAttemptDecision {
    let request = match &aggregate.detach_replay.state {
        DetachReplayState::Recorded {
            request,
            status: DetachReplayStatus::Parked,
        } => request.clone(),
        DetachReplayState::Empty | DetachReplayState::Recorded { .. } => {
            return DetachTransportAttemptDecision::Refused(DetachReplayRefusal {
                aggregate,
                input: (),
                reason: DetachReplayRefusalReason::InvalidStatus,
            });
        }
    };
    let expected_matches = aggregate.expected.as_ref().is_some_and(|expected| {
        expected.authorization != 0
            && matches!(&expected.request, crate::wire::ClientRequest::Detach(value)
            if value.conversation_id == request.conversation_id
                && value.participant_id == request.participant_id
                && value.capability_generation == request.capability_generation
                && value.detach_attempt_token == request.detach_attempt_token)
    });
    if !expected_matches {
        return DetachTransportAttemptDecision::Refused(DetachReplayRefusal {
            aggregate,
            input: (),
            reason: DetachReplayRefusalReason::InvalidStatus,
        });
    }
    let authorization = aggregate
        .expected
        .as_ref()
        .map_or(0, |expected| expected.authorization);
    if let Some(expected) = aggregate.expected.as_mut() {
        expected.issued = true;
    }
    if let DetachReplayState::Recorded { status, .. } = &mut aggregate.detach_replay.state {
        *status = DetachReplayStatus::InFlight;
    }
    DetachTransportAttemptDecision::Started {
        aggregate,
        attempt: DetachTransportAttempt {
            request,
            authorization,
        },
    }
}

/// Typed transport fate for an outstanding detach send.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DetachTransportFate {
    /// The transport failed before a semantic response was obtained.
    ResponseUnavailable,
}

/// Decision for returning an in-flight detach to parked replay.
#[derive(Debug, PartialEq, Eq)]
pub enum DetachTransportFateDecision {
    /// Typed fate consumed the exact send authority and parked replay.
    Parked(DetachReplayApplied),
    /// No matching in-flight attempt existed; state, authority, and fate are retained.
    Refused(DetachReplayRefusal<(ClientResponseCorrelation, DetachTransportFate)>),
}

/// Consumes the outstanding send authority with typed transport fate.
///
/// This is the live-process `InFlight -> Parked` path. It marks the matching
/// expected detach unissued before allowing another attempt, so the consumed
/// correlation and a replacement effect can never coexist.
#[must_use]
pub fn transport_fate(
    mut aggregate: ClientParticipantAggregate,
    correlation: ClientResponseCorrelation,
    fate: DetachTransportFate,
) -> DetachTransportFateDecision {
    if aggregate.operation_loss_pending() {
        return DetachTransportFateDecision::Refused(DetachReplayRefusal {
            aggregate,
            input: (correlation, fate),
            reason: DetachReplayRefusalReason::LostAuthorityPending,
        });
    }
    if detach_authority_matches(&aggregate, &correlation) {
        if let DetachReplayState::Recorded { status, .. } = &mut aggregate.detach_replay.state {
            *status = DetachReplayStatus::Parked;
        }
        if let Some(expected) = aggregate.expected.as_mut() {
            expected.issued = false;
        }
        return DetachTransportFateDecision::Parked(DetachReplayApplied { aggregate });
    }
    DetachTransportFateDecision::Refused(DetachReplayRefusal {
        aggregate,
        input: (correlation, fate),
        reason: DetachReplayRefusalReason::InvalidStatus,
    })
}

/// Decision for applying a matching newer attach to replay.
#[derive(Debug, PartialEq, Eq)]
pub enum ApplyAttachDecision {
    /// Matching attach superseded the old detach.
    Superseded(DetachReplayApplied),
    /// Non-matching attach was retained and replay state stayed exact.
    Refused(DetachReplayRefusal<(AttachBound, ClientResponseCorrelation)>),
}

/// Applies attach supersession without treating attach as transport fate.
#[must_use]
pub fn apply_attach(
    mut aggregate: ClientParticipantAggregate,
    attach: AttachBound,
    correlation: ClientResponseCorrelation,
) -> ApplyAttachDecision {
    if aggregate.operation_loss_pending() {
        return ApplyAttachDecision::Refused(DetachReplayRefusal {
            aggregate,
            input: (attach, correlation),
            reason: DetachReplayRefusalReason::LostAuthorityPending,
        });
    }
    if detach_authority_matches(&aggregate, &correlation)
        && aggregate.detach_replay.apply_attach(&attach)
    {
        aggregate.expected = None;
        ApplyAttachDecision::Superseded(DetachReplayApplied { aggregate })
    } else {
        ApplyAttachDecision::Refused(DetachReplayRefusal {
            aggregate,
            input: (attach, correlation),
            reason: DetachReplayRefusalReason::ForeignInput,
        })
    }
}

/// Decision for applying a durable Leave to replay.
#[derive(Debug, PartialEq, Eq)]
pub enum ApplyLeaveDecision {
    /// Matching Leave superseded the old detach.
    Superseded(DetachReplayApplied),
    /// Non-matching Leave was retained with unchanged replay.
    Refused(DetachReplayRefusal<(LeaveCommitted, ClientResponseCorrelation)>),
}

/// Applies durable Leave supersession.
#[must_use]
pub fn apply_leave_durable(
    mut aggregate: ClientParticipantAggregate,
    leave: LeaveCommitted,
    correlation: ClientResponseCorrelation,
) -> ApplyLeaveDecision {
    if aggregate.operation_loss_pending() {
        return ApplyLeaveDecision::Refused(DetachReplayRefusal {
            aggregate,
            input: (leave, correlation),
            reason: DetachReplayRefusalReason::LostAuthorityPending,
        });
    }
    if detach_authority_matches(&aggregate, &correlation)
        && aggregate.detach_replay.apply_leave(&leave)
    {
        aggregate.expected = None;
        ApplyLeaveDecision::Superseded(DetachReplayApplied { aggregate })
    } else {
        ApplyLeaveDecision::Refused(DetachReplayRefusal {
            aggregate,
            input: (leave, correlation),
            reason: DetachReplayRefusalReason::ForeignInput,
        })
    }
}

/// Typed terminal detach outcome accepted by replay.
#[derive(Debug, PartialEq, Eq)]
pub enum DetachReplayOutcome {
    /// Stable committed detach.
    DetachCommitted(DetachCommitted),
    /// Different token found a pending detach.
    DetachInProgress(DetachInProgress),
    /// Exact old token resolved to a terminalized cell.
    TerminalizedDetachCell(TerminalizedDetachCell),
}

/// Decision for terminalizing detach replay.
#[derive(Debug, PartialEq, Eq)]
pub enum ApplyDetachOutcomeDecision {
    /// Exact typed outcome terminalized replay.
    Terminal(DetachReplayApplied),
    /// Non-matching outcome was retained with unchanged replay.
    Refused(DetachReplayRefusal<(DetachReplayOutcome, ClientResponseCorrelation)>),
}

/// Validates a typed detach outcome against the retained exact request.
#[must_use]
pub fn apply_detach_outcome(
    mut aggregate: ClientParticipantAggregate,
    outcome: DetachReplayOutcome,
    correlation: ClientResponseCorrelation,
) -> ApplyDetachOutcomeDecision {
    if aggregate.operation_loss_pending() {
        return ApplyDetachOutcomeDecision::Refused(DetachReplayRefusal {
            aggregate,
            input: (outcome, correlation),
            reason: DetachReplayRefusalReason::LostAuthorityPending,
        });
    }
    if !detach_authority_matches(&aggregate, &correlation) {
        return ApplyDetachOutcomeDecision::Refused(DetachReplayRefusal {
            aggregate,
            input: (outcome, correlation),
            reason: DetachReplayRefusalReason::InvalidStatus,
        });
    }
    let applied = match &outcome {
        DetachReplayOutcome::DetachCommitted(value) => {
            aggregate.detach_replay.apply_detach_committed(value)
        }
        DetachReplayOutcome::DetachInProgress(value) => {
            aggregate.detach_replay.apply_detach_in_progress(value)
        }
        DetachReplayOutcome::TerminalizedDetachCell(value) => aggregate
            .detach_replay
            .apply_terminalized_detach_cell(value),
    };
    if applied {
        aggregate.expected = None;
        ApplyDetachOutcomeDecision::Terminal(DetachReplayApplied { aggregate })
    } else {
        ApplyDetachOutcomeDecision::Refused(DetachReplayRefusal {
            aggregate,
            input: (outcome, correlation),
            reason: DetachReplayRefusalReason::ForeignInput,
        })
    }
}

fn detach_authority_matches(
    aggregate: &ClientParticipantAggregate,
    correlation: &ClientResponseCorrelation,
) -> bool {
    let Some(expected) = aggregate.expected.as_ref() else {
        return false;
    };
    if !expected.issued || expected.authorization != correlation.authorization {
        return false;
    }
    let DetachReplayState::Recorded {
        request,
        status: DetachReplayStatus::InFlight,
    } = &aggregate.detach_replay.state
    else {
        return false;
    };
    matches!(&expected.request, crate::wire::ClientRequest::Detach(value)
        if value.conversation_id == request.conversation_id
            && value.participant_id == request.participant_id
            && value.capability_generation == request.capability_generation
            && value.detach_attempt_token == request.detach_attempt_token)
}

fn detach_committed_matches(request: &DetachEnvelope, value: &DetachCommitted) -> bool {
    value.conversation_id() == request.conversation_id
        && value.participant_id() == request.participant_id
        && value.capability_generation() == request.capability_generation
        && value.detach_attempt_token() == request.detach_attempt_token
}

fn detach_in_progress_matches(request: &DetachEnvelope, value: &DetachInProgress) -> bool {
    let expected_generation = request.capability_generation;
    let presented_generation = value.presented_generation;
    let expected_token = request.detach_attempt_token;
    let presented_token = value.presented_token;
    value.conversation_id == request.conversation_id
        && value.participant_id == request.participant_id
        && presented_generation == expected_generation
        && presented_token == expected_token
}

fn terminalized_matches(request: &DetachEnvelope, value: &TerminalizedDetachCell) -> bool {
    value.conversation_id() == request.conversation_id
        && value.participant_id() == request.participant_id
        && value.capability_generation() == request.capability_generation
        && value.detach_attempt_token() == request.detach_attempt_token
}