liminal-server 0.19.1

Standalone server for the liminal messaging bus
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
//! Terminal sources (Died, connection-close and explicit Detached, Left, and
//! the candidate-lane drains) write their own Unit 2 extension row in place,
//! right after their base row, and no commit rebuilds the conversation from
//! its log: not a connection drop, not a leave, and not the unclean-restart
//! repair a start runs over every conversation.

use std::error::Error;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

use liminal::durability::{
    DurabilityError, DurableStore, ScanCursor, ScanPage, StoredEntry, open_ephemeral,
};
use liminal_protocol::wire::{
    AttachAttemptToken, ClientRequest, ConnectionIncarnation, CredentialAttachRequest,
    EnrollmentRequest, EnrollmentToken, Generation, LeaveAttemptToken, LeaveRequest,
    RecordAdmission, RecordAdmissionAttemptToken, ServerValue,
};

use crate::config::types::ParticipantConfig;
use crate::server::participant::{
    ConnectionFateClass, ConnectionFateWorkItem, ParticipantConnectionConversations,
    ParticipantSemanticHandler,
};

use super::ProductionParticipantHandler;
use super::log::{GENERATION_STREAM_PREFIX, STREAM_PREFIX, StoredOperation};
use super::outbox_log::{OUTBOX_STREAM_PREFIX, OutboxRow};
use super::tests::{dispatch_tracked, test_participant_config};
use super::tests_p0_64_live_extension::{base_rows, extension_rows, owed_rows_match_written_rows};

// Leave, Died and connection-close Detached measured against history length.
#[path = "tests_lifecycle_history_cost.rs"]
mod lifecycle_history_cost;

/// A store that counts every row read from any conversation's operation log
/// (base rows) and Unit 2 extension stream, through every read the store
/// offers (`read_from`, `read_at`, `scan`), plus how many reads of an
/// operation log start at its first row, the start of every rebuild from the
/// log. It can also refuse the next extension append, or let the next one land
/// and fail the flush after it.
#[derive(Debug)]
struct ReplayCountingStore {
    inner: Arc<dyn DurableStore>,
    log_reads_from_start: AtomicU64,
    base_rows_read: AtomicU64,
    extension_rows_read: AtomicU64,
    all_rows_read: AtomicU64,
    refuse_next_extension_append: AtomicBool,
    fail_flush_after_next_extension_append: AtomicBool,
    flush_failure_armed: AtomicBool,
}

impl ReplayCountingStore {
    fn new() -> Result<Arc<Self>, Box<dyn Error>> {
        Ok(Arc::new(Self {
            inner: Arc::new(open_ephemeral(1)?),
            log_reads_from_start: AtomicU64::new(0),
            base_rows_read: AtomicU64::new(0),
            extension_rows_read: AtomicU64::new(0),
            all_rows_read: AtomicU64::new(0),
            refuse_next_extension_append: AtomicBool::new(false),
            fail_flush_after_next_extension_append: AtomicBool::new(false),
            flush_failure_armed: AtomicBool::new(false),
        }))
    }

    fn replays(&self) -> u64 {
        self.log_reads_from_start.load(Ordering::SeqCst)
    }

    /// Base rows and extension rows read since the last reset.
    fn rows_read(&self) -> (u64, u64) {
        (
            self.base_rows_read.load(Ordering::SeqCst),
            self.extension_rows_read.load(Ordering::SeqCst),
        )
    }

    /// Rows read from any stream at all since the last reset.
    fn all_rows_read(&self) -> u64 {
        self.all_rows_read.load(Ordering::SeqCst)
    }

    fn reset(&self) {
        self.log_reads_from_start.store(0, Ordering::SeqCst);
        self.base_rows_read.store(0, Ordering::SeqCst);
        self.extension_rows_read.store(0, Ordering::SeqCst);
        self.all_rows_read.store(0, Ordering::SeqCst);
    }

    fn count(&self, key: &str, rows: usize) {
        let rows = u64::try_from(rows).unwrap_or(u64::MAX);
        self.all_rows_read.fetch_add(rows, Ordering::SeqCst);
        if covers_operation_log(key) {
            self.base_rows_read.fetch_add(rows, Ordering::SeqCst);
        }
        if covers(key, OUTBOX_STREAM_PREFIX) {
            self.extension_rows_read.fetch_add(rows, Ordering::SeqCst);
        }
    }
}

