Skip to main content

subc_daemon/
registry.rs

1use std::{
2    collections::{BTreeMap, HashMap, HashSet},
3    error::Error,
4    fmt,
5    sync::{Mutex, MutexGuard},
6};
7
8use subc_protocol::manifest::{CapabilityDeclarations, ModuleManifest, ProviderRole};
9use tokio::sync::watch;
10use tracing::info;
11
12/// Per-connection identity assigned by [`crate::Router`] while serving a socket.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub struct ConnectionId(u64);
15
16impl ConnectionId {
17    /// Synthetic connection id used by unit tests. Router-issued connection ids
18    /// start at 1, so this 0 value never collides with a real socket owner.
19    #[cfg(test)]
20    pub const LOCAL: Self = Self(0);
21
22    pub const fn new(raw: u64) -> Self {
23        Self(raw)
24    }
25
26    pub fn get(self) -> u64 {
27        self.0
28    }
29}
30
31/// Lifecycle state for a module's channel allocation.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum ChannelState {
34    Active,
35    Closed,
36}
37
38/// Why a module registration stopped belonging to its connection.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub(crate) enum RegistrationEndReason {
41    ConnectionClosed,
42    ExplicitGoodbye,
43    Replaced,
44    SupervisorStop,
45    SupervisorRestart,
46    RegistrationFailed,
47}
48
49impl RegistrationEndReason {
50    fn as_str(self) -> &'static str {
51        match self {
52            Self::ConnectionClosed => "connection_closed",
53            Self::ExplicitGoodbye => "explicit_goodbye",
54            Self::Replaced => "replaced",
55            Self::SupervisorStop => "supervisor_stop",
56            Self::SupervisorRestart => "supervisor_restart",
57            Self::RegistrationFailed => "registration_failed",
58        }
59    }
60}
61
62/// Registry record for one active module registration.
63#[derive(Debug, Clone, PartialEq)]
64pub struct ModuleRegistration {
65    pub manifest: ModuleManifest,
66    pub ready: bool,
67    pub negotiated_ver: u8,
68    pub state: ChannelState,
69    pub connection_id: ConnectionId,
70    pub control_ops: Vec<String>,
71}
72
73/// Active routing registrations and their publication state from one lock.
74pub(crate) struct RouteAdmissionSnapshot {
75    pub(crate) modules: Vec<ModuleRegistration>,
76    pub(crate) unpublished: HashSet<ConnectionId>,
77}
78
79impl std::ops::Deref for RouteAdmissionSnapshot {
80    type Target = [ModuleRegistration];
81
82    fn deref(&self) -> &Self::Target {
83        &self.modules
84    }
85}
86
87/// Which registration a lookup or a lifecycle wait is about.
88///
89/// A module id alone stops naming one process once a blue/green swap runs two
90/// processes under the same id: the incumbent in the active slot, the
91/// replacement in the candidate slot, and, after cutover, the old incumbent
92/// demoted until its connection goes away. A wait keyed on the bare id would
93/// confuse them (a successful swap never empties the id's active slot, and a
94/// candidate's "has it registered yet" would be answered by the incumbent).
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum RegistrationSlot<'a> {
97    /// The routable registration for this module id. This is what every plain
98    /// start, stop and restart path means by "the module is registered".
99    Active(&'a str),
100    /// A swap candidate registered under this module id and not yet promoted.
101    Candidate(&'a str),
102    /// Whatever registration this module connection holds, in any slot.
103    Connection(ConnectionId),
104}
105
106/// The result of promoting a module's candidate registration to active.
107#[derive(Debug, Clone, PartialEq)]
108pub struct RegistryCutover {
109    /// The registration that is now active (the former candidate).
110    pub promoted: ModuleRegistration,
111    /// The former active registration, now demoted. `None` when the incumbent
112    /// had already gone away before the promotion.
113    pub superseded: Option<ModuleRegistration>,
114}
115
116/// Control-plane registry for module manifests and supervision ownership.
117///
118/// Duplicate active `module_id`s are rejected rather than replaced. Rejection is
119/// the safer v1 behavior because replacing a still-connected module could hijack
120/// in-flight routes. Stale registrations are removed by connection cleanup; a
121/// reconnect after the old connection drops can then register the same id again.
122///
123/// A blue/green swap is the one sanctioned way two processes hold the same id.
124/// The replacement registers into a separate candidate slot, which every by-id
125/// lookup ignores, so it stays unroutable until [`Registry::promote_candidate`]
126/// swaps it in. The old incumbent is then kept as "superseded" until its
127/// connection deregisters. Lookups keyed by connection id search all three
128/// slots, because a connection must be able to update and remove its own
129/// registration whichever slot it currently sits in.
130#[derive(Debug, Default)]
131pub struct Registry {
132    inner: Mutex<RegistryInner>,
133}
134
135#[derive(Debug, Default)]
136struct RegistryInner {
137    /// Only subscribed module ids have a sender. Changes coalesce, and writers
138    /// never wait for a supervisor to receive them.
139    // The value counts accepted active registrations. Keep that evidence even
140    // when register and disconnect coalesce before a supervisor receives them.
141    module_changes: HashMap<String, watch::Sender<u64>>,
142    modules: HashMap<String, ModuleRegistration>,
143    /// Swap candidates by module id: registered, never routable, never listed.
144    candidates: HashMap<String, ModuleRegistration>,
145    /// Former incumbents demoted by a promotion, kept only so their own
146    /// connection can still find and remove them. Never routable, never listed.
147    superseded: Vec<ModuleRegistration>,
148    /// Connections whose HELLO passed the launch-nonce check required for a
149    /// reserved module or swap candidate. Kept outside ModuleRegistration so
150    /// adding this catalog fact does not break callers that construct the public
151    /// registration struct.
152    nonce_verified: HashSet<ConnectionId>,
153    /// The active connection that displaced each superseded registration.
154    superseded_by: HashMap<ConnectionId, ConnectionId>,
155    /// Connections whose registration is reserved but not yet published.
156    ///
157    /// A HELLO registers in the registry before the daemon installs the
158    /// module's forwarding endpoint, and until that endpoint exists a
159    /// `route.open` to the module cannot be relayed. A registration in this set
160    /// already holds its module id (a duplicate HELLO is refused) and is found
161    /// by every lookup except two: [`Registry::list_modules`], which feeds
162    /// `catalog.list`, and [`Registry::published_registration`], which the swap
163    /// supervisor reads to decide that a candidate has registered. Adding a
164    /// registration to this set does not bump the catalog generation;
165    /// [`Registry::publish_registration`] removes it and bumps the generation
166    /// in the same critical section, so a catalog reader sees the module and
167    /// the new generation together.
168    unpublished: HashSet<ConnectionId>,
169    generation: u64,
170}
171
172impl Registry {
173    /// Subscribe before reading a registration so a change between the read
174    /// and the supervisor's wait remains pending on this receiver.
175    pub(crate) fn subscribe_module_changes(
176        &self,
177        module_id: &str,
178    ) -> Result<watch::Receiver<u64>, RegistryError> {
179        let mut inner = self.lock_inner()?;
180        // Retired supervisors must not leave an ever-growing set of ids.
181        inner
182            .module_changes
183            .retain(|_, sender| sender.receiver_count() > 0);
184        Ok(inner
185            .module_changes
186            .entry(module_id.to_string())
187            .or_insert_with(|| watch::channel(0).0)
188            .subscribe())
189    }
190
191    /// Register a module manifest with the module's effective granted control op set.
192    ///
193    /// The registration is published at once: it is listed by
194    /// [`Self::list_modules`] and bumps the catalog generation. The HELLO path
195    /// uses [`Self::register_unpublished_with_control_ops`] instead, because it
196    /// still has to install the module's forwarding endpoint.
197    pub fn register_with_control_ops(
198        &self,
199        manifest: ModuleManifest,
200        negotiated_ver: u8,
201        connection_id: ConnectionId,
202        control_ops: Vec<String>,
203    ) -> Result<ModuleRegistration, RegistryError> {
204        self.register_active(
205            manifest,
206            negotiated_ver,
207            connection_id,
208            control_ops,
209            true,
210            false,
211        )
212    }
213
214    /// Register a module manifest without listing it yet.
215    ///
216    /// The registration holds its module id and is visible to every lookup
217    /// except [`Self::list_modules`] (and so `catalog.list`) and
218    /// [`Self::published_registration`]. The catalog generation does not move.
219    /// Call [`Self::publish_registration`] once the module can actually be
220    /// routed to; if that never becomes possible, deregistering the connection
221    /// removes the entry without the catalog ever having listed it.
222    pub fn register_unpublished_with_control_ops(
223        &self,
224        manifest: ModuleManifest,
225        negotiated_ver: u8,
226        connection_id: ConnectionId,
227        control_ops: Vec<String>,
228    ) -> Result<ModuleRegistration, RegistryError> {
229        self.register_active(
230            manifest,
231            negotiated_ver,
232            connection_id,
233            control_ops,
234            false,
235            false,
236        )
237    }
238
239    /// Register a module after its HELLO is accepted, without listing it before forwarding is installed.
240    pub(crate) fn register_unpublished_verified_with_control_ops(
241        &self,
242        manifest: ModuleManifest,
243        negotiated_ver: u8,
244        connection_id: ConnectionId,
245        control_ops: Vec<String>,
246        nonce_verified: bool,
247    ) -> Result<ModuleRegistration, RegistryError> {
248        self.register_active(
249            manifest,
250            negotiated_ver,
251            connection_id,
252            control_ops,
253            false,
254            nonce_verified,
255        )
256    }
257
258    fn register_active(
259        &self,
260        manifest: ModuleManifest,
261        negotiated_ver: u8,
262        connection_id: ConnectionId,
263        control_ops: Vec<String>,
264        publish: bool,
265        nonce_verified: bool,
266    ) -> Result<ModuleRegistration, RegistryError> {
267        let module_id = manifest.module_id.clone();
268        if let Err(reason) = module_id_path_hazard(&module_id) {
269            return Err(RegistryError::PathHazardModuleId { module_id, reason });
270        }
271        let mut inner = self.lock_inner()?;
272        if inner.modules.contains_key(&module_id) {
273            return Err(RegistryError::DuplicateModuleId { module_id });
274        }
275
276        let ready = manifest.ready.unwrap_or(true);
277        let registration = ModuleRegistration {
278            manifest,
279            ready,
280            negotiated_ver,
281            state: ChannelState::Active,
282            connection_id,
283            control_ops,
284        };
285
286        inner.modules.insert(module_id, registration.clone());
287        if nonce_verified {
288            inner.nonce_verified.insert(connection_id);
289        } else {
290            inner.nonce_verified.remove(&connection_id);
291        }
292        if publish {
293            inner.bump_generation();
294        } else {
295            inner.unpublished.insert(connection_id);
296        }
297        if let Some(sender) = inner.module_changes.get(&registration.manifest.module_id) {
298            sender.send_modify(|accepted| *accepted = accepted.wrapping_add(1));
299        }
300        Ok(registration)
301    }
302
303    /// Register a swap candidate for `manifest.module_id` into the candidate slot.
304    ///
305    /// The candidate is invisible to [`Self::get_module`], [`Self::list_modules`]
306    /// and every other by-id lookup until [`Self::promote_candidate`]. An active
307    /// registration for the id is not required, because the incumbent may die
308    /// while the swap is open; deciding whether a candidate may register at all
309    /// belongs to the caller that admits it. A second candidate for the same id
310    /// is refused.
311    ///
312    /// The candidate is published at once, meaning candidate-slot lookups
313    /// through [`Self::published_registration`] return it immediately. The
314    /// HELLO path uses
315    /// [`Self::register_unpublished_candidate_with_control_ops`] instead.
316    pub fn register_candidate_with_control_ops(
317        &self,
318        manifest: ModuleManifest,
319        negotiated_ver: u8,
320        connection_id: ConnectionId,
321        control_ops: Vec<String>,
322    ) -> Result<ModuleRegistration, RegistryError> {
323        self.register_candidate(
324            manifest,
325            negotiated_ver,
326            connection_id,
327            control_ops,
328            true,
329            false,
330        )
331    }
332
333    /// Register a swap candidate that [`Self::published_registration`] does not
334    /// return until [`Self::publish_registration`] is called for its
335    /// connection. The swap supervisor reads that lookup to decide the
336    /// candidate has registered, and it promotes a ready candidate straight
337    /// away; promoting one whose forwarding endpoint is not installed yet would
338    /// fail the cutover.
339    pub fn register_unpublished_candidate_with_control_ops(
340        &self,
341        manifest: ModuleManifest,
342        negotiated_ver: u8,
343        connection_id: ConnectionId,
344        control_ops: Vec<String>,
345    ) -> Result<ModuleRegistration, RegistryError> {
346        self.register_candidate(
347            manifest,
348            negotiated_ver,
349            connection_id,
350            control_ops,
351            false,
352            false,
353        )
354    }
355
356    /// Register a blue/green swap candidate after its required launch nonce has been verified.
357    pub(crate) fn register_unpublished_verified_candidate_with_control_ops(
358        &self,
359        manifest: ModuleManifest,
360        negotiated_ver: u8,
361        connection_id: ConnectionId,
362        control_ops: Vec<String>,
363    ) -> Result<ModuleRegistration, RegistryError> {
364        self.register_candidate(
365            manifest,
366            negotiated_ver,
367            connection_id,
368            control_ops,
369            false,
370            true,
371        )
372    }
373
374    fn register_candidate(
375        &self,
376        manifest: ModuleManifest,
377        negotiated_ver: u8,
378        connection_id: ConnectionId,
379        control_ops: Vec<String>,
380        publish: bool,
381        nonce_verified: bool,
382    ) -> Result<ModuleRegistration, RegistryError> {
383        let module_id = manifest.module_id.clone();
384        if let Err(reason) = module_id_path_hazard(&module_id) {
385            return Err(RegistryError::PathHazardModuleId { module_id, reason });
386        }
387        let mut inner = self.lock_inner()?;
388        if inner.candidates.contains_key(&module_id) {
389            return Err(RegistryError::DuplicateModuleId { module_id });
390        }
391        let ready = manifest.ready.unwrap_or(true);
392        let registration = ModuleRegistration {
393            manifest,
394            ready,
395            negotiated_ver,
396            state: ChannelState::Active,
397            connection_id,
398            control_ops,
399        };
400        inner.candidates.insert(module_id, registration.clone());
401        if nonce_verified {
402            inner.nonce_verified.insert(connection_id);
403        } else {
404            inner.nonce_verified.remove(&connection_id);
405        }
406        if !publish {
407            inner.unpublished.insert(connection_id);
408        }
409        inner.notify_module_changed(&registration.manifest.module_id);
410        Ok(registration)
411    }
412
413    /// Publish the registration `connection_id` holds, in whichever slot.
414    ///
415    /// For an active registration this is the moment `catalog.list` starts
416    /// listing the module, and the catalog generation advances under the same
417    /// lock, so no reader can see the new generation without the module or the
418    /// module without the new generation. A candidate is not listed either way;
419    /// publishing it only makes it visible to
420    /// [`Self::published_registration`].
421    ///
422    /// Returns `false` when there is nothing to publish: the connection holds
423    /// no registration any more, or it was already published.
424    pub fn publish_registration(&self, connection_id: ConnectionId) -> Result<bool, RegistryError> {
425        let mut inner = self.lock_inner()?;
426        if !inner.unpublished.remove(&connection_id) {
427            return Ok(false);
428        }
429        let Some((slot, registration)) = inner.find_by_connection(connection_id) else {
430            return Ok(false);
431        };
432        let module_id = registration.manifest.module_id.clone();
433        if matches!(slot, SlotKind::Active) {
434            inner.bump_generation();
435        }
436        inner.notify_module_changed(&module_id);
437        Ok(true)
438    }
439
440    /// Move the candidate for `module_id` into the active slot and demote the
441    /// previous active registration, in one registry critical section.
442    ///
443    /// Returns `Ok(None)` when there is no candidate to promote. Bumps the
444    /// catalog generation, because the listed registration for the id changed.
445    pub fn promote_candidate(
446        &self,
447        module_id: &str,
448    ) -> Result<Option<RegistryCutover>, RegistryError> {
449        let mut inner = self.lock_inner()?;
450        let Some(promoted) = inner.candidates.remove(module_id) else {
451            return Ok(None);
452        };
453        let superseded = inner
454            .modules
455            .insert(module_id.to_string(), promoted.clone());
456        if let Some(superseded) = superseded.clone() {
457            let replaced_connection_id = superseded.connection_id.get();
458            inner
459                .superseded_by
460                .insert(superseded.connection_id, promoted.connection_id);
461            inner.superseded.push(superseded);
462            info!(
463                target: "subc.registry",
464                module_id = %module_id,
465                connection_id = promoted.connection_id.get(),
466                replaced = true,
467                replaced_connection_id,
468                "module registration promoted"
469            );
470        }
471        inner.bump_generation();
472        inner.notify_module_changed(module_id);
473        Ok(Some(RegistryCutover {
474            promoted,
475            superseded,
476        }))
477    }
478
479    /// The ACTIVE registration for `module_id`. Candidates and superseded
480    /// incumbents are never returned: this is the lookup routing decisions use.
481    pub fn get_module(&self, module_id: &str) -> Result<Option<ModuleRegistration>, RegistryError> {
482        Ok(self.lock_inner()?.modules.get(module_id).cloned())
483    }
484
485    /// Unlike the published-only catalog view, admission sees staged active
486    /// registrations too, exactly as `get_module` does. A target whose
487    /// registration is accepted but not yet published in the catalog must
488    /// answer `target_unavailable`, not `unknown_module`, on an ordinary open.
489    pub(crate) fn route_admission_snapshot(&self) -> Result<RouteAdmissionSnapshot, RegistryError> {
490        let inner = self.lock_inner()?;
491        let mut modules = inner.modules.values().cloned().collect::<Vec<_>>();
492        modules.sort_by(|a, b| a.manifest.module_id.cmp(&b.manifest.module_id));
493        Ok(RouteAdmissionSnapshot {
494            modules,
495            unpublished: inner.unpublished.clone(),
496        })
497    }
498
499    /// The swap candidate registered for `module_id`, if any.
500    pub fn get_candidate(
501        &self,
502        module_id: &str,
503    ) -> Result<Option<ModuleRegistration>, RegistryError> {
504        Ok(self.lock_inner()?.candidates.get(module_id).cloned())
505    }
506
507    /// The registration held in one specific slot. See [`RegistrationSlot`].
508    pub fn registration(
509        &self,
510        slot: RegistrationSlot<'_>,
511    ) -> Result<Option<ModuleRegistration>, RegistryError> {
512        let inner = self.lock_inner()?;
513        Ok(match slot {
514            RegistrationSlot::Active(module_id) => inner.modules.get(module_id).cloned(),
515            RegistrationSlot::Candidate(module_id) => inner.candidates.get(module_id).cloned(),
516            RegistrationSlot::Connection(connection_id) => inner
517                .find_by_connection(connection_id)
518                .map(|(_, registration)| registration.clone()),
519        })
520    }
521
522    pub fn active_registration_count(&self) -> Result<usize, RegistryError> {
523        Ok(self.lock_inner()?.modules.len())
524    }
525
526    /// The catalog generation and the active registrations `catalog.list`
527    /// shows. Unpublished registrations (see
528    /// [`Self::register_unpublished_with_control_ops`]) are left out.
529    pub fn list_modules(&self) -> Result<(u64, Vec<ModuleRegistration>), RegistryError> {
530        let inner = self.lock_inner()?;
531        let mut modules = inner
532            .modules
533            .values()
534            .filter(|registration| !inner.unpublished.contains(&registration.connection_id))
535            .cloned()
536            .collect::<Vec<_>>();
537        modules.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
538        Ok((inner.generation, modules))
539    }
540
541    /// List published active registrations together with their HELLO nonce-verification status.
542    /// Both values are captured under the registry lock so a concurrent swap or
543    /// disconnect cannot separate a registration from its verification fact.
544    pub fn list_modules_with_nonce_verification(
545        &self,
546    ) -> Result<(u64, Vec<(ModuleRegistration, bool)>), RegistryError> {
547        let inner = self.lock_inner()?;
548        let mut registrations = inner
549            .modules
550            .values()
551            .filter(|registration| !inner.unpublished.contains(&registration.connection_id))
552            .collect::<Vec<_>>();
553        registrations.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
554        let modules = registrations
555            .into_iter()
556            .map(|registration| {
557                (
558                    registration.clone(),
559                    inner.nonce_verified.contains(&registration.connection_id),
560                )
561            })
562            .collect();
563        Ok((inner.generation, modules))
564    }
565
566    /// Every active registration, including unpublished ones.
567    ///
568    /// For the capability evaluator and the capability deny census, which
569    /// count a module as soon as it has registered. Whether `catalog.list`
570    /// shows the module yet does not change their verdicts.
571    pub fn list_registered_modules(&self) -> Result<Vec<ModuleRegistration>, RegistryError> {
572        let inner = self.lock_inner()?;
573        let mut modules = inner.modules.values().cloned().collect::<Vec<_>>();
574        modules.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
575        Ok(modules)
576    }
577
578    /// Like [`Self::registration`], but a registration that is not published
579    /// yet is reported as absent.
580    pub fn published_registration(
581        &self,
582        slot: RegistrationSlot<'_>,
583    ) -> Result<Option<ModuleRegistration>, RegistryError> {
584        let inner = self.lock_inner()?;
585        let registration = match slot {
586            RegistrationSlot::Active(module_id) => inner.modules.get(module_id),
587            RegistrationSlot::Candidate(module_id) => inner.candidates.get(module_id),
588            RegistrationSlot::Connection(connection_id) => inner
589                .find_by_connection(connection_id)
590                .map(|(_, registration)| registration),
591        };
592        Ok(registration
593            .filter(|registration| !inner.unpublished.contains(&registration.connection_id))
594            .cloned())
595    }
596
597    pub fn generation(&self) -> Result<u64, RegistryError> {
598        Ok(self.lock_inner()?.generation)
599    }
600
601    #[cfg(test)]
602    pub(crate) fn set_module_state_for_test(
603        &self,
604        module_id: &str,
605        state: ChannelState,
606    ) -> Result<bool, RegistryError> {
607        let mut inner = self.lock_inner()?;
608        let Some(registration) = inner.modules.get_mut(module_id) else {
609            return Ok(false);
610        };
611        registration.state = state;
612        inner.notify_module_changed(module_id);
613        Ok(true)
614    }
615
616    /// The registration owned by `connection_id`, searching the active,
617    /// candidate and superseded slots in that order.
618    pub fn get_module_by_connection(
619        &self,
620        connection_id: ConnectionId,
621    ) -> Result<Option<ModuleRegistration>, RegistryError> {
622        Ok(self
623            .lock_inner()?
624            .find_by_connection(connection_id)
625            .map(|(_, registration)| registration.clone()))
626    }
627
628    /// Replace only the validated role declarations owned by this connection.
629    pub fn replace_role_declarations_for_connection(
630        &self,
631        connection_id: ConnectionId,
632        role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
633    ) -> Result<Option<ModuleRegistration>, RegistryError> {
634        let mut inner = self.lock_inner()?;
635        let Some((slot, _)) = inner.find_by_connection(connection_id) else {
636            return Ok(None);
637        };
638        let registration = inner
639            .registration_mut(slot, connection_id)
640            .expect("registration discovered under the same registry lock must still exist");
641        registration.manifest.role_declarations = role_declarations;
642        let updated = registration.clone();
643        if matches!(slot, SlotKind::Active) && !inner.unpublished.contains(&connection_id) {
644            inner.bump_generation();
645        }
646        inner.notify_module_changed(&updated.manifest.module_id);
647        Ok(Some(updated))
648    }
649
650    /// Replace the provider role list and, when supplied, the attested capability
651    /// declaration for the module owned by `connection_id`.
652    ///
653    /// Searches every slot: a swap candidate declares itself ready through this
654    /// call, and if only the active slot were searched its update would find
655    /// nothing and the candidate would never become ready. Only a change to the
656    /// active slot bumps the catalog generation, because only the active slot is
657    /// listed, and only once that registration is published.
658    pub fn replace_catalog_for_connection(
659        &self,
660        connection_id: ConnectionId,
661        provides: Vec<ProviderRole>,
662        capabilities: Option<CapabilityDeclarations>,
663        ready: Option<bool>,
664    ) -> Result<Option<ModuleRegistration>, RegistryError> {
665        let mut inner = self.lock_inner()?;
666        let Some((slot, _)) = inner.find_by_connection(connection_id) else {
667            return Ok(None);
668        };
669        let registration = inner
670            .registration_mut(slot, connection_id)
671            .expect("registration discovered under the same registry lock must still exist");
672        if let Some(capabilities) = capabilities.as_ref() {
673            let declares_federated = |caps: Option<&CapabilityDeclarations>| {
674                caps.is_some_and(|caps| {
675                    caps.provides
676                        .iter()
677                        .any(|cap| cap == subc_protocol::scope::SCOPE_FEDERATED_CAPABILITY)
678                })
679            };
680            // Pending binds rely on this declaration while the target module's outbound queue is full.
681            if declares_federated(registration.manifest.capabilities.as_ref())
682                != declares_federated(Some(capabilities))
683            {
684                return Err(RegistryError::FederatedCapabilityChanged);
685            }
686        }
687        registration.manifest.provides = provides;
688        if let Some(capabilities) = capabilities {
689            registration.manifest.capabilities = Some(capabilities);
690        }
691        if let Some(ready) = ready {
692            registration.ready = ready;
693            registration.manifest.ready = Some(ready);
694        }
695        let updated = registration.clone();
696        if matches!(slot, SlotKind::Active) && !inner.unpublished.contains(&connection_id) {
697            inner.bump_generation();
698        }
699        inner.notify_module_changed(&updated.manifest.module_id);
700        Ok(Some(updated))
701    }
702
703    /// Deregister every module owned by a dropped connection, in any slot.
704    pub fn deregister_connection(
705        &self,
706        connection_id: ConnectionId,
707    ) -> Result<Vec<ModuleRegistration>, RegistryError> {
708        self.deregister_connection_with_reason(
709            connection_id,
710            RegistrationEndReason::ConnectionClosed,
711        )
712    }
713
714    pub(crate) fn deregister_connection_with_reason(
715        &self,
716        connection_id: ConnectionId,
717        reason: RegistrationEndReason,
718    ) -> Result<Vec<ModuleRegistration>, RegistryError> {
719        let mut inner = self.lock_inner()?;
720        // A registration that was never published was never listed, so
721        // removing it leaves the catalog, and its generation, as they were.
722        let was_published = !inner.unpublished.remove(&connection_id);
723        let module_ids: Vec<String> = inner
724            .modules
725            .iter()
726            .filter(|(_, registration)| registration.connection_id == connection_id)
727            .map(|(module_id, _)| module_id.clone())
728            .collect();
729
730        let mut closed: Vec<ModuleRegistration> = module_ids
731            .into_iter()
732            .filter_map(|module_id| inner.close_module(&module_id, was_published))
733            .collect();
734
735        let candidate_ids: Vec<String> = inner
736            .candidates
737            .iter()
738            .filter(|(_, registration)| registration.connection_id == connection_id)
739            .map(|(module_id, _)| module_id.clone())
740            .collect();
741        for module_id in candidate_ids {
742            if let Some(mut registration) = inner.candidates.remove(&module_id) {
743                registration.state = ChannelState::Closed;
744                closed.push(registration);
745            }
746        }
747
748        let (removed, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut inner.superseded)
749            .into_iter()
750            .partition(|registration| registration.connection_id == connection_id);
751        let superseded_connections: std::collections::HashSet<_> = removed
752            .iter()
753            .map(|registration| registration.connection_id)
754            .collect();
755        inner.superseded = kept;
756        closed.extend(removed.into_iter().map(|mut registration| {
757            registration.state = ChannelState::Closed;
758            registration
759        }));
760        for registration in &closed {
761            inner.nonce_verified.remove(&registration.connection_id);
762            inner.notify_module_changed(&registration.manifest.module_id);
763            let replaced = superseded_connections.contains(&registration.connection_id);
764            let end_reason = if replaced {
765                RegistrationEndReason::Replaced
766            } else {
767                reason
768            };
769            let replaced_by_connection_id = if replaced {
770                inner
771                    .superseded_by
772                    .remove(&registration.connection_id)
773                    .map(ConnectionId::get)
774            } else {
775                None
776            };
777            if let Some(replaced_by_connection_id) = replaced_by_connection_id {
778                info!(
779                    target: "subc.registry",
780                    module_id = %registration.manifest.module_id,
781                    connection_id = registration.connection_id.get(),
782                    reason = %end_reason.as_str(),
783                    replaced_by_connection_id,
784                    "module registration ended"
785                );
786                continue;
787            }
788            info!(
789                target: "subc.registry",
790                module_id = %registration.manifest.module_id,
791                connection_id = registration.connection_id.get(),
792                reason = %end_reason.as_str(),
793                "module registration ended"
794            );
795        }
796        Ok(closed)
797    }
798
799    fn lock_inner(&self) -> Result<MutexGuard<'_, RegistryInner>, RegistryError> {
800        self.inner.lock().map_err(|_| RegistryError::Poisoned)
801    }
802}
803
804/// Which internal slot a connection-keyed lookup found its registration in.
805#[derive(Debug, Clone, Copy, PartialEq, Eq)]
806enum SlotKind {
807    Active,
808    Candidate,
809    Superseded,
810}
811
812impl RegistryInner {
813    fn notify_module_changed(&self, module_id: &str) {
814        if let Some(sender) = self.module_changes.get(module_id) {
815            sender.send_modify(|_| {});
816        }
817    }
818
819    fn find_by_connection(
820        &self,
821        connection_id: ConnectionId,
822    ) -> Option<(SlotKind, &ModuleRegistration)> {
823        let owned_by =
824            |registration: &&ModuleRegistration| registration.connection_id == connection_id;
825        self.modules
826            .values()
827            .find(owned_by)
828            .map(|registration| (SlotKind::Active, registration))
829            .or_else(|| {
830                self.candidates
831                    .values()
832                    .find(owned_by)
833                    .map(|registration| (SlotKind::Candidate, registration))
834            })
835            .or_else(|| {
836                self.superseded
837                    .iter()
838                    .find(owned_by)
839                    .map(|registration| (SlotKind::Superseded, registration))
840            })
841    }
842
843    fn registration_mut(
844        &mut self,
845        slot: SlotKind,
846        connection_id: ConnectionId,
847    ) -> Option<&mut ModuleRegistration> {
848        let owned_by =
849            |registration: &&mut ModuleRegistration| registration.connection_id == connection_id;
850        match slot {
851            SlotKind::Active => self.modules.values_mut().find(owned_by),
852            SlotKind::Candidate => self.candidates.values_mut().find(owned_by),
853            SlotKind::Superseded => self.superseded.iter_mut().find(owned_by),
854        }
855    }
856
857    fn close_module(&mut self, module_id: &str, listed: bool) -> Option<ModuleRegistration> {
858        let mut registration = self.modules.remove(module_id)?;
859        registration.state = ChannelState::Closed;
860        if listed {
861            self.bump_generation();
862        }
863        Some(registration)
864    }
865
866    fn bump_generation(&mut self) {
867        self.generation = self.generation.wrapping_add(1);
868    }
869}
870
871#[derive(Debug, Clone, PartialEq, Eq)]
872pub enum RegistryError {
873    FederatedCapabilityChanged,
874    DuplicateModuleId {
875        module_id: String,
876    },
877    /// The id is unusable as a single path component. Enforced at
878    /// registration because the daemon MINTS A STORAGE DESCRIPTOR from the
879    /// self-claimed id verbatim (`<data_home>/cortexkit/<module_id>/store.db`),
880    /// so an id carrying separators or dot components is a path-traversal or
881    /// store-collision primitive handed to whoever claims it (issue #32). The
882    /// derivations deliberately do NOT sanitize instead: sanitizing here would
883    /// silently re-path every deployed store and desynchronize the Rust and TS
884    /// derivations, while refusal changes nothing for any id that ever worked.
885    PathHazardModuleId {
886        module_id: String,
887        reason: String,
888    },
889    Poisoned,
890}
891
892impl fmt::Display for RegistryError {
893    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
894        match self {
895            Self::FederatedCapabilityChanged => write!(f, "scope-federated/v1 is fixed at HELLO; re-register on a new connection to change it"),
896            Self::DuplicateModuleId { module_id } => {
897                write!(f, "module_id '{module_id}' is already registered")
898            }
899            Self::PathHazardModuleId { module_id, reason } => {
900                write!(
901                    f,
902                    "module_id '{}' is not usable as a path component: {reason}",
903                    module_id.escape_debug()
904                )
905            }
906            Self::Poisoned => write!(f, "registry lock was poisoned"),
907        }
908    }
909}
910
911impl Error for RegistryError {}
912
913/// Why `module_id` cannot serve as a single path component, or `Ok(())`.
914///
915/// This is a REFUSAL predicate, not a sanitizer: every currently-working fleet
916/// id passes untouched, and anything refused here never worked meaningfully --
917/// it either escaped `<data_home>/cortexkit/` (separators, dot components) or
918/// aliased another module's store (`a/b` vs `a//b` collapsing on POSIX).
919/// Colons are allowed: reserved-namespace children (`mcp:...`) register today
920/// and a colon cannot traverse. Windows path legality is the store library's
921/// concern, not an identity rule.
922pub fn module_id_path_hazard(module_id: &str) -> Result<(), String> {
923    subc_protocol::manifest::validate_module_id(module_id)
924}
925
926#[cfg(test)]
927mod change_notification_tests {
928    use super::*;
929
930    fn manifest() -> ModuleManifest {
931        ModuleManifest::builder("watched", "1.0.0")
932            .protocol_ver(1)
933            .build()
934    }
935
936    fn changed(receiver: &mut watch::Receiver<u64>) {
937        assert!(
938            receiver.has_changed().unwrap(),
939            "registry write must notify"
940        );
941        receiver.borrow_and_update();
942    }
943
944    #[test]
945    fn every_registration_write_notifies_only_its_module() {
946        let registry = Registry::default();
947        let mut events = registry.subscribe_module_changes("watched").unwrap();
948        let other = registry.subscribe_module_changes("other").unwrap();
949        let active = ConnectionId::new(1);
950        let candidate = ConnectionId::new(2);
951        registry
952            .register_with_control_ops(manifest(), 1, active, vec![])
953            .unwrap();
954        changed(&mut events);
955        registry
956            .set_module_state_for_test("watched", ChannelState::Active)
957            .unwrap();
958        changed(&mut events);
959        registry
960            .replace_catalog_for_connection(active, vec![], None, Some(true))
961            .unwrap();
962        changed(&mut events);
963        registry
964            .register_candidate_with_control_ops(manifest(), 1, candidate, vec![])
965            .unwrap();
966        changed(&mut events);
967        registry
968            .replace_catalog_for_connection(candidate, vec![], None, Some(true))
969            .unwrap();
970        changed(&mut events);
971        registry.promote_candidate("watched").unwrap().unwrap();
972        changed(&mut events);
973        // Superseded connections can still update and deregister their slot.
974        registry
975            .replace_catalog_for_connection(active, vec![], None, Some(false))
976            .unwrap();
977        changed(&mut events);
978        registry.deregister_connection(active).unwrap();
979        changed(&mut events);
980        registry.deregister_connection(candidate).unwrap();
981        changed(&mut events);
982        registry
983            .register_candidate_with_control_ops(manifest(), 1, candidate, vec![])
984            .unwrap();
985        changed(&mut events);
986        registry.deregister_connection(candidate).unwrap();
987        changed(&mut events);
988        assert!(
989            !other.has_changed().unwrap(),
990            "other module must stay parked"
991        );
992    }
993
994    #[test]
995    fn subscription_before_read_keeps_a_change_until_waited_on() {
996        let registry = Registry::default();
997        let mut events = registry.subscribe_module_changes("watched").unwrap();
998        assert!(registry.get_module("watched").unwrap().is_none());
999        registry
1000            .register_with_control_ops(manifest(), 1, ConnectionId::new(1), vec![])
1001            .unwrap();
1002        // Neither a later lookup nor a coalesced catalog update consumes it.
1003        registry.get_module("watched").unwrap().unwrap();
1004        registry
1005            .replace_catalog_for_connection(ConnectionId::new(1), vec![], None, Some(true))
1006            .unwrap();
1007        changed(&mut events);
1008        assert!(!events.has_changed().unwrap());
1009    }
1010}
1011
1012#[cfg(test)]
1013mod publication_tests {
1014    use super::*;
1015
1016    fn manifest() -> ModuleManifest {
1017        ModuleManifest::builder("m", "1.0.0")
1018            .protocol_ver(1)
1019            .build()
1020    }
1021
1022    /// An unpublished registration holds its id and answers routing lookups,
1023    /// but `list_modules` leaves it out and the generation stays put until
1024    /// it is published; publishing lists it and bumps the generation once.
1025    #[test]
1026    fn unpublished_registration_is_unlisted_until_published() {
1027        let registry = Registry::default();
1028        let connection = ConnectionId::new(1);
1029        registry
1030            .register_unpublished_with_control_ops(manifest(), 1, connection, vec![])
1031            .unwrap();
1032        assert_eq!(registry.list_modules().unwrap(), (0, Vec::new()));
1033        assert!(registry.get_module("m").unwrap().is_some());
1034        assert_eq!(registry.list_registered_modules().unwrap().len(), 1);
1035        assert!(registry
1036            .published_registration(RegistrationSlot::Active("m"))
1037            .unwrap()
1038            .is_none());
1039        assert!(matches!(
1040            registry.register_with_control_ops(manifest(), 1, ConnectionId::new(2), vec![]),
1041            Err(RegistryError::DuplicateModuleId { .. })
1042        ));
1043        // A catalog update before publication does not move the generation.
1044        registry
1045            .replace_catalog_for_connection(connection, vec![], None, Some(true))
1046            .unwrap();
1047        assert_eq!(registry.generation().unwrap(), 0);
1048
1049        assert!(registry.publish_registration(connection).unwrap());
1050        let (generation, listed) = registry.list_modules().unwrap();
1051        assert_eq!(generation, 1);
1052        assert_eq!(listed.len(), 1);
1053        assert!(!registry.publish_registration(connection).unwrap());
1054        assert_eq!(registry.generation().unwrap(), 1);
1055    }
1056
1057    /// Removing a registration that was never published leaves no catalog
1058    /// trace: the generation does not move, and a later publish is a no-op.
1059    #[test]
1060    fn deregistering_an_unpublished_registration_leaves_the_generation() {
1061        let registry = Registry::default();
1062        let connection = ConnectionId::new(1);
1063        registry
1064            .register_unpublished_with_control_ops(manifest(), 1, connection, vec![])
1065            .unwrap();
1066        assert_eq!(registry.deregister_connection(connection).unwrap().len(), 1);
1067        assert_eq!(registry.list_modules().unwrap(), (0, Vec::new()));
1068        assert!(!registry.publish_registration(connection).unwrap());
1069        assert_eq!(registry.generation().unwrap(), 0);
1070    }
1071
1072    /// An unpublished candidate holds the candidate slot but
1073    /// `published_registration` does not return it until it is published.
1074    /// Publishing a candidate does not bump the generation: candidates are
1075    /// never listed.
1076    #[test]
1077    fn unpublished_candidate_is_hidden_from_published_lookups() {
1078        let registry = Registry::default();
1079        let candidate = ConnectionId::new(2);
1080        registry
1081            .register_unpublished_candidate_with_control_ops(manifest(), 1, candidate, vec![])
1082            .unwrap();
1083        assert!(registry
1084            .registration(RegistrationSlot::Candidate("m"))
1085            .unwrap()
1086            .is_some());
1087        assert!(registry
1088            .published_registration(RegistrationSlot::Candidate("m"))
1089            .unwrap()
1090            .is_none());
1091        assert!(registry
1092            .published_registration(RegistrationSlot::Connection(candidate))
1093            .unwrap()
1094            .is_none());
1095        assert!(registry.publish_registration(candidate).unwrap());
1096        assert!(registry
1097            .published_registration(RegistrationSlot::Candidate("m"))
1098            .unwrap()
1099            .is_some());
1100        assert_eq!(registry.generation().unwrap(), 0);
1101    }
1102}
1103
1104#[cfg(test)]
1105mod path_hazard_tests {
1106    use super::*;
1107    use crate::ConnectionId;
1108    use subc_protocol::manifest::ModuleManifest;
1109
1110    fn manifest(module_id: &str) -> ModuleManifest {
1111        ModuleManifest::builder(module_id, "0.1.0")
1112            .protocol_ver(1)
1113            .build()
1114    }
1115
1116    #[test]
1117    fn path_hazard_ids_are_refused_and_nothing_registers() {
1118        let registry = Registry::default();
1119        for (bad, reason_fragment) in [
1120            ("../escape", "path separator"),
1121            ("a/b", "path separator"),
1122            ("a\\b", "path separator"),
1123            ("..", "dot path component"),
1124            (".", "dot path component"),
1125            ("", "empty"),
1126            ("evil\u{0}id", "control character"),
1127        ] {
1128            let err = registry
1129                .register_with_control_ops(manifest(bad), 1, ConnectionId::new(7), Vec::new())
1130                .expect_err("path-hazard id must refuse");
1131            // Reason asserted so a predicate throwing the WRONG refusal fails.
1132            assert!(
1133                err.to_string().contains(reason_fragment),
1134                "id {bad:?}: expected {reason_fragment:?} in {err}"
1135            );
1136        }
1137        // THE EFFECT, not just the verdicts: no refusal left a registration
1138        // behind, and the generation never moved.
1139        assert_eq!(registry.active_registration_count().unwrap(), 0);
1140        assert_eq!(registry.generation().unwrap(), 0);
1141    }
1142
1143    #[test]
1144    fn module_id_path_component_length_matches_shared_refusal_vectors() {
1145        let doc: serde_json::Value = serde_json::from_str(include_str!(
1146            "../tests/golden/module_id_path_component_refusals.json"
1147        ))
1148        .expect("refusal fixture parses");
1149
1150        for case in doc["vectors"].as_array().expect("vectors array") {
1151            let name = case["name"].as_str().expect("name");
1152            let module_id = case["module_id"]["unit"]
1153                .as_str()
1154                .expect("module_id unit")
1155                .repeat(
1156                    case["module_id"]["repeat"]
1157                        .as_u64()
1158                        .expect("module_id repeat") as usize,
1159                );
1160            assert_eq!(
1161                module_id.len(),
1162                case["utf8_bytes"].as_u64().expect("utf8 bytes") as usize
1163            );
1164
1165            let expected = case["expect_reason"].as_str().map(str::to_owned);
1166            assert_eq!(
1167                module_id_path_hazard(&module_id).err(),
1168                expected,
1169                "shared refusal vector {name:?} diverged"
1170            );
1171        }
1172    }
1173
1174    #[test]
1175    fn working_id_shapes_register_including_namespace_colons() {
1176        let registry = Registry::default();
1177        for (i, good) in ["magic-context", "mcp:everything", "v1.2-module"]
1178            .iter()
1179            .enumerate()
1180        {
1181            registry
1182                .register_with_control_ops(
1183                    manifest(good),
1184                    1,
1185                    ConnectionId::new(10 + i as u64),
1186                    Vec::new(),
1187                )
1188                .unwrap_or_else(|err| panic!("id {good:?} must register: {err}"));
1189        }
1190        assert_eq!(registry.active_registration_count().unwrap(), 3);
1191    }
1192}
1193
1194#[cfg(test)]
1195mod swap_slot_tests {
1196    use super::*;
1197
1198    fn manifest(module_id: &str, ready: Option<bool>) -> ModuleManifest {
1199        let mut manifest = ModuleManifest::builder(module_id, "0.1.0").build();
1200        manifest.ready = ready;
1201        manifest
1202    }
1203
1204    const INCUMBENT: ConnectionId = ConnectionId(1);
1205    const CANDIDATE: ConnectionId = ConnectionId(2);
1206
1207    fn registry_with_candidate() -> Registry {
1208        let registry = Registry::default();
1209        registry
1210            .register_with_control_ops(manifest("m", None), 1, INCUMBENT, Vec::new())
1211            .unwrap();
1212        registry
1213            .register_candidate_with_control_ops(
1214                manifest("m", Some(false)),
1215                1,
1216                CANDIDATE,
1217                Vec::new(),
1218            )
1219            .unwrap();
1220        registry
1221    }
1222
1223    #[test]
1224    fn candidate_is_invisible_to_by_id_lookups_and_listing() {
1225        let registry = registry_with_candidate();
1226        let generation = registry.generation().unwrap();
1227        assert_eq!(
1228            registry.get_module("m").unwrap().unwrap().connection_id,
1229            INCUMBENT
1230        );
1231        let (listed_generation, listed) = registry.list_modules().unwrap();
1232        assert_eq!(listed.len(), 1);
1233        assert_eq!(listed[0].connection_id, INCUMBENT);
1234        assert_eq!(listed_generation, generation);
1235        assert_eq!(registry.active_registration_count().unwrap(), 1);
1236        assert_eq!(
1237            registry.get_candidate("m").unwrap().unwrap().connection_id,
1238            CANDIDATE
1239        );
1240        assert_eq!(
1241            registry
1242                .register_candidate_with_control_ops(
1243                    manifest("m", None),
1244                    1,
1245                    ConnectionId(3),
1246                    Vec::new()
1247                )
1248                .unwrap_err(),
1249            RegistryError::DuplicateModuleId {
1250                module_id: "m".to_string()
1251            }
1252        );
1253    }
1254
1255    #[test]
1256    fn promoted_candidate_keeps_its_verified_nonce_fact() {
1257        let registry = Registry::default();
1258        registry
1259            .register_unpublished_verified_candidate_with_control_ops(
1260                manifest("m", Some(true)),
1261                1,
1262                CANDIDATE,
1263                Vec::new(),
1264            )
1265            .unwrap();
1266        assert!(registry.publish_registration(CANDIDATE).unwrap());
1267        assert!(registry
1268            .list_modules_with_nonce_verification()
1269            .unwrap()
1270            .1
1271            .is_empty());
1272
1273        registry.promote_candidate("m").unwrap().unwrap();
1274        let (_, modules) = registry.list_modules_with_nonce_verification().unwrap();
1275        assert_eq!(modules.len(), 1);
1276        assert!(modules[0].1);
1277    }
1278
1279    /// Without the candidate slot in the connection-keyed search, this update
1280    /// returns `Ok(None)` and the candidate never becomes ready.
1281    #[test]
1282    fn candidate_catalog_update_reaches_the_candidate_registration() {
1283        let registry = registry_with_candidate();
1284        assert!(!registry.get_candidate("m").unwrap().unwrap().ready);
1285
1286        let updated = registry
1287            .replace_catalog_for_connection(CANDIDATE, Vec::new(), None, Some(true))
1288            .unwrap()
1289            .expect("the candidate's own connection finds its registration");
1290
1291        assert_eq!(updated.connection_id, CANDIDATE);
1292        assert!(registry.get_candidate("m").unwrap().unwrap().ready);
1293        assert_eq!(
1294            registry.get_module_by_connection(CANDIDATE).unwrap(),
1295            Some(updated)
1296        );
1297        assert_eq!(
1298            registry.get_module("m").unwrap().unwrap().connection_id,
1299            INCUMBENT,
1300            "a candidate's update must not touch the active registration"
1301        );
1302    }
1303
1304    #[test]
1305    fn promotion_swaps_slots_and_each_connection_still_deregisters_its_own() {
1306        let registry = registry_with_candidate();
1307        let before = registry.generation().unwrap();
1308        let cutover = registry.promote_candidate("m").unwrap().unwrap();
1309        assert_eq!(cutover.promoted.connection_id, CANDIDATE);
1310        assert_eq!(cutover.superseded.unwrap().connection_id, INCUMBENT);
1311        assert_ne!(registry.generation().unwrap(), before);
1312        assert_eq!(registry.promote_candidate("m").unwrap(), None);
1313
1314        assert_eq!(
1315            registry
1316                .registration(RegistrationSlot::Active("m"))
1317                .unwrap()
1318                .unwrap()
1319                .connection_id,
1320            CANDIDATE
1321        );
1322        assert!(registry
1323            .registration(RegistrationSlot::Candidate("m"))
1324            .unwrap()
1325            .is_none());
1326        assert!(registry
1327            .registration(RegistrationSlot::Connection(INCUMBENT))
1328            .unwrap()
1329            .is_some());
1330
1331        let closed = registry.deregister_connection(INCUMBENT).unwrap();
1332        assert_eq!(closed.len(), 1);
1333        assert_eq!(closed[0].connection_id, INCUMBENT);
1334        assert_eq!(closed[0].state, ChannelState::Closed);
1335        assert!(registry
1336            .registration(RegistrationSlot::Connection(INCUMBENT))
1337            .unwrap()
1338            .is_none());
1339        assert_eq!(
1340            registry.get_module("m").unwrap().unwrap().connection_id,
1341            CANDIDATE
1342        );
1343    }
1344
1345    #[test]
1346    fn a_dropped_candidate_deregisters_from_the_candidate_slot_only() {
1347        let registry = registry_with_candidate();
1348        let closed = registry.deregister_connection(CANDIDATE).unwrap();
1349        assert_eq!(closed.len(), 1);
1350        assert_eq!(closed[0].connection_id, CANDIDATE);
1351        assert!(registry.get_candidate("m").unwrap().is_none());
1352        assert_eq!(
1353            registry.get_module("m").unwrap().unwrap().connection_id,
1354            INCUMBENT
1355        );
1356    }
1357}