zenkey-model 0.24.0

zk2 keys and contracts without a Zenoh session: the key grammar, the contract authoring format, canonical form, fingerprints and bundles
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
//! `arbitration.v1`: one commander at a time, in the binding's order
//! (`spec/profiles/arbitration/v1.md`, #909).
//!
//! The profile's session-free half: a role's declaration read from its
//! contract's requirement and the revision of the required interface the
//! consumer holds (§2.2, §2.3), the first profile to read a requirement's
//! annotations; the ranking of a binding's providers (§2.4); one role's
//! arbitration as a pure state machine, which the runtime and the tools
//! both drive (§2.5 to §2.11); and §5's three questions, which never fold
//! an unestablished answer into no (§2.14).
//!
//! | Rule | Item |
//! |---|---|
//! | §2.2 the declaration: arbitrated, invalid, unread | [`declaration`], [`declaration_of`], [`Declaration`], [`Invalid`], [`Role`], [`Revision`] |
//! | §2.3 the deadline, from the revision held | [`deadline_of`], [`Arbitrated::deadline`], [`crate::timing`]'s declaration |
//! | §2.4 the ranking, wildcards, shadowed entries | [`Binding`], [`Entry`], [`Rank`] |
//! | §2.5 samples and who sent them | [`Arbiter::identify`], [`Sample`], [`Outcome`] |
//! | §2.5's outcome 6, a governed interface's incumbents (`redundancy.v1` §2.10), [`crate::redundancy::Fence`] since #987's N1 | [`Incumbents`], [`Holding`] |
//! | §2.6 to §2.8 eligibility, withdrawals, a move | [`Arbiter`], [`Event`] |
//! | §2.7 a read again, and observer §3.6 (0.38): a read never undoes a token heard since it was asked | [`Arbiter::ask`], [`Asked`], carried by [`Event::Read`] |
//! | §2.9 to §2.11 selection, switches, the dead-man | [`Arbiter::observe`], [`Step`], [`Switch`], [`Cause`] |
//! | §2.14, §5 what a tool concludes | [`judge_declaration`], [`judge_selection`], [`judge_binding`], [`held_over`] |
//!
//! ```text
//! declaration(role, revision held, params) ─▶ arbitrated {priority, stream, deadline} │ invalid [reasons] │ unread │ not arbitrated   §2.2
//! Binding::rank(address)                   ─▶ (entry, system, service), compared in that order                          §2.4
//! Arbiter::start / observe(at, event)      ─▶ switches {start│sample│deadline│withdrawn}, an outcome, reads again        §2.5–§2.11
//! Arbiter::due()                           ─▶ the instant to arm the timer for: the active provider's deadline
//! judge_declaration / _selection / _binding ─▶ §5's questions, in five states                                         §2.14
//! ```
//!
//! There is no I/O and no clock here. Every instant is a [`Mono`], a
//! reading of the consumer's monotonic clock (`timing.v1` §2.5's deadline
//! runs on it). A consumer's runtime starts the
//! [`Arbiter`] at its start, hands it each sample of the role's
//! subscription ([`Event::Sample`]), each interface token its watch hears
//! declared or withdrawn ([`Event::Declared`], [`Event::Withdrawn`]), each
//! move of the watch session's transport and the round trip after it
//! ([`Event::Moved`], [`Event::Stood`]), and its timer ([`Event::Tick`]),
//! armed for [`Arbiter::due`]; it reads again each address a [`Step`]
//! names in `reread` and hands the read back ([`Event::Read`]), with the
//! [`Asked`] [`Arbiter::ask`] gave when it asked it, so the read applies
//! to no token heard since (observer §3.6, 0.38); it
//! delivers a sample whose [`Outcome`] is [`Outcome::Delivered`], and
//! tells its application of each [`Switch`].
//!
//! The deadline is `timing.v1`'s, never restated: [`deadline_of`] reads it
//! through [`crate::timing::declaration`] (`timing.v1` §2.2, §2.3, §2.5),
//! and the [`Arbiter`] judges each provider's one key with a
//! [`crate::timing::Tracker`] of its own, eligible while that tracker holds
//! it heard and not missed.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::time::Duration;

use serde_json::Value;

use crate::authoring::{Kind, RequireCardinality};
use crate::contract::{Contract, Requirement};
use crate::grammar::{Addr, IfaceId, InstanceId, KeyError, KindToken, Name, ZkKey, parse};
use crate::redundancy::Heard;
use crate::template::Template;
use crate::timing::{self, MemberState, Mono, Tracker};

/// The profile's id, as a contract lists it in `uses`.
pub const PROFILE: &str = "arbitration.v1";

/// The profile's name, as an annotation key's prefix carries it.
pub const NAME: &str = "arbitration";

/// `arbitration.policy` (§4), on a requirement.
pub const POLICY: &str = "arbitration.policy";

/// The published vocabulary (§4): the keys under `arbitration.`, which
/// W105 reads in place of core Appendix D's interim row (core 0.54), the
/// same key.
pub const VOCABULARY: &[&str] = &["policy"];

// --- §2.2: the declaration -------------------------------------------------------

/// How a consumer chooses among a role's providers (§4). 1.0 defines one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Policy {
    /// The first eligible provider in the binding's order (§2.4 to §2.11).
    Priority,
}

impl Policy {
    /// The vocabulary's value, and the fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Priority => "priority",
        }
    }
}

impl fmt::Display for Policy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Why a declaration is invalid (§2.2), in the order checked.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Invalid {
    /// The policy carried, and the declaring contract's `uses` naming no
    /// major of the profile (core E020's).
    NotUsed,
    /// A component's manifest declares the role.
    ManifestRole,
    /// `freshest` or `lease`, reserved (§4).
    PolicyUnsupported,
    /// Not one of the strings `priority`, `freshest`, `lease`.
    Value,
    /// The role's cardinality is not `many`.
    Cardinality,
    /// The role does not consume exactly one stream.
    Resource,
    /// That stream has no deadline as `timing.v1` reads it.
    NoDeadline,
    /// A parameter of that stream's template is not bound (core R2).
    ParamsUnbound,
    /// The role consumes a frame resource (core §7.7) and no stream that
    /// is not one: a frame is never an arbitrated role's stream (text 0.6).
    Framed,
}

impl Invalid {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NotUsed => "not_used",
            Self::ManifestRole => "manifest_role",
            Self::PolicyUnsupported => "policy_unsupported",
            Self::Value => "value",
            Self::Cardinality => "cardinality",
            Self::Resource => "resource",
            Self::NoDeadline => "no_deadline",
            Self::ParamsUnbound => "params_unbound",
            Self::Framed => "framed",
        }
    }

    /// What it says, for a linter's line or a refusal.
    #[must_use]
    pub fn says(self) -> &'static str {
        match self {
            Self::NotUsed => "arbitration.policy is written, and uses does not list arbitration.v1",
            Self::ManifestRole => {
                "only a contract's role is arbitrated: a manifest's role reaches no descriptor with its policy"
            }
            Self::PolicyUnsupported => {
                "freshest and lease are reserved; arbitration.v1 1.0 defines priority only"
            }
            Self::Value => "arbitration.policy is the string priority",
            Self::Cardinality => "an arbitrated role has cardinality many",
            Self::Resource => "an arbitrated role consumes exactly one stream resource",
            Self::NoDeadline => {
                "the role's stream declares a timing.v1 deadline, at or above its period"
            }
            Self::ParamsUnbound => {
                "every parameter of the role's stream is bound by the role's parameter bindings"
            }
            Self::Framed => {
                "a frame resource is never an arbitrated role's stream: its put carries several records"
            }
        }
    }
}

