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