modem-device 0.3.0

The seam between the zenoh-modem driver and a physical or simulated medium
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
//! A conformance kit for device implementors (#131).
//!
//! The owner's IP driver implements [`Device`], [`Netdev`] and [`Configure`]
//! outside the code that shaped them, and the tests that kept this
//! workspace's implementors honest were written against specific media —
//! `modem-driver`'s decorator check, the edge-triggered event checks, the
//! "registry does not lie" test. This module is those tests with the medium
//! taken out: an implementor calls them from its own suite, and a decorator
//! wrapped around any device is checked the same way. The wire-level half —
//! against a running management plane — is `modem_mgmt::conformance`.
//!
//! Every check returns the [`Failure`]s it found rather than panicking, so
//! the kit's own tests can hand it a deliberately broken implementor and
//! read what it says; [`assert_clean`] is the one-line form for a suite.
//! Nothing here needs a runtime: the checks that wait take a deadline or a
//! tick future from the caller and race it themselves, so a paused clock
//! works.
//!
//! **What it cannot check** is that `report`, `oper` and `identity` do no
//! I/O. Their signatures are sync, and a device that blocks in them stalls
//! the plane's publish task rather than failing a test. The kit checks what
//! follows from the contract instead: two calls in a row agree, and a report
//! that carries a reading says how old it is.

use std::collections::BTreeSet;
use std::fmt;
use std::future::Future;
use std::pin::{Pin, pin};
use std::sync::{Arc, Mutex};
use std::task::Poll;

use crate::action::{ActionError, ActionOutcome, ActionSpec, Actions, CostModel};
use crate::config::{
    ConfigError, ConfigValue, Configure, Effective, ParamClass, ParamKind, ParamSpec, Schema,
};
use crate::{
    Capabilities, Counter, Device, DeviceError, DeviceEvent, Duplex, Edge, EndpointId, Guarantee,
    Identity, LaneKey, Medium, Metrics, Netdev, NetdevStats, OperStatus, Report, Scope, Sdu,
    SecurityProperties,
};

pub mod layer;

/// One thing an implementor got wrong, by the check that found it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Failure {
    /// Which check: a stable kebab-case name, so a suite can match on it.
    pub check: &'static str,
    /// What was seen, in enough words to fix it.
    pub detail: String,
}

impl Failure {
    fn new(check: &'static str, detail: impl Into<String>) -> Self {
        Self {
            check,
            detail: detail.into(),
        }
    }
}

impl fmt::Display for Failure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.check, self.detail)
    }
}

/// Panic with every failure listed, or return.
///
/// # Panics
///
/// If `failures` is not empty, naming `what` and each failure on its own line.
pub fn assert_clean(what: &str, failures: &[Failure]) {
    assert!(
        failures.is_empty(),
        "{what} fails {} conformance check(s):\n{}",
        failures.len(),
        failures
            .iter()
            .map(|f| format!("  - {f}"))
            .collect::<Vec<_>>()
            .join("\n")
    );
}

// --- decorators -------------------------------------------------------------

/// Every method of [`Device`]. All defaulted, so a decorator that forgets
/// one compiles and answers for itself.
pub const DEVICE_METHODS: [&str; 9] = [
    "report",
    "oper",
    "identity",
    "next_event",
    "close",
    "configuration",
    "actions",
    "security",
    "counters",
];

/// Every method of [`Medium`], the [`Device`] ones included. The ones with
/// no default are listed too, so this need not be edited on the day one of
/// them gains one — which is the change that would reopen the hole.
pub const MEDIUM_METHODS: [&str; 14] = [
    "report",
    "oper",
    "identity",
    "next_event",
    "close",
    "configuration",
    "actions",
    "security",
    "counters",
    "capabilities",
    "send",
    "recv",
    "metrics",
    "configure_lanes",
];

/// Every method of [`Netdev`], the [`Device`] ones included.
pub const NETDEV_METHODS: [&str; 13] = [
    "report",
    "oper",
    "identity",
    "next_event",
    "close",
    "configuration",
    "actions",
    "security",
    "counters",
    "interface",
    "statistics",
    "epoch",
    "destinations",
];

/// An inner device that records which methods reached it, and answers each
/// with a value nothing else would produce — so one fixture asserts two
/// things: that the call *arrived*, and that what the decorator handed back
/// is what the inner device said rather than something it invented.
struct Recording {
    config: RecordedConfig,
    actions: RecordedActions,
    seen: Mutex<BTreeSet<&'static str>>,
}

impl Recording {
    fn new() -> Self {
        Self {
            config: RecordedConfig,
            actions: RecordedActions,
            seen: Mutex::new(BTreeSet::new()),
        }
    }

    fn mark(&self, method: &'static str) {
        self.seen.lock().expect("not poisoned").insert(method);
    }

    fn seen(&self) -> BTreeSet<&'static str> {
        self.seen.lock().expect("not poisoned").clone()
    }

    fn caps() -> Capabilities {
        Capabilities::new(218, 217, Duplex::Half, false)
    }

    fn security() -> SecurityProperties {
        SecurityProperties::new("recorded", Scope::Hop).guarantee(Guarantee::Integrity)
    }

    fn counters() -> Vec<Counter> {
        vec![Counter::new("recorded", "calls_total", 3)]
    }

    fn report() -> Report {
        Report::new().age_ms(17).retransmits(5)
    }

    fn oper() -> OperStatus {
        OperStatus::down("recorded", true)
    }

    fn identity() -> Identity {
        Identity::unknown().model_name("recorded")
    }

    fn lane() -> LaneKey {
        LaneKey {
            endpoint: EndpointId::new("b"),
            reliable: false,
            rank: 0,
        }
    }

    fn stats() -> NetdevStats {
        NetdevStats::new().in_octets(4242)
    }
}

struct RecordedConfig;

#[async_trait::async_trait]
impl Configure for RecordedConfig {
    fn schema(&self) -> Schema {
        Schema::new()
    }
    fn effective(&self) -> Effective {
        Effective::default()
    }
}

