Skip to main content

subc_daemon/config_gate/
mod.rs

1//! Immutable config planning and approval, independent of transport dispatch.
2//!
3//! The daemon owner captures files, validates schemas/bounds and runs module
4//! review before handing snapshots here. It serializes this engine with the
5//! store and supervisor commit locks, recaptures files at completion, and uses
6//! only the committed snapshot for delivery. No client text is approval input.
7
8mod 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;
21pub(crate) mod targets;
22
23pub use approval::*;
24pub use snapshot::{CapturedInput, GateSnapshot, InputKey};
25
26/// The settings edit base advances only when a retained generation names the module.
27pub(crate) fn module_base_generation(body: &crate::config_store::StoreBody, module: &str) -> u64 {
28    if !body.stamped {
29        return 0;
30    }
31    body.generations
32        .values()
33        .rev()
34        .find(|entry| entry.tuples.iter().any(|tuple| tuple.module == module))
35        .map_or(0, |entry| entry.generation.id)
36}
37
38use std::collections::{BTreeMap, BTreeSet};
39
40use subc_config::{Changeset, Digest, Generation, Plan};
41use subc_control::config::ConfigPlanView;
42
43use crate::config_store::{CommitKind, ConfigStore, HistoryEntry, StoreError, StoreState, Tuple};
44
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct GateError {
47    pub code: String,
48    pub detail: String,
49    capture_race: bool,
50}
51type Result<T> = std::result::Result<T, GateError>;
52
53impl GateError {
54    pub fn new(code: &str, detail: impl ToString) -> Self {
55        Self {
56            code: code.into(),
57            detail: detail.to_string(),
58            capture_race: false,
59        }
60    }
61    fn invalid(detail: impl ToString) -> Self {
62        Self::new("value_invalid", detail)
63    }
64    fn stale() -> Self {
65        Self::new(
66            "plan_stale",
67            "reviewed inputs or generation changed; plan again",
68        )
69    }
70
71    // Observational retries must not also retry stale review or plan decisions
72    // just because those refusals use the same wire code and message.
73    pub(crate) fn capture_race() -> Self {
74        Self {
75            capture_race: true,
76            ..Self::stale()
77        }
78    }
79
80    pub(crate) fn is_capture_race(&self) -> bool {
81        self.capture_race
82    }
83
84    pub(crate) fn commit_timeout() -> Self {
85        Self::new("config_commit_timeout", "the post-answer commit window expired before durable publication; plan remains unapproved")
86    }
87}
88impl std::fmt::Display for GateError {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        write!(f, "{}: {}", self.code, self.detail)
91    }
92}
93impl std::error::Error for GateError {}
94impl From<StoreError> for GateError {
95    fn from(error: StoreError) -> Self {
96        use crate::config_store::StoreErrorCode as Code;
97        let code = match error.code {
98            Code::StoreUnverified => "store_unverified",
99            Code::StoreMissing => "store_missing",
100            Code::StoreTampered => "store_tampered",
101            Code::StoreTooLarge => "store_too_large",
102            Code::AnchorPending => "anchor_pending",
103            Code::GenerationPruned => "generation_pruned",
104            Code::GenerationMissing => "generation_missing",
105            Code::RevisionExhausted => "revision_exhausted",
106            Code::InvalidState => "config_gated",
107            Code::Io => "config_store_io",
108        };
109        Self::new(code, error.detail)
110    }
111}
112
113/// The supervisor's program-admission adapter supplies this authority. A module
114/// registration and a schema declaration alone never admit its running code.
115pub trait ReviewAdmission: Send + Sync {
116    fn check(&self, registration: &crate::registry::ModuleRegistration) -> Result<()>;
117}
118
119pub(crate) struct MissingReviewAdmission;
120impl ReviewAdmission for MissingReviewAdmission {
121    fn check(&self, registration: &crate::registry::ModuleRegistration) -> Result<()> {
122        Err(GateError::new(
123            "program_admission_unavailable",
124            format!(
125                "{}: running program review admission is not connected",
126                registration.manifest.module_id
127            ),
128        ))
129    }
130}
131
132/// Which build each module's approved configuration was reviewed by, as a
133/// plan writes it into its generation.
134pub(crate) enum ReviewRecord<'a> {
135    /// Write no record. Later plans then treat every module this plan approves
136    /// as owing a re-review.
137    Absent,
138    /// These modules' admitted reviewers answered `config.review` for this
139    /// plan. Their builds are recorded; other modules keep their entries from
140    /// the newest approved generation.
141    Reviewed(&'a BTreeSet<String>),
142    /// Copy a record verbatim, for a rollback to a generation whose reviewers
143    /// are known. `None` (that generation had no record) writes none.
144    Copied(Option<serde_json::Value>),
145}
146
147#[derive(Clone, Copy, Debug, PartialEq, Eq)]
148pub enum PlanKind {
149    Change,
150    Stamp,
151    Unstamp,
152    Rollback(u64),
153}
154impl PlanKind {
155    fn commit_kind(self) -> CommitKind {
156        match self {
157            Self::Change => CommitKind::Approved,
158            Self::Stamp => CommitKind::Stamp,
159            Self::Unstamp => CommitKind::Unstamp,
160            Self::Rollback(_) => CommitKind::Rollback,
161        }
162    }
163}
164
165struct PendingPlan {
166    creation_sequence: u64,
167    edits: Option<runtime::edits::EditPlan>,
168    development_approval: Option<crate::program_origin::DevelopmentApproval>,
169    view: ConfigPlanView,
170    kind: PlanKind,
171    snapshot: GateSnapshot,
172    modules: BTreeSet<String>,
173    changed: BTreeSet<InputKey>,
174    callosum_entry_changed: bool,
175    recovery: bool,
176    delivery: Option<crate::config_store::DeliverySnapshot>,
177    project_files: Vec<crate::config_store::ProjectFileApproval>,
178}
179
180impl PendingPlan {
181    fn targets(&self) -> Result<BTreeSet<Tuple>> {
182        let targets = targets::checked(&self.view.plan)?;
183        // Approving more provider declarations for a development build does
184        // not start config delivery. The module read set still detects changes
185        // while the operator reviews those declarations.
186        Ok(if self.development_approval.is_some() {
187            BTreeSet::new()
188        } else {
189            targets
190        })
191    }
192}
193
194/// Memory-only plans cannot be replayed across a daemon restart. A successful
195/// generation commit changes the base revision and consumes its approval once.
196pub struct ConfigGate {
197    incarnation: String,
198    plans: BTreeMap<Digest, PendingPlan>,
199    attempts: BTreeMap<u64, approval::Attempt>,
200    next_attempt: u64,
201    next_plan_sequence: u64,
202}
203
204impl ConfigGate {
205    fn pending_file_plan(&self, module: &str) -> Option<Digest> {
206        self.plans
207            .values()
208            .filter(|plan| plan.edits.is_none() && plan.modules.contains(module))
209            .max_by_key(|plan| plan.creation_sequence)
210            .map(|plan| plan.view.digest.clone())
211    }
212
213    pub(crate) fn plan_modules(&self, digest: &Digest) -> Result<BTreeSet<String>> {
214        self.plans
215            .get(digest)
216            .map(|plan| plan.modules.clone())
217            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))
218    }
219
220    pub(crate) fn cancel_attempt(&mut self, attempt: u64) {
221        self.attempts.remove(&attempt);
222    }
223
224    pub(crate) fn expire_plan(&mut self, digest: &Digest) -> bool {
225        self.plans.remove(digest).is_some()
226    }
227    pub fn new(incarnation: String) -> Self {
228        Self {
229            incarnation,
230            plans: BTreeMap::new(),
231            attempts: BTreeMap::new(),
232            next_attempt: 0,
233            next_plan_sequence: 0,
234        }
235    }
236
237    /// `review` enforces the approved schema and every affected project's bounds
238    /// before asking admitted module reviewers. Refusals produce no plan.
239    pub fn plan(
240        &mut self,
241        store: &mut ConfigStore,
242        kind: PlanKind,
243        candidate: GateSnapshot,
244        observed: &GateSnapshot,
245        review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
246    ) -> Result<ConfigPlanView> {
247        self.plan_reviewed(
248            store,
249            kind,
250            candidate,
251            observed,
252            ReviewRecord::Absent,
253            review,
254        )
255    }
256
257    /// As [`Self::plan`], also writing the record of which build each module's
258    /// approved configuration was reviewed by. A generation planned without that
259    /// record vouches for no review, so later plans treat each module it
260    /// approved as needing re-review.
261    pub(crate) fn plan_reviewed(
262        &mut self,
263        store: &mut ConfigStore,
264        kind: PlanKind,
265        candidate: GateSnapshot,
266        observed: &GateSnapshot,
267        record: ReviewRecord<'_>,
268        review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
269    ) -> Result<ConfigPlanView> {
270        self.plan_reviewed_inner(store, kind, candidate, observed, record, None, None, review)
271    }
272
273    #[allow(clippy::too_many_arguments)]
274    fn plan_reviewed_inner(
275        &mut self,
276        store: &mut ConfigStore,
277        kind: PlanKind,
278        candidate: GateSnapshot,
279        observed: &GateSnapshot,
280        record: ReviewRecord<'_>,
281        edits: Option<runtime::edits::EditPlan>,
282        projects: Option<targets::ProjectReviews>,
283        review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
284    ) -> Result<ConfigPlanView> {
285        let status = store.status();
286        let recovery = matches!(
287            status.state,
288            StoreState::StoreUnverified | StoreState::StoreMissing
289        );
290        if (recovery && !matches!(kind, PlanKind::Stamp | PlanKind::Unstamp))
291            || (status.state == StoreState::Unstamped && kind != PlanKind::Stamp && edits.is_none())
292        {
293            return Err(GateError::new(
294                "config_gated",
295                "stamp is required before planning changes",
296            ));
297        }
298        if self.plans.len() >= 64 {
299            return Err(GateError::new("config_busy", "too many pending plans"));
300        }
301        let mut rollback_programs = Vec::new();
302        if let PlanKind::Rollback(id) = kind {
303            let target = GateSnapshot::from_store(&store.rollback_configuration(id)?)?;
304            if target
305                .inputs
306                .iter()
307                .filter(|(key, _)| !key.is_program())
308                .ne(candidate.inputs.iter().filter(|(key, _)| !key.is_program()))
309            {
310                return Err(GateError::invalid(
311                    "rollback must reverse the target configuration",
312                ));
313            }
314            for (key, now) in candidate.inputs.iter().filter(|(key, _)| key.is_program()) {
315                if target.inputs.get(key) != Some(now) {
316                    rollback_programs.push(serde_json::json!({
317                        "module_id":key.module(),
318                        "input":key,
319                        "reason":"program changed since that version",
320                        "approved_then":target.inputs.get(key),
321                        "on_disk_now":now,
322                    }));
323                }
324            }
325        }
326        let (base_revision, base_generation, approved, active) =
327            if let Some(edit) = edits.as_ref().filter(|edit| edit.unstamped) {
328                (
329                    status.base_revision,
330                    0,
331                    edit.baseline.clone(),
332                    BTreeMap::new(),
333                )
334            } else if recovery {
335                (0, 0, GateSnapshot::default(), BTreeMap::new())
336            } else {
337                store.delivery_ready()?;
338                let body = store.body()?;
339                let active = body
340                    .versions
341                    .iter()
342                    .filter_map(|(tuple, versions)| {
343                        versions
344                            .active
345                            .map(|id| (serde_json::to_string(tuple).expect("tuple"), id))
346                    })
347                    .collect();
348                (
349                    body.base_revision,
350                    body.last_generation,
351                    GateSnapshot::from_store(&body.approved)?,
352                    active,
353                )
354            };
355        let changed: BTreeSet<InputKey> = approved
356            .changed_keys(&candidate)
357            .into_iter()
358            .cloned()
359            .collect();
360        let callosum_entry_changed = if changed.contains(&InputKey::Daemon) {
361            match (
362                approved.inputs.get(&InputKey::Daemon),
363                candidate.inputs.get(&InputKey::Daemon),
364            ) {
365                (
366                    Some(CapturedInput {
367                        value: subc_config::RecordedValue::Value { value: old },
368                        ..
369                    }),
370                    Some(CapturedInput {
371                        value: subc_config::RecordedValue::Value { value: new },
372                        ..
373                    }),
374                ) => old.pointer("/modules/callosum") != new.pointer("/modules/callosum"),
375                _ => true,
376            }
377        } else {
378            false
379        };
380        let mut user_modules: BTreeSet<String> = changed
381            .iter()
382            .filter(|key| !matches!(key, InputKey::ProjectTuple { .. }))
383            .filter_map(|key| key.module().map(str::to_owned))
384            .collect();
385        let mut changeset = review(&approved, &candidate)?;
386        for difference in &rollback_programs {
387            if let Some(module) = difference["module_id"].as_str() {
388                user_modules.insert(module.to_owned());
389                changeset
390                    .launch_manifests
391                    .entry(module.to_owned())
392                    .or_insert_with(|| serde_json::json!({}))
393                    .as_object_mut()
394                    .ok_or_else(|| GateError::invalid("launch manifest must be an object"))?
395                    .insert(
396                        "program_changed_since_target".into(),
397                        serde_json::Value::Bool(true),
398                    );
399            }
400        }
401        user_modules.extend(
402            changeset
403                .fields
404                .iter()
405                .filter(|field| field.project_id.is_none())
406                .map(|field| field.module_id.clone()),
407        );
408        user_modules.extend(changeset.launch_manifests.keys().cloned());
409        if matches!(kind, PlanKind::Stamp | PlanKind::Unstamp) {
410            user_modules.extend(
411                observed
412                    .inputs
413                    .keys()
414                    .chain(approved.inputs.keys())
415                    .filter(|key| !matches!(key, InputKey::ProjectTuple { .. }))
416                    .filter_map(|key| key.module().map(str::to_owned)),
417            );
418        }
419        // Bind the full retained view and operation, including identity-only and
420        // declaration-only changes a module's scalar diff would not describe.
421        // Keep activation policy out of reviewer metadata. `small_prompt` in
422        // approval.rs offers the compact one-change prompt only when `review`
423        // is null, so leaving the transition table in it would deny that
424        // prompt to every one-field change.
425        let transitions = changeset
426            .apply_plan
427            .as_object_mut()
428            .and_then(|review| review.remove("module_transitions"));
429        if transitions.is_some()
430            && changeset
431                .apply_plan
432                .as_object()
433                .is_some_and(|review| review.is_empty())
434        {
435            changeset.apply_plan = serde_json::Value::Null;
436        }
437        changeset.apply_plan = serde_json::json!({
438            "operation": match kind { PlanKind::Change => "change", PlanKind::Stamp => "stamp", PlanKind::Unstamp => "unstamp", PlanKind::Rollback(_) => "rollback" },
439            "rollback_to": if let PlanKind::Rollback(id) = kind { Some(id) } else { None },
440            "review": changeset.apply_plan,
441            "previous": approved.to_store()?,
442            "snapshot": candidate.to_store()?,
443        });
444        if let Some(mut transitions) = transitions {
445            if let Some(table) = transitions.as_object_mut() {
446                if projects.is_some() {
447                    table.retain(|module, _| user_modules.contains(module));
448                } else {
449                    user_modules.extend(table.keys().cloned());
450                }
451            }
452            changeset.apply_plan["module_transitions"] = transitions;
453        }
454        if matches!(kind, PlanKind::Rollback(_)) {
455            changeset.apply_plan["rollback_programs"] = serde_json::Value::Array(rollback_programs);
456        }
457        let replaces_programs =
458            !recovery && matches!(kind, PlanKind::Change | PlanKind::Rollback(_));
459        if replaces_programs {
460            // A module whose active generation ran an older program than this
461            // plan's (an earlier program change not yet active, say) still has
462            // that older process running. It must not acknowledge this
463            // generation either, even though the program matches the last
464            // approval.
465            let body = store.body()?;
466            for module in &user_modules {
467                if reviewed_build::active(body, module)?
468                    .is_some_and(|active| active != reviewed_build::identity(&candidate, module))
469                {
470                    changeset
471                        .launch_manifests
472                        .entry(module.clone())
473                        .or_insert_with(|| serde_json::json!({}))
474                        .as_object_mut()
475                        .ok_or_else(|| GateError::invalid("launch manifest must be an object"))?
476                        .insert(
477                            "program_changed_since_active".into(),
478                            serde_json::Value::Bool(true),
479                        );
480                }
481            }
482        }
483        let reviewed = match record {
484            ReviewRecord::Absent | ReviewRecord::Copied(None) => None,
485            ReviewRecord::Copied(Some(copied)) => {
486                changeset.apply_plan[reviewed_build::REVIEWED_PROGRAMS] = copied;
487                None
488            }
489            ReviewRecord::Reviewed(reviewed) => Some(reviewed),
490        };
491        if let Some(reviewed) = reviewed {
492            let mut record = if replaces_programs {
493                reviewed_build::recorded(store.body()?)?
494            } else {
495                BTreeMap::new()
496            };
497            let present = candidate.modules();
498            record.retain(|module, _| present.contains(module));
499            for module in reviewed {
500                // A stamp records the programs already running. Otherwise the
501                // reviewer is the process that acknowledged the active
502                // generation, or one admitted from the last approval when the
503                // module has never acknowledged one.
504                let program = if replaces_programs {
505                    match reviewed_build::active(store.body()?, module)? {
506                        Some(active) => active,
507                        None => reviewed_build::identity(&approved, module),
508                    }
509                } else {
510                    reviewed_build::identity(&candidate, module)
511                };
512                if let Some(previous) = record.get(module).filter(|previous| **previous != program)
513                {
514                    if projects.is_some() {
515                        user_modules.insert(module.clone());
516                    }
517                    changeset.policy_changes.push(serde_json::json!({
518                        "module_id": module,
519                        "path": "reviewed_program",
520                        "old": previous,
521                        "new": program,
522                        "reason": "approved configuration re-reviewed by the module's newly approved program",
523                    }));
524                }
525                record.insert(module.clone(), program);
526            }
527            changeset.apply_plan[reviewed_build::REVIEWED_PROGRAMS] = serde_json::json!(record);
528        }
529        apply::bind_plan(&mut changeset)?;
530        if let Some(edit) = &edits {
531            changeset.apply_plan["edit_plan"] = serde_json::json!({
532                "unstamped": edit.unstamped,
533                "write_back": edit.files.iter().map(runtime::edits::WriteBack::intent).collect::<Vec<_>>(),
534            });
535            if !edit.refusals.is_empty() {
536                // Keep refusals bound to the plan digest so apply can reject it;
537                // settings clients read the keyed rows from view.refusals.
538                changeset.apply_plan["edit_refusals"] = serde_json::json!(edit.refusals);
539            }
540        }
541        let mut modules = user_modules.clone();
542        modules.extend(changed.iter().filter_map(|key| match key {
543            InputKey::ProjectTuple { module, .. } => Some(module.clone()),
544            _ => None,
545        }));
546        if let Some(projects) = &projects {
547            modules.extend(projects.tuples.keys().map(|tuple| tuple.module.clone()));
548        }
549        let inputs = observed.read_set(&modules)?;
550        let (delivery, project_files) = if let Some(projects) = projects {
551            let body = if recovery { None } else { Some(store.body()?) };
552            let (delivery, files) = projects.bind(body, &inputs, &mut changeset, &user_modules)?;
553            if recovery && !files.is_empty() {
554                return Err(GateError::new(
555                    "apply_plan_invalid",
556                    "recovery cannot approve project file write-back",
557                ));
558            }
559            (Some(delivery), files)
560        } else {
561            (None, Vec::new())
562        };
563        let mut plan = Plan::new(
564            base_revision,
565            base_generation,
566            &self.incarnation,
567            inputs,
568            changeset,
569        );
570        plan.active_generations = active;
571        targets::checked(&plan)?;
572        let mut view = ConfigPlanView::new(plan).map_err(GateError::invalid)?;
573        if let Some(edit) = &edits {
574            view.refusals = edit.refusals.clone();
575        }
576        self.next_plan_sequence = self
577            .next_plan_sequence
578            .checked_add(1)
579            .ok_or_else(|| GateError::new("config_busy", "plan creation sequence exhausted"))?;
580        self.plans.insert(
581            view.digest.clone(),
582            PendingPlan {
583                creation_sequence: self.next_plan_sequence,
584                edits,
585                development_approval: None,
586                view: view.clone(),
587                kind,
588                snapshot: candidate,
589                modules,
590                changed,
591                callosum_entry_changed,
592                recovery,
593                delivery,
594                project_files,
595            },
596        );
597        Ok(view)
598    }
599
600    fn plan_program_keys(&self, digest: &Digest) -> Result<Vec<InputKey>> {
601        let plan = self
602            .plans
603            .get(digest)
604            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
605        Ok(plan
606            .snapshot
607            .inputs
608            .keys()
609            .filter(|key| {
610                key.is_program()
611                    && key
612                        .module()
613                        .is_some_and(|module| plan.modules.contains(module))
614            })
615            .cloned()
616            .collect())
617    }
618
619    /// Attach daemon-reviewed raw inputs without exposing them in diagnostic
620    /// plans. The saved file identities and byte digests still bind the bytes
621    /// captured for review.
622    pub(crate) fn bind_delivery(
623        &mut self,
624        digest: &Digest,
625        mut delivery: crate::config_store::DeliverySnapshot,
626    ) -> Result<()> {
627        let plan = self
628            .plans
629            .get_mut(digest)
630            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
631        if let Some(projects) = &plan.delivery {
632            for (module, declaration) in &projects.declarations {
633                if delivery
634                    .declarations
635                    .get(module)
636                    .is_some_and(|user| user != declaration)
637                {
638                    return Err(GateError::new(
639                        "apply_plan_invalid",
640                        "user and project views name different declarations of the same module",
641                    ));
642                }
643                delivery
644                    .declarations
645                    .insert(module.clone(), declaration.clone());
646            }
647            delivery.project_views.clone_from(&projects.project_views);
648            delivery
649                .project_cutoffs
650                .clone_from(&projects.project_cutoffs);
651            delivery
652                .project_approval_digests
653                .clone_from(&projects.project_approval_digests);
654        }
655        plan.delivery = Some(delivery);
656        Ok(())
657    }
658
659    /// Capture program identities for the reverse configuration's launch specs
660    /// at the restored paths at plan time. No executable bytes or historical
661    /// identities are restored. The restored generation's reviewed-program
662    /// record is copied: its reviewers are known. If that generation has no
663    /// record, the rollback has none either, so its modules owe re-review.
664    pub fn rollback(
665        &mut self,
666        store: &mut ConfigStore,
667        generation: u64,
668        observed: &GateSnapshot,
669        current_programs: &GateSnapshot,
670        review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
671    ) -> Result<ConfigPlanView> {
672        let mut target = GateSnapshot::from_store(&store.rollback_configuration(generation)?)?;
673        target.restore_programs_from(current_programs)?;
674        let copied = store
675            .body()?
676            .generations
677            .get(&generation)
678            .and_then(|entry| {
679                entry
680                    .generation
681                    .changeset
682                    .apply_plan
683                    .get(reviewed_build::REVIEWED_PROGRAMS)
684            })
685            .cloned();
686        self.plan_reviewed(
687            store,
688            PlanKind::Rollback(generation),
689            target,
690            observed,
691            ReviewRecord::Copied(copied),
692            review,
693        )
694    }
695
696    fn fresh(plan: &PendingPlan, store: &mut ConfigStore, current: &GateSnapshot) -> Result<()> {
697        plan.targets()?;
698        let status = store.status();
699        let recovery = matches!(
700            status.state,
701            StoreState::StoreUnverified | StoreState::StoreMissing
702        );
703        if recovery != plan.recovery {
704            return Err(GateError::stale());
705        }
706        let base = if recovery {
707            0
708        } else {
709            store.delivery_ready()?;
710            store.body()?.base_revision
711        };
712        plan.view
713            .plan
714            .check_fresh(base, &current.read_set(&plan.modules)?)
715            .map_err(|_| GateError::stale())
716    }
717
718    #[allow(clippy::too_many_arguments)]
719    fn commit(
720        &mut self,
721        digest: &Digest,
722        approval_channel: subc_config::ApprovalChannel,
723        store: &mut ConfigStore,
724        current: &GateSnapshot,
725        now_ms: u64,
726        before_publication: impl FnOnce() -> Result<()>,
727    ) -> Result<u64> {
728        let plan = self
729            .plans
730            .get(digest)
731            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
732        Self::fresh(plan, store, current)?;
733        let mut generation = Generation::new(
734            0,
735            approval_channel,
736            digest.clone(),
737            plan.view.plan.input_vector.clone(),
738            plan.view.plan.changeset.clone(),
739        );
740        let declarations_only = plan.development_approval.is_some();
741        generation.active_generations = plan.view.plan.active_generations.clone();
742        let tuples = plan.targets()?;
743        for tuple in &tuples {
744            let module = &tuple.module;
745            if tuple.project.is_none() {
746                generation
747                    .module_states
748                    .insert(module.clone(), subc_config::GenerationState::Pending);
749            }
750            if let Some(CapturedInput {
751                state: subc_config::InputState::Present { digest },
752                ..
753            }) = plan
754                .snapshot
755                .inputs
756                .get(&InputKey::Declaration(module.clone()))
757            {
758                generation
759                    .declaration_digests
760                    .insert(module.clone(), digest.clone());
761            }
762        }
763        let snapshot = plan.snapshot.to_store()?;
764        let entry = HistoryEntry {
765            generation,
766            kind: if declarations_only {
767                CommitKind::DeclarationApproval
768            } else {
769                plan.kind.commit_kind()
770            },
771            approval_id: digest.to_string(),
772            outcome: "approved".into(),
773            tuples,
774            project_outcomes: BTreeMap::new(),
775            configuration: snapshot.clone(),
776            delivery: plan.delivery.clone(),
777        };
778        let base_before = store.status().base_revision;
779        let observed = current.to_store()?;
780        before_publication()?;
781        let result = if plan.recovery {
782            store.recovery_exit(entry, snapshot, now_ms)
783        } else {
784            store.commit_generation_with_project_files(
785                entry,
786                snapshot,
787                observed,
788                plan.project_files.clone(),
789                now_ms,
790            )
791        };
792        // The sealed store's external revision/digest anchor may fail to update
793        // after a durable commit. The committed base makes the old plan stale;
794        // never repeat that generation while retrying the anchor update.
795        if result.is_ok() || store.status().base_revision != base_before {
796            self.plans.remove(digest);
797        }
798        let id = result?;
799        store.delivery_ready()?;
800        Ok(id)
801    }
802}
803
804mod registration;
805#[cfg(test)]
806mod tests;