impl fmt::Display for Invalid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.says())
    }
}

/// A valid declaration (§2.2): what an [`Arbiter`] needs of the role.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Arbitrated {
    pub policy: Policy,
    /// The required interface.
    pub iface: IfaceId,
    /// The role's stream: its kind token (`stream` or `@stream`) and its
    /// template.
    pub token: KindToken,
    pub template: Template,
    /// The stream's deadline in the revision held (§2.3).
    pub deadline: Duration,
    /// Its period, when written.
    pub period: Option<Duration>,
}

impl Arbitrated {
    /// The stream as the fixture writes it, `<token>/<template>`.
    #[must_use]
    pub fn resource(&self) -> String {
        format!("{}/{}", self.token.as_str(), self.template.as_str())
    }
}

/// A role's declaration (§2.2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Declaration {
    /// No `arbitration.policy`, or another major's: not this profile's. A
    /// `many` role receives from every bound provider, merged (core §3.2).
    NotArbitrated,
    /// No revision of the required interface held, checks 1 to 5 passing.
    Unread,
    /// The reasons, in the order checked.
    Invalid(Vec<Invalid>),
    /// Arbitrated.
    Arbitrated(Arbitrated),
}

impl Declaration {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::NotArbitrated => "not_arbitrated",
            Self::Unread => "unread",
            Self::Invalid(_) => "invalid",
            Self::Arbitrated(_) => "arbitrated",
        }
    }

    /// The valid declaration, if it is one.
    #[must_use]
    pub fn arbitrated(&self) -> Option<&Arbitrated> {
        match self {
            Self::Arbitrated(a) => Some(a),
            _ => None,
        }
    }

    /// Whether the role carries a policy: arbitrated, invalid or unread.
    #[must_use]
    pub fn carries_policy(&self) -> bool {
        !matches!(self, Self::NotArbitrated)
    }
}

/// A role, as §2.2 reads it.
#[derive(Debug, Clone, Copy)]
pub struct Role<'a> {
    /// The declaring contract's `uses`, or `None` for a role a component's
    /// manifest declares.
    pub declared_by: Option<&'a [IfaceId]>,
    /// The requirement's `resources` (templates), or `None`: every one.
    pub resources: Option<&'a [String]>,
    pub cardinality: RequireCardinality,
    pub annotations: &'a BTreeMap<String, Value>,
}

impl<'a> Role<'a> {
    /// A role its contract declares.
    #[must_use]
    pub fn of(declaring: &'a Contract, req: &'a Requirement) -> Self {
        Self {
            declared_by: Some(declaring.uses.as_slice()),
            resources: req.resources.as_deref(),
            cardinality: req.cardinality,
            annotations: &req.annotations,
        }
    }

    /// A role a component's manifest declares.
    #[must_use]
    pub fn of_manifest(req: &'a Requirement) -> Self {
        Self {
            declared_by: None,
            resources: req.resources.as_deref(),
            cardinality: req.cardinality,
            annotations: &req.annotations,
        }
    }
}

/// One resource of the required interface's revision, as §2.2 reads it.
#[derive(Debug, Clone, Copy)]
pub struct Offered<'a> {
    pub token: KindToken,
    pub template: &'a Template,
    /// Its resolved annotations (core §9.3).
    pub annotations: &'a BTreeMap<String, Value>,
    /// Whether it is a frame resource (core §7.7), which §2.2's check 6
    /// counts as none and check 9 refuses.
    pub frame: bool,
}

/// The revision of the required interface a reader holds (§2.3).
#[derive(Debug, Clone)]
pub struct Revision<'a> {
    pub iface: &'a IfaceId,
    pub resources: Vec<Offered<'a>>,
}

impl<'a> Revision<'a> {
    /// A contract's revision.
    #[must_use]
    pub fn of(c: &'a Contract) -> Self {
        Self {
            iface: &c.iface,
            resources: c
                .resources
                .iter()
                .map(|r| Offered {
                    token: r.token,
                    template: &r.template,
                    annotations: &r.annotations,
                    frame: matches!(&r.body, crate::contract::Body::Data(d) if d.frame.is_some()),
                })
                .collect(),
        }
    }
}

/// The resource kind a kind token carries (core §1.3).
fn kind_of(token: KindToken) -> Kind {
    match token {
        KindToken::Stream | KindToken::ExplicitStream => Kind::Stream,
        KindToken::State | KindToken::ExplicitState => Kind::State,
        KindToken::Events => Kind::Event,
        KindToken::Op => Kind::Operation,
    }
}

/// The deadline and the period of one resource of a revision, as
/// `timing.v1` reads them (§2.3, §2.2 check 7): its declaration
/// ([`timing::declaration`], `timing.v1` §2.2, §2.3) valid, and its judged
/// deadline ([`timing::Declared::judged_deadline`], `timing.v1` §2.5) one:
/// declared, and not below its period. `None` is no deadline: none
/// declared, one below the period, or a declaration invalid whole.
#[must_use]
pub fn deadline_of(r: &Offered<'_>) -> Option<(Duration, Option<Duration>)> {
    let d = match timing::declaration(kind_of(r.token), r.annotations) {
        timing::Declaration::Declared(d) => d,
        _ => return None,
    };
    Some((d.judged_deadline()?, d.period))
}

/// Reads a role's declaration (§2.2) from the role, the revision of the
/// required interface held (`None`: none held), and the role's parameter
/// bindings as configured (core R2). Each check runs alone, in §2.2's
/// order; checks 7 and 8 only when check 6 passes, and 6 to 8 only with a
/// revision held.
#[must_use]
pub fn declaration(
    role: &Role<'_>,
    provider: Option<&Revision<'_>>,
    params: &BTreeMap<String, String>,
) -> Declaration {
    let Some(policy) = role.annotations.get(POLICY) else {
        return Declaration::NotArbitrated;
    };
    let mut why = Vec::new();
    match role.declared_by {
        Some(uses) => {
            let v1 = uses.iter().any(|u| u.name() == NAME && u.major() == 1);
            let any = uses.iter().any(|u| u.name() == NAME);
            if any && !v1 {
                // Another major's text: its key is its own.
                return Declaration::NotArbitrated;
            }
            if !any {
                why.push(Invalid::NotUsed);
            }
        }
        None => why.push(Invalid::ManifestRole),
    }
    match policy.as_str() {
        Some("priority") => {}
        Some("freshest" | "lease") => why.push(Invalid::PolicyUnsupported),
        _ => why.push(Invalid::Value),
    }
    if role.cardinality != RequireCardinality::Many {
        why.push(Invalid::Cardinality);
    }
    let Some(rev) = provider else {
        return if why.is_empty() {
            Declaration::Unread
        } else {
            Declaration::Invalid(why)
        };
    };
    let consumed: Vec<&Offered<'_>> = rev
        .resources
        .iter()
        .filter(|r| match role.resources {
            None => true,
            Some(names) => names.iter().any(|n| n == r.template.as_str()),
        })
        .collect();
    // Check 6 counts no frame resource (text 0.6): a role on a frame and
    // one plain stream is read over the stream.
    let counted: Vec<&Offered<'_>> = consumed.iter().copied().filter(|r| !r.frame).collect();
    let one = match counted.as_slice() {
        [r] if matches!(r.token, KindToken::Stream | KindToken::ExplicitStream) => Some(*r),
        _ => {
            why.push(Invalid::Resource);
            None
        }
    };
    let mut deadline = None;
    if let Some(r) = one {
        deadline = deadline_of(r);
        if deadline.is_none() {
            why.push(Invalid::NoDeadline);
        }
        if r.template.params().any(|(p, _)| !params.contains_key(p)) {
            why.push(Invalid::ParamsUnbound);
        }
    }
    // Check 9: a frame consumed, and no stream that is not one.
    let plain_stream = counted
        .iter()
        .any(|r| matches!(r.token, KindToken::Stream | KindToken::ExplicitStream));
    if consumed.iter().any(|r| r.frame) && !plain_stream {
        why.push(Invalid::Framed);
    }
    match (one, deadline) {
        (Some(r), Some((deadline, period))) if why.is_empty() => {
            Declaration::Arbitrated(Arbitrated {
                policy: Policy::Priority,
                iface: rev.iface.clone(),
                token: r.token,
                template: r.template.clone(),
                deadline,
                period,
            })
        }
        _ => Declaration::Invalid(why),
    }
}

