subc-daemon 0.48.3

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
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
use std::{
    collections::{BTreeMap, HashMap, HashSet},
    error::Error,
    fmt,
    sync::{Mutex, MutexGuard},
};

use subc_protocol::manifest::{CapabilityDeclarations, ModuleManifest, ProviderRole};
use tokio::sync::watch;
use tracing::info;

/// Per-connection identity assigned by [`crate::Router`] while serving a socket.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ConnectionId(u64);

impl ConnectionId {
    /// Synthetic connection id used by unit tests. Router-issued connection ids
    /// start at 1, so this 0 value never collides with a real socket owner.
    #[cfg(test)]
    pub const LOCAL: Self = Self(0);

    pub const fn new(raw: u64) -> Self {
        Self(raw)
    }

    pub fn get(self) -> u64 {
        self.0
    }
}

/// Lifecycle state for a module's channel allocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChannelState {
    Active,
    Closed,
}

/// Why a module registration stopped belonging to its connection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RegistrationEndReason {
    ConnectionClosed,
    ExplicitGoodbye,
    Replaced,
    SupervisorStop,
    SupervisorRestart,
    RegistrationFailed,
}

impl RegistrationEndReason {
    fn as_str(self) -> &'static str {
        match self {
            Self::ConnectionClosed => "connection_closed",
            Self::ExplicitGoodbye => "explicit_goodbye",
            Self::Replaced => "replaced",
            Self::SupervisorStop => "supervisor_stop",
            Self::SupervisorRestart => "supervisor_restart",
            Self::RegistrationFailed => "registration_failed",
        }
    }
}

/// Registry record for one active module registration.
#[derive(Debug, Clone, PartialEq)]
pub struct ModuleRegistration {
    pub manifest: ModuleManifest,
    pub ready: bool,
    pub negotiated_ver: u8,
    pub state: ChannelState,
    pub connection_id: ConnectionId,
    pub control_ops: Vec<String>,
}

/// Active routing registrations and their publication state from one lock.
pub(crate) struct RouteAdmissionSnapshot {
    pub(crate) modules: Vec<ModuleRegistration>,
    pub(crate) unpublished: HashSet<ConnectionId>,
}

impl std::ops::Deref for RouteAdmissionSnapshot {
    type Target = [ModuleRegistration];

    fn deref(&self) -> &Self::Target {
        &self.modules
    }
}

