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
use alloc::boxed::Box;

use crate::wire::{
    AttachBound, AttachSecret, BindingEpoch, CredentialAttachRequest, DeliverySeq, Generation,
};

use super::{
    ActiveBinding, AttachedLifecycleRecord, AttachedRecordPosition, BindingOrigin, BindingState,
    ClosureState, CommittedBindingTerminal, CommittedBindingTerminalPosition,
    CommittedDetachedTerminal, CommittedDiedTerminal, DetachCell, Event, FencedAttachCommit,
    LiveMember, MembershipInvariantError, ObserverProgressProjection, OrdinaryBindingAuthority,
    OrdinaryBindingFate, OrdinaryDetachedAttachAdmission, PendingFinalization,
    detach::validate_pending_pair, lookup::AttachSecretProof,
};

/// Result allocation owned by one successful credential-attach transaction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AttachCommitParameters {
    /// Newly committed binding epoch.
    pub binding: ActiveBinding,
    /// Newly minted result attach secret.
    pub attach_secret: AttachSecret,
    /// Assigned `Attached` lifecycle record position.
    pub attached_position: AttachedRecordPosition,
    /// Live receipt deadline.
    pub receipt_expires_at: u128,
    /// Provenance deadline.
    pub provenance_expires_at: u128,
}

/// Failure while proving credential-attach authority before commit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AttachVerificationError {
    /// Request names another conversation.
    Conversation,
    /// Request names another participant.
    Participant,
    /// Request generation is not the current live generation.
    Generation,
    /// Presented attach secret failed the constant-time verifier.
    Secret,
    /// Current binding state cannot execute the selected attach mode.
    BindingState,
    /// Ordinary/superseding attach presented a marker, or fenced proof differed.
    MarkerProof,
    /// Fenced proof names another participant or binding epoch.
    RecoveryAuthority,
    /// Pending finalization lacks a real terminal sequence or appears in another mode.
    PendingTerminalSequence,
    /// Result binding does not name this member.
    ResultBinding,
    /// Current generation is exhausted or result generation is not its successor.
    ResultGeneration,
    /// Supersession terminal and Attached record do not share one transaction major.
    LifecycleOrder,
    /// Retained committed-terminal history cannot prove the detached recovery epoch.
    TerminalHistory,
}

/// Failure while atomically applying a previously verified attach.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AttachCommitError {
    /// A pending detach is not paired with fenced pending-finalization commit.
    PendingDetach,
    /// Detach cell belongs to another participant or generation.
    DetachCellAuthority,
    /// Binding finalization and pending detach cell do not describe one commit.
    BindingCellState,
    /// Committed detach cell and retained terminal history disagree.
    TerminalHistory,
    /// Rotated membership rejected the committed terminal.
    MembershipInvariant(MembershipInvariantError),
    /// Canonical attach receipt rejected the verified transaction.
    ReceiptInvariant,
}

/// Binding-terminal effect selected by one successful attach.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AttachTransition {
    /// Already-detached member bound without creating another terminal.
    Detached,
    /// Old active epoch committed `Detached(Superseded)` in the handoff.
    Superseded {
        /// Exact old terminal including its real delivery sequence.
        terminal: CommittedDetachedTerminal,
    },
    /// Marker-fenced recovery accepted the delivered marker atomically.
    FencedRecovery {
        /// Exact dead epoch that durably received the marker.
        prior_binding_epoch: BindingEpoch,
        /// Terminal committed from pending state in this transaction, if any.
        composed_terminal: Option<CommittedBindingTerminal>,
        /// Closure successor restricted to clear, projection, or compaction.
        next_closure_state: ClosureState,
    },
}