fn is_operation_log(stream_key: &str) -> bool {
    stream_key.starts_with(STREAM_PREFIX) || stream_key.starts_with(GENERATION_STREAM_PREFIX)
}

/// Whether a stream key, or a scan prefix, reaches streams under `prefix`.
fn covers(key: &str, prefix: &str) -> bool {
    key.starts_with(prefix) || prefix.starts_with(key)
}

fn covers_operation_log(key: &str) -> bool {
    covers(key, STREAM_PREFIX) || covers(key, GENERATION_STREAM_PREFIX)
}

#[async_trait::async_trait]
impl DurableStore for ReplayCountingStore {
    async fn append(
        &self,
        stream_key: &str,
        payload: Vec<u8>,
        expected_seq: u64,
    ) -> Result<u64, DurabilityError> {
        let extension = stream_key.starts_with(OUTBOX_STREAM_PREFIX);
        if extension
            && self
                .refuse_next_extension_append
                .swap(false, Ordering::SeqCst)
        {
            return Err(DurabilityError::ConfigError(
                "the test refused this extension append".to_owned(),
            ));
        }
        let assigned = self.inner.append(stream_key, payload, expected_seq).await?;
        if extension
            && self
                .fail_flush_after_next_extension_append
                .swap(false, Ordering::SeqCst)
        {
            self.flush_failure_armed.store(true, Ordering::SeqCst);
        }
        Ok(assigned)
    }

    async fn append_all(
        &self,
        stream_key: &str,
        payloads: Vec<Vec<u8>>,
        expected_seq: u64,
    ) -> Result<u64, DurabilityError> {
        self.inner
            .append_all(stream_key, payloads, expected_seq)
            .await
    }

    async fn read_from(
        &self,
        stream_key: &str,
        offset: u64,
        limit: usize,
    ) -> Result<Vec<StoredEntry>, DurabilityError> {
        if offset == 0 && is_operation_log(stream_key) {
            self.log_reads_from_start.fetch_add(1, Ordering::SeqCst);
        }
        let rows = self.inner.read_from(stream_key, offset, limit).await?;
        self.count(stream_key, rows.len());
        Ok(rows)
    }

    async fn read_at(
        &self,
        stream_key: &str,
        sequence: u64,
    ) -> Result<Option<StoredEntry>, DurabilityError> {
        let row = self.inner.read_at(stream_key, sequence).await?;
        self.count(stream_key, usize::from(row.is_some()));
        Ok(row)
    }

    async fn cas(&self, key: &str, old_value: u64, new_value: u64) -> Result<(), DurabilityError> {
        self.inner.cas(key, old_value, new_value).await
    }

    async fn read_stream_next_seq(&self, stream_key: &str) -> Result<Option<u64>, DurabilityError> {
        self.inner.read_stream_next_seq(stream_key).await
    }

    async fn read_value(&self, key: &str) -> Result<Option<u64>, DurabilityError> {
        self.inner.read_value(key).await
    }

    async fn scan_page(
        &self,
        prefix: &str,
        cursor: Option<ScanCursor>,
        limit: usize,
    ) -> Result<ScanPage, DurabilityError> {
        let page = self.inner.scan_page(prefix, cursor, limit).await?;
        self.count(prefix, page.entries.len());
        Ok(page)
    }

    async fn flush(&self) -> Result<(), DurabilityError> {
        if self.flush_failure_armed.swap(false, Ordering::SeqCst) {
            return Err(DurabilityError::ConfigError(
                "the test failed the flush after an extension append that landed".to_owned(),
            ));
        }
        self.inner.flush().await
    }
}

struct Member {
    connection: ConnectionIncarnation,
    conversations: ParticipantConnectionConversations,
    participant_id: u64,
    generation: Generation,
    attach_secret: liminal_protocol::wire::AttachSecret,
}