/// Which registration a lookup or a lifecycle wait is about.
///
/// A module id alone stops naming one process once a blue/green swap runs two
/// processes under the same id: the incumbent in the active slot, the
/// replacement in the candidate slot, and, after cutover, the old incumbent
/// demoted until its connection goes away. A wait keyed on the bare id would
/// confuse them (a successful swap never empties the id's active slot, and a
/// candidate's "has it registered yet" would be answered by the incumbent).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RegistrationSlot<'a> {
    /// The routable registration for this module id. This is what every plain
    /// start, stop and restart path means by "the module is registered".
    Active(&'a str),
    /// A swap candidate registered under this module id and not yet promoted.
    Candidate(&'a str),
    /// Whatever registration this module connection holds, in any slot.
    Connection(ConnectionId),
}

/// The result of promoting a module's candidate registration to active.
#[derive(Debug, Clone, PartialEq)]
pub struct RegistryCutover {
    /// The registration that is now active (the former candidate).
    pub promoted: ModuleRegistration,
    /// The former active registration, now demoted. `None` when the incumbent
    /// had already gone away before the promotion.
    pub superseded: Option<ModuleRegistration>,
}

/// Control-plane registry for module manifests and supervision ownership.
///
/// Duplicate active `module_id`s are rejected rather than replaced. Rejection is
/// the safer v1 behavior because replacing a still-connected module could hijack
/// in-flight routes. Stale registrations are removed by connection cleanup; a
/// reconnect after the old connection drops can then register the same id again.
///
/// A blue/green swap is the one sanctioned way two processes hold the same id.
/// The replacement registers into a separate candidate slot, which every by-id
/// lookup ignores, so it stays unroutable until [`Registry::promote_candidate`]
/// swaps it in. The old incumbent is then kept as "superseded" until its
/// connection deregisters. Lookups keyed by connection id search all three
/// slots, because a connection must be able to update and remove its own
/// registration whichever slot it currently sits in.
#[derive(Debug, Default)]
pub struct Registry {
    inner: Mutex<RegistryInner>,
    #[cfg(test)]
    next_lock_attempt: Mutex<Option<std::sync::mpsc::Sender<bool>>>,
}

#[derive(Debug, Default)]
struct RegistryInner {
    /// Only subscribed module ids have a sender. Changes coalesce, and writers
    /// never wait for a supervisor to receive them.
    // The value counts accepted active registrations. Keep that evidence even
    // when register and disconnect coalesce before a supervisor receives them.
    module_changes: HashMap<String, watch::Sender<u64>>,
    modules: HashMap<String, ModuleRegistration>,
    /// Swap candidates by module id: registered, never routable, never listed.
    candidates: HashMap<String, ModuleRegistration>,
    /// Former incumbents demoted by a promotion, kept only so their own
    /// connection can still find and remove them. Never routable, never listed.
    superseded: Vec<ModuleRegistration>,
    /// Connections whose HELLO passed the launch-nonce check required for a
    /// reserved module or swap candidate. Kept outside ModuleRegistration so
    /// adding this catalog fact does not break callers that construct the public
    /// registration struct.
    nonce_verified: HashSet<ConnectionId>,
    /// The active connection that displaced each superseded registration.
    superseded_by: HashMap<ConnectionId, ConnectionId>,
    /// Connections whose registration is reserved but not yet published.
    ///
    /// A HELLO registers in the registry before the daemon installs the
    /// module's forwarding endpoint, and until that endpoint exists a
    /// `route.open` to the module cannot be relayed. A registration in this set
    /// already holds its module id (a duplicate HELLO is refused) and is found
    /// by every lookup except two: [`Registry::list_modules`], which feeds
    /// `catalog.list`, and [`Registry::published_registration`], which the swap
    /// supervisor reads to decide that a candidate has registered. Adding a
    /// registration to this set does not bump the catalog generation;
    /// [`Registry::publish_registration`] removes it and bumps the generation
    /// in the same critical section, so a catalog reader sees the module and
    /// the new generation together.
    unpublished: HashSet<ConnectionId>,
    generation: u64,
    catalog_changes: Option<watch::Sender<u64>>,
}

impl Registry {
    /// Capture the current catalog generation and subscribe atomically. Writers
    /// replace one value; they never wait for discovery clients to receive it.
    pub(crate) fn subscribe_catalog_changes(&self) -> Result<watch::Receiver<u64>, RegistryError> {
        let mut inner = self.lock_inner()?;
        let generation = inner.generation;
        Ok(inner
            .catalog_changes
            .get_or_insert_with(|| watch::channel(generation).0)
            .subscribe())
    }

    /// Notify discovery after an approved declaration-set change or a change to
    /// the spawn's first-party mark (whether it may receive automatic grants).
    /// The authority owner calls this only after publishing the new state; it
    /// must not hold a spawn or forwarding lock while taking the registry lock.
    pub fn catalog_authority_changed(&self) -> Result<(), RegistryError> {
        self.lock_inner()?.bump_generation();
        Ok(())
    }

    /// Subscribe before reading a registration so a change between the read
    /// and the supervisor's wait remains pending on this receiver.
    pub(crate) fn subscribe_module_changes(
        &self,
        module_id: &str,
    ) -> Result<watch::Receiver<u64>, RegistryError> {
        let mut inner = self.lock_inner()?;
        // Retired supervisors must not leave an ever-growing set of ids.
        inner
            .module_changes
            .retain(|_, sender| sender.receiver_count() > 0);
        Ok(inner
            .module_changes
            .entry(module_id.to_string())
            .or_insert_with(|| watch::channel(0).0)
            .subscribe())
    }

    /// Register a module manifest with the module's effective granted control op set.
    ///
    /// The registration is published at once: it is listed by
    /// [`Self::list_modules`] and bumps the catalog generation. The HELLO path
    /// uses [`Self::register_unpublished_with_control_ops`] instead, because it
    /// still has to install the module's forwarding endpoint.
    pub fn register_with_control_ops(
        &self,
        manifest: ModuleManifest,
        negotiated_ver: u8,
        connection_id: ConnectionId,
        control_ops: Vec<String>,
    ) -> Result<ModuleRegistration, RegistryError> {
        self.register_active(
            manifest,
            negotiated_ver,
            connection_id,
            control_ops,
            true,
            false,
        )
    }

    /// Register a module manifest without listing it yet.
    ///
    /// The registration holds its module id and is visible to every lookup
    /// except [`Self::list_modules`] (and so `catalog.list`) and
    /// [`Self::published_registration`]. The catalog generation does not move.
    /// Call [`Self::publish_registration`] once the module can actually be
    /// routed to; if that never becomes possible, deregistering the connection
    /// removes the entry without the catalog ever having listed it.
    pub fn register_unpublished_with_control_ops(
        &self,
        manifest: ModuleManifest,
        negotiated_ver: u8,
        connection_id: ConnectionId,
        control_ops: Vec<String>,
    ) -> Result<ModuleRegistration, RegistryError> {
        self.register_active(
            manifest,
            negotiated_ver,
            connection_id,
            control_ops,
            false,
            false,
        )
    }

    /// Register a module after its HELLO is accepted, without listing it before forwarding is installed.
    pub(crate) fn register_unpublished_verified_with_control_ops(
        &self,
        manifest: ModuleManifest,
        negotiated_ver: u8,
        connection_id: ConnectionId,
        control_ops: Vec<String>,
        nonce_verified: bool,
    ) -> Result<ModuleRegistration, RegistryError> {
        self.register_active(
            manifest,
            negotiated_ver,
            connection_id,
            control_ops,
            false,
            nonce_verified,
        )
    }

    fn register_active(
        &self,
        manifest: ModuleManifest,
        negotiated_ver: u8,
        connection_id: ConnectionId,
        control_ops: Vec<String>,
        publish: bool,
        nonce_verified: bool,
    ) -> Result<ModuleRegistration, RegistryError> {
        let module_id = manifest.module_id.clone();
        if let Err(reason) = module_id_path_hazard(&module_id) {
            return Err(RegistryError::PathHazardModuleId { module_id, reason });
        }
        let mut inner = self.lock_inner()?;
        if inner.modules.contains_key(&module_id) {
            return Err(RegistryError::DuplicateModuleId { module_id });
        }

        let ready = manifest.ready.unwrap_or(true);
        let registration = ModuleRegistration {
            manifest,
            ready,
            negotiated_ver,
            state: ChannelState::Active,
            connection_id,
            control_ops,
        };

        inner.modules.insert(module_id, registration.clone());
        if nonce_verified {
            inner.nonce_verified.insert(connection_id);
        } else {
            inner.nonce_verified.remove(&connection_id);
        }
        if publish {
            inner.bump_generation();
        } else {
            inner.unpublished.insert(connection_id);
        }
        if let Some(sender) = inner.module_changes.get(&registration.manifest.module_id) {
            sender.send_modify(|accepted| *accepted = accepted.wrapping_add(1));
        }
        Ok(registration)
    }

    /// Register a swap candidate for `manifest.module_id` into the candidate slot.
    ///
    /// The candidate is invisible to [`Self::get_module`], [`Self::list_modules`]
    /// and every other by-id lookup until [`Self::promote_candidate`]. An active
    /// registration for the id is not required, because the incumbent may die
    /// while the swap is open; deciding whether a candidate may register at all
    /// belongs to the caller that admits it. A second candidate for the same id
    /// is refused.
    ///
    /// The candidate is published at once, meaning candidate-slot lookups
    /// through [`Self::published_registration`] return it immediately. The
    /// HELLO path uses
    /// [`Self::register_unpublished_candidate_with_control_ops`] instead.
    pub fn register_candidate_with_control_ops(
        &self,
        manifest: ModuleManifest,
        negotiated_ver: u8,
        connection_id: ConnectionId,
        control_ops: Vec<String>,
    ) -> Result<ModuleRegistration, RegistryError> {
        self.register_candidate(
            manifest,
            negotiated_ver,
            connection_id,
            control_ops,
            true,
            false,
        )
    }

    /// Register a swap candidate that [`Self::published_registration`] does not
    /// return until [`Self::publish_registration`] is called for its
    /// connection. The swap supervisor reads that lookup to decide the
    /// candidate has registered, and it promotes a ready candidate straight
    /// away; promoting one whose forwarding endpoint is not installed yet would
    /// fail the cutover.
    pub fn register_unpublished_candidate_with_control_ops(
        &self,
        manifest: ModuleManifest,
        negotiated_ver: u8,
        connection_id: ConnectionId,
        control_ops: Vec<String>,
    ) -> Result<ModuleRegistration, RegistryError> {
        self.register_candidate(
            manifest,
            negotiated_ver,
            connection_id,
            control_ops,
            false,
            false,
        )
    }

    /// Register a blue/green swap candidate after its required launch nonce has been verified.
    pub(crate) fn register_unpublished_verified_candidate_with_control_ops(
        &self,
        manifest: ModuleManifest,
        negotiated_ver: u8,
        connection_id: ConnectionId,
        control_ops: Vec<String>,
    ) -> Result<ModuleRegistration, RegistryError> {
        self.register_candidate(
            manifest,
            negotiated_ver,
            connection_id,
            control_ops,
            false,
            true,
        )
    }

    fn register_candidate(
        &self,
        manifest: ModuleManifest,
        negotiated_ver: u8,
        connection_id: ConnectionId,
        control_ops: Vec<String>,
        publish: bool,
        nonce_verified: bool,
    ) -> Result<ModuleRegistration, RegistryError> {
        let module_id = manifest.module_id.clone();
        if let Err(reason) = module_id_path_hazard(&module_id) {
            return Err(RegistryError::PathHazardModuleId { module_id, reason });
        }
        let mut inner = self.lock_inner()?;
        if inner.candidates.contains_key(&module_id) {
            return Err(RegistryError::DuplicateModuleId { module_id });
        }
        let ready = manifest.ready.unwrap_or(true);
        let registration = ModuleRegistration {
            manifest,
            ready,
            negotiated_ver,
            state: ChannelState::Active,
            connection_id,
            control_ops,
        };
        inner.candidates.insert(module_id, registration.clone());
        if nonce_verified {
            inner.nonce_verified.insert(connection_id);
        } else {
            inner.nonce_verified.remove(&connection_id);
        }
        if !publish {
            inner.unpublished.insert(connection_id);
        }
        inner.notify_module_changed(&registration.manifest.module_id);
        Ok(registration)
    }

    /// Publish the registration `connection_id` holds, in whichever slot.
    ///
    /// For an active registration this is the moment `catalog.list` starts
    /// listing the module, and the catalog generation advances under the same
    /// lock, so no reader can see the new generation without the module or the
    /// module without the new generation. A candidate is not listed either way;
    /// publishing it only makes it visible to
    /// [`Self::published_registration`].
    ///
    /// Returns `false` when there is nothing to publish: the connection holds
    /// no registration any more, or it was already published.
    pub fn publish_registration(&self, connection_id: ConnectionId) -> Result<bool, RegistryError> {
        let mut inner = self.lock_inner()?;
        Ok(inner.publish_registration(connection_id))
    }

    /// Install forwarding and publish without letting a registry reader observe
    /// the interval after HELLO_ACK is queued but before publication. The install
    /// callback may take forwarding's lock, but must not re-enter the registry:
    /// the lock order is Registry -> ForwardingTable::inner.
    ///
    /// An install error leaves the registration unpublished. The caller must
    /// roll it back after this method releases the registry lock. The outer
    /// result reports registry locking errors; the inner result reports install
    /// errors or whether the registration was published.
    pub(crate) fn publish_registration_after<E>(
        &self,
        connection_id: ConnectionId,
        install: impl FnOnce() -> Result<(), E>,
    ) -> Result<Result<bool, E>, RegistryError> {
        let mut inner = self.lock_inner()?;
        if let Err(err) = install() {
            return Ok(Err(err));
        }
        Ok(Ok(inner.publish_registration(connection_id)))
    }

    #[cfg(test)]
    pub(crate) fn observe_next_lock_attempt(&self) -> std::sync::mpsc::Receiver<bool> {
        let (sender, receiver) = std::sync::mpsc::channel();
        *self.next_lock_attempt.lock().unwrap() = Some(sender);
        receiver
    }

    /// Move the candidate for `module_id` into the active slot and demote the
    /// previous active registration, in one registry critical section.
    ///
    /// Returns `Ok(None)` when there is no candidate to promote. Bumps the
    /// catalog generation, because the listed registration for the id changed.
    pub fn promote_candidate(
        &self,
        module_id: &str,
    ) -> Result<Option<RegistryCutover>, RegistryError> {
        let mut inner = self.lock_inner()?;
        let Some(promoted) = inner.candidates.remove(module_id) else {
            return Ok(None);
        };
        let superseded = inner
            .modules
            .insert(module_id.to_string(), promoted.clone());
        if let Some(superseded) = superseded.clone() {
            let replaced_connection_id = superseded.connection_id.get();
            inner
                .superseded_by
                .insert(superseded.connection_id, promoted.connection_id);
            inner.superseded.push(superseded);
            info!(
                target: "subc.registry",
                module_id = %module_id,
                connection_id = promoted.connection_id.get(),
                replaced = true,
                replaced_connection_id,
                "module registration promoted"
            );
        }
        inner.bump_generation();
        inner.notify_module_changed(module_id);
        Ok(Some(RegistryCutover {
            promoted,
            superseded,
        }))
    }

    /// The ACTIVE registration for `module_id`. Candidates and superseded
    /// incumbents are never returned: this is the lookup routing decisions use.
    pub fn get_module(&self, module_id: &str) -> Result<Option<ModuleRegistration>, RegistryError> {
        Ok(self.lock_inner()?.modules.get(module_id).cloned())
    }

    /// Unlike the published-only catalog view, admission sees staged active
    /// registrations too, exactly as `get_module` does. A target whose
    /// registration is accepted but not yet published in the catalog must
    /// answer `target_unavailable`, not `unknown_module`, on an ordinary open.
    pub(crate) fn route_admission_snapshot(&self) -> Result<RouteAdmissionSnapshot, RegistryError> {
        let inner = self.lock_inner()?;
        let mut modules = inner.modules.values().cloned().collect::<Vec<_>>();
        modules.sort_by(|a, b| a.manifest.module_id.cmp(&b.manifest.module_id));
        Ok(RouteAdmissionSnapshot {
            modules,
            unpublished: inner.unpublished.clone(),
        })
    }

    /// The swap candidate registered for `module_id`, if any.
    pub fn get_candidate(
        &self,
        module_id: &str,
    ) -> Result<Option<ModuleRegistration>, RegistryError> {
        Ok(self.lock_inner()?.candidates.get(module_id).cloned())
    }

    /// The registration held in one specific slot. See [`RegistrationSlot`].
    pub fn registration(
        &self,
        slot: RegistrationSlot<'_>,
    ) -> Result<Option<ModuleRegistration>, RegistryError> {
        let inner = self.lock_inner()?;
        Ok(match slot {
            RegistrationSlot::Active(module_id) => inner.modules.get(module_id).cloned(),
            RegistrationSlot::Candidate(module_id) => inner.candidates.get(module_id).cloned(),
            RegistrationSlot::Connection(connection_id) => inner
                .find_by_connection(connection_id)
                .map(|(_, registration)| registration.clone()),
        })
    }

    pub fn active_registration_count(&self) -> Result<usize, RegistryError> {
        Ok(self.lock_inner()?.modules.len())
    }

    /// The catalog generation and the active registrations `catalog.list`
    /// shows. Unpublished registrations (see
    /// [`Self::register_unpublished_with_control_ops`]) are left out.
    pub fn list_modules(&self) -> Result<(u64, Vec<ModuleRegistration>), RegistryError> {
        let inner = self.lock_inner()?;
        let mut modules = inner
            .modules
            .values()
            .filter(|registration| !inner.unpublished.contains(&registration.connection_id))
            .cloned()
            .collect::<Vec<_>>();
        modules.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
        Ok((inner.generation, modules))
    }

    /// List published active registrations together with their HELLO nonce-verification status.
    /// Both values are captured under the registry lock so a concurrent swap or
    /// disconnect cannot separate a registration from its verification fact.
    pub fn list_modules_with_nonce_verification(
        &self,
    ) -> Result<(u64, Vec<(ModuleRegistration, bool)>), RegistryError> {
        let inner = self.lock_inner()?;
        let mut registrations = inner
            .modules
            .values()
            .filter(|registration| !inner.unpublished.contains(&registration.connection_id))
            .collect::<Vec<_>>();
        registrations.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
        let modules = registrations
            .into_iter()
            .map(|registration| {
                (
                    registration.clone(),
                    inner.nonce_verified.contains(&registration.connection_id),
                )
            })
            .collect();
        Ok((inner.generation, modules))
    }

    /// Every active registration, including unpublished ones.
    ///
    /// For the capability evaluator and the capability deny census, which
    /// count a module as soon as it has registered. Whether `catalog.list`
    /// shows the module yet does not change their verdicts.
    pub fn list_registered_modules(&self) -> Result<Vec<ModuleRegistration>, RegistryError> {
        let inner = self.lock_inner()?;
        let mut modules = inner.modules.values().cloned().collect::<Vec<_>>();
        modules.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
        Ok(modules)
    }

    /// Like [`Self::registration`], but a registration that is not published
    /// yet is reported as absent.
    pub fn published_registration(
        &self,
        slot: RegistrationSlot<'_>,
    ) -> Result<Option<ModuleRegistration>, RegistryError> {
        let inner = self.lock_inner()?;
        let registration = match slot {
            RegistrationSlot::Active(module_id) => inner.modules.get(module_id),
            RegistrationSlot::Candidate(module_id) => inner.candidates.get(module_id),
            RegistrationSlot::Connection(connection_id) => inner
                .find_by_connection(connection_id)
                .map(|(_, registration)| registration),
        };
        Ok(registration
            .filter(|registration| !inner.unpublished.contains(&registration.connection_id))
            .cloned())
    }

    pub fn generation(&self) -> Result<u64, RegistryError> {
        Ok(self.lock_inner()?.generation)
    }

    #[cfg(test)]
    pub(crate) fn set_module_state_for_test(
        &self,
        module_id: &str,
        state: ChannelState,
    ) -> Result<bool, RegistryError> {
        let mut inner = self.lock_inner()?;
        let Some(registration) = inner.modules.get_mut(module_id) else {
            return Ok(false);
        };
        registration.state = state;
        inner.notify_module_changed(module_id);
        Ok(true)
    }

    /// The registration owned by `connection_id`, searching the active,
    /// candidate and superseded slots in that order.
    pub fn get_module_by_connection(
        &self,
        connection_id: ConnectionId,
    ) -> Result<Option<ModuleRegistration>, RegistryError> {
        Ok(self
            .lock_inner()?
            .find_by_connection(connection_id)
            .map(|(_, registration)| registration.clone()))
    }

    /// Replace only the validated role declarations owned by this connection.
    pub fn replace_role_declarations_for_connection(
        &self,
        connection_id: ConnectionId,
        role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
    ) -> Result<Option<ModuleRegistration>, RegistryError> {
        let mut inner = self.lock_inner()?;
        let Some((slot, _)) = inner.find_by_connection(connection_id) else {
            return Ok(None);
        };
        let registration = inner
            .registration_mut(slot, connection_id)
            .expect("registration discovered under the same registry lock must still exist");
        registration.manifest.role_declarations = role_declarations;
        let updated = registration.clone();
        if matches!(slot, SlotKind::Active) && !inner.unpublished.contains(&connection_id) {
            inner.bump_generation();
        }
        inner.notify_module_changed(&updated.manifest.module_id);
        Ok(Some(updated))
    }

    /// Replace the provider role list and, when supplied, the attested capability
    /// declaration for the module owned by `connection_id`.
    ///
    /// Searches every slot: a swap candidate declares itself ready through this
    /// call, and if only the active slot were searched its update would find
    /// nothing and the candidate would never become ready. Only a change to the
    /// active slot bumps the catalog generation, because only the active slot is
    /// listed, and only once that registration is published.
    pub fn replace_catalog_for_connection(
        &self,
        connection_id: ConnectionId,
        provides: Vec<ProviderRole>,
        capabilities: Option<CapabilityDeclarations>,
        ready: Option<bool>,
    ) -> Result<Option<ModuleRegistration>, RegistryError> {
        let mut inner = self.lock_inner()?;
        let Some((slot, _)) = inner.find_by_connection(connection_id) else {
            return Ok(None);
        };
        let registration = inner
            .registration_mut(slot, connection_id)
            .expect("registration discovered under the same registry lock must still exist");
        if let Some(capabilities) = capabilities.as_ref() {
            let declares_federated = |caps: Option<&CapabilityDeclarations>| {
                caps.is_some_and(|caps| {
                    caps.provides
                        .iter()
                        .any(|cap| cap == subc_protocol::scope::SCOPE_FEDERATED_CAPABILITY)
                })
            };
            // Pending binds rely on this declaration while the target module's outbound queue is full.
            if declares_federated(registration.manifest.capabilities.as_ref())
                != declares_federated(Some(capabilities))
            {
                return Err(RegistryError::FederatedCapabilityChanged);
            }
            // Pending binds also decide from this declaration whether to
            // carry `caller`, so routes bound before and after an update
            // could otherwise attest differently.
            let declares_caller = |caps: Option<&CapabilityDeclarations>| {
                caps.is_some_and(|caps| {
                    caps.provides
                        .iter()
                        .any(|cap| cap == subc_protocol::peer::CALLER_ATTESTATION_CAPABILITY)
                })
            };
            if declares_caller(registration.manifest.capabilities.as_ref())
                != declares_caller(Some(capabilities))
            {
                return Err(RegistryError::CallerAttestationCapabilityChanged);
            }
        }
        registration.manifest.provides = provides;
        if let Some(capabilities) = capabilities {
            registration.manifest.capabilities = Some(capabilities);
        }
        if let Some(ready) = ready {
            registration.ready = ready;
            registration.manifest.ready = Some(ready);
        }
        let updated = registration.clone();
        if matches!(slot, SlotKind::Active) && !inner.unpublished.contains(&connection_id) {
            inner.bump_generation();
        }
        inner.notify_module_changed(&updated.manifest.module_id);
        Ok(Some(updated))
    }

    /// Deregister every module owned by a dropped connection, in any slot.
    pub fn deregister_connection(
        &self,
        connection_id: ConnectionId,
    ) -> Result<Vec<ModuleRegistration>, RegistryError> {
        self.deregister_connection_with_reason(
            connection_id,
            RegistrationEndReason::ConnectionClosed,
        )
    }

    pub(crate) fn deregister_connection_with_reason(
        &self,
        connection_id: ConnectionId,
        reason: RegistrationEndReason,
    ) -> Result<Vec<ModuleRegistration>, RegistryError> {
        let mut inner = self.lock_inner()?;
        // A registration that was never published was never listed, so
        // removing it leaves the catalog, and its generation, as they were.
        let was_published = !inner.unpublished.remove(&connection_id);
        let module_ids: Vec<String> = inner
            .modules
            .iter()
            .filter(|(_, registration)| registration.connection_id == connection_id)
            .map(|(module_id, _)| module_id.clone())
            .collect();

        let mut closed: Vec<ModuleRegistration> = module_ids
            .into_iter()
            .filter_map(|module_id| inner.close_module(&module_id, was_published))
            .collect();

        let candidate_ids: Vec<String> = inner
            .candidates
            .iter()
            .filter(|(_, registration)| registration.connection_id == connection_id)
            .map(|(module_id, _)| module_id.clone())
            .collect();
        for module_id in candidate_ids {
            if let Some(mut registration) = inner.candidates.remove(&module_id) {
                registration.state = ChannelState::Closed;
                closed.push(registration);
            }
        }

        let (removed, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut inner.superseded)
            .into_iter()
            .partition(|registration| registration.connection_id == connection_id);
        let superseded_connections: std::collections::HashSet<_> = removed
            .iter()
            .map(|registration| registration.connection_id)
            .collect();
        inner.superseded = kept;
        closed.extend(removed.into_iter().map(|mut registration| {
            registration.state = ChannelState::Closed;
            registration
        }));
        for registration in &closed {
            inner.nonce_verified.remove(&registration.connection_id);
            inner.notify_module_changed(&registration.manifest.module_id);
            let replaced = superseded_connections.contains(&registration.connection_id);
            let end_reason = if replaced {
                RegistrationEndReason::Replaced
            } else {
                reason
            };
            let replaced_by_connection_id = if replaced {
                inner
                    .superseded_by
                    .remove(&registration.connection_id)
                    .map(ConnectionId::get)
            } else {
                None
            };
            if let Some(replaced_by_connection_id) = replaced_by_connection_id {
                info!(
                    target: "subc.registry",
                    module_id = %registration.manifest.module_id,
                    connection_id = registration.connection_id.get(),
                    reason = %end_reason.as_str(),
                    replaced_by_connection_id,
                    "module registration ended"
                );
                continue;
            }
            info!(
                target: "subc.registry",
                module_id = %registration.manifest.module_id,
                connection_id = registration.connection_id.get(),
                reason = %end_reason.as_str(),
                "module registration ended"
            );
        }
        Ok(closed)
    }

    fn lock_inner(&self) -> Result<MutexGuard<'_, RegistryInner>, RegistryError> {
        #[cfg(test)]
        {
            let observer = self.next_lock_attempt.lock().unwrap().take();
            if let Some(observer) = observer {
                // Tell a held-publication test whether its reader acquired the
                // lock or must wait. This lets it release publication only after
                // the reader actually attempts the lookup, without a timer.
                match self.inner.try_lock() {
                    Ok(inner) => {
                        observer.send(true).unwrap();
                        return Ok(inner);
                    }
                    Err(std::sync::TryLockError::WouldBlock) => observer.send(false).unwrap(),
                    Err(std::sync::TryLockError::Poisoned(_)) => {
                        return Err(RegistryError::Poisoned);
                    }
                }
            }
        }
        self.inner.lock().map_err(|_| RegistryError::Poisoned)
    }
}

