liminal-protocol 0.9.2

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
#![allow(clippy::expect_used, clippy::panic)]

use alloc::{vec, vec::Vec};

use crate::algebra::WideResourceVector;
use crate::wire::{
    AttachAttemptToken, AttachSecret, BindingEpoch, ConnectionIncarnation, CredentialAttachRequest,
    DetachAttemptToken, DetachRequest, Generation,
};

use super::edge::marker_delivery_for_test;
use super::{
    ActiveBinding, AttachCommitError, AttachCommitParameters, AttachSecretProof, AttachTransition,
    AttachVerificationError, AttachedRecordPosition, BindingState, ClosureDebt, ClosureState,
    CommittedBindingTerminalPosition, CursorFateSuccessor, DebtCompletion, DetachCell,
    EnrollmentFingerprint, Event, LiveMember, LiveMemberRestore, PendingBindingTerminalPosition,
    StoredEdge, commit_attach, commit_detach, start_blocked_detach,
};

fn generation(value: u64) -> Generation {
    Generation::new(value).expect("test generation is nonzero")
}

fn epoch(generation_value: u64, ordinal: u64) -> BindingEpoch {
    BindingEpoch::new(
        ConnectionIncarnation::new(8, ordinal),
        generation(generation_value),
    )
}

fn member() -> LiveMember<Vec<u8>> {
    LiveMember::restore(LiveMemberRestore {
        participant_id: 3,
        conversation_id: 29,
        generation: generation(4),
        attach_secret: AttachSecret::new([0x44; 32]),
        cursor: 5,
        enrollment_fingerprint: EnrollmentFingerprint::new(vec![3, 29]),
        latest_terminal: None,
    })
    .expect("fixture membership is internally consistent")
}

fn member_acknowledged_through(cursor: u64) -> LiveMember<Vec<u8>> {
    LiveMember::restore(LiveMemberRestore {
        participant_id: 3,
        conversation_id: 29,
        generation: generation(4),
        attach_secret: AttachSecret::new([0x44; 32]),
        cursor,
        enrollment_fingerprint: EnrollmentFingerprint::new(vec![3, 29]),
        latest_terminal: None,
    })
    .expect("fixture membership is internally consistent")
}

fn request(marker: Option<u64>) -> CredentialAttachRequest {
    CredentialAttachRequest {
        conversation_id: 29,
        participant_id: 3,
        capability_generation: generation(4),
        attach_secret: AttachSecret::new([0x44; 32]),
        attach_attempt_token: AttachAttemptToken::new([0xA4; 16]),
        accept_marker_delivery_seq: marker,
    }
}

fn parameters() -> AttachCommitParameters {
    AttachCommitParameters {
        binding: ActiveBinding {
            participant_id: 3,
            conversation_id: 29,
            binding_epoch: epoch(5, 12),
        },
        attach_secret: AttachSecret::new([0x55; 32]),
        attached_position: AttachedRecordPosition::new(9, 15),
        receipt_expires_at: 100,
        provenance_expires_at: 200,
    }
}

fn debt() -> ClosureDebt {
    ClosureDebt::new(WideResourceVector::new(1, 10)).expect("test debt is nonzero")
}

#[test]
fn ordinary_attach_cannot_claim_marker_acceptance() {
    assert!(matches!(
        member().verify_detached_attach(
            BindingState::Detached,
            ClosureState::Clear
                .ordinary_detached_attach_admission()
                .expect("clear state admits ordinary attach"),
            request(Some(14)),
            AttachSecretProof::Verified,
            parameters(),
        ),
        Err(AttachVerificationError::MarkerProof)
    ));
}

#[test]
fn clear_closure_admission_reaches_ordinary_binding_authority() {
    let verified = member()
        .verify_detached_attach(
            BindingState::Detached,
            ClosureState::Clear
                .ordinary_detached_attach_admission()
                .expect("clear state admits ordinary attach"),
            request(None),
            AttachSecretProof::Verified,
            parameters(),
        )
        .expect("clear ordinary detached attach verifies");
    let committed = commit_attach(verified, DetachCell::<[u8; 32]>::default())
        .expect("verified ordinary detached attach commits");

    let authority = committed
        .ordinary_binding_authority()
        .expect("ordinary attach carries its admitted binding authority");
    assert_eq!(authority.binding(), parameters().binding);
    assert_eq!(authority.through_seq(), member().cursor());
    assert!(committed.binding_origin().is_unfenced());
    assert_eq!(committed.binding_origin().attached(), committed.attached);
}