/// Complete atomic result of a credential attach.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AttachCommit<F, V> {
    /// Rotated membership with preserved or replaced terminal history.
    pub member: LiveMember<F>,
    /// Exact new authoritative binding.
    pub binding_state: BindingState,
    /// Fix 1 detach cell after terminalization/preservation.
    pub detach_cell: DetachCell<V>,
    /// Exact committed phase-2 `Attached` lifecycle record.
    pub attached: AttachedLifecycleRecord,
    /// Exact wire success payload.
    pub outcome: AttachBound,
    /// Typed old-binding or fenced-recovery terminal effect.
    pub transition: AttachTransition,
    binding_origin: BindingOrigin,
    ordinary_binding_authority: Option<OrdinaryBindingAuthority>,
}

impl<F, V> AttachCommit<F, V> {
    /// Projects the binding-ending terminal committed by this attach, if any.
    #[must_use]
    pub fn observer_progress_projection(&self) -> Option<ObserverProgressProjection> {
        let terminal = match self.transition {
            AttachTransition::Detached
            | AttachTransition::FencedRecovery {
                composed_terminal: None,
                ..
            } => return None,
            AttachTransition::Superseded { terminal } => terminal.into(),
            AttachTransition::FencedRecovery {
                composed_terminal: Some(terminal),
                ..
            } => terminal,
        };
        Some(ObserverProgressProjection::new(
            terminal.conversation_id(),
            terminal.delivery_seq(),
        ))
    }

    /// Consumes one exact normal-ack event into this ordinary attach's cursor authority.
    ///
    /// Fenced recovery has no ordinary authority and therefore returns the
    /// unchanged commit. The raw authority never crosses the public boundary.
    ///
    /// # Errors
    ///
    /// Returns the unchanged commit for fenced recovery or when the event names
    /// another participant, epoch, previous cursor, or event class.
    pub fn ordinary_cursor_progressed(mut self, event: Event) -> Result<Self, Box<Self>> {
        let Some(authority) = self.ordinary_binding_authority.take() else {
            return Err(Box::new(self));
        };
        match authority.cursor_progressed(event) {
            Ok(authority) => {
                self.ordinary_binding_authority = Some(authority);
                Ok(self)
            }
            Err(authority) => {
                self.ordinary_binding_authority = Some(authority);
                Err(Box::new(self))
            }
        }
    }

    /// Consumes this ordinary attach and its exact durable death into cursor-release fate.
    ///
    /// A fenced attach cannot enter this path because it carries no ordinary
    /// binding authority; recovered epochs still require the distinct
    /// [`FencedAttachCommit`] provenance transition.
    ///
    /// # Errors
    ///
    /// Returns the unchanged commit for fenced recovery or unless the terminal
    /// names this exact ordinary participant, conversation, and binding epoch.
    pub fn ordinary_binding_fate(
        mut self,
        terminal: CommittedDiedTerminal,
        resulting_floor: DeliverySeq,
    ) -> Result<OrdinaryBindingFate, Box<Self>> {
        let Some(authority) = self.ordinary_binding_authority.take() else {
            return Err(Box::new(self));
        };
        match authority.binding_fate(terminal, resulting_floor) {
            Ok(fate) => Ok(fate),
            Err(authority) => {
                self.ordinary_binding_authority = Some(authority);
                Err(Box::new(self))
            }
        }
    }

    /// Returns no-marker fate authority only for a committed ordinary attach.
    ///
    /// Fenced recovery returns `None`; its recovered epoch must instead use the
    /// [`FencedAttachCommit`] proof that authorized that commit.
    #[must_use]
    #[allow(
        dead_code,
        reason = "the crate-owned binding-fate operation consumes this sealed attach authority"
    )]
    pub(crate) const fn ordinary_binding_authority(&self) -> Option<OrdinaryBindingAuthority> {
        self.ordinary_binding_authority
    }

    /// Returns the opaque binding origin emitted from the verified attach mode.
    #[must_use]
    #[allow(
        dead_code,
        reason = "the crate-owned event replay boundary persists this producer-emitted origin"
    )]
    pub(crate) const fn binding_origin(&self) -> BindingOrigin {
        self.binding_origin
    }
}

