labstream-net 0.2.0

Sockets, timers, and interfaces for LSL. The only crate here that touches the operating system.
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
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
//! A bounded sample queue that drops the oldest sample. SPEC.md 8.7.
//!
//! liblsl holds one of these per consumer on the outlet side
//! (`src/consumer_queue.h`), and one on the inlet side for samples that the
//! application has not pulled yet (`src/data_receiver.h:35`). Both drop the
//! oldest sample when they fill.
//!
//! The recorded behavior that this matches is in
//! `artifacts/behavior-liblsl.json`. A ring of 100 samples, fed 600 samples
//! faster than the reader consumed them, delivered sample 0 and then samples
//! 500 to 599. The writer never waited.

use crate::health::{ConsumerHealth, Gap, GapKind, OutletHealth, MAX_GAPS};
use crate::history::{History, HistoryLimits, HistoryRead};
use labstream_proto::meta::MetadataUpdate;
use labstream_wire::{PackedSample, Sample, TimestampDeducer, IRREGULAR_RATE};
use std::collections::{BTreeMap, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};

/// Maximum number of live metadata updates retained in the outlet log.
const MAX_META_LOG: usize = 4096;

/// The samples of a queue, and the number after the last one.
///
/// Each push adds one to `back`, also for a sample that the queue drops at
/// once. A removal does not change it. The samples in the queue thus always
/// have the numbers `back - len .. back`, with no gap: the queue drops only
/// from the front, and a push only adds at the back. `docs/extensions.md`.
#[derive(Debug)]
struct Ring {
    q: VecDeque<PackedSample>,
    back: u64,
    /// The full timestamp of each sample that leaves the queue, in order.
    /// Only a queue for a `resume` consumer has one. `docs/extensions.md`,
    /// rule 5 of the resend timestamps.
    deducer: Option<TimestampDeducer>,
    /// Timestamp of the last sample taken by the reader, for drop-gap tracking.
    last_popped_ts: Option<f64>,
    /// Samples dropped since the last sample taken by the reader.
    pending_drop_count: u64,
    /// Start timestamp latched when `pending_drop_count` became non-zero.
    pending_drop_start: Option<f64>,
    /// Completed drop gaps, bounded to `MAX_GAPS`.
    drop_gaps: VecDeque<Gap>,
    /// Sparse `(ring_pos, skipped_count)` markers recording wire-lost or
    /// queue-dropped samples immediately before `ring_pos`, for loss-aware
    /// dejitter (`docs/roadmap.md`, step 2). Always empty on a clean stream.
    skips: VecDeque<(u64, u64)>,
}

impl std::ops::Deref for Ring {
    type Target = VecDeque<PackedSample>;
    fn deref(&self) -> &VecDeque<PackedSample> {
        &self.q
    }
}

impl std::ops::DerefMut for Ring {
    fn deref_mut(&mut self) -> &mut VecDeque<PackedSample> {
        &mut self.q
    }
}

impl Ring {
    /// The number of the sample at the front.
    fn front_number(&self) -> u64 {
        self.back.wrapping_sub(self.q.len() as u64)
    }

    /// Record that `count` samples starting near `dropped_ts` were discarded.
    fn note_drop(&mut self, dropped_ts: f64, count: u64) {
        if count == 0 {
            return;
        }
        if self.pending_drop_count == 0 {
            self.pending_drop_start = self.last_popped_ts.or(Some(dropped_ts));
        }
        self.pending_drop_count = self.pending_drop_count.saturating_add(count);
    }

    /// Finalize any pending drop gap when the reader receives a sample at `end_ts`.
    fn note_pop(&mut self, first_ts: f64, last_ts: f64) {
        if self.pending_drop_count > 0 {
            let count = self.pending_drop_count;
            let start = self.pending_drop_start.unwrap_or(first_ts);
            self.pending_drop_count = 0;
            self.pending_drop_start = None;
            if start.is_finite() && first_ts.is_finite() {
                if self.drop_gaps.len() >= MAX_GAPS {
                    self.drop_gaps.pop_front();
                }
                self.drop_gaps.push_back(Gap {
                    start,
                    end: first_ts,
                    count,
                    kind: GapKind::Dropped,
                });
            }
        }
        self.last_popped_ts = Some(last_ts);
    }

    /// Record that `count` samples were skipped immediately before `pos`,
    /// keeping `self.skips` sorted by ascending position.
    fn push_skip(&mut self, pos: u64, count: u64) {
        if count == 0 {
            return;
        }
        if let Some((last_pos, last_count)) = self.skips.back_mut() {
            if *last_pos == pos {
                *last_count = last_count.saturating_add(count);
                return;
            }
            if *last_pos < pos {
                self.skips.push_back((pos, count));
                return;
            }
        } else {
            self.skips.push_back((pos, count));
            return;
        }
        // Front insertion (e.g. `drop_front` while a later wire skip exists).
        if let Some((first_pos, first_count)) = self.skips.front_mut() {
            if *first_pos == pos {
                *first_count = first_count.saturating_add(count);
                return;
            }
            if pos < *first_pos {
                self.skips.push_front((pos, count));
                return;
            }
        }
        for i in 0..self.skips.len() {
            let (p, c) = &mut self.skips[i];
            if *p == pos {
                *c = c.saturating_add(count);
                return;
            }
            if pos < *p {
                self.skips.insert(i, (pos, count));
                return;
            }
        }
        self.skips.push_back((pos, count));
    }

    /// Take all skipped-sample counts that precede `ring_pos`.
    fn take_skips_at(&mut self, ring_pos: u64) -> u64 {
        if self.skips.is_empty() {
            return 0;
        }
        let mut total = 0u64;
        while let Some(&(pos, count)) = self.skips.front() {
            if pos <= ring_pos {
                total = total.saturating_add(count);
                self.skips.pop_front();
            } else {
                break;
            }
        }
        total
    }

    /// Remove the oldest sample because the queue is full.
    ///
    /// The deducer sees the sample, so the full timestamp of the next sample
    /// stays correct after the drop.
    fn drop_front(&mut self) {
        let front_pos = self.front_number();
        if let Some(old) = self.q.pop_front() {
            self.note_drop(old.timestamp, 1);
            // The next surviving sample is at `front_pos + 1`; attach 1 skipped
            // sample there so loss-aware dejitter accounts for inlet drops too.
            self.push_skip(front_pos.wrapping_add(1), 1);
            if let Some(d) = self.deducer.as_mut() {
                d.apply(old.timestamp);
            }
        }
    }
}

/// A queue that never blocks its writer.
#[derive(Debug)]
pub struct SampleQueue {
    inner: Mutex<Ring>,
    room: Condvar,
    capacity: usize,
    dropped: AtomicU64,
    closed: Mutex<bool>,
    /// Set by [`SampleQueue::wake`]. The next wait returns at once.
    woken: std::sync::atomic::AtomicBool,
}

impl SampleQueue {
    /// Build a queue that holds `capacity` samples.
    ///
    /// A capacity of zero would drop every sample, so the value floors at 1.
    /// liblsl floors the same way (`src/stream_info_impl.cpp:268`).
    pub fn new(capacity: usize) -> Self {
        Self::with_first_number(capacity, 0)
    }

    /// Build a queue whose first pushed sample gets the number `first`.
    ///
    /// The `seq` feature numbers the samples of an outlet with one counter.
    /// A consumer that connects later starts at the current count.
    pub fn with_first_number(capacity: usize, first: u64) -> Self {
        Self::build(capacity, first, None)
    }

    /// Build a queue that also gives the full timestamp of each sample.
    ///
    /// `deducer` must hold the state after the sample with the number
    /// `first - 1`. [`SampleQueue::pop_many_full`] then gives the full
    /// timestamps, also after a drop.
    pub fn with_deducer(capacity: usize, first: u64, deducer: TimestampDeducer) -> Self {
        Self::build(capacity, first, Some(deducer))
    }

    fn build(capacity: usize, first: u64, deducer: Option<TimestampDeducer>) -> Self {
        let capacity = capacity.max(1);
        SampleQueue {
            inner: Mutex::new(Ring {
                q: VecDeque::with_capacity(capacity.min(4096)),
                back: first,
                deducer,
                last_popped_ts: None,
                pending_drop_count: 0,
                pending_drop_start: None,
                drop_gaps: VecDeque::new(),
                skips: VecDeque::new(),
            }),
            room: Condvar::new(),
            capacity,
            dropped: AtomicU64::new(0),
            closed: Mutex::new(false),
            woken: std::sync::atomic::AtomicBool::new(false),
        }
    }