/// Which internal slot a connection-keyed lookup found its registration in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SlotKind {
    Active,
    Candidate,
    Superseded,
}

impl RegistryInner {
    fn publish_registration(&mut self, connection_id: ConnectionId) -> bool {
        if !self.unpublished.remove(&connection_id) {
            return false;
        }
        let Some((slot, registration)) = self.find_by_connection(connection_id) else {
            return false;
        };
        let module_id = registration.manifest.module_id.clone();
        if matches!(slot, SlotKind::Active) {
            self.bump_generation();
        }
        self.notify_module_changed(&module_id);
        true
    }

    fn notify_module_changed(&self, module_id: &str) {
        if let Some(sender) = self.module_changes.get(module_id) {
            sender.send_modify(|_| {});
        }
    }

    fn find_by_connection(
        &self,
        connection_id: ConnectionId,
    ) -> Option<(SlotKind, &ModuleRegistration)> {
        let owned_by =
            |registration: &&ModuleRegistration| registration.connection_id == connection_id;
        self.modules
            .values()
            .find(owned_by)
            .map(|registration| (SlotKind::Active, registration))
            .or_else(|| {
                self.candidates
                    .values()
                    .find(owned_by)
                    .map(|registration| (SlotKind::Candidate, registration))
            })
            .or_else(|| {
                self.superseded
                    .iter()
                    .find(owned_by)
                    .map(|registration| (SlotKind::Superseded, registration))
            })
    }

