modem-mgmt 0.2.0

The management plane of zenoh-modem as a library: serve every device on a host over Zenoh, for any driver that links the contract
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
//! The configuration plane (#125, #126): `@rpc/modem/config/{device}`, its
//! echo `state/modem/config/{device}`, and the write
//! `@rpc/modem/config/{device}/{group}/set` with the server's own guards.
//!
//! Nothing is written until it can be read back (architecture §4.6), so the
//! read landed first: the schema a device declares, what it runs with, where
//! each value came from, and what it was at start. The echo is the same
//! document on **transition** QoS — zenkey RFC 04 §3: a config echo MUST use
//! `transition` or stronger — refreshed at the state cadence and rewritten
//! the moment a change lands.
//!
//! **The guards are the server's, and the ACL is the outer layer** (zenkey
//! RFC 05 §5.1). The ACL cannot filter a wildcard query (#113) and under the
//! shipped `default_permission: "allow"` a deny stops only a caller who
//! spells a key at least as narrow as it — so a write refuses anything that
//! is not its own concrete key, keeps a startup allowlist of writable groups,
//! serialises writers per device, refuses a stale revision, answers a
//! retried request with its first reply, validates through the convention's
//! reference validator, and only then lets the device see anything.

use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use modem_contract::registry::modem::{Subject, key};
use modem_device::config::{ConfigError, ConfigValue, Effective, ParamClass, Schema, Undo};
use tokio::time::Instant;
use zenkey::config::{
    ChangeOutcome, ConfigChange, ConfigChangeEvent, ControlRequest, Edit, ParamValue, PendingChange,
};
use zenkey::origin::LocalOrigin;
use zenoh::Session;

use crate::clock::{now_ms, rfc3339, ulid};
use crate::oper::Source;
use crate::overlay::{Overlay, from_toml, schema_hash, to_toml};

/// How long a retried request returns its first answer for: long enough to
/// outlive any reply a constrained link could lose, short enough that a
/// key reused tomorrow is a new request.
const IDEMPOTENCY_WINDOW: Duration = Duration::from_secs(300);

/// How long a reach change waits between its reply and its apply (#127):
/// enough for the reply to leave over the link about to be cut.
const APPLY_AFTER: Duration = Duration::from_secs(1);

/// The registry's `rate = "burst(600/h)"` for `config_change`, as a token
/// bucket: ten in hand, one back every six seconds. A confirmed commit is
/// `applied` and then `confirmed` or `rolled-back` seconds apart, which the
/// `low` class's one a minute would forbid; a script that changes something
/// ten times a second gets ten events and then one every six seconds, the
/// newest change standing for the folded ones.
pub(crate) struct Bucket {
    tokens: f64,
    last: Instant,
}

impl Bucket {
    const CAPACITY: f64 = 10.0;
    const PER_SECOND: f64 = 600.0 / 3600.0;

    pub(crate) fn new(now: Instant) -> Self {
        Self {
            tokens: Self::CAPACITY,
            last: now,
        }
    }

    fn refill(&mut self, now: Instant) {
        let earned = now.duration_since(self.last).as_secs_f64() * Self::PER_SECOND;
        self.tokens = (self.tokens + earned).min(Self::CAPACITY);
        self.last = now;
    }

    /// Spend one, if there is one.
    pub(crate) fn take(&mut self, now: Instant) -> bool {
        self.refill(now);
        if self.tokens >= 1.0 {
            self.tokens -= 1.0;
            true
        } else {
            false
        }
    }

    /// When the next one is back.
    pub(crate) fn next_at(&self, now: Instant) -> Instant {
        let short = (1.0 - self.tokens).max(0.0);
        now + Duration::from_secs_f64(short / Self::PER_SECOND)
    }
}

/// A change armed with a confirm window (#127): what to restore, when, and
/// who asked. One per device; a second writer is `error/busy`.
pub(crate) struct Pending {
    token: String,
    group: String,
    /// What was asked, for the record `persist` keeps (#128).
    values: BTreeMap<String, ConfigValue>,
    /// What the group had; `None` until a reach change has applied.
    undo: Option<Undo>,
    /// The deadline, on the wall clock, for the document.
    deadline_ms: u64,
    who: Attribution,
    /// The deadline task; aborted by confirm, cancel and extend.
    timer: Option<tokio::task::JoinHandle<()>>,
}