    /// How many samples the queue holds when full.
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// How many samples the queue has dropped.
    ///
    /// Nothing on the wire carries this number. SPEC.md 8.7 records that a
    /// reader cannot see a loss, so this exists for a local report only.
    pub fn dropped(&self) -> u64 {
        self.dropped.load(Ordering::SeqCst)
    }

    /// How many samples are waiting.
    pub fn len(&self) -> usize {
        self.inner.lock().unwrap().len()
    }

    /// True when no sample is waiting.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Add one sample. This never waits.
    ///
    /// A full queue loses its oldest sample. The writer carries on, so a slow
    /// reader never holds back the source. SPEC.md 8.7.
    pub fn push(&self, s: Sample) {
        self.push_packed(PackedSample::from(s));
    }

    /// Add one [`PackedSample`]. This never waits.
    pub fn push_packed(&self, s: PackedSample) {
        let mut q = self.inner.lock().unwrap();
        if q.len() >= self.capacity {
            q.drop_front();
            self.dropped.fetch_add(1, Ordering::SeqCst);
        }
        q.push_back(s);
        q.back = q.back.wrapping_add(1);
        drop(q);
        self.room.notify_one();
    }

    /// Add several samples with one lock. This never waits.
    ///
    /// The result is the same as one [`SampleQueue::push`] for each sample, in
    /// order. A full queue loses its oldest samples, and the count of dropped
    /// samples grows by the number that the queue lost. The recorded behavior in
    /// `artifacts/behavior-liblsl.json` therefore still holds.
    ///
    /// One lock for a block is the difference between a stream that a program
    /// can read at 1000 Hz and one that it cannot.
    pub fn push_many(&self, samples: &[Sample]) {
        if samples.is_empty() {
            return;
        }
        let packed: Vec<PackedSample> = samples.iter().map(PackedSample::from_sample).collect();
        self.push_many_packed(&packed);
    }

    /// Add several [`PackedSample`]s with one lock, cloning only `Arc` handles.
    pub fn push_many_packed(&self, samples: &[PackedSample]) {
        if samples.is_empty() {
            return;
        }
        let mut q = self.inner.lock().unwrap();
        let mut lost = 0u64;
        for s in samples {
            if q.len() >= self.capacity {
                q.drop_front();
                lost += 1;
            }
            q.push_back(s.clone());
        }
        q.back = q.back.wrapping_add(samples.len() as u64);
        drop(q);
        if lost > 0 {
            self.dropped.fetch_add(lost, Ordering::SeqCst);
        }
        if samples.len() == 1 {
            self.room.notify_one();
        } else {
            self.room.notify_all();
        }
    }

    /// Move every sample out of `samples` into the queue, with one lock.
    ///
    /// The result is the same as [`SampleQueue::push_many`], but no sample is
    /// copied. `samples` is empty after the call and keeps its capacity, so
    /// the caller can fill it again with no new allocation.
    ///
    /// A queue with a deducer must not use this call, because the samples
    /// that the queue drops at once never pass the deducer.
    pub fn push_owned(&self, samples: &mut Vec<Sample>) {
        self.push_owned_with_skips(samples, &[]);
    }

    /// Move every [`PackedSample`] out of `samples` into the queue, with one lock.
    pub fn push_owned_packed(&self, samples: &mut Vec<PackedSample>) {
        self.push_owned_packed_with_skips(samples, &[]);
    }

    /// Like [`SampleQueue::push_owned`], and attach sparse `(batch_index, count)`
    /// skipped-sample counts for loss-aware dejitter (`docs/roadmap.md`, step 2).
    pub(crate) fn push_owned_with_skips(&self, samples: &mut Vec<Sample>, skips: &[(usize, u64)]) {
        let mut packed: Vec<PackedSample> = samples.drain(..).map(PackedSample::from).collect();
        self.push_owned_packed_with_skips(&mut packed, skips);
    }

    /// Like [`SampleQueue::push_owned_packed`], and attach sparse
    /// `(batch_index, count)` skipped-sample counts for loss-aware dejitter.
    pub(crate) fn push_owned_packed_with_skips(
        &self,
        samples: &mut Vec<PackedSample>,
        skips: &[(usize, u64)],
    ) {
        if samples.is_empty() {
            if !skips.is_empty() {
                let mut q = self.inner.lock().unwrap();
                let pos = q.back;
                for &(_, count) in skips {
                    q.push_skip(pos, count);
                }
            }
            return;
        }
        let batch_len = samples.len();
        let mut q = self.inner.lock().unwrap();
        debug_assert!(q.deducer.is_none());
        let base_pos = q.back;
        for &(offset, count) in skips {
            q.push_skip(base_pos.wrapping_add(offset as u64), count);
        }
        let mut lost = 0u64;
        // Samples that the queue drops at once are never moved in.
        let skip = batch_len.saturating_sub(self.capacity);
        // Each sample takes a number, also the ones that are never moved in.
        q.back = q.back.wrapping_add(batch_len as u64);
        if skip > 0 {
            let old_len = q.len() as u64;
            if let Some(old) = q.q.front() {
                let ts = old.timestamp;
                q.note_drop(ts, old_len);
                lost += old_len;
                q.q.clear();
            }
            let skipped_ts = samples[0].timestamp;
            q.note_drop(skipped_ts, skip as u64);
            lost += skip as u64;
            let first_kept_pos = base_pos.wrapping_add(skip as u64);
            q.push_skip(first_kept_pos, lost);
            for s in samples.drain(..).skip(skip) {
                q.push_back(s);
            }
        } else {
            for s in samples.drain(..) {
                if q.len() >= self.capacity {
                    q.drop_front();
                    lost += 1;
                }
                q.push_back(s);
            }
        }
        drop(q);
        if lost > 0 {
            self.dropped.fetch_add(lost, Ordering::SeqCst);
        }
        if batch_len == 1 {
            self.room.notify_one();
        } else {
            self.room.notify_all();
        }
    }

    /// Record `count` skipped samples before the next sample that enters this queue.
    pub(crate) fn record_skipped(&self, count: u64) {
        if count == 0 {
            return;
        }
        let mut q = self.inner.lock().unwrap();
        let pos = q.back;
        q.push_skip(pos, count);
    }

    /// Drop any pending skip markers (used when attaching to a new outlet run).
    pub(crate) fn clear_skips(&self) {
        self.inner.lock().unwrap().skips.clear();
    }

    /// Take the oldest sample, waiting up to `timeout`.
    ///
    /// Returns `None` when the timeout passes with nothing waiting, or when the
    /// queue is closed and empty.
    pub fn pop(&self, timeout: Duration) -> Option<Sample> {
        self.pop_packed_with_skip(timeout)
            .map(|(s, _)| s.to_sample())
    }

    /// Take the oldest [`PackedSample`], waiting up to `timeout`.
    pub fn pop_packed(&self, timeout: Duration) -> Option<PackedSample> {
        self.pop_packed_with_skip(timeout).map(|(s, _)| s)
    }

    /// Take the oldest sample and the count of skipped samples immediately
    /// before it, waiting up to `timeout`.
    #[cfg(test)]
    pub(crate) fn pop_with_skip(&self, timeout: Duration) -> Option<(Sample, u64)> {
        self.pop_packed_with_skip(timeout)
            .map(|(s, sk)| (s.to_sample(), sk))
    }