fn enroll_and_attach(
    handler: &ProductionParticipantHandler,
    conversation_id: u64,
    connection: ConnectionIncarnation,
    token: u8,
) -> Result<Member, Box<dyn Error>> {
    let mut conversations = ParticipantConnectionConversations::default();
    let enrolled = dispatch_tracked(
        handler,
        connection,
        &mut conversations,
        ClientRequest::Enrollment(EnrollmentRequest {
            conversation_id,
            enrollment_token: EnrollmentToken::new([token; 16]),
        }),
    )?;
    let ServerValue::EnrollBound(enrolled) = enrolled else {
        return Err(format!("enrollment {token:#x} did not bind: {enrolled:?}").into());
    };
    let attached = dispatch_tracked(
        handler,
        connection,
        &mut conversations,
        ClientRequest::CredentialAttach(CredentialAttachRequest {
            conversation_id,
            participant_id: enrolled.participant_id(),
            capability_generation: Generation::ONE,
            attach_secret: enrolled.attach_secret(),
            attach_attempt_token: AttachAttemptToken::new([token.wrapping_add(1); 16]),
            accept_marker_delivery_seq: None,
        }),
    )?;
    let ServerValue::AttachBound(attached) = attached else {
        return Err(format!("attach {token:#x} did not bind: {attached:?}").into());
    };
    Ok(Member {
        connection,
        conversations,
        participant_id: enrolled.participant_id(),
        generation: attached.origin_binding_epoch().capability_generation,
        attach_secret: attached.attach_secret(),
    })
}

fn admit(
    handler: &ProductionParticipantHandler,
    conversation_id: u64,
    member: &mut Member,
    token: u8,
) -> Result<ServerValue, Box<dyn Error>> {
    dispatch_tracked(
        handler,
        member.connection,
        &mut member.conversations,
        ClientRequest::RecordAdmission(RecordAdmission {
            conversation_id,
            participant_id: member.participant_id,
            capability_generation: member.generation,
            record_admission_attempt_token: RecordAdmissionAttemptToken::new([token; 16]),
            payload: vec![token],
        }),
    )
}

fn drop_connection(
    handler: &ProductionParticipantHandler,
    member: &Member,
    class: ConnectionFateClass,
    open_sequence: u64,
) -> Result<(), Box<dyn Error>> {
    handler
        .apply_connection_fate_with_impacts(&ConnectionFateWorkItem {
            open_sequence,
            connection_incarnation: member.connection,
            class,
            tracked_conversations: member.conversations.tracked_conversations(),
        })
        .into_result()?;
    Ok(())
}

/// Every owing base row has exactly its one extension row, and a cold load of
/// the same store neither writes nor changes any extension row.
fn assert_complete_and_unrepaired(
    store: &Arc<ReplayCountingStore>,
    handler: ProductionParticipantHandler,
    config: ParticipantConfig,
    conversation_id: u64,
    label: &str,
) -> Result<ProductionParticipantHandler, Box<dyn Error>> {
    let base = base_rows(&handler, conversation_id)?;
    let live_extension = extension_rows(&handler, conversation_id)?;
    owed_rows_match_written_rows(&base, &live_extension, label);
    drop(handler);
    let reopened =
        ProductionParticipantHandler::new(Arc::clone(store) as Arc<dyn DurableStore>, config)?;
    assert_eq!(
        extension_rows(&reopened, conversation_id)?,
        live_extension,
        "after {label} a cold load changed the extension stream, so the live commit left a row \
         for it to repair"
    );
    Ok(reopened)
}

fn base_kinds(
    handler: &ProductionParticipantHandler,
    conversation_id: u64,
) -> Result<Vec<&'static str>, Box<dyn Error>> {
    Ok(base_rows(handler, conversation_id)?
        .iter()
        .map(|(_, operation)| match operation {
            StoredOperation::Died { .. } => "died",
            StoredOperation::Detached { .. } => "detached",
            StoredOperation::Left { .. } => "left",
            StoredOperation::RecordAdmission { .. } => "record",
            StoredOperation::Ordinary { .. } => "ordinary",
            _ => "other",
        })
        .collect())
}