/// [`declaration`] of the role `role` of the contract `declaring`, over the
/// revision `provider` of its required interface (`None`: none held).
/// `None` when the contract declares no such role.
#[must_use]
pub fn declaration_of(
    declaring: &Contract,
    role: &str,
    provider: Option<&Contract>,
    params: &BTreeMap<String, String>,
) -> Option<Declaration> {
    let req = declaring.requires.get(role)?;
    let rev = provider.map(Revision::of);
    Some(declaration(&Role::of(declaring, req), rev.as_ref(), params))
}

// --- §2.4: the ranking -----------------------------------------------------------

/// One entry of a binding: `<system>/<service>`, each chunk a plain chunk
/// or `*` (core §1.2, D009), a `self.system` already resolved (core §3.2).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Entry {
    /// `None` is `*`.
    system: Option<Name>,
    service: Option<Name>,
}

impl Entry {
    /// Parses an entry.
    pub fn parse(s: &str) -> Result<Self, KeyError> {
        let (sys, svc) = s.split_once('/').ok_or(KeyError::Shape(
            s.to_owned(),
            "a binding entry is <system>/<service>",
        ))?;
        let chunk = |what: &'static str, c: &str| -> Result<Option<Name>, KeyError> {
            if c == "*" {
                Ok(None)
            } else {
                Name::new(what, c).map(Some)
            }
        };
        Ok(Self {
            system: chunk("system", sys)?,
            service: chunk("service", svc)?,
        })
    }

    /// Whether either chunk is `*`.
    #[must_use]
    pub fn is_wildcard(&self) -> bool {
        self.system.is_none() || self.service.is_none()
    }

    /// The address of an exact entry.
    #[must_use]
    pub fn exact(&self) -> Option<Addr> {
        Some(Addr {
            system: self.system.clone()?,
            service: self.service.clone()?,
        })
    }

    /// Whether it matches an address: each chunk `*` or equal (§0).
    #[must_use]
    pub fn matches(&self, a: &Addr) -> bool {
        self.system.as_ref().is_none_or(|s| *s == a.system)
            && self.service.as_ref().is_none_or(|s| *s == a.service)
    }

    /// Whether it matches every address `later` does: each of its chunks
    /// `*` or equal to `later`'s (§2.4, a shadowed entry).
    #[must_use]
    pub fn covers(&self, later: &Entry) -> bool {
        fn chunk(a: Option<&Name>, b: Option<&Name>) -> bool {
            match (a, b) {
                (None, _) => true,
                (Some(a), Some(b)) => a == b,
                (Some(_), None) => false,
            }
        }
        chunk(self.system.as_ref(), later.system.as_ref())
            && chunk(self.service.as_ref(), later.service.as_ref())
    }
}

impl fmt::Display for Entry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let c = |n: &Option<Name>| n.as_ref().map_or("*", Name::as_str).to_owned();
        write!(f, "{}/{}", c(&self.system), c(&self.service))
    }
}

/// A provider's rank (§2.4): the position of the first entry matching it,
/// then its system, then its service, each compared byte by byte. Lower is
/// higher priority.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Rank {
    entry: usize,
    system: String,
    service: String,
}

impl Rank {
    /// The 0-based position of the entry it ranks at.
    #[must_use]
    pub fn entry(&self) -> usize {
        self.entry
    }
}

/// A role's binding, its entries in their configured order (core R1, R3).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Binding {
    entries: Vec<Entry>,
}

impl Binding {
    /// Parses a binding as a descriptor lists it.
    pub fn parse<S: AsRef<str>>(entries: &[S]) -> Result<Self, KeyError> {
        Ok(Self {
            entries: entries
                .iter()
                .map(|e| Entry::parse(e.as_ref()))
                .collect::<Result<_, _>>()?,
        })
    }

    /// The entries, in order.
    #[must_use]
    pub fn entries(&self) -> &[Entry] {
        &self.entries
    }

    /// Whether it has no entry: an unbound role.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// An address's rank, `None` when no entry matches it (§2.4).
    #[must_use]
    pub fn rank(&self, a: &Addr) -> Option<Rank> {
        let entry = self.entries.iter().position(|e| e.matches(a))?;
        Some(Rank {
            entry,
            system: a.system.as_str().to_owned(),
            service: a.service.as_str().to_owned(),
        })
    }

    /// The providers in rank order: every exact entry's address, heard or
    /// not, and every heard address an entry matches, once each (§2.4).
    #[must_use]
    pub fn ranked<'a, I: IntoIterator<Item = &'a Addr>>(&self, heard: I) -> Vec<Addr> {
        let mut by: BTreeMap<Rank, Addr> = BTreeMap::new();
        let mut add = |a: &Addr| {
            if let Some(r) = self.rank(a) {
                by.entry(r).or_insert_with(|| a.clone());
            }
        };
        for a in self.entries.iter().filter_map(Entry::exact) {
            add(&a);
        }
        for a in heard {
            add(a);
        }
        by.into_values().collect()
    }

    /// The heard addresses no entry matches, by system then service, once
    /// each.
    #[must_use]
    pub fn unbound<'a, I: IntoIterator<Item = &'a Addr>>(&self, heard: I) -> Vec<Addr> {
        heard
            .into_iter()
            .filter(|a| self.rank(a).is_none())
            .cloned()
            .collect::<BTreeSet<_>>()
            .into_iter()
            .collect()
    }

    /// The 0-based positions of the wildcard entries.
    #[must_use]
    pub fn wildcards(&self) -> Vec<usize> {
        self.entries
            .iter()
            .enumerate()
            .filter(|(_, e)| e.is_wildcard())
            .map(|(i, _)| i)
            .collect()
    }

    /// The 0-based positions of the shadowed entries: an entry an earlier
    /// one covers (§2.4).
    #[must_use]
    pub fn shadowed(&self) -> Vec<usize> {
        (0..self.entries.len())
            .filter(|&j| self.entries[..j].iter().any(|e| e.covers(&self.entries[j])))
            .collect()
    }
}