struct RecordedActions;

#[async_trait::async_trait]
impl Actions for RecordedActions {
    fn specs(&self) -> Vec<ActionSpec> {
        vec![ActionSpec::new("recorded", "", CostModel::Free)]
    }
    async fn invoke(
        &self,
        _name: &str,
        _arguments: &std::collections::BTreeMap<String, ConfigValue>,
    ) -> Result<ActionOutcome, ActionError> {
        Ok(ActionOutcome::new("recorded"))
    }
}

#[async_trait::async_trait]
impl Device for Recording {
    fn report(&self) -> Report {
        self.mark("report");
        Self::report()
    }
    fn oper(&self) -> OperStatus {
        self.mark("oper");
        Self::oper()
    }
    fn identity(&self) -> Identity {
        self.mark("identity");
        Self::identity()
    }
    fn configuration(&self) -> Option<&dyn Configure> {
        self.mark("configuration");
        Some(&self.config)
    }
    fn actions(&self) -> Option<&dyn Actions> {
        self.mark("actions");
        Some(&self.actions)
    }
    async fn close(&self) -> Result<(), DeviceError> {
        self.mark("close");
        Ok(())
    }
    async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
        self.mark("next_event");
        Ok(DeviceEvent::raised("recorded"))
    }
    fn security(&self) -> Option<SecurityProperties> {
        self.mark("security");
        Some(Self::security())
    }
    fn counters(&self) -> Vec<Counter> {
        self.mark("counters");
        Self::counters()
    }
}

#[async_trait::async_trait]
impl Medium for Recording {
    fn capabilities(&self) -> Capabilities {
        self.mark("capabilities");
        Self::caps()
    }
    async fn send(&self, _lane: &LaneKey, _sdu: &[u8]) -> Result<(), DeviceError> {
        self.mark("send");
        Ok(())
    }
    async fn recv(&self) -> Result<(LaneKey, Sdu), DeviceError> {
        self.mark("recv");
        Ok((Self::lane(), vec![0xAB]))
    }
    fn metrics(&self) -> Metrics {
        self.mark("metrics");
        Metrics::new().tx_sdus(7)
    }
    async fn configure_lanes(&self, _lanes: &[LaneKey]) -> Result<(), DeviceError> {
        self.mark("configure_lanes");
        Ok(())
    }
}

impl Netdev for Recording {
    fn interface(&self) -> &'static str {
        self.mark("interface");
        "recorded0"
    }
    fn statistics(&self) -> NetdevStats {
        self.mark("statistics");
        Self::stats()
    }
    fn epoch(&self) -> u64 {
        self.mark("epoch");
        42
    }
    fn destinations(&self) -> Option<Vec<crate::Destination>> {
        self.mark("destinations");
        Some(vec![crate::Destination::new("recorded-neighbour")])
    }
}

/// The [`Device`] half of a forwarding check: everything but `close`, which
/// the caller does last.
async fn device_calls(name: &str, dev: &dyn Device, out: &mut Vec<Failure>) {
    let report = dev.report();
    let oper = dev.oper();
    let identity = dev.identity();
    let configuration = dev.configuration().is_some();
    let actions = dev.actions().is_some();
    let event = dev.next_event().await;
    if report != Recording::report() {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} rewrote report: {report:?}"),
        ));
    }
    if oper != Recording::oper() {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} rewrote oper: {oper:?}"),
        ));
    }
    if identity != Recording::identity() {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} rewrote identity: {identity:?}"),
        ));
    }
    if !configuration {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} answers None for configuration: the wrapped device has a plane"),
        ));
    }
    if !actions {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} answers None for actions: the wrapped device offers one"),
        ));
    }
    if event.as_ref().ok() != Some(&DeviceEvent::raised("recorded")) {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} rewrote next_event: {event:?}"),
        ));
    }
    let security = dev.security();
    if security.as_ref() != Some(&Recording::security()) {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} rewrote security: {security:?}"),
        ));
    }
    let counters = dev.counters();
    if counters != Recording::counters() {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} rewrote counters: {counters:?}"),
        ));
    }
}

fn missing(name: &str, methods: &[&'static str], inner: &Recording, out: &mut Vec<Failure>) {
    let seen = inner.seen();
    let missing: Vec<&str> = methods
        .iter()
        .copied()
        .filter(|m| !seen.contains(m))
        .collect();
    if !missing.is_empty() {
        out.push(Failure::new(
            "decorator-forwards",
            format!(
                "{name} does not forward {missing:?}, so it answers for itself rather than for \
                 the device it wraps"
            ),
        ));
    }
}

/// Does the decorator `wrap` builds forward every method of [`Device`]?
///
/// Written against the decorator rather than a list of method names,
/// because the failure being caught is "somebody wrote a new decorator and
/// stopped at the methods they needed", and only a decorator can exhibit it.
pub async fn device_decorator_forwards<F>(name: &str, wrap: F) -> Vec<Failure>
where
    F: FnOnce(Arc<dyn Device>) -> Arc<dyn Device>,
{
    let inner = Arc::new(Recording::new());
    let dev = wrap(inner.clone() as Arc<dyn Device>);
    let mut out = Vec::new();
    device_calls(name, dev.as_ref(), &mut out).await;
    if let Err(e) = dev.close().await {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} failed close: {e}"),
        ));
    }
    missing(name, &DEVICE_METHODS, &inner, &mut out);
    out
}

