Skip to main content

subc_daemon/
registry.rs

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