    /// Take the oldest [`PackedSample`] and the count of skipped samples
    /// immediately before it, waiting up to `timeout`.
    pub(crate) fn pop_packed_with_skip(&self, timeout: Duration) -> Option<(PackedSample, u64)> {
        let mut end: Option<Instant> = None;
        let mut q = self.inner.lock().unwrap();
        loop {
            if !q.is_empty() {
                let pos = q.front_number();
                let skipped = q.take_skips_at(pos);
                let s = q.pop_front().unwrap();
                q.note_pop(s.timestamp, s.timestamp);
                return Some((s, skipped));
            }
            if timeout.is_zero() || *self.closed.lock().unwrap() {
                return None;
            }
            let deadline = *end.get_or_insert_with(|| Instant::now() + timeout);
            let left = deadline.saturating_duration_since(Instant::now());
            if left.is_zero() {
                return None;
            }
            let (guard, result) = self
                .room
                .wait_timeout(q, left.min(Duration::from_millis(100)))
                .unwrap();
            q = guard;
            if result.timed_out() && Instant::now() >= deadline {
                if !q.is_empty() {
                    let pos = q.front_number();
                    let skipped = q.take_skips_at(pos);
                    let s = q.pop_front().unwrap();
                    q.note_pop(s.timestamp, s.timestamp);
                    return Some((s, skipped));
                }
                return None;
            }
        }
    }

    /// Take every sample that waits, up to `max`, with one lock.
    ///
    /// The samples go to the end of `out`. The call gives how many it added.
    ///
    /// The timeout applies to the first sample only. When one sample waits, the
    /// call takes what is there and returns. It never waits for `max` samples,
    /// because a program that shows live signals must show what arrived.
    ///
    /// A closed and empty queue gives zero.
    pub fn pop_many(&self, out: &mut Vec<Sample>, max: usize, timeout: Duration) -> usize {
        self.pop_many_with_skips(out, None, max, timeout)
    }

    /// Take every [`PackedSample`] that waits, up to `max`, with one lock.
    pub fn pop_many_packed(
        &self,
        out: &mut Vec<PackedSample>,
        max: usize,
        timeout: Duration,
    ) -> usize {
        self.pop_many_packed_with_skips(out, None, max, timeout)
    }

    /// Like [`SampleQueue::pop_many`], and append `(offset_in_popped, skipped)`
    /// pairs to `skips_out` when any samples were skipped within this block.
    pub(crate) fn pop_many_with_skips(
        &self,
        out: &mut Vec<Sample>,
        skips_out: Option<&mut Vec<(usize, u64)>>,
        max: usize,
        timeout: Duration,
    ) -> usize {
        let mut packed = Vec::new();
        let got = self.pop_many_packed_with_skips(&mut packed, skips_out, max, timeout);
        out.extend(packed.iter().map(PackedSample::to_sample));
        got
    }

    /// Like [`SampleQueue::pop_many_packed`], and append `(offset_in_popped, skipped)`
    /// pairs to `skips_out` when any samples were skipped within this block.
    pub(crate) fn pop_many_packed_with_skips(
        &self,
        out: &mut Vec<PackedSample>,
        mut skips_out: Option<&mut Vec<(usize, u64)>>,
        max: usize,
        timeout: Duration,
    ) -> usize {
        if max == 0 {
            return 0;
        }
        let mut end: Option<Instant> = None;
        let mut q = self.inner.lock().unwrap();
        let drain_into = |q: &mut Ring,
                          out: &mut Vec<PackedSample>,
                          skips_out: &mut Option<&mut Vec<(usize, u64)>>,
                          max: usize|
         -> usize {
            let take = q.len().min(max);
            if take == 0 {
                return 0;
            }
            let first_pos = q.front_number();
            if !q.skips.is_empty() {
                if let Some(dst) = skips_out.as_mut() {
                    let lead = q.take_skips_at(first_pos);
                    if lead > 0 {
                        dst.push((0, lead));
                    }
                    let end_pos = first_pos.wrapping_add(take as u64);
                    while let Some(&(pos, count)) = q.skips.front() {
                        if pos < end_pos {
                            let idx = (pos.wrapping_sub(first_pos)) as usize;
                            dst.push((idx, count));
                            q.skips.pop_front();
                        } else {
                            break;
                        }
                    }
                } else {
                    let end_pos = first_pos.wrapping_add(take as u64);
                    while let Some(&(pos, _)) = q.skips.front() {
                        if pos < end_pos {
                            q.skips.pop_front();
                        } else {
                            break;
                        }
                    }
                }
            }
            let first_ts = q.q[0].timestamp;
            let last_ts = q.q[take - 1].timestamp;
            out.extend(q.drain(..take));
            q.note_pop(first_ts, last_ts);
            take
        };

        loop {
            if !q.is_empty() {
                return drain_into(&mut q, out, &mut skips_out, max);
            }
            if timeout.is_zero() || *self.closed.lock().unwrap() {
                return 0;
            }
            let deadline = *end.get_or_insert_with(|| Instant::now() + timeout);
            let left = deadline.saturating_duration_since(Instant::now());
            if left.is_zero() {
                return 0;
            }
            let (guard, result) = self
                .room
                .wait_timeout(q, left.min(Duration::from_millis(100)))
                .unwrap();
            q = guard;
            if result.timed_out() && Instant::now() >= deadline {
                return drain_into(&mut q, out, &mut skips_out, max);
            }
        }
    }

    /// Like [`SampleQueue::pop_many`], and also give the number of the first
    /// sample that it took.
    ///
    /// The samples that it took have consecutive numbers. With no sample, the
    /// number is the one that the next sample gets.
    pub fn pop_many_numbered(
        &self,
        out: &mut Vec<Sample>,
        max: usize,
        timeout: Duration,
    ) -> (usize, u64) {
        let mut packed = Vec::new();
        let res = self.pop_many_packed_inner(&mut packed, None, max, timeout);
        out.extend(packed.iter().map(PackedSample::to_sample));
        res
    }

    /// Like [`SampleQueue::pop_many_numbered`], returning [`PackedSample`]s.
    pub fn pop_many_numbered_packed(
        &self,
        out: &mut Vec<PackedSample>,
        max: usize,
        timeout: Duration,
    ) -> (usize, u64) {
        self.pop_many_packed_inner(out, None, max, timeout)
    }

    /// Like [`SampleQueue::pop_many_numbered`], and also add the full
    /// timestamp of each sample that it took to the end of `full`.
    ///
    /// A queue with no deducer gives the timestamps of the samples as they
    /// are.
    pub fn pop_many_full(
        &self,
        out: &mut Vec<Sample>,
        full: &mut Vec<f64>,
        max: usize,
        timeout: Duration,
    ) -> (usize, u64) {
        let mut packed = Vec::new();
        let res = self.pop_many_packed_inner(&mut packed, Some(full), max, timeout);
        out.extend(packed.iter().map(PackedSample::to_sample));
        res
    }

    /// Like [`SampleQueue::pop_many_full`], returning [`PackedSample`]s.
    pub fn pop_many_full_packed(
        &self,
        out: &mut Vec<PackedSample>,
        full: &mut Vec<f64>,
        max: usize,
        timeout: Duration,
    ) -> (usize, u64) {
        self.pop_many_packed_inner(out, Some(full), max, timeout)
    }

    fn pop_many_packed_inner(
        &self,
        out: &mut Vec<PackedSample>,
        mut full: Option<&mut Vec<f64>>,
        max: usize,
        timeout: Duration,
    ) -> (usize, u64) {
        let mut end: Option<Instant> = None;
        let mut q = self.inner.lock().unwrap();
        loop {
            if max == 0
                || !q.is_empty()
                || timeout.is_zero()
                || *self.closed.lock().unwrap()
                || self.woken.swap(false, Ordering::SeqCst)
            {
                let first = q.front_number();
                let take = q.len().min(max);
                let ring = &mut *q;
                for s in ring.q.drain(..take) {
                    // The deducer sees each sample that leaves the queue, also
                    // when the caller does not ask for the full timestamps.
                    let t = match ring.deducer.as_mut() {
                        Some(d) => d.apply(s.timestamp),
                        None => s.timestamp,
                    };
                    if let Some(f) = full.as_mut() {
                        f.push(t);
                    }
                    out.push(s);
                }
                return (take, first);
            }
            let deadline = *end.get_or_insert_with(|| Instant::now() + timeout);
            let left = deadline.saturating_duration_since(Instant::now());
            if left.is_zero() {
                return (0, q.front_number());
            }
            let (guard, _) = self
                .room
                .wait_timeout(q, left.min(Duration::from_millis(100)))
                .unwrap();
            q = guard;
        }
    }

    /// End the current wait of [`SampleQueue::pop_many_numbered`] or
    /// [`SampleQueue::pop_many_full`] at once, with what the queue holds. A
    /// session uses it when a request of its consumer arrives.
    pub fn wake(&self) {
        let _q = self.inner.lock().unwrap();
        self.woken.store(true, Ordering::SeqCst);
        self.room.notify_all();
    }

