Skip to main content

subc_daemon/config_gate/
runtime.rs

1//! Serialized production owner for the approval engine and durable authority.
2
3use std::{
4    collections::{BTreeMap, BTreeSet, HashMap, VecDeque},
5    sync::Mutex,
6    time::{Duration, Instant},
7};
8
9use subc_config::{Changeset, Digest};
10use subc_control::config::ConfigPlanView;
11use subc_protocol::config::{
12    ConfigDeclareRequest, ConfigLayer, ConfigLayerSnapshot, ConfigStatus, ConfigView,
13};
14
15use super::{
16    capture::{CapturedConfiguration, ConfigCapturer},
17    ApprovalChallenge, ApprovalFacts, ApprovalReply, ConfigGate, GateError, PlanKind, Result,
18};
19use crate::{
20    config_store::{ConfigStore, DeliverySnapshot, StoreActivity, StoreState},
21    ConnectionId,
22};
23
24#[path = "edits.rs"]
25pub(super) mod edits;
26
27#[cfg(test)]
28type UserFileTestIdle =
29    tokio::sync::mpsc::UnboundedSender<(ConnectionId, tokio::sync::oneshot::Sender<()>)>;
30
31#[cfg(test)]
32pub(crate) type SettingsProjectionHook = Box<dyn FnMut() -> Result<()> + Send>;
33
34pub struct RuntimeOwner {
35    #[cfg(test)]
36    pub(crate) user_file_test_idle: Mutex<Option<UserFileTestIdle>>,
37    #[cfg(test)]
38    config_park_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
39    #[cfg(test)]
40    pub(crate) content_kill_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
41    #[cfg(test)]
42    polled_capture_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
43    #[cfg(test)]
44    pub(crate) settings_projection_hook: Mutex<Option<SettingsProjectionHook>>,
45    #[cfg(test)]
46    pub(crate) settings_observation_hook: Mutex<Option<Box<dyn FnMut() + Send>>>,
47    #[cfg(test)]
48    polled_capture_count: std::sync::atomic::AtomicUsize,
49    #[cfg(test)]
50    census_probe: Mutex<Option<std::sync::Arc<dyn Fn() + Send + Sync>>>,
51    #[cfg(test)]
52    agent_validation_window: Mutex<Option<Duration>>,
53    #[cfg(test)]
54    pub(crate) warm_restart_pause: Mutex<Option<WarmRestartPause>>,
55    #[cfg(test)]
56    pub(crate) warm_restart_busy: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
57    #[cfg(test)]
58    pub(crate) swap_preflight_attempts: std::sync::atomic::AtomicUsize,
59    #[cfg(feature = "test-support")]
60    test_hooks: Option<crate::config_store::testing::TestSupport>,
61    #[cfg(test)]
62    spawn_exec_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
63    published: std::sync::RwLock<std::sync::Arc<Published>>,
64    /// Set after state that `published` derives from changed without an
65    /// `OwnerGuard` (a disconnect or cancellation taken with `try_lock`, or a
66    /// phone withdrawal ending). The next guard release republishes.
67    projection_stale: std::sync::atomic::AtomicBool,
68    #[cfg(test)]
69    projection_builds: std::sync::atomic::AtomicUsize,
70    #[cfg(test)]
71    owner_guards: std::sync::atomic::AtomicUsize,
72    /// Connections with a running `config.review` delivery worker. Closing
73    /// one must wake the delivery coordinator so it retires that worker.
74    config_workers: Mutex<std::collections::HashSet<ConnectionId>>,
75    configured_modules: std::sync::RwLock<Option<admission::ConfiguredModuleSnapshot>>,
76    inner: Mutex<OwnerState>,
77    capturer: ConfigCapturer,
78    startup_overrides: Vec<String>,
79    module_gates: Mutex<HashMap<String, std::sync::Arc<tokio::sync::Mutex<()>>>>,
80    delivery_changed: std::sync::Arc<tokio::sync::Notify>,
81    settings_changed: tokio::sync::watch::Sender<u64>,
82    route_policy_authority: std::sync::OnceLock<std::sync::Arc<dyn RoutePolicyAuthority>>,
83    mark_publisher: std::sync::OnceLock<std::sync::Arc<dyn mark::MarkPublisher>>,
84    binding_retirements: Mutex<BTreeMap<usize, Box<dyn Fn() + Send + Sync>>>,
85    canceled_approvals: Mutex<Vec<u64>>,
86    // Reader and Drop callbacks must not wait behind a keychain or disk check.
87    // These short queues/indexes never perform store I/O while locked.
88    approval_request_index: Mutex<HashMap<(ConnectionId, u64), std::sync::Arc<ApprovalRequest>>>,
89    disconnected_pending: Mutex<Vec<ConnectionId>>,
90    abandoned_spawns: Mutex<Vec<(DeliverySpawn, bool)>>,
91    phone_withdrawals: Mutex<phone::PhoneWithdrawals>,
92    #[cfg(any(test, feature = "test-support"))]
93    os_prompt_policy: std::sync::atomic::AtomicBool,
94    #[cfg(test)]
95    spawn_preflight_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
96    #[cfg(test)]
97    exit_record_attempts: std::sync::atomic::AtomicUsize,
98    #[cfg(test)]
99    phone_bind_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
100    #[cfg(test)]
101    begin_approval_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
102    #[cfg(test)]
103    begin_approval_completions: std::sync::atomic::AtomicUsize,
104    #[cfg(test)]
105    desktop_receipt_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
106    #[cfg(test)]
107    prepare_capture_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
108    #[cfg(all(test, unix))]
109    approval_claim_pause: Mutex<Option<ApprovalClaimPause>>,
110}
111
112/// An in-memory cutover transaction. It is borrowed only for synchronous
113/// forwarding, registry and delivery-target publication under one module gate.
114pub(crate) struct SwapConfiguration<'a> {
115    owner: &'a RuntimeOwner,
116    state: OwnerGuard<'a>,
117}
118
119#[cfg(test)]
120pub(crate) struct WarmRestartPause {
121    pub(crate) reached: tokio::sync::oneshot::Sender<()>,
122    pub(crate) resume: tokio::sync::oneshot::Receiver<()>,
123}
124
125impl SwapConfiguration<'_> {
126    pub(crate) fn before_cutover(
127        &mut self,
128        module: &str,
129        connection: ConnectionId,
130        spawn: Option<&DeliverySpawn>,
131    ) -> Result<Option<u64>> {
132        match self.state.store.loaded_admission_state().0 {
133            StoreState::Unstamped => return Ok(None),
134            StoreState::Stamped => {}
135            _ => {
136                return Err(GateError::new(
137                    "config_gated",
138                    "configuration store is in recovery",
139                ))
140            }
141        }
142        let newer = RuntimeOwner::requires_fresher_spawn_loaded(&self.state, module, spawn)?;
143        if newer.is_none() {
144            self.owner.module_get_locked(
145                &mut self.state,
146                connection,
147                module,
148                subc_protocol::config::ConfigGetRequest::new(),
149                false,
150            )?;
151        }
152        Ok(newer)
153    }
154    pub(crate) fn promoted(
155        &mut self,
156        module: &str,
157        connection: ConnectionId,
158        at: tokio::time::Instant,
159    ) -> Result<()> {
160        RuntimeOwner::promote_loaded(&mut self.state, connection, module, at).map(|_| ())
161    }
162}
163
164#[cfg(all(test, unix))]
165struct ApprovalClaimPause {
166    reached: tokio::sync::oneshot::Sender<()>,
167    release: tokio::sync::oneshot::Receiver<()>,
168}
169
170/// The post-answer deadline can withdraw queued work, but never a publication
171/// that has crossed the final commit point while holding its owned gates.
172pub(crate) struct ApprovalCommitWindow {
173    pub deadline: tokio::time::Instant,
174    phase: std::sync::atomic::AtomicU8,
175}
176
177impl ApprovalCommitWindow {
178    pub(crate) fn new(deadline: tokio::time::Instant) -> Self {
179        Self {
180            deadline,
181            phase: std::sync::atomic::AtomicU8::new(0),
182        }
183    }
184
185    pub(crate) fn expire(&self) -> bool {
186        self.phase
187            .compare_exchange(
188                0,
189                2,
190                std::sync::atomic::Ordering::AcqRel,
191                std::sync::atomic::Ordering::Acquire,
192            )
193            .is_ok()
194    }
195
196    fn begin_publication(&self) -> Result<()> {
197        if tokio::time::Instant::now() >= self.deadline {
198            self.expire();
199            return Err(GateError::commit_timeout());
200        }
201        self.phase
202            .compare_exchange(
203                0,
204                1,
205                std::sync::atomic::Ordering::AcqRel,
206                std::sync::atomic::Ordering::Acquire,
207            )
208            .map(|_| ())
209            .map_err(|_| GateError::commit_timeout())
210    }
211}
212
213pub use route_policy::{
214    ApprovedRoutePolicy, RoutePolicyAuthority, RoutePolicyInstall, RoutePolicyInstallation,
215    RoutePolicyReceipt,
216};
217
218pub use delivery::{AppliedDisposition, DeliveryProbe, DeliverySpawn};
219
220/// Supervisor callbacks for the configuration delivery lifecycle. The caller
221/// supplies observed process events, never a module's claimed readiness.
222/// Target checks and promotion callbacks run under [`RuntimeOwner::module_gate`]
223/// across forwarding and registry changes. The spawn token binds a later
224/// registration to the approved generation and its original warm-up deadline.
225pub trait DeliveryObserver: Send + Sync {
226    fn spawned(
227        &self,
228        module: &str,
229        spawned_at: tokio::time::Instant,
230        register_timeout: std::time::Duration,
231        first_health_budget: std::time::Duration,
232    ) -> Result<Option<DeliverySpawn>>;
233    fn registered(&self, connection: ConnectionId, spawn: &DeliverySpawn) -> Result<()>;
234    fn health_probe(&self, connection: ConnectionId, module: &str)
235        -> Result<Option<DeliveryProbe>>;
236    fn health_result(
237        &self,
238        probe: DeliveryProbe,
239        healthy: bool,
240    ) -> Result<Option<AppliedDisposition>>;
241    fn promoted(
242        &self,
243        connection: ConnectionId,
244        module: &str,
245        cutover_at: tokio::time::Instant,
246    ) -> Result<Option<(u64, u64)>>;
247    /// Retry only the retained, non-interactive backend when its backoff is due.
248    /// `None` means there is no pending anchor and no timer should be armed.
249    fn retry_anchor(&self) -> Result<Option<tokio::time::Instant>>;
250}
251
252impl DeliveryObserver for RuntimeOwner {
253    fn spawned(
254        &self,
255        module: &str,
256        spawned_at: tokio::time::Instant,
257        register_timeout: std::time::Duration,
258        first_health_budget: std::time::Duration,
259    ) -> Result<Option<DeliverySpawn>> {
260        self.delivery_spawned(module, spawned_at, register_timeout, first_health_budget)
261    }
262
263    fn registered(&self, connection: ConnectionId, spawn: &DeliverySpawn) -> Result<()> {
264        self.delivery_child_registered(connection, spawn)
265    }
266
267    /// Capture before dispatching the ordinary health RPC. A later result must
268    /// use this witness, not look up whichever target is current on completion.
269    fn health_probe(
270        &self,
271        connection: ConnectionId,
272        module: &str,
273    ) -> Result<Option<DeliveryProbe>> {
274        self.delivery_health_probe(connection, module)
275    }
276
277    /// Complete under the module gate. A new target, attempt or policy install
278    /// invalidates an older witness rather than lending its health to new bytes.
279    fn health_result(
280        &self,
281        probe: DeliveryProbe,
282        healthy: bool,
283    ) -> Result<Option<AppliedDisposition>> {
284        self.delivery_health_result(probe, healthy)
285    }
286
287    fn promoted(
288        &self,
289        connection: ConnectionId,
290        module: &str,
291        cutover_at: tokio::time::Instant,
292    ) -> Result<Option<(u64, u64)>> {
293        self.delivery_promoted(connection, module, cutover_at)
294    }
295
296    fn retry_anchor(&self) -> Result<Option<tokio::time::Instant>> {
297        self.poll_anchor_retry()
298    }
299}
300
301/// Keep a reviewed plan for one idle hour so the operator can read the full diff.
302const PLAN_IDLE_TIMEOUT: Duration = Duration::from_secs(60 * 60);
303/// One shared sweep reclaims idle plans without allocating a timer per plan.
304pub(crate) const PLAN_SWEEP_INTERVAL: Duration = Duration::from_secs(60);
305/// Remember recent expirations by digest without retaining unbounded plan bodies.
306const EXPIRED_PLAN_IDS: usize = 64;
307
308fn layer_file_rows(
309    changeset: &mut Changeset,
310    old: &super::GateSnapshot,
311    new: &super::GateSnapshot,
312    previous: Option<&DeliverySnapshot>,
313    candidate: &DeliverySnapshot,
314) -> Result<()> {
315    for key in old.changed_keys(new) {
316        let super::InputKey::Layer { module, path } = key else {
317            continue;
318        };
319        // A value or source row already explains the changed layer. Otherwise
320        // expose the exact raw input without disclosing its contents.
321        if changeset.fields.iter().any(|field| {
322            field.module_id == *module
323                && (field.old_source == subc_config::Layer::User
324                    || field.new_source == subc_config::Layer::User)
325        }) {
326            continue;
327        }
328        let describe = |snapshot: Option<&DeliverySnapshot>,
329                        input: Option<&super::CapturedInput>|
330         -> Result<serde_json::Value> {
331            if input.is_none()
332                || input.is_some_and(|input| input.state == subc_config::InputState::Absent)
333            {
334                return Ok(serde_json::json!({"absent":true}));
335            }
336            let bytes = snapshot
337                .and_then(|snapshot| snapshot.modules.get(module))
338                .and_then(|view| {
339                    view.layers
340                        .iter()
341                        .find(|layer| layer.path.as_deref() == Some(path.as_str()))
342                })
343                .and_then(|layer| layer.bytes.as_deref())
344                .ok_or_else(|| GateError::new("config_gated", "retained layer bytes are absent"))?;
345            Ok(
346                serde_json::json!({"sha256":subc_config::raw_digest(bytes).as_str().trim_start_matches("sha256:"), "bytes":bytes.len()}),
347            )
348        };
349        changeset.policy_changes.push(serde_json::json!({
350            "kind":"layer_file", "module_id":module, "layer":"user",
351            "old":describe(previous, old.inputs.get(key))?,
352            "new":describe(Some(candidate), new.inputs.get(key))?,
353        }));
354    }
355    Ok(())
356}
357
358pub(crate) fn daemon_review(
359    old: &super::GateSnapshot,
360    new: &super::GateSnapshot,
361) -> Result<Changeset> {
362    let mut changeset = Changeset::new();
363    for key in old.changed_keys(new) {
364        match key {
365            super::InputKey::Entry(module) | super::InputKey::Program { module, .. } => {
366                let field = match key {
367                    super::InputKey::Entry(_) => "entry".into(),
368                    super::InputKey::Program { path, .. } => format!("program:{path}"),
369                    _ => unreachable!(),
370                };
371                let manifest = changeset
372                    .launch_manifests
373                    .entry(module.clone())
374                    .or_insert_with(|| serde_json::json!({"origin": "other"}));
375                manifest.as_object_mut().expect("launch manifest is an object").insert(field,serde_json::json!({"old":old.inputs.get(key).map(|v| &v.value),"new":new.inputs.get(key).map(|v| &v.value)}));
376            }
377            super::InputKey::Declaration(module) => {
378                changeset.policy_changes.push(serde_json::json!({"module_id":module,"path":"declaration","old":old.inputs.get(key).map(|v| &v.value),"new":new.inputs.get(key).map(|v| &v.value)}));
379            }
380            super::InputKey::Daemon => {
381                changeset.policy_changes.push(serde_json::json!({
382                    "path":"subc.jsonc",
383                    "old":old.inputs.get(key).map(|v| &v.value),
384                    "new":new.inputs.get(key).map(|v| &v.value),
385                }));
386                changeset.apply_plan = serde_json::json!({"supervisor_reconcile":true});
387            }
388            _ => {}
389        }
390    }
391    Ok(changeset)
392}
393
394struct OwnerState {
395    authority_incarnation: std::sync::Arc<()>,
396    observed_snapshot: Option<super::GateSnapshot>,
397    stamp_channel_cutover: bool,
398    gate: ConfigGate,
399    store: ConfigStore,
400    _writer_lock: Option<crate::config_store::StoreWriterLock>,
401    plan_deadlines: BTreeMap<Digest, Instant>,
402    // Only a successfully flushed complete plan on this connection can bind
403    // its desktop approval. A later view replaces the connection's old view.
404    desktop_views: BTreeMap<u64, (Digest, u64)>,
405    phone_waiters: BTreeMap<u64, tokio::sync::oneshot::Sender<()>>,
406    approval_requests: HashMap<(ConnectionId, u64), u64>,
407    delivery: delivery::DeliveryState,
408    anchor_retry: super::anchor_retry::AnchorRetry,
409    // Keep the original objects alive through approval so an unlinked file's
410    // inode/file id cannot be recycled to impersonate the reviewed input.
411    retained_plan_files: BTreeMap<Digest, Vec<std::fs::File>>,
412    expired_plans: VecDeque<Digest>,
413    declarations: HashMap<ConnectionId, (String, ConfigDeclareRequest)>,
414    active_declarations: BTreeMap<String, ConnectionId>,
415    activity: Option<crate::activity::ActivityLedger>,
416    refused_generations: BTreeMap<String, Digest>,
417    admission_holds: Vec<String>,
418    admission_releases: Vec<String>,
419    authority_exit: Option<u64>,
420    // Last reconciled daemon entries, independent of module-layer activation.
421    reconciled_entries: BTreeMap<String, crate::daemon_config::ConfiguredModule>,
422    recovery_exit_hold: bool,
423    unstamp_hints: std::collections::HashSet<ConnectionId>,
424    anchor_waiters: std::collections::HashSet<ConnectionId>,
425    anchor_hints: std::collections::HashSet<ConnectionId>,
426    anchor_notify: std::sync::Arc<tokio::sync::Notify>,
427    installed_route_policies: BTreeMap<String, u64>,
428    route_policy_receipts: BTreeMap<(String, u64), route_policy::PendingRoutePolicy>,
429    #[cfg(test)]
430    publication_hook: Option<Box<dyn FnOnce() + Send>>,
431    #[cfg(test)]
432    prepublication_hook: Option<Box<dyn FnOnce() + Send>>,
433    #[cfg(test)]
434    after_approval_drain_hook: Option<Box<dyn FnOnce() + Send>>,
435}
436
437impl OwnerState {
438    fn retry_anchor(&mut self, operator_command: bool) -> Option<tokio::time::Instant> {
439        let pending = self.store.status().anchor_pending;
440        let events = self.anchor_retry.poll(
441            pending,
442            tokio::time::Instant::now(),
443            operator_command,
444            || {
445                let error = self
446                    .store
447                    .retry_anchor()
448                    .err()
449                    .map(|error| error.to_string());
450                (self.store.status().anchor_pending, error)
451            },
452        );
453        for event in events {
454            match event {
455                super::anchor_retry::Event::Pending => {
456                    tracing::info!("configuration anchor became pending")
457                }
458                super::anchor_retry::Event::Failed(reason) => {
459                    tracing::warn!(%reason, "configuration anchor retry failed")
460                }
461                super::anchor_retry::Event::Recovered => {
462                    tracing::info!("configuration anchor recovered");
463                    self.queue_anchor_hints();
464                }
465            }
466        }
467        self.commit_anchored_route_policies();
468        self.anchor_retry.next()
469    }
470    fn with_desktop_view(&self, digest: &Digest, facts: &ApprovalFacts) -> ApprovalFacts {
471        let mut checked = facts.clone();
472        let bound = self
473            .desktop_views
474            .get(&facts.connection)
475            .is_some_and(|(shown, revision)| {
476                shown == digest
477                    && self
478                        .gate
479                        .plans
480                        .get(digest)
481                        .is_some_and(|plan| plan.view.base_revision == *revision)
482            });
483        if !bound {
484            checked.desktop_app = false;
485            checked.attested_operator_app = false;
486        }
487        checked
488    }
489    /// Reclaim idle plans. Returns whether any plan expired.
490    fn expire_idle(&mut self, now: Instant) -> bool {
491        let expired: Vec<_> = self
492            .plan_deadlines
493            .iter()
494            .filter(|(digest, deadline)| **deadline <= now && !self.gate.has_open_approval(digest))
495            .map(|(digest, _)| digest.clone())
496            .collect();
497        let any = !expired.is_empty();
498        for digest in expired {
499            self.plan_deadlines.remove(&digest);
500            self.retained_plan_files.remove(&digest);
501            self.desktop_views.retain(|_, (shown, _)| shown != &digest);
502            if self.gate.expire_plan(&digest) {
503                self.expired_plans.push_back(digest);
504                if self.expired_plans.len() > EXPIRED_PLAN_IDS {
505                    self.expired_plans.pop_front();
506                }
507            }
508        }
509        any
510    }
511    fn reviewed(&mut self, digest: &Digest, now: Instant) {
512        self.plan_deadlines
513            .insert(digest.clone(), now + PLAN_IDLE_TIMEOUT);
514        self.expired_plans.retain(|expired| expired != digest);
515    }
516}
517
518/// The owner's state, held exclusively. Releasing it republishes the polled
519/// projection, admission and approved-daemon views when anything they derive
520/// from could have changed: any mutable access through this guard, a store
521/// check that moved the store, or a change made outside a guard that set
522/// `RuntimeOwner::projection_stale`. A guard used only to read publishes
523/// nothing, so read-like authority checks do not rebuild the projection.
524struct OwnerGuard<'a> {
525    state: std::sync::MutexGuard<'a, OwnerState>,
526    owner: &'a RuntimeOwner,
527    changed: bool,
528}
529impl std::ops::Deref for OwnerGuard<'_> {
530    type Target = OwnerState;
531    fn deref(&self) -> &Self::Target {
532        &self.state
533    }
534}
535impl std::ops::DerefMut for OwnerGuard<'_> {
536    fn deref_mut(&mut self) -> &mut Self::Target {
537        // Any mutable access may change a published input. Read-only store
538        // checks use `OwnerGuard::store_read` so they republish only when the
539        // check itself changed the store.
540        self.changed = true;
541        &mut self.state
542    }
543}
544
545/// The parts of a store that a read-only integrity check can change and that
546/// feed the published views: its state (a failed check moves it into
547/// recovery), its atomic publications, its pending anchor and its key status.
548fn store_witness(store: &ConfigStore) -> (StoreState, u64, bool, u64) {
549    (
550        store.loaded_admission_state().0,
551        store.publication_sequence(),
552        store.loaded_anchor_pending(),
553        store.key_status_revision(),
554    )
555}
556
557impl<'a> OwnerGuard<'a> {
558    fn new(state: std::sync::MutexGuard<'a, OwnerState>, owner: &'a RuntimeOwner) -> Self {
559        #[cfg(test)]
560        owner
561            .owner_guards
562            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
563        Self {
564            state,
565            owner,
566            changed: false,
567        }
568    }
569
570    /// Run a store integrity read (`check`, `status`, `delivery_ready`) and
571    /// mark the guard changed only if the read changed what the store
572    /// publishes. Every caller still checks authority on every call.
573    fn store_read<T>(&mut self, read: impl FnOnce(&mut ConfigStore) -> T) -> T {
574        let before = store_witness(&self.state.store);
575        let result = read(&mut self.state.store);
576        if store_witness(&self.state.store) != before {
577            self.changed = true;
578        }
579        result
580    }
581
582    /// `ConfigStore::body` without marking the guard changed when the check
583    /// it performs leaves the store as it was.
584    fn checked_body(
585        &mut self,
586    ) -> std::result::Result<&crate::config_store::StoreBody, crate::config_store::StoreError> {
587        self.store_read(ConfigStore::check)?;
588        Ok(self.state.store.loaded_admission_state().1)
589    }
590
591    fn publish(&mut self) {
592        #[cfg(test)]
593        self.owner
594            .projection_builds
595            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
596        // Project committed or invalidated authority before releasing its owner.
597        // Parse changed generations outside the cheap reader lock, then publish
598        // only the Arc; list polling never waits for store or keychain work.
599        let previous = self
600            .owner
601            .published
602            .read()
603            .map(|view| view.approved_daemon.clone())
604            .unwrap_or(ApprovedDaemonView::Unavailable);
605        let approved_daemon = ApprovedDaemonView::from_store(
606            &self.state.store,
607            self.state.recovery_exit_hold,
608            &previous,
609        );
610        // Volatile holds follow the same lifetime as their durable records.
611        // Approving another program identity retires the previous identity's
612        // volatile hold, even if that previous identity is later approved again.
613        let (_, body) = self.state.store.loaded_admission_state();
614        let valid: std::collections::BTreeSet<_> = body
615            .program_refusals
616            .iter()
617            .map(|refusal| (refusal.module.clone(), refusal.approved_base.clone()))
618            .collect();
619        self.state
620            .refused_generations
621            .retain(|module, base| valid.contains(&(module.clone(), base.clone())));
622        let next = admission::AdmissionCache::from_state(&self.state);
623        // Lower the marks this state rules out (an unstamp, an ungated
624        // module, an active generation the spawn never acknowledged) before
625        // the owner is released: delivery, then record, then forwarding.
626        mark::sweep(self.owner, &mut self.state, &next);
627        let observed = self.state.observed_snapshot.clone();
628        let projection = self
629            .owner
630            .status_projection(&mut self.state, observed, &next);
631        if let Ok(mut cache) = self.owner.published.write() {
632            let (holds, releases) = next.transitions_from(&cache);
633            let changed = next.is_recovering() != cache.is_recovering()
634                || !holds.is_empty()
635                || !releases.is_empty();
636            self.state.admission_holds.extend(holds);
637            self.state.admission_releases.extend(releases);
638            *cache = std::sync::Arc::new(Published {
639                admission: next,
640                approved_daemon,
641                projection,
642            });
643            self.owner
644                .settings_changed
645                .send_modify(|revision| *revision = revision.wrapping_add(1));
646            if changed {
647                self.owner.delivery_changed.notify_one();
648            }
649        }
650    }
651}
652impl Drop for OwnerGuard<'_> {
653    fn drop(&mut self) {
654        // Clear the outside-change flag even when this guard publishes anyway.
655        let stale = self
656            .owner
657            .projection_stale
658            .swap(false, std::sync::atomic::Ordering::AcqRel);
659        let published = (!(self.changed || stale))
660            .then(|| {
661                self.owner
662                    .published
663                    .read()
664                    .ok()
665                    .map(|view| std::sync::Arc::clone(&view))
666            })
667            .flatten();
668        match published {
669            // Nothing published here changed, so the published admission is
670            // what a rebuild would produce. Spawn records still carry their
671            // own mark facts, so sweep them against it on every release.
672            Some(published) => mark::sweep(self.owner, &mut self.state, &published.admission),
673            None => self.publish(),
674        }
675        let Some(ledger) = self.state.activity.clone() else {
676            return;
677        };
678        let Ok(gates) = self.owner.module_gates.try_lock() else {
679            return;
680        };
681        let held: Vec<_> = gates
682            .values()
683            .filter(|gate| gate.try_lock().is_err())
684            .cloned()
685            .collect();
686        drop(gates);
687        if held.is_empty() {
688            for activity in self.state.store.take_activities() {
689                ledger.config_store_activity(activity);
690            }
691        } else if let Ok(runtime) = tokio::runtime::Handle::try_current() {
692            let activities = self.state.store.take_activities();
693            if !activities.is_empty() {
694                runtime.spawn(async move {
695                    // No store mutex follows the activity into this task. Drop
696                    // each gate before waiting for another, then publish the log.
697                    for gate in held {
698                        drop(gate.lock_owned().await);
699                    }
700                    for activity in activities {
701                        ledger.config_store_activity(activity);
702                    }
703                });
704            }
705        }
706    }
707}
708
709pub struct PreparedPlan {
710    edits: Option<edits::EditPlan>,
711    pub candidate: CapturedConfiguration,
712    pub bases: BTreeMap<String, ConfigView>,
713    pub base_schemas: BTreeMap<String, subc_config::Schema>,
714    pub kind: PlanKind,
715    pub review_modules: std::collections::BTreeSet<String>,
716    /// Modules in `review_modules` only because their newly approved program
717    /// is active and has not yet reviewed their approved layers. A missing
718    /// reviewer drops such a module from this plan instead of failing it.
719    pub rereview_modules: std::collections::BTreeSet<String>,
720    base_revision: u64,
721    active_generations: BTreeMap<crate::config_store::Tuple, Option<u64>>,
722    touched_modules: BTreeSet<String>,
723    read_set: subc_config::InputVector,
724    program_keys: Vec<super::InputKey>,
725    observed_handles: Vec<std::fs::File>,
726}
727
728/// Immutable command inputs for the supervisor's approved rollback admission.
729pub struct ApprovedRollbackCommands {
730    pub generation: u64,
731    pub daemon: ConfigLayerSnapshot,
732    pub programs: BTreeMap<String, ApprovedRollbackProgram>,
733}
734
735/// A supervisor reconciliation witness minted only from a verified committed
736/// generation. Keeping the raw layer prevents a caller from substituting a
737/// freshly parsed live file for the approved command inputs.
738#[derive(Clone, Debug)]
739pub(crate) struct ApprovedDaemonConfiguration {
740    generation: u64,
741    approval_digest: Digest,
742    authority_incarnation: std::sync::Arc<()>,
743    daemon: std::sync::Arc<ConfigLayerSnapshot>,
744    changed_entries: BTreeSet<String>,
745}
746
747#[derive(Clone, Debug)]
748pub(crate) struct ApprovalIdentity {
749    generation: u64,
750    approval_digest: Digest,
751    // Rebuilding rejected store authority from unchanged files can repeat both
752    // generation and digest. Retain this token in ApprovedDaemonConfiguration and
753    // each actor's approved_start_failure so old failures cannot alias new authority.
754    authority_incarnation: std::sync::Arc<()>,
755}
756
757impl PartialEq for ApprovalIdentity {
758    fn eq(&self, other: &Self) -> bool {
759        self.generation == other.generation
760            && self.approval_digest == other.approval_digest
761            && std::sync::Arc::ptr_eq(&self.authority_incarnation, &other.authority_incarnation)
762    }
763}
764
765impl Eq for ApprovalIdentity {}
766
767pub struct ApprovedRollbackProgram {
768    pub path: String,
769    pub identity: super::CapturedInput,
770}
771
772#[cfg(test)]
773#[path = "runtime_tests.rs"]
774mod tests;
775
776#[cfg(test)]
777#[path = "commit_pause.rs"]
778pub(crate) mod commit_pause;
779
780#[path = "delivery.rs"]
781pub(crate) mod delivery;
782
783#[path = "admission.rs"]
784mod admission;
785#[path = "mark.rs"]
786pub(crate) mod mark;
787#[path = "recovery.rs"]
788mod recovery;
789#[path = "route_policy.rs"]
790mod route_policy;
791pub(crate) use admission::SpawnAdmission;
792
793#[path = "approval_request.rs"]
794mod approval_request;
795#[path = "daemon_readers.rs"]
796mod daemon_readers;
797pub(crate) use daemon_readers::ApprovedDaemonView;
798#[path = "phone.rs"]
799mod phone;
800#[path = "placement.rs"]
801mod placement;
802#[path = "polled.rs"]
803mod polled;
804#[path = "published.rs"]
805mod published;
806#[path = "unstamped.rs"]
807pub(crate) mod unstamped;
808#[path = "widening.rs"]
809mod widening;
810pub(crate) use published::Published;
811#[path = "settings.rs"]
812pub(crate) mod settings;
813#[path = "status_inputs.rs"]
814mod status_inputs;
815pub(crate) use approval_request::{ApprovalRequest, ApprovalRequestGuard, CancelApprovalRequest};
816
817impl RuntimeOwner {
818    /// Keep store I/O and waits for its synchronous owner lock off runtime threads.
819    pub(crate) async fn on_blocking<T: Send + 'static>(
820        self: &std::sync::Arc<Self>,
821        work: impl FnOnce(std::sync::Arc<Self>) -> Result<T> + Send + 'static,
822    ) -> Result<T> {
823        let owner = self.clone();
824        tokio::task::spawn_blocking(move || work(owner))
825            .await
826            .map_err(|_| GateError::new("config_unavailable", "configuration worker stopped"))?
827    }
828
829    #[cfg(feature = "test-support")]
830    pub(crate) fn pause_spawn_before_exec(&self) -> Result<()> {
831        if let Some(hooks) = &self.test_hooks {
832            hooks
833                .pause_spawn_before_exec()
834                .map_err(|error| GateError::new("config_test_pause", error.to_string()))?;
835        }
836        Ok(())
837    }
838
839    #[cfg(feature = "test-support")]
840    pub(crate) fn pause_swap_before_promotion(&self) -> Result<()> {
841        if let Some(hooks) = &self.test_hooks {
842            hooks
843                .pause_swap_before_promotion()
844                .map_err(|error| GateError::new("config_test_pause", error.to_string()))?;
845        }
846        Ok(())
847    }
848    /// Record the exact full response only after its writer flush succeeds and
849    /// the adapter revalidates the same live desktop connection.
850    #[cfg(test)]
851    pub(crate) fn desktop_view_delivered(
852        &self,
853        connection: ConnectionId,
854        view: &subc_control::config::ConfigPlanView,
855    ) -> Result<()> {
856        self.desktop_view_delivered_when(connection, view, || true)
857    }
858
859    pub(crate) fn desktop_view_delivered_when(
860        &self,
861        connection: ConnectionId,
862        view: &subc_control::config::ConfigPlanView,
863        is_live: impl FnOnce() -> bool,
864    ) -> Result<()> {
865        #[cfg(test)]
866        if let Some(hook) = self.desktop_receipt_hook.lock().unwrap().take() {
867            hook();
868        }
869        let mut state = self.lock()?;
870        // Check the live peer after acquiring the owner, without retaining the
871        // peer mutex during an owner wait or any configuration/store work.
872        if !is_live() {
873            return Ok(());
874        }
875        let plan = state
876            .gate
877            .plans
878            .get(&view.digest)
879            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or expired"))?;
880        if plan.view != *view {
881            return Err(GateError::new(
882                "plan_stale",
883                "delivered view differs from the immutable plan",
884            ));
885        }
886        state
887            .desktop_views
888            .insert(connection.get(), (view.digest.clone(), view.base_revision));
889        Ok(())
890    }
891    pub fn new(incarnation: String, mut store: ConfigStore, capturer: ConfigCapturer) -> Self {
892        // Daemon-restart generations newer than the booted one stay deferred.
893        let initial_generation = match store.booted_generation() {
894            Some(booted) => booted,
895            None => store.body().map(|body| body.last_generation).unwrap_or(0),
896        };
897        let admission = admission::AdmissionCache::from_store(&store);
898        let approved_daemon =
899            ApprovedDaemonView::from_store(&store, false, &ApprovedDaemonView::Unavailable);
900        let reconciled_entries = match &approved_daemon {
901            ApprovedDaemonView::Approved { config, .. } => config
902                .modules
903                .iter()
904                .map(|module| (module.module_id.clone(), module.clone()))
905                .collect(),
906            _ => BTreeMap::new(),
907        };
908        let published = std::sync::RwLock::new(std::sync::Arc::new(Published {
909            admission,
910            approved_daemon,
911            projection: polled::Projection::default(),
912        }));
913        let delivery_changed = std::sync::Arc::new(tokio::sync::Notify::new());
914        let owner = Self {
915            #[cfg(test)]
916            user_file_test_idle: Mutex::new(None),
917            #[cfg(test)]
918            polled_capture_hook: Mutex::new(None),
919            #[cfg(test)]
920            settings_projection_hook: Mutex::new(None),
921            #[cfg(test)]
922            settings_observation_hook: Mutex::new(None),
923            #[cfg(test)]
924            config_park_hook: Mutex::new(None),
925            #[cfg(test)]
926            content_kill_hook: Mutex::new(None),
927            #[cfg(test)]
928            polled_capture_count: std::sync::atomic::AtomicUsize::new(0),
929            #[cfg(test)]
930            census_probe: Mutex::new(None),
931            #[cfg(test)]
932            agent_validation_window: Mutex::new(None),
933            #[cfg(test)]
934            warm_restart_pause: Mutex::new(None),
935            #[cfg(test)]
936            warm_restart_busy: Mutex::new(None),
937            #[cfg(test)]
938            swap_preflight_attempts: std::sync::atomic::AtomicUsize::new(0),
939            #[cfg(feature = "test-support")]
940            test_hooks: store.test_support().cloned(),
941            #[cfg(test)]
942            spawn_exec_hook: Mutex::new(None),
943            published,
944            // The first guard release below builds the initial projection.
945            projection_stale: std::sync::atomic::AtomicBool::new(true),
946            #[cfg(test)]
947            projection_builds: std::sync::atomic::AtomicUsize::new(0),
948            #[cfg(test)]
949            owner_guards: std::sync::atomic::AtomicUsize::new(0),
950            config_workers: Mutex::new(std::collections::HashSet::new()),
951            configured_modules: std::sync::RwLock::new(None),
952            inner: Mutex::new(OwnerState {
953                authority_incarnation: std::sync::Arc::new(()),
954                observed_snapshot: None,
955                stamp_channel_cutover: false,
956                gate: ConfigGate::new(incarnation),
957                store,
958                _writer_lock: None,
959                plan_deadlines: BTreeMap::new(),
960                desktop_views: BTreeMap::new(),
961                phone_waiters: BTreeMap::new(),
962                approval_requests: HashMap::new(),
963                delivery: delivery::DeliveryState::new(initial_generation),
964                anchor_retry: super::anchor_retry::AnchorRetry::default(),
965                retained_plan_files: BTreeMap::new(),
966                expired_plans: VecDeque::new(),
967                declarations: HashMap::new(),
968                active_declarations: BTreeMap::new(),
969                activity: None,
970                refused_generations: BTreeMap::new(),
971                admission_holds: Vec::new(),
972                admission_releases: Vec::new(),
973                authority_exit: None,
974                reconciled_entries,
975                recovery_exit_hold: false,
976                unstamp_hints: std::collections::HashSet::new(),
977                anchor_waiters: std::collections::HashSet::new(),
978                anchor_hints: std::collections::HashSet::new(),
979                anchor_notify: delivery_changed.clone(),
980                installed_route_policies: BTreeMap::new(),
981                route_policy_receipts: BTreeMap::new(),
982                #[cfg(test)]
983                publication_hook: None,
984                #[cfg(test)]
985                prepublication_hook: None,
986                #[cfg(test)]
987                after_approval_drain_hook: None,
988            }),
989            capturer,
990            startup_overrides: status_inputs::present_overrides(|name| {
991                std::env::var_os(name).is_some()
992            }),
993            module_gates: Mutex::new(HashMap::new()),
994            delivery_changed,
995            settings_changed: tokio::sync::watch::channel(0).0,
996            route_policy_authority: std::sync::OnceLock::new(),
997            mark_publisher: std::sync::OnceLock::new(),
998            binding_retirements: Mutex::new(BTreeMap::new()),
999            canceled_approvals: Mutex::new(Vec::new()),
1000            approval_request_index: Mutex::new(HashMap::new()),
1001            disconnected_pending: Mutex::new(Vec::new()),
1002            abandoned_spawns: Mutex::new(Vec::new()),
1003            phone_withdrawals: Mutex::new(phone::PhoneWithdrawals::default()),
1004            #[cfg(any(test, feature = "test-support"))]
1005            os_prompt_policy: std::sync::atomic::AtomicBool::new(false),
1006            #[cfg(test)]
1007            spawn_preflight_hook: Mutex::new(None),
1008            #[cfg(test)]
1009            exit_record_attempts: std::sync::atomic::AtomicUsize::new(0),
1010            #[cfg(test)]
1011            phone_bind_hook: Mutex::new(None),
1012            #[cfg(test)]
1013            begin_approval_hook: Mutex::new(None),
1014            #[cfg(test)]
1015            begin_approval_completions: std::sync::atomic::AtomicUsize::new(0),
1016            #[cfg(test)]
1017            desktop_receipt_hook: Mutex::new(None),
1018            #[cfg(test)]
1019            prepare_capture_hook: Mutex::new(None),
1020            #[cfg(all(test, unix))]
1021            approval_claim_pause: Mutex::new(None),
1022        };
1023        if let Ok(state) = owner.lock() {
1024            drop(state);
1025        }
1026        owner
1027    }
1028
1029    pub fn module_gate(&self, module: &str) -> Result<std::sync::Arc<tokio::sync::Mutex<()>>> {
1030        let mut gates = self
1031            .module_gates
1032            .lock()
1033            .map_err(|_| GateError::new("config_unavailable", "module gate lock is poisoned"))?;
1034        Ok(gates.entry(module.into()).or_default().clone())
1035    }
1036
1037    #[cfg(all(test, unix))]
1038    pub(crate) fn set_agent_validation_window_for_test(&self, window: Duration) {
1039        *self.agent_validation_window.lock().unwrap() = Some(window);
1040    }
1041
1042    #[cfg(test)]
1043    pub(crate) fn agent_validation_window_for_test(&self) -> Option<Duration> {
1044        *self.agent_validation_window.lock().unwrap()
1045    }
1046
1047    pub(crate) fn install_binding_retirement(
1048        &self,
1049        key: usize,
1050        retire: impl Fn() + Send + Sync + 'static,
1051    ) {
1052        self.binding_retirements
1053            .lock()
1054            .unwrap_or_else(|poisoned| poisoned.into_inner())
1055            .insert(key, Box::new(retire));
1056    }
1057
1058    pub(crate) fn delivery_notifications(&self) -> std::sync::Arc<tokio::sync::Notify> {
1059        self.delivery_changed.clone()
1060    }
1061
1062    pub(crate) fn notify_delivery_changed(&self) {
1063        self.delivery_changed.notify_one();
1064    }
1065
1066    pub(crate) fn retain_writer_lock(
1067        self,
1068        lock: crate::config_store::StoreWriterLock,
1069    ) -> Result<Self> {
1070        self.lock()?._writer_lock = Some(lock);
1071        Ok(self)
1072    }
1073
1074    fn lock(&self) -> Result<OwnerGuard<'_>> {
1075        // The owner's state comes before the forwarding lock: lowering a
1076        // first-party mark takes the forwarding lock under it.
1077        crate::forwarding::assert_forwarding_unlocked("the configuration owner's state");
1078        let mut guard = self
1079            .inner
1080            .lock()
1081            .map(|state| OwnerGuard::new(state, self))
1082            .map_err(|_| {
1083                GateError::new("config_unavailable", "configuration owner lock is poisoned")
1084            })?;
1085        // The test seam only arms a backend failure; nothing published reads it.
1086        #[cfg(feature = "test-support")]
1087        guard.state.store.refresh_test_anchor_failure();
1088        // Deferred cancellations, disconnects and abandoned spawns, and idle
1089        // plan expiry, change the owner only when they had work. Each runs on
1090        // every acquisition, and work done here publishes on release.
1091        let drained = self.drain_canceled_approvals(&mut guard.state)
1092            | self.drain_disconnections(&mut guard.state)
1093            | self.drain_abandoned_spawns(&mut guard.state)
1094            | guard.state.expire_idle(Instant::now());
1095        guard.changed |= drained;
1096        Ok(guard)
1097    }
1098
1099    pub(crate) fn try_swap_configuration(&self) -> Result<SwapConfiguration<'_>> {
1100        let state = self.inner.try_lock().map_err(|_| {
1101            GateError::new(
1102                "config_delivery_deferred",
1103                "configuration publication is busy or unavailable",
1104            )
1105        })?;
1106        Ok(SwapConfiguration {
1107            owner: self,
1108            state: OwnerGuard::new(state, self),
1109        })
1110    }
1111
1112    pub(crate) fn try_requires_fresher_spawn(
1113        &self,
1114        module: &str,
1115        spawn: Option<&DeliverySpawn>,
1116    ) -> Result<Option<u64>> {
1117        let state = self.inner.try_lock().map_err(|_| {
1118            GateError::new(
1119                "config_delivery_deferred",
1120                "configuration publication is busy or unavailable",
1121            )
1122        })?;
1123        Self::requires_fresher_spawn_loaded(&state, module, spawn)
1124    }
1125
1126    pub(crate) fn sweep_expired(&self) -> Result<()> {
1127        drop(self.lock()?);
1128        Ok(())
1129    }
1130
1131    pub(crate) fn poll_anchor_retry(&self) -> Result<Option<tokio::time::Instant>> {
1132        Ok(self.lock()?.retry_anchor(false))
1133    }
1134
1135    pub(crate) fn set_activity(
1136        &self,
1137        ledger: Option<crate::activity::ActivityLedger>,
1138    ) -> Result<()> {
1139        self.lock()?.activity = ledger;
1140        Ok(())
1141    }
1142
1143    pub fn take_activities(&self) -> Vec<StoreActivity> {
1144        self.inner
1145            .lock()
1146            .map(|mut state| state.store.take_activities())
1147            .unwrap_or_default()
1148    }
1149
1150    /// Declaration ownership comes from the registered transport connection.
1151    /// A candidate's proposal is retained without replacing the incumbent's.
1152    pub fn declare(
1153        &self,
1154        connection: ConnectionId,
1155        module: &str,
1156        declaration: ConfigDeclareRequest,
1157        active: bool,
1158    ) -> Result<()> {
1159        subc_config::Schema::new(declaration.schema.clone())
1160            .map_err(|r| GateError::new("schema_invalid", format!("{module}: {}", r.path)))?;
1161        let mut state = self.lock()?;
1162        if state.store.status().state == StoreState::StoreMissing
1163            || state.store.status().state == StoreState::StoreUnverified
1164        {
1165            return Err(GateError::new(
1166                "config_gated",
1167                "configuration store is in recovery",
1168            ));
1169        }
1170        if state.declarations.contains_key(&connection) {
1171            return Err(GateError::new(
1172                "declaration_order",
1173                "configuration is declared once per connection",
1174            ));
1175        }
1176        state
1177            .declarations
1178            .insert(connection, (module.into(), declaration));
1179        state.delivery.declared(connection, module, active);
1180        if active {
1181            state.active_declarations.insert(module.into(), connection);
1182        }
1183        self.notify_delivery_changed();
1184        Ok(())
1185    }
1186
1187    /// Clear everything `connection` held in the configuration owner. The
1188    /// delivery coordinator wakes only when the connection held configuration
1189    /// state (a declaration, a delivery, an approval or its request, a desktop
1190    /// view, an anchor wait) or ran a `config.review` worker. Unrelated client
1191    /// disconnects do not wake it.
1192    pub fn disconnected(&self, connection: ConnectionId) {
1193        let mut held = false;
1194        if let Ok(mut index) = self.approval_request_index.lock() {
1195            index.retain(|(caller, _), request| {
1196                if *caller == connection {
1197                    request.cancel();
1198                    held = true;
1199                    false
1200                } else {
1201                    true
1202                }
1203            });
1204        }
1205        match self.inner.try_lock() {
1206            Ok(mut state) => {
1207                if state.disconnected(connection) {
1208                    held = true;
1209                    // This change bypassed an OwnerGuard. Flag it before the
1210                    // owner is released so the next guard republishes it.
1211                    self.projection_stale
1212                        .store(true, std::sync::atomic::Ordering::Release);
1213                }
1214            }
1215            Err(_) => {
1216                if let Ok(mut pending) = self.disconnected_pending.lock() {
1217                    pending.push(connection);
1218                }
1219                // The busy owner cannot say whether this connection held
1220                // state. Wake the coordinator so its next owner acquisition
1221                // applies the queued disconnect promptly.
1222                held = true;
1223            }
1224        }
1225        if held || self.runs_config_worker(connection) {
1226            self.notify_delivery_changed();
1227        }
1228    }
1229
1230    /// The delivery coordinator started a `config.review` worker for
1231    /// `connection`.
1232    pub(crate) fn config_worker_started(&self, connection: ConnectionId) {
1233        self.config_workers
1234            .lock()
1235            .unwrap_or_else(|poisoned| poisoned.into_inner())
1236            .insert(connection);
1237    }
1238
1239    /// The delivery coordinator retired `connection`'s worker.
1240    pub(crate) fn config_worker_stopped(&self, connection: ConnectionId) {
1241        self.config_workers
1242            .lock()
1243            .unwrap_or_else(|poisoned| poisoned.into_inner())
1244            .remove(&connection);
1245    }
1246
1247    fn runs_config_worker(&self, connection: ConnectionId) -> bool {
1248        self.config_workers
1249            .lock()
1250            .map_or(true, |workers| workers.contains(&connection))
1251    }
1252
1253    pub fn module_get(
1254        &self,
1255        connection: ConnectionId,
1256        module: &str,
1257        request: subc_protocol::config::ConfigGetRequest,
1258    ) -> Result<subc_protocol::config::ConfigGetReply> {
1259        let mut state = self.lock()?;
1260        self.module_get_locked(&mut state, connection, module, request, true)
1261    }
1262
1263    fn module_get_locked(
1264        &self,
1265        state: &mut OwnerState,
1266        connection: ConnectionId,
1267        module: &str,
1268        request: subc_protocol::config::ConfigGetRequest,
1269        check_store: bool,
1270    ) -> Result<subc_protocol::config::ConfigGetReply> {
1271        let declaration = state
1272            .declarations
1273            .get(&connection)
1274            .filter(|(id, _)| id == module)
1275            .map(|(_, declaration)| declaration.clone())
1276            .ok_or_else(|| {
1277                GateError::new(
1278                    "declaration_order",
1279                    "config.declare must precede get or applied on this connection",
1280                )
1281            })?;
1282        if request.project_id.is_some() {
1283            return Err(GateError::new(
1284                "config_gated",
1285                format!("{module}: project-tuple delivery is not supported yet"),
1286            ));
1287        }
1288        if check_store {
1289            let checked = state.store.check();
1290            if matches!(
1291                state.store.loaded_admission_state().0,
1292                StoreState::StoreMissing | StoreState::StoreUnverified
1293            ) {
1294                return recovery::active_view(state, module, &declaration, &request);
1295            }
1296            checked?;
1297        }
1298        if state.store.loaded_admission_state().0 == StoreState::Unstamped {
1299            if request.generation.is_some() || request.attempt.is_some() {
1300                return Err(GateError::new(
1301                    "config_gated",
1302                    "unstamped reads have no assigned generation or delivery attempt",
1303                ));
1304            }
1305            let mut declarations = Self::declarations(state)?;
1306            declarations.insert(module.into(), declaration);
1307            let mut captured = self
1308                .capturer
1309                .capture_modules(&declarations, &BTreeSet::from([module.to_owned()]))?;
1310            let view = captured
1311                .modules
1312                .remove(module)
1313                .ok_or_else(|| GateError::new("config_gated", "module declaration is unavailable"))?
1314                .view;
1315            return Ok(subc_protocol::config::ConfigGetReply::new(Some(view), None));
1316        }
1317        if check_store {
1318            state.store.delivery_ready()?;
1319        }
1320        let body = if check_store {
1321            state.store.body()?
1322        } else {
1323            state.store.loaded_admission_state().1
1324        };
1325        let tuple = crate::config_store::Tuple {
1326            module: module.into(),
1327            project: None,
1328        };
1329        let versions = body
1330            .versions
1331            .iter()
1332            .find(|(entry, _)| entry == &tuple)
1333            .map(|(_, versions)| versions)
1334            .ok_or_else(|| {
1335                GateError::new("config_gated", "module is not in an approved generation")
1336            })?;
1337        let approved_declaration = [versions.pending, versions.active]
1338            .into_iter()
1339            .flatten()
1340            .any(|generation| {
1341                body.generations
1342                    .get(&generation)
1343                    .and_then(|entry| entry.delivery.as_ref())
1344                    .and_then(|snapshot| snapshot.declarations.get(module))
1345                    == Some(&declaration)
1346            });
1347        if !approved_declaration && versions.active.is_none() {
1348            return Err(GateError::new(
1349                "config_gated",
1350                "module has no approved active configuration",
1351            ));
1352        }
1353        let view = |generation: Option<u64>, status: ConfigStatus| -> Result<Option<ConfigView>> {
1354            let Some(generation) = generation else {
1355                return Ok(None);
1356            };
1357            let delivery = body
1358                .generations
1359                .get(&generation)
1360                .and_then(|entry| entry.delivery.as_ref())
1361                .ok_or_else(|| {
1362                    GateError::new("config_gated", "approved delivery bytes are absent")
1363                })?;
1364            let mut view =
1365                delivery.modules.get(module).cloned().ok_or_else(|| {
1366                    GateError::new("config_gated", "approved module view is absent")
1367                })?;
1368            view.generation = generation;
1369            view.status = status;
1370            Ok(Some(view))
1371        };
1372        let active = view(versions.active, ConfigStatus::Active)?;
1373        if !approved_declaration {
1374            let mut reply = subc_protocol::config::ConfigGetReply::new(active, None);
1375            reply.declaration_pending = Self::declaration_pending(state, module, &declaration);
1376            return if check_store {
1377                delivery::bind_declaration_fallback(state, connection, module, &request, reply)
1378            } else {
1379                Ok(reply)
1380            };
1381        }
1382        let pending = view(versions.pending, ConfigStatus::Pending)?;
1383        let transition = versions
1384            .pending
1385            .and_then(|id| body.generations.get(&id))
1386            .map(|entry| super::apply::Transition::for_module(&entry.generation.changeset, module))
1387            .transpose()?
1388            .unwrap_or(super::apply::Transition::Live);
1389        if active.is_none() && pending.is_none() {
1390            return Err(GateError::new(
1391                "config_gated",
1392                "module has no active or deliverable generation",
1393            ));
1394        }
1395        if !check_store {
1396            return delivery::visible_reply(
1397                state,
1398                connection,
1399                subc_protocol::config::ConfigGetReply::new(active, pending),
1400                transition,
1401            );
1402        }
1403        delivery::bind_get(
1404            state,
1405            connection,
1406            module,
1407            &request,
1408            subc_protocol::config::ConfigGetReply::new(active, pending),
1409            transition,
1410        )
1411    }
1412
1413    fn declaration_pending(
1414        state: &OwnerState,
1415        module: &str,
1416        declaration: &ConfigDeclareRequest,
1417    ) -> Option<subc_protocol::config::ConfigDeclarationPending> {
1418        let body = state.store.loaded_admission_state().1;
1419        if !body.stamped {
1420            return None;
1421        }
1422        let versions = body
1423            .versions
1424            .iter()
1425            .find(|(tuple, _)| tuple.module == module && tuple.project.is_none())?
1426            .1
1427            .clone();
1428        if versions.active.is_none()
1429            || [versions.active, versions.pending]
1430                .into_iter()
1431                .flatten()
1432                .any(|id| {
1433                    body.generations
1434                        .get(&id)
1435                        .and_then(|entry| entry.delivery.as_ref())
1436                        .and_then(|delivery| delivery.declarations.get(module))
1437                        == Some(declaration)
1438                })
1439        {
1440            return None;
1441        }
1442        let mut marker = subc_protocol::config::ConfigDeclarationPending::default();
1443        marker.plan_digest = state
1444            .gate
1445            .plans
1446            .values()
1447            .filter(|plan| {
1448                plan.modules.contains(module)
1449                    && plan
1450                        .delivery
1451                        .as_ref()
1452                        .and_then(|delivery| delivery.declarations.get(module))
1453                        == Some(declaration)
1454            })
1455            .max_by_key(|plan| plan.creation_sequence)
1456            .map(|plan| plan.view.digest.clone());
1457        Some(marker)
1458    }
1459
1460    fn declarations(state: &mut OwnerState) -> Result<BTreeMap<String, ConfigDeclareRequest>> {
1461        let mut declarations = if state.store.status().state == StoreState::Stamped {
1462            state
1463                .store
1464                .body()?
1465                .generations
1466                .values()
1467                .next_back()
1468                .and_then(|entry| entry.delivery.as_ref())
1469                .map(|snapshot| snapshot.declarations.clone())
1470                .unwrap_or_default()
1471        } else {
1472            BTreeMap::new()
1473        };
1474        for (module, connection) in &state.active_declarations {
1475            if let Some((_, declaration)) = state.declarations.get(connection) {
1476                declarations.insert(module.clone(), declaration.clone());
1477            }
1478        }
1479        Ok(declarations)
1480    }
1481
1482    fn capture(&self, state: &mut OwnerState) -> Result<CapturedConfiguration> {
1483        let declarations = Self::declarations(state)?;
1484        let captured = self.capturer.capture(&declarations)?;
1485        state.observed_snapshot = Some(captured.diagnostic.clone());
1486        Ok(captured)
1487    }
1488
1489    fn capture_modules(
1490        &self,
1491        state: &mut OwnerState,
1492        modules: &BTreeSet<String>,
1493    ) -> Result<CapturedConfiguration> {
1494        self.capturer
1495            .capture_modules(&Self::declarations(state)?, modules)
1496    }
1497
1498    fn check_authority(state: &mut OwnerState, recovery: bool) -> Result<()> {
1499        if let Err(error) = state.store.check() {
1500            return if recovery
1501                && matches!(
1502                    state.store.loaded_admission_state().0,
1503                    StoreState::StoreUnverified | StoreState::StoreMissing
1504                ) {
1505                Ok(())
1506            } else {
1507                Err(error.into())
1508            };
1509        }
1510        state.retry_anchor(true);
1511        match state.store.check() {
1512            Ok(()) => Ok(()),
1513            Err(_)
1514                if recovery
1515                    && matches!(
1516                        state.store.status().state,
1517                        StoreState::StoreUnverified | StoreState::StoreMissing
1518                    ) =>
1519            {
1520                Ok(())
1521            }
1522            Err(error) => Err(error.into()),
1523        }
1524    }
1525
1526    /// Run from a blocking worker: capture and store publication may touch disk
1527    /// and the platform keychain. No transport wait takes place under this lock.
1528    /// Preflight may record the proposal observed on disk. Refusals for missing
1529    /// authoritative project membership, active-scope usage or approved-program
1530    /// launch selection happen before any plan, approval or generation is
1531    /// written. A proposal neither approves nor records the refused plan.
1532    pub fn prepare(&self, kind: PlanKind) -> Result<PreparedPlan> {
1533        let mut state = self.lock()?;
1534        Self::check_authority(
1535            &mut state,
1536            matches!(kind, PlanKind::Stamp | PlanKind::Unstamp),
1537        )?;
1538        #[cfg(test)]
1539        if let Some(hook) = self.prepare_capture_hook.lock().unwrap().take() {
1540            hook();
1541        }
1542        let observed = self.capture(&mut state)?;
1543        if observed.daemon.bytes.is_none() {
1544            return Err(GateError::new(
1545                "invalid_daemon_config",
1546                "subc.jsonc is absent; refusing to rescan",
1547            ));
1548        }
1549        if !state.recovery_exit_hold && state.store.status().state == StoreState::Stamped {
1550            let approved = super::GateSnapshot::from_store(&state.store.body()?.approved)?;
1551            state
1552                .store
1553                .observe(observed.proposal_snapshot(&approved).to_store()?)?;
1554        }
1555        let rollback = if let PlanKind::Rollback(id) = kind {
1556            let target = super::GateSnapshot::from_store(&state.store.rollback_configuration(id)?)?;
1557            let delivery = state
1558                .store
1559                .body()?
1560                .generations
1561                .get(&id)
1562                .and_then(|entry| entry.delivery.as_ref())
1563                .ok_or_else(|| {
1564                    GateError::new(
1565                        "rollback_snapshot_unavailable",
1566                        "retained raw configuration is absent",
1567                    )
1568                })?;
1569            Some((self.capturer.capture_retained(&target, delivery)?, target))
1570        } else {
1571            None
1572        };
1573        let (candidate, mut observed, target) = if let Some((candidate, target)) = rollback {
1574            (candidate, Some(observed), Some(target))
1575        } else {
1576            (observed, None, None)
1577        };
1578        if kind == PlanKind::Stamp {
1579            super::registration::check_stamp(&candidate.diagnostic)?;
1580        }
1581        let base_revision = state.store.status().base_revision;
1582        let old = if state.store.status().state == StoreState::Stamped {
1583            super::GateSnapshot::from_store(&state.store.body()?.approved)?
1584        } else {
1585            super::GateSnapshot::default()
1586        };
1587        let mut touched_modules: BTreeSet<_> = candidate
1588            .diagnostic
1589            .changed_keys(&old)
1590            .iter()
1591            .filter_map(|key| key.module().map(str::to_owned))
1592            .collect();
1593        if matches!(kind, PlanKind::Stamp | PlanKind::Unstamp) {
1594            touched_modules.extend(candidate.diagnostic.modules());
1595            touched_modules.extend(old.modules());
1596        }
1597        if let Some(target) = target {
1598            touched_modules.extend(
1599                candidate
1600                    .diagnostic
1601                    .inputs
1602                    .iter()
1603                    .filter(|(key, value)| {
1604                        key.is_program() && target.inputs.get(*key) != Some(*value)
1605                    })
1606                    .filter_map(|(key, _)| key.module().map(str::to_owned)),
1607            );
1608        }
1609        let mut review_modules: BTreeSet<String> = touched_modules
1610            .iter()
1611            .filter(|module| candidate.modules.contains_key(*module))
1612            .filter(|module|matches!(kind,PlanKind::Stamp|PlanKind::Unstamp) || candidate.diagnostic.changed_keys(&old).iter().any(|key|matches!(key,super::InputKey::Layer {module:owner,..}|super::InputKey::Declaration(owner) if owner==*module)))
1613            .cloned()
1614            .collect();
1615        // A program change is approved launch-only: neither the build being
1616        // approved nor the one still running can review for it. Once the new
1617        // program is active, the next plan re-reviews the approved layers with
1618        // it. While it is not yet active the module waits, and the plan
1619        // carries its earlier reviewer forward.
1620        let mut rereview_modules = BTreeSet::new();
1621        if matches!(kind, PlanKind::Change | PlanKind::Rollback(_))
1622            && state.store.status().state == StoreState::Stamped
1623        {
1624            for (module, rereview) in
1625                super::reviewed_build::pending(state.store.body()?, candidate.modules.keys())?
1626            {
1627                if rereview == super::reviewed_build::Rereview::Ready
1628                    && !review_modules.contains(&module)
1629                {
1630                    touched_modules.insert(module.clone());
1631                    review_modules.insert(module.clone());
1632                    rereview_modules.insert(module);
1633                }
1634            }
1635        }
1636        let program_keys: Vec<_> = candidate
1637            .diagnostic
1638            .inputs
1639            .keys()
1640            .filter(|key| {
1641                key.is_program()
1642                    && key
1643                        .module()
1644                        .is_some_and(|module| touched_modules.contains(module))
1645            })
1646            .cloned()
1647            .collect();
1648        let read_set = if let Some(observed) = &mut observed {
1649            observed.capture_programs(&program_keys)?;
1650            if program_keys.iter().any(|key| {
1651                observed.diagnostic.inputs.get(key) != candidate.diagnostic.inputs.get(key)
1652            }) {
1653                return Err(GateError::stale());
1654            }
1655            observed.diagnostic.read_set(&touched_modules)?
1656        } else {
1657            candidate.diagnostic.read_set(&touched_modules)?
1658        };
1659        let observed_handles = observed
1660            .as_mut()
1661            .map(CapturedConfiguration::take_handles)
1662            .unwrap_or_default();
1663        let mut bases = BTreeMap::new();
1664        let mut base_schemas = BTreeMap::new();
1665        let mut active_generations = BTreeMap::new();
1666        if state.store.status().state == StoreState::Stamped {
1667            let body = state.store.body()?;
1668            let approved_id = placement::last_approved_generation(body);
1669            for (tuple, versions) in &body.versions {
1670                if touched_modules.contains(&tuple.module) {
1671                    active_generations.insert(tuple.clone(), versions.active);
1672                }
1673                if tuple.project.is_some() || !review_modules.contains(&tuple.module) {
1674                    continue;
1675                }
1676                // A plan replaces the last approval, even when that generation
1677                // has not activated. The reviewer and the card use that base.
1678                // A launch entry alone is not an approved configuration base;
1679                // only a retained declaration establishes one for review.
1680                if old
1681                    .inputs
1682                    .contains_key(&super::InputKey::Declaration(tuple.module.clone()))
1683                {
1684                    let id = approved_id;
1685                    let snapshot = body
1686                        .generations
1687                        .get(&id)
1688                        .and_then(|entry| entry.delivery.as_ref())
1689                        .ok_or_else(|| {
1690                            GateError::new(
1691                                "approved_schema_unavailable",
1692                                format!(
1693                                    "{}: approved old schema is missing or damaged",
1694                                    tuple.module
1695                                ),
1696                            )
1697                        })?;
1698                    let schema = snapshot
1699                        .declarations
1700                        .get(&tuple.module)
1701                        .and_then(|declaration| {
1702                            subc_config::Schema::new(declaration.schema.clone()).ok()
1703                        })
1704                        .ok_or_else(|| {
1705                            GateError::new(
1706                                "approved_schema_unavailable",
1707                                format!(
1708                                    "{}: approved old schema is missing or damaged",
1709                                    tuple.module
1710                                ),
1711                            )
1712                        })?;
1713                    base_schemas.insert(tuple.module.clone(), schema);
1714                    let view = snapshot.modules.get(&tuple.module).ok_or_else(|| {
1715                        GateError::new(
1716                            "config_gated",
1717                            format!("{}: approved view is absent", tuple.module),
1718                        )
1719                    })?;
1720                    let mut view = view.clone();
1721                    view.generation = id;
1722                    view.status = if versions.active == Some(id) {
1723                        ConfigStatus::Active
1724                    } else {
1725                        ConfigStatus::Pending
1726                    };
1727                    bases.insert(tuple.module.clone(), view);
1728                }
1729            }
1730        }
1731        Ok(PreparedPlan {
1732            edits: None,
1733            candidate,
1734            bases,
1735            base_schemas,
1736            kind,
1737            review_modules,
1738            rereview_modules,
1739            base_revision,
1740            active_generations,
1741            touched_modules,
1742            read_set,
1743            program_keys,
1744            observed_handles,
1745        })
1746    }
1747
1748    pub fn finish_plan(
1749        &self,
1750        mut prepared: PreparedPlan,
1751        review: impl FnOnce(&super::GateSnapshot, &super::GateSnapshot) -> Result<Changeset>,
1752    ) -> Result<ConfigPlanView> {
1753        let mut state = self.lock()?;
1754        Self::check_authority(
1755            &mut state,
1756            matches!(prepared.kind, PlanKind::Stamp | PlanKind::Unstamp),
1757        )?;
1758        let active_generations = if state.store.status().state == StoreState::Stamped {
1759            state
1760                .store
1761                .body()?
1762                .versions
1763                .iter()
1764                .filter(|(tuple, _)| prepared.touched_modules.contains(&tuple.module))
1765                .map(|(tuple, versions)| (tuple.clone(), versions.active))
1766                .collect()
1767        } else {
1768            BTreeMap::new()
1769        };
1770        let mut current = if prepared.edits.is_some() {
1771            self.edit_baseline(&mut state, Some(&prepared.touched_modules))
1772        } else {
1773            self.capture_modules(&mut state, &prepared.touched_modules)
1774        }
1775        .map_err(|_| GateError::stale())?;
1776        current
1777            .capture_programs(&prepared.program_keys)
1778            .map_err(|_| GateError::stale())?;
1779        if (prepared.edits.is_none()
1780            && state.store.status().base_revision != prepared.base_revision)
1781            || active_generations != prepared.active_generations
1782            || !prepared
1783                .read_set
1784                .matches(&current.diagnostic.read_set(&prepared.touched_modules)?)
1785        {
1786            return Err(if prepared.edits.is_some() {
1787                GateError::new(
1788                    "config_changed_since_review",
1789                    "a touched module changed while the edits were reviewed",
1790                )
1791            } else {
1792                GateError::stale()
1793            });
1794        }
1795        if prepared.edits.is_some() {
1796            // Carry forward approvals for modules outside the edit set. Changes
1797            // to those approvals must neither refuse these edits nor be reverted by them.
1798            let touched = &prepared.touched_modules;
1799            for (key, input) in &current.diagnostic.inputs {
1800                if key.module().is_none_or(|module| !touched.contains(module)) {
1801                    prepared
1802                        .candidate
1803                        .diagnostic
1804                        .inputs
1805                        .insert(key.clone(), input.clone());
1806                }
1807            }
1808            prepared.candidate.diagnostic.inputs.retain(|key, _| {
1809                key.module().is_some_and(|module| touched.contains(module))
1810                    || current.diagnostic.inputs.contains_key(key)
1811            });
1812            prepared
1813                .candidate
1814                .modules
1815                .retain(|module, _| touched.contains(module));
1816            for (module, captured) in std::mem::take(&mut current.modules) {
1817                if !touched.contains(&module) {
1818                    prepared.candidate.modules.insert(module, captured);
1819                }
1820            }
1821        }
1822        let delivery = DeliverySnapshot {
1823            daemon: Some(ConfigLayerSnapshot::file(
1824                "subc",
1825                ConfigLayer::User,
1826                prepared.candidate.daemon.path.to_string_lossy(),
1827                prepared.candidate.daemon.bytes.clone(),
1828            )),
1829            modules: prepared
1830                .candidate
1831                .modules
1832                .iter()
1833                .map(|(module, captured)| (module.clone(), captured.view.clone()))
1834                .collect(),
1835            declarations: prepared
1836                .candidate
1837                .modules
1838                .iter()
1839                .map(|(module, captured)| (module.clone(), captured.declaration.clone()))
1840                .collect(),
1841        };
1842        let mut handles = prepared.candidate.take_handles();
1843        handles.append(&mut prepared.observed_handles);
1844        let previous_delivery = if state.store.status().state == StoreState::Stamped {
1845            let body = state.store.body()?;
1846            body.generations
1847                .get(&placement::last_approved_generation(body))
1848                .and_then(|entry| entry.delivery.clone())
1849        } else if prepared.edits.as_ref().is_some_and(|edit| edit.unstamped) {
1850            Some(DeliverySnapshot {
1851                daemon: delivery.daemon.clone(),
1852                modules: prepared.bases.clone(),
1853                declarations: delivery.declarations.clone(),
1854            })
1855        } else {
1856            None
1857        };
1858        // Activation policy compares the candidate with what is running, not
1859        // with the last approval used by the visible field rows.
1860        let mut active_fields = Vec::new();
1861        for (module, captured) in prepared.candidate.modules.iter().filter(|(module, _)| {
1862            // Stamping records the inputs already running; unstamping returns
1863            // authority to files. Neither operation changes runtime values.
1864            matches!(prepared.kind, PlanKind::Change | PlanKind::Rollback(_))
1865                && prepared.touched_modules.contains(*module)
1866        }) {
1867            let active = if state.store.status().state == StoreState::Stamped {
1868                let body = state.store.body()?;
1869                body.versions
1870                    .iter()
1871                    .find(|(tuple, _)| tuple.module == *module && tuple.project.is_none())
1872                    .and_then(|(_, versions)| versions.active)
1873                    .and_then(|id| body.generations.get(&id))
1874                    .and_then(|entry| entry.delivery.as_ref())
1875            } else {
1876                None
1877            };
1878            let base = active.and_then(|snapshot| snapshot.modules.get(module));
1879            let schema = active
1880                .and_then(|snapshot| snapshot.declarations.get(module))
1881                .map(|declaration| subc_config::Schema::new(declaration.schema.clone()))
1882                .transpose()
1883                .map_err(GateError::invalid)?;
1884            active_fields.extend(
1885                super::review::expected_fields(
1886                    module,
1887                    &captured.schema,
1888                    base,
1889                    schema.as_ref(),
1890                    &captured.view,
1891                )?
1892                .into_values(),
1893            );
1894        }
1895        let OwnerState { gate, store, .. } = &mut *state;
1896        let view = gate.plan_reviewed_inner(
1897            store,
1898            prepared.kind,
1899            prepared.candidate.diagnostic,
1900            &current.diagnostic,
1901            super::ReviewRecord::Reviewed(&prepared.review_modules),
1902            prepared.edits,
1903            |old, new| {
1904                let mut changeset = review(old, new)?;
1905                layer_file_rows(
1906                    &mut changeset,
1907                    old,
1908                    new,
1909                    previous_delivery.as_ref(),
1910                    &delivery,
1911                )?;
1912                let mut activation = changeset.clone();
1913                activation.fields = active_fields;
1914                super::apply::bind_plan(&mut activation)?;
1915                if !changeset.apply_plan.is_object() {
1916                    changeset.apply_plan = if changeset.apply_plan.is_null() {
1917                        serde_json::json!({})
1918                    } else {
1919                        serde_json::json!({"review": changeset.apply_plan})
1920                    };
1921                }
1922                changeset.apply_plan["module_transitions"] =
1923                    activation.apply_plan["module_transitions"].clone();
1924                Ok(changeset)
1925            },
1926        )?;
1927        if let Err(error) = self.check_route_policy_authority(&view.plan.changeset) {
1928            gate.expire_plan(&view.digest);
1929            return Err(error);
1930        }
1931        gate.bind_delivery(&view.digest, delivery)?;
1932        state.reviewed(&view.digest, Instant::now());
1933        state
1934            .retained_plan_files
1935            .insert(view.digest.clone(), handles);
1936        Ok(view)
1937    }
1938
1939    pub fn begin_approval(
1940        &self,
1941        digest: &Digest,
1942        facts: &ApprovalFacts,
1943    ) -> Result<ApprovalChallenge> {
1944        self.begin_approval_for_request(digest, facts, None)
1945    }
1946
1947    pub(crate) fn begin_approval_for_request(
1948        &self,
1949        digest: &Digest,
1950        facts: &ApprovalFacts,
1951        request: Option<&ApprovalRequest>,
1952    ) -> Result<ApprovalChallenge> {
1953        #[cfg(test)]
1954        struct Completion<'a>(&'a std::sync::atomic::AtomicUsize);
1955        #[cfg(test)]
1956        impl Drop for Completion<'_> {
1957            fn drop(&mut self) {
1958                self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1959            }
1960        }
1961        #[cfg(test)]
1962        let _completed = Completion(&self.begin_approval_completions);
1963        #[cfg(test)]
1964        if let Some(hook) = self.begin_approval_hook.lock().unwrap().take() {
1965            hook();
1966        }
1967        let mut state = self.lock()?;
1968        if let Some(request) = request {
1969            request.ensure_live()?;
1970        }
1971        if state.expired_plans.contains(digest) {
1972            return Err(GateError::new(
1973                "plan_expired",
1974                "configuration plan exceeded its one-hour idle lifetime",
1975            ));
1976        }
1977        Self::check_authority(&mut state, true)?;
1978        let modules = state.gate.plan_modules(digest)?;
1979        let program_keys = state.gate.plan_program_keys(digest)?;
1980        let mut current = if state
1981            .gate
1982            .plans
1983            .get(digest)
1984            .is_some_and(|plan| plan.edits.is_some())
1985        {
1986            self.edit_baseline(&mut state, Some(&modules))
1987        } else {
1988            self.capture_modules(&mut state, &modules)
1989        }
1990        .map_err(|_| GateError::stale())?;
1991        current
1992            .capture_programs(&program_keys)
1993            .map_err(|_| GateError::stale())?;
1994        let facts = state.with_desktop_view(digest, facts);
1995        let OwnerState { gate, store, .. } = &mut *state;
1996        if let Some(request) = request {
1997            request.ensure_live()?;
1998        }
1999        let challenge = gate.begin_approval(digest, store, &current.diagnostic, &facts)?;
2000        state.reviewed(digest, Instant::now());
2001        Ok(challenge)
2002    }
2003
2004    /// Acquire only after interactive approval. Sorted module locks serialize
2005    /// the final freshness check and publication with target changes at cutover.
2006    pub(crate) async fn approval_commit_gates(
2007        self: &std::sync::Arc<Self>,
2008        attempt: u64,
2009    ) -> Result<Vec<tokio::sync::OwnedMutexGuard<()>>> {
2010        let modules = self
2011            .on_blocking(move |owner| owner.lock()?.gate.approval_gate_modules(attempt))
2012            .await?;
2013        let mut guards = Vec::with_capacity(modules.len());
2014        for module in modules {
2015            guards.push(self.module_gate(&module)?.lock_owned().await);
2016        }
2017        Ok(guards)
2018    }
2019
2020    pub fn finish_approval(
2021        &self,
2022        attempt: u64,
2023        facts: &ApprovalFacts,
2024        reply: ApprovalReply,
2025        now_ms: u64,
2026    ) -> Result<u64> {
2027        // In-process approvals have no reader reservation. Wire approvals pass
2028        // their exact request token into the publication job instead.
2029        self.finish_approval_with_commit_window(
2030            attempt,
2031            facts,
2032            reply,
2033            now_ms,
2034            None,
2035            ApprovalRequest::for_attempt(attempt),
2036        )
2037    }
2038
2039    pub(crate) fn finish_approval_with_commit_window(
2040        &self,
2041        attempt: u64,
2042        facts: &ApprovalFacts,
2043        reply: ApprovalReply,
2044        now_ms: u64,
2045        window: Option<std::sync::Arc<ApprovalCommitWindow>>,
2046        cancellation: std::sync::Arc<ApprovalRequest>,
2047    ) -> Result<u64> {
2048        if cancellation.attempt() != attempt {
2049            return Err(GateError::new(
2050                "config_unavailable",
2051                "approval request witness does not match its attempt",
2052            ));
2053        }
2054        let mut state = self.lock()?;
2055        let digest = state.gate.approval_digest(attempt)?;
2056        let declarations_only = state
2057            .gate
2058            .plans
2059            .get(&digest)
2060            .is_some_and(|plan| plan.development_approval.is_some());
2061        state.reviewed(&digest, Instant::now());
2062        let modules = state.gate.approval_modules(attempt)?;
2063        let program_keys = state.gate.plan_program_keys(&digest)?;
2064        // Reopen inputs after the operator's interactive confirmation, immediately
2065        // before freshness checking and atomic publication of the saved plan.
2066        let edit_plan = state
2067            .gate
2068            .plans
2069            .get(&digest)
2070            .and_then(|plan| plan.edits.clone());
2071        let current = match Self::check_authority(&mut state, true).and_then(|_| {
2072            let mut current = if edit_plan.is_some() {
2073                self.edit_baseline(&mut state, Some(&modules))
2074            } else {
2075                self.capture_modules(&mut state, &modules)
2076            }
2077            .map_err(|_| GateError::stale())?;
2078            current
2079                .capture_programs(&program_keys)
2080                .map_err(|_| GateError::stale())?;
2081            Ok(current)
2082        }) {
2083            Ok(current) => current,
2084            Err(error) => {
2085                state.gate.cancel_attempt(attempt);
2086                return Err(error);
2087            }
2088        };
2089        let facts = state.with_desktop_view(&digest, facts);
2090        self.drain_canceled_approvals(&mut state);
2091        self.drain_disconnections(&mut state);
2092        #[cfg(test)]
2093        if let Some(hook) = state.after_approval_drain_hook.take() {
2094            hook();
2095        }
2096        let was_unstamped = state.store.status().state == StoreState::Unstamped;
2097        let was_recovery = state.recovery_exit_hold
2098            || matches!(
2099                state.store.status().state,
2100                StoreState::StoreMissing | StoreState::StoreUnverified
2101            );
2102        let unstamp_hints = recovery::changed_file_views(self, &mut state, &current);
2103        #[cfg(test)]
2104        let publication_hook = state.publication_hook.take();
2105        #[cfg(test)]
2106        let prepublication_hook = state.prepublication_hook.take();
2107        let publication_before = state.store.publication_sequence();
2108        let OwnerState {
2109            gate,
2110            store,
2111            route_policy_receipts,
2112            installed_route_policies,
2113            delivery,
2114            ..
2115        } = &mut *state;
2116        let result = gate.finish_approval_with_precommit(
2117            attempt,
2118            reply,
2119            store,
2120            &current.diagnostic,
2121            &facts,
2122            now_ms,
2123            || {
2124                #[cfg(test)]
2125                if let Some(hook) = prepublication_hook {
2126                    hook();
2127                }
2128                if let Some(window) = window {
2129                    window.begin_publication()?;
2130                }
2131                {
2132                    // Serialize the publication claim with cancellation-index
2133                    // health, then release the index before any store work.
2134                    let _index = self.approval_request_index.lock().map_err(|_| {
2135                        GateError::new(
2136                            "config_unavailable",
2137                            "approval cancellation index is poisoned",
2138                        )
2139                    })?;
2140                    cancellation.claim_publication()?;
2141                }
2142                if !declarations_only {
2143                    route_policy::restore_superseded(
2144                        route_policy_receipts,
2145                        installed_route_policies,
2146                        &modules,
2147                        delivery,
2148                    );
2149                }
2150                #[cfg(test)]
2151                if let Some(hook) = publication_hook {
2152                    hook();
2153                }
2154                Ok(())
2155            },
2156        );
2157        let committed_this_call = state.store.publication_sequence() != publication_before;
2158        if committed_this_call {
2159            if let Some(edit_plan) = edit_plan {
2160                for file in &edit_plan.files {
2161                    let _ = file.write_back();
2162                }
2163                // Publication already succeeded. Refresh drift after reconciliation
2164                // without turning a failed diagnostic capture into a failed approval.
2165                let _ = (|| -> Result<()> {
2166                    let captured = self.capture(&mut state)?;
2167                    let approved = super::GateSnapshot::from_store(&state.store.body()?.approved)?;
2168                    state
2169                        .store
2170                        .observe(captured.proposal_snapshot(&approved).to_store()?)?;
2171                    Ok(())
2172                })();
2173            }
2174        }
2175        let stamped_files = committed_this_call
2176            && (was_unstamped || was_recovery)
2177            && state.store.body().is_ok_and(|body| {
2178                body.generations
2179                    .get(&body.last_generation)
2180                    .is_some_and(|entry| {
2181                        entry.generation.plan_digest == digest
2182                            && entry.kind == crate::config_store::CommitKind::Stamp
2183                    })
2184            });
2185        if result.is_ok() {
2186            state.plan_deadlines.remove(&digest);
2187            state.retained_plan_files.remove(&digest);
2188            state.desktop_views.retain(|_, (shown, _)| shown != &digest);
2189        }
2190        let unstamped = result.is_ok() && state.store.status().state == StoreState::Unstamped;
2191        let committed_exit = state
2192            .store
2193            .loaded_admission_state()
2194            .1
2195            .generations
2196            .iter()
2197            .next_back()
2198            .filter(|(_, entry)| {
2199                committed_this_call
2200                    && entry.generation.plan_digest == digest
2201                    && entry.kind != crate::config_store::CommitKind::DeclarationApproval
2202                    && (was_recovery
2203                        || state.store.loaded_admission_state().1.stamped
2204                        || entry.kind == crate::config_store::CommitKind::Unstamp)
2205            })
2206            .map(|(generation, entry)| {
2207                (
2208                    *generation,
2209                    entry.kind == crate::config_store::CommitKind::Unstamp,
2210                )
2211            });
2212        if committed_this_call && was_recovery {
2213            state.authority_incarnation = std::sync::Arc::new(());
2214        }
2215        if let Some((generation, unstamp)) = committed_exit {
2216            state.authority_exit = Some(generation);
2217            state.recovery_exit_hold = was_recovery;
2218            if was_recovery || unstamp {
2219                state
2220                    .delivery
2221                    .reset_for_authority_exit(if unstamp { generation } else { 0 });
2222            }
2223            if unstamp {
2224                state.stamp_channel_cutover = false;
2225                state.reconciled_entries.clear();
2226                state.unstamp_hints.extend(unstamp_hints);
2227            }
2228        } else if committed_this_call {
2229            state.authority_exit = None;
2230        }
2231        if stamped_files {
2232            state.stamp_channel_cutover = true;
2233            let connections: Vec<_> = state.active_declarations.values().copied().collect();
2234            state.delivery.remember_stamp_connections(connections);
2235        }
2236        drop(state);
2237        if unstamped {
2238            self.retire_unstamped_bindings();
2239        }
2240        result
2241    }
2242
2243    #[cfg(all(test, unix))]
2244    pub(crate) fn set_publication_hook(&self, hook: impl FnOnce() + Send + 'static) {
2245        self.inner.lock().unwrap().publication_hook = Some(Box::new(hook));
2246    }
2247
2248    #[cfg(all(test, unix))]
2249    pub(crate) fn set_prepublication_hook(&self, hook: impl FnOnce() + Send + 'static) {
2250        self.inner.lock().unwrap().prepublication_hook = Some(Box::new(hook));
2251    }
2252
2253    #[cfg(all(test, unix))]
2254    pub(crate) fn set_after_approval_drain_hook(&self, hook: impl FnOnce() + Send + 'static) {
2255        self.inner.lock().unwrap().after_approval_drain_hook = Some(Box::new(hook));
2256    }
2257
2258    #[cfg(all(test, unix))]
2259    pub(crate) fn approval_request_count_for_test(&self) -> usize {
2260        self.approval_request_index.lock().unwrap().len()
2261    }
2262
2263    #[cfg(all(test, unix))]
2264    pub(crate) fn poison_approval_request_index_for_test(&self) {
2265        let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2266            let _guard = self.approval_request_index.lock().unwrap();
2267            panic!("injected approval index poison");
2268        }));
2269        assert!(poisoned.is_err());
2270    }
2271
2272    #[cfg(all(test, unix))]
2273    pub(crate) fn pause_next_approval_claim_for_test(
2274        &self,
2275    ) -> (
2276        tokio::sync::oneshot::Receiver<()>,
2277        tokio::sync::oneshot::Sender<()>,
2278    ) {
2279        let (reached, observed) = tokio::sync::oneshot::channel();
2280        let (release, wait) = tokio::sync::oneshot::channel();
2281        *self.approval_claim_pause.lock().unwrap() = Some(ApprovalClaimPause {
2282            reached,
2283            release: wait,
2284        });
2285        (observed, release)
2286    }
2287
2288    #[cfg(all(test, unix))]
2289    pub(crate) async fn pause_approval_claim_for_test(&self) {
2290        let pause = self.approval_claim_pause.lock().unwrap().take();
2291        if let Some(pause) = pause {
2292            let _ = pause.reached.send(());
2293            pause.release.await.unwrap();
2294        }
2295    }
2296
2297    // Flipping a flag is platform-neutral. Its callers are the unix-only phone
2298    // tests and, under test-support, the ckdev config test seam and its tests.
2299    #[cfg(any(all(test, unix), feature = "test-support"))]
2300    pub(crate) fn set_os_prompt_policy_for_tests(&self) {
2301        self.os_prompt_policy
2302            .store(true, std::sync::atomic::Ordering::Relaxed);
2303    }
2304
2305    #[cfg(any(test, feature = "test-support"))]
2306    pub(crate) fn os_prompt_policy_for_tests(&self) -> bool {
2307        self.os_prompt_policy
2308            .load(std::sync::atomic::Ordering::Relaxed)
2309    }
2310
2311    pub fn status(&self) -> Result<subc_control::config::ConfigStatus> {
2312        let mut state = self.lock()?;
2313        let mut current_snapshot = None;
2314        state.retry_anchor(true);
2315        let verified = state.store.check().is_ok();
2316        if verified
2317            && !state.recovery_exit_hold
2318            && !state.store.status().anchor_pending
2319            && matches!(
2320                state.store.status().state,
2321                StoreState::Stamped | StoreState::Unstamped
2322            )
2323        {
2324            let captured = self.capture(&mut state)?;
2325            current_snapshot = Some(captured.diagnostic.clone());
2326            let approved = super::GateSnapshot::from_store(&state.store.body()?.approved)?;
2327            state
2328                .store
2329                .observe(captured.proposal_snapshot(&approved).to_store()?)?;
2330        }
2331        let store_status = state.store.status();
2332        let mut status = subc_control::config::ConfigStatus::default();
2333        status.state = match store_status.state {
2334            StoreState::Stamped => "stamped",
2335            StoreState::Unstamped => "unstamped",
2336            StoreState::StoreMissing => "store_missing",
2337            StoreState::StoreUnverified => "store_unverified",
2338        }
2339        .into();
2340        if state.recovery_exit_hold {
2341            if store_status.state != StoreState::Stamped {
2342                status.state = "store_unverified".into();
2343            }
2344            status
2345                .warnings
2346                .push("approved recovery exit is waiting for reconciliation".into());
2347        }
2348        status.integrity = match store_status.integrity {
2349            crate::config_store::IntegrityMode::DigestOnly => "digest_only",
2350            crate::config_store::IntegrityMode::Sealed => "sealed",
2351        }
2352        .into();
2353        status.revision = store_status.revision;
2354        status.base_revision = store_status.base_revision;
2355        status.anchor_pending = store_status.anchor_pending;
2356        status.ungated_inputs = self.startup_overrides.clone();
2357        #[cfg(feature = "test-support")]
2358        if state.store.uses_config_gate_test_seam() {
2359            status
2360                .development_switches
2361                .push("SUBC_TEST_CONFIG_GATE".into());
2362        }
2363        status.warnings.extend(store_status.warnings);
2364        if cfg!(feature = "dev-desktop-approval") {
2365            status
2366                .development_switches
2367                .push("dev-desktop-approval".into());
2368        }
2369        #[cfg(feature = "dev-desktop-approval")]
2370        if let Some(floor) = crate::operator_apps::development_floor_diagnostic() {
2371            status.development_switches.push(floor);
2372        }
2373        if cfg!(feature = "dev-placement") {
2374            status.development_switches.push("dev-placement".into());
2375        }
2376        let declared: Vec<String> = Self::declarations(&mut state)
2377            .map(|declarations| declarations.into_keys().collect())
2378            .unwrap_or_default();
2379        if let Ok(body) = state.store.body() {
2380            if body.stamped {
2381                for (module, rereview) in
2382                    super::reviewed_build::pending(body, &declared).unwrap_or_default()
2383                {
2384                    status.warnings.push(match rereview {
2385                        super::reviewed_build::Rereview::WaitingForProgram => format!(
2386                            "module {module}: needs configuration re-review: its approved program has not reviewed its approved layers; the re-review waits until that program is running and active"
2387                        ),
2388                        super::reviewed_build::Rereview::Ready => format!(
2389                            "module {module}: needs configuration re-review: its approved program has not reviewed its approved layers; the next configuration plan re-reviews them with the running program"
2390                        ),
2391                    });
2392                }
2393            }
2394            if body.stamped {
2395                current_snapshot = super::GateSnapshot::from_store(&body.approved).ok();
2396            }
2397            for entry in body.generations.values().rev().take_while(|entry| {
2398                matches!(
2399                    entry.kind,
2400                    crate::config_store::CommitKind::Development
2401                        | crate::config_store::CommitKind::DeclarationApproval
2402                )
2403            }) {
2404                if entry.kind != crate::config_store::CommitKind::Development {
2405                    continue;
2406                }
2407                status.warnings.push(format!(
2408                    "development generation {}: development placement (no approval)",
2409                    entry.generation.id
2410                ));
2411            }
2412            status.approval_channels = body
2413                .generations
2414                .iter()
2415                .map(|(id, entry)| {
2416                    subc_control::config::ConfigApprovalRecord::new(
2417                        *id,
2418                        entry.generation.approval_channel,
2419                    )
2420                })
2421                .chain(body.pruned.iter().map(|(id, entry)| {
2422                    subc_control::config::ConfigApprovalRecord::new(*id, entry.approval_channel)
2423                }))
2424                .collect();
2425            status
2426                .approval_channels
2427                .sort_by_key(|record| record.generation);
2428            status.pending_proposals = u64::from(body.proposal.is_some());
2429            for (tuple, versions) in &body.versions {
2430                if let Some(generation) = versions.pending {
2431                    let entry = body.generations.get(&generation);
2432                    let transition = entry.and_then(|entry| {
2433                        super::apply::Transition::for_module(
2434                            &entry.generation.changeset,
2435                            &tuple.module,
2436                        )
2437                        .ok()
2438                    });
2439                    status.approved_but_inactive.push(serde_json::json!({
2440                        "module_id":tuple.module,"project_id":tuple.project,"generation":generation,
2441                        "digest":entry.map(|entry| &entry.generation.plan_digest),
2442                        "waiting_for":match transition {
2443                            Some(super::apply::Transition::DaemonRestart) => "daemon_restart",
2444                            Some(super::apply::Transition::NextSupervision) => "next_supervision",
2445                            _ => "delivery",
2446                        },
2447                    }));
2448                }
2449            }
2450        }
2451        if let Some(snapshot) = current_snapshot {
2452            status_inputs::report_snapshot(&snapshot, &mut status);
2453        }
2454        status.gated_modules = admission::AdmissionCache::from_state(&state).held_modules();
2455        if state.store.loaded_admission_state().0 == StoreState::Stamped {
2456            let declarations: Vec<_> = state
2457                .declarations
2458                .iter()
2459                .map(|(connection, (module, _))| (*connection, module.clone()))
2460                .collect();
2461            for (connection, module) in declarations {
2462                // Use get's approved-declaration/view checks without opening the
2463                // store or binding a delivery attempt merely to display status.
2464                let reply = self.module_get_locked(
2465                    &mut state,
2466                    connection,
2467                    &module,
2468                    subc_protocol::config::ConfigGetRequest::new(),
2469                    false,
2470                );
2471                if let Ok(reply) = &reply {
2472                    Self::report_declaration_pending(
2473                        &state,
2474                        connection,
2475                        &module,
2476                        reply,
2477                        &mut status,
2478                    );
2479                }
2480                if reply.is_err_and(|error| error.code == "config_gated") {
2481                    status.gated_modules.push(module);
2482                }
2483            }
2484            status.gated_modules.sort();
2485            status.gated_modules.dedup();
2486        }
2487        Ok(status)
2488    }
2489
2490    fn report_declaration_pending(
2491        state: &OwnerState,
2492        connection: ConnectionId,
2493        module: &str,
2494        reply: &subc_protocol::config::ConfigGetReply,
2495        status: &mut subc_control::config::ConfigStatus,
2496    ) {
2497        if state.active_declarations.get(module) != Some(&connection) {
2498            return;
2499        }
2500        if let Some(marker) = &reply.declaration_pending {
2501            status
2502                .declaration_pending
2503                .insert(module.into(), marker.clone());
2504            if let Some(generation) = state.delivery.fallback_applied.get(&connection) {
2505                if reply
2506                    .active
2507                    .as_ref()
2508                    .is_some_and(|view| view.generation == *generation)
2509                {
2510                    status.warnings.push(format!("module {module}: running last approved settings (generation {generation}); declaration awaits approval"));
2511                }
2512            }
2513        }
2514    }
2515
2516    pub fn history(&self) -> Result<(Vec<subc_config::Generation>, Vec<serde_json::Value>)> {
2517        let mut state = self.lock()?;
2518        state.retry_anchor(true);
2519        state.store.check()?;
2520        let body = state.store.body()?;
2521        Ok((
2522            body.generations
2523                .values()
2524                .map(|entry| entry.generation.clone())
2525                .collect(),
2526            body.pruned
2527                .values()
2528                .map(serde_json::to_value)
2529                .collect::<std::result::Result<_, _>>()
2530                .map_err(GateError::invalid)?,
2531        ))
2532    }
2533
2534    /// Admission is owned by the supervisor adapter; until it is installed it
2535    /// must not infer executable authority from diagnostic snapshots.
2536    pub fn approved_snapshot(&self) -> Result<DeliverySnapshot> {
2537        let mut state = self.lock()?;
2538        state.store.delivery_ready()?;
2539        state
2540            .store
2541            .body()?
2542            .generations
2543            .values()
2544            .next_back()
2545            .and_then(|entry| entry.delivery.clone())
2546            .ok_or_else(|| GateError::new("config_gated", "approved delivery snapshot is absent"))
2547    }
2548
2549    /// Read the saved rollback, never today's edited files. This is not spawn
2550    /// authorization: admission must select an eligible module generation and
2551    /// launch exactly the returned identity under that module's gate lock.
2552    /// Re-check the file identity at spawn and refuse `plan_stale` if it changed
2553    /// since approval. Path-changing rollback plans remain refused until the
2554    /// supervisor uses these approved inputs to select and launch programs at
2555    /// the restored paths.
2556    pub fn approved_rollback_commands(&self, generation: u64) -> Result<ApprovedRollbackCommands> {
2557        let mut state = self.lock()?;
2558        state.store.delivery_ready()?;
2559        let configuration = state.store.rollback_configuration(generation)?;
2560        let entry = &state.store.body()?.generations[&generation];
2561        if entry.kind != crate::config_store::CommitKind::Rollback {
2562            return Err(GateError::new(
2563                "rollback_generation_required",
2564                "generation is not an approved rollback",
2565            ));
2566        }
2567        let daemon = entry
2568            .delivery
2569            .as_ref()
2570            .and_then(|snapshot| snapshot.daemon.clone())
2571            .ok_or_else(|| {
2572                GateError::new(
2573                    "rollback_snapshot_unavailable",
2574                    "approved rollback command input is absent",
2575                )
2576            })?;
2577        let snapshot = super::GateSnapshot::from_store(&configuration)?;
2578        let mut programs = BTreeMap::new();
2579        for (key, identity) in snapshot.inputs {
2580            if let super::InputKey::Program { module, path } = key {
2581                if programs
2582                    .insert(module, ApprovedRollbackProgram { path, identity })
2583                    .is_some()
2584                {
2585                    return Err(GateError::new(
2586                        "rollback_snapshot_unavailable",
2587                        "rollback contains conflicting program identities",
2588                    ));
2589                }
2590            }
2591        }
2592        Ok(ApprovedRollbackCommands {
2593            generation,
2594            daemon,
2595            programs,
2596        })
2597    }
2598}