/// What the plane knows about one device's configuration that the device
/// does not: what it was at start, which values the file named, which a
/// remote writer set, the revision, the pending change — the facts the
/// read-back carries beside the device's own — and the guards' state.
pub(crate) struct ConfigState {
    pub(crate) device: String,
    pub(crate) source: Source,
    pub(crate) schema: Schema,
    pub(crate) startup: Effective,
    pub(crate) file_keys: BTreeSet<String>,
    /// The groups a remote writer may change (#126): the startup file's
    /// `writable`, so an operator switches remote writes off per group
    /// without touching a router. Empty is the default, and means none.
    pub(crate) writable: BTreeSet<String>,
    pub(crate) revision: AtomicU64,
    /// `group/name` of every parameter a remote writer set: its source.
    runtime: std::sync::Mutex<BTreeSet<String>>,
    /// One pending change per device (RFC 05 §5.1, #127).
    pending: std::sync::Mutex<Option<Pending>>,
    /// The last confirmed change (#127): what `persist` may keep (#128).
    confirmed: std::sync::Mutex<Option<Confirmed>>,
    /// The overlay file for this device, when there is a state directory.
    overlay: Option<std::path::PathBuf>,
    /// `group/name` of every parameter the overlay set at boot: its source.
    overlay_keys: std::sync::Mutex<BTreeSet<String>>,
    /// One writer at a time, per device: the single-writer rule (RFC 03
    /// §1.5) for configuration, held across validate-and-apply.
    writer: tokio::sync::Mutex<()>,
    /// The first reply to every idempotency key seen inside the window.
    replies: std::sync::Mutex<BTreeMap<String, (Instant, String)>>,
    /// Changes landed and not yet published, oldest first; the echo loop
    /// drains them under the event floor.
    events: tokio::sync::Mutex<Vec<ConfigChangeEvent>>,
    /// An undo that failed, in the device's words (#127): published as a
    /// `device_fault` beside the `partial` change event. Never retried.
    faults: tokio::sync::Mutex<Vec<String>>,
    /// Wakes the echo loop the moment a change lands.
    changed: tokio::sync::Notify,
}

/// A change an operator confirmed (#127), as `persist` keeps it (#128):
/// the values, and the startup values they overrode.
#[derive(Clone, Debug)]
struct Confirmed {
    token: String,
    group: String,
    values: BTreeMap<String, ConfigValue>,
}

/// Who asked, as the caller claimed it (RFC 05 §5.1): never authentication
/// (I5) — the ACL is the authority, the event is the record.
#[derive(Clone, Debug, Default)]
pub(crate) struct Attribution {
    pub(crate) actor: Option<String>,
    pub(crate) request_id: Option<String>,
    pub(crate) claimed_source: Option<String>,
}

/// Why a write did not happen, as the wire spells it: a reserved error or
/// one of this producer's own, and one line for the operator.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Refusal {
    pub(crate) error: String,
    pub(crate) message: String,
}

impl Refusal {
    pub(crate) fn new(error: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            error: error.into(),
            message: message.into(),
        }
    }

    /// The convention's mapping (RFC 05 §5.1), plus this producer's own.
    fn of(e: &zenkey::config::ConfigError) -> Self {
        use modem_contract::registry::modem::error;
        let name = match e {
            zenkey::config::ConfigError::Contract(_) => error::RESTART_REQUIRED,
            zenkey::config::ConfigError::Device(_) => error::DEVICE_REFUSED,
            other => other.reserved_error().unwrap_or("error/invalid-args"),
        };
        Self::new(name, e.to_string())
    }

    fn of_device(e: &ConfigError) -> Self {
        use modem_contract::registry::modem::error;
        match e {
            ConfigError::UnknownGroup(_) | ConfigError::UnknownParameter { .. } => {
                Self::new("error/not-found", e.to_string())
            }
            ConfigError::Invalid { .. } => Self::new("error/invalid-args", e.to_string()),
            ConfigError::Contract(_) => Self::new(error::RESTART_REQUIRED, e.to_string()),
            ConfigError::Device(words) => Self::new(error::DEVICE_REFUSED, words.clone()),
            _ => Self::new("error/unsupported", e.to_string()),
        }
    }

    /// The JSON envelope every refusal travels as.
    pub(crate) fn envelope(&self) -> String {
        serde_json::json!({ "error": self.error, "message": self.message }).to_string()
    }
}

impl ConfigState {
    /// For a node that declares a configuration plane; `None` for one that
    /// does not, whose procedures stay gated.
    pub(crate) fn of(
        device: &str,
        source: Source,
        file_keys: BTreeSet<String>,
        writable: BTreeSet<String>,
        overlay: Option<std::path::PathBuf>,
    ) -> Option<Self> {
        let schema = source.schema()?;
        let startup = source.effective().unwrap_or_default();
        Some(Self {
            device: device.to_string(),
            source,
            schema,
            startup,
            file_keys,
            writable,
            revision: AtomicU64::new(0),
            runtime: std::sync::Mutex::new(BTreeSet::new()),
            pending: std::sync::Mutex::new(None),
            confirmed: std::sync::Mutex::new(None),
            overlay,
            overlay_keys: std::sync::Mutex::new(BTreeSet::new()),
            writer: tokio::sync::Mutex::new(()),
            replies: std::sync::Mutex::new(BTreeMap::new()),
            events: tokio::sync::Mutex::new(Vec::new()),
            faults: tokio::sync::Mutex::new(Vec::new()),
            changed: tokio::sync::Notify::new(),
        })
    }

    fn view_of(&self, effective: &Effective) -> zenkey::config::ConfigView {
        let runtime = self.runtime.lock().expect("not poisoned");
        let overlay = self.overlay_keys.lock().expect("not poisoned");
        modem_contract::config::view(
            &self.device,
            &self.schema,
            effective,
            &modem_contract::config::Provenance {
                startup: Some(&self.startup),
                file_keys: Some(&self.file_keys),
                runtime_keys: Some(&runtime),
                overlay_keys: Some(&overlay),
                revision: self.revision.load(Ordering::Relaxed),
                pending: self
                    .pending
                    .lock()
                    .expect("not poisoned")
                    .as_ref()
                    .map(|p| {
                        PendingChange::new(p.token.clone(), [p.group.clone()])
                            .until(rfc3339(p.deadline_ms))
                    }),
            },
        )
    }