/// Does the decorator `wrap` builds forward every method of [`Medium`]?
pub async fn medium_decorator_forwards<F>(name: &str, wrap: F) -> Vec<Failure>
where
    F: FnOnce(Arc<dyn Medium>) -> Arc<dyn Medium>,
{
    let inner = Arc::new(Recording::new());
    let medium = wrap(inner.clone() as Arc<dyn Medium>);
    let mut out = Vec::new();
    device_calls(name, medium.as_ref(), &mut out).await;
    let caps = medium.capabilities();
    if caps != Recording::caps() {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} rewrote capabilities: {caps:?}"),
        ));
    }
    if let Err(e) = medium.send(&Recording::lane(), b"payload").await {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} failed send: {e}"),
        ));
    }
    match medium.recv().await {
        Ok((_, sdu)) if sdu == vec![0xAB] => {}
        other => out.push(Failure::new(
            "decorator-forwards",
            format!("{name} rewrote recv: {other:?}"),
        )),
    }
    let metrics = medium.metrics();
    if metrics.tx_sdus != 7 {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} rewrote metrics: {metrics:?}"),
        ));
    }
    if let Err(e) = medium.configure_lanes(&[Recording::lane()]).await {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} failed configure_lanes: {e}"),
        ));
    }
    if let Err(e) = medium.close().await {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} failed close: {e}"),
        ));
    }
    missing(name, &MEDIUM_METHODS, &inner, &mut out);
    out
}

/// Does the decorator `wrap` builds forward every method of [`Netdev`]?
pub async fn netdev_decorator_forwards<F>(name: &str, wrap: F) -> Vec<Failure>
where
    F: FnOnce(Arc<dyn Netdev>) -> Arc<dyn Netdev>,
{
    let inner = Arc::new(Recording::new());
    let dev = wrap(inner.clone() as Arc<dyn Netdev>);
    let mut out = Vec::new();
    device_calls(name, dev.as_ref(), &mut out).await;
    if dev.interface() != "recorded0" {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} rewrote interface: {:?}", dev.interface()),
        ));
    }
    if dev.statistics() != Recording::stats() {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} rewrote statistics: {:?}", dev.statistics()),
        ));
    }
    if dev.epoch() != 42 {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} rewrote epoch: {}", dev.epoch()),
        ));
    }
    if dev.destinations() != Some(vec![crate::Destination::new("recorded-neighbour")]) {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} rewrote destinations: {:?}", dev.destinations()),
        ));
    }
    if let Err(e) = dev.close().await {
        out.push(Failure::new(
            "decorator-forwards",
            format!("{name} failed close: {e}"),
        ));
    }
    missing(name, &NETDEV_METHODS, &inner, &mut out);
    out
}

// --- the core plane ---------------------------------------------------------

/// `report`, `oper` and `identity` are sync and cached: two calls in a row
/// agree, and a report that carries any reading says how old it is
/// ([`Report::age_ms`]), which is how a cached answer is honest about being
/// one.
///
/// A report's age may tick between the two calls; it is the one field left
/// out of the comparison.
#[must_use]
pub fn core(dev: &dyn Device) -> Vec<Failure> {
    let mut out = Vec::new();
    let ageless = |mut r: Report| {
        r.age_ms = None;
        r
    };
    let (a, b) = (dev.report(), dev.report());
    if ageless(a) != ageless(b) {
        out.push(Failure::new(
            "report-is-cached",
            format!("two calls in a row disagree: {a:?} then {b:?}"),
        ));
    }
    if ageless(a) != Report::default() && a.age_ms.is_none() {
        out.push(Failure::new(
            "report-says-its-age",
            format!("the report carries a reading and no age_ms: {a:?}"),
        ));
    }
    let (a, b) = (dev.oper(), dev.oper());
    if a != b {
        out.push(Failure::new(
            "oper-is-cached",
            format!("two calls in a row disagree: {a:?} then {b:?}"),
        ));
    }
    let (a, b) = (dev.identity(), dev.identity());
    if a != b {
        out.push(Failure::new(
            "identity-is-cached",
            format!("two calls in a row disagree: {a:?} then {b:?}"),
        ));
    }
    out
}