#[derive(Clone, Copy, Debug)]
enum AttachMode<'a> {
    Detached(OrdinaryDetachedAttachAdmission),
    Superseded(CommittedDetachedTerminal),
    Fenced {
        proof: &'a FencedAttachCommit,
        pending: Option<(PendingFinalization, DeliverySeq)>,
    },
}

/// Successful attach proof; fields are private so only mode verification mints it.
#[derive(Clone, Debug)]
pub struct VerifiedAttachCommit<'a, F> {
    member: LiveMember<F>,
    request: CredentialAttachRequest,
    parameters: AttachCommitParameters,
    mode: AttachMode<'a>,
}

impl<F> LiveMember<F> {
    /// Verifies an ordinary attach from an already detached member.
    ///
    /// # Errors
    ///
    /// Returns [`AttachVerificationError`] for authority, marker, state, or allocation mismatch.
    pub fn verify_detached_attach(
        self,
        binding_state: BindingState,
        closure_admission: OrdinaryDetachedAttachAdmission,
        request: CredentialAttachRequest,
        secret_proof: AttachSecretProof,
        parameters: AttachCommitParameters,
    ) -> Result<VerifiedAttachCommit<'static, F>, AttachVerificationError> {
        self.verify_attach_common(&request, secret_proof, &parameters)?;
        if binding_state != BindingState::Detached {
            return Err(AttachVerificationError::BindingState);
        }
        if request.accept_marker_delivery_seq.is_some() {
            return Err(AttachVerificationError::MarkerProof);
        }
        Ok(VerifiedAttachCommit {
            member: self,
            request,
            parameters,
            mode: AttachMode::Detached(closure_admission),
        })
    }

    /// Verifies an attach that atomically supersedes this member's active epoch.
    ///
    /// # Errors
    ///
    /// Returns [`AttachVerificationError`] when authority, marker absence,
    /// handoff ordering, or result allocation is inconsistent.
    pub fn verify_superseding_attach(
        self,
        active_binding: ActiveBinding,
        request: CredentialAttachRequest,
        secret_proof: AttachSecretProof,
        terminal_position: CommittedBindingTerminalPosition,
        parameters: AttachCommitParameters,
    ) -> Result<VerifiedAttachCommit<'static, F>, AttachVerificationError> {
        self.verify_attach_common(&request, secret_proof, &parameters)?;
        if active_binding.conversation_id != self.conversation_id()
            || active_binding.participant_id != self.participant_id()
            || active_binding.binding_epoch.capability_generation != self.generation()
        {
            return Err(AttachVerificationError::BindingState);
        }
        if request.accept_marker_delivery_seq.is_some() {
            return Err(AttachVerificationError::MarkerProof);
        }
        if terminal_position.transaction_order() != parameters.attached_position.transaction_order()
        {
            return Err(AttachVerificationError::LifecycleOrder);
        }
        let terminal = active_binding.superseded(terminal_position);
        Ok(VerifiedAttachCommit {
            member: self,
            request,
            parameters,
            mode: AttachMode::Superseded(terminal),
        })
    }

    /// Verifies marker-fenced recovery proven by the closure-edge transition.
    ///
    /// # Errors
    ///
    /// Returns [`AttachVerificationError`] when credential authority,
    /// marker/epoch proof, pending-terminal shape, or result allocation differs.
    pub fn verify_fenced_attach(
        self,
        binding_state: BindingState,
        request: CredentialAttachRequest,
        secret_proof: AttachSecretProof,
        proof: &FencedAttachCommit,
        pending_terminal_delivery_seq: Option<DeliverySeq>,
        parameters: AttachCommitParameters,
    ) -> Result<VerifiedAttachCommit<'_, F>, AttachVerificationError> {
        self.verify_attach_common(&request, secret_proof, &parameters)?;
        if request.accept_marker_delivery_seq != Some(proof.marker_delivery_seq()) {
            return Err(AttachVerificationError::MarkerProof);
        }
        if proof.participant_id() != self.participant_id()
            || proof.prior_binding_epoch().capability_generation != self.generation()
            || proof.new_binding_epoch() != parameters.binding.binding_epoch
        {
            return Err(AttachVerificationError::RecoveryAuthority);
        }
        let pending = match (binding_state, pending_terminal_delivery_seq) {
            (BindingState::Detached, None) => {
                if self
                    .latest_terminal()
                    .is_none_or(|terminal| terminal.binding_epoch() != proof.prior_binding_epoch())
                {
                    return Err(AttachVerificationError::TerminalHistory);
                }
                None
            }
            (BindingState::PendingFinalization(finalization), Some(sequence)) => {
                let same_conversation = finalization.conversation_id() == self.conversation_id();
                let same_participant = finalization.participant_id() == self.participant_id();
                let same_prior_epoch = finalization.binding_epoch() == proof.prior_binding_epoch();
                if !(same_conversation && same_participant && same_prior_epoch) {
                    return Err(AttachVerificationError::BindingState);
                }
                Some((finalization, sequence))
            }
            (BindingState::PendingFinalization(_), None) | (BindingState::Detached, Some(_)) => {
                return Err(AttachVerificationError::PendingTerminalSequence);
            }
            (BindingState::Bound(_), _) => {
                return Err(AttachVerificationError::BindingState);
            }
        };
        Ok(VerifiedAttachCommit {
            member: self,
            request,
            parameters,
            mode: AttachMode::Fenced { proof, pending },
        })
    }

    fn verify_attach_common(
        &self,
        request: &CredentialAttachRequest,
        secret_proof: AttachSecretProof,
        parameters: &AttachCommitParameters,
    ) -> Result<(), AttachVerificationError> {
        if request.conversation_id != self.conversation_id() {
            return Err(AttachVerificationError::Conversation);
        }
        if request.participant_id != self.participant_id() {
            return Err(AttachVerificationError::Participant);
        }
        if request.capability_generation != self.generation() {
            return Err(AttachVerificationError::Generation);
        }
        if secret_proof == AttachSecretProof::Mismatch {
            return Err(AttachVerificationError::Secret);
        }
        if parameters.binding.conversation_id != self.conversation_id()
            || parameters.binding.participant_id != self.participant_id()
        {
            return Err(AttachVerificationError::ResultBinding);
        }
        let Some(next_raw) = self.generation().get().checked_add(1) else {
            return Err(AttachVerificationError::ResultGeneration);
        };
        let Some(next_generation) = Generation::new(next_raw) else {
            return Err(AttachVerificationError::ResultGeneration);
        };
        if parameters.binding.binding_epoch.capability_generation != next_generation {
            return Err(AttachVerificationError::ResultGeneration);
        }
        Ok(())
    }
}

