Skip to main content

release_kit/commands/
reconcile.rs

1//! `rk reconcile`: the plan computed, stored, shown, and applied.
2//!
3//! `plan` observes the target, reads the embedded bundle, computes the
4//! plan, stores it under the state root, and prints it; it writes
5//! nothing into the target. `--to` with a version this binary does not
6//! carry reads the crates venue and says so. `--observe forge` opts into
7//! the one forge read. `show` renders a stored plan. `apply` executes
8//! one: it computes the same plan again over the same request, refuses
9//! on any difference in the fingerprint, writes through one staged
10//! transaction, runs the postconditions, and journals the run.
11
12use std::collections::BTreeMap;
13
14use camino::Utf8Path;
15use serde::Serialize;
16
17use crate::cli::reconcile::{
18    ApplyArgs, ListArgs, Observe, PlanArgs, ReconcileAction, ReconcileArgs, ShowArgs,
19};
20use crate::diagnostic::{Diagnostic, Reason};
21use crate::error::RkError;
22use crate::landing::manifest;
23use crate::output::Output;
24use crate::plan::apply::{self, Applied};
25use crate::plan::gather::{self, Flags, RecordRead, Request};
26use crate::plan::planner::{self, Baseline, Candidate};
27use crate::plan::store;
28use crate::plan::{
29    Classification, Intent, Operation, Plan, PlanRequest, Planned, Readiness, ResolvedRelease,
30    Verification,
31};
32use crate::release::declared;
33use crate::release::{CrateReleaseSource, EmbeddedReleaseSource, ReleaseSource};
34use crate::setup::journal::Journal;
35
36/// Dispatch one reconcile action.
37///
38/// # Errors
39///
40/// The planner's, the store's, and the apply's own failures.
41pub fn run(args: &ReconcileArgs) -> Result<(), RkError> {
42    match &args.action {
43        ReconcileAction::Plan(plan_args) => plan(plan_args),
44        ReconcileAction::Show(show_args) => show(show_args),
45        ReconcileAction::Apply(apply_args) => apply_stored(apply_args),
46        ReconcileAction::List(list_args) => list(list_args),
47    }
48}
49
50/// Compute, store, and print one plan.
51fn plan(args: &PlanArgs) -> Result<(), RkError> {
52    let out = Output::new(args.json);
53    let decisions = parse_decisions(&args.decide)?;
54    let nix = match args.nix.as_deref() {
55        None => None,
56        Some("on") => Some(true),
57        Some("off") => Some(false),
58        Some(other) => {
59            return Err(RkError::Usage(format!(
60                "unknown --nix value '{other}'; the values are: on, off"
61            )));
62        }
63    };
64    let request = PlanRequest {
65        target: args.target.clone(),
66        intent: Intent::Reconcile,
67        selector: args.to.clone(),
68        fetch: args.fetch,
69        observe_forge: args.observe.contains(&Observe::Forge),
70        flags: Flags {
71            tech: args.tech.clone(),
72            forge: args.forge.clone(),
73            repo: args.repo.clone(),
74            workflow: args.workflow.clone(),
75            style: args.style.clone(),
76            nix,
77        },
78        decisions,
79    }
80    .canonicalized()?;
81    let planned = compute(&request, &manifest::now())?;
82    store::persist(&planned, &request)?;
83    render(out, &planned.plan, true);
84    out.emit(&planned.plan)
85}
86
87/// Render a stored plan.
88fn show(args: &ShowArgs) -> Result<(), RkError> {
89    let out = Output::new(args.json);
90    let stored = store::load(&args.plan_id)?;
91    render(out, &stored.plan, false);
92    out.emit(&stored.plan)
93}
94
95/// Execute a stored plan.
96fn apply_stored(args: &ApplyArgs) -> Result<(), RkError> {
97    let out = Output::new(args.json);
98    let stored = store::load(&args.plan_id)?;
99    // The target is taken before it is observed, so the world the fresh
100    // plan describes is the world this apply goes on to write: another
101    // run committing between the observation and the first rename is
102    // what the lock exists to stop.
103    let _lock = crate::plan::lock::acquire(&stored.request.target)?;
104    // The same request at the same instant: a fresh landing's record
105    // carries the plan's instant, so recomputing at another one would
106    // read as the record moving when nothing did.
107    // The candidate is the release the plan froze, served from the cache:
108    // the selector was resolved once at plan time and is never resolved
109    // again.
110    let fresh = compute_frozen(
111        &stored.request,
112        &stored.plan.identity.created_at,
113        Some(&stored.plan.desired_state.release),
114    )?;
115    let journal = open_journal("reconcile apply", &stored.plan).map_err(|error| {
116        RkError::refusal(
117            Diagnostic::new(
118                Reason::JournalUnavailable,
119                format!("the run journal could not be created, and nothing was written: {error}"),
120            )
121            .expected("a writable state root for the journal")
122            .target_state("unchanged"),
123        )
124    })?;
125    let applied = apply::run_locked(
126        &stored.request.target,
127        &stored.plan,
128        &stored.blobs,
129        &fresh.plan,
130        Some(journal),
131    )?;
132    render_applied(out, &applied);
133    out.emit(&applied)?;
134    applied.failure().map_or(Ok(()), Err)
135}
136
137/// The listing of stored plans.
138#[derive(Debug, Serialize)]
139struct ListReport {
140    /// The shape version of this document.
141    schema: &'static str,
142    /// Every stored plan, oldest first.
143    plans: Vec<ListRow>,
144}
145
146/// One stored plan's row.
147#[derive(Debug, Serialize)]
148struct ListRow {
149    /// The plan id.
150    plan_id: String,
151    /// The instant it was computed.
152    created_at: String,
153}
154
155fn list(args: &ListArgs) -> Result<(), RkError> {
156    let out = Output::new(args.json);
157    let rows: Vec<ListRow> = store::list()
158        .into_iter()
159        .map(|(created_at, plan_id)| ListRow {
160            plan_id,
161            created_at,
162        })
163        .collect();
164    for row in &rows {
165        out.result_line(format!("{}  {}", row.plan_id, row.created_at));
166    }
167    if rows.is_empty() {
168        out.result_line("no plans are stored");
169    }
170    out.emit(&ListReport {
171        schema: "rk.reconcile-list/1",
172        plans: rows,
173    })
174}
175
176/// The trace a front's report carries of the plan it applied.
177#[derive(Debug, Serialize)]
178pub struct Trace {
179    /// The plan that was applied.
180    pub plan_id: String,
181    /// The fingerprint the apply revalidated against.
182    pub input_fingerprint: crate::digest::Digest,
183    /// Whether the store took the plan.
184    pub stored: bool,
185    /// The journal entry, where the journal took one.
186    #[serde(skip_serializing_if = "Option::is_none")]
187    pub run_id: Option<String>,
188}
189
190impl FrontApplied {
191    /// The trace for a front's report.
192    #[must_use]
193    pub fn trace(&self) -> Trace {
194        Trace {
195            plan_id: self.applied.plan_id.clone(),
196            input_fingerprint: self.applied.input_fingerprint.clone(),
197            stored: self.stored,
198            run_id: self.applied.run_id.clone(),
199        }
200    }
201
202    /// The human line a front prints for the plan it applied.
203    #[must_use]
204    pub fn line(&self) -> String {
205        self.applied.run_id.as_ref().map_or_else(
206            || format!("applied plan {}", self.applied.plan_id),
207            |run_id| format!("applied plan {} (run {run_id})", self.applied.plan_id),
208        )
209    }
210
211    /// The bytes an operation wrote at `path`, where one did.
212    #[must_use]
213    pub fn written<'a>(planned: &'a Planned, path: &str) -> Option<&'a [u8]> {
214        planned
215            .plan
216            .operations
217            .iter()
218            .find_map(|operation| match operation {
219                Operation::WriteFile { path: p, after, .. }
220                | Operation::SpliceBlock { path: p, after, .. }
221                    if p == path =>
222                {
223                    planned.blobs.get(after).map(Vec::as_slice)
224                }
225                _ => None,
226            })
227    }
228}
229
230/// What a front's apply came back with: the engine's report and whether
231/// the store took the plan.
232#[derive(Debug)]
233pub struct FrontApplied {
234    /// The engine's report.
235    pub applied: Applied,
236    /// Whether the plan was stored; a front is one process with no review
237    /// window, so a store that cannot be written costs the record alone.
238    pub stored: bool,
239}
240
241/// One computed plan applied in the same process, which is what the
242/// fronts do on `--apply`: the store and the journal are best effort,
243/// and the execution path is the one `rk reconcile apply` takes.
244///
245/// # Errors
246///
247/// The apply's own refusals and failures.
248pub fn apply_in_process(
249    planned: &Planned,
250    request: &PlanRequest,
251    command: &str,
252) -> Result<FrontApplied, RkError> {
253    let stored = store::persist(planned, request).is_ok();
254    let journal = open_journal(command, &planned.plan).ok();
255    let applied = apply::run(
256        &request.target,
257        &planned.plan,
258        &planned.blobs,
259        &planned.plan,
260        journal,
261    )?;
262    Ok(FrontApplied { applied, stored })
263}
264
265fn open_journal(command: &str, plan: &Plan) -> std::io::Result<Journal> {
266    let (forge, repo) = plan
267        .desired_state
268        .configuration
269        .as_ref()
270        .map_or(("", ""), |c| (c.forge.as_str(), c.repo.as_str()));
271    Journal::create(command, &plan.observed_state.repository.target, forge, repo)
272}
273
274/// The whole computation, shared with the fronts.
275///
276/// # Errors
277///
278/// A selector the crates venue cannot resolve, a bundle the engine
279/// cannot read, and the gathering's own failures.
280pub fn compute(request: &PlanRequest, clock: &str) -> Result<Planned, RkError> {
281    compute_frozen(request, clock, None)
282}
283
284/// The same computation over a release a stored plan froze: the exact
285/// version is served from the release cache and the selector is never
286/// resolved again, so an apply is offline once its plan exists.
287///
288/// # Errors
289///
290/// [`compute`]'s failures, and a `bundle-unverified` refusal when the
291/// cache no longer holds the frozen release.
292#[allow(
293    clippy::too_many_lines,
294    reason = "one computation is one linear sequence from the selector to the planner's inputs, and cutting it would separate a bundle from the observation it is read against"
295)]
296pub fn compute_frozen(
297    request: &PlanRequest,
298    clock: &str,
299    frozen: Option<&ResolvedRelease>,
300) -> Result<Planned, RkError> {
301    let target: &Utf8Path = &request.target;
302    let selector = request.selector.as_str();
303    let embedded = EmbeddedReleaseSource;
304    let crate_source = match frozen {
305        _ if selector == "embedded" => None,
306        Some(release) => {
307            let source = CrateReleaseSource::new(&release.version)?;
308            if !source.is_cached() {
309                return Err(RkError::refusal(
310                    Diagnostic::new(
311                        Reason::BundleUnverified,
312                        format!(
313                            "the plan froze release-kit {} ({}), and the release cache no longer holds that bundle; nothing was written",
314                            release.version, release.payload_sha256
315                        ),
316                    )
317                    .expected("the frozen release's verified bundle in the release cache")
318                    .action("rk reconcile plan --to <version> resolves and caches it again")
319                    .target_state("unchanged"),
320                ));
321            }
322            Some(source)
323        }
324        None => Some(CrateReleaseSource::new(selector)?),
325    };
326    let (candidate_source, venue, verification): (&dyn ReleaseSource, &str, Verification) =
327        match &crate_source {
328            None => (&embedded, "embedded", Verification::Embedded),
329            Some(source) => {
330                let resolved = source.resolve()?;
331                (
332                    source,
333                    "crates",
334                    Verification::RegistryChecksum {
335                        cksum: resolved.cksum.clone(),
336                    },
337                )
338            }
339        };
340    let candidate_manifest = candidate_source.manifest()?;
341    let declared = declared::compatibility(candidate_source, &candidate_manifest)?;
342    let guidance_files = declared::guidance(candidate_source, &candidate_manifest)?;
343    let carries_guidance = declared::carries_guidance(&candidate_manifest);
344    let extra_paths: Vec<String> = guidance_files
345        .iter()
346        .flat_map(|file| file.destinations.iter().cloned())
347        .collect();
348    let gather_request = Request {
349        target,
350        flags: &request.flags,
351        decisions: &request.decisions,
352        observe_forge: request.observe_forge,
353        clock,
354        source: candidate_source,
355        extra_paths: &extra_paths,
356    };
357    let mut observation = gather::observe(&gather_request)?;
358    let resolution = gather::resolve(&gather_request, &observation)?;
359    gather::observe_host_tools(
360        &mut observation,
361        resolution.params.as_ref().map(crate::landing::Params::tech),
362        resolution
363            .params
364            .as_ref()
365            .map(crate::landing::Params::forge),
366        clock,
367    );
368
369    // The recorded release's bundle: the embedded one where the record
370    // names its payload, the cache where it holds the recorded version,
371    // the venue where `--fetch` allows it, and not observed otherwise.
372    let recorded = match &observation.record {
373        RecordRead::Present { manifest, .. } => {
374            Some((manifest.rk_version.clone(), manifest.payload_sha256.clone()))
375        }
376        RecordRead::Absent | RecordRead::Invalid { .. } => None,
377    };
378    let baseline_crate = match &recorded {
379        Some((version, digest))
380            if *digest != EmbeddedReleaseSource::manifest_ref().payload_sha256
381                && *digest != candidate_manifest.payload_sha256 =>
382        {
383            let source = CrateReleaseSource::new(version)?;
384            if request.fetch || source.is_cached() {
385                Some(source)
386            } else {
387                None
388            }
389        }
390        _ => None,
391    };
392    let baseline = match &recorded {
393        None => Baseline::NotNeeded,
394        Some((_, digest)) if *digest == EmbeddedReleaseSource::manifest_ref().payload_sha256 => {
395            Baseline::Embedded(&embedded)
396        }
397        Some((version, digest)) if *digest == candidate_manifest.payload_sha256 => {
398            Baseline::Cached {
399                version: version.clone(),
400                source: candidate_source,
401            }
402        }
403        Some((version, _)) => cached_baseline(version, baseline_crate.as_ref()),
404    };
405    planner::plan(planner::Inputs {
406        intent: request.intent,
407        clock,
408        engine_version: env!("CARGO_PKG_VERSION"),
409        selector,
410        candidate: Candidate {
411            source: candidate_source,
412            manifest: candidate_manifest,
413            venue,
414            verification,
415        },
416        baseline,
417        observation,
418        resolution,
419        selected: &request.decisions,
420        declared: &declared,
421        guidance_files: &guidance_files,
422        carries_guidance,
423    })
424}
425
426/// The baseline for a recorded release the cache may hold.
427///
428/// A baseline that will not verify is an evidence gap, never a refusal.
429/// The candidate is what an apply writes and it refuses unverified; the
430/// recorded release only says what the target started from, so a plan
431/// that cannot read it says so and lets the readiness policy decide. A
432/// cache written before the seal existed is exactly this case, and it
433/// must still be able to plan.
434fn cached_baseline<'a>(version: &str, source: Option<&'a CrateReleaseSource>) -> Baseline<'a> {
435    let Some(source) = source else {
436        return Baseline::NotObserved {
437            reason: format!(
438                "the recorded release {version} is not in the release cache; --fetch reads it through the crates venue"
439            ),
440        };
441    };
442    match source.resolve() {
443        Ok(_) => Baseline::Cached {
444            version: version.to_owned(),
445            source,
446        },
447        Err(error) => Baseline::NotObserved {
448            reason: format!(
449                "the recorded release {version} is in the release cache and did not verify: {}",
450                error.diagnostic().message
451            ),
452        },
453    }
454}
455
456/// `<id>=<answer>` pairs into a map, refusing a malformed one.
457///
458/// # Errors
459///
460/// Returns [`RkError::Usage`] for an item without `=` or with an empty
461/// side.
462pub fn parse_decisions(raw: &[String]) -> Result<BTreeMap<String, String>, RkError> {
463    let mut decisions = BTreeMap::new();
464    for item in raw {
465        let Some((id, answer)) = item.split_once('=') else {
466            return Err(RkError::Usage(format!(
467                "--decide takes <id>=<answer>; '{item}' has no '='"
468            )));
469        };
470        if id.is_empty() || answer.is_empty() {
471            return Err(RkError::Usage(format!(
472                "--decide takes <id>=<answer>; '{item}' leaves one side empty"
473            )));
474        }
475        // A decision's choices are the whole of what answers it, so an
476        // unrecognized id or answer is refused where the operator typed
477        // it rather than read as a decision taken.
478        let Some(choices) = crate::plan::decision_choices(id) else {
479            let ids: Vec<&str> = crate::plan::DECISION_CHOICES
480                .iter()
481                .map(|(id, _)| *id)
482                .collect();
483            return Err(RkError::Usage(format!(
484                "--decide names no decision '{id}'; the decisions are: {}",
485                ids.join(", ")
486            )));
487        };
488        if !choices.contains(&answer) {
489            return Err(RkError::Usage(format!(
490                "--decide {id}={answer} is not an answer it takes; the answers are: {}",
491                choices.join(", ")
492            )));
493        }
494        decisions.insert(id.to_owned(), answer.to_owned());
495    }
496    Ok(decisions)
497}
498
499/// The human lines: the routing word, the readiness, the operations by
500/// kind, every precondition that does not hold, every decision that
501/// waits, and the fingerprint.
502fn render(out: Output, plan: &Plan, fresh: bool) {
503    out.result_line(format!(
504        "plan {} for {} toward release-kit {} ({}){}",
505        plan.identity.plan_id,
506        plan.observed_state.repository.target,
507        plan.desired_state.release.version,
508        plan.desired_state.release.venue,
509        if fresh { ", stored" } else { "" }
510    ));
511    out.result_line(format!("classification: {}", plan.classification.as_str()));
512    for finding in &plan.findings {
513        out.result_line(format!("  {}: {}", finding.code, finding.detail));
514    }
515    out.result_line(format!("readiness: {}", plan.readiness.as_str()));
516    let mut by_kind: BTreeMap<&str, usize> = BTreeMap::new();
517    for operation in &plan.operations {
518        *by_kind.entry(operation.kind()).or_default() += 1;
519    }
520    if by_kind.is_empty() {
521        out.result_line("operations: none");
522    } else {
523        out.result_line(format!(
524            "operations: {}",
525            by_kind
526                .iter()
527                .map(|(kind, count)| format!("{count} {kind}"))
528                .collect::<Vec<_>>()
529                .join(", ")
530        ));
531        for operation in &plan.operations {
532            out.result_line(format!("  {}", describe(operation)));
533        }
534    }
535    for precondition in plan.preconditions.iter().filter(|p| !p.evaluation.holds()) {
536        let reason = match &precondition.evaluation {
537            crate::plan::Evaluation::Satisfied => String::new(),
538            crate::plan::Evaluation::NotObserved { reason }
539            | crate::plan::Evaluation::Unsatisfied { reason } => reason.clone(),
540        };
541        out.result_line(format!(
542            "precondition {} ({}): {}: {reason}",
543            precondition.id,
544            precondition.requirement.as_str(),
545            precondition.evaluation.word()
546        ));
547    }
548    for decision in plan.decisions.iter().filter(|d| d.selected.is_none()) {
549        out.result_line(format!("decision {}: {}", decision.id, decision.question));
550        for choice in &decision.choices {
551            out.result_line(format!("  {}: {}", choice.answer, choice.consequence));
552        }
553    }
554    match &plan.release.guidance.coverage {
555        crate::plan::Coverage::NotNeeded => {}
556        coverage => {
557            let word = match coverage {
558                crate::plan::Coverage::Covered => "covered".to_owned(),
559                crate::plan::Coverage::Partial { since } => format!("partial above {since}"),
560                crate::plan::Coverage::Unavailable => "unavailable".to_owned(),
561                crate::plan::Coverage::NotNeeded => String::new(),
562            };
563            out.result_line(format!(
564                "guidance: {word}, {} step(s) for this target, {} excluded",
565                plan.release.guidance.steps.len(),
566                plan.release.guidance.excluded
567            ));
568            for step in &plan.release.guidance.steps {
569                out.result_line(format!(
570                    "  {} ({}): {} [{}]",
571                    step.version,
572                    step.action,
573                    step.title,
574                    step.destinations.join(", ")
575                ));
576            }
577        }
578    }
579    out.result_line(format!("fingerprint: {}", plan.input_fingerprint));
580    out.next(&next_lines(plan));
581}
582
583/// The human lines of an apply.
584fn render_applied(out: Output, applied: &Applied) {
585    out.result_line(format!(
586        "applied plan {} to {}",
587        applied.plan_id, applied.target
588    ));
589    for result in &applied.operations {
590        out.result_line(format!(
591            "  {} {}",
592            result.op,
593            result.path.as_deref().unwrap_or_default()
594        ));
595    }
596    for result in &applied.postconditions {
597        out.result_line(result.detail.as_ref().map_or_else(
598            || format!("postcondition {}: {}", result.check, result.status),
599            |detail| {
600                format!(
601                    "postcondition {}: {} ({detail})",
602                    result.check, result.status
603                )
604            },
605        ));
606    }
607    if let Some(run_id) = &applied.run_id {
608        out.result_line(format!("journal: run {run_id}"));
609    }
610    out.next(&applied.next);
611}
612
613/// One operation as a human line.
614pub(crate) fn describe(operation: &Operation) -> String {
615    match operation {
616        Operation::WriteFile { path, kind, .. } => format!("write-file {path} ({})", kind.as_str()),
617        Operation::SpliceBlock { path, .. } => format!("splice-block {path}"),
618        Operation::RemoveOwnedFile { path, .. } => format!("remove-owned-file {path}"),
619        Operation::WriteRecord { .. } => format!("write-record {}", manifest::MANIFEST_PATH),
620        Operation::UpdatePin {
621            manager,
622            before,
623            after,
624        } => format!("update-pin {manager} {before} -> {after}"),
625    }
626}
627
628/// What plausibly follows, from the readiness.
629fn next_lines(plan: &Plan) -> Vec<String> {
630    let target = &plan.observed_state.repository.target;
631    match plan.readiness {
632        Readiness::Blocked => {
633            vec!["resolve each unsatisfied required precondition above, then plan again".to_owned()]
634        }
635        Readiness::NeedsDecision => plan
636            .decisions
637            .iter()
638            .filter(|d| d.selected.is_none())
639            .map(|d| {
640                format!(
641                    "rk reconcile plan --target {target} --decide {}=<{}> selects an answer",
642                    d.id,
643                    d.choices
644                        .iter()
645                        .map(|c| c.answer.as_str())
646                        .collect::<Vec<_>>()
647                        .join("|")
648                )
649            })
650            .collect(),
651        Readiness::Ready => match plan.classification {
652            Classification::Upgrade if plan.operations.is_empty() => {
653                vec!["nothing to take: the target is at this release".to_owned()]
654            }
655            Classification::Setup | Classification::Migration | Classification::Upgrade => {
656                vec![format!(
657                    "rk reconcile apply {} executes exactly these operations",
658                    plan.identity.plan_id
659                )]
660            }
661            Classification::Drift | Classification::Invalid => {
662                vec!["resolve the findings above, then plan again".to_owned()]
663            }
664        },
665    }
666}