/// Race `fut` against a deadline: `Some` if it finished first.
async fn until<T>(
    fut: impl Future<Output = T>,
    mut deadline: Pin<&mut impl Future<Output = ()>>,
) -> Option<T> {
    let mut fut = pin!(fut);
    std::future::poll_fn(|cx| {
        if let Poll::Ready(v) = fut.as_mut().poll(cx) {
            return Poll::Ready(Some(v));
        }
        match deadline.as_mut().poll(cx) {
            Poll::Ready(()) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    })
    .await
}

/// `next_event` is edge-triggered (the [`Edge`] contract): the same words
/// with the same edge twice in a row on one lane, with nothing between, is
/// a condition being repeated while it persists — the stream no `rate`
/// declaration could cover.
///
/// Drains events until `deadline` resolves; an `Err` from `next_event` ends
/// the drain and is not a finding, since a device may say it has closed. A
/// device with nothing to report passes trivially, so an implementor's own
/// test should provoke a condition first where it can.
pub async fn events_are_edge_triggered(
    dev: &dyn Device,
    deadline: impl Future<Output = ()>,
) -> Vec<Failure> {
    let mut deadline = pin!(deadline);
    let mut out = Vec::new();
    let mut last: Vec<(Option<LaneKey>, DeviceEvent)> = Vec::new();
    // An `Err` ends the drain: a device may say it has closed.
    while let Some(Ok(ev)) = until(dev.next_event(), deadline.as_mut()).await {
        if let Some((_, prev)) = last.iter().find(|(lane, _)| *lane == ev.lane)
            && prev.edge == ev.edge
            && prev.detail == ev.detail
        {
            out.push(Failure::new(
                "events-are-edge-triggered",
                format!(
                    "{:?} {:?} was reported twice in a row with no {:?} between: a condition \
                     is one event when it starts and one when it stops",
                    ev.edge,
                    ev.detail,
                    match ev.edge {
                        Edge::Raised => Edge::Cleared,
                        _ => Edge::Raised,
                    }
                ),
            ));
        }
        last.retain(|(lane, _)| *lane != ev.lane);
        last.push((ev.lane.clone(), ev));
    }
    out
}

// --- the configuration plane ------------------------------------------------

fn plain_chunk(s: &str) -> bool {
    !s.is_empty()
        && s.chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
}

/// The schema is well-formed: unique group and parameter names that can be
/// spelled in a key, a description on each, at least one parameter per
/// group, and integer bounds that do not cross.
///
/// A unit is not required on an integer: the vocabulary says `None` is a
/// count.
#[must_use]
pub fn schema_is_valid(schema: &Schema) -> Vec<Failure> {
    let mut out = Vec::new();
    let mut groups = BTreeSet::new();
    for g in &schema.groups {
        if !plain_chunk(g.name) {
            out.push(Failure::new(
                "schema-is-valid",
                format!(
                    "group {:?} is not a plain chunk (lowercase, digits, `_`, `-`): it is \
                     spelled in the write key",
                    g.name
                ),
            ));
        }
        if !groups.insert(g.name) {
            out.push(Failure::new(
                "schema-is-valid",
                format!("group {:?} is declared twice", g.name),
            ));
        }
        if g.description.trim().is_empty() {
            out.push(Failure::new(
                "schema-is-valid",
                format!("group {:?} has no description", g.name),
            ));
        }
        if g.parameters.is_empty() {
            out.push(Failure::new(
                "schema-is-valid",
                format!("group {:?} declares no parameter", g.name),
            ));
        }
        let mut names = BTreeSet::new();
        for p in &g.parameters {
            if !plain_chunk(p.name) {
                out.push(Failure::new(
                    "schema-is-valid",
                    format!("{}/{:?} is not a plain chunk", g.name, p.name),
                ));
            }
            if !names.insert(p.name) {
                out.push(Failure::new(
                    "schema-is-valid",
                    format!("{}/{} is declared twice", g.name, p.name),
                ));
            }
            if p.description.trim().is_empty() {
                out.push(Failure::new(
                    "schema-is-valid",
                    format!("{}/{} has no description", g.name, p.name),
                ));
            }
            if let ParamKind::Integer {
                min: Some(min),
                max: Some(max),
                ..
            } = p.kind
                && min > max
            {
                out.push(Failure::new(
                    "schema-is-valid",
                    format!("{}/{}: min {min} is above max {max}", g.name, p.name),
                ));
            }
        }
    }
    out
}

/// What the device runs with is within what it declares: every value in
/// `effective` names a declared parameter and passes its bound, and no
/// sensitive parameter is read back.
#[must_use]
pub fn effective_within_schema(schema: &Schema, effective: &Effective) -> Vec<Failure> {
    let mut out = Vec::new();
    for (group, params) in effective {
        for (name, value) in params {
            if let Err(e) = schema.check(group, name, value) {
                out.push(Failure::new(
                    "effective-within-schema",
                    format!("effective carries {group}/{name} = {value}: {e}"),
                ));
            }
        }
    }
    out.extend(sensitive_absent(schema, effective));
    out
}

fn sensitive_absent(schema: &Schema, effective: &Effective) -> Vec<Failure> {
    let mut out = Vec::new();
    for g in &schema.groups {
        for p in g.parameters.iter().filter(|p| p.sensitive) {
            if effective
                .get(g.name)
                .is_some_and(|values| values.contains_key(p.name))
            {
                out.push(Failure::new(
                    "sensitive-never-read-back",
                    format!(
                        "{}/{} is sensitive and effective carries a value for it",
                        g.name, p.name
                    ),
                ));
            }
        }
    }
    out
}

/// A value the spec accepts that differs from `current`.
fn other_value(spec: &ParamSpec, current: Option<&ConfigValue>) -> ConfigValue {
    match (&spec.kind, current) {
        (ParamKind::Bool, Some(ConfigValue::Bool(b))) => ConfigValue::Bool(!b),
        (ParamKind::Bool, _) => ConfigValue::Bool(true),
        (ParamKind::Integer { min, max, .. }, cur) => {
            let cur = match cur {
                Some(ConfigValue::Integer(i)) => *i,
                _ => min.unwrap_or(0),
            };
            let up = cur.saturating_add(1);
            if max.is_none_or(|m| up <= m) {
                ConfigValue::Integer(up)
            } else {
                ConfigValue::Integer(cur.saturating_sub(1).max(min.unwrap_or(i64::MIN)))
            }
        }
        (ParamKind::Text, Some(ConfigValue::Text(t))) => {
            ConfigValue::Text(format!("{t}-conformance"))
        }
        (_, _) => ConfigValue::Text("conformance".into()),
    }
}

/// Every contract group is refused at runtime with the restart named
/// ([`ConfigError::Contract`]): a change to what the transport was started
/// against belongs in the startup file.
pub async fn contract_refused(cfg: &dyn Configure) -> Vec<Failure> {
    let mut out = Vec::new();
    let schema = cfg.schema();
    let effective = cfg.effective();
    for g in schema
        .groups
        .iter()
        .filter(|g| g.class == ParamClass::Contract)
    {
        let Some(p) = g.parameters.first() else {
            continue;
        };
        let current = effective.get(g.name).and_then(|v| v.get(p.name));
        let value = other_value(p, current);
        let change = [(p.name.to_string(), value.clone())].into_iter().collect();
        match cfg.apply(g.name, &change).await {
            Err(ConfigError::Contract(_)) => {}
            Ok(_) => out.push(Failure::new(
                "contract-refused",
                format!(
                    "contract group {:?} accepted {}={} at runtime; it is part of what the \
                     transport was started against and belongs in the startup file",
                    g.name, p.name, value
                ),
            )),
            Err(e) => out.push(Failure::new(
                "contract-refused",
                format!(
                    "contract group {:?} was refused for another reason than the contract, so \
                     the caller is not told to restart: {e}",
                    g.name
                ),
            )),
        }
    }
    out
}

/// The read-back rule (architecture §4.6): after `apply`, `effective` shows
/// the change; after applying the `Undo` it answered, the previous values
/// are back. Every non-sensitive parameter of every hot and reach group,
/// one at a time, with a value the schema accepts.
///
/// A group the device answers [`ConfigError::Unsupported`] for is skipped:
/// declaring a group before being able to change it is what that error
/// means, and it is honest.
pub async fn read_back_and_undo(cfg: &dyn Configure) -> Vec<Failure> {
    let mut out = Vec::new();
    let schema = cfg.schema();
    for g in schema
        .groups
        .iter()
        .filter(|g| g.class != ParamClass::Contract)
    {
        for p in g.parameters.iter().filter(|p| !p.sensitive) {
            let before = cfg.effective();
            let current = before.get(g.name).and_then(|v| v.get(p.name));
            let value = other_value(p, current);
            let change = [(p.name.to_string(), value.clone())].into_iter().collect();
            let undo = match cfg.apply(g.name, &change).await {
                Ok(undo) => undo,
                Err(ConfigError::Unsupported(_)) => break,
                Err(e) => {
                    out.push(Failure::new(
                        "read-back",
                        format!(
                            "the schema says {}/{} accepts {value}; the device refused it: {e}",
                            g.name, p.name
                        ),
                    ));
                    continue;
                }
            };
            let after = cfg.effective();
            let read_back = after.get(g.name).and_then(|v| v.get(p.name));
            if read_back != Some(&value) {
                out.push(Failure::new(
                    "read-back",
                    format!(
                        "after apply {}/{}={value}, effective says {}: a change is not done \
                         until it can be read back",
                        g.name,
                        p.name,
                        read_back.map_or("nothing".to_string(), ToString::to_string)
                    ),
                ));
            }
            if let Err(e) = cfg.apply(g.name, &undo).await {
                out.push(Failure::new(
                    "undo-restores",
                    format!("the undo for {}/{} was refused: {e}", g.name, p.name),
                ));
                continue;
            }
            let restored = cfg.effective();
            if restored != before {
                out.push(Failure::new(
                    "undo-restores",
                    format!(
                        "after apply {}/{}={value} and its undo {undo:?}, effective is not what \
                         it was: {restored:?} vs {before:?}",
                        g.name, p.name
                    ),
                ));
            }
        }
    }
    out
}

/// A sensitive parameter is write-only: after a value is applied, it is in
/// none of `effective`, its `Debug`, or the `Debug` of the report, the
/// operational status and the identity.
///
/// Text parameters carry a marker nothing else would contain; a sensitive
/// integer or switch is only checked to be absent from `effective`, because
/// a number cannot be told from any other.
pub async fn sensitive_never_read_back(dev: &dyn Device) -> Vec<Failure> {
    let Some(cfg) = dev.configuration() else {
        return Vec::new();
    };
    let schema = cfg.schema();
    let mut out = sensitive_absent(&schema, &cfg.effective());
    let marker = format!(
        "conformance-{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_nanos())
    );
    for g in schema
        .groups
        .iter()
        .filter(|g| g.class != ParamClass::Contract)
    {
        for p in g
            .parameters
            .iter()
            .filter(|p| p.sensitive && p.kind == ParamKind::Text)
        {
            let change = [(p.name.to_string(), ConfigValue::Text(marker.clone()))]
                .into_iter()
                .collect();
            let undo = match cfg.apply(g.name, &change).await {
                Ok(undo) => undo,
                Err(ConfigError::Unsupported(_)) => break,
                Err(e) => {
                    out.push(Failure::new(
                        "sensitive-never-read-back",
                        format!(
                            "the schema says {}/{} takes text; the device refused it: {e}",
                            g.name, p.name
                        ),
                    ));
                    continue;
                }
            };
            let effective = cfg.effective();
            let leaks = [
                ("effective", format!("{effective:?}")),
                ("the schema", format!("{:?}", cfg.schema())),
                ("the report", format!("{:?}", dev.report())),
                ("oper", format!("{:?}", dev.oper())),
                ("the identity", format!("{:?}", dev.identity())),
            ];
            for (what, text) in leaks {
                if text.contains(&marker) {
                    out.push(Failure::new(
                        "sensitive-never-read-back",
                        format!(
                            "the value written to sensitive {}/{} appears in {what}: {text}",
                            g.name, p.name
                        ),
                    ));
                }
            }
            if !undo.is_empty()
                && let Err(e) = cfg.apply(g.name, &undo).await
            {
                out.push(Failure::new(
                    "sensitive-never-read-back",
                    format!("the undo for {}/{} was refused: {e}", g.name, p.name),
                ));
            }
        }
    }
    out
}

/// The whole configuration plane, for a device that has one; nothing to
/// check for one that does not.
pub async fn configuration(dev: &dyn Device) -> Vec<Failure> {
    let Some(cfg) = dev.configuration() else {
        return Vec::new();
    };
    let schema = cfg.schema();
    let mut out = schema_is_valid(&schema);
    out.extend(effective_within_schema(&schema, &cfg.effective()));
    out.extend(contract_refused(cfg).await);
    out.extend(read_back_and_undo(cfg).await);
    out.extend(sensitive_never_read_back(dev).await);
    out
}

// --- a netdev -----------------------------------------------------------------

/// One counter of a [`NetdevStats`].
type StatRead = fn(&NetdevStats) -> Option<u64>;

/// Each counter by name.
const COUNTERS: [(&str, StatRead); 9] = [
    ("in_octets", |s| s.in_octets),
    ("out_octets", |s| s.out_octets),
    ("in_errors", |s| s.in_errors),
    ("out_errors", |s| s.out_errors),
    ("in_discards", |s| s.in_discards),
    ("out_discards", |s| s.out_discards),
    ("in_multicast_pkts", |s| s.in_multicast_pkts),
    ("in_pkts", |s| s.in_pkts),
    ("out_pkts", |s| s.out_pkts),
];

/// The interface has a name, and within one presence epoch no counter goes
/// backwards: `samples` readings, `tick` awaited between each — a sleep, or
/// whatever lets the device's poller run.
///
/// A counter that does decrease is the device's cue to move its epoch,
/// which is the one reset the registry sanctions; a decrease without one
/// is what this catches.
pub async fn netdev<Fut>(
    dev: &dyn Netdev,
    samples: usize,
    mut tick: impl FnMut() -> Fut,
) -> Vec<Failure>
where
    Fut: Future<Output = ()>,
{
    let mut out = Vec::new();
    if dev.interface().trim().is_empty() {
        out.push(Failure::new(
            "netdev-is-named",
            "interface() is empty: a netdev is named as the kernel spells it",
        ));
    }
    let mut prev = (dev.epoch(), dev.statistics());
    for _ in 0..samples {
        tick().await;
        let now = (dev.epoch(), dev.statistics());
        if now.0 == prev.0 {
            for (name, read) in COUNTERS {
                if let (Some(a), Some(b)) = (read(&prev.1), read(&now.1))
                    && b < a
                {
                    out.push(Failure::new(
                        "counters-never-decrease",
                        format!(
                            "{name} went from {a} to {b} within epoch {}: a counter that resets \
                             moves the epoch",
                            now.0
                        ),
                    ));
                }
            }
        }
        prev = now;
    }
    out
}

/// Everything a [`Device`] is held to: [`core()`], [`events_are_edge_triggered`]
/// until `event_deadline`, and [`configuration`].
pub async fn device(dev: &dyn Device, event_deadline: impl Future<Output = ()>) -> Vec<Failure> {
    let mut out = core(dev);
    out.extend(events_are_edge_triggered(dev, event_deadline).await);
    out.extend(configuration(dev).await);
    out
}

#[cfg(test)]
mod tests {
    //! One deliberately broken implementor per check, and a clean one that
    //! passes them all.
    use std::collections::BTreeMap;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::time::Duration;

    use super::*;
    use crate::config::{ConfigGroup, Undo};

    fn checks(failures: &[Failure]) -> Vec<&'static str> {
        failures.iter().map(|f| f.check).collect()
    }

    fn detail(failures: &[Failure], check: &str) -> String {
        failures
            .iter()
            .filter(|f| f.check == check)
            .map(|f| f.detail.clone())
            .collect::<Vec<_>>()
            .join("\n")
    }

    // --- decorators ---------------------------------------------------------

    /// Forwards everything but `oper`.
    struct ForgetsOper(Arc<dyn Device>);

    #[async_trait::async_trait]
    impl Device for ForgetsOper {
        fn report(&self) -> Report {
            self.0.report()
        }
        fn identity(&self) -> Identity {
            self.0.identity()
        }
        fn configuration(&self) -> Option<&dyn Configure> {
            self.0.configuration()
        }
        fn actions(&self) -> Option<&dyn Actions> {
            self.0.actions()
        }
        async fn close(&self) -> Result<(), DeviceError> {
            self.0.close().await
        }
        async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
            self.0.next_event().await
        }
        fn security(&self) -> Option<SecurityProperties> {
            self.0.security()
        }
        fn counters(&self) -> Vec<Counter> {
            self.0.counters()
        }
    }

    /// Forwards everything but `metrics`.
    struct ForgetsMetrics(Arc<dyn Medium>);

    #[async_trait::async_trait]
    impl Device for ForgetsMetrics {
        fn report(&self) -> Report {
            self.0.report()
        }
        fn oper(&self) -> OperStatus {
            self.0.oper()
        }
        fn identity(&self) -> Identity {
            self.0.identity()
        }
        fn configuration(&self) -> Option<&dyn Configure> {
            self.0.configuration()
        }
        fn actions(&self) -> Option<&dyn Actions> {
            self.0.actions()
        }
        async fn close(&self) -> Result<(), DeviceError> {
            self.0.close().await
        }
        async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
            self.0.next_event().await
        }
        fn security(&self) -> Option<SecurityProperties> {
            self.0.security()
        }
        fn counters(&self) -> Vec<Counter> {
            self.0.counters()
        }
    }

    #[async_trait::async_trait]
    impl Medium for ForgetsMetrics {
        fn capabilities(&self) -> Capabilities {
            self.0.capabilities()
        }
        async fn send(&self, lane: &LaneKey, sdu: &[u8]) -> Result<(), DeviceError> {
            self.0.send(lane, sdu).await
        }
        async fn recv(&self) -> Result<(LaneKey, Sdu), DeviceError> {
            self.0.recv().await
        }
        fn metrics(&self) -> Metrics {
            Metrics::default()
        }
        async fn configure_lanes(&self, lanes: &[LaneKey]) -> Result<(), DeviceError> {
            self.0.configure_lanes(lanes).await
        }
    }

    /// Forwards everything but `epoch`.
    struct ForgetsEpoch(Arc<dyn Netdev>);

    #[async_trait::async_trait]
    impl Device for ForgetsEpoch {
        fn report(&self) -> Report {
            self.0.report()
        }
        fn oper(&self) -> OperStatus {
            self.0.oper()
        }
        fn identity(&self) -> Identity {
            self.0.identity()
        }
        fn configuration(&self) -> Option<&dyn Configure> {
            self.0.configuration()
        }
        fn actions(&self) -> Option<&dyn Actions> {
            self.0.actions()
        }
        async fn close(&self) -> Result<(), DeviceError> {
            self.0.close().await
        }
        async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
            self.0.next_event().await
        }
        fn security(&self) -> Option<SecurityProperties> {
            self.0.security()
        }
        fn counters(&self) -> Vec<Counter> {
            self.0.counters()
        }
    }

    impl Netdev for ForgetsEpoch {
        fn interface(&self) -> &str {
            self.0.interface()
        }
        fn statistics(&self) -> NetdevStats {
            self.0.statistics()
        }
        fn destinations(&self) -> Option<Vec<crate::Destination>> {
            self.0.destinations()
        }
    }

    #[tokio::test]
    async fn a_decorator_that_forgets_a_method_is_named_with_the_method() {
        let f =
            device_decorator_forwards("ForgetsOper", |inner| Arc::new(ForgetsOper(inner))).await;
        assert_eq!(checks(&f), ["decorator-forwards", "decorator-forwards"]);
        let d = detail(&f, "decorator-forwards");
        assert!(
            d.contains("rewrote oper") && d.contains("[\"oper\"]"),
            "{d}"
        );

        let f =
            medium_decorator_forwards("ForgetsMetrics", |inner| Arc::new(ForgetsMetrics(inner)))
                .await;
        assert!(
            detail(&f, "decorator-forwards").contains("[\"metrics\"]"),
            "{f:?}"
        );

        let f =
            netdev_decorator_forwards("ForgetsEpoch", |inner| Arc::new(ForgetsEpoch(inner))).await;
        assert!(
            detail(&f, "decorator-forwards").contains("[\"epoch\"]"),
            "{f:?}"
        );

        // The identity decorator forwards everything, three times over.
        assert!(
            device_decorator_forwards("id", |inner| inner)
                .await
                .is_empty()
        );
        assert!(
            medium_decorator_forwards("id", |inner| inner)
                .await
                .is_empty()
        );
        assert!(
            netdev_decorator_forwards("id", |inner| inner)
                .await
                .is_empty()
        );
    }

    // --- the core plane -----------------------------------------------------

    /// `oper` alternates between two answers: not a cache.
    struct Flickers(AtomicU64);

    impl Device for Flickers {
        fn oper(&self) -> OperStatus {
            if self.0.fetch_add(1, Ordering::Relaxed).is_multiple_of(2) {
                OperStatus::up()
            } else {
                OperStatus::unknown()
            }
        }
    }

    /// A reading without an age: an answer from I/O pretending to be cached.
    struct Ageless;

    impl Device for Ageless {
        fn report(&self) -> Report {
            Report::new().rssi(-70_000)
        }
    }

    #[test]
    fn a_status_that_changes_between_two_calls_and_a_reading_without_an_age_are_findings() {
        assert_eq!(
            checks(&core(&Flickers(AtomicU64::new(0)))),
            ["oper-is-cached"]
        );
        assert_eq!(checks(&core(&Ageless)), ["report-says-its-age"]);
        assert!(core(&Recording::new()).is_empty());
    }

    // --- events ---------------------------------------------------------------

    /// Says the same thing `n` times, then falls silent.
    struct Repeats {
        script: Vec<DeviceEvent>,
        at: AtomicU64,
    }

    #[async_trait::async_trait]
    impl Device for Repeats {
        async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
            #[allow(clippy::cast_possible_truncation)]
            let i = self.at.fetch_add(1, Ordering::Relaxed) as usize;
            match self.script.get(i) {
                Some(ev) => Ok(ev.clone()),
                None => std::future::pending().await,
            }
        }
    }

    #[tokio::test(start_paused = true)]
    async fn a_condition_reported_twice_without_the_opposite_edge_is_a_finding() {
        let nags = Repeats {
            script: vec![
                DeviceEvent::raised("+CME ERROR 3"),
                DeviceEvent::raised("+CME ERROR 3"),
                DeviceEvent::cleared("+CME ERROR 3"),
            ],
            at: AtomicU64::new(0),
        };
        let f = events_are_edge_triggered(&nags, tokio::time::sleep(Duration::from_secs(1))).await;
        assert_eq!(checks(&f), ["events-are-edge-triggered"]);
        assert!(f[0].detail.contains("twice in a row"), "{f:?}");

        // Different words for the two edges, as a netdev spells a carrier,
        // and a condition that comes back after clearing: no finding.
        let edgy = Repeats {
            script: vec![
                DeviceEvent::raised("no carrier"),
                DeviceEvent::cleared("carrier"),
                DeviceEvent::raised("no carrier"),
                DeviceEvent::raised("registration lost"),
            ],
            at: AtomicU64::new(0),
        };
        assert!(
            events_are_edge_triggered(&edgy, tokio::time::sleep(Duration::from_secs(1)))
                .await
                .is_empty()
        );
    }

    // --- the configuration plane --------------------------------------------

    #[derive(Clone, Copy, Default)]
    #[allow(clippy::struct_excessive_bools)] // one switch per way to get it wrong
    struct Faults {
        /// Accepts a change and changes nothing.
        nods: bool,
        /// Answers an empty undo.
        forgets_undo: bool,
        /// Accepts a change to the contract group.
        bends: bool,
        /// Reads the PIN back.
        leaks: bool,
        /// Puts the PIN in the identity.
        echoes: bool,
        /// Reads back a parameter the schema does not declare.
        off_schema: bool,
        /// Declares a group twice and a bound that crosses.
        bad_schema: bool,
    }

    /// A device with three groups: hot `tune`, hot `auth` with a sensitive
    /// PIN, contract `port`. Each fault is one way to get it wrong.
    struct Knobs {
        faults: Faults,
        state: Mutex<BTreeMap<&'static str, ConfigValue>>,
    }

    impl Knobs {
        fn new(faults: Faults) -> Self {
            Self {
                faults,
                state: Mutex::new(
                    [
                        ("level", ConfigValue::Integer(3)),
                        ("label", ConfigValue::Text("lab".into())),
                        ("pin", ConfigValue::Text("0000".into())),
                        ("baud", ConfigValue::Integer(9600)),
                    ]
                    .into_iter()
                    .collect(),
                ),
            }
        }

        fn get(&self, name: &str) -> ConfigValue {
            self.state.lock().expect("not poisoned")[name].clone()
        }
    }

    impl Device for Knobs {
        fn identity(&self) -> Identity {
            if self.faults.echoes {
                Identity::unknown().serial_num(self.get("pin").to_string())
            } else {
                Identity::unknown()
            }
        }
        fn configuration(&self) -> Option<&dyn Configure> {
            Some(self)
        }
    }

    #[async_trait::async_trait]
    impl Configure for Knobs {
        fn schema(&self) -> Schema {
            let mut s = Schema::new()
                .with(
                    ConfigGroup::new("tune", ParamClass::Hot, "tuning")
                        .with(ParamSpec::new(
                            "level",
                            ParamKind::integer(Some(0), Some(10), None),
                            "a level",
                        ))
                        .with(ParamSpec::new("label", ParamKind::Text, "a label")),
                )
                .with(
                    ConfigGroup::new("auth", ParamClass::Hot, "the PIN")
                        .with(ParamSpec::new("pin", ParamKind::Text, "the SIM PIN").sensitive()),
                )
                .with(
                    ConfigGroup::new("port", ParamClass::Contract, "the port").with(
                        ParamSpec::new(
                            "baud",
                            ParamKind::integer(Some(1200), Some(115_200), Some("bit/s")),
                            "the rate",
                        ),
                    ),
                );
            if self.faults.bad_schema {
                s = s.with(ConfigGroup::new("tune", ParamClass::Hot, "again").with(
                    ParamSpec::new("x", ParamKind::integer(Some(10), Some(1), None), "crossed"),
                ));
            }
            s
        }

        fn effective(&self) -> Effective {
            let mut tune: BTreeMap<String, ConfigValue> = [
                ("level".to_string(), self.get("level")),
                ("label".to_string(), self.get("label")),
            ]
            .into_iter()
            .collect();
            if self.faults.off_schema {
                tune.insert("bogus".into(), ConfigValue::Bool(true));
            }
            let mut auth = BTreeMap::new();
            if self.faults.leaks {
                auth.insert("pin".to_string(), self.get("pin"));
            }
            [
                ("tune".to_string(), tune),
                ("auth".to_string(), auth),
                (
                    "port".to_string(),
                    [("baud".to_string(), self.get("baud"))]
                        .into_iter()
                        .collect(),
                ),
            ]
            .into_iter()
            .collect()
        }

        async fn apply(
            &self,
            group: &str,
            values: &BTreeMap<String, ConfigValue>,
        ) -> Result<Undo, ConfigError> {
            if group == "port" && !self.faults.bends {
                return Err(ConfigError::Contract(group.into()));
            }
            let mut state = self.state.lock().expect("not poisoned");
            let mut undo = Undo::new();
            for (name, v) in values {
                let key: &'static str = match name.as_str() {
                    "level" => "level",
                    "label" => "label",
                    "pin" => "pin",
                    "baud" => "baud",
                    other => {
                        return Err(ConfigError::UnknownParameter {
                            group: group.into(),
                            name: other.into(),
                        });
                    }
                };
                if !self.faults.forgets_undo {
                    undo.insert(name.clone(), state[key].clone());
                }
                if !self.faults.nods {
                    state.insert(key, v.clone());
                }
            }
            Ok(undo)
        }
    }

    #[tokio::test]
    async fn each_configuration_fault_is_found_and_a_device_without_one_passes() {
        assert!(
            configuration(&Knobs::new(Faults::default()))
                .await
                .is_empty()
        );

        let cases: [(&str, Faults, &str, &str); 7] = [
            (
                "nods",
                Faults {
                    nods: true,
                    ..Faults::default()
                },
                "read-back",
                "not done until it can be read back",
            ),
            (
                "forgets_undo",
                Faults {
                    forgets_undo: true,
                    ..Faults::default()
                },
                "undo-restores",
                "not what it was",
            ),
            (
                "bends",
                Faults {
                    bends: true,
                    ..Faults::default()
                },
                "contract-refused",
                "accepted",
            ),
            (
                "leaks",
                Faults {
                    leaks: true,
                    ..Faults::default()
                },
                "sensitive-never-read-back",
                "effective",
            ),
            (
                "echoes",
                Faults {
                    echoes: true,
                    ..Faults::default()
                },
                "sensitive-never-read-back",
                "the identity",
            ),
            (
                "off_schema",
                Faults {
                    off_schema: true,
                    ..Faults::default()
                },
                "effective-within-schema",
                "tune/bogus",
            ),
            (
                "bad_schema",
                Faults {
                    bad_schema: true,
                    ..Faults::default()
                },
                "schema-is-valid",
                "declared twice",
            ),
        ];
        for (name, faults, check, words) in cases {
            let f = configuration(&Knobs::new(faults)).await;
            let d = detail(&f, check);
            assert!(
                !d.is_empty() && d.contains(words),
                "{name}: expected {check} saying {words:?}; got {f:?}"
            );
        }
        // The crossed bound is a second finding of the bad schema.
        let f = schema_is_valid(
            &Knobs::new(Faults {
                bad_schema: true,
                ..Faults::default()
            })
            .schema(),
        );
        assert!(
            detail(&f, "schema-is-valid").contains("min 10 is above max 1"),
            "{f:?}"
        );
    }

    // --- a netdev ---------------------------------------------------------

    /// Counters that go backwards; with `honest`, the epoch moves when they do.
    struct Rewinds {
        honest: bool,
        reads: AtomicU64,
    }

    impl Device for Rewinds {}

    impl Netdev for Rewinds {
        fn interface(&self) -> &'static str {
            "wwan0"
        }
        fn statistics(&self) -> NetdevStats {
            let n = self.reads.fetch_add(1, Ordering::Relaxed);
            NetdevStats::new().in_octets(if n < 2 { 1_000 } else { 10 })
        }
        fn epoch(&self) -> u64 {
            u64::from(self.honest && self.reads.load(Ordering::Relaxed) >= 2)
        }
    }

    #[tokio::test]
    async fn a_counter_that_goes_backwards_without_moving_the_epoch_is_a_finding() {
        let f = netdev(
            &Rewinds {
                honest: false,
                reads: AtomicU64::new(0),
            },
            3,
            || async {},
        )
        .await;
        assert_eq!(checks(&f), ["counters-never-decrease"]);
        assert!(
            f[0].detail.contains("in_octets went from 1000 to 10"),
            "{f:?}"
        );

        let f = netdev(
            &Rewinds {
                honest: true,
                reads: AtomicU64::new(0),
            },
            3,
            || async {},
        )
        .await;
        assert!(f.is_empty(), "{f:?}");
    }
}