    /// The read-back, now.
    pub(crate) fn view(&self) -> zenkey::config::ConfigView {
        self.view_of(&self.source.effective().unwrap_or_default())
    }

    /// The write (#126): the guards in order, then the device, then the
    /// read-back. `Ok` is the reply's JSON; `Err` is the refusal.
    pub(crate) async fn set(
        self: &Arc<Self>,
        group: &str,
        change: ConfigChange,
        who: Attribution,
    ) -> Result<String, Refusal> {
        // 2. The startup allowlist.
        if !self.writable.contains(group) {
            return Err(Refusal::new(
                "error/gated",
                format!(
                    "group {group:?} is not remotely writable on device {:?}: the startup \
                     file's `writable` names the groups that are (RFC 05 §5.1)",
                    self.device
                ),
            ));
        }
        // 3. One writer at a time, and one pending change per device.
        let _writer = self.writer.lock().await;
        self.not_busy()?;
        // 4. A retried request returns its first answer; a stale revision is
        //    refused.
        if let Some(k) = &change.idempotency_key {
            let mut replies = self.replies.lock().expect("not poisoned");
            let now = Instant::now();
            replies.retain(|_, (at, _)| now.duration_since(*at) < IDEMPOTENCY_WINDOW);
            if let Some((_, first)) = replies.get(k) {
                return Ok(first.clone());
            }
        }
        let current = self.revision.load(Ordering::Relaxed);
        if let Some(expected) = change.expected_revision
            && expected != current
        {
            return Err(Refusal::of(&zenkey::config::ConfigError::StaleRevision {
                expected,
                current,
            }));
        }
        // 5. Validation, through the convention's reference validator, so
        //    every producer refuses the same input in the same words.
        modem_contract::config::schema(&self.schema)
            .validate(group, &change)
            .map_err(|e| Refusal::of(&e))?;
        let values: BTreeMap<String, ConfigValue> = change
            .values
            .iter()
            .map(|(k, v)| (k.clone(), modem_contract::config::value_of(v)))
            .collect();
        let before = self.source.effective().unwrap_or_default();
        // 7. A dry run reports what would change and touches nothing.
        if change.dry_run {
            let mut would = before.clone();
            would
                .entry(group.to_string())
                .or_default()
                .extend(values.iter().map(|(k, v)| (k.clone(), v.clone())));
            return serde_json::to_string(&self.view_of(&would)).map_err(|e| {
                Refusal::new(
                    "error/invalid-args",
                    format!("the dry run did not serialize: {e}"),
                )
            });
        }
        // 6. Apply — now for a hot group, after the reply for a reach group
        //    (#127), because the read-back would cross the link being
        //    changed; with a confirm window, armed to roll back.
        let class = self
            .schema
            .group(group)
            .map_or(ParamClass::Hot, |g| g.class);
        if let Some(confirm_s) = change.confirm_s {
            let window = Duration::from_secs(confirm_s).max(self.confirm_floor());
            let token = ulid(&AtomicU64::new(0));
            if class == ParamClass::Reach {
                // The reply first: `{token, apply_at}`, then the change,
                // then the caller reads the echo over the new link.
                let apply_at_ms = now_ms() + APPLY_AFTER.as_millis() as u64;
                self.arm(
                    token.clone(),
                    group,
                    values.clone(),
                    None,
                    Instant::now() + APPLY_AFTER + window,
                    apply_at_ms + window.as_millis() as u64,
                    who.clone(),
                );
                let me = self.clone();
                let (g, v, t, w) = (group.to_string(), values.clone(), token.clone(), who);
                tokio::spawn(async move {
                    tokio::time::sleep(APPLY_AFTER).await;
                    me.apply_armed(&g, &v, &t, &w).await;
                });
                return Ok(serde_json::json!({
                    "token": token,
                    "apply_at": rfc3339(apply_at_ms),
                    "deadline": rfc3339(apply_at_ms + window.as_millis() as u64),
                })
                .to_string());
            }
            let undo = self
                .apply_now(group, &values, &before, Some(&token), &who)
                .await?;
            let deadline_ms = now_ms() + window.as_millis() as u64;
            self.arm(
                token,
                group,
                values.clone(),
                Some(undo),
                Instant::now() + window,
                deadline_ms,
                who,
            );
        } else {
            self.apply_now(group, &values, &before, None, &who).await?;
        }
        let after = self.source.effective().unwrap_or_default();
        let reply = serde_json::to_string(&self.view_of(&after)).map_err(|e| {
            Refusal::new(
                "error/invalid-args",
                format!("the read-back did not serialize: {e}"),
            )
        })?;
        if let Some(k) = change.idempotency_key {
            self.replies
                .lock()
                .expect("not poisoned")
                .insert(k, (Instant::now(), reply.clone()));
        }
        Ok(reply)
    }