#[test]
fn connection_loss_and_close_commit_their_rows_in_place_with_no_replay()
-> Result<(), Box<dyn Error>> {
    const CONVERSATION: u64 = 0x7E1;
    let store = ReplayCountingStore::new()?;
    let config = test_participant_config();
    let handler =
        ProductionParticipantHandler::new(Arc::clone(&store) as Arc<dyn DurableStore>, config)?;
    let lost = enroll_and_attach(
        &handler,
        CONVERSATION,
        ConnectionIncarnation::new(71, 1),
        0x11,
    )?;
    let closed = enroll_and_attach(
        &handler,
        CONVERSATION,
        ConnectionIncarnation::new(71, 2),
        0x21,
    )?;
    let _peer = enroll_and_attach(
        &handler,
        CONVERSATION,
        ConnectionIncarnation::new(71, 3),
        0x31,
    )?;

    store.reset();
    drop_connection(&handler, &lost, ConnectionFateClass::ConnectionLost, 5)?;
    drop_connection(&handler, &closed, ConnectionFateClass::CleanDisconnect, 6)?;
    assert_eq!(
        store.replays(),
        0,
        "a connection drop rebuilt the conversation from its log"
    );
    assert_eq!(
        store.rows_read(),
        (0, 0),
        "a connection drop read base or extension rows"
    );
    let kinds = base_kinds(&handler, CONVERSATION)?;
    assert!(
        kinds.contains(&"died") && kinds.contains(&"detached"),
        "{kinds:?}"
    );
    assert_complete_and_unrepaired(&store, handler, config, CONVERSATION, "connection drops")?;
    Ok(())
}

#[test]
fn leave_commits_its_row_in_place_with_no_replay() -> Result<(), Box<dyn Error>> {
    const CONVERSATION: u64 = 0x7E2;
    let store = ReplayCountingStore::new()?;
    let config = test_participant_config();
    let handler =
        ProductionParticipantHandler::new(Arc::clone(&store) as Arc<dyn DurableStore>, config)?;
    let mut leaver = enroll_and_attach(
        &handler,
        CONVERSATION,
        ConnectionIncarnation::new(72, 1),
        0x41,
    )?;
    let _peer = enroll_and_attach(
        &handler,
        CONVERSATION,
        ConnectionIncarnation::new(72, 2),
        0x51,
    )?;

    store.reset();
    let left = dispatch_tracked(
        &handler,
        leaver.connection,
        &mut leaver.conversations,
        ClientRequest::Leave(LeaveRequest {
            conversation_id: CONVERSATION,
            participant_id: leaver.participant_id,
            capability_generation: leaver.generation,
            attach_secret: leaver.attach_secret,
            leave_attempt_token: LeaveAttemptToken::new([0x42; 16]),
        }),
    )?;
    assert!(matches!(left, ServerValue::LeaveCommitted(_)), "{left:?}");
    assert_eq!(
        store.replays(),
        0,
        "a leave rebuilt the conversation from its log"
    );
    assert_eq!(
        store.rows_read(),
        (0, 0),
        "a leave read base or extension rows"
    );
    assert_complete_and_unrepaired(&store, handler, config, CONVERSATION, "a leave")?;
    Ok(())
}