    /// Wake every reader and stop the queue.
    pub fn close(&self) {
        *self.closed.lock().unwrap() = true;
        self.room.notify_all();
    }

    /// True once [`SampleQueue::close`] has run.
    pub fn is_closed(&self) -> bool {
        *self.closed.lock().unwrap()
    }

    /// Number of recorded drop gaps (including any in-progress overflow).
    pub(crate) fn drop_gap_count(&self) -> usize {
        let q = self.inner.lock().unwrap();
        let pending = usize::from(q.pending_drop_count > 0 && q.q.front().is_some());
        q.drop_gaps.len() + pending
    }

    /// Snapshot all drop gaps on this queue, shifted by `shift`.
    pub(crate) fn drop_gaps(&self, shift: f64) -> Vec<Gap> {
        let q = self.inner.lock().unwrap();
        let mut out: Vec<Gap> = q
            .drop_gaps
            .iter()
            .map(|g| Gap {
                start: g.start + shift,
                end: g.end + shift,
                count: g.count,
                kind: g.kind,
            })
            .collect();
        if q.pending_drop_count > 0 {
            if let Some(front) = q.q.front() {
                let start = q.pending_drop_start.unwrap_or(front.timestamp);
                if start.is_finite() && front.timestamp.is_finite() {
                    out.push(Gap {
                        start: start + shift,
                        end: front.timestamp + shift,
                        count: q.pending_drop_count,
                        kind: GapKind::Dropped,
                    });
                }
            }
        }
        out
    }

    /// Drain all finalized drop gaps on this queue, shifted by `shift`.
    pub(crate) fn take_drop_gaps(&self, shift: f64) -> Vec<Gap> {
        let mut q = self.inner.lock().unwrap();
        q.drop_gaps
            .drain(..)
            .map(|g| Gap {
                start: g.start + shift,
                end: g.end + shift,
                count: g.count,
                kind: g.kind,
            })
            .collect()
    }
}

#[derive(Debug)]
struct ConsumerEntry {
    id: u64,
    peer: String,
    queue: Arc<SampleQueue>,
}

#[derive(Debug)]
struct ShmConsumerEntry {
    id: u64,
    peer: String,
    writer: Arc<crate::shm::ShmWriter>,
    channels: Option<Vec<u16>>,
}

/// A set of consumers that all receive the same sample.
///
/// liblsl calls this the send buffer (`src/send_buffer.h`). Each consumer holds
/// its own queue, so a slow consumer loses only its own samples. SPEC.md 8.8.
///
/// The fanout also holds the history of the `resume` feature, and the
/// timestamp deducer that gives the history its full timestamps.
/// `docs/extensions.md`, section `resume`.
#[derive(Debug, Default)]
pub struct Fanout {
    consumers: Mutex<Consumers>,
    meta_gen: AtomicU64,
    meta: Mutex<MetadataLog>,
}

#[derive(Debug, Default)]
struct MetadataLog {
    next_id: u64,
    entries: VecDeque<(u64, MetadataUpdate)>,
    latest: BTreeMap<String, MetadataUpdate>,
}

/// The queues of a fanout, the number of the next pushed sample, and the
/// history.
///
/// One lock holds all of them, so a new queue starts at the number that the
/// next push gives, every queue sees the same numbers, and the history holds
/// the same numbers.
#[derive(Debug)]
struct Consumers {
    list: Vec<ConsumerEntry>,
    shm_list: Vec<ShmConsumerEntry>,
    ts_scratch: Vec<f64>,
    next_consumer_id: u64,
    next: u64,
    /// Calculates the full timestamp of each pushed sample, in the order of
    /// the numbers. It runs also when there is no history, so that a history
    /// that starts in the middle of a chunk gets correct timestamps.
    deducer: TimestampDeducer,
    srate: f64,
    limits: HistoryLimits,
    /// `None` until the first consumer agrees to `resume/1`.
    history: Option<History>,
}

impl Default for Consumers {
    fn default() -> Self {
        Consumers {
            list: Vec::new(),
            shm_list: Vec::new(),
            ts_scratch: Vec::new(),
            next_consumer_id: 1,
            next: 0,
            deducer: TimestampDeducer::new(IRREGULAR_RATE),
            srate: IRREGULAR_RATE,
            limits: HistoryLimits::DEFAULT,
            history: None,
        }
    }
}

impl Consumers {
    /// Give one sample its number, its full timestamp, and its place in the
    /// history.
    fn record_packed_with_full(&mut self, s: &PackedSample, full: f64) {
        if let Some(h) = self.history.as_mut() {
            debug_assert_eq!(h.next(), self.next);
            h.push_packed(s.with_timestamp(full));
        }
        self.next = self.next.wrapping_add(1);
    }
}

impl Fanout {
    /// Build an empty set for a stream with an irregular rate and the
    /// default history limits.
    pub fn new() -> Self {
        Fanout::default()
    }

    /// Build an empty set for a stream with the nominal rate `srate`.
    ///
    /// The rate gives the deduced timestamps and the time limit of the
    /// history.
    pub fn with_rate(srate: f64, limits: HistoryLimits) -> Self {
        Fanout {
            consumers: Mutex::new(Consumers {
                deducer: TimestampDeducer::new(srate),
                srate,
                limits,
                ..Consumers::default()
            }),
            meta_gen: AtomicU64::new(0),
            meta: Mutex::new(MetadataLog::default()),
        }
    }

    /// Record a live metadata change at the current sample sequence boundary
    /// and wake all active consumers (`docs/roadmap.md`, step 16).
    pub fn push_metadata(&self, key: String, value: String, timestamp: f64) -> MetadataUpdate {
        let (seq, queues): (u64, Vec<Arc<SampleQueue>>) = {
            let set = self.consumers.lock().unwrap();
            let qs = set.list.iter().map(|c| Arc::clone(&c.queue)).collect();
            (set.next, qs)
        };
        let update = MetadataUpdate {
            seq,
            timestamp,
            key: key.clone(),
            value,
        };
        {
            let mut log = self.meta.lock().unwrap();
            log.next_id = log.next_id.wrapping_add(1);
            let id = log.next_id;
            if log.entries.len() >= MAX_META_LOG {
                log.entries.pop_front();
            }
            log.entries.push_back((id, update.clone()));
            log.latest.insert(key, update.clone());
            self.meta_gen.store(id, Ordering::Release);
        }
        for q in queues {
            q.wake();
        }
        update
    }

    /// Current metadata generation counter (0 when no metadata was pushed).
    pub fn metadata_generation(&self) -> u64 {
        self.meta_gen.load(Ordering::Acquire)
    }

    /// Snapshot the current latest metadata map together with its generation.
    pub fn metadata_snapshot(&self) -> (u64, BTreeMap<String, MetadataUpdate>) {
        if self.meta_gen.load(Ordering::Acquire) == 0 {
            return (0, BTreeMap::new());
        }
        let log = self.meta.lock().unwrap();
        (log.next_id, log.latest.clone())
    }

    /// Append any live metadata updates emitted after `*cursor` into `out` and
    /// advance `*cursor`. Fast-paths with a single atomic load when idle.
    pub fn read_metadata_since(&self, cursor: &mut u64, out: &mut Vec<MetadataUpdate>) {
        let gen = self.meta_gen.load(Ordering::Acquire);
        if gen == *cursor {
            return;
        }
        let log = self.meta.lock().unwrap();
        for (id, upd) in &log.entries {
            if *id > *cursor {
                out.push(upd.clone());
            }
        }
        *cursor = log.next_id;
    }

    /// Start the history, if the limits allow it. The result is true when
    /// the history is on.
    ///
    /// The history holds each sample that the outlet pushes from this point.
    /// A second call changes nothing. `docs/extensions.md`, history rule 3.
    pub fn start_history(&self) -> bool {
        let mut set = self.consumers.lock().unwrap();
        if set.history.is_none() && set.limits.allow_history() {
            let h = History::new(set.limits.clone(), set.srate, set.next);
            set.history = Some(h);
        }
        set.history.is_some()
    }

    /// How many samples the history holds across RAM and disk. Zero when it is off.
    pub fn history_len(&self) -> usize {
        let set = self.consumers.lock().unwrap();
        set.history.as_ref().map_or(0, History::len)
    }