// --- §2.5 to §2.11: one role's arbitration -----------------------------------------

/// What became of a sample (§2.5, §2.9).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Outcome {
    /// An arrival of the active provider: delivered.
    Delivered,
    /// An arrival of another provider: counted, never delivered.
    NotActive,
    /// Its key is not concrete (core R6).
    Wild,
    /// Not the role's stream's key at any address.
    Unresolved,
    /// No entry matches its address.
    Unbound,
    /// A delete sample: no arrival (`timing.v1` §2.5).
    Deleted,
    /// `timing.v1` reads it expired: no arrival (`timing.v1` §2.6).
    Expired,
    /// A governed interface's sample `redundancy.v1` §2.10 does not
    /// accept: no arrival.
    NotIncumbent,
}

impl Outcome {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Delivered => "delivered",
            Self::NotActive => "not_active",
            Self::Wild => "wild",
            Self::Unresolved => "unresolved",
            Self::Unbound => "unbound",
            Self::Deleted => "deleted",
            Self::Expired => "expired",
            Self::NotIncumbent => "not_incumbent",
        }
    }

    /// Whether the sample is delivered to the application.
    #[must_use]
    pub fn delivered(self) -> bool {
        self == Self::Delivered
    }
}

/// A sample of the role's subscription, as the runtime hands it over.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sample<'a> {
    /// Its key, base-relative (core §1.6).
    pub key: &'a str,
    /// A delete sample, which is no arrival (`timing.v1` §2.5).
    pub delete: bool,
    /// `timing.v1` reads it expired, on the deployment's stated bound
    /// (`timing.v1` §2.6).
    pub expired: bool,
    /// The required interface is governed, and `redundancy.v1` §2.10 does
    /// not accept it.
    pub not_incumbent: bool,
}

impl<'a> Sample<'a> {
    /// A put sample, neither expired nor refused by `redundancy.v1`.
    #[must_use]
    pub fn new(key: &'a str) -> Self {
        Self {
            key,
            delete: false,
            expired: false,
            not_incumbent: false,
        }
    }
}

/// Why a switch happened (§2.10).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Cause {
    /// The consumer's start: the dead-man, from none.
    Start,
    /// An arrival made its provider active.
    Sample,
    /// The active provider missed its deadline.
    Deadline,
    /// The active provider was withdrawn.
    Withdrawn,
}

impl Cause {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Start => "start",
            Self::Sample => "sample",
            Self::Deadline => "deadline",
            Self::Withdrawn => "withdrawn",
        }
    }
}

impl fmt::Display for Cause {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A switch (§2.10): `None` is no provider, the dead-man.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Switch {
    pub from: Option<Addr>,
    pub to: Option<Addr>,
    pub cause: Cause,
    /// `from`'s last arrival, `None` when `from` is: what a consumer prints
    /// beside the switch as `last_ms` (`scenarios.md`, its conventions).
    pub last: Option<Mono>,
}

/// What the runtime tells an [`Arbiter`], each at its instant.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event<'a> {
    /// A sample of the role's subscription (§2.5).
    Sample(Sample<'a>),
    /// The watch heard an interface token declared: its key (§2.7).
    Declared(&'a str),
    /// The watch heard an interface token withdrawn: its key (§2.7).
    Withdrawn(&'a str),
    /// A read of an address's presence: when it was asked
    /// ([`Arbiter::ask`]), whether it is complete (core §8.1), and the
    /// instances it shows holding the required interface's token there
    /// (§2.7). It applies to no instance whose token the watch heard since
    /// it was asked (observer §3.6).
    Read {
        address: Addr,
        asked: Asked,
        complete: bool,
        held: BTreeSet<InstanceId>,
    },
    /// The watch session's transport closed or opened (§2.8).
    Moved,
    /// The round trip asked after the last move stands (§2.8).
    Stood,
    /// The timer fired (§2.9).
    Tick,
}

/// What an [`Arbiter`] decided at one event.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Step {
    /// At most two: the active provider's miss (cause `deadline`), then
    /// the event's own (§2.9, §2.10).
    pub switches: Vec<Switch>,
    /// For a sample: what became of it.
    pub outcome: Option<Outcome>,
    /// The addresses to read again (§2.7), in rank order: the reference
    /// reads each 0.1 s later, one read for a burst.
    pub reread: Vec<Addr>,
}

/// A provider's counts of the samples counted for it (§2.5).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Counts {
    pub delivered: u64,
    pub not_active: u64,
    pub deleted: u64,
    pub expired: u64,
    pub not_incumbent: u64,
}

/// The counts of the samples with no provider (§2.5).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Discards {
    pub wild: u64,
    pub unresolved: u64,
    pub unbound: u64,
}

/// The member a provider's tracker holds: its one key in the role (§2.2
/// check 8), so a provider's deadline is `timing.v1` §2.5's per (address,
/// key).
const MEMBER: &str = "key";

/// A deadline tracker for one provider's one key (`timing.v1` §2.5), its
/// bound one member, started at `start` when given: a tracker counts no
/// arrival before its start.
fn tracker(deadline: Duration, start: Option<Mono>) -> Tracker {
    let mut t = Tracker::new(deadline, Some(1), [MEMBER]);
    if let Some(at) = start {
        t.observe(at, timing::Event::Start);
    }
    t
}

#[derive(Debug, Clone)]
struct Provider {
    addr: Addr,
    /// Its key's deadline (`timing.v1` §2.5): its arrivals since its last
    /// re-admission, a withdrawal starting it anew (§2.6, §2.7).
    tracker: Tracker,
    withdrawn: bool,
    /// The instances known holding the required interface's token (§2.7).
    held: BTreeSet<InstanceId>,
    /// When the watch last heard each instance's token (observer §3.6).
    heard: Heard,
    counts: Counts,
    /// Its last arrival its tracker took, kept across a withdrawal: a
    /// switch's `last` (never a decision's input).
    arrived: Option<Mono>,
}

impl Provider {
    fn new(addr: Addr, deadline: Duration, start: Option<Mono>) -> Self {
        Self {
            addr,
            tracker: tracker(deadline, start),
            withdrawn: false,
            held: BTreeSet::new(),
            heard: Heard::default(),
            counts: Counts::default(),
            arrived: None,
        }
    }

    /// Withdrawn: ineligible, its arrivals forgotten (§2.7).
    fn withdraw(&mut self, deadline: Duration, at: Mono) {
        self.withdrawn = true;
        self.tracker = tracker(deadline, Some(at));
    }

    /// Its last arrival, while its key is in time or not yet judged missed.
    fn last(&self) -> Option<Mono> {
        match self.tracker.state(MEMBER) {
            Some(MemberState::Heard { last }) => Some(last),
            _ => None,
        }
    }
}

/// A presence event kept from a move until its round trip stands (§2.8).
#[derive(Debug, Clone)]
enum Kept {
    Declared(Rank, InstanceId),
    Withdrawn(Rank, InstanceId),
    Read(Rank, Asked, bool, BTreeSet<InstanceId>),
}