    fn not_busy(&self) -> Result<(), Refusal> {
        if let Some(pending) = self.pending.lock().expect("not poisoned").as_ref() {
            return Err(Refusal::new(
                "error/busy",
                zenkey::config::ConfigError::Busy {
                    token: pending.token.clone(),
                }
                .to_string(),
            ));
        }
        Ok(())
    }

    fn confirm_floor(&self) -> Duration {
        match &self.source {
            Source::Sdu(plane) => plane.configuration().map(|c| c.confirm_floor()),
            Source::Device(dev) => dev.configuration().map(|c| c.confirm_floor()),
        }
        .unwrap_or(Duration::from_secs(60))
    }

    async fn device_apply(
        &self,
        group: &str,
        values: &BTreeMap<String, ConfigValue>,
    ) -> Result<Undo, ConfigError> {
        match &self.source {
            Source::Sdu(plane) => match plane.configuration() {
                Some(c) => c.apply(group, values).await,
                None => Err(ConfigError::Unsupported(group.to_string())),
            },
            Source::Device(dev) => match dev.configuration() {
                Some(c) => c.apply(group, values).await,
                None => Err(ConfigError::Unsupported(group.to_string())),
            },
        }
    }

    /// The device, then the record: revision, sources, the event.
    async fn apply_now(
        &self,
        group: &str,
        values: &BTreeMap<String, ConfigValue>,
        before: &Effective,
        token: Option<&str>,
        who: &Attribution,
    ) -> Result<Undo, Refusal> {
        let undo = self
            .device_apply(group, values)
            .await
            .map_err(|e| Refusal::of_device(&e))?;
        let revision = self.revision.fetch_add(1, Ordering::Relaxed) + 1;
        {
            let mut runtime = self.runtime.lock().expect("not poisoned");
            for name in values.keys() {
                runtime.insert(format!("{group}/{name}"));
            }
        }
        let after = self.source.effective().unwrap_or_default();
        let edits = self.edits(group, before, &after, values);
        let event = change_event(
            &self.device,
            revision,
            token,
            ChangeOutcome::Applied,
            edits,
            who,
        );
        self.events.lock().await.push(event);
        self.changed.notify_waiters();
        Ok(undo)
    }

    /// Arm the rollback: the pending change, and the task that runs it at
    /// the deadline — once, never retried, never escalated (I1).
    #[allow(clippy::too_many_arguments)]
    fn arm(
        self: &Arc<Self>,
        token: String,
        group: &str,
        values: BTreeMap<String, ConfigValue>,
        undo: Option<Undo>,
        deadline: Instant,
        deadline_ms: u64,
        who: Attribution,
    ) {
        let me = self.clone();
        let t = token.clone();
        let timer = tokio::spawn(async move {
            tokio::time::sleep_until(deadline).await;
            me.expire(&t).await;
        });
        *self.pending.lock().expect("not poisoned") = Some(Pending {
            token,
            group: group.to_string(),
            values,
            undo,
            deadline_ms,
            who,
            timer: Some(timer),
        });
        self.changed.notify_waiters();
    }

    /// A reach change, after its reply has left (#127).
    async fn apply_armed(
        self: &Arc<Self>,
        group: &str,
        values: &BTreeMap<String, ConfigValue>,
        token: &str,
        who: &Attribution,
    ) {
        let before = self.source.effective().unwrap_or_default();
        match self
            .apply_now(group, values, &before, Some(token), who)
            .await
        {
            Ok(undo) => {
                if let Some(p) = self
                    .pending
                    .lock()
                    .expect("not poisoned")
                    .as_mut()
                    .filter(|p| p.token == token)
                {
                    p.undo = Some(undo);
                }
            }
            Err(refusal) => {
                // Nobody is listening for this reply; the record is the
                // fault, and nothing was applied, so nothing is pending.
                tracing::warn!(
                    device = %self.device,
                    group,
                    error = %refusal.message,
                    "a reach change was refused after its reply"
                );
                self.faults.lock().await.push(refusal.message);
                self.take_pending(Some(token), false);
            }
        }
        self.changed.notify_waiters();
    }

    /// Take the pending change if `token` names it (or unconditionally
    /// with `None`), stopping its deadline task — unless the caller *is*
    /// that task, which must not abort itself mid-rollback.
    fn take_pending(&self, token: Option<&str>, from_timer: bool) -> Option<Pending> {
        let mut slot = self.pending.lock().expect("not poisoned");
        match (slot.as_ref(), token) {
            (Some(p), Some(t)) if p.token != t => None,
            (Some(_), _) => {
                let mut p = slot.take().expect("checked");
                if let Some(timer) = p.timer.take()
                    && !from_timer
                {
                    timer.abort();
                }
                Some(p)
            }
            (None, _) => None,
        }
    }

    fn pending_token(&self, request: &ControlRequest) -> Result<(), Refusal> {
        match self.pending.lock().expect("not poisoned").as_ref() {
            None => Err(Refusal::new(
                "error/not-found",
                format!("no change is pending on device {:?}", self.device),
            )),
            Some(p) if p.token != request.token => Err(Refusal::new(
                "error/invalid-args",
                format!(
                    "the pending change on device {:?} has token {}, not {}",
                    self.device, p.token, request.token
                ),
            )),
            Some(_) => Ok(()),
        }
    }