/// Retention at its cap with a peer that never acks, so a lost connection's
/// terminal pends; the peer's next record then drains that terminal and
/// commits its own record in ONE operation — two owing base rows — which is
/// exactly the shape whose rows must reach the extension stream in base order.
#[test]
fn a_drained_terminal_and_the_record_that_drained_it_complete_in_base_order()
-> Result<(), Box<dyn Error>> {
    const CONVERSATION: u64 = 0x7E3;
    let mut config = test_participant_config();
    config.max_retained_record_rows = 4;
    let store = ReplayCountingStore::new()?;
    let handler =
        ProductionParticipantHandler::new(Arc::clone(&store) as Arc<dyn DurableStore>, config)?;
    let mut victim = enroll_and_attach(
        &handler,
        CONVERSATION,
        ConnectionIncarnation::new(73, 1),
        0x61,
    )?;
    let mut peer_conversations = ParticipantConnectionConversations::default();
    let peer = dispatch_tracked(
        &handler,
        ConnectionIncarnation::new(73, 2),
        &mut peer_conversations,
        ClientRequest::Enrollment(EnrollmentRequest {
            conversation_id: CONVERSATION,
            enrollment_token: EnrollmentToken::new([0x71; 16]),
        }),
    )?;
    let ServerValue::EnrollBound(peer) = peer else {
        return Err(format!("peer enrollment did not bind: {peer:?}").into());
    };
    let committed = admit(&handler, CONVERSATION, &mut victim, 0x62)?;
    assert!(
        matches!(committed, ServerValue::RecordCommitted(_)),
        "{committed:?}"
    );

    store.reset();
    drop_connection(&handler, &victim, ConnectionFateClass::ConnectionLost, 9)?;
    assert_eq!(
        store.replays(),
        0,
        "the drop rebuilt the conversation from its log"
    );
    let mut peer_member = Member {
        connection: ConnectionIncarnation::new(73, 2),
        conversations: peer_conversations,
        participant_id: peer.participant_id(),
        generation: Generation::ONE,
        attach_secret: peer.attach_secret(),
    };
    let before = base_rows(&handler, CONVERSATION)?.len();
    store.reset();
    let drained = admit(&handler, CONVERSATION, &mut peer_member, 0x72)?;
    assert!(
        matches!(drained, ServerValue::RecordCommitted(_)),
        "{drained:?}"
    );
    assert_eq!(
        store.replays(),
        0,
        "the drop or the draining record rebuilt the conversation from its log"
    );

    let base = base_rows(&handler, CONVERSATION)?;
    let appended: Vec<_> = base
        .iter()
        .skip(before)
        .map(|(sequence, operation)| (*sequence, operation.clone()))
        .collect();
    assert!(
        matches!(
            appended.as_slice(),
            [
                (_, StoredOperation::Died { .. }),
                ..,
                (_, StoredOperation::RecordAdmission { .. })
            ]
        ),
        "the peer's record did not drain the pending terminal first: {:?}",
        base_kinds(&handler, CONVERSATION)?
    );
    let extension = extension_rows(&handler, CONVERSATION)?;
    let sources: Vec<u64> = extension
        .iter()
        .filter_map(|(_, row)| match row {
            OutboxRow::Produced(batch) => Some(batch.source_log_sequence()),
            OutboxRow::AckAdvanced {
                source_log_sequence,
                ..
            } => Some(*source_log_sequence),
            OutboxRow::MarkerAckCommitted(_) => None,
        })
        .collect();
    let mut ascending = sources.clone();
    ascending.sort_unstable();
    assert_eq!(
        sources, ascending,
        "extension rows are out of base-row order"
    );
    assert_complete_and_unrepaired(
        &store,
        handler,
        config,
        CONVERSATION,
        "a drain and its record",
    )?;
    Ok(())
}