/// One consumer's arbitration of one role (§2.5 to §2.11): a pure state
/// machine over events that carry their instants, with no clock and no
/// I/O. It asks reads ([`Step::reread`]) and is told what they found
/// ([`Event::Read`]); it is told of a move ([`Event::Moved`]) and of the
/// round trip after it ([`Event::Stood`]). A restart is a new `Arbiter`.
#[derive(Debug, Clone)]
pub struct Arbiter {
    iface: IfaceId,
    token: KindToken,
    template: Template,
    params: BTreeMap<String, String>,
    deadline: Duration,
    binding: Binding,
    /// Every provider known, in rank order.
    providers: BTreeMap<Rank, Provider>,
    active: Option<Rank>,
    started: bool,
    /// A move pending: from [`Event::Moved`] until [`Event::Stood`].
    moving: bool,
    kept: Vec<Kept>,
    discards: Discards,
    /// The instant of the last event, which no later one may precede.
    last: Option<Mono>,
    /// The interface tokens heard, counted (observer §3.6).
    heard: u64,
}

impl Arbiter {
    /// The arbitration of a role declared `declared`, bound by `binding`,
    /// its parameter bindings `params` resolved (a `self.system` or
    /// `self.service` replaced by the consumer's own; core R2). It holds
    /// nothing until [`Arbiter::start`].
    #[must_use]
    pub fn new(declared: &Arbitrated, binding: Binding, params: BTreeMap<String, String>) -> Self {
        let providers = binding
            .entries()
            .iter()
            .filter_map(Entry::exact)
            .filter_map(|a| Some((binding.rank(&a)?, Provider::new(a, declared.deadline, None))))
            .collect();
        Self {
            iface: declared.iface.clone(),
            token: declared.token,
            template: declared.template.clone(),
            params,
            deadline: declared.deadline,
            binding,
            providers,
            active: None,
            started: false,
            moving: false,
            kept: Vec::new(),
            discards: Discards::default(),
            last: None,
            heard: 0,
        }
    }

    /// A presence read is asked now: what it carries back in
    /// [`Event::Read`], so it applies to no token heard since (observer
    /// §3.6).
    #[must_use]
    pub fn ask(&self) -> Asked {
        Asked(self.heard)
    }

    /// The deadline it judges by (§2.3).
    #[must_use]
    pub fn deadline(&self) -> Duration {
        self.deadline
    }

    /// Its binding.
    #[must_use]
    pub fn binding(&self) -> &Binding {
        &self.binding
    }

    /// The active provider, `None` in the dead-man (§2.9, §2.11).
    #[must_use]
    pub fn active(&self) -> Option<&Addr> {
        self.active
            .as_ref()
            .and_then(|r| self.providers.get(r))
            .map(|p| &p.addr)
    }

    /// Whether it holds the dead-man (§2.11).
    #[must_use]
    pub fn dead_man(&self) -> bool {
        self.active.is_none()
    }

    /// The active provider's due instant: its last arrival plus the
    /// deadline, after which it has missed (`timing.v1` §2.5). The runtime
    /// arms its timer to fire after it, within the detection bound. `None`
    /// in the dead-man, where only an arrival can make a provider eligible
    /// (§2.9).
    #[must_use]
    pub fn due(&self) -> Option<Mono> {
        let p = self.providers.get(self.active.as_ref()?)?;
        Some(p.last()?.saturating_add(self.deadline))
    }

    /// Whether a move is pending (§2.8).
    #[must_use]
    pub fn moving(&self) -> bool {
        self.moving
    }

    /// The providers known, in rank order (§2.4).
    pub fn providers(&self) -> impl Iterator<Item = &Addr> {
        self.providers.values().map(|p| &p.addr)
    }

    /// The counts of a provider's samples (§2.5).
    #[must_use]
    pub fn counts(&self, a: &Addr) -> Counts {
        self.binding
            .rank(a)
            .and_then(|r| self.providers.get(&r))
            .map(|p| p.counts)
            .unwrap_or_default()
    }

    /// The counts of the samples with no provider (§2.5).
    #[must_use]
    pub fn discards(&self) -> Discards {
        self.discards
    }

    /// Whether a provider is withdrawn (§2.7).
    #[must_use]
    pub fn withdrawn(&self, a: &Addr) -> bool {
        self.binding
            .rank(a)
            .and_then(|r| self.providers.get(&r))
            .is_some_and(|p| p.withdrawn)
    }

    /// The provider a sample's key names, or why it has none (§2.5's
    /// outcomes 1 to 3): never from the payload.
    pub fn identify(&self, key: &str) -> Result<Addr, Outcome> {
        if key.contains('*') {
            return Err(Outcome::Wild);
        }
        let Ok(ZkKey::Data {
            addr,
            iface,
            kind,
            resource,
        }) = parse(key)
        else {
            return Err(Outcome::Unresolved);
        };
        if iface != self.iface || kind != self.token {
            return Err(Outcome::Unresolved);
        }
        let chunks: Vec<&str> = resource.iter().map(String::as_str).collect();
        let Some(values) = self.template.matches(&chunks) else {
            return Err(Outcome::Unresolved);
        };
        for (name, vs) in &values {
            match (self.params.get(name), vs.as_slice()) {
                (Some(p), [v]) if p == v => {}
                _ => return Err(Outcome::Unresolved),
            }
        }
        if self.binding.rank(&addr).is_none() {
            return Err(Outcome::Unbound);
        }
        Ok(addr)
    }

    /// Starts: the dead-man, cause `start` (§2.11), every provider's
    /// tracker started (`timing.v1` §2.5). Called once.
    pub fn start(&mut self, at: Mono) -> Step {
        if self.started {
            return Step::default();
        }
        self.started = true;
        self.active = None;
        self.last = Some(at);
        for p in self.providers.values_mut() {
            p.tracker.observe(at, timing::Event::Start);
        }
        Step {
            switches: vec![Switch {
                from: None,
                to: None,
                cause: Cause::Start,
                last: None,
            }],
            ..Step::default()
        }
    }