/// Atomically commits a verified attach and applies Fix 1's detach-cell rule.
///
/// # Errors
///
/// Returns [`AttachCommitError`] for cell/history mismatch, invalid rotation,
/// or a canonical receipt invariant rejected after verification.
pub fn commit_attach<F, V>(
    verified: VerifiedAttachCommit<'_, F>,
    detach_cell: DetachCell<V>,
) -> Result<AttachCommit<F, V>, AttachCommitError>
where
    V: Copy + Eq,
{
    let VerifiedAttachCommit {
        member: previous_member,
        request,
        parameters,
        mode,
    } = verified;
    let next_cell = transition_detach_cell(&mode, &previous_member, detach_cell)?;
    let attached =
        AttachedLifecycleRecord::from_binding(parameters.binding, parameters.attached_position);
    let (persisted_cursor, terminal, transition, binding_origin) = match mode {
        AttachMode::Detached(_) => (
            previous_member.cursor(),
            None,
            AttachTransition::Detached,
            BindingOrigin::unfenced(attached),
        ),
        AttachMode::Superseded(committed) => (
            previous_member.cursor(),
            Some(CommittedBindingTerminal::from(committed)),
            AttachTransition::Superseded {
                terminal: committed,
            },
            BindingOrigin::unfenced(attached),
        ),
        AttachMode::Fenced { proof, pending } => {
            let composed_terminal =
                pending.map(|(finalization, sequence)| finalization.commit(sequence));
            (
                proof.marker_delivery_seq(),
                composed_terminal,
                AttachTransition::FencedRecovery {
                    prior_binding_epoch: proof.prior_binding_epoch(),
                    composed_terminal,
                    next_closure_state: proof.next_state(),
                },
                BindingOrigin::recovered(
                    attached,
                    proof.marker_delivery_seq(),
                    proof.prior_binding_epoch(),
                ),
            )
        }
    };
    let result_generation = parameters.binding.binding_epoch.capability_generation;
    let member = previous_member
        .rotate(
            result_generation,
            parameters.attach_secret,
            persisted_cursor,
            terminal,
        )
        .map_err(AttachCommitError::MembershipInvariant)?;
    let outcome = match transition {
        AttachTransition::FencedRecovery { .. } => AttachBound::fenced(
            request.conversation_id,
            request.attach_attempt_token,
            request.participant_id,
            request.capability_generation,
            parameters.attach_secret,
            parameters.binding.binding_epoch,
            persisted_cursor,
            parameters.receipt_expires_at,
            parameters.provenance_expires_at,
        ),
        AttachTransition::Detached | AttachTransition::Superseded { .. } => AttachBound::ordinary(
            request.conversation_id,
            request.attach_attempt_token,
            request.participant_id,
            request.capability_generation,
            parameters.attach_secret,
            parameters.binding.binding_epoch,
            persisted_cursor,
            parameters.receipt_expires_at,
            parameters.provenance_expires_at,
        ),
    }
    .ok_or(AttachCommitError::ReceiptInvariant)?;
    let ordinary_binding_authority = match transition {
        AttachTransition::Detached | AttachTransition::Superseded { .. } => Some(
            OrdinaryBindingAuthority::new(parameters.binding, persisted_cursor),
        ),
        AttachTransition::FencedRecovery { .. } => None,
    };
    Ok(AttachCommit {
        member,
        binding_state: BindingState::Bound(parameters.binding),
        detach_cell: next_cell,
        attached,
        outcome,
        transition,
        binding_origin,
        ordinary_binding_authority,
    })
}