#[test]
fn active_same_participant_attach_records_supersession() {
    let old_binding = ActiveBinding {
        participant_id: 3,
        conversation_id: 29,
        binding_epoch: epoch(4, 11),
    };
    let verified = member()
        .verify_superseding_attach(
            old_binding,
            request(None),
            AttachSecretProof::Verified,
            CommittedBindingTerminalPosition::new(9, 14),
            parameters(),
        )
        .expect("same-participant current binding may be superseded");
    let committed = commit_attach(verified, DetachCell::<[u8; 32]>::default())
        .expect("verified supersession commits");

    assert_eq!(committed.member.cursor(), 5);
    assert_eq!(committed.outcome.persisted_cursor(), 5);
    assert_eq!(committed.outcome.accepted_marker_delivery_seq(), None);
    let ordinary_authority = committed
        .ordinary_binding_authority()
        .expect("ordinary supersession mints no-marker fate authority");
    assert_eq!(ordinary_authority.binding(), parameters().binding);
    assert_eq!(ordinary_authority.through_seq(), 5);
    assert!(committed.binding_origin().is_unfenced());
    let AttachTransition::Superseded { terminal } = committed.transition else {
        panic!("supersession must carry its real old terminal");
    };
    assert_eq!(terminal.binding_epoch(), old_binding.binding_epoch);
    assert_eq!(terminal.delivery_seq(), 14);
    assert_eq!(committed.attached.delivery_seq(), 15);
    assert_eq!(committed.member.latest_terminal(), Some(terminal.into()));
}

#[test]
fn fenced_recovery_composes_pending_detach_and_sets_both_marker_fields() {
    let old_binding = ActiveBinding {
        participant_id: 3,
        conversation_id: 29,
        binding_epoch: epoch(4, 11),
    };
    let detach_request = DetachRequest {
        conversation_id: 29,
        participant_id: 3,
        capability_generation: generation(4),
        detach_attempt_token: DetachAttemptToken::new([0xD4; 16]),
    };
    let verified_detach = old_binding
        .verify_detach_request(detach_request, [0xDD; 32])
        .expect("detach request matches old binding");
    let (pending_member, pending_state, pending_cell, _) = start_blocked_detach(
        member(),
        verified_detach,
        DetachCell::default(),
        PendingBindingTerminalPosition::new(7),
        6,
    )
    .expect("blocked detach creates one paired pending cell")
    .into_parts();

    let closure_debt = debt();
    let delivery = marker_delivery_for_test(3, old_binding.binding_epoch, 14)
        .expect("validated marker fixture restores");
    let delivered = delivery
        .delivered(
            closure_debt,
            Event::marker_delivered(3, old_binding.binding_epoch, 14),
        )
        .expect("exact delivery creates marker-backed cursor progress");
    let ClosureState::Owed {
        edge: StoredEdge::ParticipantCursorProgress(progress),
        ..
    } = delivered
    else {
        panic!("marker delivery must select participant cursor progress");
    };
    let fate = progress
        .binding_fate(
            closure_debt,
            Event::binding_fate_observed(3, old_binding.binding_epoch, 5),
        )
        .expect("exact old-epoch fate derives recovery");
    let CursorFateSuccessor::DetachedCredentialRecovery(recovery) = fate else {
        panic!("marker-backed fate must derive credential recovery");
    };
    let proof = recovery
        .fenced_attach(
            super::edge::validated_marker_record_for_recovery_test(recovery),
            closure_debt,
            Event::fenced_recovery_committed(
                3,
                14,
                old_binding.binding_epoch,
                parameters().binding.binding_epoch,
                15,
            ),
            DebtCompletion::clear(),
        )
        .expect("exact fenced event consumes recovery edge");

    let verified = pending_member
        .verify_fenced_attach(
            pending_state,
            request(Some(14)),
            AttachSecretProof::Verified,
            proof,
            Some(13),
            parameters(),
        )
        .expect("proof and pending finalization name one old epoch");
    let committed = commit_attach(verified, DetachCell::Pending(pending_cell))
        .expect("fenced attach composes the pending terminal");

    assert_eq!(committed.member.cursor(), 14);
    assert_eq!(committed.outcome.persisted_cursor(), 14);
    assert_eq!(committed.outcome.accepted_marker_delivery_seq(), Some(14));
    assert_eq!(committed.ordinary_binding_authority(), None);
    assert!(!committed.binding_origin().is_unfenced());
    assert_eq!(
        committed.binding_origin().recovered_marker(),
        Some((14, old_binding.binding_epoch))
    );
    assert!(matches!(committed.detach_cell, DetachCell::Terminalized(_)));
    assert_eq!(
        committed.transition,
        AttachTransition::FencedRecovery {
            prior_binding_epoch: old_binding.binding_epoch,
            composed_terminal: committed.member.latest_terminal(),
            next_closure_state: ClosureState::Clear,
        }
    );
}