    /// Hands it an event at instant `at`, never before the last one's: it
    /// decides the time first, then the event, then selects (§2.9).
    pub fn observe(&mut self, at: Mono, event: Event<'_>) -> Step {
        let mut step = Step::default();
        if !self.started {
            return step;
        }
        debug_assert!(
            self.last.is_none_or(|l| at >= l),
            "an event at {at:?} precedes the last one, at {:?}",
            self.last
        );
        self.last = Some(at);
        // The time first: the active provider's miss at or before `at`.
        if let Some(r) = self.active.clone()
            && !self.eligible(&r, at)
        {
            let next = self.select(at);
            step.switches.push(self.switch_to(next, Cause::Deadline));
        }
        let mut reread = Vec::new();
        let mut arrival = None;
        match event {
            Event::Sample(s) => match self.identify(s.key) {
                Err(o) => {
                    match o {
                        Outcome::Wild => self.discards.wild += 1,
                        Outcome::Unbound => self.discards.unbound += 1,
                        _ => self.discards.unresolved += 1,
                    }
                    step.outcome = Some(o);
                }
                Ok(addr) => {
                    // `identify` found an entry matching it, so `provider`
                    // knows it from here on.
                    if let Some(r) = self.provider(addr, at)
                        && let Some(p) = self.providers.get_mut(&r)
                    {
                        if s.delete {
                            p.counts.deleted += 1;
                            step.outcome = Some(Outcome::Deleted);
                        } else if s.expired {
                            p.counts.expired += 1;
                            step.outcome = Some(Outcome::Expired);
                        } else if s.not_incumbent {
                            p.counts.not_incumbent += 1;
                            step.outcome = Some(Outcome::NotIncumbent);
                        } else {
                            if !p.withdrawn {
                                p.tracker.observe(
                                    at,
                                    timing::Event::Arrival {
                                        member: MEMBER,
                                        expired: false,
                                    },
                                );
                                p.arrived = Some(at);
                            }
                            arrival = Some(r);
                        }
                    }
                }
            },
            Event::Declared(key) => {
                if let Some((r, i)) = self.token(key, at) {
                    self.note(&r, &i);
                    if self.moving {
                        self.kept.push(Kept::Declared(r, i));
                    } else if let Some(p) = self.providers.get_mut(&r) {
                        p.held.insert(i);
                        p.withdrawn = false;
                    }
                }
            }
            Event::Withdrawn(key) => {
                if let Some((r, i)) = self.token(key, at) {
                    self.note(&r, &i);
                    if self.moving {
                        self.kept.push(Kept::Withdrawn(r, i));
                    } else if let Some(p) = self.providers.get_mut(&r) {
                        p.held.remove(&i);
                        if p.held.is_empty() {
                            p.withdraw(self.deadline, at);
                            reread.push(r);
                        }
                    }
                }
            }
            Event::Read {
                address,
                asked,
                complete,
                held,
            } => {
                if let Some(r) = self.provider(address, at) {
                    if self.moving {
                        self.kept.push(Kept::Read(r, asked, complete, held));
                    } else if let Some(p) = self.providers.get_mut(&r) {
                        p.heard.read_into(&mut p.held, asked, complete, held);
                        if !p.held.is_empty() {
                            p.withdrawn = false;
                        }
                    }
                }
            }
            Event::Moved => self.moving = true,
            Event::Stood => {
                if self.moving {
                    self.stand(at, &mut reread);
                }
            }
            Event::Tick => {}
        }
        let next = self.select(at);
        if next != self.active {
            let cause = if arrival.is_some() && next == arrival {
                Cause::Sample
            } else {
                // Only a withdrawal makes the active provider ineligible
                // within an event (§2.10): the time is settled above, and
                // an arrival makes no provider ineligible.
                debug_assert!(
                    self.active
                        .as_ref()
                        .and_then(|r| self.providers.get(r))
                        .is_some_and(|p| p.withdrawn),
                    "a switch at {at:?} that is no arrival's, from a provider not withdrawn"
                );
                Cause::Withdrawn
            };
            step.switches.push(self.switch_to(next, cause));
        }
        if let Some(r) = arrival {
            let delivered = self.active.as_ref() == Some(&r);
            if let Some(p) = self.providers.get_mut(&r) {
                step.outcome = Some(if delivered {
                    p.counts.delivered += 1;
                    Outcome::Delivered
                } else {
                    p.counts.not_active += 1;
                    Outcome::NotActive
                });
            }
        }
        reread.sort();
        reread.dedup();
        step.reread = reread
            .iter()
            .filter_map(|r| self.providers.get(r))
            .map(|p| p.addr.clone())
            .collect();
        step
    }

    /// Whether a provider is eligible at `at` (§2.6): not withdrawn, and
    /// its key heard and not missed, a miss holding once more than the
    /// deadline has passed since its last arrival (`timing.v1` §2.5).
    fn eligible(&self, r: &Rank, at: Mono) -> bool {
        self.providers.get(r).is_some_and(|p| {
            !p.withdrawn
                && p.last()
                    .is_some_and(|l| at <= l.saturating_add(self.deadline))
        })
    }

    /// The eligible provider of highest rank at `at` (§2.9).
    fn select(&self, at: Mono) -> Option<Rank> {
        self.providers
            .keys()
            .find(|r| self.eligible(r, at))
            .cloned()
    }

    fn switch_to(&mut self, next: Option<Rank>, cause: Cause) -> Switch {
        let addr = |r: &Option<Rank>| {
            r.as_ref()
                .and_then(|r| self.providers.get(r))
                .map(|p| p.addr.clone())
        };
        let switch = Switch {
            from: addr(&self.active),
            to: addr(&next),
            cause,
            last: self
                .active
                .as_ref()
                .and_then(|r| self.providers.get(r))
                .and_then(|p| p.arrived),
        };
        self.active = next;
        switch
    }

    /// A bound address's provider, known from now on (§2.4): one first
    /// heard at `at` has its tracker started then. `None` for an address
    /// no entry matches, which is no provider.
    fn provider(&mut self, addr: Addr, at: Mono) -> Option<Rank> {
        let r = self.binding.rank(&addr)?;
        let deadline = self.deadline;
        self.providers
            .entry(r.clone())
            .or_insert_with(|| Provider::new(addr, deadline, Some(at)));
        Some(r)
    }

    /// An interface token of the required interface at a bound address:
    /// its provider and its instance. Any other key is ignored (§2.7).
    fn token(&mut self, key: &str, at: Mono) -> Option<(Rank, InstanceId)> {
        let Ok(ZkKey::Alive {
            addr,
            iface,
            instance,
            ..
        }) = parse(key)
        else {
            return None;
        };
        if iface != self.iface {
            return None;
        }
        Some((self.provider(addr, at)?, instance))
    }

    /// The watch heard `i`'s token at `r`'s address, declared or withdrawn:
    /// numbered now, kept through a move or not (observer §3.6).
    fn note(&mut self, r: &Rank, i: &InstanceId) {
        self.heard += 1;
        if let Some(p) = self.providers.get_mut(r) {
            p.heard.note(i.clone(), self.heard, &p.held);
        }
    }

    /// The round trip after the last move stands: what was kept, applied in
    /// order as one change (§2.8).
    fn stand(&mut self, at: Mono, reread: &mut Vec<Rank>) {
        self.moving = false;
        // Per provider: withdrawn before, and whether a withdrawal was kept.
        let mut touched: BTreeMap<Rank, (bool, bool)> = BTreeMap::new();
        for k in std::mem::take(&mut self.kept) {
            let r = match &k {
                Kept::Declared(r, _) | Kept::Withdrawn(r, _) | Kept::Read(r, ..) => r.clone(),
            };
            let Some(p) = self.providers.get_mut(&r) else {
                continue;
            };
            let t = touched.entry(r).or_insert((p.withdrawn, false));
            match k {
                Kept::Declared(_, i) => {
                    p.held.insert(i);
                }
                Kept::Withdrawn(_, i) => {
                    p.held.remove(&i);
                    t.1 = true;
                }
                Kept::Read(_, asked, complete, held) => {
                    p.heard.read_into(&mut p.held, asked, complete, held);
                }
            }
        }
        for (r, (before, withdrawal)) in touched {
            let Some(p) = self.providers.get_mut(&r) else {
                continue;
            };
            if p.held.is_empty() && withdrawal {
                p.withdraw(self.deadline, at);
                reread.push(r);
            } else if !p.held.is_empty() && before {
                p.withdrawn = false;
            }
        }
    }
}

// --- §2.5's outcome 6: a governed interface's incumbents ------------------------------

/// The holders of a governed required interface's token, as the watch and
/// the reads show them (§2.5, outcome 6): `redundancy`'s presence event,
/// moved there with [`Incumbents`] (#987's N1).
pub use crate::redundancy::{Asked, Holding};