    fn registration_mut(
        &mut self,
        slot: SlotKind,
        connection_id: ConnectionId,
    ) -> Option<&mut ModuleRegistration> {
        let owned_by =
            |registration: &&mut ModuleRegistration| registration.connection_id == connection_id;
        match slot {
            SlotKind::Active => self.modules.values_mut().find(owned_by),
            SlotKind::Candidate => self.candidates.values_mut().find(owned_by),
            SlotKind::Superseded => self.superseded.iter_mut().find(owned_by),
        }
    }

    fn close_module(&mut self, module_id: &str, listed: bool) -> Option<ModuleRegistration> {
        let mut registration = self.modules.remove(module_id)?;
        registration.state = ChannelState::Closed;
        if listed {
            self.bump_generation();
        }
        Some(registration)
    }

    fn bump_generation(&mut self) {
        self.generation = self.generation.wrapping_add(1);
        if let Some(sender) = &self.catalog_changes {
            sender.send_replace(self.generation);
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RegistryError {
    FederatedCapabilityChanged,
    /// A `catalog.update` tried to add or drop `caller-attestation/v1`, which
    /// decides whether binds carry `caller` and so is fixed at HELLO.
    CallerAttestationCapabilityChanged,
    DuplicateModuleId {
        module_id: String,
    },
    /// The id is unusable as a single path component. Enforced at
    /// registration because the daemon MINTS A STORAGE DESCRIPTOR from the
    /// self-claimed id verbatim (`<data_home>/cortexkit/<module_id>/store.db`),
    /// so an id carrying separators or dot components is a path-traversal or
    /// store-collision primitive handed to whoever claims it (issue #32). The
    /// derivations deliberately do NOT sanitize instead: sanitizing here would
    /// silently re-path every deployed store and desynchronize the Rust and TS
    /// derivations, while refusal changes nothing for any id that ever worked.
    PathHazardModuleId {
        module_id: String,
        reason: String,
    },
    Poisoned,
}

impl fmt::Display for RegistryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::FederatedCapabilityChanged => write!(
                f,
                "scope-federated/v1 is fixed at HELLO; restart the module to change it"
            ),
            Self::CallerAttestationCapabilityChanged => write!(
                f,
                "caller-attestation/v1 is fixed at HELLO; restart the module to change it"
            ),
            Self::DuplicateModuleId { module_id } => {
                write!(f, "module_id '{module_id}' is already registered")
            }
            Self::PathHazardModuleId { module_id, reason } => {
                write!(
                    f,
                    "module_id '{}' is not usable as a path component: {reason}",
                    module_id.escape_debug()
                )
            }
            Self::Poisoned => write!(f, "registry lock was poisoned"),
        }
    }
}

