kunobi-daemon 0.10.1

Process ownership, request draining, and verified upgrades for local daemons
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
//! Blocking transport primitives extracted from the Kunobi relay.
//!
//! Transport adapters supply half-close and their own I/O deadlines. Discovery,
//! authentication, request IDs, and protocol bootstrap remain with the caller.

#[cfg(loom)]
use loom::sync::{Condvar, Mutex, MutexGuard};
use std::collections::BTreeMap;
use std::io::{self, Read, Write};
use std::sync::TryLockError;
#[cfg(not(loom))]
use std::sync::{Condvar, Mutex, MutexGuard};

/// A transport writer that can close requests while preserving incoming replies.
pub trait WriteHalf: Write + Send + 'static {
    /// Close the sending direction without closing the receiving direction.
    fn shutdown_write(&mut self) -> io::Result<()>;
}

/// The current peer writer, replaceable without waiting for client input.
pub struct WriterSlot<W> {
    state: Mutex<WriterState<W>>,
    changed: Condvar,
}

struct WriterState<W> {
    generation: u64,
    writer: W,
    paused: bool,
    at_boundary: bool,
    written: u64,
    failed: bool,
    ended: bool,
    closed: bool,
}

impl<W: WriteHalf> WriterSlot<W> {
    /// Retain the initial connected writer.
    pub fn new(writer: W) -> Self {
        Self {
            state: Mutex::new(WriterState {
                generation: 0,
                writer,
                paused: false,
                at_boundary: true,
                written: 0,
                failed: false,
                ended: false,
                closed: false,
            }),
            changed: Condvar::new(),
        }
    }

    /// Install immediately; only one writer is retained even across repeated
    /// idle broker restarts.
    pub fn replace(&self, writer: W) {
        self.replace_with_offset(writer, 0);
    }

    /// Install a new writer with its already-written bootstrap byte count.
    pub fn replace_with_offset(&self, writer: W, written: u64) {
        self.replace_paused(writer, written);
        self.resume();
    }

    /// Keep future client bytes parked until old request observations have
    /// been settled by the downstream coordinator.
    pub fn replace_paused(&self, writer: W, written: u64) {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        if state.closed {
            let mut writer = writer;
            let _ = writer.shutdown_write();
            return;
        }
        let mut old = std::mem::replace(&mut state.writer, writer);
        state.generation = state.generation.wrapping_add(1);
        state.written = written;
        state.at_boundary = true;
        state.failed = false;
        state.paused = true;
        if state.ended {
            let _ = state.writer.shutdown_write();
        }
        self.changed.notify_all();
        drop(state);
        let _ = old.shutdown_write();
    }

    /// Freeze only between successful whole writes ending at a newline.
    /// A blocked writer or partial record postpones this connection's upgrade.
    pub fn try_pause(&self) -> Option<u64> {
        let mut state = match self.state.try_lock() {
            Ok(state) => state,
            Err(TryLockError::Poisoned(error)) => error.into_inner(),
            Err(TryLockError::WouldBlock) => return None,
        };
        if state.paused || state.failed || state.ended || state.closed || !state.at_boundary {
            return None;
        }
        state.paused = true;
        Some(state.written)
    }

    /// Resume client writes after the coordinator settles the old session.
    pub fn resume(&self) {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        state.paused = false;
        self.changed.notify_all();
    }

    /// Half-close the current writer, marking the end of the request stream.
    ///
    /// Public for the coordinator: when a reconnect completes after the
    /// upstream thread has already exited, nobody else is left to signal the
    /// replacement connection that no request will ever come.
    ///
    /// An error means the peer did not learn that the requests ended, for
    /// example because the transport has no half-close. End the session
    /// another way, such as [`Outstanding::wait_settled`].
    pub fn shutdown(&self) -> io::Result<()> {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        state.ended = true;
        state.writer.shutdown_write()
    }

    /// Stop accepting bytes and wake writers waiting for a replacement.
    /// This cannot interrupt a transport write that is already blocked.
    ///
    /// Waiting writers are released even when the half-close fails; the error
    /// only reports that the peer did not learn that the requests ended.
    pub fn close(&self) -> io::Result<()> {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        state.closed = true;
        let result = state.writer.shutdown_write();
        self.changed.notify_all();
        result
    }

    /// Write once. On ambiguity, discard the window and wait until the main
    /// thread has installed a different connection before reading more stdin.
    #[cfg(test)]
    fn write_or_wait_for_replacement(&self, bytes: &[u8]) {
        self.write_observed(bytes, || {});
    }

    /// Observe and write one window under the same pause boundary.
    /// A failed window is never replayed. The call waits for a replacement or
    /// `close`; transport writes must have their own deadlines.
    pub fn write_observed(&self, bytes: &[u8], observe: impl FnOnce()) {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        while state.paused && !state.closed {
            state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner());
        }
        if state.closed {
            return;
        }
        // Observation shares the pause boundary with the write. Unsent input
        // waiting for B must not be cleared with A's completed request ids.
        observe();
        if state
            .writer
            .write_all(bytes)
            .and_then(|()| state.writer.flush())
            .is_ok()
        {
            match state.written.checked_add(bytes.len() as u64) {
                Some(written) => state.written = written,
                None => state.failed = true,
            }
            state.at_boundary = bytes.last().is_none_or(|byte| *byte == b'\n');
            return;
        }
        state.failed = true;
        let _ = state.writer.shutdown_write();
        let failed_generation = state.generation;
        while state.generation == failed_generation && !state.closed {
            state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner());
        }
    }
}

/// Maximum bytes buffered in one transfer direction.
pub const BUFFER_SIZE: usize = 65_536;