/// The crash point between a base row and its extension row: the commit is
/// refused by name, and the next request on the conversation writes the
/// missing row before anything of its own.
///
/// A Leave carries it here. A connection fate that fails part way latches the
/// service fatal instead, by its own design: its durable Open is its retry.
#[test]
fn an_unwritten_extension_row_is_refused_by_name_and_written_by_the_next_request()
-> Result<(), Box<dyn Error>> {
    const CONVERSATION: u64 = 0x7E4;
    let store = ReplayCountingStore::new()?;
    let config = test_participant_config();
    let handler =
        ProductionParticipantHandler::new(Arc::clone(&store) as Arc<dyn DurableStore>, config)?;
    let mut leaver = enroll_and_attach(
        &handler,
        CONVERSATION,
        ConnectionIncarnation::new(74, 1),
        0x81,
    )?;
    let mut peer = enroll_and_attach(
        &handler,
        CONVERSATION,
        ConnectionIncarnation::new(74, 2),
        0x91,
    )?;

    store
        .refuse_next_extension_append
        .store(true, Ordering::SeqCst);
    let refused = dispatch_tracked(
        &handler,
        leaver.connection,
        &mut leaver.conversations,
        ClientRequest::Leave(LeaveRequest {
            conversation_id: CONVERSATION,
            participant_id: leaver.participant_id,
            capability_generation: leaver.generation,
            attach_secret: leaver.attach_secret,
            leave_attempt_token: LeaveAttemptToken::new([0x82; 16]),
        }),
    );
    let text = match refused {
        Ok(value) => {
            return Err(
                format!("the leave answered although its row was refused: {value:?}").into(),
            );
        }
        Err(error) => error.to_string(),
    };
    assert!(
        text.contains("is not confirmed durable")
            && text.contains("the next request on it reloads"),
        "the refusal does not name the missing row and the act that writes it: {text}"
    );
    let base = base_rows(&handler, CONVERSATION)?;
    let left_sequence = base
        .iter()
        .rev()
        .find_map(|(sequence, operation)| {
            matches!(operation, StoredOperation::Left { .. }).then_some(*sequence)
        })
        .ok_or("the Left base row was not durable")?;
    let before = extension_rows(&handler, CONVERSATION)?;
    assert!(
        !before.iter().any(|(_, row)| matches!(
            row,
            OutboxRow::Produced(batch) if batch.source_log_sequence() == left_sequence
        )),
        "the refused extension row was written anyway"
    );

    let next = admit(&handler, CONVERSATION, &mut peer, 0x92)?;
    assert!(matches!(next, ServerValue::RecordCommitted(_)), "{next:?}");
    let after = extension_rows(&handler, CONVERSATION)?;
    let left_row = after
        .iter()
        .position(|(_, row)| {
            matches!(
                row,
                OutboxRow::Produced(batch) if batch.source_log_sequence() == left_sequence
            )
        })
        .ok_or("the next request did not write the missing extension row")?;
    let record_row = after
        .iter()
        .position(|(_, row)| {
            matches!(
                row,
                OutboxRow::Produced(batch) if batch.source_log_sequence() > left_sequence
            )
        })
        .ok_or("the next request's own extension row is missing")?;
    assert!(
        left_row < record_row,
        "the missing row was written after the next request's own row"
    );
    assert_complete_and_unrepaired(&store, handler, config, CONVERSATION, "the recovered leave")?;
    Ok(())
}

/// A start's unclean-restart repair walks every conversation and closes each
/// binding the previous server process left Bound. It reads no operation-log
/// row, however long the conversation's history: its work is the bindings it
/// closes, never the rows behind them.
#[test]
fn restart_repair_reads_no_log_rows_whatever_the_history_length() -> Result<(), Box<dyn Error>> {
    const CONVERSATION: u64 = 0x7E5;
    const PRIOR_SERVER: u64 = 75;
    let mut measured = Vec::new();
    for records in [2_u16, 96] {
        let store = ReplayCountingStore::new()?;
        let config = test_participant_config();
        let handler =
            ProductionParticipantHandler::new(Arc::clone(&store) as Arc<dyn DurableStore>, config)?;
        let mut writer = enroll_and_attach(
            &handler,
            CONVERSATION,
            ConnectionIncarnation::new(PRIOR_SERVER, 1),
            0xA1,
        )?;
        let _reader = enroll_and_attach(
            &handler,
            CONVERSATION,
            ConnectionIncarnation::new(PRIOR_SERVER, 2),
            0xB1,
        )?;
        for index in 0..records {
            let [high, low] = index.to_be_bytes();
            let mut token = [0xC0; 16];
            token[0] = high;
            token[1] = low;
            let committed = dispatch_tracked(
                &handler,
                writer.connection,
                &mut writer.conversations,
                ClientRequest::RecordAdmission(RecordAdmission {
                    conversation_id: CONVERSATION,
                    participant_id: writer.participant_id,
                    capability_generation: writer.generation,
                    record_admission_attempt_token: RecordAdmissionAttemptToken::new(token),
                    payload: vec![low],
                }),
            )?;
            assert!(
                matches!(committed, ServerValue::RecordCommitted(_)),
                "{committed:?}"
            );
        }
        let history = base_rows(&handler, CONVERSATION)?.len();
        drop(handler);

        let reopened =
            ProductionParticipantHandler::new(Arc::clone(&store) as Arc<dyn DurableStore>, config)?;
        store.reset();
        reopened.repair_unclean_server_restart(PRIOR_SERVER + 1)?;
        assert_eq!(
            (store.replays(), store.rows_read()),
            (0, (0, 0)),
            "the restart repair over {history} rows of history read base or extension rows \
             (rebuilds from row 0, (base rows, extension rows))"
        );
        let kinds = base_kinds(&reopened, CONVERSATION)?;
        assert_eq!(
            kinds.iter().filter(|kind| **kind == "died").count(),
            2,
            "the repair did not close both bindings the prior process left Bound: {kinds:?}"
        );
        measured.push((history, store.rows_read()));
        assert_complete_and_unrepaired(
            &store,
            reopened,
            config,
            CONVERSATION,
            "an unclean-restart repair",
        )?;
    }
    assert!(
        measured[0].0 < measured[1].0,
        "the two runs did not differ in history length: {measured:?}"
    );
    Ok(())
}

