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    /// Skip install if a disconnect removed the unpublished entry. Otherwise
553    /// an install could queue a HELLO_ACK for a registration that cannot publish.
554    /// An install error leaves the registration unpublished. The caller must
555    /// roll it back after this method releases the registry lock. The outer
556    /// result reports registry locking errors; the inner result reports install
557    /// errors or whether the registration was published.
558    pub(crate) fn publish_registration_after<E>(
559        &self,
560        connection_id: ConnectionId,
561        install: impl FnOnce() -> Result<(), E>,
562    ) -> Result<Result<bool, E>, RegistryError> {
563        let mut inner = self.lock_inner()?;
564        if !inner.unpublished.contains(&connection_id)
565            || inner.find_by_connection(connection_id).is_none()
566        {
567            return Ok(Ok(false));
568        }
569        if let Err(err) = install() {
570            return Ok(Err(err));
571        }
572        Ok(Ok(inner.publish_registration(connection_id)))
573    }
574
575    #[cfg(test)]
576    pub(crate) fn hold_lock_for_test(&self, while_locked: impl FnOnce()) {
577        let _hold = self.lock_inner().unwrap();
578        while_locked();
579    }
580
581    #[cfg(test)]
582    pub(crate) fn observe_next_lock_attempt(&self) -> std::sync::mpsc::Receiver<bool> {
583        let (sender, receiver) = std::sync::mpsc::channel();
584        *self.next_lock_attempt.lock().unwrap() = Some(sender);
585        receiver
586    }
587
588    /// Move the candidate for `module_id` into the active slot and demote the
589    /// previous active registration, in one registry critical section.
590    ///
591    /// Returns `Ok(None)` when there is no candidate to promote. Bumps the
592    /// catalog generation, because the listed registration for the id changed.
593    pub fn promote_candidate(
594        &self,
595        module_id: &str,
596    ) -> Result<Option<RegistryCutover>, RegistryError> {
597        let mut inner = self.lock_inner()?;
598        let Some(promoted) = inner.candidates.remove(module_id) else {
599            return Ok(None);
600        };
601        let superseded = inner
602            .modules
603            .insert(module_id.to_string(), promoted.clone());
604        if let Some(superseded) = superseded.clone() {
605            let replaced_connection_id = superseded.connection_id.get();
606            inner
607                .superseded_by
608                .insert(superseded.connection_id, promoted.connection_id);
609            inner.superseded.push(superseded);
610            info!(
611                target: "subc.registry",
612                module_id = %module_id,
613                connection_id = promoted.connection_id.get(),
614                replaced = true,
615                replaced_connection_id,
616                "module registration promoted"
617            );
618        }
619        inner.bump_generation();
620        inner.notify_module_changed(module_id);
621        Ok(Some(RegistryCutover {
622            promoted,
623            superseded,
624        }))
625    }
626
627    /// The ACTIVE registration for `module_id`. Candidates and superseded
628    /// incumbents are never returned: this is the lookup routing decisions use.
629    pub fn get_module(&self, module_id: &str) -> Result<Option<ModuleRegistration>, RegistryError> {
630        Ok(self.lock_inner()?.modules.get(module_id).cloned())
631    }
632
633    pub(crate) fn grants_control_op(
634        &self,
635        module_id: &str,
636        op: &str,
637    ) -> Result<bool, RegistryError> {
638        Ok(self
639            .lock_inner()?
640            .modules
641            .get(module_id)
642            .is_some_and(|registration| {
643                registration.control_ops.iter().any(|granted| granted == op)
644            }))
645    }
646
647    /// Unlike the published-only catalog view, admission sees staged active
648    /// registrations too, exactly as `get_module` does. A target whose
649    /// registration is accepted but not yet published in the catalog must
650    /// answer `target_unavailable`, not `unknown_module`, on an ordinary open.
651    pub(crate) fn route_admission_snapshot(
652        &self,
653    ) -> Result<Arc<RouteAdmissionSnapshot>, RegistryError> {
654        let mut inner = self.lock_inner()?;
655        if let Some(snapshot) = &inner.admission_cache {
656            return Ok(snapshot.clone());
657        }
658        let mut modules = inner
659            .modules
660            .values()
661            .map(|registration| Arc::new(RouteRegistration::from(registration)))
662            .collect::<Vec<_>>();
663        modules.sort_by(|a, b| a.module_id.cmp(&b.module_id));
664        let mut connections: HashMap<_, _> = modules
665            .iter()
666            .map(|registration| (registration.connection_id, registration.clone()))
667            .collect();
668        for registration in inner.candidates.values().chain(inner.superseded.iter()) {
669            connections
670                .entry(registration.connection_id)
671                .or_insert_with(|| Arc::new(RouteRegistration::from(registration)));
672        }
673        let snapshot = Arc::new(RouteAdmissionSnapshot {
674            modules,
675            unpublished: inner.unpublished.clone(),
676            connections,
677        });
678        inner.admission_cache = Some(snapshot.clone());
679        Ok(snapshot)
680    }
681
682    pub(crate) fn route_registration_by_connection(
683        &self,
684        connection: ConnectionId,
685    ) -> Result<Option<Arc<RouteRegistration>>, RegistryError> {
686        Ok(self
687            .route_admission_snapshot()?
688            .connections
689            .get(&connection)
690            .cloned())
691    }
692
693    /// The swap candidate registered for `module_id`, if any.
694    pub fn get_candidate(
695        &self,
696        module_id: &str,
697    ) -> Result<Option<ModuleRegistration>, RegistryError> {
698        Ok(self.lock_inner()?.candidates.get(module_id).cloned())
699    }
700
701    /// The registration held in one specific slot. See [`RegistrationSlot`].
702    pub fn registration(
703        &self,
704        slot: RegistrationSlot<'_>,
705    ) -> Result<Option<ModuleRegistration>, RegistryError> {
706        let inner = self.lock_inner()?;
707        Ok(match slot {
708            RegistrationSlot::Active(module_id) => inner.modules.get(module_id).cloned(),
709            RegistrationSlot::Candidate(module_id) => inner.candidates.get(module_id).cloned(),
710            RegistrationSlot::Connection(connection_id) => inner
711                .find_by_connection(connection_id)
712                .map(|(_, registration)| registration.clone()),
713        })
714    }
715
716    pub fn active_registration_count(&self) -> Result<usize, RegistryError> {
717        Ok(self.lock_inner()?.modules.len())
718    }
719
720    /// The catalog generation and the active registrations `catalog.list`
721    /// shows. Unpublished registrations (see
722    /// [`Self::register_unpublished_with_control_ops`]) are left out.
723    pub fn list_modules(&self) -> Result<(u64, Vec<ModuleRegistration>), RegistryError> {
724        let inner = self.lock_inner()?;
725        let mut modules = inner
726            .modules
727            .values()
728            .filter(|registration| !inner.unpublished.contains(&registration.connection_id))
729            .cloned()
730            .collect::<Vec<_>>();
731        modules.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
732        Ok((inner.generation, modules))
733    }
734
735    /// List published active registrations together with their HELLO nonce-verification status.
736    /// Both values are captured under the registry lock so a concurrent swap or
737    /// disconnect cannot separate a registration from its verification fact.
738    pub fn list_modules_with_nonce_verification(
739        &self,
740    ) -> Result<(u64, Vec<(ModuleRegistration, bool)>), RegistryError> {
741        let inner = self.lock_inner()?;
742        let mut registrations = inner
743            .modules
744            .values()
745            .filter(|registration| !inner.unpublished.contains(&registration.connection_id))
746            .collect::<Vec<_>>();
747        registrations.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
748        let modules = registrations
749            .into_iter()
750            .map(|registration| {
751                (
752                    registration.clone(),
753                    inner.nonce_verified.contains(&registration.connection_id),
754                )
755            })
756            .collect();
757        Ok((inner.generation, modules))
758    }
759
760    /// Every active registration, including unpublished ones.
761    ///
762    /// For the capability evaluator and the capability deny census, which
763    /// count a module as soon as it has registered. Whether `catalog.list`
764    /// shows the module yet does not change their verdicts.
765    pub fn list_registered_modules(&self) -> Result<Vec<ModuleRegistration>, RegistryError> {
766        let inner = self.lock_inner()?;
767        let mut modules = inner.modules.values().cloned().collect::<Vec<_>>();
768        modules.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
769        Ok(modules)
770    }
771
772    /// IDs from the active registration slots, including unpublished ones.
773    pub(crate) fn registered_module_ids(&self) -> Result<BTreeSet<String>, RegistryError> {
774        Ok(self.lock_inner()?.modules.keys().cloned().collect())
775    }
776
777    /// Active config reviewers, even if their catalog entries are not published yet.
778    pub(crate) fn config_review_registrations(
779        &self,
780    ) -> Result<Vec<ConfigReviewRegistration>, RegistryError> {
781        let inner = self.lock_inner()?;
782        let mut registrations: Vec<_> = inner
783            .modules
784            .iter()
785            .filter(|(_, registration)| {
786                registration
787                    .control_ops
788                    .iter()
789                    .any(|op| op == "config.review")
790            })
791            .map(|(module_id, registration)| ConfigReviewRegistration {
792                module_id: module_id.clone(),
793                connection_id: registration.connection_id,
794                negotiated_ver: registration.negotiated_ver,
795            })
796            .collect();
797        registrations.sort_unstable_by(|left, right| left.module_id.cmp(&right.module_id));
798        Ok(registrations)
799    }
800
801    /// Like [`Self::registration`], but a registration that is not published
802    /// yet is reported as absent.
803    pub fn published_registration(
804        &self,
805        slot: RegistrationSlot<'_>,
806    ) -> Result<Option<ModuleRegistration>, RegistryError> {
807        let inner = self.lock_inner()?;
808        let registration = match slot {
809            RegistrationSlot::Active(module_id) => inner.modules.get(module_id),
810            RegistrationSlot::Candidate(module_id) => inner.candidates.get(module_id),
811            RegistrationSlot::Connection(connection_id) => inner
812                .find_by_connection(connection_id)
813                .map(|(_, registration)| registration),
814        };
815        Ok(registration
816            .filter(|registration| !inner.unpublished.contains(&registration.connection_id))
817            .cloned())
818    }
819
820    pub fn generation(&self) -> Result<u64, RegistryError> {
821        Ok(self.lock_inner()?.generation)
822    }
823
824    #[cfg(test)]
825    pub(crate) fn set_module_state_for_test(
826        &self,
827        module_id: &str,
828        state: ChannelState,
829    ) -> Result<bool, RegistryError> {
830        let mut inner = self.lock_inner()?;
831        let Some(registration) = inner.modules.get_mut(module_id) else {
832            return Ok(false);
833        };
834        registration.state = state;
835        inner.notify_module_changed(module_id);
836        Ok(true)
837    }
838
839    /// The registration owned by `connection_id`, searching the active,
840    /// candidate and superseded slots in that order.
841    pub fn get_module_by_connection(
842        &self,
843        connection_id: ConnectionId,
844    ) -> Result<Option<ModuleRegistration>, RegistryError> {
845        Ok(self
846            .lock_inner()?
847            .find_by_connection(connection_id)
848            .map(|(_, registration)| registration.clone()))
849    }
850
851    pub(crate) fn module_id_for_connection(
852        &self,
853        connection_id: ConnectionId,
854    ) -> Result<Option<String>, RegistryError> {
855        Ok(self
856            .lock_inner()?
857            .find_by_connection(connection_id)
858            .map(|(_, registration)| registration.manifest.module_id.clone()))
859    }
860
861    /// Replace only the validated role declarations owned by this connection.
862    pub fn replace_role_declarations_for_connection(
863        &self,
864        connection_id: ConnectionId,
865        role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
866    ) -> Result<Option<ModuleRegistration>, RegistryError> {
867        let mut inner = self.lock_inner()?;
868        let Some((slot, _)) = inner.find_by_connection(connection_id) else {
869            return Ok(None);
870        };
871        let registration = inner
872            .registration_mut(slot, connection_id)
873            .expect("registration discovered under the same registry lock must still exist");
874        registration.manifest.role_declarations = role_declarations;
875        let updated = registration.clone();
876        if matches!(slot, SlotKind::Active) && !inner.unpublished.contains(&connection_id) {
877            inner.bump_generation();
878        }
879        inner.notify_module_changed(&updated.manifest.module_id);
880        Ok(Some(updated))
881    }
882
883    /// Replace the provider role list and, when supplied, the attested capability
884    /// declaration for the module owned by `connection_id`.
885    ///
886    /// Searches every slot: a swap candidate declares itself ready through this
887    /// call, and if only the active slot were searched its update would find
888    /// nothing and the candidate would never become ready. Only a change to the
889    /// active slot bumps the catalog generation, because only the active slot is
890    /// listed, and only once that registration is published.
891    pub fn replace_catalog_for_connection(
892        &self,
893        connection_id: ConnectionId,
894        provides: Vec<ProviderRole>,
895        capabilities: Option<CapabilityDeclarations>,
896        ready: Option<bool>,
897    ) -> Result<Option<ModuleRegistration>, RegistryError> {
898        let mut inner = self.lock_inner()?;
899        let Some((slot, _)) = inner.find_by_connection(connection_id) else {
900            return Ok(None);
901        };
902        let registration = inner
903            .registration_mut(slot, connection_id)
904            .expect("registration discovered under the same registry lock must still exist");
905        if let Some(capabilities) = capabilities.as_ref() {
906            let declares_federated = |caps: Option<&CapabilityDeclarations>| {
907                caps.is_some_and(|caps| {
908                    caps.provides
909                        .iter()
910                        .any(|cap| cap == subc_protocol::scope::SCOPE_FEDERATED_CAPABILITY)
911                })
912            };
913            // Pending binds rely on this declaration while the target module's outbound queue is full.
914            if declares_federated(registration.manifest.capabilities.as_ref())
915                != declares_federated(Some(capabilities))
916            {
917                return Err(RegistryError::FederatedCapabilityChanged);
918            }
919            // Pending binds also decide from this declaration whether to
920            // carry `caller`, so routes bound before and after an update
921            // could otherwise attest differently.
922            let declares_caller = |caps: Option<&CapabilityDeclarations>| {
923                caps.is_some_and(|caps| {
924                    caps.provides
925                        .iter()
926                        .any(|cap| cap == subc_protocol::peer::CALLER_ATTESTATION_CAPABILITY)
927                })
928            };
929            if declares_caller(registration.manifest.capabilities.as_ref())
930                != declares_caller(Some(capabilities))
931            {
932                return Err(RegistryError::CallerAttestationCapabilityChanged);
933            }
934        }
935        registration.manifest.provides = provides;
936        if let Some(capabilities) = capabilities {
937            registration.manifest.capabilities = Some(capabilities);
938        }
939        if let Some(ready) = ready {
940            registration.ready = ready;
941            registration.manifest.ready = Some(ready);
942        }
943        let updated = registration.clone();
944        if matches!(slot, SlotKind::Active) && !inner.unpublished.contains(&connection_id) {
945            inner.bump_generation();
946        }
947        inner.notify_module_changed(&updated.manifest.module_id);
948        Ok(Some(updated))
949    }
950
951    /// Deregister every module owned by a dropped connection, in any slot.
952    pub fn deregister_connection(
953        &self,
954        connection_id: ConnectionId,
955    ) -> Result<Vec<ModuleRegistration>, RegistryError> {
956        self.deregister_connection_with_reason(
957            connection_id,
958            RegistrationEndReason::ConnectionClosed,
959        )
960    }
961
962    pub(crate) fn deregister_connection_with_reason(
963        &self,
964        connection_id: ConnectionId,
965        reason: RegistrationEndReason,
966    ) -> Result<Vec<ModuleRegistration>, RegistryError> {
967        let mut inner = self.lock_inner()?;
968        // A registration that was never published was never listed, so
969        // removing it leaves the catalog, and its generation, as they were.
970        let was_published = !inner.unpublished.remove(&connection_id);
971        let module_ids: Vec<String> = inner
972            .modules
973            .iter()
974            .filter(|(_, registration)| registration.connection_id == connection_id)
975            .map(|(module_id, _)| module_id.clone())
976            .collect();
977
978        let mut closed: Vec<ModuleRegistration> = module_ids
979            .into_iter()
980            .filter_map(|module_id| inner.close_module(&module_id, was_published))
981            .collect();
982
983        let candidate_ids: Vec<String> = inner
984            .candidates
985            .iter()
986            .filter(|(_, registration)| registration.connection_id == connection_id)
987            .map(|(module_id, _)| module_id.clone())
988            .collect();
989        for module_id in candidate_ids {
990            if let Some(mut registration) = inner.candidates.remove(&module_id) {
991                registration.state = ChannelState::Closed;
992                closed.push(registration);
993            }
994        }
995
996        let (removed, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut inner.superseded)
997            .into_iter()
998            .partition(|registration| registration.connection_id == connection_id);
999        let superseded_connections: std::collections::HashSet<_> = removed
1000            .iter()
1001            .map(|registration| registration.connection_id)
1002            .collect();
1003        inner.superseded = kept;
1004        closed.extend(removed.into_iter().map(|mut registration| {
1005            registration.state = ChannelState::Closed;
1006            registration
1007        }));
1008        for registration in &closed {
1009            inner.nonce_verified.remove(&registration.connection_id);
1010            inner.notify_module_changed(&registration.manifest.module_id);
1011            let replaced = superseded_connections.contains(&registration.connection_id);
1012            let end_reason = if replaced {
1013                RegistrationEndReason::Replaced
1014            } else {
1015                reason
1016            };
1017            let replaced_by_connection_id = if replaced {
1018                inner
1019                    .superseded_by
1020                    .remove(&registration.connection_id)
1021                    .map(ConnectionId::get)
1022            } else {
1023                None
1024            };
1025            if let Some(replaced_by_connection_id) = replaced_by_connection_id {
1026                info!(
1027                    target: "subc.registry",
1028                    module_id = %registration.manifest.module_id,
1029                    connection_id = registration.connection_id.get(),
1030                    reason = %end_reason.as_str(),
1031                    replaced_by_connection_id,
1032                    "module registration ended"
1033                );
1034                continue;
1035            }
1036            info!(
1037                target: "subc.registry",
1038                module_id = %registration.manifest.module_id,
1039                connection_id = registration.connection_id.get(),
1040                reason = %end_reason.as_str(),
1041                "module registration ended"
1042            );
1043        }
1044        Ok(closed)
1045    }
1046
1047    fn lock_inner(&self) -> Result<MutexGuard<'_, RegistryInner>, RegistryError> {
1048        #[cfg(test)]
1049        {
1050            let observer = self.next_lock_attempt.lock().unwrap().take();
1051            if let Some(observer) = observer {
1052                // Tell a held-publication test whether its reader acquired the
1053                // lock or must wait. This lets it release publication only after
1054                // the reader actually attempts the lookup, without a timer.
1055                match self.inner.try_lock() {
1056                    Ok(inner) => {
1057                        observer.send(true).unwrap();
1058                        return Ok(inner);
1059                    }
1060                    Err(std::sync::TryLockError::WouldBlock) => observer.send(false).unwrap(),
1061                    Err(std::sync::TryLockError::Poisoned(_)) => {
1062                        return Err(RegistryError::Poisoned);
1063                    }
1064                }
1065            }
1066        }
1067        self.inner.lock().map_err(|_| RegistryError::Poisoned)
1068    }
1069}
1070
1071/// Which internal slot a connection-keyed lookup found its registration in.
1072#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1073enum SlotKind {
1074    Active,
1075    Candidate,
1076    Superseded,
1077}
1078
1079impl RegistryInner {
1080    fn publish_registration(&mut self, connection_id: ConnectionId) -> bool {
1081        if !self.unpublished.remove(&connection_id) {
1082            return false;
1083        }
1084        let Some((slot, registration)) = self.find_by_connection(connection_id) else {
1085            return false;
1086        };
1087        let module_id = registration.manifest.module_id.clone();
1088        if matches!(slot, SlotKind::Active) {
1089            self.bump_generation();
1090        }
1091        self.notify_module_changed(&module_id);
1092        true
1093    }
1094
1095    fn notify_module_changed(&mut self, module_id: &str) {
1096        // Staging, candidate updates and disconnects can change admission facts
1097        // without advancing the published catalog generation.
1098        self.admission_cache = None;
1099        if let Some(sender) = self.module_changes.get(module_id) {
1100            sender.send_modify(|_| {});
1101        }
1102    }
1103
1104    fn find_by_connection(
1105        &self,
1106        connection_id: ConnectionId,
1107    ) -> Option<(SlotKind, &ModuleRegistration)> {
1108        let owned_by =
1109            |registration: &&ModuleRegistration| registration.connection_id == connection_id;
1110        self.modules
1111            .values()
1112            .find(owned_by)
1113            .map(|registration| (SlotKind::Active, registration))
1114            .or_else(|| {
1115                self.candidates
1116                    .values()
1117                    .find(owned_by)
1118                    .map(|registration| (SlotKind::Candidate, registration))
1119            })
1120            .or_else(|| {
1121                self.superseded
1122                    .iter()
1123                    .find(owned_by)
1124                    .map(|registration| (SlotKind::Superseded, registration))
1125            })
1126    }
1127
1128    fn registration_mut(
1129        &mut self,
1130        slot: SlotKind,
1131        connection_id: ConnectionId,
1132    ) -> Option<&mut ModuleRegistration> {
1133        let owned_by =
1134            |registration: &&mut ModuleRegistration| registration.connection_id == connection_id;
1135        match slot {
1136            SlotKind::Active => self.modules.values_mut().find(owned_by),
1137            SlotKind::Candidate => self.candidates.values_mut().find(owned_by),
1138            SlotKind::Superseded => self.superseded.iter_mut().find(owned_by),
1139        }
1140    }
1141
1142    fn close_module(&mut self, module_id: &str, listed: bool) -> Option<ModuleRegistration> {
1143        let mut registration = self.modules.remove(module_id)?;
1144        registration.state = ChannelState::Closed;
1145        if listed {
1146            self.bump_generation();
1147        }
1148        Some(registration)
1149    }
1150
1151    fn bump_generation(&mut self) {
1152        self.admission_cache = None;
1153        self.generation = self.generation.wrapping_add(1);
1154        if let Some(sender) = &self.catalog_changes {
1155            sender.send_replace(self.generation);
1156        }
1157    }
1158}
1159
1160#[derive(Debug, Clone, PartialEq, Eq)]
1161pub enum RegistryError {
1162    FederatedCapabilityChanged,
1163    /// A `catalog.update` tried to add or drop `caller-attestation/v1`, which
1164    /// decides whether binds carry `caller` and so is fixed at HELLO.
1165    CallerAttestationCapabilityChanged,
1166    DuplicateModuleId {
1167        module_id: String,
1168    },
1169    /// The id is unusable as a single path component. Enforced at
1170    /// registration because the daemon MINTS A STORAGE DESCRIPTOR from the
1171    /// self-claimed id verbatim (`<data_home>/cortexkit/<module_id>/store.db`),
1172    /// so an id carrying separators or dot components is a path-traversal or
1173    /// store-collision primitive handed to whoever claims it (issue #32). The
1174    /// derivations deliberately do NOT sanitize instead: sanitizing here would
1175    /// silently re-path every deployed store and desynchronize the Rust and TS
1176    /// derivations, while refusal changes nothing for any id that ever worked.
1177    PathHazardModuleId {
1178        module_id: String,
1179        reason: String,
1180    },
1181    Poisoned,
1182}
1183
1184impl fmt::Display for RegistryError {
1185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1186        match self {
1187            Self::FederatedCapabilityChanged => write!(
1188                f,
1189                "scope-federated/v1 is fixed at HELLO; restart the module to change it"
1190            ),
1191            Self::CallerAttestationCapabilityChanged => write!(
1192                f,
1193                "caller-attestation/v1 is fixed at HELLO; restart the module to change it"
1194            ),
1195            Self::DuplicateModuleId { module_id } => {
1196                write!(f, "module_id '{module_id}' is already registered")
1197            }
1198            Self::PathHazardModuleId { module_id, reason } => {
1199                write!(
1200                    f,
1201                    "module_id '{}' is not usable as a path component: {reason}",
1202                    module_id.escape_debug()
1203                )
1204            }
1205            Self::Poisoned => write!(f, "registry lock was poisoned"),
1206        }
1207    }
1208}
1209
1210impl Error for RegistryError {}
1211
1212/// Why `module_id` cannot serve as a single path component, or `Ok(())`.
1213///
1214/// This is a REFUSAL predicate, not a sanitizer: every currently-working fleet
1215/// id passes untouched, and anything refused here never worked meaningfully --
1216/// it either escaped `<data_home>/cortexkit/` (separators, dot components) or
1217/// aliased another module's store (`a/b` vs `a//b` collapsing on POSIX).
1218/// Colons are allowed: reserved-namespace children (`mcp:...`) register today
1219/// and a colon cannot traverse. Windows path legality is the store library's
1220/// concern, not an identity rule.
1221pub fn module_id_path_hazard(module_id: &str) -> Result<(), String> {
1222    subc_protocol::module_id::module_id_path_hazard(module_id)
1223}
1224
1225#[cfg(test)]
1226mod change_notification_tests {
1227    use super::*;
1228
1229    fn manifest() -> ModuleManifest {
1230        ModuleManifest::builder("watched", "1.0.0")
1231            .protocol_ver(1)
1232            .build()
1233    }
1234
1235    fn changed(receiver: &mut watch::Receiver<u64>) {
1236        assert!(
1237            receiver.has_changed().unwrap(),
1238            "registry write must notify"
1239        );
1240        receiver.borrow_and_update();
1241    }
1242
1243    #[test]
1244    fn every_registration_write_notifies_only_its_module() {
1245        let registry = Registry::default();
1246        let mut events = registry.subscribe_module_changes("watched").unwrap();
1247        let other = registry.subscribe_module_changes("other").unwrap();
1248        let active = ConnectionId::new(1);
1249        let candidate = ConnectionId::new(2);
1250        registry
1251            .register_with_control_ops(manifest(), 1, active, vec![])
1252            .unwrap();
1253        changed(&mut events);
1254        registry
1255            .set_module_state_for_test("watched", ChannelState::Active)
1256            .unwrap();
1257        changed(&mut events);
1258        registry
1259            .replace_catalog_for_connection(active, vec![], None, Some(true))
1260            .unwrap();
1261        changed(&mut events);
1262        registry
1263            .register_candidate_with_control_ops(manifest(), 1, candidate, vec![])
1264            .unwrap();
1265        changed(&mut events);
1266        registry
1267            .replace_catalog_for_connection(candidate, vec![], None, Some(true))
1268            .unwrap();
1269        changed(&mut events);
1270        registry.promote_candidate("watched").unwrap().unwrap();
1271        changed(&mut events);
1272        // Superseded connections can still update and deregister their slot.
1273        registry
1274            .replace_catalog_for_connection(active, vec![], None, Some(false))
1275            .unwrap();
1276        changed(&mut events);
1277        registry.deregister_connection(active).unwrap();
1278        changed(&mut events);
1279        registry.deregister_connection(candidate).unwrap();
1280        changed(&mut events);
1281        registry
1282            .register_candidate_with_control_ops(manifest(), 1, candidate, vec![])
1283            .unwrap();
1284        changed(&mut events);
1285        registry.deregister_connection(candidate).unwrap();
1286        changed(&mut events);
1287        assert!(
1288            !other.has_changed().unwrap(),
1289            "other module must stay parked"
1290        );
1291    }
1292
1293    #[test]
1294    fn subscription_before_read_keeps_a_change_until_waited_on() {
1295        let registry = Registry::default();
1296        let mut events = registry.subscribe_module_changes("watched").unwrap();
1297        assert!(registry.get_module("watched").unwrap().is_none());
1298        registry
1299            .register_with_control_ops(manifest(), 1, ConnectionId::new(1), vec![])
1300            .unwrap();
1301        // Neither a later lookup nor a coalesced catalog update consumes it.
1302        registry.get_module("watched").unwrap().unwrap();
1303        registry
1304            .replace_catalog_for_connection(ConnectionId::new(1), vec![], None, Some(true))
1305            .unwrap();
1306        changed(&mut events);
1307        assert!(!events.has_changed().unwrap());
1308    }
1309}
1310
1311#[cfg(test)]
1312mod publication_tests {
1313    use super::*;
1314
1315    fn manifest() -> ModuleManifest {
1316        ModuleManifest::builder("m", "1.0.0")
1317            .protocol_ver(1)
1318            .build()
1319    }
1320
1321    /// An unpublished registration holds its id and answers routing lookups,
1322    /// but `list_modules` leaves it out and the generation stays put until
1323    /// it is published; publishing lists it and bumps the generation once.
1324    #[test]
1325    fn unpublished_registration_is_unlisted_until_published() {
1326        let registry = Registry::default();
1327        let connection = ConnectionId::new(1);
1328        registry
1329            .register_unpublished_with_control_ops(manifest(), 1, connection, vec![])
1330            .unwrap();
1331        assert_eq!(registry.list_modules().unwrap(), (0, Vec::new()));
1332        assert!(registry.get_module("m").unwrap().is_some());
1333        assert_eq!(registry.list_registered_modules().unwrap().len(), 1);
1334        assert!(registry
1335            .published_registration(RegistrationSlot::Active("m"))
1336            .unwrap()
1337            .is_none());
1338        assert!(matches!(
1339            registry.register_with_control_ops(manifest(), 1, ConnectionId::new(2), vec![]),
1340            Err(RegistryError::DuplicateModuleId { .. })
1341        ));
1342        // A catalog update before publication does not move the generation.
1343        registry
1344            .replace_catalog_for_connection(connection, vec![], None, Some(true))
1345            .unwrap();
1346        assert_eq!(registry.generation().unwrap(), 0);
1347
1348        assert!(registry.publish_registration(connection).unwrap());
1349        let (generation, listed) = registry.list_modules().unwrap();
1350        assert_eq!(generation, 1);
1351        assert_eq!(listed.len(), 1);
1352        assert!(!registry.publish_registration(connection).unwrap());
1353        assert_eq!(registry.generation().unwrap(), 1);
1354    }
1355
1356    /// Removing a registration that was never published leaves no catalog
1357    /// trace: the generation does not move, and a later publish is a no-op.
1358    #[test]
1359    fn deregistering_an_unpublished_registration_leaves_the_generation() {
1360        let registry = Registry::default();
1361        let connection = ConnectionId::new(1);
1362        registry
1363            .register_unpublished_with_control_ops(manifest(), 1, connection, vec![])
1364            .unwrap();
1365        assert_eq!(registry.deregister_connection(connection).unwrap().len(), 1);
1366        assert_eq!(registry.list_modules().unwrap(), (0, Vec::new()));
1367        assert!(!registry.publish_registration(connection).unwrap());
1368        assert_eq!(registry.generation().unwrap(), 0);
1369    }
1370
1371    /// An unpublished candidate holds the candidate slot but
1372    /// `published_registration` does not return it until it is published.
1373    /// Publishing a candidate does not bump the generation: candidates are
1374    /// never listed.
1375    #[test]
1376    fn unpublished_candidate_is_hidden_from_published_lookups() {
1377        let registry = Registry::default();
1378        let candidate = ConnectionId::new(2);
1379        registry
1380            .register_unpublished_candidate_with_control_ops(manifest(), 1, candidate, vec![])
1381            .unwrap();
1382        assert!(registry
1383            .registration(RegistrationSlot::Candidate("m"))
1384            .unwrap()
1385            .is_some());
1386        assert!(registry
1387            .published_registration(RegistrationSlot::Candidate("m"))
1388            .unwrap()
1389            .is_none());
1390        assert!(registry
1391            .published_registration(RegistrationSlot::Connection(candidate))
1392            .unwrap()
1393            .is_none());
1394        assert!(registry.publish_registration(candidate).unwrap());
1395        assert!(registry
1396            .published_registration(RegistrationSlot::Candidate("m"))
1397            .unwrap()
1398            .is_some());
1399        assert_eq!(registry.generation().unwrap(), 0);
1400    }
1401}
1402
1403#[cfg(test)]
1404mod path_hazard_tests {
1405    use super::*;
1406    use crate::ConnectionId;
1407    use subc_protocol::manifest::ModuleManifest;
1408
1409    fn manifest(module_id: &str) -> ModuleManifest {
1410        ModuleManifest::builder(module_id, "0.1.0")
1411            .protocol_ver(1)
1412            .build()
1413    }
1414
1415    #[test]
1416    fn path_hazard_ids_are_refused_and_nothing_registers() {
1417        let registry = Registry::default();
1418        for (bad, reason_fragment) in [
1419            ("../escape", "path separator"),
1420            ("a/b", "path separator"),
1421            ("a\\b", "path separator"),
1422            ("..", "dot path component"),
1423            (".", "dot path component"),
1424            ("", "empty"),
1425            ("evil\u{0}id", "control character"),
1426        ] {
1427            let err = registry
1428                .register_with_control_ops(manifest(bad), 1, ConnectionId::new(7), Vec::new())
1429                .expect_err("path-hazard id must refuse");
1430            // Reason asserted so a predicate throwing the WRONG refusal fails.
1431            assert!(
1432                err.to_string().contains(reason_fragment),
1433                "id {bad:?}: expected {reason_fragment:?} in {err}"
1434            );
1435        }
1436        // THE EFFECT, not just the verdicts: no refusal left a registration
1437        // behind, and the generation never moved.
1438        assert_eq!(registry.active_registration_count().unwrap(), 0);
1439        assert_eq!(registry.generation().unwrap(), 0);
1440    }
1441
1442    #[test]
1443    fn module_id_path_component_length_matches_shared_refusal_vectors() {
1444        let doc: serde_json::Value = serde_json::from_str(include_str!(
1445            "../tests/golden/module_id_path_component_refusals.json"
1446        ))
1447        .expect("refusal fixture parses");
1448
1449        for case in doc["vectors"].as_array().expect("vectors array") {
1450            let name = case["name"].as_str().expect("name");
1451            let module_id = case["module_id"]["unit"]
1452                .as_str()
1453                .expect("module_id unit")
1454                .repeat(
1455                    case["module_id"]["repeat"]
1456                        .as_u64()
1457                        .expect("module_id repeat") as usize,
1458                );
1459            assert_eq!(
1460                module_id.len(),
1461                case["utf8_bytes"].as_u64().expect("utf8 bytes") as usize
1462            );
1463
1464            let expected = case["expect_reason"].as_str().map(str::to_owned);
1465            assert_eq!(
1466                module_id_path_hazard(&module_id).err(),
1467                expected,
1468                "shared refusal vector {name:?} diverged"
1469            );
1470        }
1471    }
1472
1473    #[test]
1474    fn working_id_shapes_register_including_namespace_colons() {
1475        let registry = Registry::default();
1476        for (i, good) in ["magic-context", "mcp:everything", "v1.2-module"]
1477            .iter()
1478            .enumerate()
1479        {
1480            registry
1481                .register_with_control_ops(
1482                    manifest(good),
1483                    1,
1484                    ConnectionId::new(10 + i as u64),
1485                    Vec::new(),
1486                )
1487                .unwrap_or_else(|err| panic!("id {good:?} must register: {err}"));
1488        }
1489        assert_eq!(registry.active_registration_count().unwrap(), 3);
1490    }
1491}
1492
1493#[cfg(test)]
1494mod swap_slot_tests {
1495    use super::*;
1496
1497    fn manifest(module_id: &str, ready: Option<bool>) -> ModuleManifest {
1498        let mut manifest = ModuleManifest::builder(module_id, "0.1.0").build();
1499        manifest.ready = ready;
1500        manifest
1501    }
1502
1503    const INCUMBENT: ConnectionId = ConnectionId(1);
1504    const CANDIDATE: ConnectionId = ConnectionId(2);
1505
1506    fn registry_with_candidate() -> Registry {
1507        let registry = Registry::default();
1508        registry
1509            .register_with_control_ops(manifest("m", None), 1, INCUMBENT, Vec::new())
1510            .unwrap();
1511        registry
1512            .register_candidate_with_control_ops(
1513                manifest("m", Some(false)),
1514                1,
1515                CANDIDATE,
1516                Vec::new(),
1517            )
1518            .unwrap();
1519        registry
1520    }
1521
1522    #[test]
1523    fn candidate_is_invisible_to_by_id_lookups_and_listing() {
1524        let registry = registry_with_candidate();
1525        let generation = registry.generation().unwrap();
1526        assert_eq!(
1527            registry.get_module("m").unwrap().unwrap().connection_id,
1528            INCUMBENT
1529        );
1530        let (listed_generation, listed) = registry.list_modules().unwrap();
1531        assert_eq!(listed.len(), 1);
1532        assert_eq!(listed[0].connection_id, INCUMBENT);
1533        assert_eq!(listed_generation, generation);
1534        assert_eq!(registry.active_registration_count().unwrap(), 1);
1535        assert_eq!(
1536            registry.get_candidate("m").unwrap().unwrap().connection_id,
1537            CANDIDATE
1538        );
1539        assert_eq!(
1540            registry
1541                .register_candidate_with_control_ops(
1542                    manifest("m", None),
1543                    1,
1544                    ConnectionId(3),
1545                    Vec::new()
1546                )
1547                .unwrap_err(),
1548            RegistryError::DuplicateModuleId {
1549                module_id: "m".to_string()
1550            }
1551        );
1552    }
1553
1554    #[test]
1555    fn promoted_candidate_keeps_its_verified_nonce_fact() {
1556        let registry = Registry::default();
1557        registry
1558            .register_unpublished_verified_candidate_with_control_ops(
1559                manifest("m", Some(true)),
1560                1,
1561                CANDIDATE,
1562                Vec::new(),
1563            )
1564            .unwrap();
1565        assert!(registry.publish_registration(CANDIDATE).unwrap());
1566        assert!(registry
1567            .list_modules_with_nonce_verification()
1568            .unwrap()
1569            .1
1570            .is_empty());
1571
1572        registry.promote_candidate("m").unwrap().unwrap();
1573        let (_, modules) = registry.list_modules_with_nonce_verification().unwrap();
1574        assert_eq!(modules.len(), 1);
1575        assert!(modules[0].1);
1576    }
1577
1578    /// Without the candidate slot in the connection-keyed search, this update
1579    /// returns `Ok(None)` and the candidate never becomes ready.
1580    #[test]
1581    fn candidate_catalog_update_reaches_the_candidate_registration() {
1582        let registry = registry_with_candidate();
1583        assert!(!registry.get_candidate("m").unwrap().unwrap().ready);
1584
1585        let updated = registry
1586            .replace_catalog_for_connection(CANDIDATE, Vec::new(), None, Some(true))
1587            .unwrap()
1588            .expect("the candidate's own connection finds its registration");
1589
1590        assert_eq!(updated.connection_id, CANDIDATE);
1591        assert!(registry.get_candidate("m").unwrap().unwrap().ready);
1592        assert_eq!(
1593            registry.get_module_by_connection(CANDIDATE).unwrap(),
1594            Some(updated)
1595        );
1596        assert_eq!(
1597            registry.get_module("m").unwrap().unwrap().connection_id,
1598            INCUMBENT,
1599            "a candidate's update must not touch the active registration"
1600        );
1601    }
1602
1603    #[test]
1604    fn promotion_swaps_slots_and_each_connection_still_deregisters_its_own() {
1605        let registry = registry_with_candidate();
1606        let before = registry.generation().unwrap();
1607        let cutover = registry.promote_candidate("m").unwrap().unwrap();
1608        assert_eq!(cutover.promoted.connection_id, CANDIDATE);
1609        assert_eq!(cutover.superseded.unwrap().connection_id, INCUMBENT);
1610        assert_ne!(registry.generation().unwrap(), before);
1611        assert_eq!(registry.promote_candidate("m").unwrap(), None);
1612
1613        assert_eq!(
1614            registry
1615                .registration(RegistrationSlot::Active("m"))
1616                .unwrap()
1617                .unwrap()
1618                .connection_id,
1619            CANDIDATE
1620        );
1621        assert!(registry
1622            .registration(RegistrationSlot::Candidate("m"))
1623            .unwrap()
1624            .is_none());
1625        assert!(registry
1626            .registration(RegistrationSlot::Connection(INCUMBENT))
1627            .unwrap()
1628            .is_some());
1629
1630        let closed = registry.deregister_connection(INCUMBENT).unwrap();
1631        assert_eq!(closed.len(), 1);
1632        assert_eq!(closed[0].connection_id, INCUMBENT);
1633        assert_eq!(closed[0].state, ChannelState::Closed);
1634        assert!(registry
1635            .registration(RegistrationSlot::Connection(INCUMBENT))
1636            .unwrap()
1637            .is_none());
1638        assert_eq!(
1639            registry.get_module("m").unwrap().unwrap().connection_id,
1640            CANDIDATE
1641        );
1642    }
1643
1644    #[test]
1645    fn a_dropped_candidate_deregisters_from_the_candidate_slot_only() {
1646        let registry = registry_with_candidate();
1647        let closed = registry.deregister_connection(CANDIDATE).unwrap();
1648        assert_eq!(closed.len(), 1);
1649        assert_eq!(closed[0].connection_id, CANDIDATE);
1650        assert!(registry.get_candidate("m").unwrap().is_none());
1651        assert_eq!(
1652            registry.get_module("m").unwrap().unwrap().connection_id,
1653            INCUMBENT
1654        );
1655    }
1656}