/// Why forwarding from the peer to the client stopped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PumpExit {
    /// The peer closed or failed its stream; the coordinator may reconnect.
    PeerClosed,
    /// Writing to the client failed.
    ClientGone,
}

fn copy_flushing<R: Read, W: Write>(from: &mut R, to: &mut W, buf: &mut [u8]) -> io::Result<()> {
    loop {
        let n = match from.read(buf) {
            Ok(0) => return Ok(()),
            Ok(n) => n,
            // A signal interrupting a blocking read is not a failure; retrying
            // is the documented contract. Treating it as EOF would silently
            // truncate a response.
            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
            Err(e) => return Err(e),
        };
        to.write_all(&buf[..n])?;
        // Without this a response with no trailing newline sits in the
        // LineWriter and the client waits forever.
        to.flush()?;
    }
}

/// Forward opaque request bytes, flushing each window, then half-close the peer.
/// The response direction remains open for a late reply after client EOF.
///
/// A copy error is returned first. Otherwise the half-close error is: for
/// example `Unsupported` on a named pipe, where the peer was not told that the
/// requests ended and the caller must end the session with [`Outstanding`].
pub fn pump_upstream<R: Read, W: WriteHalf>(client_in: &mut R, sock_w: &mut W) -> io::Result<()> {
    let mut buf = vec![0u8; BUFFER_SIZE];
    let result = copy_flushing(client_in, sock_w, &mut buf);
    // Signal end-of-request-stream whichever way we got here. If the client
    // vanished mid-write the broker still needs to stop waiting for more, so
    // this is deliberately not on the success path only.
    let shutdown = sock_w.shutdown_write();
    result.and(shutdown)
}

/// Forward opaque response bytes, flushing even a newline-free tail.
/// On peer closure the caller may replace the connection; do not join a thread
/// that is still waiting for client input.
pub fn pump_downstream<R: Read, W: Write>(sock_r: &mut R, client_out: &mut W) -> PumpExit {
    let mut buf = vec![0u8; BUFFER_SIZE];
    loop {
        let n = match sock_r.read(&mut buf) {
            Ok(0) => {
                return if client_out.flush().is_ok() {
                    PumpExit::PeerClosed
                } else {
                    PumpExit::ClientGone
                };
            }
            Ok(n) => n,
            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
            Err(_) => return PumpExit::PeerClosed,
        };
        if client_out
            .write_all(&buf[..n])
            .and_then(|()| client_out.flush())
            .is_err()
        {
            return PumpExit::ClientGone;
        }
    }
}

/// Combine independently owned halves for a blocking codec.
pub struct SplitIo<R, W> {
    /// Input half.
    pub read: R,
    /// Output half.
    pub write: W,
}
impl<R: std::io::Read, W> std::io::Read for SplitIo<R, W> {
    fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
        self.read.read(bytes)
    }
}
impl<R, W: std::io::Write> std::io::Write for SplitIo<R, W> {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        self.write.write(bytes)
    }
    fn flush(&mut self) -> std::io::Result<()> {
        self.write.flush()
    }
}

/// Requests sent to the peer whose replies have not yet reached the client.
///
/// When the client stops sending, [`WriterSlot::shutdown`] half-closes the
/// connection so the peer answers what it has and then closes. A transport
/// without a half-close, such as a Windows named pipe, cannot deliver that
/// signal, and both ends would wait for each other. There the session instead
/// ends once every outstanding request is settled: [`Outstanding::wait_settled`]
/// returns, and the caller closes the connection.
///
/// The caller decides what a key is (for example a JSON-RPC id) and calls
/// [`Outstanding::settle`] only after the reply has been written and flushed
/// to the client, including any record delimiter. Settling earlier lets the
/// session end with part of a reply unsent.
///
/// Settlements carry the [`Epoch`] in which the peer connection delivering
/// them started. [`Outstanding::fail`] and [`Outstanding::clear`] start a new
/// epoch, so a late reply from a failed peer cannot settle a newer request that
/// reuses its key.
///
/// An update wakes blocked [`Outstanding::wait_settled`] callers only when it
/// leaves the set settled and at least one caller is waiting, so settling a
/// reply that leaves others outstanding, or that nobody waits on, costs no
/// wake-up.
pub struct Outstanding<K> {
    state: Mutex<OutstandingState<K>>,
    changed: Condvar,
    capacity: usize,
}

struct OutstandingState<K> {
    /// Each key with the number of its requests in flight. A client may reuse
    /// a key before the first reply arrives, and each request needs its own.
    keys: BTreeMap<K, usize>,
    /// Requests in flight, counting every duplicate.
    tracked: usize,
    /// Bumped whenever the tracked requests are failed or cleared.
    epoch: u64,
    /// A request arrived while the set was full, so an empty set no longer
    /// proves that every reply was delivered.
    overflowed: bool,
    /// [`Failing`] guards alive: keys taken, their errors still being written.
    failing: usize,
    /// [`Transition`] guards alive: the session is moving between peers.
    transitions: usize,
    /// Callers blocked in [`Outstanding::wait_settled`]. Updates skip the
    /// wake-up while this is zero.
    waiters: usize,
}

impl<K: Ord> Outstanding<K> {
    /// Track at most `capacity` requests. Beyond it the set can no longer
    /// prove that it is settled, until the requests are failed or cleared.
    pub fn new(capacity: usize) -> Self {
        Self {
            state: Mutex::new(OutstandingState {
                keys: BTreeMap::new(),
                tracked: 0,
                epoch: 0,
                overflowed: false,
                failing: 0,
                transitions: 0,
                waiters: 0,
            }),
            changed: Condvar::new(),
            capacity,
        }
    }