/// The extension append lands and the flush after it fails: the commit is
/// refused as unconfirmed, the row is already in the stream, and the next
/// request keeps it rather than writing a second copy.
#[test]
fn an_extension_row_whose_flush_failed_is_kept_once_by_the_next_request()
-> Result<(), Box<dyn Error>> {
    const CONVERSATION: u64 = 0x7E6;
    let store = ReplayCountingStore::new()?;
    let config = test_participant_config();
    let handler =
        ProductionParticipantHandler::new(Arc::clone(&store) as Arc<dyn DurableStore>, config)?;
    let mut leaver = enroll_and_attach(
        &handler,
        CONVERSATION,
        ConnectionIncarnation::new(76, 1),
        0xD1,
    )?;
    let mut peer = enroll_and_attach(
        &handler,
        CONVERSATION,
        ConnectionIncarnation::new(76, 2),
        0xE1,
    )?;

    store
        .fail_flush_after_next_extension_append
        .store(true, Ordering::SeqCst);
    let refused = dispatch_tracked(
        &handler,
        leaver.connection,
        &mut leaver.conversations,
        ClientRequest::Leave(LeaveRequest {
            conversation_id: CONVERSATION,
            participant_id: leaver.participant_id,
            capability_generation: leaver.generation,
            attach_secret: leaver.attach_secret,
            leave_attempt_token: LeaveAttemptToken::new([0xD2; 16]),
        }),
    );
    let text = match refused {
        Ok(value) => {
            return Err(
                format!("the leave answered although its row's flush failed: {value:?}").into(),
            );
        }
        Err(error) => error.to_string(),
    };
    assert!(
        text.contains("is not confirmed durable") && text.contains("flush after an extension"),
        "the refusal does not say the row is unconfirmed and keep its cause: {text}"
    );
    let left_sequence = base_rows(&handler, CONVERSATION)?
        .iter()
        .rev()
        .find_map(|(sequence, operation)| {
            matches!(operation, StoredOperation::Left { .. }).then_some(*sequence)
        })
        .ok_or("the Left base row was not durable")?;
    let rows_for_left = |rows: &[(u64, OutboxRow)]| {
        rows.iter()
            .filter(|(_, row)| {
                matches!(
                    row,
                    OutboxRow::Produced(batch) if batch.source_log_sequence() == left_sequence
                )
            })
            .count()
    };
    assert_eq!(
        rows_for_left(&extension_rows(&handler, CONVERSATION)?),
        1,
        "the landed extension row is not in the stream exactly once"
    );

    let next = admit(&handler, CONVERSATION, &mut peer, 0xE2)?;
    assert!(matches!(next, ServerValue::RecordCommitted(_)), "{next:?}");
    let after = extension_rows(&handler, CONVERSATION)?;
    assert_eq!(
        rows_for_left(&after),
        1,
        "the next request wrote a second copy of a row that had landed"
    );
    assert!(
        after.iter().any(|(_, row)| matches!(
            row,
            OutboxRow::Produced(batch) if batch.source_log_sequence() > left_sequence
        )),
        "the next request's own extension row is missing"
    );
    let reopened = assert_complete_and_unrepaired(
        &store,
        handler,
        config,
        CONVERSATION,
        "a leave whose flush failed",
    )?;
    assert_eq!(
        rows_for_left(&extension_rows(&reopened, CONVERSATION)?),
        1,
        "a reopen wrote a second copy of the landed row"
    );
    Ok(())
}