Skip to main content

subc_daemon/config_gate/
delivery.rs

1//! Connection-bound delivery attempts; durable vectors remain in ConfigStore.
2
3use std::collections::HashSet;
4use subc_protocol::config::{ConfigAppliedRequest, ConfigGetReply, ConfigGetRequest};
5
6use super::*;
7use crate::config_gate::apply::Transition;
8use crate::config_store::Tuple;
9
10#[path = "rpc_delivery.rs"]
11mod rpc_delivery;
12use rpc_delivery::record_served_view;
13
14pub(crate) const CONFIG_LIVE_ACK_TIMEOUT: Duration = Duration::from_secs(30);
15pub(crate) const CONFIG_WARMUP_SLACK: Duration = Duration::from_secs(10);
16
17#[allow(clippy::too_many_arguments)]
18fn allocate_spawn(
19    state: &mut OwnerState,
20    module: &str,
21    generation: u64,
22    at: tokio::time::Instant,
23    register: Duration,
24    health: Duration,
25    authority: Option<(
26        std::sync::Arc<crate::spawn_authority::SpawnAuthorityRecord>,
27        bool,
28    )>,
29    program: Option<super::admission::AdmittedProgram>,
30) -> Result<DeliverySpawn> {
31    #[cfg(test)]
32    if state.delivery.failed_spawn_module.as_deref() == Some(module) {
33        return Err(GateError::new(
34            "delivery_spawn_exhausted",
35            "delivery spawn identifiers exhausted",
36        ));
37    }
38    state.delivery.next_spawn = state.delivery.next_spawn.checked_add(1).ok_or_else(|| {
39        GateError::new(
40            "delivery_spawn_exhausted",
41            "delivery spawn identifiers exhausted",
42        )
43    })?;
44    let (authority, stamped) =
45        authority.map_or((None, false), |(record, stamped)| (Some(record), stamped));
46    Ok(DeliverySpawn {
47        id: state.delivery.next_spawn,
48        module: module.into(),
49        generation,
50        deadline: at + register + health + CONFIG_WARMUP_SLACK,
51        authority,
52        stamped,
53        program,
54    })
55}
56
57#[derive(Clone, Debug)]
58struct Attempt {
59    module: String,
60    generation: u64,
61    id: u64,
62    transition: Transition,
63    ready: bool,
64    acknowledged: bool,
65    delivered: bool,
66    deadline: Option<tokio::time::Instant>,
67    // Catch-up belongs to one promoted child, not to the durable generation.
68    // A daemon restart drops it: every fresh launch receives the active vector.
69    catchup: bool,
70    write_deadline: Option<tokio::time::Instant>,
71    policy_probe_requested: bool,
72    /// The spawn this attempt was assigned to, when it carries an authority
73    /// record. Its acknowledgement counts toward that spawn's first-party
74    /// mark only, never another spawn's.
75    spawn: Option<DeliverySpawn>,
76    /// A catch-up assigned only so a fresh spawn acknowledges the active
77    /// generation for its first-party mark. Its refusal or timeout leaves the
78    /// spawn unmarked and starts no recovery.
79    mark_only: bool,
80    declaration_fallback: bool,
81}
82
83#[derive(Clone, Debug)]
84pub struct DeliverySpawn {
85    id: u64,
86    module: String,
87    generation: u64,
88    deadline: tokio::time::Instant,
89    /// The launch's spawn authority record, when the supervisor launched it.
90    authority: Option<std::sync::Arc<crate::spawn_authority::SpawnAuthorityRecord>>,
91    /// The stamped store gated this module when the spawn was admitted. Only
92    /// such a spawn can ever carry the first-party mark.
93    stamped: bool,
94    /// The program the spawn was admitted under, when the stamped store
95    /// gated its module. A placement or approval that supersedes it rules
96    /// the spawn out of the mark.
97    program: Option<super::admission::AdmittedProgram>,
98}
99
100impl DeliverySpawn {
101    pub(crate) fn module(&self) -> &str {
102        &self.module
103    }
104    pub(crate) fn generation(&self) -> u64 {
105        self.generation
106    }
107    pub(crate) fn authority(
108        &self,
109    ) -> Option<&std::sync::Arc<crate::spawn_authority::SpawnAuthorityRecord>> {
110        self.authority.as_ref()
111    }
112    pub(crate) fn stamped(&self) -> bool {
113        self.stamped
114    }
115    pub(super) fn admitted_program(&self) -> Option<&super::admission::AdmittedProgram> {
116        self.program.as_ref()
117    }
118    /// Attach a launch's authority record, as the supervisor's admission path
119    /// does, to a spawn a test allocated directly.
120    #[cfg(test)]
121    pub(crate) fn with_authority_for_test(
122        mut self,
123        record: std::sync::Arc<crate::spawn_authority::SpawnAuthorityRecord>,
124        stamped: bool,
125    ) -> Self {
126        self.authority = Some(record);
127        self.stamped = stamped;
128        self
129    }
130}
131
132#[derive(Default)]
133pub(super) struct DeliveryState {
134    pub(super) fallback_applied: HashMap<ConnectionId, u64>,
135    #[cfg(test)]
136    failed_spawn_module: Option<String>,
137    next_spawn: u64,
138    next_attempt: u64,
139    policy_epochs: HashMap<String, u64>,
140    attempts: HashMap<ConnectionId, Attempt>,
141    served: HashMap<ConnectionId, (Option<u64>, Option<u64>)>,
142    pub(super) unstamped_views: HashMap<ConnectionId, std::sync::Arc<ConfigView>>,
143    stamp_running: HashSet<ConnectionId>,
144    initial_generation: u64,
145    children: HashMap<ConnectionId, DeliverySpawn>,
146    healthy_children: HashSet<(ConnectionId, u64)>,
147    readiness_observed: HashSet<(ConnectionId, u64)>,
148    unregistered_children: HashMap<(String, bool), DeliverySpawn>,
149    recoveries: Vec<(ConnectionId, String, AppliedDisposition)>,
150    exited: HashMap<String, ExitedDelivery>,
151    // Transport cleanup may precede the process-exit observation. Retain the
152    // last active child's assigned generation, not an unattempted deferred one.
153    last_target_attempt: HashMap<String, (u64, u64)>,
154    /// Every spawn admitted under the stamp, which carries or may still earn
155    /// the first-party mark. Unlike the rest of this state it survives
156    /// `reset_for_authority_exit`, so a committed unstamp still finds the
157    /// spawns whose marks must be lowered. Each is kept with the program it
158    /// was admitted under.
159    mark_records: Vec<(
160        std::sync::Weak<crate::spawn_authority::SpawnAuthorityRecord>,
161        Option<super::admission::AdmittedProgram>,
162    )>,
163}
164
165impl DeliveryState {
166    pub(super) fn reset_for_authority_exit(&mut self, generation: u64) {
167        *self = Self {
168            next_spawn: self.next_spawn,
169            next_attempt: self.next_attempt,
170            mark_records: std::mem::take(&mut self.mark_records),
171            ..Self::new(generation)
172        };
173    }
174    /// Remember `spawn` for the mark sweep when it was admitted under the
175    /// stamp with an authority record.
176    pub(super) fn track_mark(&mut self, spawn: &DeliverySpawn) {
177        let Some(record) = spawn.authority.as_ref().filter(|_| spawn.stamped) else {
178            return;
179        };
180        if !self
181            .mark_records
182            .iter()
183            .any(|(known, _)| std::ptr::eq(known.as_ptr(), std::sync::Arc::as_ptr(record)))
184        {
185            self.mark_records
186                .push((std::sync::Arc::downgrade(record), spawn.program.clone()));
187        }
188    }
189    /// The live spawns remembered for the mark sweep, each with the program
190    /// it was admitted under; forgets dead ones.
191    pub(super) fn mark_records(
192        &mut self,
193    ) -> Vec<(
194        std::sync::Arc<crate::spawn_authority::SpawnAuthorityRecord>,
195        Option<super::admission::AdmittedProgram>,
196    )> {
197        self.mark_records
198            .retain(|(record, _)| record.upgrade().is_some_and(|record| record.alive()));
199        self.mark_records
200            .iter()
201            .filter_map(|(record, program)| Some((record.upgrade()?, program.clone())))
202            .collect()
203    }
204    pub(super) fn started_at_generation(&self) -> u64 {
205        self.initial_generation
206    }
207    pub(super) fn policy_authorization(
208        &self,
209        module: &str,
210        generation: u64,
211        connection: ConnectionId,
212    ) -> Option<(u64, tokio::time::Instant)> {
213        let attempt = self.attempts.get(&connection)?;
214        let deadline = attempt.deadline?;
215        (attempt.module == module
216            && attempt.generation == generation
217            && attempt.delivered
218            && attempt.acknowledged
219            && tokio::time::Instant::now() < deadline)
220            .then_some((attempt.id, deadline))
221    }
222    pub(super) fn fenced_modules(&self) -> impl Iterator<Item = String> + '_ {
223        self.exited.keys().cloned()
224    }
225}
226
227/// Captured before a health RPC; only the same child and installed policy may
228/// consume its result. The fields are private so a completion cannot retarget it.
229#[derive(Clone, Debug)]
230pub struct DeliveryProbe {
231    connection: ConnectionId,
232    module: String,
233    generation: u64,
234    attempt: Option<u64>,
235    policy_epoch: u64,
236    route_readiness: bool,
237}
238
239impl DeliveryProbe {
240    pub(crate) fn connection(&self) -> ConnectionId {
241        self.connection
242    }
243    pub(crate) fn owns_failure(&self) -> bool {
244        self.route_readiness
245    }
246}
247
248#[derive(Clone)]
249pub(crate) struct ExitedDelivery {
250    pub module: String,
251    spawn: u64,
252    generation: u64,
253    changed: tokio::sync::watch::Sender<bool>,
254}
255
256#[derive(Clone, Debug, PartialEq, Eq)]
257pub enum AppliedDisposition {
258    Ignored,
259    WaitingForReadiness,
260    Active,
261    CatchupComplete,
262    Failed {
263        generation: u64,
264        restore: Option<u64>,
265        keep_running: bool,
266    },
267    CatchupFailed {
268        active: u64,
269    },
270}
271
272#[derive(Clone, Copy)]
273pub(crate) struct DeliveryWindow {
274    pub generation: u64,
275    pub attempt: u64,
276    pub delivered: bool,
277    pub deadline: Option<tokio::time::Instant>,
278}
279
280impl DeliveryState {
281    pub(super) fn invalidate_policy(&mut self, module: &str, generation: u64) {
282        for attempt in self
283            .attempts
284            .values_mut()
285            .filter(|attempt| attempt.module == module && attempt.generation == generation)
286        {
287            attempt.ready = false;
288            attempt.policy_probe_requested = false;
289        }
290    }
291    pub(super) fn policy_installed(
292        &mut self,
293        module: &str,
294        generation: u64,
295        target: Option<ConnectionId>,
296    ) -> Result<()> {
297        // The generation may be unchanged after a restore and retry. Use a
298        // separate epoch so a probe begun before this installation cannot count.
299        let epoch = self.policy_epochs.entry(module.into()).or_default();
300        *epoch = epoch.checked_add(1).ok_or_else(|| {
301            GateError::new(
302                "delivery_probe_exhausted",
303                "policy readiness epochs exhausted",
304            )
305        })?;
306        self.invalidate_policy(module, generation);
307        let connections: HashSet<_> = self
308            .children
309            .iter()
310            .filter(|(_, spawn)| spawn.module == module)
311            .map(|(connection, _)| *connection)
312            .chain(
313                self.attempts
314                    .iter()
315                    .filter(|(_, attempt)| attempt.module == module)
316                    .map(|(connection, _)| *connection),
317            )
318            .chain(target)
319            .collect();
320        self.readiness_observed.retain(|(connection, observed)| {
321            *observed != generation || !connections.contains(connection)
322        });
323        self.healthy_children.retain(|(connection, observed)| {
324            *observed != generation || !connections.contains(connection)
325        });
326        Ok(())
327    }
328    pub(super) fn declared(&mut self, connection: ConnectionId, module: &str, active: bool) {
329        if let Some(spawn) = self.unregistered_children.remove(&(module.into(), active)) {
330            self.children.insert(connection, spawn);
331        }
332    }
333    pub(super) fn new(initial_generation: u64) -> Self {
334        Self {
335            initial_generation,
336            ..Self::default()
337        }
338    }
339
340    /// Forget `connection`'s delivery state. Returns whether it had any.
341    pub(super) fn disconnected(&mut self, connection: ConnectionId) -> bool {
342        let mut held = self.attempts.remove(&connection).is_some();
343        held |= self.fallback_applied.remove(&connection).is_some();
344        held |= self.served.remove(&connection).is_some();
345        held |= self.unstamped_views.remove(&connection).is_some();
346        held |= self.stamp_running.remove(&connection);
347        held |= self.children.remove(&connection).is_some();
348        let observed = self.healthy_children.len() + self.readiness_observed.len();
349        self.healthy_children
350            .retain(|(child, _)| *child != connection);
351        self.readiness_observed
352            .retain(|(child, _)| *child != connection);
353        held || self.healthy_children.len() + self.readiness_observed.len() != observed
354    }
355
356    pub(super) fn remember_stamp_connections(&mut self, connections: Vec<ConnectionId>) {
357        self.stamp_running.extend(connections);
358    }
359
360    fn boundary_open(
361        &self,
362        connection: ConnectionId,
363        generation: u64,
364        transition: Transition,
365    ) -> bool {
366        if transition == Transition::DaemonRestart && generation > self.initial_generation {
367            return false;
368        }
369        !transition.requires_spawn()
370            || self
371                .children
372                .get(&connection)
373                .is_some_and(|spawn| spawn.generation == generation)
374    }
375
376    fn allocate(
377        &mut self,
378        module: &str,
379        generation: u64,
380        transition: Transition,
381    ) -> Result<Attempt> {
382        self.next_attempt = self.next_attempt.checked_add(1).ok_or_else(|| {
383            GateError::new(
384                "delivery_attempt_exhausted",
385                "delivery attempt ids exhausted",
386            )
387        })?;
388        Ok(Attempt {
389            module: module.into(),
390            generation,
391            id: self.next_attempt,
392            transition,
393            ready: transition == Transition::Live,
394            acknowledged: false,
395            delivered: false,
396            deadline: None,
397            catchup: false,
398            write_deadline: None,
399            policy_probe_requested: false,
400            spawn: None,
401            mark_only: false,
402            declaration_fallback: false,
403        })
404    }
405}
406
407pub(super) fn visible_reply(
408    state: &OwnerState,
409    connection: ConnectionId,
410    mut reply: ConfigGetReply,
411    transition: Transition,
412) -> Result<ConfigGetReply> {
413    if reply.pending.as_ref().is_some_and(|view| {
414        !state
415            .delivery
416            .boundary_open(connection, view.generation, transition)
417    }) {
418        reply.pending = None;
419    }
420    if reply.active.is_none() && reply.pending.is_none() {
421        return Err(GateError::new(
422            "config_gated",
423            "generation waits for its required supervision or daemon boundary",
424        ));
425    }
426    Ok(reply)
427}
428
429pub(super) fn bind_get(
430    state: &mut OwnerState,
431    connection: ConnectionId,
432    module: &str,
433    request: &ConfigGetRequest,
434    reply: ConfigGetReply,
435    transition: Transition,
436) -> Result<ConfigGetReply> {
437    let mut reply = visible_reply(state, connection, reply, transition)?;
438    match (request.generation, request.attempt) {
439        (None, None) => {}
440        (Some(generation), Some(attempt))
441            if state
442                .delivery
443                .attempts
444                .get(&connection)
445                .is_some_and(|bound| {
446                    bound.module == module && bound.generation == generation && bound.id == attempt
447                }) => {}
448        _ => {
449            return Err(GateError::new(
450                "config_gated",
451                "requested generation and attempt are not assigned to this connection",
452            ))
453        }
454    }
455    if reply.pending.is_none()
456        && state
457            .delivery
458            .attempts
459            .get(&connection)
460            .is_some_and(|bound| {
461                bound.catchup
462                    && reply
463                        .active
464                        .as_ref()
465                        .is_some_and(|view| view.generation == bound.generation)
466            })
467    {
468        reply.pending = reply.active.clone();
469        if let Some(view) = &mut reply.pending {
470            view.status = ConfigStatus::Pending;
471        }
472    }
473    if reply.pending.is_none() && request.generation.is_none() {
474        let generation = reply.active.as_ref().map(|view| view.generation);
475        if let Some(attempt) = generation
476            .map(|generation| mark_acknowledgement(state, connection, module, generation))
477            .transpose()?
478            .flatten()
479        {
480            state.delivery.attempts.insert(connection, attempt);
481            reply.pending = reply.active.clone();
482            if let Some(view) = &mut reply.pending {
483                view.status = ConfigStatus::Pending;
484            }
485        }
486    }
487    if let Some(pending) = &mut reply.pending {
488        let matches = state
489            .delivery
490            .attempts
491            .get(&connection)
492            .is_some_and(|bound| bound.module == module && bound.generation == pending.generation);
493        if !matches {
494            let mut attempt = state
495                .delivery
496                .allocate(module, pending.generation, transition)?;
497            if transition.requires_spawn() {
498                attempt.ready = state
499                    .delivery
500                    .healthy_children
501                    .contains(&(connection, pending.generation));
502                attempt.deadline = state
503                    .delivery
504                    .children
505                    .get(&connection)
506                    .filter(|warmup| warmup.generation == pending.generation)
507                    .map(|warmup| warmup.deadline);
508            }
509            attempt.ready &= super::route_policy::ready(state, module, pending.generation)?;
510            attempt.spawn = state.delivery.children.get(&connection).cloned();
511            state.delivery.attempts.insert(connection, attempt);
512        }
513        pending.attempt = state
514            .delivery
515            .attempts
516            .get(&connection)
517            .map(|bound| bound.id);
518        let mark_only = state
519            .delivery
520            .attempts
521            .get(&connection)
522            .is_some_and(|bound| bound.mark_only);
523        if state.active_declarations.get(module) == Some(&connection) && !mark_only {
524            if let Some(spawn) = state.delivery.children.get(&connection) {
525                let id = spawn.id;
526                state
527                    .delivery
528                    .last_target_attempt
529                    .insert(module.into(), (id, pending.generation));
530            }
531        }
532    } else {
533        state.delivery.attempts.remove(&connection);
534    }
535    if request
536        .generation
537        .is_some_and(|id| reply.pending.as_ref().map(|view| view.generation) != Some(id))
538    {
539        return Err(GateError::new(
540            "config_gated",
541            "selected delivery has been superseded",
542        ));
543    }
544    Ok(reply)
545}
546
547pub(super) fn bind_declaration_fallback(
548    state: &mut OwnerState,
549    connection: ConnectionId,
550    module: &str,
551    request: &ConfigGetRequest,
552    mut reply: ConfigGetReply,
553) -> Result<ConfigGetReply> {
554    let active = reply.active.as_mut().ok_or_else(|| {
555        GateError::new(
556            "config_gated",
557            "module has no approved active configuration",
558        )
559    })?;
560    if request.generation.is_some() || request.attempt.is_some() {
561        let assigned = state
562            .delivery
563            .attempts
564            .get(&connection)
565            .is_some_and(|attempt| {
566                attempt.declaration_fallback
567                    && attempt.module == module
568                    && Some(attempt.generation) == request.generation
569                    && Some(attempt.id) == request.attempt
570                    && attempt.generation == active.generation
571            });
572        if !assigned {
573            return Err(GateError::new(
574                "config_gated",
575                "requested fallback attempt is not assigned to this connection",
576            ));
577        }
578    }
579    if state.delivery.fallback_applied.get(&connection) == Some(&active.generation) {
580        return Ok(reply);
581    }
582    if !state
583        .delivery
584        .attempts
585        .get(&connection)
586        .is_some_and(|attempt| {
587            attempt.declaration_fallback && attempt.generation == active.generation
588        })
589    {
590        // Serve only the daemon's approved bytes: a module-owned copy could be
591        // edited without approval. Re-applying them is connection-local catch-up,
592        // never an activation of a generation under the unapproved declaration.
593        let mut attempt = state
594            .delivery
595            .allocate(module, active.generation, Transition::Live)?;
596        attempt.catchup = true;
597        attempt.declaration_fallback = true;
598        attempt.spawn = state.delivery.children.get(&connection).cloned();
599        state.delivery.attempts.insert(connection, attempt);
600    }
601    active.attempt = state
602        .delivery
603        .attempts
604        .get(&connection)
605        .map(|attempt| attempt.id);
606    Ok(reply)
607}
608
609/// The catch-up attempt that asks a fresh spawn to acknowledge its module's
610/// active generation, so the spawn can earn the first-party mark: a spawn is
611/// marked only after it acknowledged the active generation and reported
612/// ready, on every start path. Delivering
613/// the active view at launch is not proof the spawn applied it, and without a
614/// pending change a crash, health, manual or boot restart is otherwise never
615/// asked for an acknowledgement.
616///
617/// Assigned only to the active target of a stamped, gated module whose spawn
618/// carries an authority record that could still be marked, at most once per
619/// active generation; never when a pending change already has an attempt.
620/// Unstamped and ungated modules are never asked, so their delivery is
621/// unchanged. A refusal or timeout leaves the spawn unmarked and starts no
622/// recovery.
623fn mark_acknowledgement(
624    state: &mut OwnerState,
625    connection: ConnectionId,
626    module: &str,
627    generation: u64,
628) -> Result<Option<Attempt>> {
629    if state.store.loaded_admission_state().0 != crate::config_store::StoreState::Stamped
630        || state.active_declarations.get(module) != Some(&connection)
631        || state.delivery.attempts.contains_key(&connection)
632    {
633        return Ok(None);
634    }
635    let Some(spawn) = state
636        .delivery
637        .children
638        .get(&connection)
639        .filter(|spawn| spawn.stamped && spawn.module == module)
640        .cloned()
641    else {
642        return Ok(None);
643    };
644    let Some(record) = spawn.authority.as_ref() else {
645        return Ok(None);
646    };
647    let facts = record.mark_facts();
648    if !facts.unmarked || !facts.origin_qualifies || !record.request_acknowledgement(generation) {
649        return Ok(None);
650    }
651    let mut attempt = state
652        .delivery
653        .allocate(module, generation, Transition::Live)?;
654    attempt.catchup = true;
655    attempt.mark_only = true;
656    attempt.spawn = Some(spawn);
657    Ok(Some(attempt))
658}
659
660impl RuntimeOwner {
661    pub(crate) fn policy_probe_due(&self, connection: ConnectionId) -> Result<Option<(u64, u64)>> {
662        let mut state = self.lock()?;
663        let Some(bound) = state.delivery.attempts.get(&connection) else {
664            return Ok(None);
665        };
666        let (module, generation, attempt) = (bound.module.clone(), bound.generation, bound.id);
667        // A mark-only attempt asks for an acknowledgement and nothing else;
668        // readiness and route policy belong to the spawn's ordinary delivery.
669        if bound.ready
670            || bound.mark_only
671            || bound.policy_probe_requested
672            || state.active_declarations.get(&module) != Some(&connection)
673            || !state
674                .store
675                .body()?
676                .generations
677                .get(&generation)
678                .is_some_and(|entry| {
679                    super::route_policy::required(&entry.generation.changeset, &module)
680                })
681            || !super::route_policy::ready(&mut state, &module, generation)?
682        {
683            return Ok(None);
684        }
685        state
686            .delivery
687            .attempts
688            .get_mut(&connection)
689            .unwrap()
690            .policy_probe_requested = true;
691        Ok(Some((generation, attempt)))
692    }
693
694    pub(crate) fn policy_probe_pending(
695        &self,
696        connection: ConnectionId,
697        generation: u64,
698        attempt: u64,
699    ) -> Result<bool> {
700        let mut state = self.lock()?;
701        let Some(bound) = state.delivery.attempts.get(&connection) else {
702            return Ok(false);
703        };
704        let module = bound.module.clone();
705        Ok(bound.generation == generation
706            && bound.id == attempt
707            && !bound.ready
708            && state.active_declarations.get(&module) == Some(&connection)
709            && super::route_policy::ready(&mut state, &module, generation)?)
710    }
711    pub(crate) fn delivery_health_probe(
712        &self,
713        connection: ConnectionId,
714        module: &str,
715    ) -> Result<Option<DeliveryProbe>> {
716        let mut state = self.lock()?;
717        if state.active_declarations.get(module) != Some(&connection) {
718            return Ok(None);
719        }
720        let attempt = state
721            .delivery
722            .attempts
723            .get(&connection)
724            .map(|attempt| (attempt.generation, attempt.id));
725        let generation = attempt.map(|attempt| attempt.0).or_else(|| {
726            state
727                .delivery
728                .children
729                .get(&connection)
730                .map(|child| child.generation)
731        });
732        let route_readiness = match generation {
733            Some(generation) if attempt.is_some() => state
734                .store
735                .body()?
736                .generations
737                .get(&generation)
738                .is_some_and(|entry| {
739                    super::route_policy::required(&entry.generation.changeset, module)
740                }),
741            _ => false,
742        };
743        Ok(generation.map(|generation| DeliveryProbe {
744            connection,
745            module: module.into(),
746            generation,
747            attempt: attempt.map(|attempt| attempt.1),
748            route_readiness,
749            policy_epoch: state
750                .delivery
751                .policy_epochs
752                .get(module)
753                .copied()
754                .unwrap_or_default(),
755        }))
756    }
757
758    pub(crate) fn delivery_health_result(
759        &self,
760        probe: DeliveryProbe,
761        healthy: bool,
762    ) -> Result<Option<AppliedDisposition>> {
763        let attempt = {
764            let mut state = self.lock()?;
765            if state.active_declarations.get(&probe.module) != Some(&probe.connection)
766                || state
767                    .delivery
768                    .policy_epochs
769                    .get(&probe.module)
770                    .copied()
771                    .unwrap_or_default()
772                    != probe.policy_epoch
773            {
774                return Ok(None);
775            }
776            let current = state.delivery.attempts.get(&probe.connection);
777            if probe
778                .attempt
779                .is_some_and(|id| current.is_none_or(|bound| bound.id != id))
780                || current.is_some_and(|bound| bound.generation != probe.generation)
781            {
782                return Ok(None);
783            }
784            // A warm-up probe answering not ready is no answer to a mark-only
785            // attempt: only the spawn's own acknowledgement settles it, so a
786            // spawn still warming up is never refused the mark by a probe.
787            let attempt = current
788                .filter(|bound| !bound.mark_only)
789                .map(|bound| bound.id);
790            if !healthy
791                && (!super::route_policy::ready(&mut state, &probe.module, probe.generation)?
792                    || !state
793                        .store
794                        .body()?
795                        .generations
796                        .get(&probe.generation)
797                        .is_some_and(|entry| {
798                            super::route_policy::required(
799                                &entry.generation.changeset,
800                                &probe.module,
801                            )
802                        }))
803            {
804                return Ok(None);
805            }
806            attempt
807        };
808        if healthy {
809            self.delivery_readiness_complete(probe.connection, &probe.module, probe.generation)
810        } else if let Some(attempt) = attempt {
811            self.module_outcome(
812                probe.connection,
813                &probe.module,
814                ConfigAppliedRequest::new(
815                    probe.generation,
816                    attempt,
817                    subc_protocol::config::ConfigApplyResult::Nack,
818                    vec![],
819                ),
820                true,
821            )
822            .map(Some)
823        } else {
824            Ok(None)
825        }
826    }
827
828    #[cfg(test)]
829    pub(super) fn ready(
830        &self,
831        connection: ConnectionId,
832        module: &str,
833        generation: u64,
834    ) -> Result<Option<AppliedDisposition>> {
835        self.delivery_readiness_complete(connection, module, generation)
836    }
837
838    pub(crate) fn pending_config_restarts(&self) -> Result<Vec<(String, u64)>> {
839        let mut state = self.lock()?;
840        state.store_read(ConfigStore::delivery_ready)?;
841        let body = state.checked_body()?;
842        body.versions
843            .iter()
844            .filter(|(tuple, _)| tuple.project.is_none())
845            .filter_map(|(tuple, versions)| {
846                let generation = versions.pending?;
847                let entry = body.generations.get(&generation)?;
848                Some(
849                    Transition::for_module(&entry.generation.changeset, &tuple.module).map(
850                        |transition| {
851                            (transition == Transition::ModuleRestart)
852                                .then(|| (tuple.module.clone(), generation))
853                        },
854                    ),
855                )
856            })
857            .collect::<Result<Vec<_>>>()
858            .map(|entries| entries.into_iter().flatten().collect())
859    }
860
861    pub(crate) fn requires_fresher_spawn(
862        &self,
863        module: &str,
864        spawn: Option<&DeliverySpawn>,
865    ) -> Result<Option<u64>> {
866        let mut state = self.lock()?;
867        state.store.delivery_ready()?;
868        Self::requires_fresher_spawn_loaded(&state, module, spawn)
869    }
870
871    pub(super) fn requires_fresher_spawn_loaded(
872        state: &OwnerState,
873        module: &str,
874        spawn: Option<&DeliverySpawn>,
875    ) -> Result<Option<u64>> {
876        let body = state.store.loaded_admission_state().1;
877        let pending = body
878            .versions
879            .iter()
880            .find(|(tuple, _)| tuple.module == module && tuple.project.is_none())
881            .and_then(|(_, versions)| versions.pending);
882        let Some(generation) = pending else {
883            return Ok(None);
884        };
885        let entry = body
886            .generations
887            .get(&generation)
888            .ok_or_else(|| GateError::new("config_gated", "pending generation is absent"))?;
889        let transition = Transition::for_module(&entry.generation.changeset, module)?;
890        let deferred_daemon = transition == Transition::DaemonRestart
891            && generation > state.delivery.initial_generation;
892        Ok((transition.requires_spawn()
893            && !deferred_daemon
894            && spawn
895                .is_none_or(|spawn| spawn.module != module || spawn.generation() != generation))
896        .then_some(generation))
897    }
898
899    /// A supervised process exit, not a transport disconnect, fails warm-up.
900    /// The synchronous fence closes the gap before the async failure commit.
901    pub(crate) fn delivery_child_exited(&self, spawn: &DeliverySpawn) -> Result<()> {
902        let mut state = self.lock()?;
903        let pending = state
904            .store
905            .body()?
906            .versions
907            .iter()
908            .find(|(tuple, _)| tuple.module == spawn.module && tuple.project.is_none())
909            .and_then(|(_, versions)| versions.pending);
910        let pending = pending.filter(|generation| {
911            state
912                .store
913                .loaded_admission_state()
914                .1
915                .generations
916                .get(generation)
917                .and_then(|entry| entry.delivery.as_ref())
918                .is_some_and(|delivery| delivery.declarations.contains_key(&spawn.module))
919        });
920        if let Some(generation) = pending.filter(|generation| {
921            *generation == spawn.generation
922                || state.delivery.last_target_attempt.get(&spawn.module)
923                    == Some(&(spawn.id, *generation))
924        }) {
925            state
926                .delivery
927                .exited
928                .entry(spawn.module.clone())
929                .or_insert_with(|| ExitedDelivery {
930                    module: spawn.module.clone(),
931                    spawn: spawn.id,
932                    generation,
933                    changed: tokio::sync::watch::channel(true).0,
934                });
935        }
936        self.notify_delivery_changed();
937        Ok(())
938    }
939
940    pub(crate) fn delivery_exit_fence(
941        &self,
942        module: &str,
943    ) -> Result<Option<tokio::sync::watch::Receiver<bool>>> {
944        Ok(self
945            .lock()?
946            .delivery
947            .exited
948            .get(module)
949            .map(|entry| entry.changed.subscribe()))
950    }
951
952    pub(crate) fn delivery_exits(&self) -> Result<Vec<ExitedDelivery>> {
953        Ok(self.lock()?.delivery.exited.values().cloned().collect())
954    }
955
956    /// The delivery worker holds this module's asynchronous configuration lock
957    /// while recording the failure. Respawn stays blocked until the failure has
958    /// restored the previous active generation or, if none exists, the supervisor
959    /// has canceled respawn and stopped the module.
960    /// `AnchorPending` still restores the previous active generation in memory;
961    /// its durable failure record is retried before delivery can resume.
962    pub(crate) fn delivery_record_exit(&self, exited: &ExitedDelivery) -> Result<bool> {
963        #[cfg(test)]
964        self.exit_record_attempts
965            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
966        let mut state = self.lock()?;
967        if !state
968            .delivery
969            .exited
970            .get(&exited.module)
971            .is_some_and(|entry| entry.spawn == exited.spawn)
972        {
973            return Ok(false);
974        }
975        let tuple = Tuple {
976            module: exited.module.clone(),
977            project: None,
978        };
979        let versions = state
980            .store
981            .body()?
982            .versions
983            .iter()
984            .find(|(key, _)| key == &tuple)
985            .map(|(_, versions)| versions.clone())
986            .unwrap_or_default();
987        if versions
988            .pending
989            .is_some_and(|generation| generation != exited.generation)
990        {
991            return Ok(false);
992        }
993        if versions.pending == Some(exited.generation) {
994            state.restore_route_policy(&exited.module, exited.generation);
995            let result = state
996                .store
997                .record_delivery(&tuple, exited.generation, false);
998            if let Err(error) = result {
999                if error.code != crate::config_store::StoreErrorCode::AnchorPending {
1000                    return Err(error.into());
1001                }
1002            }
1003            state.delivery.attempts.retain(|_, attempt| {
1004                attempt.module != exited.module || attempt.generation != exited.generation
1005            });
1006        }
1007        Ok(versions.active.is_none())
1008    }
1009
1010    #[cfg(all(test, unix))]
1011    pub(crate) fn exit_record_attempts_for_test(&self) -> usize {
1012        self.exit_record_attempts
1013            .load(std::sync::atomic::Ordering::SeqCst)
1014    }
1015
1016    pub(crate) fn delivery_release_exit(&self, exited: &ExitedDelivery) -> Result<()> {
1017        let mut state = self.lock()?;
1018        if state
1019            .delivery
1020            .exited
1021            .get(&exited.module)
1022            .is_some_and(|entry| entry.spawn == exited.spawn)
1023        {
1024            if let Some(entry) = state.delivery.exited.remove(&exited.module) {
1025                entry.changed.send_replace(false);
1026                // A prior release may have reached the worker while this fence
1027                // still blocked admission. Recheck it after the fence is gone;
1028                // the worker starts only enabled modules with no remaining hold.
1029                state.admission_releases.push(exited.module.clone());
1030            }
1031        }
1032        self.notify_delivery_changed();
1033        Ok(())
1034    }
1035    pub(crate) fn delivery_abandon_spawn(&self, spawn: &DeliverySpawn, active: bool) {
1036        if let Ok(mut state) = self.lock() {
1037            let key = (spawn.module.clone(), active);
1038            if state
1039                .delivery
1040                .unregistered_children
1041                .get(&key)
1042                .is_some_and(|current| current.id == spawn.id)
1043            {
1044                state.delivery.unregistered_children.remove(&key);
1045            }
1046        }
1047    }
1048    pub(crate) fn delivery_queue_abandoned_spawn(&self, spawn: DeliverySpawn, active: bool) {
1049        if let Ok(mut abandoned) = self.abandoned_spawns.lock() {
1050            abandoned.push((spawn, active));
1051        }
1052        self.notify_delivery_changed();
1053    }
1054    /// Forget spawns abandoned while the owner was busy. Returns whether any
1055    /// was queued.
1056    pub(super) fn drain_abandoned_spawns(&self, state: &mut OwnerState) -> bool {
1057        let mut drained = false;
1058        if let Ok(mut abandoned) = self.abandoned_spawns.lock() {
1059            for (spawn, active) in abandoned.drain(..) {
1060                drained = true;
1061                let key = (spawn.module.clone(), active);
1062                if state
1063                    .delivery
1064                    .unregistered_children
1065                    .get(&key)
1066                    .is_some_and(|current| current.id == spawn.id)
1067                {
1068                    state.delivery.unregistered_children.remove(&key);
1069                }
1070            }
1071        }
1072        drained
1073    }
1074
1075    /// The full authority check and reservation ran on a blocking worker while
1076    /// the caller owned the module gate. Recheck only that exact witness here;
1077    /// contention asks the async caller to wait off the runtime thread.
1078    pub(crate) fn delivery_launch_current(
1079        &self,
1080        spawn: &DeliverySpawn,
1081        active: bool,
1082    ) -> Result<Option<bool>> {
1083        let state = match self.inner.try_lock() {
1084            Ok(state) => state,
1085            Err(std::sync::TryLockError::WouldBlock) => return Ok(None),
1086            Err(_) => {
1087                return Err(GateError::new(
1088                    "config_unavailable",
1089                    "configuration owner lock is poisoned",
1090                ))
1091            }
1092        };
1093        Ok(Some(
1094            super::admission::AdmissionCache::from_state(&state)
1095                .spawn_generation(&spawn.module)
1096                .is_ok_and(|generation| generation == spawn.generation)
1097                && state
1098                    .delivery
1099                    .unregistered_children
1100                    .get(&(spawn.module.clone(), active))
1101                    .is_some_and(|current| current.id == spawn.id)
1102                && !state.delivery.exited.contains_key(&spawn.module),
1103        ))
1104    }
1105    #[cfg(test)]
1106    pub(crate) fn pause_spawn_preflight_for_test(&self) {
1107        let hook = self.spawn_preflight_hook.lock().unwrap().take();
1108        if let Some(hook) = hook {
1109            hook();
1110        }
1111    }
1112    #[cfg(all(test, unix))]
1113    pub(crate) fn exhaust_delivery_spawns_for_test(&self) {
1114        self.lock().unwrap().delivery.next_spawn = u64::MAX;
1115    }
1116    #[cfg(all(test, unix))]
1117    pub(crate) fn restore_unused_delivery_spawns_for_test(&self) {
1118        self.lock().unwrap().delivery.next_spawn = 1000;
1119    }
1120    #[cfg(all(test, unix))]
1121    pub(crate) fn fail_delivery_spawns_for_module_for_test(&self, module: &str) {
1122        self.lock().unwrap().delivery.failed_spawn_module = Some(module.into());
1123    }
1124    #[cfg(all(test, unix))]
1125    pub(crate) fn clear_delivery_spawn_failure_for_test(&self) {
1126        self.lock().unwrap().delivery.failed_spawn_module = None;
1127    }
1128    #[cfg(all(test, unix))]
1129    pub(crate) fn set_spawn_preflight_hook_for_test(&self, hook: impl FnOnce() + Send + 'static) {
1130        *self.spawn_preflight_hook.lock().unwrap() = Some(Box::new(hook));
1131    }
1132    #[cfg(all(test, unix))]
1133    pub(crate) fn unregistered_spawn_count_for_test(&self) -> usize {
1134        self.lock().unwrap().delivery.unregistered_children.len()
1135    }
1136    #[allow(clippy::too_many_arguments)]
1137    pub(crate) fn delivery_spawned_for_admission_in_slot(
1138        &self,
1139        module: &str,
1140        admission: &super::admission::SpawnAdmission,
1141        at: tokio::time::Instant,
1142        register: Duration,
1143        health: Duration,
1144        active: bool,
1145        authority: Option<std::sync::Arc<crate::spawn_authority::SpawnAuthorityRecord>>,
1146    ) -> Result<Option<DeliverySpawn>> {
1147        let mut state = OwnerGuard::new(
1148            self.inner.try_lock().map_err(|error| {
1149                if matches!(error, std::sync::TryLockError::Poisoned(_)) {
1150                    return GateError::new("config_unavailable", "configuration owner is poisoned");
1151                }
1152                GateError::new(
1153                    "config_delivery_deferred",
1154                    "configuration publication is busy",
1155                )
1156            })?,
1157            self,
1158        );
1159        state.store.check()?;
1160        // Admission under the stamped gate is the only way to the mark: a
1161        // stamp never marks a child admitted before it.
1162        let stamped = admission.gated()
1163            && state.store.loaded_admission_state().0 == crate::config_store::StoreState::Stamped;
1164        let spawn = allocate_spawn(
1165            &mut state,
1166            module,
1167            admission.generation(),
1168            at,
1169            register,
1170            health,
1171            authority.map(|record| (record, stamped)),
1172            admission.admitted_program(),
1173        )?;
1174        state.delivery.track_mark(&spawn);
1175        state
1176            .delivery
1177            .unregistered_children
1178            .insert((module.into(), active), spawn.clone());
1179        Ok(Some(spawn))
1180    }
1181
1182    #[cfg(test)]
1183    pub(crate) fn delivery_spawned_in_slot(
1184        &self,
1185        module: &str,
1186        at: tokio::time::Instant,
1187        register: Duration,
1188        health: Duration,
1189        active: bool,
1190    ) -> Result<Option<DeliverySpawn>> {
1191        let spawn = self.delivery_spawned(module, at, register, health)?;
1192        if let Some(spawn) = &spawn {
1193            self.lock()?
1194                .delivery
1195                .unregistered_children
1196                .insert((module.into(), active), spawn.clone());
1197        }
1198        Ok(spawn)
1199    }
1200    pub(crate) fn delivery_take_recoveries(
1201        &self,
1202    ) -> Result<Vec<(ConnectionId, String, AppliedDisposition)>> {
1203        let mut state = self.lock()?;
1204        if state.delivery.recoveries.is_empty() {
1205            // Nothing to take: leave the owner unchanged.
1206            return Ok(Vec::new());
1207        }
1208        Ok(std::mem::take(&mut state.delivery.recoveries))
1209    }
1210
1211    pub(crate) fn delivery_window(
1212        &self,
1213        connection: ConnectionId,
1214    ) -> Result<Option<DeliveryWindow>> {
1215        Ok(self
1216            .lock()?
1217            .delivery
1218            .attempts
1219            .get(&connection)
1220            .map(|bound| DeliveryWindow {
1221                generation: bound.generation,
1222                attempt: bound.id,
1223                delivered: bound.delivered,
1224                deadline: bound.deadline,
1225            }))
1226    }
1227
1228    pub(crate) fn delivery_write_started(
1229        &self,
1230        connection: ConnectionId,
1231        generation: u64,
1232        attempt: u64,
1233        now: tokio::time::Instant,
1234    ) -> Result<()> {
1235        if let Some(bound) = self
1236            .lock()?
1237            .delivery
1238            .attempts
1239            .get_mut(&connection)
1240            .filter(|bound| {
1241                bound.generation == generation && bound.id == attempt && !bound.delivered
1242            })
1243        {
1244            bound
1245                .write_deadline
1246                .get_or_insert(now + CONFIG_LIVE_ACK_TIMEOUT);
1247        }
1248        Ok(())
1249    }
1250
1251    pub(crate) fn delivery_timeout(
1252        &self,
1253        connection: ConnectionId,
1254        module: &str,
1255        generation: u64,
1256        attempt: u64,
1257    ) -> Result<AppliedDisposition> {
1258        self.module_outcome(
1259            connection,
1260            module,
1261            ConfigAppliedRequest::new(
1262                generation,
1263                attempt,
1264                subc_protocol::config::ConfigApplyResult::Nack,
1265                vec![],
1266            ),
1267            true,
1268        )
1269    }
1270
1271    /// Capture the common spawn instant, not the later HELLO instant, so a slow
1272    /// registration cannot extend the approved generation's warm-up deadline.
1273    pub(crate) fn delivery_spawned(
1274        &self,
1275        module: &str,
1276        spawned_at: tokio::time::Instant,
1277        register_timeout: Duration,
1278        first_health_budget: Duration,
1279    ) -> Result<Option<DeliverySpawn>> {
1280        let mut state = self.lock()?;
1281        state.store.check()?;
1282        let admission = super::admission::AdmissionCache::from_state(&state);
1283        let generation = admission.spawn_generation(module)?;
1284        allocate_spawn(
1285            &mut state,
1286            module,
1287            generation,
1288            spawned_at,
1289            register_timeout,
1290            first_health_budget,
1291            None,
1292            admission.admitted_program(module),
1293        )
1294        .map(Some)
1295    }
1296
1297    pub(crate) fn delivery_child_registered(
1298        &self,
1299        connection: ConnectionId,
1300        spawn: &DeliverySpawn,
1301    ) -> Result<()> {
1302        let mut state = self.lock()?;
1303        state.delivery.track_mark(spawn);
1304        state.delivery.children.insert(connection, spawn.clone());
1305        if let Some(bound) = state
1306            .delivery
1307            .attempts
1308            .get_mut(&connection)
1309            .filter(|bound| bound.module == spawn.module && bound.generation == spawn.generation)
1310        {
1311            if bound.transition.requires_spawn() {
1312                bound.deadline = Some(spawn.deadline);
1313            }
1314        }
1315        Ok(())
1316    }
1317
1318    pub(crate) fn module_view_delivered(
1319        &self,
1320        connection: ConnectionId,
1321        module: &str,
1322        reply: &ConfigGetReply,
1323        written_at: tokio::time::Instant,
1324        active: bool,
1325    ) -> Result<()> {
1326        {
1327            let mut state = self.lock()?;
1328            if !state
1329                .declarations
1330                .get(&connection)
1331                .is_some_and(|(id, _)| id == module)
1332            {
1333                return Err(GateError::new(
1334                    "not_delivery_target",
1335                    "configuration connection has ended",
1336                ));
1337            }
1338            let before = store_witness(&state.store);
1339            let checked = state.store_read(ConfigStore::check);
1340            if store_witness(&state.store) != before {
1341                self.notify_delivery_changed();
1342            }
1343            checked?;
1344            let (_, body) = state.store.loaded_admission_state();
1345            if body.stamped {
1346                let versions = body
1347                    .versions
1348                    .iter()
1349                    .find(|(tuple, _)| tuple.module == module && tuple.project.is_none())
1350                    .map(|(_, versions)| versions.clone())
1351                    .unwrap_or_default();
1352                if reply
1353                    .active
1354                    .as_ref()
1355                    .is_some_and(|view| versions.active != Some(view.generation))
1356                    || reply.pending.as_ref().is_some_and(|view| {
1357                        // A promoted child catches up to the durable active
1358                        // vector through its own pending, child-local attempt.
1359                        let catchup = versions.active == Some(view.generation)
1360                            && state
1361                                .delivery
1362                                .attempts
1363                                .get(&connection)
1364                                .is_some_and(|bound| {
1365                                    bound.catchup
1366                                        && bound.generation == view.generation
1367                                        && Some(bound.id) == view.attempt
1368                                });
1369                        versions.pending != Some(view.generation) && !catchup
1370                    })
1371                {
1372                    return Err(GateError::new(
1373                        "delivery_superseded",
1374                        "configuration changed while its view was being written",
1375                    ));
1376                }
1377            }
1378        }
1379        if active {
1380            if reply.declaration_pending.is_some() {
1381                if let Some(view) = &reply.active {
1382                    if let Some(attempt) = view.attempt {
1383                        self.record_rpc_write(connection, view.generation, attempt, written_at)?;
1384                    }
1385                }
1386            }
1387            if let Some(view) = &reply.pending {
1388                if let Some(attempt) = view.attempt {
1389                    self.record_rpc_write(connection, view.generation, attempt, written_at)?;
1390                }
1391            }
1392        }
1393        let mut state = self.lock()?;
1394        if !state
1395            .declarations
1396            .get(&connection)
1397            .is_some_and(|(id, _)| id == module)
1398        {
1399            return Err(GateError::new(
1400                "not_delivery_target",
1401                "configuration connection has ended",
1402            ));
1403        }
1404        if record_served_view(&mut state, connection, reply) {
1405            self.notify_delivery_changed();
1406        }
1407        Ok(())
1408    }
1409    /// Completion is supplied by the supervisor after registration, the first
1410    /// healthy probe and any required route teardown, never by a module body.
1411    pub(crate) fn delivery_readiness_complete(
1412        &self,
1413        connection: ConnectionId,
1414        module: &str,
1415        generation: u64,
1416    ) -> Result<Option<AppliedDisposition>> {
1417        let attempt = {
1418            let mut state = self.lock()?;
1419            if state.active_declarations.get(module) != Some(&connection) {
1420                return Err(GateError::new(
1421                    "not_delivery_target",
1422                    "readiness belongs to another connection",
1423                ));
1424            }
1425            let started_for_generation = state
1426                .delivery
1427                .children
1428                .get(&connection)
1429                .is_some_and(|warmup| warmup.generation == generation);
1430            if started_for_generation {
1431                state
1432                    .delivery
1433                    .healthy_children
1434                    .insert((connection, generation));
1435            }
1436            let policy_ready = super::route_policy::ready(&mut state, module, generation)?;
1437            let Some(bound) = state
1438                .delivery
1439                .attempts
1440                .get_mut(&connection)
1441                .filter(|bound| bound.module == module && bound.generation == generation)
1442            else {
1443                return Ok(None);
1444            };
1445            if bound.transition.requires_spawn() && !started_for_generation {
1446                return Ok(None);
1447            }
1448            bound.ready = policy_ready;
1449            let acknowledged = bound.ready && bound.acknowledged;
1450            let id = bound.id;
1451            state
1452                .delivery
1453                .readiness_observed
1454                .insert((connection, generation));
1455            acknowledged.then_some(id)
1456        };
1457        attempt
1458            .map(|attempt| {
1459                self.module_applied(
1460                    connection,
1461                    module,
1462                    ConfigAppliedRequest::new(
1463                        generation,
1464                        attempt,
1465                        subc_protocol::config::ConfigApplyResult::Ack,
1466                        vec![],
1467                    ),
1468                )
1469            })
1470            .transpose()
1471    }
1472
1473    /// Both forwarding and registry promotion happen under the caller's module
1474    /// gate before this connection becomes an acknowledgement target.
1475    pub(crate) fn delivery_promoted(
1476        &self,
1477        connection: ConnectionId,
1478        module: &str,
1479        cutover_at: tokio::time::Instant,
1480    ) -> Result<Option<(u64, u64)>> {
1481        let mut state = self.lock()?;
1482        state.store.delivery_ready()?;
1483        Self::promote_loaded(&mut state, connection, module, cutover_at)
1484    }
1485
1486    pub(super) fn promote_loaded(
1487        state: &mut OwnerState,
1488        connection: ConnectionId,
1489        module: &str,
1490        cutover_at: tokio::time::Instant,
1491    ) -> Result<Option<(u64, u64)>> {
1492        if state.store.loaded_admission_state().0 == crate::config_store::StoreState::Unstamped {
1493            if state
1494                .declarations
1495                .get(&connection)
1496                .is_some_and(|(id, _)| id == module)
1497            {
1498                state.phone_target_changed(module, connection);
1499                state.active_declarations.insert(module.into(), connection);
1500            }
1501            return Ok(None);
1502        }
1503        let Some((id, declaration)) = state
1504            .declarations
1505            .get(&connection)
1506            .cloned()
1507            .filter(|(id, _)| id == module)
1508        else {
1509            return Err(GateError::new(
1510                "config_gated",
1511                "candidate has not declared its approved configuration",
1512            ));
1513        };
1514        let tuple = Tuple {
1515            module: module.into(),
1516            project: None,
1517        };
1518        let body = state.store.loaded_admission_state().1;
1519        let versions = body
1520            .versions
1521            .iter()
1522            .find(|(key, _)| key == &tuple)
1523            .map(|(_, versions)| versions.clone())
1524            .unwrap_or_default();
1525        let transition = versions
1526            .pending
1527            .and_then(|id| body.generations.get(&id))
1528            .map(|entry| Transition::for_module(&entry.generation.changeset, module))
1529            .transpose()?
1530            .unwrap_or(Transition::Live);
1531        let pending_declaration = versions
1532            .pending
1533            .and_then(|id| body.generations.get(&id))
1534            .and_then(|entry| entry.delivery.as_ref())
1535            .and_then(|snapshot| snapshot.declarations.get(module))
1536            .cloned();
1537        let active_declaration = versions
1538            .active
1539            .and_then(|id| body.generations.get(&id))
1540            .and_then(|entry| entry.delivery.as_ref())
1541            .and_then(|snapshot| snapshot.declarations.get(module))
1542            .cloned();
1543        let pending = versions.pending.filter(|generation| {
1544            state
1545                .delivery
1546                .boundary_open(connection, *generation, transition)
1547        });
1548        if pending != versions.pending && transition != Transition::DaemonRestart {
1549            return Err(GateError::new(
1550                "config_gated",
1551                "candidate launch was superseded by a configuration requiring a fresh start",
1552            ));
1553        }
1554        let expected = if pending.is_some() {
1555            pending_declaration
1556        } else {
1557            active_declaration
1558        };
1559        if expected.as_ref() != Some(&declaration) {
1560            return Err(GateError::new(
1561                "config_gated",
1562                "candidate declaration differs from the approved declaration",
1563            ));
1564        }
1565        let transition = if pending.is_some() {
1566            transition
1567        } else {
1568            Transition::Live
1569        };
1570        let vector = (versions.active, pending);
1571        let catchup = pending.is_none()
1572            && versions.active.is_some()
1573            && state.delivery.served.get(&connection) != Some(&vector);
1574        state.phone_target_changed(module, connection);
1575        state.active_declarations.insert(id, connection);
1576        state.delivery.attempts.remove(&connection);
1577        let Some(generation) = pending.or_else(|| catchup.then_some(versions.active).flatten())
1578        else {
1579            return Ok(None);
1580        };
1581        let mut attempt = state.delivery.allocate(module, generation, transition)?;
1582        attempt.catchup = catchup;
1583        attempt.spawn = state.delivery.children.get(&connection).cloned();
1584        // Swap readiness completed before promotion. Its new target now gets
1585        // a full live ACK window, independently of the finished spawn budget.
1586        // A route obligation still needs its own post-install probe: the
1587        // candidate's earlier HEALTHY did not bind the installed policy epoch.
1588        attempt.ready = super::route_policy::ready_loaded(state, module, generation)
1589            && !state
1590                .store
1591                .loaded_admission_state()
1592                .1
1593                .generations
1594                .get(&generation)
1595                .is_some_and(|entry| {
1596                    super::route_policy::required(&entry.generation.changeset, module)
1597                });
1598        attempt.deadline = Some(cutover_at + CONFIG_LIVE_ACK_TIMEOUT);
1599        let assignment = (generation, attempt.id);
1600        state.delivery.attempts.insert(connection, attempt);
1601        state
1602            .delivery
1603            .readiness_observed
1604            .insert((connection, generation));
1605        Ok(Some(assignment))
1606    }
1607
1608    /// The control adapter calls this only for the active target while holding
1609    /// its module gate, after the delivery frame's writer flush succeeds.
1610    pub(crate) fn delivery_written(
1611        &self,
1612        connection: ConnectionId,
1613        generation: u64,
1614        attempt: u64,
1615        written_at: tokio::time::Instant,
1616    ) -> Result<()> {
1617        self.record_delivery_written(connection, generation, attempt, written_at)?;
1618        Ok(())
1619    }
1620
1621    fn record_delivery_written(
1622        &self,
1623        connection: ConnectionId,
1624        generation: u64,
1625        attempt: u64,
1626        written_at: tokio::time::Instant,
1627    ) -> Result<bool> {
1628        let mut state = self.lock()?;
1629        let bound = state
1630            .delivery
1631            .attempts
1632            .get_mut(&connection)
1633            .filter(|bound| bound.generation == generation && bound.id == attempt)
1634            .ok_or_else(|| {
1635                GateError::new(
1636                    "delivery_superseded",
1637                    "writer receipt no longer names the current delivery attempt",
1638                )
1639            })?;
1640        if bound
1641            .write_deadline
1642            .is_some_and(|deadline| written_at >= deadline)
1643            || bound
1644                .deadline
1645                .is_some_and(|deadline| written_at >= deadline)
1646        {
1647            return Err(GateError::new(
1648                "delivery_expired",
1649                "configuration delivery timed out",
1650            ));
1651        }
1652        let mut changed = !bound.delivered;
1653        bound.delivered = true;
1654        if !bound.transition.requires_spawn() && bound.deadline.is_none() {
1655            bound.deadline = Some(written_at + CONFIG_LIVE_ACK_TIMEOUT);
1656            changed = true;
1657        }
1658        Ok(changed)
1659    }
1660
1661    pub(crate) fn module_applied(
1662        &self,
1663        connection: ConnectionId,
1664        module: &str,
1665        request: ConfigAppliedRequest,
1666    ) -> Result<AppliedDisposition> {
1667        self.module_outcome(connection, module, request, false)
1668    }
1669
1670    fn module_outcome(
1671        &self,
1672        connection: ConnectionId,
1673        module: &str,
1674        request: ConfigAppliedRequest,
1675        timed_out: bool,
1676    ) -> Result<AppliedDisposition> {
1677        let mut state = self.lock()?;
1678        if !state
1679            .declarations
1680            .get(&connection)
1681            .is_some_and(|(id, _)| id == module)
1682        {
1683            return Err(GateError::new(
1684                "declaration_order",
1685                "config.declare must precede get or applied on this connection",
1686            ));
1687        }
1688        if request.project_id.is_some() {
1689            return Err(GateError::new(
1690                "config_gated",
1691                "project-tuple delivery is not supported yet",
1692            ));
1693        }
1694        if state.active_declarations.get(module) != Some(&connection) {
1695            return Err(GateError::new(
1696                "not_delivery_target",
1697                "connection is not the active delivery target",
1698            ));
1699        }
1700        state.store.check()?;
1701        let Some(bound) = state
1702            .delivery
1703            .attempts
1704            .get(&connection)
1705            .cloned()
1706            .filter(|bound| {
1707                bound.module == module
1708                    && bound.generation == request.generation
1709                    && bound.id == request.attempt
1710            })
1711        else {
1712            return Ok(AppliedDisposition::Ignored);
1713        };
1714        if !bound.delivered && !timed_out {
1715            return Ok(AppliedDisposition::Ignored);
1716        }
1717        let tuple = Tuple {
1718            module: module.into(),
1719            project: None,
1720        };
1721        let versions = state
1722            .store
1723            .body()?
1724            .versions
1725            .iter()
1726            .find(|(key, _)| key == &tuple)
1727            .map(|(_, versions)| versions.clone())
1728            .unwrap_or_default();
1729        let ack = request.result.is_ack()
1730            && !bound
1731                .deadline
1732                .is_some_and(|deadline| tokio::time::Instant::now() >= deadline);
1733        if bound.declaration_fallback {
1734            let declaration = &state.declarations[&connection].1;
1735            if versions.active != Some(bound.generation)
1736                || Self::declaration_pending(&state, module, declaration).is_none()
1737            {
1738                return Ok(AppliedDisposition::Ignored);
1739            }
1740            state.delivery.attempts.remove(&connection);
1741            if ack {
1742                state
1743                    .delivery
1744                    .fallback_applied
1745                    .insert(connection, bound.generation);
1746                super::mark::acknowledged(self, &state, bound.spawn.as_ref(), bound.generation);
1747                return Ok(AppliedDisposition::CatchupComplete);
1748            }
1749            return Ok(AppliedDisposition::Ignored);
1750        }
1751        if bound.catchup {
1752            // A later approval waiting for a new daemon cannot replace the
1753            // active configuration this child is catching up to now.
1754            let pending_transition = versions
1755                .pending
1756                .map(|generation| {
1757                    let entry = state
1758                        .store
1759                        .body()?
1760                        .generations
1761                        .get(&generation)
1762                        .ok_or_else(|| {
1763                            GateError::new("config_gated", "pending generation is absent")
1764                        })?;
1765                    Transition::for_module(&entry.generation.changeset, module)
1766                })
1767                .transpose()?;
1768            let pending_is_deliverable =
1769                versions
1770                    .pending
1771                    .zip(pending_transition)
1772                    .is_some_and(|(generation, transition)| {
1773                        state
1774                            .delivery
1775                            .boundary_open(connection, generation, transition)
1776                    });
1777            if pending_is_deliverable || versions.active != Some(bound.generation) {
1778                return Ok(AppliedDisposition::Ignored);
1779            }
1780            state.delivery.attempts.remove(&connection);
1781            if bound.mark_only {
1782                // Asked only for the mark: a refusal or timeout leaves the
1783                // spawn unmarked and starts no recovery.
1784                return Ok(if ack {
1785                    super::mark::acknowledged(self, &state, bound.spawn.as_ref(), bound.generation);
1786                    AppliedDisposition::CatchupComplete
1787                } else {
1788                    super::mark::acknowledgement_refused(self, &state, bound.spawn.as_ref());
1789                    AppliedDisposition::Ignored
1790                });
1791            }
1792            if ack {
1793                super::mark::acknowledged(self, &state, bound.spawn.as_ref(), bound.generation);
1794            } else {
1795                super::mark::delivery_failed(self, bound.spawn.as_ref());
1796                state.delivery.recoveries.push((
1797                    connection,
1798                    module.into(),
1799                    AppliedDisposition::CatchupFailed {
1800                        active: bound.generation,
1801                    },
1802                ));
1803            }
1804            return Ok(if ack {
1805                AppliedDisposition::CatchupComplete
1806            } else {
1807                AppliedDisposition::CatchupFailed {
1808                    active: bound.generation,
1809                }
1810            });
1811        }
1812        if versions.pending != Some(bound.generation) {
1813            return Ok(AppliedDisposition::Ignored);
1814        }
1815        if ack
1816            && (!bound.ready
1817                || (bound.transition == Transition::DaemonRestart
1818                    && bound.generation > state.delivery.initial_generation))
1819        {
1820            if let Some(bound) = state.delivery.attempts.get_mut(&connection) {
1821                bound.acknowledged = true;
1822            }
1823            return Ok(AppliedDisposition::WaitingForReadiness);
1824        }
1825        if !ack {
1826            state.restore_route_policy(module, bound.generation);
1827        }
1828        let result = state.store.record_delivery(&tuple, bound.generation, ack);
1829        if result.is_ok() && ack {
1830            state.commit_route_policy(module, bound.generation);
1831        }
1832        // A pending-anchor NACK has already restored memory. Discard its attempt
1833        // even though the durable failure must wait for the anchor retry.
1834        if result.is_ok() || !ack {
1835            state.delivery.attempts.remove(&connection);
1836        }
1837        if !ack {
1838            let keep_running =
1839                versions.active.is_none() && state.delivery.stamp_running.contains(&connection);
1840            state.delivery.recoveries.push((
1841                connection,
1842                module.into(),
1843                AppliedDisposition::Failed {
1844                    generation: bound.generation,
1845                    restore: versions.active,
1846                    keep_running,
1847                },
1848            ));
1849        }
1850        if ack && result.is_ok() {
1851            super::mark::acknowledged(self, &state, bound.spawn.as_ref(), bound.generation);
1852        } else if !ack {
1853            super::mark::delivery_failed(self, bound.spawn.as_ref());
1854        }
1855        result?;
1856        Ok(if ack {
1857            AppliedDisposition::Active
1858        } else {
1859            AppliedDisposition::Failed {
1860                generation: bound.generation,
1861                restore: versions.active,
1862                keep_running: versions.active.is_none()
1863                    && state.delivery.stamp_running.contains(&connection),
1864            }
1865        })
1866    }
1867}