/// A fenced recovery must not move a participant's cursor BACKWARDS.
///
/// The recovery marker says where DELIVERY stands. It does not say what the
/// participant has acknowledged, and a participant that is already past the
/// marker has acknowledged those records durably. Until this leg the fenced
/// arm persisted the marker's sequence alone, so a recovery attach behind the
/// participant's own boundary lowered the cursor; the participant's next
/// cumulative acknowledgement was then refused as a gap over records it had
/// already accounted for, it withheld further acknowledgements, and the seat
/// never came back.
///
/// RED against the pre-fix tree: the cursor came back as the marker's 14.
#[test]
fn a_fenced_recovery_behind_the_participants_own_boundary_keeps_the_boundary() {
    let old_binding = ActiveBinding {
        participant_id: 3,
        conversation_id: 29,
        binding_epoch: epoch(4, 11),
    };
    let detach_request = DetachRequest {
        conversation_id: 29,
        participant_id: 3,
        capability_generation: generation(4),
        detach_attempt_token: DetachAttemptToken::new([0xD4; 16]),
    };
    let verified_detach = old_binding
        .verify_detach_request(detach_request, [0xDD; 32])
        .expect("detach request matches old binding");
    // The participant has acknowledged well past the marker the recovery
    // proof will carry.
    let acknowledged_through = 20;
    let (pending_member, pending_state, pending_cell, _) = start_blocked_detach(
        member_acknowledged_through(acknowledged_through),
        verified_detach,
        DetachCell::default(),
        PendingBindingTerminalPosition::new(7),
        6,
    )
    .expect("blocked detach creates one paired pending cell")
    .into_parts();

    let closure_debt = debt();
    let delivery = marker_delivery_for_test(3, old_binding.binding_epoch, 14)
        .expect("validated marker fixture restores");
    let delivered = delivery
        .delivered(
            closure_debt,
            Event::marker_delivered(3, old_binding.binding_epoch, 14),
        )
        .expect("exact delivery creates marker-backed cursor progress");
    let ClosureState::Owed {
        edge: StoredEdge::ParticipantCursorProgress(progress),
        ..
    } = delivered
    else {
        panic!("marker delivery must select participant cursor progress");
    };
    let fate = progress
        .binding_fate(
            closure_debt,
            Event::binding_fate_observed(3, old_binding.binding_epoch, 5),
        )
        .expect("exact old-epoch fate derives recovery");
    let CursorFateSuccessor::DetachedCredentialRecovery(recovery) = fate else {
        panic!("marker-backed fate must derive credential recovery");
    };
    let proof = recovery
        .fenced_attach(
            super::edge::validated_marker_record_for_recovery_test(recovery),
            closure_debt,
            Event::fenced_recovery_committed(
                3,
                14,
                old_binding.binding_epoch,
                parameters().binding.binding_epoch,
                15,
            ),
            DebtCompletion::clear(),
        )
        .expect("exact fenced event consumes recovery edge");

    let verified = pending_member
        .verify_fenced_attach(
            pending_state,
            request(Some(14)),
            AttachSecretProof::Verified,
            proof,
            Some(13),
            parameters(),
        )
        .expect("proof and pending finalization name one old epoch");
    let committed = commit_attach(verified, DetachCell::Pending(pending_cell))
        .expect("fenced attach composes the pending terminal");

    // The boundary survives the generation, and the receipt states the cursor
    // the broker now holds, so the participant resumes from the same number
    // the broker has rather than acknowledging over a gap. A fenced receipt
    // carries one number in both fields — its decoder refuses one whose
    // persisted cursor and accepted marker differ — so both read as the
    // boundary here. The marker's OWN sequence is not lost: it stays in the
    // binding origin's provenance, which is where the recovery's marker is
    // read from.
    assert_eq!(committed.member.cursor(), acknowledged_through);
    assert_eq!(committed.outcome.persisted_cursor(), acknowledged_through);
    assert_eq!(
        committed.outcome.accepted_marker_delivery_seq(),
        Some(acknowledged_through)
    );
    assert_eq!(
        committed.binding_origin().recovered_marker(),
        Some((14, old_binding.binding_epoch))
    );
}

#[test]
fn supersession_cannot_coexist_with_a_committed_detach_cell() {
    let old_binding = ActiveBinding {
        participant_id: 3,
        conversation_id: 29,
        binding_epoch: epoch(4, 11),
    };
    let detach_request = DetachRequest {
        conversation_id: 29,
        participant_id: 3,
        capability_generation: generation(4),
        detach_attempt_token: DetachAttemptToken::new([0xD5; 16]),
    };
    let verified_detach = old_binding
        .verify_detach_request(detach_request, [0xEE; 32])
        .expect("detach request matches old binding");
    let (detached_member, _, _, committed_cell, _) = commit_detach(
        member(),
        verified_detach,
        DetachCell::default(),
        CommittedBindingTerminalPosition::new(8, 9),
    )
    .expect("test detach commits")
    .into_parts();
    let verified = detached_member
        .verify_superseding_attach(
            old_binding,
            request(None),
            AttachSecretProof::Verified,
            CommittedBindingTerminalPosition::new(9, 14),
            parameters(),
        )
        .expect("supersession proof is independently valid");

    assert_eq!(
        commit_attach(verified, DetachCell::Committed(committed_cell)),
        Err(AttachCommitError::DetachCellAuthority)
    );
}