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