1mod anchor_retry;
9mod apply;
10mod approval;
11pub mod capture;
12pub(crate) mod program;
13pub mod project_registry;
14pub(crate) mod review;
15mod reviewed_build;
16mod root_io;
17pub mod runtime;
18mod snapshot;
19mod strict_json;
20
21pub use approval::*;
22pub use snapshot::{CapturedInput, GateSnapshot, InputKey};
23
24pub(crate) fn module_base_generation(body: &crate::config_store::StoreBody, module: &str) -> u64 {
26 if !body.stamped {
27 return 0;
28 }
29 body.generations
30 .values()
31 .rev()
32 .find(|entry| entry.tuples.iter().any(|tuple| tuple.module == module))
33 .map_or(0, |entry| entry.generation.id)
34}
35
36use std::collections::{BTreeMap, BTreeSet};
37
38use subc_config::{Changeset, Digest, Generation, Plan};
39use subc_control::config::ConfigPlanView;
40
41use crate::config_store::{CommitKind, ConfigStore, HistoryEntry, StoreError, StoreState, Tuple};
42
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct GateError {
45 pub code: String,
46 pub detail: String,
47 capture_race: bool,
48}
49type Result<T> = std::result::Result<T, GateError>;
50
51impl GateError {
52 pub fn new(code: &str, detail: impl ToString) -> Self {
53 Self {
54 code: code.into(),
55 detail: detail.to_string(),
56 capture_race: false,
57 }
58 }
59 fn invalid(detail: impl ToString) -> Self {
60 Self::new("value_invalid", detail)
61 }
62 fn stale() -> Self {
63 Self::new(
64 "plan_stale",
65 "reviewed inputs or generation changed; plan again",
66 )
67 }
68
69 pub(crate) fn capture_race() -> Self {
72 Self {
73 capture_race: true,
74 ..Self::stale()
75 }
76 }
77
78 pub(crate) fn is_capture_race(&self) -> bool {
79 self.capture_race
80 }
81
82 pub(crate) fn commit_timeout() -> Self {
83 Self::new("config_commit_timeout", "the post-answer commit window expired before durable publication; plan remains unapproved")
84 }
85}
86impl std::fmt::Display for GateError {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 write!(f, "{}: {}", self.code, self.detail)
89 }
90}
91impl std::error::Error for GateError {}
92impl From<StoreError> for GateError {
93 fn from(error: StoreError) -> Self {
94 use crate::config_store::StoreErrorCode as Code;
95 let code = match error.code {
96 Code::StoreUnverified => "store_unverified",
97 Code::StoreMissing => "store_missing",
98 Code::StoreTampered => "store_tampered",
99 Code::StoreTooLarge => "store_too_large",
100 Code::AnchorPending => "anchor_pending",
101 Code::GenerationPruned => "generation_pruned",
102 Code::GenerationMissing => "generation_missing",
103 Code::RevisionExhausted => "revision_exhausted",
104 Code::InvalidState => "config_gated",
105 Code::Io => "config_store_io",
106 };
107 Self::new(code, error.detail)
108 }
109}
110
111pub trait ReviewAdmission: Send + Sync {
114 fn check(&self, registration: &crate::registry::ModuleRegistration) -> Result<()>;
115}
116
117pub(crate) struct MissingReviewAdmission;
118impl ReviewAdmission for MissingReviewAdmission {
119 fn check(&self, registration: &crate::registry::ModuleRegistration) -> Result<()> {
120 Err(GateError::new(
121 "program_admission_unavailable",
122 format!(
123 "{}: running program review admission is not connected",
124 registration.manifest.module_id
125 ),
126 ))
127 }
128}
129
130pub(crate) enum ReviewRecord<'a> {
133 Absent,
136 Reviewed(&'a BTreeSet<String>),
140 Copied(Option<serde_json::Value>),
143}
144
145#[derive(Clone, Copy, Debug, PartialEq, Eq)]
146pub enum PlanKind {
147 Change,
148 Stamp,
149 Unstamp,
150 Rollback(u64),
151}
152impl PlanKind {
153 fn commit_kind(self) -> CommitKind {
154 match self {
155 Self::Change => CommitKind::Approved,
156 Self::Stamp => CommitKind::Stamp,
157 Self::Unstamp => CommitKind::Unstamp,
158 Self::Rollback(_) => CommitKind::Rollback,
159 }
160 }
161}
162
163struct PendingPlan {
164 creation_sequence: u64,
165 edits: Option<runtime::edits::EditPlan>,
166 development_approval: Option<crate::program_origin::DevelopmentApproval>,
167 view: ConfigPlanView,
168 kind: PlanKind,
169 snapshot: GateSnapshot,
170 modules: BTreeSet<String>,
171 changed: BTreeSet<InputKey>,
172 callosum_entry_changed: bool,
173 recovery: bool,
174 delivery: Option<crate::config_store::DeliverySnapshot>,
175}
176
177pub struct ConfigGate {
180 incarnation: String,
181 plans: BTreeMap<Digest, PendingPlan>,
182 attempts: BTreeMap<u64, approval::Attempt>,
183 next_attempt: u64,
184 next_plan_sequence: u64,
185}
186
187impl ConfigGate {
188 fn pending_file_plan(&self, module: &str) -> Option<Digest> {
189 self.plans
190 .values()
191 .filter(|plan| plan.edits.is_none() && plan.modules.contains(module))
192 .max_by_key(|plan| plan.creation_sequence)
193 .map(|plan| plan.view.digest.clone())
194 }
195
196 pub(crate) fn plan_modules(&self, digest: &Digest) -> Result<BTreeSet<String>> {
197 self.plans
198 .get(digest)
199 .map(|plan| plan.modules.clone())
200 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))
201 }
202
203 pub(crate) fn cancel_attempt(&mut self, attempt: u64) {
204 self.attempts.remove(&attempt);
205 }
206
207 pub(crate) fn expire_plan(&mut self, digest: &Digest) -> bool {
208 self.plans.remove(digest).is_some()
209 }
210 pub fn new(incarnation: String) -> Self {
211 Self {
212 incarnation,
213 plans: BTreeMap::new(),
214 attempts: BTreeMap::new(),
215 next_attempt: 0,
216 next_plan_sequence: 0,
217 }
218 }
219
220 pub fn plan(
223 &mut self,
224 store: &mut ConfigStore,
225 kind: PlanKind,
226 candidate: GateSnapshot,
227 observed: &GateSnapshot,
228 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
229 ) -> Result<ConfigPlanView> {
230 self.plan_reviewed(
231 store,
232 kind,
233 candidate,
234 observed,
235 ReviewRecord::Absent,
236 review,
237 )
238 }
239
240 pub(crate) fn plan_reviewed(
245 &mut self,
246 store: &mut ConfigStore,
247 kind: PlanKind,
248 candidate: GateSnapshot,
249 observed: &GateSnapshot,
250 record: ReviewRecord<'_>,
251 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
252 ) -> Result<ConfigPlanView> {
253 self.plan_reviewed_inner(store, kind, candidate, observed, record, None, review)
254 }
255
256 #[allow(clippy::too_many_arguments)]
257 fn plan_reviewed_inner(
258 &mut self,
259 store: &mut ConfigStore,
260 kind: PlanKind,
261 candidate: GateSnapshot,
262 observed: &GateSnapshot,
263 record: ReviewRecord<'_>,
264 edits: Option<runtime::edits::EditPlan>,
265 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
266 ) -> Result<ConfigPlanView> {
267 let status = store.status();
268 let recovery = matches!(
269 status.state,
270 StoreState::StoreUnverified | StoreState::StoreMissing
271 );
272 if (recovery && !matches!(kind, PlanKind::Stamp | PlanKind::Unstamp))
273 || (status.state == StoreState::Unstamped && kind != PlanKind::Stamp && edits.is_none())
274 {
275 return Err(GateError::new(
276 "config_gated",
277 "stamp is required before planning changes",
278 ));
279 }
280 if self.plans.len() >= 64 {
281 return Err(GateError::new("config_busy", "too many pending plans"));
282 }
283 let mut rollback_programs = Vec::new();
284 if let PlanKind::Rollback(id) = kind {
285 let target = GateSnapshot::from_store(&store.rollback_configuration(id)?)?;
286 if target
287 .inputs
288 .iter()
289 .filter(|(key, _)| !key.is_program())
290 .ne(candidate.inputs.iter().filter(|(key, _)| !key.is_program()))
291 {
292 return Err(GateError::invalid(
293 "rollback must reverse the target configuration",
294 ));
295 }
296 for (key, now) in candidate.inputs.iter().filter(|(key, _)| key.is_program()) {
297 if target.inputs.get(key) != Some(now) {
298 rollback_programs.push(serde_json::json!({
299 "module_id":key.module(),
300 "input":key,
301 "reason":"program changed since that version",
302 "approved_then":target.inputs.get(key),
303 "on_disk_now":now,
304 }));
305 }
306 }
307 }
308 let (base_revision, base_generation, approved, active) =
309 if let Some(edit) = edits.as_ref().filter(|edit| edit.unstamped) {
310 (
311 status.base_revision,
312 0,
313 edit.baseline.clone(),
314 BTreeMap::new(),
315 )
316 } else if recovery {
317 (0, 0, GateSnapshot::default(), BTreeMap::new())
318 } else {
319 store.delivery_ready()?;
320 let body = store.body()?;
321 let active = body
322 .versions
323 .iter()
324 .filter_map(|(tuple, versions)| {
325 versions
326 .active
327 .map(|id| (serde_json::to_string(tuple).expect("tuple"), id))
328 })
329 .collect();
330 (
331 body.base_revision,
332 body.last_generation,
333 GateSnapshot::from_store(&body.approved)?,
334 active,
335 )
336 };
337 let changed: BTreeSet<InputKey> = approved
338 .changed_keys(&candidate)
339 .into_iter()
340 .cloned()
341 .collect();
342 let callosum_entry_changed = if changed.contains(&InputKey::Daemon) {
343 match (
344 approved.inputs.get(&InputKey::Daemon),
345 candidate.inputs.get(&InputKey::Daemon),
346 ) {
347 (
348 Some(CapturedInput {
349 value: subc_config::RecordedValue::Value { value: old },
350 ..
351 }),
352 Some(CapturedInput {
353 value: subc_config::RecordedValue::Value { value: new },
354 ..
355 }),
356 ) => old.pointer("/modules/callosum") != new.pointer("/modules/callosum"),
357 _ => true,
358 }
359 } else {
360 false
361 };
362 let mut modules: BTreeSet<String> = changed
363 .iter()
364 .filter_map(|key| key.module().map(str::to_owned))
365 .collect();
366 let mut changeset = review(&approved, &candidate)?;
367 for difference in &rollback_programs {
368 if let Some(module) = difference["module_id"].as_str() {
369 modules.insert(module.to_owned());
370 changeset
371 .launch_manifests
372 .entry(module.to_owned())
373 .or_insert_with(|| serde_json::json!({}))
374 .as_object_mut()
375 .ok_or_else(|| GateError::invalid("launch manifest must be an object"))?
376 .insert(
377 "program_changed_since_target".into(),
378 serde_json::Value::Bool(true),
379 );
380 }
381 }
382 modules.extend(changeset.fields.iter().map(|field| field.module_id.clone()));
383 modules.extend(changeset.launch_manifests.keys().cloned());
384 if matches!(kind, PlanKind::Stamp | PlanKind::Unstamp) {
385 modules.extend(observed.modules());
386 modules.extend(approved.modules());
387 }
388 let transitions = changeset
395 .apply_plan
396 .as_object_mut()
397 .and_then(|review| review.remove("module_transitions"));
398 if transitions.is_some()
399 && changeset
400 .apply_plan
401 .as_object()
402 .is_some_and(|review| review.is_empty())
403 {
404 changeset.apply_plan = serde_json::Value::Null;
405 }
406 changeset.apply_plan = serde_json::json!({
407 "operation": match kind { PlanKind::Change => "change", PlanKind::Stamp => "stamp", PlanKind::Unstamp => "unstamp", PlanKind::Rollback(_) => "rollback" },
408 "rollback_to": if let PlanKind::Rollback(id) = kind { Some(id) } else { None },
409 "review": changeset.apply_plan,
410 "previous": approved.to_store()?,
411 "snapshot": candidate.to_store()?,
412 });
413 if let Some(transitions) = transitions {
414 if let Some(table) = transitions.as_object() {
415 modules.extend(table.keys().cloned());
416 }
417 changeset.apply_plan["module_transitions"] = transitions;
418 }
419 if matches!(kind, PlanKind::Rollback(_)) {
420 changeset.apply_plan["rollback_programs"] = serde_json::Value::Array(rollback_programs);
421 }
422 let replaces_programs =
423 !recovery && matches!(kind, PlanKind::Change | PlanKind::Rollback(_));
424 if replaces_programs {
425 let body = store.body()?;
431 for module in &modules {
432 if reviewed_build::active(body, module)?
433 .is_some_and(|active| active != reviewed_build::identity(&candidate, module))
434 {
435 changeset
436 .launch_manifests
437 .entry(module.clone())
438 .or_insert_with(|| serde_json::json!({}))
439 .as_object_mut()
440 .ok_or_else(|| GateError::invalid("launch manifest must be an object"))?
441 .insert(
442 "program_changed_since_active".into(),
443 serde_json::Value::Bool(true),
444 );
445 }
446 }
447 }
448 let reviewed = match record {
449 ReviewRecord::Absent | ReviewRecord::Copied(None) => None,
450 ReviewRecord::Copied(Some(copied)) => {
451 changeset.apply_plan[reviewed_build::REVIEWED_PROGRAMS] = copied;
452 None
453 }
454 ReviewRecord::Reviewed(reviewed) => Some(reviewed),
455 };
456 if let Some(reviewed) = reviewed {
457 let mut record = if replaces_programs {
458 reviewed_build::recorded(store.body()?)?
459 } else {
460 BTreeMap::new()
461 };
462 let present = candidate.modules();
463 record.retain(|module, _| present.contains(module));
464 for module in reviewed {
465 let program = if replaces_programs {
470 match reviewed_build::active(store.body()?, module)? {
471 Some(active) => active,
472 None => reviewed_build::identity(&approved, module),
473 }
474 } else {
475 reviewed_build::identity(&candidate, module)
476 };
477 if let Some(previous) = record.get(module).filter(|previous| **previous != program)
478 {
479 changeset.policy_changes.push(serde_json::json!({
480 "module_id": module,
481 "path": "reviewed_program",
482 "old": previous,
483 "new": program,
484 "reason": "approved configuration re-reviewed by the module's newly approved program",
485 }));
486 }
487 record.insert(module.clone(), program);
488 }
489 changeset.apply_plan[reviewed_build::REVIEWED_PROGRAMS] = serde_json::json!(record);
490 }
491 apply::bind_plan(&mut changeset)?;
492 if let Some(edit) = &edits {
493 changeset.apply_plan["edit_plan"] = serde_json::json!({
494 "unstamped": edit.unstamped,
495 "write_back": edit.files.iter().map(runtime::edits::WriteBack::intent).collect::<Vec<_>>(),
496 });
497 if !edit.refusals.is_empty() {
498 changeset.apply_plan["edit_refusals"] = serde_json::json!(edit.refusals);
501 }
502 }
503 let mut plan = Plan::new(
504 base_revision,
505 base_generation,
506 &self.incarnation,
507 observed.read_set(&modules)?,
508 changeset,
509 );
510 plan.active_generations = active;
511 let mut view = ConfigPlanView::new(plan).map_err(GateError::invalid)?;
512 if let Some(edit) = &edits {
513 view.refusals = edit.refusals.clone();
514 }
515 self.next_plan_sequence = self
516 .next_plan_sequence
517 .checked_add(1)
518 .ok_or_else(|| GateError::new("config_busy", "plan creation sequence exhausted"))?;
519 self.plans.insert(
520 view.digest.clone(),
521 PendingPlan {
522 creation_sequence: self.next_plan_sequence,
523 edits,
524 development_approval: None,
525 view: view.clone(),
526 kind,
527 snapshot: candidate,
528 modules,
529 changed,
530 callosum_entry_changed,
531 recovery,
532 delivery: None,
533 },
534 );
535 Ok(view)
536 }
537
538 fn plan_program_keys(&self, digest: &Digest) -> Result<Vec<InputKey>> {
539 let plan = self
540 .plans
541 .get(digest)
542 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
543 Ok(plan
544 .snapshot
545 .inputs
546 .keys()
547 .filter(|key| {
548 key.is_program()
549 && key
550 .module()
551 .is_some_and(|module| plan.modules.contains(module))
552 })
553 .cloned()
554 .collect())
555 }
556
557 pub(crate) fn bind_delivery(
561 &mut self,
562 digest: &Digest,
563 delivery: crate::config_store::DeliverySnapshot,
564 ) -> Result<()> {
565 self.plans
566 .get_mut(digest)
567 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?
568 .delivery = Some(delivery);
569 Ok(())
570 }
571
572 pub fn rollback(
578 &mut self,
579 store: &mut ConfigStore,
580 generation: u64,
581 observed: &GateSnapshot,
582 current_programs: &GateSnapshot,
583 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
584 ) -> Result<ConfigPlanView> {
585 let mut target = GateSnapshot::from_store(&store.rollback_configuration(generation)?)?;
586 target.restore_programs_from(current_programs)?;
587 let copied = store
588 .body()?
589 .generations
590 .get(&generation)
591 .and_then(|entry| {
592 entry
593 .generation
594 .changeset
595 .apply_plan
596 .get(reviewed_build::REVIEWED_PROGRAMS)
597 })
598 .cloned();
599 self.plan_reviewed(
600 store,
601 PlanKind::Rollback(generation),
602 target,
603 observed,
604 ReviewRecord::Copied(copied),
605 review,
606 )
607 }
608
609 fn fresh(plan: &PendingPlan, store: &mut ConfigStore, current: &GateSnapshot) -> Result<()> {
610 let status = store.status();
611 let recovery = matches!(
612 status.state,
613 StoreState::StoreUnverified | StoreState::StoreMissing
614 );
615 if recovery != plan.recovery {
616 return Err(GateError::stale());
617 }
618 let base = if recovery {
619 0
620 } else {
621 store.delivery_ready()?;
622 store.body()?.base_revision
623 };
624 plan.view
625 .plan
626 .check_fresh(base, ¤t.read_set(&plan.modules)?)
627 .map_err(|_| GateError::stale())
628 }
629
630 #[allow(clippy::too_many_arguments)]
631 fn commit(
632 &mut self,
633 digest: &Digest,
634 approval_channel: subc_config::ApprovalChannel,
635 store: &mut ConfigStore,
636 current: &GateSnapshot,
637 now_ms: u64,
638 before_publication: impl FnOnce() -> Result<()>,
639 ) -> Result<u64> {
640 let plan = self
641 .plans
642 .get(digest)
643 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
644 Self::fresh(plan, store, current)?;
645 let mut generation = Generation::new(
646 0,
647 approval_channel,
648 digest.clone(),
649 plan.view.plan.input_vector.clone(),
650 plan.view.plan.changeset.clone(),
651 );
652 let declarations_only = plan.development_approval.is_some();
653 generation.active_generations = plan.view.plan.active_generations.clone();
654 for module in plan.modules.iter().filter(|_| !declarations_only) {
655 generation
656 .module_states
657 .insert(module.clone(), subc_config::GenerationState::Pending);
658 if let Some(CapturedInput {
659 state: subc_config::InputState::Present { digest },
660 ..
661 }) = plan
662 .snapshot
663 .inputs
664 .get(&InputKey::Declaration(module.clone()))
665 {
666 generation
667 .declaration_digests
668 .insert(module.clone(), digest.clone());
669 }
670 }
671 let mut tuples: BTreeSet<Tuple> = plan
672 .modules
673 .iter()
674 .map(|module| Tuple {
675 module: module.clone(),
676 project: None,
677 })
678 .chain(plan.view.plan.changeset.fields.iter().map(|field| Tuple {
679 module: field.module_id.clone(),
680 project: field.project_id.clone(),
681 }))
682 .chain(plan.modules.iter().flat_map(|module| {
683 plan.view
684 .plan
685 .changeset
686 .affected_projects
687 .iter()
688 .map(move |project| Tuple {
689 module: module.clone(),
690 project: Some(project.clone()),
691 })
692 }))
693 .collect();
694 if declarations_only {
695 tuples.clear();
696 }
697 let snapshot = plan.snapshot.to_store()?;
698 let entry = HistoryEntry {
699 generation,
700 kind: if declarations_only {
701 CommitKind::DeclarationApproval
702 } else {
703 plan.kind.commit_kind()
704 },
705 approval_id: digest.to_string(),
706 outcome: "approved".into(),
707 tuples,
708 configuration: snapshot.clone(),
709 delivery: plan.delivery.clone(),
710 };
711 let base_before = store.status().base_revision;
712 let observed = current.to_store()?;
713 before_publication()?;
714 let result = if plan.recovery {
715 store.recovery_exit(entry, snapshot, now_ms)
716 } else {
717 store.commit_generation(entry, snapshot, observed, now_ms)
718 };
719 if result.is_ok() || store.status().base_revision != base_before {
723 self.plans.remove(digest);
724 }
725 let id = result?;
726 store.delivery_ready()?;
727 Ok(id)
728 }
729}
730
731mod registration;
732#[cfg(test)]
733mod tests;