impl Error for RegistryError {}

/// Why `module_id` cannot serve as a single path component, or `Ok(())`.
///
/// This is a REFUSAL predicate, not a sanitizer: every currently-working fleet
/// id passes untouched, and anything refused here never worked meaningfully --
/// it either escaped `<data_home>/cortexkit/` (separators, dot components) or
/// aliased another module's store (`a/b` vs `a//b` collapsing on POSIX).
/// Colons are allowed: reserved-namespace children (`mcp:...`) register today
/// and a colon cannot traverse. Windows path legality is the store library's
/// concern, not an identity rule.
pub fn module_id_path_hazard(module_id: &str) -> Result<(), String> {
    subc_protocol::module_id::module_id_path_hazard(module_id)
}

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

    fn manifest() -> ModuleManifest {
        ModuleManifest::builder("watched", "1.0.0")
            .protocol_ver(1)
            .build()
    }

    fn changed(receiver: &mut watch::Receiver<u64>) {
        assert!(
            receiver.has_changed().unwrap(),
            "registry write must notify"
        );
        receiver.borrow_and_update();
    }

    #[test]
    fn every_registration_write_notifies_only_its_module() {
        let registry = Registry::default();
        let mut events = registry.subscribe_module_changes("watched").unwrap();
        let other = registry.subscribe_module_changes("other").unwrap();
        let active = ConnectionId::new(1);
        let candidate = ConnectionId::new(2);
        registry
            .register_with_control_ops(manifest(), 1, active, vec![])
            .unwrap();
        changed(&mut events);
        registry
            .set_module_state_for_test("watched", ChannelState::Active)
            .unwrap();
        changed(&mut events);
        registry
            .replace_catalog_for_connection(active, vec![], None, Some(true))
            .unwrap();
        changed(&mut events);
        registry
            .register_candidate_with_control_ops(manifest(), 1, candidate, vec![])
            .unwrap();
        changed(&mut events);
        registry
            .replace_catalog_for_connection(candidate, vec![], None, Some(true))
            .unwrap();
        changed(&mut events);
        registry.promote_candidate("watched").unwrap().unwrap();
        changed(&mut events);
        // Superseded connections can still update and deregister their slot.
        registry
            .replace_catalog_for_connection(active, vec![], None, Some(false))
            .unwrap();
        changed(&mut events);
        registry.deregister_connection(active).unwrap();
        changed(&mut events);
        registry.deregister_connection(candidate).unwrap();
        changed(&mut events);
        registry
            .register_candidate_with_control_ops(manifest(), 1, candidate, vec![])
            .unwrap();
        changed(&mut events);
        registry.deregister_connection(candidate).unwrap();
        changed(&mut events);
        assert!(
            !other.has_changed().unwrap(),
            "other module must stay parked"
        );
    }

    #[test]
    fn subscription_before_read_keeps_a_change_until_waited_on() {
        let registry = Registry::default();
        let mut events = registry.subscribe_module_changes("watched").unwrap();
        assert!(registry.get_module("watched").unwrap().is_none());
        registry
            .register_with_control_ops(manifest(), 1, ConnectionId::new(1), vec![])
            .unwrap();
        // Neither a later lookup nor a coalesced catalog update consumes it.
        registry.get_module("watched").unwrap().unwrap();
        registry
            .replace_catalog_for_connection(ConnectionId::new(1), vec![], None, Some(true))
            .unwrap();
        changed(&mut events);
        assert!(!events.has_changed().unwrap());
    }
}

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

    fn manifest() -> ModuleManifest {
        ModuleManifest::builder("m", "1.0.0")
            .protocol_ver(1)
            .build()
    }

    /// An unpublished registration holds its id and answers routing lookups,
    /// but `list_modules` leaves it out and the generation stays put until
    /// it is published; publishing lists it and bumps the generation once.
    #[test]
    fn unpublished_registration_is_unlisted_until_published() {
        let registry = Registry::default();
        let connection = ConnectionId::new(1);
        registry
            .register_unpublished_with_control_ops(manifest(), 1, connection, vec![])
            .unwrap();
        assert_eq!(registry.list_modules().unwrap(), (0, Vec::new()));
        assert!(registry.get_module("m").unwrap().is_some());
        assert_eq!(registry.list_registered_modules().unwrap().len(), 1);
        assert!(registry
            .published_registration(RegistrationSlot::Active("m"))
            .unwrap()
            .is_none());
        assert!(matches!(
            registry.register_with_control_ops(manifest(), 1, ConnectionId::new(2), vec![]),
            Err(RegistryError::DuplicateModuleId { .. })
        ));
        // A catalog update before publication does not move the generation.
        registry
            .replace_catalog_for_connection(connection, vec![], None, Some(true))
            .unwrap();
        assert_eq!(registry.generation().unwrap(), 0);

        assert!(registry.publish_registration(connection).unwrap());
        let (generation, listed) = registry.list_modules().unwrap();
        assert_eq!(generation, 1);
        assert_eq!(listed.len(), 1);
        assert!(!registry.publish_registration(connection).unwrap());
        assert_eq!(registry.generation().unwrap(), 1);
    }

    /// Removing a registration that was never published leaves no catalog
    /// trace: the generation does not move, and a later publish is a no-op.
    #[test]
    fn deregistering_an_unpublished_registration_leaves_the_generation() {
        let registry = Registry::default();
        let connection = ConnectionId::new(1);
        registry
            .register_unpublished_with_control_ops(manifest(), 1, connection, vec![])
            .unwrap();
        assert_eq!(registry.deregister_connection(connection).unwrap().len(), 1);
        assert_eq!(registry.list_modules().unwrap(), (0, Vec::new()));
        assert!(!registry.publish_registration(connection).unwrap());
        assert_eq!(registry.generation().unwrap(), 0);
    }

    /// An unpublished candidate holds the candidate slot but
    /// `published_registration` does not return it until it is published.
    /// Publishing a candidate does not bump the generation: candidates are
    /// never listed.
    #[test]
    fn unpublished_candidate_is_hidden_from_published_lookups() {
        let registry = Registry::default();
        let candidate = ConnectionId::new(2);
        registry
            .register_unpublished_candidate_with_control_ops(manifest(), 1, candidate, vec![])
            .unwrap();
        assert!(registry
            .registration(RegistrationSlot::Candidate("m"))
            .unwrap()
            .is_some());
        assert!(registry
            .published_registration(RegistrationSlot::Candidate("m"))
            .unwrap()
            .is_none());
        assert!(registry
            .published_registration(RegistrationSlot::Connection(candidate))
            .unwrap()
            .is_none());
        assert!(registry.publish_registration(candidate).unwrap());
        assert!(registry
            .published_registration(RegistrationSlot::Candidate("m"))
            .unwrap()
            .is_some());
        assert_eq!(registry.generation().unwrap(), 0);
    }
}

