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