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