    /// The deadline: roll back, once.
    async fn expire(self: &Arc<Self>, token: &str) {
        let _writer = self.writer.lock().await;
        if let Some(p) = self.take_pending(Some(token), true) {
            self.rollback(p, "the confirm window expired").await;
        }
    }

    /// `confirm` (#127): the change is permanent.
    pub(crate) async fn confirm(&self, request: &ControlRequest) -> Result<String, Refusal> {
        let _writer = self.writer.lock().await;
        self.pending_token(request)?;
        let applied = self
            .pending
            .lock()
            .expect("not poisoned")
            .as_ref()
            .is_some_and(|p| p.undo.is_some());
        if !applied {
            // A reach change that has not applied yet cannot be confirmed:
            // there is nothing to keep yet.
            return Err(Refusal::new(
                "error/busy",
                "the change has not been applied yet; confirm it once the echo shows it",
            ));
        }
        let p = self
            .take_pending(Some(&request.token), false)
            .expect("checked");
        *self.confirmed.lock().expect("not poisoned") = Some(Confirmed {
            token: p.token.clone(),
            group: p.group.clone(),
            values: p.values.clone(),
        });
        let revision = self.revision.load(Ordering::Relaxed);
        let event = change_event(
            &self.device,
            revision,
            Some(&p.token),
            ChangeOutcome::Confirmed,
            Vec::new(),
            &p.who,
        );
        self.events.lock().await.push(event);
        self.changed.notify_waiters();
        self.reply()
    }

    /// `cancel` (#127): roll back now.
    pub(crate) async fn cancel(&self, request: &ControlRequest) -> Result<String, Refusal> {
        let _writer = self.writer.lock().await;
        self.pending_token(request)?;
        let p = self
            .take_pending(Some(&request.token), false)
            .expect("checked");
        self.rollback(p, "cancelled").await;
        self.reply()
    }

    /// `extend` (#127): a new window, from now.
    pub(crate) async fn extend(
        self: &Arc<Self>,
        request: &ControlRequest,
    ) -> Result<String, Refusal> {
        let _writer = self.writer.lock().await;
        self.pending_token(request)?;
        let Some(confirm_s) = request.confirm_s else {
            return Err(Refusal::new(
                "error/invalid-args",
                "extend carries `confirm_s`, the new window from now",
            ));
        };
        let window = Duration::from_secs(confirm_s).max(self.confirm_floor());
        let mut p = self
            .take_pending(Some(&request.token), false)
            .expect("checked");
        p.deadline_ms = now_ms() + window.as_millis() as u64;
        let me = self.clone();
        let t = p.token.clone();
        let deadline = Instant::now() + window;
        p.timer = Some(tokio::spawn(async move {
            tokio::time::sleep_until(deadline).await;
            me.expire(&t).await;
        }));
        *self.pending.lock().expect("not poisoned") = Some(p);
        self.changed.notify_waiters();
        self.reply()
    }

    fn reply(&self) -> Result<String, Refusal> {
        serde_json::to_string(&self.view()).map_err(|e| {
            Refusal::new(
                "error/invalid-args",
                format!("the read-back did not serialize: {e}"),
            )
        })
    }

    /// Apply the undo once. Success is `rolled-back`; failure is `partial`
    /// plus a `device_fault` in the device's words, and the read-back is
    /// the truth. Never retried, never escalated: the driver executes an
    /// operator's instruction with the operator's own deadline, once (I1).
    async fn rollback(&self, p: Pending, why: &str) {
        let Some(undo) = p.undo else {
            // A reach change that never applied: nothing to undo.
            return;
        };
        let before = self.source.effective().unwrap_or_default();
        match self.device_apply(&p.group, &undo).await {
            Ok(_) => {
                let revision = self.revision.fetch_add(1, Ordering::Relaxed) + 1;
                {
                    let mut runtime = self.runtime.lock().expect("not poisoned");
                    for name in undo.keys() {
                        runtime.remove(&format!("{}/{name}", p.group));
                    }
                }
                let after = self.source.effective().unwrap_or_default();
                let edits = self.edits(&p.group, &before, &after, &undo);
                let event = change_event(
                    &self.device,
                    revision,
                    Some(&p.token),
                    ChangeOutcome::RolledBack,
                    edits,
                    &p.who,
                );
                tracing::info!(device = %self.device, group = %p.group, why, "rolled back");
                self.events.lock().await.push(event);
            }
            Err(e) => {
                let revision = self.revision.load(Ordering::Relaxed);
                let event = change_event(
                    &self.device,
                    revision,
                    Some(&p.token),
                    ChangeOutcome::Partial,
                    Vec::new(),
                    &p.who,
                );
                tracing::warn!(
                    device = %self.device,
                    group = %p.group,
                    error = %e,
                    "the undo failed; not retried"
                );
                self.events.lock().await.push(event);
                self.faults
                    .lock()
                    .await
                    .push(format!("undo of {} ({why}) failed: {e}", p.group));
            }
        }
        self.changed.notify_waiters();
    }

