Skip to main content

subc_daemon/supervise/
registration.rs

1//! Per-launch registration, tracked separately from nonce checks keyed by module ID.
2//! Locks only protect snapshots; neither service nor launch waits hold them.
3
4#[cfg(test)]
5#[path = "registration_read_tests.rs"]
6mod read_tests;
7#[cfg(all(test, target_os = "linux"))]
8#[path = "retirement_tests.rs"]
9mod retirement_tests;
10#[cfg(all(test, unix))]
11#[path = "registration_review_tests.rs"]
12mod review_tests;
13
14use super::*;
15use std::collections::BTreeSet;
16use std::sync::{
17    atomic::{AtomicBool, Ordering},
18    Weak,
19};
20
21/// The refusal code for any registration operation that reaches a spawn whose
22/// exit has been observed. Terminal: the channel never carries authority again.
23pub(crate) const REGISTRATION_CHANNEL_CLOSED: &str = "registration_channel_closed";
24
25/// What a consumer's launch nonce attests, from
26/// [`SupervisorHandle::attest_spawned_consumer`].
27#[derive(Debug)]
28pub(crate) enum NonceAttestation {
29    /// The nonce does not attest the module, or the launch it was minted for
30    /// had an authority record that is gone.
31    Refused,
32    /// The nonce attests the module and no launch was ever recorded for it,
33    /// so the consumer is the module with no spawn record behind it.
34    Unrecorded,
35    /// The nonce attests the module through this launch's record.
36    Spawn(Arc<crate::spawn_authority::SpawnAuthorityRecord>),
37}
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40enum LaunchState {
41    Pending,
42    Ready,
43    Dead,
44}
45
46#[cfg(test)]
47#[derive(Debug)]
48struct RetirementPause {
49    reached: tokio::sync::oneshot::Sender<()>,
50    release: std::sync::mpsc::Receiver<()>,
51}
52
53#[derive(Debug)]
54pub(crate) struct RegistrationSpawn {
55    pub(crate) incarnation: String,
56    pub(super) binding_key: program_binding::ProgramBindingKey,
57    pub(crate) claims: std::sync::OnceLock<Arc<crate::control::claims::LaunchClaims>>,
58    pub(crate) module_id: String,
59    /// This launch's authority record, created with it. It dies in the same
60    /// retirement step that ends the channel and voids the claims.
61    pub(crate) authority: Arc<crate::spawn_authority::SpawnAuthorityRecord>,
62    pub(super) role: SpawnRole,
63    hello_seen: AtomicBool,
64    registered: AtomicBool,
65    nonce_registered: AtomicBool,
66    deadline: std::sync::OnceLock<Instant>,
67    launch: tokio::sync::watch::Sender<LaunchState>,
68    transition: Mutex<()>,
69    primary_sink: Mutex<Option<crate::FrameSink>>,
70    #[cfg(test)]
71    retirement_pause: Mutex<Option<RetirementPause>>,
72    #[cfg(unix)]
73    endpoint: Mutex<Option<std::os::unix::net::UnixStream>>,
74    #[cfg(windows)]
75    endpoint: Mutex<Option<subc_os::registration_channel::RegistrationPipeShutdown>>,
76    binding: Option<ProgramBindingPublication>,
77    requires_binding: bool,
78    pub(super) identity: std::sync::OnceLock<ProcessIdentity>,
79    connections: Weak<Mutex<HashMap<ConnectionId, Arc<RegistrationSpawn>>>>,
80}
81
82impl RegistrationSpawn {
83    #[cfg(all(test, unix))]
84    pub(crate) fn set_content_probe_for_test(&self, probe: content_binding::ContentProbe) {
85        self.binding.as_ref().unwrap().set_content_probe(probe);
86    }
87    #[cfg(all(test, unix))]
88    pub(crate) fn defer_content_kill_for_test(&self) -> impl Drop {
89        self.binding.as_ref().unwrap().defer_content_kill_for_test()
90    }
91
92    #[cfg(all(test, unix))]
93    pub(crate) fn content_was_refused_for_test(&self) -> bool {
94        self.binding.as_ref().unwrap().content_was_refused()
95    }
96    #[cfg(test)]
97    pub(super) fn new(
98        handle: &SupervisorHandle,
99        module: &str,
100        role: SpawnRole,
101        binding: Option<ProgramBindingPublication>,
102    ) -> Arc<Self> {
103        let required = binding.is_some();
104        Self::new_with_binding_requirement(handle, module, role, binding, required)
105    }
106
107    pub(super) fn new_with_binding_requirement(
108        handle: &SupervisorHandle,
109        module: &str,
110        role: SpawnRole,
111        binding: Option<ProgramBindingPublication>,
112        requires_binding: bool,
113    ) -> Arc<Self> {
114        let (launch, _) = tokio::sync::watch::channel(LaunchState::Pending);
115        let binding_key = binding
116            .as_ref()
117            .map(|binding| binding.channel_key())
118            .unwrap_or_else(|| program_binding::ProgramBindingKey::new(handle));
119        // The spawn generation names this launch from now on, so a candidate
120        // that registers and opens routes before cutover attests the same
121        // number it keeps after promotion.
122        let (incarnation, generation) = handle.spawn_events.allocate_generation(module);
123        let spawn = Arc::new(Self {
124            incarnation: binding_key.incarnation.clone(),
125            binding_key,
126            claims: std::sync::OnceLock::new(),
127            module_id: module.into(),
128            authority: crate::spawn_authority::SpawnAuthorityRecord::new(
129                incarnation,
130                generation,
131                module,
132            ),
133            role,
134            hello_seen: AtomicBool::new(false),
135            registered: AtomicBool::new(false),
136            nonce_registered: AtomicBool::new(false),
137            deadline: std::sync::OnceLock::new(),
138            launch,
139            transition: Mutex::new(()),
140            primary_sink: Mutex::new(None),
141            #[cfg(test)]
142            retirement_pause: Mutex::new(None),
143            #[cfg(any(unix, windows))]
144            endpoint: Mutex::new(None),
145            binding,
146            requires_binding,
147            identity: std::sync::OnceLock::new(),
148            connections: Arc::downgrade(&handle.registration_connections),
149        });
150        if let Some(binding) = &spawn.binding {
151            binding.attach_registration(&spawn);
152        }
153        let mut launches = handle
154            .registration_launches
155            .lock()
156            .unwrap_or_else(|p| p.into_inner());
157        launches.retain(|launch| launch.strong_count() != 0);
158        launches.push(Arc::downgrade(&spawn));
159        spawn
160    }
161
162    pub(crate) fn bind(self: &Arc<Self>, connection: ConnectionId) {
163        if let Some(connections) = self.connections.upgrade() {
164            connections
165                .lock()
166                .unwrap_or_else(|p| p.into_inner())
167                .insert(connection, self.clone());
168        }
169    }
170
171    pub(super) fn ready(&self) {
172        self.launch.send_if_modified(|state| {
173            if *state == LaunchState::Pending {
174                *state = LaunchState::Ready;
175                true
176            } else {
177                false
178            }
179        });
180    }
181    pub(super) fn refuse(&self) {
182        self.retire();
183    }
184    /// The one retirement step, run at the first exit observation (and when
185    /// the launch is refused or its primary registration ends): the authority
186    /// record dies, the claims are voided, the channel is shut and the epoch
187    /// is bumped, synchronously and before the caller's next await.
188    pub(crate) fn retire(&self) {
189        self.retire_transition(
190            self.transition.lock().unwrap_or_else(|p| p.into_inner()),
191            true,
192        );
193    }
194
195    /// End the inherited transport without ending a legacy launch that may
196    /// still register by nonce. Once a child registers here, or the gate
197    /// requires this channel to bind registration to its admitted executable,
198    /// losing the transport ends its authority.
199    pub(crate) fn retire_registration_channel(&self) {
200        let transition = self.transition.lock().unwrap_or_else(|p| p.into_inner());
201        if !self.nonce_registered.load(Ordering::Acquire) {
202            self.retire_transition(transition, self.registered() || self.requires_binding);
203        }
204    }
205
206    // HELLO publication holds the transition guard, so retirement cannot miss
207    // the primary sink or race a replacement into this slot after Dead.
208    pub(crate) fn bind_primary_sink(&self, sink: crate::FrameSink) {
209        *self.primary_sink.lock().unwrap_or_else(|p| p.into_inner()) = Some(sink);
210    }
211
212    pub(crate) fn end_primary_registration(&self) {
213        let _transition = self.transition.lock().unwrap_or_else(|p| p.into_inner());
214        if let Some(claims) = self.claims.get() {
215            claims.end_primary_registration();
216        }
217    }
218
219    fn retire_unused(&self) {
220        let transition = self.transition.lock().unwrap_or_else(|p| p.into_inner());
221        if !self.registered() {
222            self.nonce_registered.store(true, Ordering::Release);
223            // The spawn registered by nonce instead: only its unused channel
224            // ends. Its authority record stays live for its nonce consumers.
225            self.retire_transition(transition, false);
226        }
227    }
228
229    fn retire_transition(&self, transition: std::sync::MutexGuard<'_, ()>, ends_authority: bool) {
230        let revoked;
231        // Marking the record dead comes first; dropping the fence at the end
232        // of this block bumps its epoch after the claims and channel ended.
233        let authority_fence = ends_authority
234            .then(|| self.authority.begin_retirement())
235            .flatten();
236        {
237            if *self.launch.borrow() == LaunchState::Dead {
238                return;
239            }
240            self.launch.send_replace(LaunchState::Dead);
241            if let Some(primary) = self
242                .primary_sink
243                .lock()
244                .unwrap_or_else(|p| p.into_inner())
245                .take()
246            {
247                primary.terminate_ingress();
248                primary.terminate_egress();
249            }
250            revoked = self.claims.get().map(|claims| claims.revoke());
251            #[cfg(any(unix, windows))]
252            if let Some(endpoint) = self
253                .endpoint
254                .lock()
255                .unwrap_or_else(|p| p.into_inner())
256                .take()
257            {
258                #[cfg(unix)]
259                let _ = endpoint.shutdown(std::net::Shutdown::Both);
260                #[cfg(windows)]
261                endpoint.shutdown();
262            }
263        }
264        drop(authority_fence);
265        drop(transition);
266        #[cfg(test)]
267        if let Some(pause) = self.retirement_pause.lock().unwrap().take() {
268            let _ = pause.reached.send(());
269            let _ = pause.release.recv_timeout(Duration::from_secs(5));
270        }
271        if let (Some(claims), Some(revoked)) = (self.claims.get(), revoked) {
272            claims.close_revoked(revoked);
273        }
274        if let Some(binding) = &self.binding {
275            binding.retire();
276        }
277    }
278
279    pub(crate) async fn wait_launch(&self) {
280        let mut state = self.launch.subscribe();
281        while *state.borrow_and_update() == LaunchState::Pending {
282            if state.changed().await.is_err() {
283                break;
284            }
285        }
286    }
287
288    pub(crate) fn launch_ready(&self) -> bool {
289        *self.launch.borrow() == LaunchState::Ready
290    }
291
292    pub(crate) fn deadline(&self) -> Instant {
293        *self
294            .deadline
295            .get()
296            .expect("served registration has a spawn deadline")
297    }
298
299    pub(crate) fn registered(&self) -> bool {
300        self.registered.load(Ordering::Acquire)
301    }
302
303    /// Serialize the registry/forwarding publication with synchronous retirement.
304    /// Image verification happens before this lock; only snapshot writes follow it.
305    pub(crate) fn begin_publication(&self) -> Result<std::sync::MutexGuard<'_, ()>, &'static str> {
306        let guard = self.transition.lock().unwrap_or_else(|p| p.into_inner());
307        if !self.launch_ready() {
308            return Err(REGISTRATION_CHANNEL_CLOSED);
309        }
310        Ok(guard)
311    }
312
313    pub(crate) async fn registration_expired(&self) {
314        tokio::time::sleep_until(self.deadline()).await;
315        if self.registered.load(Ordering::Acquire) {
316            std::future::pending::<()>().await;
317        }
318    }
319
320    pub(crate) async fn wait_closed(&self) {
321        let mut state = self.launch.subscribe();
322        loop {
323            if matches!(*state.borrow_and_update(), LaunchState::Dead) {
324                return;
325            }
326            if state.changed().await.is_err() {
327                return;
328            }
329        }
330    }
331
332    pub(crate) async fn wait_registration_failure(&self) {
333        // A launch without a required program binding can still register by
334        // nonce through an older SDK. Closing its unused channel is not a
335        // registration failure.
336        if !self.requires_binding {
337            std::future::pending::<()>().await;
338        }
339        self.wait_closed().await;
340        if self.registered() || self.nonce_registered.load(Ordering::Acquire) {
341            std::future::pending::<()>().await;
342        }
343    }
344
345    pub(crate) fn admit_hello(&self, module: Option<&str>) -> Result<(), &'static str> {
346        if self.hello_seen.swap(true, Ordering::AcqRel) {
347            return Err("registration_channel_hello_repeated");
348        }
349        if module != Some(self.module_id.as_str()) {
350            return Err("registration_channel_module_mismatch");
351        }
352        self.check()
353    }
354
355    pub(crate) fn check(&self) -> Result<(), &'static str> {
356        self.check_state()?;
357        if self
358            .binding
359            .as_ref()
360            .is_some_and(|binding| binding.check().is_err())
361        {
362            return Err("program_refused");
363        }
364        Ok(())
365    }
366
367    fn verdict(&self) -> Result<(), &'static str> {
368        self.check_state()?;
369        if self
370            .binding
371            .as_ref()
372            .is_some_and(|binding| binding.verdict().is_err())
373        {
374            return Err("program_refused");
375        }
376        self.check_state()
377    }
378
379    fn check_state(&self) -> Result<(), &'static str> {
380        match *self.launch.borrow() {
381            LaunchState::Dead => return Err(REGISTRATION_CHANNEL_CLOSED),
382            LaunchState::Pending => return Err("config_delivery_deferred"),
383            LaunchState::Ready => {}
384        }
385        if self.requires_binding && self.binding.is_none() {
386            return Err("program_refused");
387        }
388        Ok(())
389    }
390
391    pub(crate) fn has_program_binding(&self) -> bool {
392        self.binding.is_some()
393    }
394
395    pub(crate) fn is_candidate(&self) -> bool {
396        self.role == SpawnRole::SwapCandidate
397    }
398
399    pub(crate) fn hello_accepted(&self) {
400        self.registered.store(true, Ordering::Release);
401        #[cfg(windows)]
402        if let Some(binding) = &self.binding {
403            binding.hello_accepted();
404        }
405    }
406}
407
408#[derive(Debug, Clone)]
409pub(crate) struct RegistrationService {
410    router: Weak<crate::Router>,
411    auth: crate::server::ServerAuth,
412}
413
414impl SupervisorHandle {
415    /// Includes warming and not-yet-registered launches, not just the active slot.
416    pub(crate) fn spawn_authority_records_for_module(
417        &self,
418        module: &str,
419    ) -> Vec<Arc<crate::spawn_authority::SpawnAuthorityRecord>> {
420        self.registration_launches
421            .lock()
422            .unwrap_or_else(|p| p.into_inner())
423            .iter()
424            .filter_map(Weak::upgrade)
425            .filter(|spawn| spawn.module_id == module)
426            .map(|spawn| spawn.authority.clone())
427            .collect()
428    }
429    /// The daemon incarnation spawn generations and authority records belong to.
430    pub(crate) fn daemon_incarnation(&self) -> String {
431        self.spawn_events
432            .0
433            .lock()
434            .unwrap_or_else(|p| p.into_inner())
435            .daemon_incarnation
436            .clone()
437    }
438
439    /// Remember which launch the nonce just minted for `spawn` belongs to. A
440    /// launch that received no nonce (a gated, channel-only launch) records
441    /// nothing.
442    pub(super) fn record_nonce_launch(&self, spawn: &Arc<RegistrationSpawn>) {
443        let nonce = match spawn.role {
444            SpawnRole::Plain => self
445                .spawn_nonces
446                .lock()
447                .unwrap_or_else(|p| p.into_inner())
448                .get(&spawn.module_id)
449                .cloned(),
450            SpawnRole::SwapCandidate => self
451                .swaps
452                .lock()
453                .unwrap_or_else(|p| p.into_inner())
454                .get(&spawn.module_id)
455                .map(|swap| swap.candidate_nonce.clone()),
456        };
457        let Some(nonce) = nonce.filter(|nonce| !nonce.is_empty()) else {
458            return;
459        };
460        let current = self.current_launch_nonces();
461        let mut launches = self
462            .nonce_launches
463            .lock()
464            .unwrap_or_else(|p| p.into_inner());
465        launches.retain(|nonce, (_, launch)| launch.strong_count() != 0 || current.contains(nonce));
466        launches.insert(nonce, (spawn.module_id.clone(), Arc::downgrade(spawn)));
467    }
468
469    /// Every nonce that can still authorize a consumer: each module's recorded
470    /// spawn nonce and both nonces of each open swap.
471    fn current_launch_nonces(&self) -> std::collections::HashSet<String> {
472        let mut current = self
473            .spawn_nonces
474            .lock()
475            .unwrap_or_else(|p| p.into_inner())
476            .values()
477            .cloned()
478            .collect::<std::collections::HashSet<_>>();
479        for swap in self
480            .swaps
481            .lock()
482            .unwrap_or_else(|p| p.into_inner())
483            .values()
484        {
485            current.insert(swap.candidate_nonce.clone());
486            current.extend(swap.incumbent_nonce.clone());
487        }
488        current
489    }
490
491    /// What a consumer presenting `presented` as `module_id`'s launch nonce
492    /// attests, decided in one step: the launch the nonce was minted for is
493    /// resolved first and held, then the nonce is authorized exactly as
494    /// `spawned_consumer_authorized` decides. A launch that ends, or a nonce
495    /// that is withdrawn, after that step is caught later by the record's own
496    /// liveness, never turned into a principal with no record.
497    pub(crate) fn attest_spawned_consumer(
498        &self,
499        module_id: &str,
500        presented: &str,
501    ) -> NonceAttestation {
502        let recorded = self
503            .nonce_launches
504            .lock()
505            .unwrap_or_else(|p| p.into_inner())
506            .get(presented)
507            .map(|(module, launch)| (module.clone(), launch.upgrade()));
508        if !self.spawned_consumer_authorized(module_id, presented) {
509            return NonceAttestation::Refused;
510        }
511        match recorded {
512            // No launch was ever recorded for this nonce: the legacy launch
513            // nonce with no registration spawn behind it.
514            None => NonceAttestation::Unrecorded,
515            Some((module, Some(spawn))) if module == module_id => {
516                NonceAttestation::Spawn(spawn.authority.clone())
517            }
518            // The nonce's launch had a record and it is gone, or the launch
519            // belongs to another module. Either way the record that would
520            // fence this consumer is not there, so it attests nothing.
521            Some(_) => NonceAttestation::Refused,
522        }
523    }
524
525    /// The authority record of the launch whose nonce `presented` is, when it
526    /// still attests `module_id` exactly as `spawned_consumer_authorized`
527    /// decides. `None` for an unknown, superseded or gated nonce.
528    pub(crate) fn spawned_consumer_record(
529        &self,
530        module_id: &str,
531        presented: &str,
532    ) -> Option<Arc<crate::spawn_authority::SpawnAuthorityRecord>> {
533        match self.attest_spawned_consumer(module_id, presented) {
534            NonceAttestation::Spawn(record) => Some(record),
535            NonceAttestation::Unrecorded | NonceAttestation::Refused => None,
536        }
537    }
538
539    pub(crate) fn retire_unused_registration_channel(&self, module: &str, candidate: bool) {
540        // Successful registration claims the id even when legacy policy did
541        // not require a nonce. Resolve its unused endpoint from our launch
542        // history, not a credential supplied by that registration.
543        let launch = self
544            .registration_launches
545            .lock()
546            .unwrap_or_else(|p| p.into_inner())
547            .iter()
548            .rev()
549            .filter_map(Weak::upgrade)
550            .find(|spawn| spawn.module_id == module && spawn.is_candidate() == candidate);
551        if let Some(launch) = launch {
552            launch.retire_unused();
553        }
554    }
555    #[cfg(test)]
556    pub(crate) fn capture_registration_channels_for_test(&self) {
557        *self.registration_test_channels.lock().unwrap() = Some(Vec::new());
558    }
559
560    #[cfg(test)]
561    pub(crate) fn registration_for_test(&self, module: &str) -> Option<Arc<RegistrationSpawn>> {
562        self.registration_test_channels
563            .lock()
564            .unwrap()
565            .as_ref()?
566            .iter()
567            .rev()
568            .find(|(spawn, _)| spawn.module_id == module)
569            .map(|(spawn, _)| spawn.clone())
570    }
571
572    #[cfg(test)]
573    pub(crate) fn registration_proof_for_test(&self, module: &str) -> Option<RegistrationProof> {
574        let Some(channel) = self.registration_for_test(module) else {
575            return self.spawn_nonce(module).map(Into::into);
576        };
577        Some(RegistrationProof {
578            key: channel
579                .binding
580                .as_ref()
581                .map(|binding| binding.key_for_test())
582                .unwrap_or_else(|| format!("channel-fixture:{:p}", Arc::as_ptr(&channel))),
583            channel: Some(channel),
584        })
585    }
586
587    #[cfg(test)]
588    pub(crate) fn candidate_registration_proof_for_test(
589        &self,
590        module: &str,
591    ) -> Option<RegistrationProof> {
592        let channel = self.registration_for_test(module)?;
593        if !channel.is_candidate() {
594            return None;
595        }
596        Some(RegistrationProof {
597            key: channel.binding.as_ref()?.key_for_test(),
598            channel: Some(channel),
599        })
600    }
601    /// Both proofs name the registration connection, not merely its module ID.
602    /// A process birth identity ties a channel to the current launch snapshot,
603    /// excluding candidates before promotion and incumbents after promotion.
604    pub(crate) fn registration_is_current_live(
605        &self,
606        registry: &Registry,
607        module: &str,
608        connection: ConnectionId,
609        nonce: Option<&str>,
610    ) -> bool {
611        if !self.registration_snapshot_is_current_live(registry, module, connection, nonce) {
612            return false;
613        }
614        if self
615            .registration_spawn(connection)
616            .is_some_and(|spawn| spawn.verdict().is_err())
617        {
618            return false;
619        }
620        self.registration_snapshot_is_current_live(registry, module, connection, nonce)
621    }
622
623    pub(crate) fn registration_snapshot_is_current_live(
624        &self,
625        registry: &Registry,
626        module: &str,
627        connection: ConnectionId,
628        nonce: Option<&str>,
629    ) -> bool {
630        if !registry
631            .get_module(module)
632            .ok()
633            .flatten()
634            .is_some_and(|registration| registration.connection_id == connection)
635        {
636            return false;
637        }
638        let Some(child) = self.get(module) else {
639            return false;
640        };
641        let Some(launch) = child.resource_launch() else {
642            return false;
643        };
644        if !launch.enabled || !launch.alive {
645            return false;
646        }
647        if let Some(spawn) = self.registration_spawn(connection) {
648            return spawn.module_id == module
649                && spawn.check_state().is_ok()
650                && (!self.module_is_gated(module) || spawn.has_program_binding())
651                && spawn.identity.get().is_some_and(|identity| {
652                    launch.pid == Some(identity.pid) && launch.start == Some(identity.start_time)
653                });
654        }
655        if self.module_is_gated(module) {
656            return false;
657        }
658        nonce.is_some_and(|presented| {
659            self.spawn_nonce(module).is_some_and(|current| {
660                !presented.is_empty() && constant_time_eq(current.as_bytes(), presented.as_bytes())
661            })
662        })
663    }
664
665    pub(crate) fn install_registration_service(
666        &self,
667        router: Weak<crate::Router>,
668        auth: crate::server::ServerAuth,
669    ) {
670        let mut service = self
671            .registration_service
672            .lock()
673            .unwrap_or_else(|p| p.into_inner());
674        debug_assert!(service.is_none(), "registration service installed twice");
675        if service.is_none() {
676            *service = Some(RegistrationService { router, auth });
677        }
678    }
679
680    pub(crate) fn registration_spawn(
681        &self,
682        connection: ConnectionId,
683    ) -> Option<Arc<RegistrationSpawn>> {
684        self.registration_connections
685            .lock()
686            .unwrap_or_else(|p| p.into_inner())
687            .get(&connection)
688            .cloned()
689    }
690
691    pub(crate) fn forget_registration_connection(&self, connection: ConnectionId) {
692        self.registration_connections
693            .lock()
694            .unwrap_or_else(|p| p.into_inner())
695            .remove(&connection);
696    }
697
698    #[cfg(any(unix, windows))]
699    pub(super) fn serve_registration(
700        &self,
701        channel: SpawnRegistrationChannel,
702        spawn: Arc<RegistrationSpawn>,
703        pid: u32,
704        deadline: Instant,
705    ) {
706        let _ = spawn.deadline.set(deadline);
707        #[cfg(unix)]
708        let endpoint = channel.try_clone();
709        #[cfg(windows)]
710        let endpoint = channel.shutdown_handle();
711        match endpoint {
712            Ok(endpoint) => {
713                let _transition = spawn.transition.lock().unwrap_or_else(|p| p.into_inner());
714                if *spawn.launch.borrow() == LaunchState::Dead {
715                    #[cfg(unix)]
716                    let _ = endpoint.shutdown(std::net::Shutdown::Both);
717                    #[cfg(windows)]
718                    endpoint.shutdown();
719                    return;
720                }
721                *spawn.endpoint.lock().unwrap_or_else(|p| p.into_inner()) = Some(endpoint);
722            }
723            Err(_) => {
724                spawn.retire_registration_channel();
725                return;
726            }
727        }
728        #[cfg(test)]
729        {
730            let mut captured = self.registration_test_channels.lock().unwrap();
731            if let Some(channels) = &mut *captured {
732                channels.push((
733                    spawn,
734                    super::CapturedRegistrationEndpoint { _channel: channel },
735                ));
736                return;
737            }
738        }
739        let service = self
740            .registration_service
741            .lock()
742            .unwrap_or_else(|p| p.into_inner())
743            .clone();
744        let Some((router, auth)) =
745            service.and_then(|service| Some((service.router.upgrade()?, service.auth)))
746        else {
747            // This transport cannot authorize registration. A legacy launch
748            // may still use its nonce; a channel-only launch loses authority.
749            spawn.retire_registration_channel();
750            #[cfg(unix)]
751            let _ = channel.shutdown(std::net::Shutdown::Both);
752            return;
753        };
754        tokio::spawn(async move {
755            let serve = async {
756                #[cfg(unix)]
757                let stream = {
758                    let _ = pid;
759                    channel.set_nonblocking(true)?;
760                    tokio::net::UnixStream::from_std(channel)?
761                };
762                #[cfg(windows)]
763                let stream = {
764                    tokio::task::spawn_blocking(move || {
765                        channel.accept_tokio_pipe_server(pid, deadline.into_std())
766                    })
767                    .await
768                    .map_err(io::Error::other)??
769                };
770                let _ = crate::server::handle_connection_with_origin(
771                    RegistrationStream {
772                        stream,
773                        spawn: spawn.clone(),
774                    },
775                    router,
776                    auth,
777                    crate::server::LocalOrigin::RegistrationChannel(spawn.clone()),
778                )
779                .await;
780                Ok::<(), io::Error>(())
781            };
782            let _ = serve.await;
783            spawn.retire_registration_channel();
784        });
785    }
786}
787
788// End registration at the transport's first EOF, including during authentication
789// or frame decoding, without waiting for the connection loop to unwind. Legacy
790// nonce authority survives an unused channel's closure. An Interrupted I/O read
791// error skips only this revoke; connection cleanup still ends registration.
792struct RegistrationStream<S> {
793    stream: S,
794    spawn: Arc<RegistrationSpawn>,
795}
796
797impl<S: tokio::io::AsyncRead + Unpin> tokio::io::AsyncRead for RegistrationStream<S> {
798    fn poll_read(
799        self: std::pin::Pin<&mut Self>,
800        cx: &mut std::task::Context<'_>,
801        buf: &mut tokio::io::ReadBuf<'_>,
802    ) -> std::task::Poll<io::Result<()>> {
803        let this = self.get_mut();
804        let before = buf.filled().len();
805        let can_read = buf.remaining() != 0;
806        let result = std::pin::Pin::new(&mut this.stream).poll_read(cx, buf);
807        let ended = match &result {
808            std::task::Poll::Ready(Ok(())) => can_read && buf.filled().len() == before,
809            std::task::Poll::Ready(Err(error)) => error.kind() != io::ErrorKind::Interrupted,
810            std::task::Poll::Pending => false,
811        };
812        if ended {
813            this.spawn.retire_registration_channel();
814        }
815        result
816    }
817}
818
819impl<S: tokio::io::AsyncWrite + Unpin> tokio::io::AsyncWrite for RegistrationStream<S> {
820    fn poll_write(
821        self: std::pin::Pin<&mut Self>,
822        cx: &mut std::task::Context<'_>,
823        buf: &[u8],
824    ) -> std::task::Poll<io::Result<usize>> {
825        std::pin::Pin::new(&mut self.get_mut().stream).poll_write(cx, buf)
826    }
827
828    fn poll_flush(
829        self: std::pin::Pin<&mut Self>,
830        cx: &mut std::task::Context<'_>,
831    ) -> std::task::Poll<io::Result<()>> {
832        std::pin::Pin::new(&mut self.get_mut().stream).poll_flush(cx)
833    }
834
835    fn poll_shutdown(
836        self: std::pin::Pin<&mut Self>,
837        cx: &mut std::task::Context<'_>,
838    ) -> std::task::Poll<io::Result<()>> {
839        std::pin::Pin::new(&mut self.get_mut().stream).poll_shutdown(cx)
840    }
841}
842
843/// A unit fixture owns the daemon endpoint while it dispatches HELLO directly,
844/// without a socket reader. Its table key locates a channel; it is not sent as a
845/// launch nonce. Full transport tests use the authenticated service instead.
846#[cfg(test)]
847#[derive(Clone, Debug)]
848pub(crate) struct RegistrationProof {
849    key: String,
850    channel: Option<Arc<RegistrationSpawn>>,
851}
852#[cfg(test)]
853impl std::ops::Deref for RegistrationProof {
854    type Target = str;
855    fn deref(&self) -> &str {
856        &self.key
857    }
858}
859#[cfg(test)]
860impl PartialEq for RegistrationProof {
861    fn eq(&self, other: &Self) -> bool {
862        self.key == other.key
863    }
864}
865#[cfg(test)]
866impl From<String> for RegistrationProof {
867    fn from(key: String) -> Self {
868        Self { key, channel: None }
869    }
870}
871#[cfg(test)]
872impl From<&str> for RegistrationProof {
873    fn from(key: &str) -> Self {
874        key.to_owned().into()
875    }
876}
877#[cfg(test)]
878impl RegistrationProof {
879    pub(crate) fn bind(&self, connection: ConnectionId) {
880        if let Some(channel) = &self.channel {
881            channel.bind(connection);
882        }
883    }
884    pub(crate) fn nonce(&self) -> Option<String> {
885        self.channel.is_none().then(|| self.key.clone())
886    }
887    #[cfg(target_os = "linux")]
888    pub(crate) fn as_str(&self) -> &str {
889        &self.key
890    }
891}
892
893#[cfg(test)]
894mod tests {
895    use super::*;
896    use serde_json::json;
897    use subc_protocol::{Frame, FrameType};
898
899    fn hello(module: &str) -> Frame {
900        let manifest = subc_protocol::manifest::ModuleManifest::builder(module, "0.1.0")
901            .protocol_ver(subc_protocol::PROTOCOL_VERSION)
902            .build();
903        Frame::build(
904            FrameType::Hello,
905            subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
906            0,
907            0,
908            10,
909            serde_json::to_vec(
910                &json!({"protocol_ver": subc_protocol::PROTOCOL_VERSION, "manifest": manifest}),
911            )
912            .unwrap(),
913        )
914        .unwrap()
915    }
916
917    fn code(frames: &[Frame]) -> String {
918        assert_eq!(frames.len(), 1);
919        assert_eq!(frames[0].header.ty, FrameType::Error);
920        serde_json::from_slice::<serde_json::Value>(&frames[0].body).unwrap()["code"]
921            .as_str()
922            .unwrap()
923            .into()
924    }
925
926    fn setup() -> (SupervisorHandle, Arc<Registry>, crate::ControlHandler) {
927        let handle = SupervisorHandle::new();
928        let registry = Arc::new(Registry::default());
929        let control = crate::ControlHandler::new(registry.clone()).with_supervisor(handle.clone());
930        (handle, registry, control)
931    }
932
933    fn bound(handle: &SupervisorHandle, id: u64, role: SpawnRole) -> Arc<RegistrationSpawn> {
934        let spawn = RegistrationSpawn::new(handle, "channel-module", role, None);
935        spawn.ready();
936        spawn.bind(ConnectionId::new(id));
937        spawn
938    }
939
940    #[cfg(unix)]
941    async fn hello_rollback_case(candidate: bool) {
942        let worker = if candidate {
943            "supervise::registration::tests::candidate_hello_forwarding_rollback_worker"
944        } else {
945            "supervise::registration::tests::ordinary_hello_forwarding_rollback_worker"
946        };
947        let mut child = tokio::process::Command::new(std::env::current_exe().unwrap())
948            .args(["--exact", worker, "--ignored", "--nocapture"])
949            .kill_on_drop(true)
950            .spawn()
951            .unwrap();
952        let result = tokio::time::timeout(Duration::from_secs(5), child.wait()).await;
953        if result.is_err() {
954            let _ = child.kill().await;
955            let _ = child.wait().await;
956        }
957        assert!(matches!(result, Ok(Ok(status)) if status.success()),
958            "channel HELLO rollback must finish and allow later retirement within the subprocess deadline");
959    }
960
961    #[cfg(unix)]
962    #[tokio::test]
963    async fn ordinary_channel_hello_rollback_does_not_reenter_transition() {
964        hello_rollback_case(false).await;
965    }
966
967    #[cfg(unix)]
968    #[tokio::test]
969    async fn candidate_channel_hello_rollback_does_not_reenter_transition() {
970        hello_rollback_case(true).await;
971    }
972
973    #[cfg(unix)]
974    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
975    #[ignore = "subprocess fixture; invoked only by the bounded rollback tests"]
976    async fn ordinary_hello_forwarding_rollback_worker() {
977        hello_forwarding_rollback_worker(false).await;
978    }
979
980    #[cfg(unix)]
981    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
982    #[ignore = "subprocess fixture; invoked only by the bounded rollback tests"]
983    async fn candidate_hello_forwarding_rollback_worker() {
984        hello_forwarding_rollback_worker(true).await;
985    }
986
987    #[cfg(unix)]
988    async fn hello_forwarding_rollback_worker(candidate: bool) {
989        let (handle, registry, control) = setup();
990        if candidate {
991            assert_eq!(
992                control
993                    .handle_control(ConnectionId::new(90), hello("channel-module"))
994                    .unwrap()[0]
995                    .header
996                    .ty,
997                FrameType::HelloAck
998            );
999            handle.open_swap("channel-module", "candidate".into());
1000        }
1001        let forwarding = control.forwarding();
1002        forwarding.begin_daemon_drain().unwrap();
1003        let role = if candidate {
1004            SpawnRole::SwapCandidate
1005        } else {
1006            SpawnRole::Plain
1007        };
1008        let spawn = RegistrationSpawn::new(&handle, "channel-module", role, None);
1009        spawn.ready();
1010        let router = Arc::new(crate::Router::with_control_handler(Arc::new(control)));
1011        let info = subc_transport::ConnectionInfo {
1012            schema: subc_transport::SCHEMA_VERSION,
1013            wire_version: None,
1014            endpoints: Vec::new(),
1015            key: vec![0x42; 32],
1016            daemon_id: [0x24; 16],
1017            pid: std::process::id(),
1018            daemon_ver: "test".into(),
1019        };
1020        router.install_registration_service(crate::server::ServerAuth::new(
1021            info.key.clone(),
1022            info.daemon_id,
1023            "test",
1024        ));
1025        let (parent, child) = std::os::unix::net::UnixStream::pair().unwrap();
1026        child.set_nonblocking(true).unwrap();
1027        let mut child = tokio::net::UnixStream::from_std(child).unwrap();
1028        handle.serve_registration(
1029            parent,
1030            spawn.clone(),
1031            std::process::id(),
1032            Instant::now() + Duration::from_secs(5),
1033        );
1034        subc_transport::authenticate_client(&mut child, &info, Duration::from_secs(1))
1035            .await
1036            .unwrap();
1037        subc_transport::write_frame(&mut child, &hello("channel-module"))
1038            .await
1039            .unwrap();
1040        let reply = tokio::time::timeout(
1041            Duration::from_secs(1),
1042            subc_transport::read_frame(&mut child),
1043        )
1044        .await
1045        .expect("forwarding refusal must settle the channel HELLO")
1046        .unwrap();
1047        if let Some(reply) = reply {
1048            assert_eq!(reply.header.ty, FrameType::Error);
1049        }
1050        assert!(!spawn.registered());
1051        if candidate {
1052            assert!(registry.get_candidate("channel-module").unwrap().is_none());
1053        } else {
1054            assert!(registry.get_module("channel-module").unwrap().is_none());
1055        }
1056        tokio::time::timeout(
1057            Duration::from_secs(1),
1058            tokio::task::spawn_blocking(move || spawn.retire()),
1059        )
1060        .await
1061        .expect("retirement after HELLO rollback must return")
1062        .unwrap();
1063    }
1064
1065    #[test]
1066    fn registration_channel_wrong_id_consumes_hello() {
1067        let (handle, registry, control) = setup();
1068        let _spawn = bound(&handle, 1, SpawnRole::Plain);
1069        assert_eq!(
1070            code(
1071                &control
1072                    .handle_control(ConnectionId::new(1), hello("another-module"))
1073                    .unwrap()
1074            ),
1075            "registration_channel_module_mismatch"
1076        );
1077        assert_eq!(
1078            code(
1079                &control
1080                    .handle_control(ConnectionId::new(1), hello("channel-module"))
1081                    .unwrap()
1082            ),
1083            "registration_channel_hello_repeated"
1084        );
1085        assert_eq!(registry.active_registration_count().unwrap(), 0);
1086    }
1087
1088    #[test]
1089    fn registration_channel_second_hello_is_refused() {
1090        let (handle, registry, control) = setup();
1091        let _spawn = bound(&handle, 1, SpawnRole::Plain);
1092        let replies = control
1093            .handle_control(ConnectionId::new(1), hello("channel-module"))
1094            .unwrap();
1095        assert_eq!(
1096            replies[0].header.ty,
1097            FrameType::HelloAck,
1098            "{}",
1099            String::from_utf8_lossy(&replies[0].body)
1100        );
1101        assert_eq!(
1102            code(
1103                &control
1104                    .handle_control(ConnectionId::new(1), hello("channel-module"))
1105                    .unwrap()
1106            ),
1107            "registration_channel_hello_repeated"
1108        );
1109        assert_eq!(registry.active_registration_count().unwrap(), 1);
1110    }
1111
1112    #[test]
1113    fn registration_channel_hello_after_exit_is_refused() {
1114        let (handle, registry, control) = setup();
1115        let spawn = bound(&handle, 1, SpawnRole::Plain);
1116        spawn.retire();
1117        assert_eq!(
1118            code(
1119                &control
1120                    .handle_control(ConnectionId::new(1), hello("channel-module"))
1121                    .unwrap()
1122            ),
1123            "registration_channel_closed"
1124        );
1125        assert_eq!(registry.active_registration_count().unwrap(), 0);
1126    }
1127
1128    #[test]
1129    fn registration_channel_plain_respawn_during_swap_preserves_draining_slot() {
1130        let (handle, registry, control) = setup();
1131        let _incumbent = bound(&handle, 1, SpawnRole::Plain);
1132        assert_eq!(
1133            control
1134                .handle_control(ConnectionId::new(1), hello("channel-module"))
1135                .unwrap()[0]
1136                .header
1137                .ty,
1138            FrameType::HelloAck
1139        );
1140        handle.open_swap("channel-module", "legacy-swap-token".into());
1141        let _candidate = bound(&handle, 2, SpawnRole::SwapCandidate);
1142        assert_eq!(
1143            control
1144                .handle_control(ConnectionId::new(2), hello("channel-module"))
1145                .unwrap()[0]
1146                .header
1147                .ty,
1148            FrameType::HelloAck
1149        );
1150        registry
1151            .promote_candidate("channel-module")
1152            .unwrap()
1153            .unwrap();
1154        control.cleanup_connection(ConnectionId::new(2)).unwrap();
1155        assert_eq!(
1156            handle.swap_hello_admission("channel-module", None),
1157            SwapHelloAdmission::Refused
1158        );
1159        let _respawn = bound(&handle, 3, SpawnRole::Plain);
1160        assert_eq!(
1161            control
1162                .handle_control(ConnectionId::new(3), hello("channel-module"))
1163                .unwrap()[0]
1164                .header
1165                .ty,
1166            FrameType::HelloAck
1167        );
1168        assert_eq!(
1169            registry
1170                .get_module("channel-module")
1171                .unwrap()
1172                .unwrap()
1173                .connection_id,
1174            ConnectionId::new(3)
1175        );
1176        assert!(registry
1177            .get_module_by_connection(ConnectionId::new(1))
1178            .unwrap()
1179            .is_some());
1180        assert!(registry.list_modules_with_nonce_verification().unwrap().1[0].1);
1181        control.cleanup_connection(ConnectionId::new(1)).unwrap();
1182        assert_eq!(
1183            registry
1184                .get_module("channel-module")
1185                .unwrap()
1186                .unwrap()
1187                .connection_id,
1188            ConnectionId::new(3)
1189        );
1190    }
1191
1192    fn auth() -> (crate::server::ServerAuth, subc_transport::ConnectionInfo) {
1193        let key = vec![0x42; 32];
1194        let daemon_id = [0x24; 16];
1195        let info = subc_transport::ConnectionInfo {
1196            schema: subc_transport::SCHEMA_VERSION,
1197            wire_version: None,
1198            endpoints: Vec::new(),
1199            key: key.clone(),
1200            daemon_id,
1201            pid: std::process::id(),
1202            daemon_ver: "test".into(),
1203        };
1204        (crate::server::ServerAuth::new(key, daemon_id, "test"), info)
1205    }
1206
1207    #[cfg(unix)]
1208    #[tokio::test]
1209    async fn registration_channel_service_reuses_authenticated_frames_and_never_reconnects() {
1210        let (handle, registry, _) = setup();
1211        let forwarding = Arc::new(crate::ForwardingTable::default());
1212        let control = crate::ControlHandler::with_forwarding(registry.clone(), forwarding.clone())
1213            .with_supervisor(handle.clone());
1214        let router = Arc::new(crate::Router::with_control_handler(Arc::new(control)));
1215        let (auth, info) = auth();
1216        router.install_registration_service(auth);
1217        let spawn = RegistrationSpawn::new(&handle, "channel-module", SpawnRole::Plain, None);
1218        spawn.ready();
1219        let (parent, child) = std::os::unix::net::UnixStream::pair().unwrap();
1220        child.set_nonblocking(true).unwrap();
1221        let mut child = tokio::net::UnixStream::from_std(child).unwrap();
1222        handle.serve_registration(
1223            parent,
1224            spawn.clone(),
1225            std::process::id(),
1226            Instant::now() + Duration::from_secs(2),
1227        );
1228        subc_transport::authenticate_client(&mut child, &info, Duration::from_secs(2))
1229            .await
1230            .unwrap();
1231        let mut body: subc_protocol::ModuleHelloBody =
1232            serde_json::from_slice(&hello("channel-module").body).unwrap();
1233        body.control_ops = Some(vec!["health.check".into()]);
1234        let registration = Frame::build(
1235            FrameType::Hello,
1236            super::super::control_flags(),
1237            0,
1238            0,
1239            1,
1240            serde_json::to_vec(&body).unwrap(),
1241        )
1242        .unwrap();
1243        subc_transport::write_frame(&mut child, &registration)
1244            .await
1245            .unwrap();
1246        assert_eq!(
1247            subc_transport::read_frame(&mut child)
1248                .await
1249                .unwrap()
1250                .unwrap()
1251                .header
1252                .ty,
1253            FrameType::HelloAck
1254        );
1255        assert!(
1256            registry.list_modules_with_nonce_verification().unwrap().1[0].1,
1257            "the channel itself proves the spawn identity without a body nonce"
1258        );
1259        let ping = Frame::build(
1260            FrameType::Ping,
1261            subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
1262            0,
1263            0,
1264            11,
1265            Vec::new(),
1266        )
1267        .unwrap();
1268        subc_transport::write_frame(&mut child, &ping)
1269            .await
1270            .unwrap();
1271        assert_eq!(
1272            subc_transport::read_frame(&mut child)
1273                .await
1274                .unwrap()
1275                .unwrap()
1276                .header
1277                .ty,
1278            FrameType::Pong
1279        );
1280        let request = Frame::build(
1281            FrameType::Request,
1282            subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
1283            0,
1284            0,
1285            12,
1286            serde_json::to_vec(
1287                &subc_protocol::session::ModuleControlRequestFromModule::CatalogUpdate {
1288                    provides: Vec::new(),
1289                    capabilities: None,
1290                    ready: Some(true),
1291                },
1292            )
1293            .unwrap(),
1294        )
1295        .unwrap();
1296        subc_transport::write_frame(&mut child, &request)
1297            .await
1298            .unwrap();
1299        assert_eq!(
1300            subc_transport::read_frame(&mut child)
1301                .await
1302                .unwrap()
1303                .unwrap()
1304                .header
1305                .ty,
1306            FrameType::Response
1307        );
1308        let started = tokio::time::Instant::now();
1309        let pending = forwarding
1310            .begin_health_probe_rpc_for(
1311                "channel-module",
1312                "health.check",
1313                started,
1314                started + Duration::from_secs(2),
1315            )
1316            .unwrap();
1317        let health = Frame::build(
1318            FrameType::Request,
1319            super::super::control_flags(),
1320            0,
1321            0,
1322            pending.corr,
1323            serde_json::to_vec(&subc_protocol::session::ModuleControlRequest::HealthCheck {})
1324                .unwrap(),
1325        )
1326        .unwrap();
1327        pending.module_sink.send(health).await.unwrap();
1328        let health = tokio::time::timeout(
1329            Duration::from_secs(2),
1330            subc_transport::read_frame(&mut child),
1331        )
1332        .await
1333        .unwrap()
1334        .unwrap()
1335        .unwrap();
1336        assert_eq!(
1337            serde_json::from_slice::<serde_json::Value>(&health.body).unwrap(),
1338            json!({"op":"health.check"})
1339        );
1340        let reply =
1341            json!({"op":"health.check", "status":"degraded", "detail":"channel health reply"});
1342        let response = Frame::build(
1343            FrameType::Response,
1344            super::super::control_flags(),
1345            0,
1346            0,
1347            health.header.corr,
1348            serde_json::to_vec(&reply).unwrap(),
1349        )
1350        .unwrap();
1351        subc_transport::write_frame(&mut child, &response)
1352            .await
1353            .unwrap();
1354        match tokio::time::timeout(Duration::from_secs(2), pending.receiver)
1355            .await
1356            .unwrap()
1357            .unwrap()
1358        {
1359            crate::forwarding::ModuleControlRpcOutcome::Response(response) => {
1360                assert_eq!(serde_json::to_value(response).unwrap(), reply)
1361            }
1362            other => panic!("health reply did not traverse the channel: {other:?}"),
1363        }
1364        let push_body =
1365            serde_json::to_vec(&subc_protocol::config::ConfigChanged::new(7, Vec::new())).unwrap();
1366        let push = Frame::build(
1367            FrameType::Push,
1368            super::super::control_flags(),
1369            0,
1370            0,
1371            0,
1372            push_body.clone(),
1373        )
1374        .unwrap();
1375        pending.module_sink.send(push).await.unwrap();
1376        let pushed = tokio::time::timeout(
1377            Duration::from_secs(2),
1378            subc_transport::read_frame(&mut child),
1379        )
1380        .await
1381        .unwrap()
1382        .unwrap()
1383        .unwrap();
1384        assert_eq!(pushed.header.ty, FrameType::Push);
1385        assert_eq!(pushed.body, push_body);
1386        drop(pending.module_sink);
1387        spawn.retire();
1388        assert!(tokio::time::timeout(
1389            Duration::from_secs(2),
1390            subc_transport::read_frame(&mut child)
1391        )
1392        .await
1393        .unwrap()
1394        .unwrap()
1395        .is_none());
1396        tokio::time::timeout(Duration::from_secs(2), async {
1397            while registry.get_module("channel-module").unwrap().is_some() {
1398                tokio::task::yield_now().await;
1399            }
1400        })
1401        .await
1402        .unwrap();
1403    }
1404
1405    #[cfg(unix)]
1406    #[tokio::test]
1407    async fn registration_channel_missing_or_gone_service_closes_without_nonce_fallback() {
1408        let (handle, _, control) = setup();
1409        for installed in [false, true] {
1410            if installed {
1411                let router = Arc::new(crate::Router::with_control_handler(Arc::new(
1412                    control.clone(),
1413                )));
1414                router.install_registration_service(auth().0);
1415                drop(router);
1416            }
1417            let spawn = RegistrationSpawn::new(&handle, "channel-module", SpawnRole::Plain, None);
1418            let (parent, child) = std::os::unix::net::UnixStream::pair().unwrap();
1419            child.set_nonblocking(true).unwrap();
1420            let mut child = tokio::net::UnixStream::from_std(child).unwrap();
1421            handle.serve_registration(
1422                parent,
1423                spawn.clone(),
1424                1,
1425                Instant::now() + Duration::from_secs(1),
1426            );
1427            use tokio::io::AsyncReadExt;
1428            assert_eq!(child.read(&mut [0]).await.unwrap(), 0);
1429            assert_eq!(spawn.check(), Err("registration_channel_closed"));
1430            assert!(handle.spawn_nonce("channel-module").is_none());
1431        }
1432    }
1433
1434    #[test]
1435    fn registration_channel_service_installs_only_once() {
1436        let (handle, _, control) = setup();
1437        let router = Arc::new(crate::Router::with_control_handler(Arc::new(control)));
1438        router.install_registration_service(auth().0);
1439        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1440            router.install_registration_service(auth().0)
1441        }));
1442        assert_eq!(result.is_err(), cfg!(debug_assertions));
1443        assert!(handle
1444            .registration_service
1445            .lock()
1446            .unwrap_or_else(|p| p.into_inner())
1447            .is_some());
1448    }
1449
1450    #[cfg(target_os = "macos")]
1451    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1452    async fn registration_channel_macos_hello_waits_for_verified_transition_and_refusal_closes() {
1453        for refused in [false, true] {
1454            let (handle, _, control) = setup();
1455            let router = Arc::new(crate::Router::with_control_handler(Arc::new(control)));
1456            let (auth, info) = auth();
1457            router.install_registration_service(auth);
1458            let roster = ChildRoster::default();
1459            roster.set_privacy_trampoline(Ok(test_privacy_trampoline()));
1460            let scratch = cortexkit_test_support::ScratchDir::new("channel-launch");
1461            let spec = ModuleSpec {
1462                script: None,
1463                module_id: "channel-module".into(),
1464                program: "/bin/sleep".into(),
1465                args: vec!["60".into()],
1466                env: [
1467                    "HOME",
1468                    "XDG_DATA_HOME",
1469                    "XDG_RUNTIME_DIR",
1470                    "XDG_CONFIG_HOME",
1471                ]
1472                .into_iter()
1473                .map(|key| (key.into(), scratch.display().to_string()))
1474                .collect(),
1475                reserved: false,
1476                reserved_prefixes: Vec::new(),
1477                protocol: ModuleProtocol::Subc,
1478                overlap: Default::default(),
1479                carry_containment: false,
1480            };
1481            let mut spec = spec;
1482            spec.protocol = ModuleProtocol::None;
1483            let owner = super::super::suspended_spawn_tests::gated_owner(&scratch, &spec, true);
1484            let mut runtime =
1485                Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
1486                    .with_config_runtime(owner)
1487                    .runtime_config();
1488            runtime.child_roster = roster;
1489            let mut child = spawn_child_in_slot_async(&spec, &runtime, SpawnRole::Plain, false)
1490                .await
1491                .unwrap();
1492            let spawn = RegistrationSpawn::new(&handle, "channel-module", SpawnRole::Plain, None);
1493            child.registration_spawn = Some(spawn.clone());
1494            let (parent, peer) = std::os::unix::net::UnixStream::pair().unwrap();
1495            peer.set_nonblocking(true).unwrap();
1496            let mut peer = tokio::net::UnixStream::from_std(peer).unwrap();
1497            handle.serve_registration(
1498                parent,
1499                spawn,
1500                child.pid,
1501                Instant::now() + Duration::from_secs(2),
1502            );
1503            subc_transport::authenticate_client(&mut peer, &info, Duration::from_secs(2))
1504                .await
1505                .unwrap();
1506            subc_transport::write_frame(&mut peer, &hello("channel-module"))
1507                .await
1508                .unwrap();
1509            let pid = child.pid;
1510            tokio::time::timeout(Duration::from_secs(2), async {
1511                while !subc_os::privacy_identity::SuspendedSignature::is_suspended(pid).unwrap() {
1512                    tokio::time::sleep(Duration::from_millis(1)).await;
1513                }
1514            })
1515            .await
1516            .unwrap();
1517            // The exec-acknowledgement reader returns EOF and the PID has not changed. Neither fact
1518            // authorizes HELLO before signature verification and resume.
1519            let reader = &child.privacy_exec.as_ref().unwrap().reader;
1520            let mut readiness = reader.readable().await.unwrap();
1521            assert_eq!(
1522                readiness
1523                    .try_io(|reader| {
1524                        use std::io::Read;
1525                        reader.get_ref().read(&mut [0])
1526                    })
1527                    .unwrap()
1528                    .unwrap(),
1529                0
1530            );
1531            assert_eq!(child.pid, pid);
1532            assert!(tokio::time::timeout(
1533                Duration::from_millis(50),
1534                subc_transport::read_frame(&mut peer)
1535            )
1536            .await
1537            .is_err());
1538            if refused {
1539                child.privacy_exec.as_mut().unwrap().expected = None;
1540            }
1541            child.confirm_privacy_exec().await;
1542            let reply = tokio::time::timeout(
1543                Duration::from_secs(2),
1544                subc_transport::read_frame(&mut peer),
1545            )
1546            .await
1547            .unwrap()
1548            .unwrap();
1549            if refused {
1550                assert!(reply.is_none());
1551            } else {
1552                assert_eq!(reply.unwrap().header.ty, FrameType::HelloAck);
1553            }
1554            let _ = child.start_admission_kill();
1555            child.wait().await.unwrap();
1556        }
1557    }
1558}
1559
1560pub(crate) const DEFAULT_REGISTER_TIMEOUT: Duration = Duration::from_secs(120);
1561pub(super) const REGISTRY_RELEASE_TIMEOUT: Duration = Duration::from_secs(1);
1562pub(super) const REGISTRY_RELEASE_POLL: Duration = Duration::from_millis(10);
1563
1564impl SupervisedChild {
1565    pub(super) fn retire_registration(&self) {
1566        // All exit observers enter here before cleanup can await. The retired
1567        // program-binding flag and the registration's Dead state make repeated
1568        // observations harmless, even when another task observes the group
1569        // leader retained unreaped to reserve its process-group id.
1570        if let Some(spawn) = &self.registration_spawn {
1571            spawn.retire();
1572        } else if let Some(binding) = &self._program_binding {
1573            binding.retire();
1574        }
1575        #[cfg(unix)]
1576        if let Some(channel) = &self.registration_channel {
1577            let _ = channel.shutdown(std::net::Shutdown::Both);
1578        }
1579        #[cfg(windows)]
1580        if let Some(channel) = &self.registration_channel {
1581            if let Ok(shutdown) = channel.shutdown_handle() {
1582                shutdown.shutdown();
1583            }
1584        }
1585    }
1586    pub(super) fn registered_since_spawn(&self) -> bool {
1587        self.registration_watch
1588            .as_ref()
1589            .is_some_and(|watch| *watch.changes.borrow() != watch.baseline)
1590    }
1591
1592    pub(super) fn awaiting_registration(&self) -> bool {
1593        // Admission failure retires the channel before its kill becomes
1594        // waitable. That closure must not replace the admission failure with
1595        // a registration failure and spend crash restart budget.
1596        let admission_failed = self.admission_kill_sent && self.spawn_failure.is_some();
1597        !admission_failed && !self.registered_since_spawn()
1598    }
1599}
1600
1601fn registration_release_events() -> &'static watch::Sender<u64> {
1602    static EVENTS: OnceLock<watch::Sender<u64>> = OnceLock::new();
1603    EVENTS.get_or_init(|| {
1604        let (sender, _receiver) = watch::channel(0);
1605        sender
1606    })
1607}
1608
1609pub(crate) fn notify_registration_release() {
1610    let events = registration_release_events();
1611    let next_generation = (*events.borrow()).wrapping_add(1);
1612    events.send_replace(next_generation);
1613}
1614
1615#[cfg(test)]
1616#[derive(Debug)]
1617pub(super) struct IdentitySamplePause {
1618    pub(super) reached: std::sync::mpsc::Sender<()>,
1619    pub(super) release: std::sync::mpsc::Receiver<()>,
1620}
1621
1622#[derive(Debug, Clone, PartialEq, Eq)]
1623pub(crate) enum ReservedHelloRejection {
1624    Exact {
1625        module_id: String,
1626    },
1627    Prefix {
1628        prefix: String,
1629        owner_module_id: String,
1630    },
1631}
1632
1633/// Identity facts established by the reserved-module policy for one HELLO.
1634#[derive(Debug, Default)]
1635pub(crate) struct ReservedHelloVerification {
1636    pub(crate) nonce_verified: bool,
1637    pub(crate) prefix_owner: Option<String>,
1638}
1639
1640fn matching_reserved_prefix<'a>(
1641    owners: &'a HashMap<String, String>,
1642    module_id: &str,
1643) -> Option<(&'a String, &'a String)> {
1644    owners
1645        .iter()
1646        .filter(|(prefix, _)| module_id.starts_with(prefix.as_str()))
1647        .max_by_key(|(prefix, _)| prefix.len())
1648}
1649
1650impl SupervisorHandle {
1651    /// Record the launch nonce from a supervised spawn, replacing any prior nonce so
1652    /// a respawn invalidates stale consumer identities.
1653    pub fn set_spawn_nonce(&self, module_id: &str, nonce: String) {
1654        self.spawn_nonces
1655            .lock()
1656            .unwrap_or_else(|poisoned| poisoned.into_inner())
1657            .insert(module_id.to_string(), nonce);
1658        self.refresh_program_binding_nonces(module_id);
1659    }
1660
1661    /// Record the launch nonce expected from the next HELLO for a reserved module,
1662    /// replacing any prior nonce (a respawn invalidates the previous one).
1663    pub fn set_reserved_nonce(&self, module_id: &str, nonce: String) {
1664        {
1665            let mut reserved = self
1666                .reserved_nonces
1667                .lock()
1668                .unwrap_or_else(|p| p.into_inner());
1669            self.implicit_protocol_none
1670                .lock()
1671                .unwrap_or_else(|p| p.into_inner())
1672                .remove(module_id);
1673            reserved.insert(module_id.to_string(), Some(nonce));
1674        }
1675        self.refresh_program_binding_nonces(module_id);
1676    }
1677
1678    /// Record namespace prefixes owned by a supervised module.
1679    pub fn set_reserved_prefixes(&self, owner_module_id: &str, prefixes: &[String]) {
1680        let mut owners = self
1681            .reserved_prefix_owners
1682            .lock()
1683            .unwrap_or_else(|poisoned| poisoned.into_inner());
1684        owners.retain(|_, owner| owner != owner_module_id);
1685        for prefix in prefixes {
1686            owners.insert(prefix.clone(), owner_module_id.to_string());
1687        }
1688    }
1689
1690    pub(crate) fn remove_reserved_prefix_children(&self, module_ids: &mut BTreeSet<String>) {
1691        let owners = self
1692            .reserved_prefix_owners
1693            .lock()
1694            .unwrap_or_else(|poisoned| poisoned.into_inner());
1695        module_ids.retain(|id| {
1696            matching_reserved_prefix(&owners, id).is_none_or(|(_, owner)| owner == id)
1697        });
1698    }
1699
1700    /// The launch nonce most recently minted for a module's spawn, if any.
1701    pub(crate) fn spawn_nonce(&self, module_id: &str) -> Option<String> {
1702        if self.module_is_gated(module_id) {
1703            return None;
1704        }
1705        self.spawn_nonces
1706            .lock()
1707            .unwrap_or_else(|poisoned| poisoned.into_inner())
1708            .get(module_id)
1709            .cloned()
1710    }
1711
1712    #[cfg(all(test, unix))]
1713    pub(crate) fn legacy_nonce_present_for_test(&self, module: &str) -> bool {
1714        self.spawn_nonces.lock().unwrap().contains_key(module)
1715    }
1716
1717    pub(crate) fn apply_identity_configuration(&self, spec: &ModuleSpec) {
1718        // Prefix ownership follows staged configuration, not the running
1719        // child's launch settings. A respawn may still carry an older spec.
1720        self.set_reserved_prefixes(&spec.module_id, &spec.reserved_prefixes);
1721        let protocol = self
1722            .get(&spec.module_id)
1723            .and_then(|module| {
1724                let snapshot = module.inner.snapshot.lock().ok()?;
1725                snapshot
1726                    .process_alive
1727                    .then_some(snapshot.spawned_protocol.unwrap_or(spec.protocol))
1728            })
1729            .unwrap_or(spec.protocol);
1730        self.apply_identity_policy(spec, protocol);
1731    }
1732
1733    #[cfg(all(test, unix))]
1734    pub(crate) fn pause_plain_identity_policy_for_test(
1735        &self,
1736        module: &str,
1737    ) -> (std::sync::mpsc::Receiver<()>, std::sync::mpsc::Sender<()>) {
1738        let (reached, waiting) = std::sync::mpsc::channel();
1739        let (release, paused) = std::sync::mpsc::channel();
1740        *self.plain_identity_policy_pause.lock().unwrap() = Some((
1741            module.to_owned(),
1742            IdentitySamplePause {
1743                reached,
1744                release: paused,
1745            },
1746        ));
1747        (waiting, release)
1748    }
1749
1750    pub(super) fn apply_identity_policy(&self, spec: &ModuleSpec, protocol: ModuleProtocol) {
1751        let channel_only = self.module_is_gated(&spec.module_id);
1752        let mut current_nonces = self
1753            .spawn_nonces
1754            .lock()
1755            .unwrap_or_else(|poisoned| poisoned.into_inner());
1756        if protocol == ModuleProtocol::None || channel_only {
1757            current_nonces.remove(&spec.module_id);
1758        }
1759        let spawn_nonce = current_nonces.get(&spec.module_id).cloned();
1760        #[cfg(test)]
1761        if let Some(pause) = self.identity_sample_pause.lock().unwrap().take() {
1762            pause.reached.send(()).unwrap();
1763            pause.release.recv().unwrap();
1764        }
1765        let mut reserved_nonces = self
1766            .reserved_nonces
1767            .lock()
1768            .unwrap_or_else(|poisoned| poisoned.into_inner());
1769        let mut implicit = self
1770            .implicit_protocol_none
1771            .lock()
1772            .unwrap_or_else(|p| p.into_inner());
1773        if spec.reserved {
1774            implicit.remove(&spec.module_id);
1775        } else if protocol == ModuleProtocol::None {
1776            if !reserved_nonces.contains_key(&spec.module_id) {
1777                implicit.insert(spec.module_id.clone());
1778            }
1779        } else if implicit.remove(&spec.module_id) {
1780            reserved_nonces.remove(&spec.module_id);
1781        }
1782        if spec.reserved || protocol == ModuleProtocol::None {
1783            // `None` (no spawn nonce minted) is INSERTED, not skipped: a
1784            // reserved name whose module has never spawned has no legitimate
1785            // holder, and the entry's absence is what used to leave the name
1786            // open to the first claimant.
1787            reserved_nonces.insert(spec.module_id.clone(), spawn_nonce);
1788        }
1789        drop(implicit);
1790        drop(reserved_nonces);
1791        drop(current_nonces);
1792        self.refresh_program_binding_nonces(&spec.module_id);
1793        // A later unreserved declaration must not silently unreserve an id that
1794        // was retained after its reserved configuration was removed. The explicit
1795        // release ceremony is the only operation that retires that gate.
1796        self.removal_tombstones
1797            .lock()
1798            .unwrap_or_else(|poisoned| poisoned.into_inner())
1799            .remove(&spec.module_id);
1800    }
1801
1802    /// Whether a HELLO claiming `module_id` is authorized. An exact reserved id is
1803    /// authorized only by its expected nonce; otherwise a matching reserved prefix
1804    /// is authorized by the owner module's current spawn nonce. Non-reserved ids
1805    /// with no matching prefix are always authorized.
1806    pub fn reserved_hello_authorized(&self, module_id: &str, presented: Option<&str>) -> bool {
1807        self.reserved_hello_verification(module_id, presented)
1808            .is_ok()
1809    }
1810
1811    /// Whether HELLO passed a nonce check that was actually required by reserved
1812    /// module policy, or the refusal explaining why a required check failed.
1813    pub(crate) fn reserved_hello_verification(
1814        &self,
1815        module_id: &str,
1816        presented: Option<&str>,
1817    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
1818        if self.module_is_gated(module_id) {
1819            return Err(ReservedHelloRejection::Exact {
1820                module_id: module_id.into(),
1821            });
1822        }
1823        self.hello_verification(module_id, presented, false)
1824    }
1825
1826    pub(crate) fn channel_hello_verification(
1827        &self,
1828        module_id: &str,
1829    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
1830        if self
1831            .get(module_id)
1832            .is_some_and(|module| module.declared_protocol().ok() == Some(ModuleProtocol::None))
1833        {
1834            return Err(ReservedHelloRejection::Exact {
1835                module_id: module_id.into(),
1836            });
1837        }
1838        let mut verification = self.hello_verification(module_id, None, true)?;
1839        verification.nonce_verified = true;
1840        Ok(verification)
1841    }
1842
1843    pub(crate) fn prefix_claim_authorized(&self, owner: &str, module_id: &str) -> bool {
1844        self.prefix_claim_publication(owner, module_id).is_some()
1845    }
1846
1847    #[cfg(all(test, unix))]
1848    pub(crate) fn prefix_publication_locked_for_test(&self) -> bool {
1849        matches!(
1850            self.reserved_prefix_owners.try_lock(),
1851            Err(std::sync::TryLockError::WouldBlock)
1852        )
1853    }
1854
1855    // Keep this guard through registry/forwarding publication. Rescans replace
1856    // prefix owners without stopping their launches, so the spawn guard alone
1857    // cannot fence a reservation transfer.
1858    pub(crate) fn prefix_claim_publication(
1859        &self,
1860        owner: &str,
1861        module_id: &str,
1862    ) -> Option<std::sync::MutexGuard<'_, HashMap<String, String>>> {
1863        if subc_protocol::manifest::validate_module_id(module_id).is_err()
1864            || self.module_is_gated(module_id)
1865            || self
1866                .reserved_nonces
1867                .lock()
1868                .unwrap_or_else(|p| p.into_inner())
1869                .contains_key(module_id)
1870        {
1871            return None;
1872        }
1873        let owners = self
1874            .reserved_prefix_owners
1875            .lock()
1876            .unwrap_or_else(|p| p.into_inner());
1877        let authorized = matching_reserved_prefix(&owners, module_id)
1878            .is_some_and(|(prefix, holder)| holder == owner && module_id.len() > prefix.len());
1879        authorized.then_some(owners)
1880    }
1881
1882    fn hello_verification(
1883        &self,
1884        module_id: &str,
1885        presented: Option<&str>,
1886        channel: bool,
1887    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
1888        let nonces = self
1889            .reserved_nonces
1890            .lock()
1891            .unwrap_or_else(|poisoned| poisoned.into_inner());
1892        if let Some(expected) = nonces.get(module_id) {
1893            // `None` = reserved with no legitimate holder: refuse every
1894            // presentation, because no process can hold a nonce that was never
1895            // minted. Only a real minted nonce admits, in constant time.
1896            let authorized = channel
1897                || match expected {
1898                    Some(expected) => presented.is_some_and(|p| {
1899                        !p.is_empty() && constant_time_eq(expected.as_bytes(), p.as_bytes())
1900                    }),
1901                    None => false,
1902                };
1903            if authorized {
1904                return Ok(ReservedHelloVerification {
1905                    nonce_verified: true,
1906                    prefix_owner: None,
1907                });
1908            }
1909            return Err(ReservedHelloRejection::Exact {
1910                module_id: module_id.to_string(),
1911            });
1912        }
1913        drop(nonces);
1914
1915        let matched_prefix = {
1916            let owners = self
1917                .reserved_prefix_owners
1918                .lock()
1919                .unwrap_or_else(|poisoned| poisoned.into_inner());
1920            matching_reserved_prefix(&owners, module_id)
1921                .map(|(prefix, owner)| (prefix.clone(), owner.clone()))
1922        };
1923        let Some((prefix, owner_module_id)) = matched_prefix else {
1924            return Ok(ReservedHelloVerification::default());
1925        };
1926
1927        if module_id.len() == prefix.len()
1928            || (!channel
1929                && (self.module_is_gated(&owner_module_id) || self.protocol_none(&owner_module_id)))
1930        {
1931            return Err(ReservedHelloRejection::Prefix {
1932                prefix,
1933                owner_module_id,
1934            });
1935        }
1936
1937        let authorized = if channel {
1938            owner_module_id == module_id
1939        } else {
1940            presented.is_some_and(|presented| {
1941                self.spawn_nonces
1942                .lock()
1943                .unwrap_or_else(|poisoned| poisoned.into_inner())
1944                .get(&owner_module_id)
1945                .is_some_and(|expected| !presented.is_empty() && constant_time_eq(expected.as_bytes(), presented.as_bytes()))
1946                // While the owner is being swapped, children started by
1947                // either of its two processes hold that process's nonce.
1948                || self.swap_nonce_matches(&owner_module_id, presented)
1949            })
1950        };
1951        if authorized {
1952            Ok(ReservedHelloVerification {
1953                nonce_verified: true,
1954                prefix_owner: (owner_module_id != module_id).then_some(owner_module_id),
1955            })
1956        } else {
1957            Err(ReservedHelloRejection::Prefix {
1958                prefix,
1959                owner_module_id,
1960            })
1961        }
1962    }
1963
1964    /// Whether a consumer connection proved it came from a daemon-spawned module.
1965    ///
1966    /// Absence of an expected spawn nonce is a hard failure: consumer_identity is
1967    /// accepted only for module ids the supervisor has spawned.
1968    pub fn spawned_consumer_authorized(&self, module_id: &str, presented: &str) -> bool {
1969        if self.module_is_gated(module_id) || self.protocol_none(module_id) {
1970            return false;
1971        }
1972        let nonces = self
1973            .spawn_nonces
1974            .lock()
1975            .unwrap_or_else(|poisoned| poisoned.into_inner());
1976        let current = nonces.get(module_id).is_some_and(|expected| {
1977            !presented.is_empty() && constant_time_eq(expected.as_bytes(), presented.as_bytes())
1978        });
1979        drop(nonces);
1980        // Before cutover both launches may attest. Promotion removes the
1981        // incumbent's token even if its process still needs time to drain.
1982        current || self.swap_nonce_matches(module_id, presented)
1983    }
1984}
1985
1986impl SupervisorHandle {
1987    pub(super) fn protocol_none(&self, module: &str) -> bool {
1988        self.get(module)
1989            .is_some_and(|module| module.declared_protocol().ok() == Some(ModuleProtocol::None))
1990    }
1991}
1992
1993impl SupervisorHandle {
1994    /// Test/support lookup for the current launch nonce of a supervised spawn.
1995    pub fn spawn_launch_nonce_for(&self, module_id: &str) -> Option<String> {
1996        self.spawn_nonce(module_id)
1997    }
1998
1999    /// Test/support lookup for the HELLO-gating nonce of a reserved module.
2000    pub fn reserved_launch_nonce_for(&self, module_id: &str) -> Option<String> {
2001        if self.module_is_gated(module_id) {
2002            return None;
2003        }
2004        self.reserved_nonces
2005            .lock()
2006            .unwrap_or_else(|poisoned| poisoned.into_inner())
2007            .get(module_id)
2008            .cloned()
2009            .flatten()
2010    }
2011}
2012
2013/// Constant-time byte comparison so a reserved-nonce mismatch leaks no timing
2014/// signal about how many leading bytes matched.
2015pub(super) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
2016    if a.len() != b.len() {
2017        return false;
2018    }
2019    let mut diff = 0u8;
2020    for (x, y) in a.iter().zip(b.iter()) {
2021        diff |= x ^ y;
2022    }
2023    diff == 0
2024}
2025
2026pub(super) struct RegistrationWatch {
2027    pub(super) changes: watch::Receiver<u64>,
2028    pub(super) baseline: u64,
2029}
2030
2031// Capture before spawning: a fast child's accepted HELLO can disappear from the
2032// active registry before the monitor first runs. A pre-existing registration
2033// must not satisfy a new process's deadline either.
2034pub(super) fn watch_registration(
2035    registry: &Registry,
2036    spec: &ModuleSpec,
2037) -> Option<RegistrationWatch> {
2038    if spec.protocol != ModuleProtocol::Subc {
2039        return None;
2040    }
2041    let changes = registry.subscribe_module_changes(&spec.module_id).ok()?;
2042    let baseline = *changes.borrow();
2043    Some(RegistrationWatch { changes, baseline })
2044}
2045
2046pub(super) fn arm_registration_deadline(
2047    child: &mut SupervisedChild,
2048    budget: Duration,
2049    registration_watch: Option<RegistrationWatch>,
2050) {
2051    child.registration_watch = registration_watch;
2052    child.registration_deadline = (child.protocol == ModuleProtocol::Subc
2053        && child.awaiting_registration())
2054    .then_some(child.spawned_at + budget);
2055}
2056
2057pub(super) enum RegistrationWaitOutcome {
2058    Registered,
2059    Exited(ExitReport),
2060    TimedOut,
2061}
2062
2063pub(super) struct ReloadRegistrationFailure {
2064    pub(super) cleanup_detail: Option<String>,
2065    pub(super) exit_report: ExitReport,
2066    pub(super) reason: String,
2067}
2068
2069/// Wait for the freshly spawned child to take the ACTIVE slot for `module_id`,
2070/// the only slot a plain (non-swap) spawn can register into.
2071pub(super) async fn wait_for_registration_after_reload(
2072    registry: &Registry,
2073    module_id: &str,
2074    snapshot: &SharedSnapshot,
2075    child: &mut SupervisedChild,
2076    wait: Duration,
2077) -> Result<RegistrationWaitOutcome, SuperviseError> {
2078    wait_for_slot_registration(
2079        registry,
2080        crate::registry::RegistrationSlot::Active(module_id),
2081        module_id,
2082        snapshot,
2083        child,
2084        wait,
2085    )
2086    .await
2087}
2088
2089/// Wait for `child` to register into `slot`, or to exit, or for `wait` to pass.
2090///
2091/// Keyed on the slot rather than the bare module id because during a swap the
2092/// id's active slot is already held by the incumbent: an id-keyed wait would
2093/// report the incumbent's registration as the candidate's and a candidate that
2094/// never registers would look registered. A swap candidate waits on
2095/// `crate::registry::RegistrationSlot::Candidate`.
2096async fn wait_for_slot_registration(
2097    registry: &Registry,
2098    slot: crate::registry::RegistrationSlot<'_>,
2099    module_id: &str,
2100    snapshot: &SharedSnapshot,
2101    child: &mut SupervisedChild,
2102    wait: Duration,
2103) -> Result<RegistrationWaitOutcome, SuperviseError> {
2104    let deadline = Instant::now() + wait;
2105    loop {
2106        if registry
2107            .registration(slot)
2108            .map_err(SuperviseError::Registry)?
2109            .is_some()
2110        {
2111            return Ok(RegistrationWaitOutcome::Registered);
2112        }
2113
2114        let now = Instant::now();
2115        if now >= deadline {
2116            return Ok(RegistrationWaitOutcome::TimedOut);
2117        }
2118        let remaining = deadline.saturating_duration_since(now);
2119        let poll = remaining.min(REGISTRY_RELEASE_POLL);
2120
2121        tokio::select! {
2122            wait_result = child.wait() => {
2123                let status = wait_result.map_err(|source| SuperviseError::Wait {
2124                    module_id: module_id.to_string(),
2125                    source,
2126                })?;
2127                return Ok(RegistrationWaitOutcome::Exited(classify_reaped_child_exit(
2128                    snapshot,
2129                    child,
2130                    &status,
2131                )));
2132            }
2133            _ = sleep(poll) => {}
2134        }
2135    }
2136}
2137
2138pub(super) fn registration_failure_exit_report(mut exit_report: ExitReport) -> ExitReport {
2139    // A process stopped for missing its first HELLO did not provide service,
2140    // even if its TERM handler exits zero. Reload also uses this classification
2141    // when a replacement exits before registering.
2142    if exit_report.kind != ExitKind::DeliberateSeverance {
2143        exit_report.kind = ExitKind::Crash;
2144    }
2145    exit_report
2146}
2147
2148pub(super) async fn handle_reload_child_registration_failure(
2149    spec: &ModuleSpec,
2150    runtime: &SupervisorRuntimeConfig,
2151    registry: &Registry,
2152    process_liveness: &SupervisorProcessLiveness,
2153    snapshot: &SharedSnapshot,
2154    _child: &mut Option<SupervisedChild>,
2155    failure: ReloadRegistrationFailure,
2156) -> Result<(), SuperviseError> {
2157    let ReloadRegistrationFailure {
2158        exit_report,
2159        reason,
2160        cleanup_detail,
2161    } = failure;
2162    match on_child_exit_with_detail(
2163        spec,
2164        runtime.restart_policy,
2165        registry,
2166        snapshot,
2167        &runtime.terminal_ring,
2168        &runtime.spawn_events,
2169        &runtime.child_roster,
2170        exit_report,
2171        runtime.recovery_is_daemon,
2172        cleanup_detail,
2173    )
2174    .await
2175    {
2176        NextAction::Stop {
2177            registration_released,
2178        } => {
2179            if registration_released {
2180                process_liveness.untrack_if_current(&spec.module_id, snapshot);
2181            }
2182        }
2183        NextAction::Restart { schedule } => {
2184            let delay = schedule.map_or(runtime.restart_policy.delay_for_restart(0), |schedule| {
2185                schedule.delay
2186            });
2187            if let Some(schedule) = schedule {
2188                log_crash_respawn(&spec.module_id, schedule);
2189            }
2190            schedule_respawn(
2191                runtime,
2192                snapshot,
2193                &spec.module_id,
2194                delay,
2195                RespawnKind::after_exit(schedule),
2196                true,
2197            )?;
2198        }
2199    }
2200    Err(SuperviseError::ReloadFailed {
2201        module_id: spec.module_id.clone(),
2202        reason,
2203    })
2204}
2205
2206pub(super) async fn handle_reload_spawn_failure(
2207    spec: &ModuleSpec,
2208    runtime: &SupervisorRuntimeConfig,
2209    process_liveness: &SupervisorProcessLiveness,
2210    snapshot: &SharedSnapshot,
2211    _child: &mut Option<SupervisedChild>,
2212    reason: String,
2213) -> Result<(), SuperviseError> {
2214    let now = Instant::now();
2215    let mut schedule = None;
2216    update_snapshot(snapshot, Some(&spec.module_id), |state| {
2217        clear_current_process_facts(state);
2218        if state.enabled {
2219            schedule = state.next_crash_restart(&runtime.restart_policy, now);
2220            state.state = if schedule.is_some() {
2221                ModuleState::Restarting
2222            } else {
2223                if runtime
2224                    .failure_context(runtime.recovery_is_daemon)
2225                    .may_retry()
2226                {
2227                    state.failed_retry.schedule(&spec.module_id);
2228                }
2229                ModuleState::Failed
2230            };
2231        } else {
2232            state.state = ModuleState::Disabled;
2233        }
2234    })?;
2235    if let Some(schedule) = schedule {
2236        schedule_respawn(
2237            runtime,
2238            snapshot,
2239            &spec.module_id,
2240            schedule.delay,
2241            RespawnKind::CrashRestart,
2242            true,
2243        )?;
2244    } else {
2245        process_liveness.untrack_if_current(&spec.module_id, snapshot);
2246    }
2247    Err(SuperviseError::ReloadFailed {
2248        module_id: spec.module_id.clone(),
2249        reason,
2250    })
2251}
2252
2253/// Release a reaped child's registration before allowing another spawn.
2254///
2255/// EOF is not a process-lifetime signal: an inherited socket can stay open
2256/// indefinitely, and serial frame dispatch can be waiting on egress instead of
2257/// reading EOF. After the normal release grace, request connection close (which
2258/// cancels both reads and dispatch), then allow one more release grace for the
2259/// connection guard's forwarding cleanup. Never evict a different connection.
2260pub(super) async fn release_dead_registration(
2261    registry: &Registry,
2262    forwarding: Option<&ForwardingTable>,
2263    snapshot: &SharedSnapshot,
2264    module_id: &str,
2265    failure: &FailureContext,
2266) -> Result<(), SuperviseError> {
2267    let result = async {
2268        let registration = registry
2269            .get_module(module_id)
2270            .map_err(SuperviseError::Registry)?;
2271        match wait_for_registration_release(registry, module_id, REGISTRY_RELEASE_TIMEOUT).await {
2272            Ok(()) => return Ok(()),
2273            Err(SuperviseError::RegistrationStillActive { .. }) => {}
2274            Err(err) => return Err(err),
2275        }
2276        let pid = lock_snapshot(snapshot)?.reaped_pid;
2277        if let (Some(registration), Some(forwarding), Some(pid)) = (registration, forwarding, pid) {
2278            warn!(
2279                module_id,
2280                pid,
2281                connection_id = registration.connection_id.get(),
2282                "reaped module registration outlived release grace; closing dead connection"
2283            );
2284            forwarding.request_connection_close(
2285                registration.connection_id,
2286                CloseReason::new(
2287                    "supervised_process_reaped",
2288                    format!("module '{module_id}' pid {pid} exited"),
2289                ),
2290            );
2291            wait_for_slot_registration_release(
2292                registry,
2293                crate::registry::RegistrationSlot::Connection(registration.connection_id),
2294                REGISTRY_RELEASE_TIMEOUT,
2295            )
2296            .await?;
2297        }
2298        wait_for_registration_release(registry, module_id, Duration::ZERO).await
2299    }
2300    .await;
2301    if let Err(err) = &result {
2302        fail_snapshot(snapshot, Some(module_id), None, failure);
2303        error!(module_id, error = %err, "registration release failed after child exit; module is failed and start can retry");
2304    }
2305    result
2306}
2307
2308/// Wait for the ACTIVE registration of `module_id` to go away, which is what a
2309/// plain stop or restart waits for before it spawns a replacement.
2310pub(super) async fn wait_for_registration_release(
2311    registry: &Registry,
2312    module_id: &str,
2313    wait: Duration,
2314) -> Result<(), SuperviseError> {
2315    wait_for_slot_registration_release(
2316        registry,
2317        crate::registry::RegistrationSlot::Active(module_id),
2318        wait,
2319    )
2320    .await
2321}
2322
2323/// Wait for the registration in `slot` to go away.
2324///
2325/// Keyed on the slot rather than the bare module id because a successful swap
2326/// never empties the id's active slot (the promoted candidate is in it), so an
2327/// id-keyed wait for the incumbent's release would always time out. Draining a
2328/// swap's incumbent waits on `crate::registry::RegistrationSlot::Connection` with the
2329/// incumbent's connection instead.
2330pub(super) async fn wait_for_slot_registration_release(
2331    registry: &Registry,
2332    slot: crate::registry::RegistrationSlot<'_>,
2333    wait: Duration,
2334) -> Result<(), SuperviseError> {
2335    let deadline = Instant::now() + wait;
2336    let mut release_events = registration_release_events().subscribe();
2337    let still_active = |registration: &crate::registry::ModuleRegistration| {
2338        SuperviseError::RegistrationStillActive {
2339            module_id: registration.manifest.module_id.clone(),
2340            waited: wait,
2341        }
2342    };
2343    loop {
2344        let _observed_generation = *release_events.borrow_and_update();
2345        let Some(registration) = registry
2346            .registration(slot)
2347            .map_err(SuperviseError::Registry)?
2348        else {
2349            return Ok(());
2350        };
2351
2352        let now = Instant::now();
2353        if now >= deadline {
2354            return Err(still_active(&registration));
2355        }
2356
2357        let remaining = deadline.saturating_duration_since(now);
2358        match timeout(remaining, release_events.changed()).await {
2359            Ok(Ok(())) | Ok(Err(_)) => {}
2360            Err(_) => return Err(still_active(&registration)),
2361        }
2362    }
2363}
2364
2365pub(super) fn registration_child_is_running(child: &mut SupervisedChild) -> bool {
2366    child.try_wait().is_ok_and(|status| status.is_none())
2367}