impl Holding {
    /// An interface token of `iface` at an address `binding` ranks,
    /// declared (`put`) or withdrawn; `None` for any other key.
    #[must_use]
    pub fn of_token(key: &str, put: bool, iface: &IfaceId, binding: &Binding) -> Option<Self> {
        let Ok(ZkKey::Alive {
            addr,
            iface: i,
            instance,
            ..
        }) = parse(key)
        else {
            return None;
        };
        if i != *iface || binding.rank(&addr).is_none() {
            return None;
        }
        Some(if put {
            Self::Declared(addr, instance)
        } else {
            Self::Withdrawn(addr, instance)
        })
    }
}

/// The incumbent of each provider of a governed required interface (§2.5,
/// outcome 6; `redundancy.v1` §2.10, `redundancy.v2` §2.10): the lowest
/// instance holding the interface's token, as the watch and the reads show
/// it, and what its descriptors state. Session-free, so that a consumer's
/// runtime and a tool's view (#909's BC) follow it alike: moved here from
/// `zenkey::arbitration` at BC, and to [`crate::redundancy::Fence`] at
/// #987's N1, which fences by `meta.zid` or by run.
pub type Incumbents = crate::redundancy::Fence;

// --- §2.14, §5: what a tool may conclude ---------------------------------------------

/// A question of §5, answered in its states (core O5).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Answer {
    Yes,
    No,
    /// The question was put, and the reading could not answer it.
    Unobservable,
    /// Nobody put the question.
    NotAsked,
    /// The role carries no policy.
    NotThisProfiles,
}

impl Answer {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Yes => "yes",
            Self::No => "no",
            Self::Unobservable => "unobservable",
            Self::NotAsked => "not_asked",
            Self::NotThisProfiles => "not_this_profiles",
        }
    }
}

impl fmt::Display for Answer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Why an answer is what it is: the fixture's reason (§2.14).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Reason {
    NoContract,
    NotArbitrated,
    RevisionsDisagree,
    NoProviderContract,
    Invalid,
    Valid,
    Unbound,
    NotListened,
    Lost,
    Selected,
    Listening,
    DeadMan,
    Wildcard,
    Shadowed,
    Exact,
    /// The tool read no consumer's descriptor: no binding, and no view
    /// (text 0.2, F-272).
    NoDescriptor,
}

impl Reason {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NoContract => "no_contract",
            Self::NotArbitrated => "not_arbitrated",
            Self::RevisionsDisagree => "revisions_disagree",
            Self::NoProviderContract => "no_provider_contract",
            Self::Invalid => "invalid",
            Self::Valid => "valid",
            Self::Unbound => "unbound",
            Self::NotListened => "not_listened",
            Self::Lost => "lost",
            Self::Selected => "selected",
            Self::Listening => "listening",
            Self::DeadMan => "dead_man",
            Self::Wildcard => "wildcard",
            Self::Shadowed => "shadowed",
            Self::Exact => "exact",
            Self::NoDescriptor => "no_descriptor",
        }
    }
}

impl fmt::Display for Reason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// An answer and its reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Judged {
    pub answer: Answer,
    pub reason: Reason,
}

impl Judged {
    const fn new(answer: Answer, reason: Reason) -> Self {
        Self { answer, reason }
    }
}

/// What a tool holds of a role's declaration (§2.14).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Held {
    /// The declaring contract not held.
    NoContract,
    /// The revisions of the required interface held give two declarations.
    RevisionsDisagree,
    /// The one declaration they give, unread when none is held. A
    /// manifest's role, whose policy no tool sees, is
    /// [`Declaration::NotArbitrated`].
    Read(Declaration),
}

/// §2.14's declaration over every revision of the required interface a
/// tool holds: the one they all give, [`Held::RevisionsDisagree`] when two
/// differ, unread when none is held.
#[must_use]
pub fn held_over(
    role: &Role<'_>,
    revisions: &[Revision<'_>],
    params: &BTreeMap<String, String>,
) -> Held {
    let mut seen: Option<Declaration> = None;
    for rev in revisions {
        let d = declaration(role, Some(rev), params);
        match &seen {
            None => seen = Some(d),
            Some(s) if *s == d => {}
            Some(_) => return Held::RevisionsDisagree,
        }
    }
    Held::Read(seen.unwrap_or_else(|| declaration(role, None, params)))
}

/// A tool's own view of a role (§2.14): never the consumer's.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct View {
    /// How long it has listened.
    pub listened: Duration,
    /// Whether it knows it lost a sample within the last deadline.
    pub lost: bool,
    /// The provider its own [`Arbiter`] selects, `None` in the dead-man.
    pub active: Option<Addr>,
}

/// What a tool read of one consumer's role (§2.14).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reading {
    pub declaration: Held,
    /// The descriptor's binding, in order; `None` when the tool read no
    /// consumer's descriptor, a contract read offline with no consumer
    /// (text 0.2, F-272).
    pub binding: Option<Binding>,
    /// Its own view, `None` when it did not listen.
    pub view: Option<View>,
}

/// The premises every row reads first (§5): the contract held, and the
/// role carrying a policy.
fn premises(r: &Reading) -> Result<(), Judged> {
    match &r.declaration {
        Held::NoContract => Err(Judged::new(Answer::Unobservable, Reason::NoContract)),
        Held::Read(Declaration::NotArbitrated) => {
            Err(Judged::new(Answer::NotThisProfiles, Reason::NotArbitrated))
        }
        _ => Ok(()),
    }
}

/// §5's first question, "is the role's declaration valid?" (§2.14), with
/// the reasons of an invalid one. No is the finding.
#[must_use]
pub fn judge_declaration(r: &Reading) -> (Judged, Vec<Invalid>) {
    match &r.declaration {
        Held::NoContract => (
            Judged::new(Answer::Unobservable, Reason::NoContract),
            Vec::new(),
        ),
        Held::Read(Declaration::NotArbitrated) => (
            Judged::new(Answer::NotThisProfiles, Reason::NotArbitrated),
            Vec::new(),
        ),
        Held::RevisionsDisagree => (
            Judged::new(Answer::Unobservable, Reason::RevisionsDisagree),
            Vec::new(),
        ),
        Held::Read(Declaration::Unread) => (
            Judged::new(Answer::Unobservable, Reason::NoProviderContract),
            Vec::new(),
        ),
        Held::Read(Declaration::Invalid(why)) => {
            (Judged::new(Answer::No, Reason::Invalid), why.clone())
        }
        Held::Read(Declaration::Arbitrated(_)) => {
            (Judged::new(Answer::Yes, Reason::Valid), Vec::new())
        }
    }
}

/// §5's second question, "which provider does the tool's view select?"
/// (§2.14), with the provider when it selects one. Its answer is the
/// tool's own view, never the consumer's. With no consumer's descriptor
/// read, after the premises, it is not asked (text 0.2, F-272).
#[must_use]
pub fn judge_selection(r: &Reading) -> (Judged, Option<Addr>) {
    if let Err(j) = premises(r) {
        return (j, None);
    }
    let Some(binding) = &r.binding else {
        return (Judged::new(Answer::NotAsked, Reason::NoDescriptor), None);
    };
    let deadline = match &r.declaration {
        Held::Read(Declaration::Arbitrated(a)) => a.deadline,
        Held::Read(Declaration::Invalid(_)) => {
            return (Judged::new(Answer::Unobservable, Reason::Invalid), None);
        }
        // The premises, and a declaration not read: the first question's
        // answer, without its reasons.
        _ => return (judge_declaration(r).0, None),
    };
    if binding.is_empty() {
        return (Judged::new(Answer::No, Reason::Unbound), None);
    }
    let Some(view) = &r.view else {
        return (Judged::new(Answer::NotAsked, Reason::NotListened), None);
    };
    if view.lost {
        return (Judged::new(Answer::Unobservable, Reason::Lost), None);
    }
    if let Some(a) = &view.active {
        return (Judged::new(Answer::Yes, Reason::Selected), Some(a.clone()));
    }
    if view.listened < deadline {
        return (Judged::new(Answer::Unobservable, Reason::Listening), None);
    }
    (Judged::new(Answer::No, Reason::DeadMan), None)
}