    /// `persist` (#128): the last confirmed change, into the overlay. Its
    /// own key, so an ACL can allow a change and deny making it survive a
    /// reboot; never a sensitive value; and only what an operator confirmed.
    pub(crate) async fn persist(&self, request: &ControlRequest) -> Result<String, Refusal> {
        let _writer = self.writer.lock().await;
        let Some(path) = &self.overlay else {
            return Err(Refusal::new(
                "error/unsupported",
                "nothing persists on this host: set `[management] state_dir`, or run under a \
                 systemd unit with `StateDirectory=` (#128)",
            ));
        };
        let confirmed = self.confirmed.lock().expect("not poisoned").clone();
        let Some(c) = confirmed.filter(|c| c.token == request.token) else {
            return Err(Refusal::new(
                "error/not-found",
                format!(
                    "no confirmed change with token {} on device {:?}: persist keeps a change an \
                     operator confirmed (RFC 05 §5.1)",
                    request.token, self.device
                ),
            ));
        };
        if let Some(name) = c.values.keys().find(|n| {
            self.schema
                .group(&c.group)
                .and_then(|g| g.parameter(n))
                .is_some_and(|p| p.sensitive)
        }) {
            return Err(Refusal::new(
                "error/invalid-args",
                format!(
                    "{}/{name} is sensitive and is never written to the overlay: a secret belongs \
                     in the operator's credential store — the startup file, or a systemd \
                     credential",
                    c.group
                ),
            ));
        }
        let hash = schema_hash(&self.schema);
        let mut overlay = match Overlay::load(path) {
            Ok(Some(o)) if o.schema == hash => o,
            Ok(_) => Overlay::new(hash),
            Err(e) => {
                tracing::warn!(device = %self.device, path = %path.display(), error = %e, "the overlay was unreadable and is being replaced");
                Overlay::new(hash)
            }
        };
        for (name, value) in &c.values {
            let overrode = self
                .startup
                .get(&c.group)
                .and_then(|m| m.get(name))
                .map_or(toml::Value::String(String::new()), to_toml);
            overlay.upsert(&c.group, name, to_toml(value), overrode);
        }
        overlay.save(path).map_err(|e| {
            Refusal::new(
                "error/unsupported",
                format!(
                    "the overlay could not be written to {}: {e}",
                    path.display()
                ),
            )
        })?;
        {
            // Persisted, so `overlay` rather than `runtime`: what the source
            // tells an operator is whether the value survives a restart.
            let mut keys = self.overlay_keys.lock().expect("not poisoned");
            let mut runtime = self.runtime.lock().expect("not poisoned");
            for name in c.values.keys() {
                let key = format!("{}/{name}", c.group);
                runtime.remove(&key);
                keys.insert(key);
            }
        }
        tracing::info!(device = %self.device, group = %c.group, path = %path.display(), "persisted");
        self.changed.notify_waiters();
        Ok("{}".to_string())
    }

    /// Boot reconciles; it does not assume (#128). The overlay is read
    /// back under its safeguards — the schema it was written against, the
    /// startup value each entry overrode, the schema's own bounds — and
    /// what survives is applied to the device, because a device keeps its
    /// own state across a daemon restart and the file says what should be.
    /// What is dropped is dropped from the file too, and reported as a
    /// `partial` change by `boot`; never fatal. Answers how many applied.
    pub(crate) async fn boot(&self) -> usize {
        let Some(path) = &self.overlay else {
            return 0;
        };
        let overlay = match Overlay::load(path) {
            Ok(Some(o)) => o,
            Ok(None) => return 0,
            Err(e) => {
                tracing::warn!(device = %self.device, path = %path.display(), error = %e, "the overlay is unreadable and is ignored");
                return 0;
            }
        };
        let hash = schema_hash(&self.schema);
        let mut keep: Vec<crate::overlay::Entry> = Vec::new();
        let mut dropped: Vec<(crate::overlay::Entry, String)> = Vec::new();
        for e in overlay.entries {
            let key = format!("{}/{}", e.group, e.name);
            let startup = self
                .startup
                .get(&e.group)
                .and_then(|m| m.get(&e.name))
                .cloned();
            let reason = if overlay.schema != hash {
                Some("the schema changed since it was written".to_string())
            } else if from_toml(&e.overrode) != startup {
                Some(format!(
                    "the startup value moved from {} to {}",
                    e.overrode,
                    startup.map_or("nothing".to_string(), |v| v.to_string())
                ))
            } else {
                match from_toml(&e.value) {
                    None => Some(format!("{} is not a value {key} takes", e.value)),
                    Some(v) => self
                        .schema
                        .check(&e.group, &e.name, &v)
                        .err()
                        .map(|err| err.to_string()),
                }
            };
            match reason {
                Some(r) => dropped.push((e, r)),
                None => keep.push(e),
            }
        }
        let mut applied = 0;
        let mut by_group: BTreeMap<String, BTreeMap<String, ConfigValue>> = BTreeMap::new();
        for e in &keep {
            if let Some(v) = from_toml(&e.value) {
                by_group
                    .entry(e.group.clone())
                    .or_default()
                    .insert(e.name.clone(), v);
            }
        }
        let mut refused: Vec<(crate::overlay::Entry, String)> = Vec::new();
        for (group, values) in by_group {
            match self.device_apply(&group, &values).await {
                Ok(_) => {
                    let mut keys = self.overlay_keys.lock().expect("not poisoned");
                    for name in values.keys() {
                        keys.insert(format!("{group}/{name}"));
                    }
                    applied += values.len();
                }
                Err(e) => {
                    let why = format!("the device refused it at boot: {e}");
                    keep.retain(|k| {
                        if k.group == group {
                            refused.push((k.clone(), why.clone()));
                            false
                        } else {
                            true
                        }
                    });
                }
            }
        }
        dropped.extend(refused);
        if !dropped.is_empty() {
            let pruned = Overlay {
                schema: hash,
                entries: keep,
            };
            if let Err(e) = pruned.save(path) {
                tracing::warn!(device = %self.device, error = %e, "the pruned overlay could not be written");
            }
            let edits: Vec<Edit> = dropped
                .iter()
                .map(|(e, why)| {
                    tracing::warn!(device = %self.device, parameter = %format!("{}/{}", e.group, e.name), why, "an overlay entry was dropped");
                    Edit::of(
                        format!("{}/{}", e.group, e.name),
                        e.value.clone().try_into::<ParamValue>().ok(),
                        self.startup
                            .get(&e.group)
                            .and_then(|m| m.get(&e.name))
                            .map(modem_contract::config::value),
                    )
                })
                .collect();
            let who = Attribution {
                actor: Some("boot".into()),
                ..Attribution::default()
            };
            let event = change_event(&self.device, 0, None, ChangeOutcome::Partial, edits, &who);
            self.events.lock().await.push(event);
        }
        if applied > 0 {
            tracing::info!(device = %self.device, applied, path = %path.display(), "the overlay applied at boot");
        }
        applied
    }