    fn lock(&self) -> MutexGuard<'_, OutstandingState<K>> {
        self.state.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Wake every blocked [`Outstanding::wait_settled`] caller if `state` is
    /// settled. Call it with the lock still held after an update: a waiter
    /// registers and checks settledness under the same lock, so it is either
    /// counted here or sees the settled state before it would block.
    fn wake_if_settled(&self, state: &OutstandingState<K>) {
        if state.must_wake() {
            self.changed.notify_all();
        }
    }

    /// Record a request sent to the peer.
    pub fn begin(&self, key: K) {
        let mut state = self.lock();
        if state.tracked < self.capacity {
            *state.keys.entry(key).or_insert(0) += 1;
            state.tracked += 1;
        } else {
            state.overflowed = true;
        }
    }

    /// The current epoch. Capture it when a peer connection starts and pass it
    /// to [`Outstanding::settle`] for every reply that connection delivers.
    pub fn epoch(&self) -> Epoch {
        Epoch(self.lock().epoch)
    }

    /// Record that one reply for `key`, delivered by a connection that started
    /// in `epoch`, has fully reached the client. A reply from before the last
    /// [`Outstanding::fail`] or [`Outstanding::clear`] settles nothing.
    pub fn settle(&self, epoch: Epoch, key: &K) {
        let mut state = self.lock();
        if epoch.0 != state.epoch {
            return;
        }
        if let Some(count) = state.keys.get_mut(key) {
            *count -= 1;
            if *count == 0 {
                state.keys.remove(key);
            }
            state.tracked -= 1;
            self.wake_if_settled(&state);
        }
    }

    /// Record that the peer proved every request settled, for example with a
    /// handoff receipt after all replies reached the client.
    pub fn clear(&self) {
        let mut state = self.lock();
        state.keys.clear();
        state.tracked = 0;
        state.epoch += 1;
        state.overflowed = false;
        self.wake_if_settled(&state);
    }

    /// Take every outstanding request to report it as failed, because the
    /// peer that owned it is gone. The set does not count as settled until
    /// the returned guard drops, so the caller can finish writing the
    /// failures first. Untracked requests fail with the session, so this also
    /// clears an overflow.
    pub fn fail(&self) -> Failing<'_, K> {
        let mut state = self.lock();
        state.failing += 1;
        state.overflowed = false;
        state.tracked = 0;
        state.epoch += 1;
        let keys = std::mem::take(&mut state.keys);
        Failing { owner: self, keys }
    }

    /// Hold off [`Outstanding::wait_settled`] while the session moves to
    /// another peer, so it does not end with a replacement half-connected.
    pub fn transition(&self) -> Transition<'_, K> {
        self.lock().transitions += 1;
        Transition(self)
    }

    /// Block until every tracked request is settled, no failures are still
    /// being reported and no transition is in progress. After an overflow
    /// this waits until the requests are failed or cleared.
    pub fn wait_settled(&self) {
        let mut state = self.lock();
        // Registered under the lock that every update holds while it decides
        // whether to wake, and released only after the wait ends.
        state.waiters += 1;
        while !state.settled() {
            state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner());
        }
        state.waiters -= 1;
    }
}

impl<K> OutstandingState<K> {
    /// What [`Outstanding::wait_settled`] waits for.
    fn settled(&self) -> bool {
        !self.overflowed && self.failing == 0 && self.transitions == 0 && self.keys.is_empty()
    }

    /// Whether the update that left this state must wake blocked callers:
    /// only once it is settled and someone is waiting.
    fn must_wake(&self) -> bool {
        self.waiters > 0 && self.settled()
    }
}

/// Which set of requests a settlement belongs to; see [`Outstanding::epoch`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Epoch(u64);

/// Requests taken by [`Outstanding::fail`], still being reported.
pub struct Failing<'a, K: Ord> {
    owner: &'a Outstanding<K>,
    keys: BTreeMap<K, usize>,
}

impl<K: Ord> Failing<'_, K> {
    /// The key of every request to report as failed: once per request, so a
    /// key reused by two requests appears twice.
    pub fn keys(&self) -> impl Iterator<Item = &K> {
        self.keys
            .iter()
            .flat_map(|(key, &count)| std::iter::repeat_n(key, count))
    }
}

impl<K: Ord> Drop for Failing<'_, K> {
    fn drop(&mut self) {
        let mut state = self.owner.lock();
        state.failing -= 1;
        self.owner.wake_if_settled(&state);
    }
}

/// A session transition in progress; see [`Outstanding::transition`].
pub struct Transition<'a, K: Ord>(&'a Outstanding<K>);