fn transition_detach_cell<F, V>(
    mode: &AttachMode<'_>,
    member: &LiveMember<F>,
    detach_cell: DetachCell<V>,
) -> Result<DetachCell<V>, AttachCommitError>
where
    V: Copy + Eq,
{
    match detach_cell {
        DetachCell::Empty(cell) => Ok(DetachCell::Empty(cell)),
        DetachCell::Pending(cell) => {
            let AttachMode::Fenced {
                pending: Some((binding_state, _)),
                ..
            } = mode
            else {
                return Err(AttachCommitError::PendingDetach);
            };
            validate_pending_pair(
                BindingState::PendingFinalization(*binding_state),
                &cell,
                Some(member.conversation_id()),
            )
            .map_err(|_| AttachCommitError::BindingCellState)?;
            Ok(DetachCell::Terminalized(cell.terminalize_after_attach()))
        }
        DetachCell::Committed(cell) => {
            if matches!(mode, AttachMode::Superseded(_))
                || cell.participant_id() != member.participant_id()
                || cell.request_generation() != member.generation()
            {
                return Err(AttachCommitError::DetachCellAuthority);
            }
            let Some(terminal) = member.latest_terminal() else {
                return Err(AttachCommitError::TerminalHistory);
            };
            if terminal.detached_cause() != Some(crate::wire::DetachedCause::CleanDeregister)
                || terminal.binding_epoch() != cell.committed_binding_epoch()
                || terminal.delivery_seq() != cell.detached_delivery_seq()
            {
                return Err(AttachCommitError::TerminalHistory);
            }
            Ok(DetachCell::Terminalized(cell.terminalize_after_attach()))
        }
        DetachCell::Terminalized(cell) => {
            if cell.participant_id() != member.participant_id() {
                return Err(AttachCommitError::DetachCellAuthority);
            }
            Ok(DetachCell::Terminalized(cell))
        }
    }
}