    /// Bytes currently held by the history in RAM. Zero when it is off.
    pub fn history_ram_bytes(&self) -> usize {
        let set = self.consumers.lock().unwrap();
        set.history.as_ref().map_or(0, History::bytes)
    }

    /// Bytes currently held by the history in disk spool segments. Zero when off.
    pub fn history_disk_bytes(&self) -> u64 {
        let set = self.consumers.lock().unwrap();
        set.history.as_ref().map_or(0, History::disk_bytes)
    }

    /// Path of the active disk spool directory, if disk spilling has started.
    pub fn history_spool_dir(&self) -> Option<std::path::PathBuf> {
        let set = self.consumers.lock().unwrap();
        set.history.as_ref().and_then(History::spool_dir)
    }

    /// Copy at most `max` samples of the history to the end of `out`, from
    /// the number `from`, and below the number `until`. Each sample has its
    /// full timestamp.
    ///
    /// The call takes the lock of the set one time. A push thus waits for at
    /// most the copy of `max` samples (and never for disk I/O).
    /// [`History::read`] gives the rules and the result.
    pub fn read_history(
        &self,
        from: u64,
        until: u64,
        max: usize,
        out: &mut Vec<Sample>,
    ) -> Option<(u64, usize)> {
        let mut packed = Vec::new();
        let res = self.read_history_packed(from, until, max, &mut packed)?;
        out.extend(packed.iter().map(PackedSample::to_sample));
        Some(res)
    }

    /// Share at most `max` packed samples of the history to the end of `out`.
    ///
    /// RAM reads clone `Arc` handles under the lock; disk reads execute
    /// outside the `Fanout` lock so live pushes and other consumers never
    /// wait on disk I/O.
    pub fn read_history_packed(
        &self,
        from: u64,
        until: u64,
        max: usize,
        out: &mut Vec<PackedSample>,
    ) -> Option<(u64, usize)> {
        let plan = {
            let set = self.consumers.lock().unwrap();
            set.history
                .as_ref()?
                .plan_read_packed(from, until, max, out)
        };
        match plan {
            HistoryRead::Empty => None,
            HistoryRead::Ready { first, count } => Some((first, count)),
            HistoryRead::Disk(disk_plan) => disk_plan.execute(out),
        }
    }

    /// Add a consumer with its own queue.
    pub fn add(&self, capacity: usize) -> Arc<SampleQueue> {
        self.add_with_peer(capacity, String::new())
    }

    /// Add a consumer with its own queue and peer label.
    pub(crate) fn add_with_peer(&self, capacity: usize, peer: String) -> Arc<SampleQueue> {
        let mut set = self.consumers.lock().unwrap();
        let id = set.next_consumer_id;
        set.next_consumer_id = id.wrapping_add(1);
        let q = Arc::new(SampleQueue::with_first_number(capacity, set.next));
        set.list.push(ConsumerEntry {
            id,
            peer,
            queue: Arc::clone(&q),
        });
        q
    }

    /// Add a consumer for the `resume` feature. The result is its queue and
    /// `N`, the number of the first sample that the queue gets.
    ///
    /// The queue gives the full timestamp of each sample
    /// ([`SampleQueue::pop_many_full`]). The history holds the samples below
    /// `N`. `docs/extensions.md`, resend rule 1.
    pub fn add_resumable(&self, capacity: usize) -> (Arc<SampleQueue>, u64) {
        self.add_resumable_with_peer(capacity, String::new())
    }

    /// Add a resumable consumer with its peer label.
    pub(crate) fn add_resumable_with_peer(
        &self,
        capacity: usize,
        peer: String,
    ) -> (Arc<SampleQueue>, u64) {
        let mut set = self.consumers.lock().unwrap();
        let id = set.next_consumer_id;
        set.next_consumer_id = id.wrapping_add(1);
        let n = set.next;
        let q = Arc::new(SampleQueue::with_deducer(capacity, n, set.deducer.clone()));
        set.list.push(ConsumerEntry {
            id,
            peer,
            queue: Arc::clone(&q),
        });
        (q, n)
    }

    /// The number that the next pushed sample gets.
    pub fn next_number(&self) -> u64 {
        self.consumers.lock().unwrap().next
    }

    /// Add a direct `shm/1` consumer ring to the fanout.
    pub(crate) fn add_shm_with_peer(
        &self,
        writer: Arc<crate::shm::ShmWriter>,
        peer: String,
        channels: Option<Vec<u16>>,
    ) -> u64 {
        let mut set = self.consumers.lock().unwrap();
        let id = set.next_consumer_id;
        set.next_consumer_id = id.wrapping_add(1);
        let n = set.next;
        set.shm_list.push(ShmConsumerEntry {
            id,
            peer,
            writer,
            channels,
        });
        n
    }

    /// Remove a `shm/1` consumer ring from the fanout.
    pub(crate) fn remove_shm(&self, writer: &Arc<crate::shm::ShmWriter>) {
        self.consumers
            .lock()
            .unwrap()
            .shm_list
            .retain(|c| !Arc::ptr_eq(&c.writer, writer));
    }

    /// Remove a consumer.
    pub fn remove(&self, q: &Arc<SampleQueue>) {
        self.consumers
            .lock()
            .unwrap()
            .list
            .retain(|c| !Arc::ptr_eq(&c.queue, q));
    }

    /// How many consumers are connected.
    pub fn count(&self) -> usize {
        let set = self.consumers.lock().unwrap();
        set.list.len() + set.shm_list.len()
    }

    /// Snapshot the fill and drop state of every connected consumer queue.
    pub fn health(&self) -> OutletHealth {
        let mut set = self.consumers.lock().unwrap();
        set.list.retain(|c| !c.queue.is_closed());
        set.shm_list.retain(|c| !c.writer.is_closed());
        let mut consumers: Vec<ConsumerHealth> = set
            .list
            .iter()
            .map(|c| ConsumerHealth {
                id: c.id,
                peer: c.peer.clone(),
                fill: c.queue.len(),
                capacity: c.queue.capacity(),
                dropped: c.queue.dropped(),
            })
            .collect();
        consumers.extend(set.shm_list.iter().map(|c| ConsumerHealth {
            id: c.id,
            peer: c.peer.clone(),
            fill: c.writer.fill(),
            capacity: c.writer.requested_capacity(),
            dropped: c.writer.outlet_dropped(),
        }));
        OutletHealth {
            consumers,
            history_len: set.history.as_ref().map_or(0, History::len),
            pushed: set.next,
        }
    }

    /// Give one sample to every consumer.
    ///
    /// A consumer that has gone away is dropped from the set. The call never
    /// waits, whatever any consumer is doing.
    pub fn push(&self, s: &Sample) {
        self.push_packed(PackedSample::from_sample(s));
    }

    /// Zero-allocation numeric single-sample push: writes directly to any
    /// `shm/1` consumer rings first, and allocates a [`PackedSample`] only if
    /// queued consumers or `resume/1` history exist.
    pub(crate) fn push_numeric_raw(
        &self,
        timestamp: f64,
        format: labstream_wire::Format,
        bytes: &[u8],
    ) {
        let mut set = self.consumers.lock().unwrap();
        let seq = set.next;
        let full = set.deducer.apply(timestamp);
        if !set.shm_list.is_empty() {
            set.shm_list.retain(|c| !c.writer.is_closed());
            for c in set.shm_list.iter() {
                c.writer
                    .push_raw_one(seq, full, bytes, c.channels.as_deref());
            }
        }
        if !set.list.is_empty() || set.history.is_some() {
            let s = PackedSample::from_raw_bytes(timestamp, format, Arc::from(bytes));
            set.list.retain(|c| !c.queue.is_closed());
            for c in set.list.iter() {
                c.queue.push_packed(s.clone());
            }
            set.record_packed_with_full(&s, full);
        } else {
            set.next = set.next.wrapping_add(1);
        }
    }

