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