    /// The provisional boot (#128): if the device is not `up` by the
    /// operator's deadline under the overlay, the startup values come back,
    /// the overlay is set aside (`<device>.overlay.toml.provisional`, for
    /// the operator to read), and an event says so. Once (I1).
    pub(crate) fn provisional(self: &Arc<Self>, after: Duration) -> tokio::task::JoinHandle<()> {
        let me = self.clone();
        tokio::spawn(async move {
            tokio::time::sleep(after).await;
            if me.source.oper().is_up() {
                return;
            }
            let _writer = me.writer.lock().await;
            let keys: Vec<String> = me
                .overlay_keys
                .lock()
                .expect("not poisoned")
                .iter()
                .cloned()
                .collect();
            let mut by_group: BTreeMap<String, BTreeMap<String, ConfigValue>> = BTreeMap::new();
            for key in &keys {
                if let Some((group, name)) = key.split_once('/')
                    && let Some(v) = me.startup.get(group).and_then(|m| m.get(name))
                {
                    by_group
                        .entry(group.to_string())
                        .or_default()
                        .insert(name.to_string(), v.clone());
                }
            }
            let before = me.source.effective().unwrap_or_default();
            let mut edits = Vec::new();
            for (group, values) in &by_group {
                match me.device_apply(group, values).await {
                    Ok(_) => {
                        let after = me.source.effective().unwrap_or_default();
                        edits.extend(me.edits(group, &before, &after, values));
                    }
                    Err(e) => {
                        tracing::warn!(device = %me.device, group, error = %e, "the provisional rollback was refused; not retried");
                        me.faults
                            .lock()
                            .await
                            .push(format!("provisional boot: undo of {group} failed: {e}"));
                    }
                }
            }
            me.overlay_keys.lock().expect("not poisoned").clear();
            if let Some(path) = &me.overlay {
                let aside = path.with_extension("toml.provisional");
                if let Err(e) = std::fs::rename(path, &aside) {
                    tracing::warn!(device = %me.device, error = %e, "the overlay could not be set aside");
                } else {
                    tracing::warn!(device = %me.device, aside = %aside.display(), after_s = after.as_secs(), "not up under the overlay by the deadline: the startup file alone applies, and the overlay is set aside");
                }
            }
            let who = Attribution {
                actor: Some("boot".into()),
                ..Attribution::default()
            };
            let revision = me.revision.load(Ordering::Relaxed);
            let event = change_event(
                &me.device,
                revision,
                None,
                ChangeOutcome::RolledBack,
                edits,
                &who,
            );
            me.events.lock().await.push(event);
            me.changed.notify_waiters();
        })
    }

    /// What changed, as RFC 6470 spells it — with a sensitive parameter's
    /// values redacted, whatever they were.
    fn edits(
        &self,
        group: &str,
        before: &Effective,
        after: &Effective,
        asked: &BTreeMap<String, ConfigValue>,
    ) -> Vec<Edit> {
        let sensitive = |name: &str| {
            self.schema
                .group(group)
                .and_then(|g| g.parameter(name))
                .is_some_and(|p| p.sensitive)
        };
        asked
            .keys()
            .map(|name| {
                let parameter = format!("{group}/{name}");
                if sensitive(name) {
                    return Edit::redacted(parameter);
                }
                let value = |e: &Effective| {
                    e.get(group)
                        .and_then(|m| m.get(name))
                        .map(modem_contract::config::value)
                };
                Edit::of(parameter, value(before), value(after))
            })
            .collect()
    }
}