#[cfg(test)]
mod path_hazard_tests {
    use super::*;
    use crate::ConnectionId;
    use subc_protocol::manifest::ModuleManifest;

    fn manifest(module_id: &str) -> ModuleManifest {
        ModuleManifest::builder(module_id, "0.1.0")
            .protocol_ver(1)
            .build()
    }

    #[test]
    fn path_hazard_ids_are_refused_and_nothing_registers() {
        let registry = Registry::default();
        for (bad, reason_fragment) in [
            ("../escape", "path separator"),
            ("a/b", "path separator"),
            ("a\\b", "path separator"),
            ("..", "dot path component"),
            (".", "dot path component"),
            ("", "empty"),
            ("evil\u{0}id", "control character"),
        ] {
            let err = registry
                .register_with_control_ops(manifest(bad), 1, ConnectionId::new(7), Vec::new())
                .expect_err("path-hazard id must refuse");
            // Reason asserted so a predicate throwing the WRONG refusal fails.
            assert!(
                err.to_string().contains(reason_fragment),
                "id {bad:?}: expected {reason_fragment:?} in {err}"
            );
        }
        // THE EFFECT, not just the verdicts: no refusal left a registration
        // behind, and the generation never moved.
        assert_eq!(registry.active_registration_count().unwrap(), 0);
        assert_eq!(registry.generation().unwrap(), 0);
    }