    /// Give one [`PackedSample`] to every consumer and the `resume` history,
    /// sharing its `Arc` payload with zero byte copies.
    pub fn push_packed(&self, s: PackedSample) {
        let mut set = self.consumers.lock().unwrap();
        let seq = set.next;
        let full = set.deducer.apply(s.timestamp);
        // SHM consumers get the sample first (zero-hop direct write + wake).
        if !set.shm_list.is_empty() {
            set.shm_list.retain(|c| !c.writer.is_closed());
            if let labstream_wire::PackedValues::Numeric { bytes, .. } = &s.values {
                for c in set.shm_list.iter() {
                    c.writer
                        .push_raw_one(seq, full, bytes, c.channels.as_deref());
                }
            }
        }
        // The consumers get the sample first, so that recording into the
        // history does not delay them. The lock holds both steps, so a new
        // queue and the history still agree on each number.
        set.list.retain(|c| !c.queue.is_closed());
        for c in set.list.iter() {
            c.queue.push_packed(s.clone());
        }
        set.record_packed_with_full(&s, full);
    }

    /// Give several samples to every consumer, with one lock for the set.
    ///
    /// The result for each consumer is the same as one [`Fanout::push`] for each
    /// sample, in order.
    pub fn push_many(&self, samples: &[Sample]) {
        if samples.is_empty() {
            return;
        }
        let packed: Vec<PackedSample> = samples.iter().map(PackedSample::from_sample).collect();
        self.push_many_packed(&packed);
    }

    /// Give several [`PackedSample`]s to every consumer and the `resume`
    /// history with one lock, sharing each `Arc` payload with zero byte copies.
    pub fn push_many_packed(&self, samples: &[PackedSample]) {
        if samples.is_empty() {
            return;
        }
        let mut set = self.consumers.lock().unwrap();
        let first_seq = set.next;
        let mut full_ts = std::mem::take(&mut set.ts_scratch);
        full_ts.clear();
        full_ts.reserve(samples.len());
        for s in samples {
            full_ts.push(set.deducer.apply(s.timestamp));
        }
        if !set.shm_list.is_empty() {
            set.shm_list.retain(|c| !c.writer.is_closed());
            for c in set.shm_list.iter() {
                c.writer
                    .push_batch(first_seq, samples, &full_ts, c.channels.as_deref());
            }
        }
        // The consumers first, as in [`Fanout::push_packed`].
        set.list.retain(|c| !c.queue.is_closed());
        for c in set.list.iter() {
            c.queue.push_many_packed(samples);
        }
        for (s, &full) in samples.iter().zip(&full_ts) {
            set.record_packed_with_full(s, full);
        }
        set.ts_scratch = full_ts;
    }

    /// Push a flat contiguous numeric chunk with per-sample timestamps, writing
    /// directly to any `shm/1` consumers before allocating `PackedSample`s for
    /// queued consumers or `resume/1` history.
    pub(crate) fn push_chunk_numeric_raw(
        &self,
        format: labstream_wire::Format,
        raw: &[u8],
        row_bytes: usize,
        timestamps: &[f64],
    ) {
        let n = timestamps.len();
        if n == 0 || row_bytes == 0 || raw.len() < n * row_bytes {
            return;
        }
        let mut set = self.consumers.lock().unwrap();
        let first_seq = set.next;
        let mut full_ts = std::mem::take(&mut set.ts_scratch);
        full_ts.clear();
        full_ts.reserve(n);
        for &t in timestamps {
            full_ts.push(set.deducer.apply(t));
        }
        if !set.shm_list.is_empty() {
            set.shm_list.retain(|c| !c.writer.is_closed());
            for c in set.shm_list.iter() {
                c.writer
                    .push_chunk_raw(first_seq, raw, row_bytes, &full_ts, c.channels.as_deref());
            }
        }
        if !set.list.is_empty() || set.history.is_some() {
            let block: Vec<PackedSample> = (0..n)
                .map(|k| {
                    PackedSample::from_raw_bytes(
                        timestamps[k],
                        format,
                        Arc::from(&raw[k * row_bytes..(k + 1) * row_bytes]),
                    )
                })
                .collect();
            set.list.retain(|c| !c.queue.is_closed());
            for c in set.list.iter() {
                c.queue.push_many_packed(&block);
            }
            for (s, &full) in block.iter().zip(&full_ts) {
                set.record_packed_with_full(s, full);
            }
        } else {
            set.next = set.next.wrapping_add(n as u64);
        }
        set.ts_scratch = full_ts;
    }

