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