    #[test]
    fn module_id_path_component_length_matches_shared_refusal_vectors() {
        let doc: serde_json::Value = serde_json::from_str(include_str!(
            "../tests/golden/module_id_path_component_refusals.json"
        ))
        .expect("refusal fixture parses");

        for case in doc["vectors"].as_array().expect("vectors array") {
            let name = case["name"].as_str().expect("name");
            let module_id = case["module_id"]["unit"]
                .as_str()
                .expect("module_id unit")
                .repeat(
                    case["module_id"]["repeat"]
                        .as_u64()
                        .expect("module_id repeat") as usize,
                );
            assert_eq!(
                module_id.len(),
                case["utf8_bytes"].as_u64().expect("utf8 bytes") as usize
            );

            let expected = case["expect_reason"].as_str().map(str::to_owned);
            assert_eq!(
                module_id_path_hazard(&module_id).err(),
                expected,
                "shared refusal vector {name:?} diverged"
            );
        }
    }

    #[test]
    fn working_id_shapes_register_including_namespace_colons() {
        let registry = Registry::default();
        for (i, good) in ["magic-context", "mcp:everything", "v1.2-module"]
            .iter()
            .enumerate()
        {
            registry
                .register_with_control_ops(
                    manifest(good),
                    1,
                    ConnectionId::new(10 + i as u64),
                    Vec::new(),
                )
                .unwrap_or_else(|err| panic!("id {good:?} must register: {err}"));
        }
        assert_eq!(registry.active_registration_count().unwrap(), 3);
    }
}

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

    fn manifest(module_id: &str, ready: Option<bool>) -> ModuleManifest {
        let mut manifest = ModuleManifest::builder(module_id, "0.1.0").build();
        manifest.ready = ready;
        manifest
    }

    const INCUMBENT: ConnectionId = ConnectionId(1);
    const CANDIDATE: ConnectionId = ConnectionId(2);

    fn registry_with_candidate() -> Registry {
        let registry = Registry::default();
        registry
            .register_with_control_ops(manifest("m", None), 1, INCUMBENT, Vec::new())
            .unwrap();
        registry
            .register_candidate_with_control_ops(
                manifest("m", Some(false)),
                1,
                CANDIDATE,
                Vec::new(),
            )
            .unwrap();
        registry
    }

    #[test]
    fn candidate_is_invisible_to_by_id_lookups_and_listing() {
        let registry = registry_with_candidate();
        let generation = registry.generation().unwrap();
        assert_eq!(
            registry.get_module("m").unwrap().unwrap().connection_id,
            INCUMBENT
        );
        let (listed_generation, listed) = registry.list_modules().unwrap();
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].connection_id, INCUMBENT);
        assert_eq!(listed_generation, generation);
        assert_eq!(registry.active_registration_count().unwrap(), 1);
        assert_eq!(
            registry.get_candidate("m").unwrap().unwrap().connection_id,
            CANDIDATE
        );
        assert_eq!(
            registry
                .register_candidate_with_control_ops(
                    manifest("m", None),
                    1,
                    ConnectionId(3),
                    Vec::new()
                )
                .unwrap_err(),
            RegistryError::DuplicateModuleId {
                module_id: "m".to_string()
            }
        );
    }

    #[test]
    fn promoted_candidate_keeps_its_verified_nonce_fact() {
        let registry = Registry::default();
        registry
            .register_unpublished_verified_candidate_with_control_ops(
                manifest("m", Some(true)),
                1,
                CANDIDATE,
                Vec::new(),
            )
            .unwrap();
        assert!(registry.publish_registration(CANDIDATE).unwrap());
        assert!(registry
            .list_modules_with_nonce_verification()
            .unwrap()
            .1
            .is_empty());

        registry.promote_candidate("m").unwrap().unwrap();
        let (_, modules) = registry.list_modules_with_nonce_verification().unwrap();
        assert_eq!(modules.len(), 1);
        assert!(modules[0].1);
    }

    /// Without the candidate slot in the connection-keyed search, this update
    /// returns `Ok(None)` and the candidate never becomes ready.
    #[test]
    fn candidate_catalog_update_reaches_the_candidate_registration() {
        let registry = registry_with_candidate();
        assert!(!registry.get_candidate("m").unwrap().unwrap().ready);

        let updated = registry
            .replace_catalog_for_connection(CANDIDATE, Vec::new(), None, Some(true))
            .unwrap()
            .expect("the candidate's own connection finds its registration");

        assert_eq!(updated.connection_id, CANDIDATE);
        assert!(registry.get_candidate("m").unwrap().unwrap().ready);
        assert_eq!(
            registry.get_module_by_connection(CANDIDATE).unwrap(),
            Some(updated)
        );
        assert_eq!(
            registry.get_module("m").unwrap().unwrap().connection_id,
            INCUMBENT,
            "a candidate's update must not touch the active registration"
        );
    }

    #[test]
    fn promotion_swaps_slots_and_each_connection_still_deregisters_its_own() {
        let registry = registry_with_candidate();
        let before = registry.generation().unwrap();
        let cutover = registry.promote_candidate("m").unwrap().unwrap();
        assert_eq!(cutover.promoted.connection_id, CANDIDATE);
        assert_eq!(cutover.superseded.unwrap().connection_id, INCUMBENT);
        assert_ne!(registry.generation().unwrap(), before);
        assert_eq!(registry.promote_candidate("m").unwrap(), None);

        assert_eq!(
            registry
                .registration(RegistrationSlot::Active("m"))
                .unwrap()
                .unwrap()
                .connection_id,
            CANDIDATE
        );
        assert!(registry
            .registration(RegistrationSlot::Candidate("m"))
            .unwrap()
            .is_none());
        assert!(registry
            .registration(RegistrationSlot::Connection(INCUMBENT))
            .unwrap()
            .is_some());

        let closed = registry.deregister_connection(INCUMBENT).unwrap();
        assert_eq!(closed.len(), 1);
        assert_eq!(closed[0].connection_id, INCUMBENT);
        assert_eq!(closed[0].state, ChannelState::Closed);
        assert!(registry
            .registration(RegistrationSlot::Connection(INCUMBENT))
            .unwrap()
            .is_none());
        assert_eq!(
            registry.get_module("m").unwrap().unwrap().connection_id,
            CANDIDATE
        );
    }

    #[test]
    fn a_dropped_candidate_deregisters_from_the_candidate_slot_only() {
        let registry = registry_with_candidate();
        let closed = registry.deregister_connection(CANDIDATE).unwrap();
        assert_eq!(closed.len(), 1);
        assert_eq!(closed[0].connection_id, CANDIDATE);
        assert!(registry.get_candidate("m").unwrap().is_none());
        assert_eq!(
            registry.get_module("m").unwrap().unwrap().connection_id,
            INCUMBENT
        );
    }
}