    /// Close every consumer queue and shared-memory ring.
    pub fn close(&self) {
        let set = self.consumers.lock().unwrap();
        for c in set.list.iter() {
            c.queue.close();
        }
        for c in set.shm_list.iter() {
            c.writer.close();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use labstream_wire::Value;

    fn sample(i: i32) -> Sample {
        Sample {
            timestamp: i as f64,
            values: vec![Value::I32(i)],
        }
    }

    fn index(s: &Sample) -> i32 {
        match s.values[0] {
            Value::I32(v) => v,
            _ => panic!("wrong format"),
        }
    }

    #[test]
    fn a_full_queue_keeps_the_newest() {
        // The recorded shape from `artifacts/behavior-liblsl.json`, in small.
        let q = SampleQueue::new(100);
        for i in 0..600 {
            q.push(sample(i));
        }
        assert_eq!(q.len(), 100);
        assert_eq!(q.dropped(), 500);

        let first = q.pop(Duration::from_millis(10)).expect("a sample");
        assert_eq!(index(&first), 500, "the oldest surviving sample");

        let mut last = first;
        while let Some(s) = q.pop(Duration::from_millis(10)) {
            last = s;
        }
        assert_eq!(index(&last), 599, "the newest sample");
    }

    #[test]
    fn a_block_write_gives_what_single_writes_give() {
        // The batch call is an optimization. It must lose the same samples, keep
        // the same samples, and count the same drops.
        let one = SampleQueue::new(100);
        let many = SampleQueue::new(100);
        let block: Vec<Sample> = (0..600).map(sample).collect();
        for s in &block {
            one.push(s.clone());
        }
        many.push_many(&block);

        assert_eq!(one.len(), many.len());
        assert_eq!(one.dropped(), many.dropped());
        while let Some(a) = one.pop(Duration::from_millis(10)) {
            let b = many.pop(Duration::from_millis(10)).expect("the same count");
            assert_eq!(index(&a), index(&b));
        }
        assert!(many.pop(Duration::from_millis(10)).is_none());
    }

    #[test]
    fn an_owned_block_write_gives_what_single_writes_give() {
        // The same rules as `push_many`, with the existing samples first, then
        // a block larger than the queue.
        for (before, block_len) in [(0, 50), (30, 50), (30, 600), (0, 100), (99, 1)] {
            let one = SampleQueue::new(100);
            let owned = SampleQueue::new(100);
            for i in 0..before {
                one.push(sample(i));
                owned.push(sample(i));
            }
            let mut block: Vec<Sample> = (1000..1000 + block_len).map(sample).collect();
            for s in &block {
                one.push(s.clone());
            }
            owned.push_owned(&mut block);
            assert!(block.is_empty(), "the call takes every sample");

            assert_eq!(one.len(), owned.len());
            assert_eq!(one.dropped(), owned.dropped(), "{before} then {block_len}");
            while let Some(a) = one.pop(Duration::from_millis(10)) {
                let b = owned
                    .pop(Duration::from_millis(10))
                    .expect("the same count");
                assert_eq!(index(&a), index(&b));
            }
            assert!(owned.pop(Duration::from_millis(10)).is_none());
        }
    }

    #[test]
    fn a_block_read_takes_what_waits_in_order() {
        let q = SampleQueue::new(100);
        q.push_many(&(0..10).map(sample).collect::<Vec<_>>());

        let mut out = Vec::new();
        let got = q.pop_many(&mut out, 4, Duration::from_millis(10));
        assert_eq!(got, 4, "the call stops at max");
        assert_eq!(out.iter().map(index).collect::<Vec<_>>(), [0, 1, 2, 3]);

        let got = q.pop_many(&mut out, 100, Duration::from_millis(10));
        assert_eq!(got, 6, "the call takes what waits, and not more");
        assert_eq!(out.len(), 10, "the samples go to the end of the buffer");
        assert_eq!(index(&out[9]), 9);
    }

    #[test]
    fn a_block_read_of_an_empty_queue_gives_nothing() {
        let q = SampleQueue::new(10);
        let mut out = Vec::new();
        assert_eq!(q.pop_many(&mut out, 8, Duration::from_millis(5)), 0);
        assert!(out.is_empty());

        q.close();
        assert_eq!(q.pop_many(&mut out, 8, Duration::from_millis(50)), 0);
    }

    #[test]
    fn a_block_read_waits_for_the_first_sample_only() {
        // A reader that waited for `max` samples would hold a viewer back by the
        // time that the rest of the block needs.
        let q = Arc::new(SampleQueue::new(10));
        let writer = Arc::clone(&q);
        std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(20));
            writer.push_many(&[sample(1), sample(2)]);
        });
        let mut out = Vec::new();
        let start = Instant::now();
        let got = q.pop_many(&mut out, 1000, Duration::from_secs(5));
        assert_eq!(got, 2, "the call takes the block that arrived");
        assert!(
            start.elapsed() < Duration::from_secs(1),
            "the call returned"
        );
    }

    #[test]
    fn a_block_reaches_every_consumer() {
        let fan = Fanout::new();
        let a = fan.add(10);
        let b = fan.add(10);
        fan.push_many(&[sample(7), sample(8)]);

        for q in [&a, &b] {
            let mut out = Vec::new();
            assert_eq!(q.pop_many(&mut out, 10, Duration::from_millis(10)), 2);
            assert_eq!(out.iter().map(index).collect::<Vec<_>>(), [7, 8]);
        }
    }

    #[test]
    fn the_writer_never_waits() {
        // A queue of one, written a million times, must finish at once. A
        // design that waited for a reader would never return.
        let q = SampleQueue::new(1);
        let start = Instant::now();
        for i in 0..1_000_000 {
            q.push(sample(i));
        }
        assert!(
            start.elapsed() < Duration::from_secs(10),
            "the writer waited"
        );
        assert_eq!(q.len(), 1);
        assert_eq!(index(&q.pop(Duration::from_millis(10)).unwrap()), 999_999);
    }

    #[test]
    fn a_capacity_of_zero_floors_at_one() {
        let q = SampleQueue::new(0);
        assert_eq!(q.capacity(), 1);
        q.push(sample(7));
        assert_eq!(index(&q.pop(Duration::from_millis(10)).unwrap()), 7);
    }

    #[test]
    fn an_empty_queue_reports_nothing_after_the_timeout() {
        let q = SampleQueue::new(4);
        let start = Instant::now();
        assert!(q.pop(Duration::from_millis(120)).is_none());
        assert!(start.elapsed() >= Duration::from_millis(100));
    }

    #[test]
    fn a_closed_queue_stops_a_reader_at_once() {
        let q = Arc::new(SampleQueue::new(4));
        let c = Arc::clone(&q);
        std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(30));
            c.close();
        });
        let start = Instant::now();
        assert!(q.pop(Duration::from_secs(10)).is_none());
        assert!(
            start.elapsed() < Duration::from_secs(2),
            "the reader waited out the timeout"
        );
    }

    #[test]
    fn a_reader_wakes_when_a_sample_arrives() {
        let q = Arc::new(SampleQueue::new(4));
        let c = Arc::clone(&q);
        std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(30));
            c.push(sample(42));
        });
        let got = q.pop(Duration::from_secs(2)).expect("a sample");
        assert_eq!(index(&got), 42);
    }

    #[test]
    fn a_slow_consumer_never_holds_back_a_fast_one() {
        // SPEC.md 8.8. The fast queue is large and the slow queue is small.
        let f = Fanout::new();
        let fast = f.add(1000);
        let slow = f.add(10);
        for i in 0..500 {
            f.push(&sample(i));
        }
        assert_eq!(fast.len(), 500, "the fast consumer lost samples");
        assert_eq!(fast.dropped(), 0);
        assert_eq!(slow.len(), 10);
        assert_eq!(slow.dropped(), 490);
    }

    #[test]
    fn a_closed_consumer_leaves_the_set() {
        let f = Fanout::new();
        let a = f.add(10);
        let b = f.add(10);
        assert_eq!(f.count(), 2);
        b.close();
        f.push(&sample(1));
        assert_eq!(f.count(), 1, "a closed consumer must be removed");
        assert_eq!(a.len(), 1);
    }

    #[test]
    fn removing_a_consumer_stops_its_samples() {
        let f = Fanout::new();
        let a = f.add(10);
        f.push(&sample(1));
        f.remove(&a);
        f.push(&sample(2));
        assert_eq!(a.len(), 1, "a removed consumer must receive nothing more");
    }

    /// A small generator, so the test runs the same steps on each run.
    struct Steps(u64);

    impl Steps {
        fn next(&mut self, below: u64) -> u64 {
            self.0 ^= self.0 << 13;
            self.0 ^= self.0 >> 7;
            self.0 ^= self.0 << 17;
            self.0 % below
        }
    }

    #[test]
    fn the_numbers_follow_a_model_with_one_number_for_each_sample() {
        // Each sample carries its own number as its value. The model keeps
        // the numbers. Every way to push, drop and pop must agree with it.
        for seed in 1..40u64 {
            let mut steps = Steps(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15));
            let capacity = 1 + steps.next(12) as usize;
            let first = steps.next(1000);
            let q = SampleQueue::with_first_number(capacity, first);
            let mut model: VecDeque<u64> = VecDeque::new();
            let mut next = first;
            for _ in 0..400 {
                match steps.next(5) {
                    0 => {
                        q.push(sample(next as i32));
                        model.push_back(next);
                        next += 1;
                    }
                    1 | 2 => {
                        let k = steps.next(30) as usize;
                        let block: Vec<Sample> =
                            (0..k).map(|i| sample((next + i as u64) as i32)).collect();
                        if steps.next(2) == 0 {
                            q.push_many(&block);
                        } else {
                            let mut owned = block;
                            q.push_owned(&mut owned);
                        }
                        for i in 0..k as u64 {
                            model.push_back(next + i);
                        }
                        next += k as u64;
                    }
                    3 => {
                        let got = q.pop(Duration::ZERO);
                        let want = model.pop_front();
                        assert_eq!(got.map(|s| index(&s) as u64), want);
                    }
                    _ => {
                        let max = 1 + steps.next(20) as usize;
                        let mut out = Vec::new();
                        let (n, number) = q.pop_many_numbered(&mut out, max, Duration::ZERO);
                        assert_eq!(n, out.len());
                        let want_first = model.front().copied().unwrap_or(next);
                        assert_eq!(number, want_first, "seed {seed}");
                        for (i, s) in out.iter().enumerate() {
                            assert_eq!(index(s) as u64, number + i as u64, "seed {seed}");
                            assert_eq!(model.pop_front(), Some(number + i as u64));
                        }
                    }
                }
                while model.len() > capacity {
                    model.pop_front();
                }
                assert_eq!(q.len(), model.len(), "seed {seed}");
            }
        }
    }

    #[test]
    fn a_late_consumer_starts_at_the_current_number() {
        let f = Fanout::new();
        let a = f.add(100);
        for i in 0..5 {
            f.push(&sample(i));
        }
        let b = f.add(100);
        assert_eq!(f.next_number(), 5);
        f.push_many(&[sample(5), sample(6)]);
        let mut out = Vec::new();
        assert_eq!(a.pop_many_numbered(&mut out, 100, Duration::ZERO), (7, 0));
        out.clear();
        assert_eq!(b.pop_many_numbered(&mut out, 100, Duration::ZERO), (2, 5));
        assert_eq!(index(&out[0]), 5);
    }

    /// A chunk as `Outlet::push_chunk` makes it: a timestamp on the first
    /// sample, and the deduced tag on the others. SPEC.md 9.2.
    fn chunk(first: i32, len: i32, t: f64) -> Vec<Sample> {
        (first..first + len)
            .map(|i| Sample {
                timestamp: if i == first {
                    t
                } else {
                    labstream_wire::DEDUCED_TIMESTAMP
                },
                values: vec![Value::I32(i)],
            })
            .collect()
    }

    #[test]
    fn the_history_is_off_until_a_consumer_asks_for_it() {
        let f = Fanout::with_rate(100.0, HistoryLimits::DEFAULT);
        let q = f.add(100);
        f.push_many(&chunk(0, 10, 1.0));
        assert_eq!(f.history_len(), 0);
        assert_eq!(f.read_history(0, 10, 256, &mut Vec::new()), None);

        assert!(f.start_history());
        assert!(f.start_history(), "a second call changes nothing");
        assert_eq!(
            f.history_len(),
            0,
            "the history holds no sample from before"
        );

        // The history holds the samples that no consumer gets.
        f.remove(&q);
        f.push_many(&chunk(10, 5, 2.0));
        f.push(&sample(15));
        assert_eq!(f.history_len(), 6);
        let mut out = Vec::new();
        assert_eq!(
            f.read_history(0, f.next_number(), 256, &mut out),
            Some((10, 6))
        );
        assert_eq!(
            out.iter().map(index).collect::<Vec<_>>(),
            (10..16).collect::<Vec<_>>()
        );
    }

    #[test]
    fn limits_that_turn_the_history_off_keep_it_off() {
        let f = Fanout::with_rate(100.0, HistoryLimits::OFF);
        assert!(!f.start_history());
        f.push(&sample(0));
        assert_eq!(f.history_len(), 0);
    }

    #[test]
    fn the_history_and_the_queues_use_the_same_numbers() {
        let f = Fanout::with_rate(100.0, HistoryLimits::DEFAULT);
        f.push_many(&chunk(0, 7, 1.0));
        f.start_history();
        let q = f.add(100);
        f.push_many(&chunk(7, 20, 2.0));
        let mut live = Vec::new();
        let (_, first) = q.pop_many_numbered(&mut live, 100, Duration::ZERO);
        assert_eq!(first, 7);
        let mut old = Vec::new();
        assert_eq!(
            f.read_history(first, u64::MAX / 4, 256, &mut old),
            Some((7, 20))
        );
        let a: Vec<i32> = live.iter().map(index).collect();
        let b: Vec<i32> = old.iter().map(index).collect();
        assert_eq!(a, b);
        // A resend stops below the first number of the new queue, so no
        // sample goes to the consumer twice.
        assert_eq!(f.read_history(0, first, 256, &mut Vec::new()), None);
        let q2 = f.add(100);
        let n = f.next_number();
        f.push_many(&chunk(27, 5, 3.0));
        let mut resent = Vec::new();
        assert_eq!(f.read_history(10, n, 256, &mut resent), Some((10, 17)));
        assert_eq!(index(resent.last().unwrap()) as u64, n - 1);
        let mut live = Vec::new();
        assert_eq!(q2.pop_many_numbered(&mut live, 100, Duration::ZERO), (5, n));
    }

    #[test]
    fn the_history_holds_the_timestamps_that_an_inlet_calculates() {
        // A rate with no exact binary form, so that each addition rounds.
        let srate = 300.0;
        let f = Fanout::with_rate(srate, HistoryLimits::DEFAULT);
        // Push the first part of a chunk, then start the history in the
        // middle of the next chunk.
        let mut pushed = chunk(0, 9, 1.234_567);
        pushed.extend(chunk(9, 9, 1.5));
        let second = chunk(18, 9, 2.0);
        f.push_many(&pushed);
        f.push_many(&second[..4]);
        f.start_history();
        f.push_many(&second[4..]);
        f.push(&sample(27));
        pushed.extend(second);
        pushed.push(sample(27));

        // An inlet with no dropout reads every sample of the connection.
        let mut inlet = TimestampDeducer::new(srate);
        let want: Vec<u64> = pushed
            .iter()
            .map(|s| inlet.apply(s.timestamp).to_bits())
            .collect();

        let mut got = Vec::new();
        assert_eq!(f.read_history(0, 28, 256, &mut got), Some((22, 6)));
        assert_eq!(got.len(), 6);
        for s in &got {
            assert_ne!(s.timestamp, labstream_wire::DEDUCED_TIMESTAMP);
            let i = index(s) as usize;
            assert_eq!(s.timestamp.to_bits(), want[i], "sample {i}");
        }
    }

    #[test]
    fn a_read_takes_one_block() {
        let f = Fanout::with_rate(1000.0, HistoryLimits::DEFAULT);
        f.start_history();
        for i in 0..1000 {
            f.push(&sample(i));
        }
        let mut out = Vec::new();
        let mut from = 0;
        let mut blocks = 0;
        while let Some((first, count)) = f.read_history(from, 1000, 256, &mut out) {
            from = first + count as u64;
            blocks += 1;
        }
        assert_eq!(blocks, 4);
        assert_eq!(out.len(), 1000);
        assert_eq!(
            out.iter().map(index).collect::<Vec<_>>(),
            (0..1000).collect::<Vec<_>>()
        );
    }

    #[test]
    fn a_full_queue_records_a_coalesced_drop_gap() {
        let q = SampleQueue::new(4);
        q.push(sample(10));
        let first = q.pop(Duration::from_millis(10)).unwrap();
        assert_eq!(first.timestamp, 10.0);

        // Overflow the 4-sample queue with 10 samples (11..=20): drops 6 (11..=16).
        let mut batch: Vec<Sample> = (11..=20).map(sample).collect();
        q.push_owned(&mut batch);
        assert_eq!(q.dropped(), 6);
        let pending = q.drop_gaps(0.0);
        assert_eq!(pending.len(), 1);
        assert_eq!(pending[0].start, 10.0);
        assert_eq!(pending[0].end, 17.0);
        assert_eq!(pending[0].count, 6);
        assert_eq!(pending[0].kind, GapKind::Dropped);

        let next = q.pop(Duration::from_millis(10)).unwrap();
        assert_eq!(next.timestamp, 17.0);
        let taken = q.take_drop_gaps(50.0);
        assert_eq!(taken.len(), 1);
        assert_eq!(taken[0].start, 60.0);
        assert_eq!(taken[0].end, 67.0);
        assert_eq!(taken[0].count, 6);
        assert!(q.drop_gaps(0.0).is_empty());
    }

    #[test]
    fn fanout_health_reports_fill_capacity_and_drops_per_consumer() {
        let fan = Fanout::new();
        let fast = fan.add_with_peer(10, "127.0.0.1:40001".to_string());
        let slow = fan.add_with_peer(3, "127.0.0.1:40002".to_string());

        for i in 0..8 {
            fan.push(&sample(i));
            let _ = fast.pop(Duration::from_millis(1));
        }

        let h = fan.health();
        assert_eq!(h.pushed, 8);
        assert_eq!(h.consumers.len(), 2);
        assert_eq!(h.consumers[0].id, 1);
        assert_eq!(h.consumers[0].peer, "127.0.0.1:40001");
        assert_eq!(h.consumers[0].fill, 0);
        assert_eq!(h.consumers[0].capacity, 10);
        assert_eq!(h.consumers[0].dropped, 0);

        assert_eq!(h.consumers[1].id, 2);
        assert_eq!(h.consumers[1].peer, "127.0.0.1:40002");
        assert_eq!(h.consumers[1].fill, 3);
        assert_eq!(h.consumers[1].capacity, 3);
        assert_eq!(h.consumers[1].dropped, 5);
        drop(slow);
    }

    #[test]
    fn queue_delivers_exact_skip_positions_on_pop_and_pop_many() {
        let q = SampleQueue::new(32);
        let mut batch: Vec<Sample> = (0..6).map(sample).collect();
        // 100 samples lost between sample 2 and sample 3.
        q.push_owned_with_skips(&mut batch, &[(3, 100)]);

        let mut out = Vec::new();
        let mut skips = Vec::new();
        let got = q.pop_many_with_skips(&mut out, Some(&mut skips), 32, Duration::ZERO);
        assert_eq!(got, 6);
        assert_eq!(skips, vec![(3, 100)]);

        // Also test combining a front drop with a later wire skip.
        let q2 = SampleQueue::new(3);
        let mut b1: Vec<Sample> = vec![sample(0), sample(1), sample(2)];
        q2.push_owned_with_skips(&mut b1, &[(2, 50)]);
        // Push one more sample -> drops sample 0 at front (1 drop skip before sample 1),
        // while keeping the 50-sample wire skip before sample 2.
        q2.push(sample(3));
        let (s1, sk1) = q2.pop_with_skip(Duration::ZERO).unwrap();
        assert_eq!(index(&s1), 1);
        assert_eq!(sk1, 1);
        let (s2, sk2) = q2.pop_with_skip(Duration::ZERO).unwrap();
        assert_eq!(index(&s2), 2);
        assert_eq!(sk2, 50);
    }
}