/// The change event, in the convention's shape (zenkey RFC 05 §5.1; RFC
/// 6470's `netconf-config-change`): the resource, the new revision, the
/// token if any, the outcome, the edits, and the attribution as the caller
/// claimed it — none of which authenticates (I5).
fn change_event(
    device: &str,
    revision: u64,
    token: Option<&str>,
    outcome: ChangeOutcome,
    edits: Vec<Edit>,
    who: &Attribution,
) -> ConfigChangeEvent {
    let mut event = ConfigChangeEvent::new(device, revision, outcome, edits);
    if let Some(t) = token {
        event = event.token(t);
    }
    if let Some(a) = &who.actor {
        event = event.actor(a);
    }
    if let Some(r) = &who.request_id {
        event = event.request_id(r);
    }
    if let Some(c) = &who.claimed_source {
        event = event.claimed_source(c);
    }
    event
}

/// The echo: the read-back on `state/modem/config/{device}`, refreshed at
/// the state cadence and rewritten the moment a change lands; and the
/// change events, damped under the same floor as every other event here.
pub(super) async fn publish_loop(
    session: Session,
    origin: LocalOrigin,
    state: Arc<ConfigState>,
    ttl_s: u64,
) {
    let subject = Subject::config(&state.device);
    let doc_key = key(&origin, &subject);
    let qos = subject.qos();
    let refresh = Duration::from_secs((ttl_s / 2).max(1));
    let counter = AtomicU64::new(0);
    let mut bucket = Bucket::new(Instant::now());
    // The newest change the bucket could not afford, held until it can:
    // folded, never dropped.
    let mut folded: Option<ConfigChangeEvent> = None;
    // Boot's own reports (#128) are queued before anyone can have
    // subscribed — the plane was not listening yet — so the first pass
    // publishes the document alone and leaves them for the next, one
    // refresh later, when a reader that was waiting for the plane is back.
    let mut first = true;
    loop {
        crate::state::put(&session, &doc_key, &state.view(), qos).await;
        let queued = if first {
            first = false;
            Vec::new()
        } else {
            std::mem::take(&mut *state.events.lock().await)
        };
        let now = Instant::now();
        for event in folded.take().into_iter().chain(queued) {
            if bucket.take(now) {
                publish_event(&session, &origin, &state.device, &counter, &event).await;
            } else {
                folded = Some(event);
            }
        }
        // An undo that failed is a fault, in the device's words (#127).
        for words in std::mem::take(&mut *state.faults.lock().await) {
            let event_id = ulid(&counter);
            let subject = Subject::device_device_fault(&state.device, &event_id);
            let doc = super::DeviceFault::of(
                &state.device,
                event_id,
                now_ms(),
                &modem_device::DeviceEvent::raised(words),
                1,
            );
            crate::events::publish(&session, &origin, &subject, &doc, "device_fault").await;
        }
        let wake = if folded.is_some() {
            bucket.next_at(now).min(now + refresh)
        } else {
            now + refresh
        };
        tokio::select! {
            () = state.changed.notified() => {}
            () = tokio::time::sleep_until(wake) => {}
        }
    }
}

async fn publish_event(
    session: &Session,
    origin: &LocalOrigin,
    device: &str,
    counter: &AtomicU64,
    event: &ConfigChangeEvent,
) {
    let event_id = ulid(counter);
    let subject = Subject::device_config_change(device, &event_id);
    crate::events::publish(session, origin, &subject, event, "config_change").await;
}

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

    #[test]
    fn the_event_is_the_conventions() {
        // Built with the convention's own constructors since zenkey 0.10.1
        // (zenkey#487, filed from here). Before that the type could not be
        // constructed outside its crate, and this module hand-built the JSON.
        // That JSON is what subscribers have been receiving, so it is the
        // expectation: the constructors must not move a field.
        let edits = vec![
            Edit::of(
                "poll/signal_poll_s",
                Some(ParamValue::Integer(60)),
                Some(ParamValue::Integer(30)),
            ),
            Edit::redacted("auth/pin"),
        ];
        let who = Attribution {
            actor: Some("marc".into()),
            request_id: Some("r-1".into()),
            claimed_source: None,
        };
        let event = change_event("sat0", 1, None, ChangeOutcome::Applied, edits, &who);
        assert_eq!(
            serde_json::to_value(&event).expect("serializes"),
            serde_json::json!({
                "resource": "sat0",
                "revision": 1,
                "outcome": "applied",
                "edits": [
                    { "parameter": "poll/signal_poll_s", "old": 60, "new": 30 },
                    { "parameter": "auth/pin", "redacted": true },
                ],
                "actor": "marc",
                "request_id": "r-1",
            }),
            "the change event's wire shape moved"
        );
        let rolled = change_event(
            "sat0",
            2,
            Some("t-1"),
            ChangeOutcome::RolledBack,
            Vec::new(),
            &Attribution::default(),
        );
        assert_eq!(
            serde_json::to_value(&rolled).expect("serializes"),
            serde_json::json!({
                "resource": "sat0", "revision": 2, "token": "t-1",
                "outcome": "rolled-back", "edits": [],
            })
        );
    }
}