/// §5's third question, "does the binding leave a priority to an order
/// nobody chose?" (§2.4, §2.14), with the wildcard and the shadowed
/// entries' positions. Yes is the finding, a warning. With no consumer's
/// descriptor read, after the premises, it is not asked (text 0.2, F-272).
#[must_use]
pub fn judge_binding(r: &Reading) -> (Judged, Vec<usize>, Vec<usize>) {
    if let Err(j) = premises(r) {
        return (j, Vec::new(), Vec::new());
    }
    let Some(binding) = &r.binding else {
        return (
            Judged::new(Answer::NotAsked, Reason::NoDescriptor),
            Vec::new(),
            Vec::new(),
        );
    };
    let wild = binding.wildcards();
    let shadowed = binding.shadowed();
    if !wild.is_empty() {
        return (Judged::new(Answer::Yes, Reason::Wildcard), wild, shadowed);
    }
    if !shadowed.is_empty() {
        return (
            Judged::new(Answer::Yes, Reason::Shadowed),
            Vec::new(),
            shadowed,
        );
    }
    (
        Judged::new(Answer::No, Reason::Exact),
        Vec::new(),
        Vec::new(),
    )
}

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

    fn arbitrated(deadline_ms: u64) -> Arbitrated {
        Arbitrated {
            policy: Policy::Priority,
            iface: "steer.v1".parse().unwrap(),
            token: KindToken::Stream,
            template: Template::parse("cmd").unwrap(),
            deadline: Duration::from_millis(deadline_ms),
            period: None,
        }
    }

    fn arbiter() -> Arbiter {
        Arbiter::new(
            &arbitrated(300),
            Binding::parse(&["lab/safety", "lab/teleop"]).unwrap(),
            BTreeMap::new(),
        )
    }

    const SAFETY: &str = "zk2/lab/safety/steer.v1/stream/cmd";

    /// Before its start an arbiter decides nothing, and it starts once.
    #[test]
    fn nothing_before_the_start_and_one_start() {
        let mut a = arbiter();
        let ms = |n| Mono::after(Duration::from_millis(n));
        assert_eq!(
            a.observe(ms(0), Event::Sample(Sample::new(SAFETY))),
            Step::default()
        );
        assert_eq!(a.start(ms(1)).switches.len(), 1);
        assert_eq!(a.start(ms(2)), Step::default());
        assert!(a.dead_man());
        let s = a.observe(ms(3), Event::Sample(Sample::new(SAFETY)));
        assert_eq!(s.outcome, Some(Outcome::Delivered));
        assert_eq!(a.due(), Some(ms(303)));
        assert_eq!(a.counts(&"lab/safety".parse().unwrap()).delivered, 1);
    }

    /// A switch carries `from`'s last arrival, kept across its withdrawal;
    /// none from the dead-man.
    #[test]
    fn a_switch_carries_its_froms_last_arrival() {
        let mut a = arbiter();
        let ms = |n| Mono::after(Duration::from_millis(n));
        assert_eq!(a.start(ms(0)).switches[0].last, None);
        let s = a.observe(ms(10), Event::Sample(Sample::new(SAFETY)));
        assert_eq!(s.switches[0].last, None, "from the dead-man");
        a.observe(ms(20), Event::Sample(Sample::new(SAFETY)));
        let s = a.observe(ms(400), Event::Tick);
        assert_eq!(s.switches[0].cause, Cause::Deadline);
        assert_eq!(s.switches[0].last, Some(ms(20)));
        a.observe(ms(410), Event::Sample(Sample::new(SAFETY)));
        let s = a.observe(
            ms(420),
            Event::Withdrawn("zk2/lab/safety/@zk/alive/steer.v1/000000000000000a/0123456789abcdef"),
        );
        assert_eq!(s.switches[0].cause, Cause::Withdrawn);
        assert_eq!(
            s.switches[0].last,
            Some(ms(410)),
            "kept across the withdrawal"
        );
    }

    /// A read never undoes a token heard since it was asked (observer §3.6,
    /// 0.38; round 128's F-629): through a move, A's withdrawal and B's
    /// declaration kept, the read asked between them comes back complete
    /// without B. When the move stands, B holds and the provider stays
    /// eligible: no switch. A read asked after B decides it.
    #[test]
    fn a_read_never_undoes_a_token_heard_since_it_was_asked() {
        let mut a = arbiter();
        let ms = |n| Mono::after(Duration::from_millis(n));
        let safety: Addr = "lab/safety".parse().unwrap();
        let alive = |i: u64| format!("zk2/lab/safety/@zk/alive/steer.v1/{i:016x}/0123456789abcdef");
        let (ka, kb) = (alive(0xa), alive(0xb));
        a.start(ms(0));
        a.observe(ms(10), Event::Declared(&ka));
        a.observe(ms(20), Event::Sample(Sample::new(SAFETY)));
        assert_eq!(a.active(), Some(&safety));
        a.observe(ms(30), Event::Moved);
        a.observe(ms(40), Event::Withdrawn(&ka));
        let asked = a.ask();
        a.observe(ms(50), Event::Declared(&kb));
        let read = |asked| Event::Read {
            address: safety.clone(),
            asked,
            complete: true,
            held: BTreeSet::new(),
        };
        a.observe(ms(60), read(asked));
        let s = a.observe(ms(70), Event::Stood);
        assert!(s.switches.is_empty(), "{:?}", s.switches);
        assert!(
            !a.withdrawn(&safety),
            "B holds: the read says nothing of it"
        );
        assert_eq!(a.active(), Some(&safety));
        // Asked after B, the read decides it: gone, though no withdrawal
        // makes it ineligible (§2.7).
        let asked = a.ask();
        a.observe(ms(80), read(asked));
        let s = a.observe(ms(90), Event::Withdrawn(&ka));
        assert!(
            a.withdrawn(&safety),
            "none held once A's stale withdrawal is heard"
        );
        assert_eq!(s.reread, [safety]);
    }

    /// An event before the last one's instant is the runtime's fault: a
    /// debug build says so.
    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "precedes the last one")]
    fn an_event_never_goes_back_in_time() {
        let mut a = arbiter();
        let ms = |n| Mono::after(Duration::from_millis(n));
        a.start(ms(10));
        a.observe(ms(5), Event::Tick);
    }

    /// An entry's text round-trips, `*` included; a malformed one is
    /// refused.
    #[test]
    fn entries_parse_and_print() {
        for e in ["lab/safety", "lab/*", "*/teleop", "*/*"] {
            assert_eq!(Entry::parse(e).unwrap().to_string(), e);
        }
        for bad in ["lab", "lab/Safety", "lab/**", "/x"] {
            assert!(Entry::parse(bad).is_err(), "{bad}");
        }
    }
}