impl<K: Ord> Drop for Transition<'_, K> {
    fn drop(&mut self) {
        let mut state = self.0.lock();
        state.transitions -= 1;
        self.0.wake_if_settled(&state);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, mpsc};
    use std::time::{Duration, Instant};

    /// Counts flushes so the LineWriter rule can be asserted directly.
    #[derive(Default)]
    struct CountingSink {
        data: Vec<u8>,
        flushes: usize,
        writes: usize,
        shutdowns: AtomicUsize,
    }
    impl Write for CountingSink {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.writes += 1;
            self.data.extend_from_slice(buf);
            Ok(buf.len())
        }
        fn flush(&mut self) -> io::Result<()> {
            self.flushes += 1;
            Ok(())
        }
    }
    impl WriteHalf for CountingSink {
        fn shutdown_write(&mut self) -> io::Result<()> {
            self.shutdowns.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }

    struct SharedSink {
        data: Arc<Mutex<Vec<u8>>>,
        fail: bool,
        attempted: Option<mpsc::Sender<()>>,
    }

    impl Write for SharedSink {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            if let Some(attempted) = self.attempted.take() {
                let _ = attempted.send(());
            }
            if self.fail {
                return Err(io::Error::new(io::ErrorKind::BrokenPipe, "fixture"));
            }
            self.data.lock().unwrap().extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    impl WriteHalf for SharedSink {
        fn shutdown_write(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    struct ShutdownSink(Arc<AtomicUsize>);

    impl Write for ShutdownSink {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    impl WriteHalf for ShutdownSink {
        fn shutdown_write(&mut self) -> io::Result<()> {
            self.0.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }

    #[test]
    fn pause_never_splits_a_request_or_observes_input_waiting_for_replacement() {
        let slot = Arc::new(WriterSlot::new(CountingSink::default()));
        slot.write_or_wait_for_replacement(b"{\"id\":1");
        assert_eq!(slot.try_pause(), None);
        slot.write_or_wait_for_replacement(b"}\n");
        assert_eq!(slot.try_pause(), Some(9));
        let (observed, received) = mpsc::channel();
        let next = Arc::clone(&slot);
        let thread = std::thread::spawn(move || {
            next.write_observed(b"next\n", || observed.send(()).unwrap())
        });
        assert!(received.recv_timeout(Duration::from_millis(30)).is_err());
        slot.replace_paused(CountingSink::default(), 17);
        assert!(received.recv_timeout(Duration::from_millis(30)).is_err());
        slot.resume();
        received.recv_timeout(Duration::from_secs(1)).unwrap();
        thread.join().unwrap();
        assert_eq!(slot.try_pause(), Some(22));
        slot.shutdown().unwrap();
        slot.replace_paused(CountingSink::default(), 0);
        assert_eq!(
            slot.state
                .lock()
                .unwrap()
                .writer
                .shutdowns
                .load(Ordering::SeqCst),
            1,
            "replacement lost client EOF"
        );
    }

    #[test]
    fn writer_slot_shutdown_reaches_the_current_writer() {
        let shutdowns = Arc::new(AtomicUsize::new(0));
        let slot = WriterSlot::new(ShutdownSink(Arc::clone(&shutdowns)));

        slot.shutdown().unwrap();

        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn writer_slot_keeps_only_the_latest_idle_replacement() {
        let first = Arc::new(Mutex::new(Vec::new()));
        let second = Arc::new(Mutex::new(Vec::new()));
        let latest = Arc::new(Mutex::new(Vec::new()));
        let slot = WriterSlot::new(SharedSink {
            data: Arc::clone(&first),
            fail: false,
            attempted: None,
        });
        slot.replace(SharedSink {
            data: Arc::clone(&second),
            fail: false,
            attempted: None,
        });
        slot.replace(SharedSink {
            data: Arc::clone(&latest),
            fail: false,
            attempted: None,
        });

        slot.write_or_wait_for_replacement(b"request");
        assert!(first.lock().unwrap().is_empty());
        assert!(second.lock().unwrap().is_empty());
        assert_eq!(&*latest.lock().unwrap(), b"request");
    }

    #[test]
    fn ambiguous_failed_window_is_not_replayed_after_replacement() {
        let failed = Arc::new(Mutex::new(Vec::new()));
        let replacement = Arc::new(Mutex::new(Vec::new()));
        let (attempted_tx, attempted_rx) = mpsc::channel();
        let (done_tx, done_rx) = mpsc::channel();
        let slot = Arc::new(WriterSlot::new(SharedSink {
            data: Arc::clone(&failed),
            fail: true,
            attempted: Some(attempted_tx),
        }));
        let writer = {
            let slot = Arc::clone(&slot);
            std::thread::spawn(move || {
                slot.write_or_wait_for_replacement(b"ambiguous");
                let _ = done_tx.send(());
            })
        };
        attempted_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("writer never attempted the ambiguous window");
        assert!(
            matches!(
                done_rx.recv_timeout(Duration::from_millis(100)),
                Err(mpsc::RecvTimeoutError::Timeout)
            ),
            "failed writer returned before a replacement existed"
        );
        slot.replace(SharedSink {
            data: Arc::clone(&replacement),
            fail: false,
            attempted: None,
        });
        done_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("writer did not resume after replacement");
        writer.join().unwrap();

        assert!(failed.lock().unwrap().is_empty());
        assert!(replacement.lock().unwrap().is_empty());
        slot.write_or_wait_for_replacement(b"next");
        assert_eq!(&*replacement.lock().unwrap(), b"next");
    }

    #[test]
    fn a_payload_larger_than_the_window_round_trips_byte_identical() {
        // Framing correctness across buffer boundaries: the pump must not care
        // where a message starts or ends.
        let payload: Vec<u8> = (0..(BUFFER_SIZE * 3 + 12345))
            .map(|i| (i % 251) as u8)
            .collect();
        let mut src = io::Cursor::new(payload.clone());
        let mut sink = CountingSink::default();
        let mut buf = vec![0u8; BUFFER_SIZE];

        copy_flushing(&mut src, &mut sink, &mut buf).unwrap();

        assert_eq!(
            sink.data, payload,
            "payload corrupted across buffer boundaries"
        );
    }

    #[test]
    fn the_recovery_window_remains_exactly_sixty_four_kibibytes() {
        assert_eq!(BUFFER_SIZE, 65_536);
    }

    #[test]
    fn a_newline_free_payload_is_still_flushed() {
        // The LineWriter trap. Without the flush this data would be invisible to
        // the client and the server would present as hung.
        let mut src = io::Cursor::new(b"{\"jsonrpc\":\"2.0\"}".to_vec());
        let mut sink = CountingSink::default();
        let mut buf = vec![0u8; BUFFER_SIZE];

        copy_flushing(&mut src, &mut sink, &mut buf).unwrap();

        assert!(
            !sink.data.contains(&b'\n'),
            "fixture should have no newline"
        );
        assert!(
            sink.flushes >= 1,
            "a newline-free payload was never flushed"
        );
        assert_eq!(sink.flushes, sink.writes, "every write must be flushed");
    }

    #[test]
    fn bytes_are_opaque_invalid_utf8_survives_unchanged() {
        // No String, no validation. A length-prefixed or binary-ish frame must
        // pass through untouched.
        let payload = vec![0xff, 0xfe, 0x00, 0x80, b'\r', b'\n', 0x01];
        let mut src = io::Cursor::new(payload.clone());
        let mut sink = CountingSink::default();
        let mut buf = vec![0u8; BUFFER_SIZE];

        copy_flushing(&mut src, &mut sink, &mut buf).unwrap();

        assert_eq!(sink.data, payload, "bytes were normalised or validated");
    }

    #[test]
    fn crlf_is_not_normalised() {
        let payload = b"a\r\nb\rc\nd".to_vec();
        let mut src = io::Cursor::new(payload.clone());
        let mut sink = CountingSink::default();
        let mut buf = vec![0u8; BUFFER_SIZE];
        copy_flushing(&mut src, &mut sink, &mut buf).unwrap();
        assert_eq!(sink.data, payload);
    }

    /// A reader that returns `Interrupted` before yielding its data.
    struct InterruptOnce {
        fired: bool,
        inner: io::Cursor<Vec<u8>>,
    }

    #[derive(Default)]
    struct ErrorThenEof {
        reads: usize,
    }

    impl Read for ErrorThenEof {
        fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
            self.reads += 1;
            if self.reads == 1 {
                Err(io::Error::other("fixture"))
            } else {
                Ok(0)
            }
        }
    }

    #[test]
    fn a_non_interrupted_read_error_is_returned() {
        let mut reader = ErrorThenEof::default();
        let mut sink = CountingSink::default();
        let mut buf = [0u8; 8];
        assert_eq!(
            copy_flushing(&mut reader, &mut sink, &mut buf)
                .unwrap_err()
                .kind(),
            io::ErrorKind::Other
        );
        assert_eq!(reader.reads, 1, "a real error must not be retried");
    }

    impl Read for InterruptOnce {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            if !self.fired {
                self.fired = true;
                return Err(io::Error::new(io::ErrorKind::Interrupted, "signal"));
            }
            self.inner.read(buf)
        }
    }

    #[test]
    fn an_interrupted_read_is_retried_not_treated_as_eof() {
        // Treating EINTR as EOF would truncate a response under any signal the
        // host happens to deliver - a rare, unreproducible data-loss bug.
        let mut src = InterruptOnce {
            fired: false,
            inner: io::Cursor::new(b"payload".to_vec()),
        };
        let mut sink = CountingSink::default();
        let mut buf = vec![0u8; BUFFER_SIZE];

        copy_flushing(&mut src, &mut sink, &mut buf).unwrap();

        assert_eq!(sink.data, b"payload");
    }

    #[test]
    fn upstream_signals_shutdown_on_clean_eof() {
        let mut src = io::Cursor::new(b"request".to_vec());
        let mut sink = CountingSink::default();

        pump_upstream(&mut src, &mut sink).unwrap();

        assert_eq!(
            sink.shutdowns.load(Ordering::SeqCst),
            1,
            "without shutdown_write the broker waits forever for a request that will never come"
        );
        assert_eq!(sink.data, b"request");
    }

    /// Fails every write, standing in for a dead client's stdout or a broker
    /// that went away mid-request.
    #[derive(Default)]
    struct DeadPipe {
        shutdowns: AtomicUsize,
    }
    impl Write for DeadPipe {
        fn write(&mut self, _: &[u8]) -> io::Result<usize> {
            Err(io::Error::new(io::ErrorKind::BrokenPipe, "EPIPE"))
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }
    impl WriteHalf for DeadPipe {
        fn shutdown_write(&mut self) -> io::Result<()> {
            self.shutdowns.fetch_add(1, Ordering::SeqCst);
            Err(io::Error::new(io::ErrorKind::NotConnected, "already gone"))
        }
    }

    #[test]
    fn upstream_still_signals_shutdown_when_the_write_fails() {
        // The client vanished mid-request. The broker must still be told the
        // request stream ended, or it holds the connection open indefinitely.
        let mut src = io::Cursor::new(b"half a request".to_vec());
        let mut sink = DeadPipe::default();

        let result = pump_upstream(&mut src, &mut sink);

        assert!(
            result.is_err(),
            "a failed write must be reported, not swallowed"
        );
        assert_eq!(
            sink.shutdowns.load(Ordering::SeqCst),
            1,
            "shutdown skipped on the error path"
        );
    }

    #[test]
    fn upstream_reports_a_half_close_the_transport_cannot_make() {
        // A named pipe has no half-close. Returning Ok here told the caller the
        // peer knew the requests had ended, and both ends waited for each other.
        struct NoHalfClose(Vec<u8>);
        impl Write for NoHalfClose {
            fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
                self.0.extend_from_slice(bytes);
                Ok(bytes.len())
            }
            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }
        impl WriteHalf for NoHalfClose {
            fn shutdown_write(&mut self) -> io::Result<()> {
                Err(io::ErrorKind::Unsupported.into())
            }
        }
        let mut src = io::Cursor::new(b"request".to_vec());
        let mut sink = NoHalfClose(Vec::new());
        let error = pump_upstream(&mut src, &mut sink).unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::Unsupported);
        assert_eq!(sink.0, b"request", "the request is still delivered");
    }

    #[test]
    fn upstream_reports_the_write_error_even_though_shutdown_also_failed() {
        // Both fail here. The caller must still learn the transfer failed rather
        // than seeing the shutdown error swallow it into an Ok.
        let mut src = io::Cursor::new(b"x".to_vec());
        let mut sink = DeadPipe::default();
        assert!(pump_upstream(&mut src, &mut sink).is_err());
    }

    #[test]
    fn downstream_reports_broker_closed_on_clean_eof() {
        let mut src = io::Cursor::new(b"response".to_vec());
        let mut sink = CountingSink::default();
        assert_eq!(pump_downstream(&mut src, &mut sink), PumpExit::PeerClosed);
        assert_eq!(sink.data, b"response");
    }

    #[test]
    fn downstream_allows_reconnect_after_a_peer_read_error() {
        let mut reader = ErrorThenEof::default();
        assert_eq!(
            pump_downstream(&mut reader, &mut CountingSink::default()),
            PumpExit::PeerClosed
        );
        assert_eq!(reader.reads, 1);
    }

    #[test]
    fn downstream_retries_interrupted_reads_and_preserves_the_reply() {
        let mut reader = InterruptOnce {
            fired: false,
            inner: io::Cursor::new(b"reply".to_vec()),
        };
        let mut sink = CountingSink::default();
        assert_eq!(
            pump_downstream(&mut reader, &mut sink),
            PumpExit::PeerClosed
        );
        assert_eq!(sink.data, b"reply");
    }

    #[test]
    fn downstream_reports_client_gone_on_a_broken_pipe() {
        // Must be an ordinary return, not a signal death: the relay owns its own
        // exit code so the host can tell "client left" from "relay crashed".
        let mut src = io::Cursor::new(b"response".to_vec());
        assert_eq!(
            pump_downstream(&mut src, &mut DeadPipe::default()),
            PumpExit::ClientGone
        );
    }

    /// A writer that accepts a bounded amount per call, so the pump's
    /// `write_all` has to loop - the shape a throttled socket presents.
    struct Throttled {
        chunk: usize,
        total: AtomicUsize,
    }
    impl Write for Throttled {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            let n = buf.len().min(self.chunk);
            self.total.fetch_add(n, Ordering::SeqCst);
            Ok(n)
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn a_partial_write_does_not_lose_bytes() {
        // `write_all` handles this, but a future refactor to `write` would drop
        // the tail of every buffer silently, so it is pinned here.
        let payload: Vec<u8> = (0..200_000).map(|i| (i % 97) as u8).collect();
        let mut src = io::Cursor::new(payload.clone());
        let mut sink = Throttled {
            chunk: 13,
            total: AtomicUsize::new(0),
        };
        let mut buf = vec![0u8; BUFFER_SIZE];

        copy_flushing(&mut src, &mut sink, &mut buf).unwrap();

        assert_eq!(sink.total.load(Ordering::SeqCst), payload.len());
    }

    #[test]
    fn memory_stays_bounded_regardless_of_payload_size() {
        // The anti-buffering property, asserted the only way a unit test can:
        // the transfer window is a compile-time constant and the pump allocates
        // exactly one of them per direction, independent of how much flows.
        let huge: Vec<u8> = vec![b'x'; BUFFER_SIZE * 20];
        let mut src = io::Cursor::new(huge.clone());
        let mut sink = CountingSink::default();
        let mut buf = vec![0u8; BUFFER_SIZE];

        copy_flushing(&mut src, &mut sink, &mut buf).unwrap();

        assert_eq!(buf.len(), BUFFER_SIZE, "the window grew with the payload");
        assert_eq!(sink.data.len(), huge.len());
        assert!(
            sink.writes >= 20,
            "a single write means the payload was buffered whole, not streamed"
        );
    }
    #[test]
    fn closing_releases_a_writer_waiting_after_an_ambiguous_write() {
        let (attempted_tx, attempted_rx) = mpsc::channel();
        let (done_tx, done_rx) = mpsc::channel();
        let slot = Arc::new(WriterSlot::new(SharedSink {
            data: Arc::new(Mutex::new(Vec::new())),
            fail: true,
            attempted: Some(attempted_tx),
        }));
        let task = {
            let slot = Arc::clone(&slot);
            std::thread::spawn(move || {
                slot.write_or_wait_for_replacement(b"ambiguous");
                done_tx.send(()).unwrap();
            })
        };
        attempted_rx.recv_timeout(Duration::from_secs(5)).unwrap();
        slot.close().unwrap();
        done_rx.recv_timeout(Duration::from_secs(5)).unwrap();
        task.join().unwrap();
        let unused = Arc::new(Mutex::new(Vec::new()));
        slot.replace(SharedSink {
            data: Arc::clone(&unused),
            fail: false,
            attempted: None,
        });
        slot.write_or_wait_for_replacement(b"after close");
        assert!(unused.lock().unwrap().is_empty());
    }

    /// Whether `wait_settled` returns within `within`, observed from another
    /// thread so a wrong answer fails the test instead of hanging it.
    fn settles(outstanding: &Arc<Outstanding<u32>>, within: Duration) -> bool {
        let (done, settled) = mpsc::channel();
        let waiter = Arc::clone(outstanding);
        std::thread::spawn(move || {
            waiter.wait_settled();
            let _ = done.send(());
        });
        settled.recv_timeout(within).is_ok()
    }

    const NOT_YET: Duration = Duration::from_millis(100);
    const SOON: Duration = Duration::from_secs(5);

    /// Start a waiter and return once it is blocked in `wait_settled`, so the
    /// update that follows has to wake it instead of being seen on entry.
    fn blocked_waiter(outstanding: &Arc<Outstanding<u32>>) -> mpsc::Receiver<()> {
        let before = outstanding.lock().waiters;
        let (done, settled) = mpsc::channel();
        let waiter = Arc::clone(outstanding);
        std::thread::spawn(move || {
            waiter.wait_settled();
            let _ = done.send(());
        });
        // The waiter registers and starts waiting in one critical section, so
        // once the count moves it is parked on the condvar.
        let deadline = Instant::now() + SOON;
        while outstanding.lock().waiters == before {
            assert!(Instant::now() < deadline, "the waiter never blocked");
            #[expect(
                clippy::disallowed_methods,
                reason = "The test waits for condvar waiter registration, with a deadline."
            )]
            std::thread::sleep(Duration::from_millis(1));
        }
        settled
    }

    #[test]
    fn each_update_that_settles_the_set_wakes_a_blocked_waiter() {
        let outstanding = Arc::new(Outstanding::new(1));

        outstanding.begin(1);
        let woken = blocked_waiter(&outstanding);
        outstanding.settle(outstanding.epoch(), &1);
        assert!(woken.recv_timeout(SOON).is_ok(), "the last settle");

        outstanding.begin(1);
        outstanding.begin(2);
        let woken = blocked_waiter(&outstanding);
        outstanding.settle(outstanding.epoch(), &1);
        assert!(
            !outstanding.lock().must_wake(),
            "a waiter is blocked but the set is overflowed"
        );
        assert!(
            woken.recv_timeout(NOT_YET).is_err(),
            "woke while the set was overflowed"
        );
        outstanding.clear();
        assert!(woken.recv_timeout(SOON).is_ok(), "a receipt");

        outstanding.begin(1);
        let failing = outstanding.fail();
        let woken = blocked_waiter(&outstanding);
        drop(failing);
        assert!(
            woken.recv_timeout(SOON).is_ok(),
            "a finished failure report"
        );

        let transition = outstanding.transition();
        let woken = blocked_waiter(&outstanding);
        drop(transition);
        assert!(woken.recv_timeout(SOON).is_ok(), "the end of a transition");

        assert_eq!(
            outstanding.lock().waiters,
            0,
            "a waiter that returned is still counted, so every settle would wake"
        );
        assert!(
            !outstanding.lock().must_wake(),
            "settled with nobody waiting"
        );
    }

    #[test]
    fn outstanding_settles_when_its_last_request_is_settled() {
        let outstanding = Arc::new(Outstanding::new(8));
        assert!(settles(&outstanding, SOON), "an empty set is settled");
        outstanding.begin(1);
        outstanding.begin(2);
        outstanding.settle(outstanding.epoch(), &1);
        assert!(!settles(&outstanding, NOT_YET));
        outstanding.settle(outstanding.epoch(), &2);
        assert!(settles(&outstanding, SOON));
    }

    #[test]
    fn an_overflowed_set_is_never_settled_until_its_requests_fail() {
        // Past capacity a request is not tracked, so an empty set could hide
        // a reply still on its way.
        let outstanding = Arc::new(Outstanding::new(2));
        for key in 0..3 {
            outstanding.begin(key);
        }
        outstanding.settle(outstanding.epoch(), &0);
        outstanding.settle(outstanding.epoch(), &1);
        assert!(!settles(&outstanding, NOT_YET));
        drop(outstanding.fail());
        assert!(
            settles(&outstanding, SOON),
            "failing the session clears the overflow"
        );
    }

    #[test]
    fn failed_requests_are_not_settled_until_their_report_is_written() {
        let outstanding = Arc::new(Outstanding::new(8));
        outstanding.begin(7);
        let failing = outstanding.fail();
        assert_eq!(failing.keys().copied().collect::<Vec<_>>(), [7]);
        assert!(
            !settles(&outstanding, NOT_YET),
            "settled while failures were still being written"
        );
        drop(failing);
        assert!(settles(&outstanding, SOON));
    }

    #[test]
    fn a_reused_key_needs_one_settle_per_request() {
        // A client may reuse an id before the first reply arrives. Counting it
        // once would end the session with the second reply still on its way.
        let outstanding = Arc::new(Outstanding::new(8));
        outstanding.begin(1);
        outstanding.begin(1);
        outstanding.settle(outstanding.epoch(), &1);
        assert!(!settles(&outstanding, NOT_YET));
        outstanding.settle(outstanding.epoch(), &1);
        assert!(settles(&outstanding, SOON));
    }

    #[test]
    fn a_late_reply_from_a_failed_peer_does_not_settle_a_newer_request() {
        let outstanding = Arc::new(Outstanding::new(8));
        let old_peer = outstanding.epoch();
        outstanding.begin(1);
        drop(outstanding.fail());
        // The client reuses the key with the replacement peer.
        outstanding.begin(1);
        outstanding.settle(old_peer, &1);
        assert!(
            !settles(&outstanding, NOT_YET),
            "a stale reply settled the new request"
        );
        outstanding.settle(outstanding.epoch(), &1);
        assert!(settles(&outstanding, SOON));
    }

    #[test]
    fn a_reused_key_is_reported_once_per_failed_request() {
        let outstanding = Outstanding::new(8);
        outstanding.begin(1);
        outstanding.begin(1);
        outstanding.begin(2);
        let failing = outstanding.fail();
        assert_eq!(failing.keys().copied().collect::<Vec<_>>(), [1, 1, 2]);
    }

    #[test]
    fn a_transition_holds_off_settling() {
        let outstanding = Arc::new(Outstanding::new(8));
        let transition = outstanding.transition();
        assert!(!settles(&outstanding, NOT_YET));
        drop(transition);
        assert!(settles(&outstanding, SOON));
    }

    #[test]
    fn a_receipt_clears_requests_and_an_overflow() {
        let outstanding = Arc::new(Outstanding::new(1));
        outstanding.begin(1);
        outstanding.begin(2);
        outstanding.clear();
        assert!(settles(&outstanding, SOON));
    }
}

/// `Outstanding` against a plain model: a multiset of keys for the current
/// epoch, an overflow flag, and counts of live report and transition guards.
/// Random operation sequences reach key reuse, stale settlements and overflow
/// in orders no example test lists.
#[cfg(test)]
mod properties {
    use super::*;
    use proptest::prelude::*;
    use std::sync::{Arc, mpsc};
    use std::time::Duration;

    #[derive(Clone, Debug)]
    enum Op {
        Begin(u8),
        /// Settle `key` with the epoch captured `age` fails or clears ago.
        Settle {
            age: usize,
            key: u8,
        },
        Clear,
        /// Take the requests. `hold` keeps the report guard alive for later steps.
        Fail {
            hold: bool,
        },
        FinishReport(usize),
        StartTransition,
        EndTransition(usize),
    }

    fn op() -> impl Strategy<Value = Op> {
        // Few keys, so clients reuse them.
        let key = 0u8..4;
        prop_oneof![
            4 => key.clone().prop_map(Op::Begin),
            3 => key.clone().prop_map(|key| Op::Settle { age: 0, key }),
            1 => (1usize..4, key).prop_map(|(age, key)| Op::Settle { age, key }),
            1 => Just(Op::Clear),
            1 => any::<bool>().prop_map(|hold| Op::Fail { hold }),
            1 => any::<usize>().prop_map(Op::FinishReport),
            1 => Just(Op::StartTransition),
            1 => any::<usize>().prop_map(Op::EndTransition),
        ]
    }

    #[derive(Default)]
    struct Model {
        epoch: usize,
        keys: BTreeMap<u8, usize>,
        overflowed: bool,
        reports: usize,
        transitions: usize,
    }

    impl Model {
        fn settled(&self) -> bool {
            !self.overflowed && self.reports == 0 && self.transitions == 0 && self.keys.is_empty()
        }

        /// Every request in flight, once per request, in key order.
        fn outstanding(&self) -> Vec<u8> {
            self.keys
                .iter()
                .flat_map(|(&key, &count)| std::iter::repeat_n(key, count))
                .collect()
        }
    }

    proptest! {
        #![proptest_config(ProptestConfig {
            cases: 256,
            failure_persistence: None,
            ..ProptestConfig::default()
        })]

        #[test]
        fn outstanding_matches_a_multiset_per_epoch(
            capacity in 0usize..5,
            ops in proptest::collection::vec(op(), 0..64),
        ) {
            let outstanding = Arc::new(Outstanding::new(capacity));
            let mut model = Model::default();
            // The epoch observed while the model was at each epoch number.
            let mut epochs = vec![outstanding.epoch()];
            let mut reports = Vec::new();
            let mut transitions = Vec::new();

            for op in &ops {
                match *op {
                    Op::Begin(key) => {
                        outstanding.begin(key);
                        if model.keys.values().sum::<usize>() < capacity {
                            *model.keys.entry(key).or_insert(0) += 1;
                        } else {
                            model.overflowed = true;
                        }
                    }
                    Op::Settle { age, key } => {
                        let captured = model.epoch.saturating_sub(age);
                        outstanding.settle(epochs[captured], &key);
                        // A reply from before the last fail or clear settles nothing.
                        if captured == model.epoch
                            && let Some(count) = model.keys.get_mut(&key)
                        {
                            *count -= 1;
                            if *count == 0 {
                                model.keys.remove(&key);
                            }
                        }
                    }
                    Op::Clear => {
                        outstanding.clear();
                        model.keys.clear();
                        model.overflowed = false;
                        model.epoch += 1;
                    }
                    Op::Fail { hold } => {
                        let failing = outstanding.fail();
                        prop_assert_eq!(
                            failing.keys().copied().collect::<Vec<_>>(),
                            model.outstanding(),
                            "fail() must report each request in flight exactly once"
                        );
                        model.keys.clear();
                        model.overflowed = false;
                        model.epoch += 1;
                        if hold {
                            reports.push(failing);
                            model.reports += 1;
                        }
                    }
                    Op::FinishReport(index) => {
                        if !reports.is_empty() {
                            drop(reports.swap_remove(index % reports.len()));
                            model.reports -= 1;
                        }
                    }
                    Op::StartTransition => {
                        transitions.push(outstanding.transition());
                        model.transitions += 1;
                    }
                    Op::EndTransition(index) => {
                        if !transitions.is_empty() {
                            drop(transitions.swap_remove(index % transitions.len()));
                            model.transitions -= 1;
                        }
                    }
                }
                if model.epoch == epochs.len() {
                    let epoch = outstanding.epoch();
                    prop_assert!(
                        !epochs.contains(&epoch),
                        "a fail or clear reused an earlier epoch"
                    );
                    epochs.push(epoch);
                }
                prop_assert_eq!(
                    outstanding.lock().settled(),
                    model.settled(),
                    "after {:?}",
                    op
                );
                prop_assert!(
                    !outstanding.lock().must_wake(),
                    "{:?} would wake with nobody waiting",
                    op
                );
            }

            drop(reports);
            drop(transitions);
            model.reports = 0;
            model.transitions = 0;
            prop_assert_eq!(outstanding.lock().settled(), model.settled());

            // Failing whatever is left ends the session: an overflow included.
            let failing = outstanding.fail();
            prop_assert_eq!(
                failing.keys().copied().collect::<Vec<_>>(),
                model.outstanding()
            );
            drop(failing);
            let (done, settled) = mpsc::channel();
            let waiter = Arc::clone(&outstanding);
            std::thread::spawn(move || {
                waiter.wait_settled();
                let _ = done.send(());
            });
            prop_assert!(
                settled.recv_timeout(Duration::from_secs(5)).is_ok(),
                "wait_settled did not return after every request failed"
            );
        }
    }
}