Skip to main content

eggup_service/
commit_engine.rs

1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3//! The single commit-and-rollback engine shared by every `eggup-service`
4//! orchestrator.
5//!
6//! Before this module existed, `disposition.rs` and `lifecycle_update.rs` each
7//! carried a full orchestrator **and** their own copies of the transition,
8//! rollback-quiesce, panic-safe-inspect, panic-safe-restore, deadline, and
9//! detail-truncation mechanics. The copies had already drifted apart in
10//! safety-relevant ways. This module is the single home of those mechanics;
11//! both public orchestrators reach them here.
12//!
13//! # What the engine guarantees
14//!
15//! * **No panic on manager- or caller-supplied state.** Every manager-reported
16//!   state and every desired state is handled by a typed arm. A desired state
17//!   outside `{Running, Stopped}` is a typed, bounded failure — never a panic,
18//!   never a fabricated success.
19//! * **Fail closed.** Ownership that is not `Owned` is a typed failure unless
20//!   the caller explicitly selects
21//!   [`OwnershipLossTolerance::TolerateAlreadyStopped`]. `Owned` is never
22//!   inferred: it is returned only by a caller-proven ownership check.
23//! * **One catch boundary per mechanic.** A panicking manager is caught at the
24//!   mechanic that is executing and recorded under the phase actually
25//!   executing, so a panicking `start`/`stop` is never reported as a
26//!   post-install check failure.
27//! * **One truncation rule.** Failure detail is control-character free and
28//!   bounded by [`crate::MAX_DIAGNOSTIC_BYTES`].
29//!
30//! # Named policy inputs
31//!
32//! The two behavioural differences between the former copies are explicit,
33//! named, separately testable inputs on [`CommitEnginePolicy`]:
34//!
35//! | Input | Default | Fail-closed direction |
36//! |---|---|---|
37//! | [`CommitEnginePolicy::post_transition_verification`] | [`PostTransitionVerification::Verify`] | a manager's own `completed` flag is a self-report, not evidence of observed state, so the engine re-inspects and validates |
38//! | [`CommitEnginePolicy::ownership_loss_tolerance`] | [`OwnershipLossTolerance::Deny`] | unproven ownership must not be able to produce a successful outcome |
39//!
40//! Both defaults are the **stricter** of the two former behaviours.
41
42use crate::{LifecycleSnapshot, LifecycleState, Ownership, ServiceManager, ServiceSpec};
43use std::{
44    fmt,
45    panic::{catch_unwind, AssertUnwindSafe},
46    time::{Duration, Instant},
47};
48
49/// Phase that produced lifecycle-specific update evidence.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51#[non_exhaustive]
52pub enum LifecycleUpdatePhase {
53    /// Initial state observation.
54    Inspect,
55    /// Stop the prior generation before artifact mutation.
56    Quiesce,
57    /// Core transaction returned before a terminal receipt.
58    Commit,
59    /// Restore the successful new generation's desired state.
60    RestoreNew,
61    /// Caller-owned post-install validation.
62    PostInstallCheck,
63    /// Stop the new generation before Core rollback.
64    QuiesceForRollback,
65    /// Restore the prior generation's lifecycle state after rollback.
66    RestoreOld,
67    /// Optional final read-only observation.
68    FinalInspect,
69}
70
71/// Bounded service-specific failure evidence, separate from Core artifact evidence.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct LifecycleFailure {
74    /// Orchestration phase.
75    pub phase: LifecycleUpdatePhase,
76    /// Service identifier.
77    pub service_id: String,
78    /// Bounded detail. Implementations must not include secrets.
79    pub detail: String,
80    /// Ownership observed when applicable.
81    pub ownership: Option<Ownership>,
82    /// State observed when applicable.
83    pub state: Option<LifecycleState>,
84}
85
86impl LifecycleFailure {
87    /// Builds bounded failure evidence for one phase and observation.
88    pub(crate) fn new(
89        spec: &ServiceSpec,
90        phase: LifecycleUpdatePhase,
91        detail: impl fmt::Display,
92        snapshot: Option<&LifecycleSnapshot>,
93    ) -> Self {
94        Self {
95            phase,
96            service_id: spec.id().as_str().to_owned(),
97            detail: bounded_detail(detail.to_string()),
98            ownership: snapshot.map(|s| s.ownership),
99            state: snapshot.map(|s| s.state),
100        }
101    }
102}
103
104/// Bounded caller-owned post-install check failure.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct PostInstallCheckError(String);
107
108impl PostInstallCheckError {
109    /// Creates bounded, non-secret failure evidence.
110    pub fn new(detail: impl Into<String>) -> Self {
111        Self(bounded_detail(detail.into()))
112    }
113}
114
115impl fmt::Display for PostInstallCheckError {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        f.write_str(&self.0)
118    }
119}
120impl std::error::Error for PostInstallCheckError {}
121
122/// Caller-controlled post-install check. Implementations must honor `remaining`.
123pub trait PostInstallCheck: fmt::Debug {
124    /// Check the installed generation within the supplied remaining-time budget.
125    ///
126    /// Synchronous user code cannot be forcibly cancelled safely. This method
127    /// must return within `remaining` and must not include secrets in its error.
128    fn check(
129        &self,
130        spec: &ServiceSpec,
131        snapshot: &LifecycleSnapshot,
132        remaining: Duration,
133    ) -> Result<(), PostInstallCheckError>;
134}
135
136/// No-op check for consumers that require lifecycle restoration only.
137#[derive(Debug, Default)]
138pub struct NoPostInstallCheck;
139
140impl PostInstallCheck for NoPostInstallCheck {
141    fn check(
142        &self,
143        _spec: &ServiceSpec,
144        _snapshot: &LifecycleSnapshot,
145        _remaining: Duration,
146    ) -> Result<(), PostInstallCheckError> {
147        Ok(())
148    }
149}
150
151/// Whether the engine re-inspects the manager after a transition.
152///
153/// A manager's `completed` flag is a **self-report**, not evidence of observed
154/// state: the M010 quiescence work already established that a nominal
155/// completion is not proof. `Verify` therefore re-inspects the manager and
156/// validates the observed ownership and state against the wanted state.
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
158#[non_exhaustive]
159pub enum PostTransitionVerification {
160    /// Re-inspect the manager and validate ownership and state after every
161    /// transition. This is the default and the fail-closed direction.
162    #[default]
163    Verify,
164    /// Accept the manager's own completion report without re-inspecting.
165    ///
166    /// This is the former disposition-path behaviour. It is available only as
167    /// an explicitly selected, non-default input, because it can report a
168    /// successful transition whose observed state or ownership never changed.
169    TrustManagerReport,
170}
171
172/// Whether ownership loss during a transition is tolerated.
173///
174/// `Owned` is never inferred, so an ownership that is no longer `Owned` is
175/// unproven. `Deny` (the default) makes that a typed failure; only the
176/// explicitly selected `TolerateAlreadyStopped` input lets an already-stopped
177/// unit pass a transition.
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
179#[non_exhaustive]
180pub enum OwnershipLossTolerance {
181    /// Ownership that is not `Owned` is always a typed failure. This is the
182    /// default and the fail-closed direction.
183    #[default]
184    Deny,
185    /// Tolerate ownership loss when the unit is already in the wanted stopped
186    /// state.
187    ///
188    /// This is the former disposition-path behaviour. It is available only as
189    /// an explicitly selected, non-default input, because it lets an unproven
190    /// ownership produce a successful outcome.
191    TolerateAlreadyStopped,
192}
193
194/// The two named, separately testable inputs that distinguish the unified
195/// engine's behaviour.
196///
197/// Both fields default to the **stricter** of the two former engine copies'
198/// behaviours, and both public orchestrators run the same engine under this
199/// default policy.
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
201pub struct CommitEnginePolicy {
202    /// Whether the engine re-inspects and validates after a transition.
203    pub post_transition_verification: PostTransitionVerification,
204    /// Whether ownership loss during a transition is tolerated.
205    pub ownership_loss_tolerance: OwnershipLossTolerance,
206}
207
208/// The one valid target state of a lifecycle transition.
209///
210/// `Running` and `Stopped` are the only desired states a transition may
211/// request. Every other [`LifecycleState`] is rejected by the engine at the
212/// point of use.
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
214enum Desired {
215    Running,
216    Stopped,
217}
218
219/// Detail text used when a caller supplies a desired state that is not a valid
220/// `Running`/`Stopped` target.
221const INVALID_DESIRED_STATE: &str =
222    "desired lifecycle state is not a valid Running or Stopped target";
223
224/// Remaining budget under a deadline.
225///
226/// One implementation for the whole crate: the deadline arithmetic is
227/// unchanged by this engine, only its single home is.
228pub(crate) fn remaining(deadline: Instant) -> Duration {
229    deadline.saturating_duration_since(Instant::now())
230}
231
232/// Bounded, control-character-free failure detail.
233///
234/// One implementation for the whole crate, bounded by
235/// [`crate::MAX_DIAGNOSTIC_BYTES`].
236pub(crate) fn bounded_detail(mut detail: String) -> String {
237    detail = detail.chars().filter(|c| !c.is_control()).collect();
238    crate::truncate_utf8_bytes(detail, crate::MAX_DIAGNOSTIC_BYTES)
239}
240
241/// Panic-safe manager inspection.
242///
243/// The catch boundary lives at the mechanic that is executing, so a panicking
244/// manager is recorded under the phase actually running.
245pub(crate) fn safe_inspect<M: ServiceManager>(
246    manager: &mut M,
247    spec: &ServiceSpec,
248    phase: LifecycleUpdatePhase,
249) -> Result<LifecycleSnapshot, LifecycleFailure> {
250    match catch_unwind(AssertUnwindSafe(|| manager.inspect(spec))) {
251        Ok(Ok(snapshot)) => Ok(snapshot),
252        Ok(Err(error)) => Err(LifecycleFailure::new(spec, phase, error, None)),
253        Err(_) => Err(LifecycleFailure::new(
254            spec,
255            phase,
256            "service manager panicked while inspecting",
257            None,
258        )),
259    }
260}
261
262/// Whether an ownership loss is tolerated under the selected policy.
263///
264/// One implementation for the whole engine: the named tolerance governs
265/// **every** ownership check the engine performs — the check at the transition
266/// point and the post-transition verification alike — so the input means the
267/// same thing wherever it is observed.
268fn ownership_tolerated(
269    policy: &CommitEnginePolicy,
270    wanted: LifecycleState,
271    snapshot: &LifecycleSnapshot,
272) -> bool {
273    policy.ownership_loss_tolerance == OwnershipLossTolerance::TolerateAlreadyStopped
274        && wanted == LifecycleState::Stopped
275        && snapshot.state == LifecycleState::Stopped
276}
277
278/// The single transition mechanic.
279///
280/// The engine performs, in order:
281///
282/// 1. the deadline check;
283/// 2. the **desired-state validity check at the point of use** — a desired
284///    state outside `{Running, Stopped}` is a typed, bounded failure;
285/// 3. the ownership check, which honours
286///    [`CommitEnginePolicy::ownership_loss_tolerance`];
287/// 4. the `start`/`stop` call and its `completed` check;
288/// 5. the optional post-transition re-inspection and validation, governed by
289///    [`CommitEnginePolicy::post_transition_verification`].
290///
291/// No `unreachable!`, `unwrap`, `expect`, or arithmetic panic is reachable from
292/// any manager-reported state or caller-supplied desired state.
293pub(crate) fn transition_to<M: ServiceManager>(
294    manager: &mut M,
295    spec: &ServiceSpec,
296    wanted: LifecycleState,
297    timeout: Duration,
298    phase: LifecycleUpdatePhase,
299    policy: &CommitEnginePolicy,
300) -> Result<(), LifecycleFailure> {
301    if timeout.is_zero() {
302        return Err(LifecycleFailure::new(
303            spec,
304            phase,
305            "lifecycle operation deadline exhausted",
306            None,
307        ));
308    }
309    let desired = match wanted {
310        LifecycleState::Running => Desired::Running,
311        LifecycleState::Stopped => Desired::Stopped,
312        LifecycleState::Transitioning | LifecycleState::Unknown => {
313            return Err(LifecycleFailure::new(
314                spec,
315                phase,
316                INVALID_DESIRED_STATE,
317                None,
318            ))
319        }
320    };
321    let current = manager
322        .inspect(spec)
323        .map_err(|e| LifecycleFailure::new(spec, phase, e, None))?;
324    if current.ownership != Ownership::Owned {
325        if ownership_tolerated(policy, wanted, &current) {
326            return Ok(());
327        }
328        return Err(LifecycleFailure::new(
329            spec,
330            phase,
331            "service ownership is no longer Owned",
332            Some(&current),
333        ));
334    }
335    let result = match (desired, current.state) {
336        (Desired::Running, LifecycleState::Running)
337        | (Desired::Stopped, LifecycleState::Stopped) => return Ok(()),
338        (Desired::Running, LifecycleState::Stopped) => manager.start(spec, timeout),
339        (Desired::Stopped, LifecycleState::Running) => manager.stop(spec, timeout),
340        (_, LifecycleState::Transitioning | LifecycleState::Unknown) => {
341            return Err(LifecycleFailure::new(
342                spec,
343                phase,
344                "service state is Unknown or Transitioning",
345                Some(&current),
346            ))
347        }
348    }
349    .map_err(|e| LifecycleFailure::new(spec, phase, e, Some(&current)))?;
350    if !result.completed {
351        return Err(LifecycleFailure::new(
352            spec,
353            phase,
354            "service transition did not complete",
355            Some(&current),
356        ));
357    }
358    if policy.post_transition_verification == PostTransitionVerification::Verify {
359        let after = manager
360            .inspect(spec)
361            .map_err(|e| LifecycleFailure::new(spec, phase, e, None))?;
362        validate_observed(spec, &after, wanted, phase, policy)?;
363    }
364    Ok(())
365}
366
367/// Panic-safe [`transition_to`].
368///
369/// The caller's own `catch_unwind` wraps a whole post-commit block, so a panic
370/// escaping here would be labelled with the wrong phase. Catching it at the
371/// point of execution records it under `phase` — so a panicking `start`/`stop`
372/// cannot be reported as a post-install check failure.
373pub(crate) fn safe_transition_to<M: ServiceManager>(
374    manager: &mut M,
375    spec: &ServiceSpec,
376    wanted: LifecycleState,
377    timeout: Duration,
378    phase: LifecycleUpdatePhase,
379    policy: &CommitEnginePolicy,
380) -> Result<(), LifecycleFailure> {
381    match catch_unwind(AssertUnwindSafe(|| {
382        transition_to(manager, spec, wanted, timeout, phase, policy)
383    })) {
384        Ok(result) => result,
385        Err(_) => Err(LifecycleFailure::new(
386            spec,
387            phase,
388            "service manager panicked while transitioning",
389            None,
390        )),
391    }
392}
393
394/// Validates one observation against the wanted state.
395///
396/// The ownership half of the check honours the selected
397/// [`CommitEnginePolicy::ownership_loss_tolerance`], so the named tolerance
398/// means the same thing at the transition point and in the post-transition
399/// verification.
400pub(crate) fn validate_observed(
401    spec: &ServiceSpec,
402    snapshot: &LifecycleSnapshot,
403    wanted: LifecycleState,
404    phase: LifecycleUpdatePhase,
405    policy: &CommitEnginePolicy,
406) -> Result<(), LifecycleFailure> {
407    let ownership_ok =
408        snapshot.ownership == Ownership::Owned || ownership_tolerated(policy, wanted, snapshot);
409    if !ownership_ok || snapshot.state != wanted {
410        return Err(LifecycleFailure::new(
411            spec,
412            phase,
413            "service ownership/state does not match the requested state",
414            Some(snapshot),
415        ));
416    }
417    Ok(())
418}
419
420/// Stops an owned, running service before Core mutation.
421///
422/// One implementation for the whole crate. The stop is panic-guarded at the
423/// mechanic that is executing, and the post-stop observation must prove
424/// `Owned` and `Stopped` before the mutation is allowed to proceed.
425pub(crate) fn quiesce_service<M: ServiceManager>(
426    manager: &mut M,
427    spec: &ServiceSpec,
428    before: &LifecycleSnapshot,
429    timeout: Duration,
430) -> Result<(), LifecycleFailure> {
431    let stop_result = catch_unwind(AssertUnwindSafe(|| manager.stop(spec, timeout)));
432    match stop_result {
433        Ok(Err(error)) => Err(LifecycleFailure::new(
434            spec,
435            LifecycleUpdatePhase::Quiesce,
436            error,
437            Some(before),
438        )),
439        Err(_) => Err(LifecycleFailure::new(
440            spec,
441            LifecycleUpdatePhase::Quiesce,
442            "service manager panicked while stopping",
443            Some(before),
444        )),
445        Ok(Ok(result)) if !result.completed => Err(LifecycleFailure::new(
446            spec,
447            LifecycleUpdatePhase::Quiesce,
448            "stop did not complete",
449            Some(before),
450        )),
451        Ok(Ok(_)) => {
452            let after = safe_inspect(manager, spec, LifecycleUpdatePhase::Quiesce)?;
453            if after.ownership == Ownership::Owned && after.state == LifecycleState::Stopped {
454                Ok(())
455            } else {
456                Err(LifecycleFailure::new(
457                    spec,
458                    LifecycleUpdatePhase::Quiesce,
459                    "ownership/state changed after stop",
460                    Some(&after),
461                ))
462            }
463        }
464    }
465}
466
467/// Stops the new generation before Core rolls the artifact back.
468///
469/// One implementation for the whole crate, and the **fail-closed** one:
470///
471/// * an `inspect` failure is not "no information, proceed" — ownership could
472///   not be established, so the destructive `stop` below would run against an
473///   unproven target. It is refused instead;
474/// * a service that is not `Owned` is refused as well.
475///
476/// The caller wraps this call in its own `catch_unwind`, because this
477/// mechanic's boundary is the caller's post-commit block.
478pub(crate) fn quiesce_for_rollback<M: ServiceManager>(
479    manager: &mut M,
480    spec: &ServiceSpec,
481    deadline: Instant,
482) -> Option<LifecycleFailure> {
483    let budget = remaining(deadline);
484    if budget.is_zero() {
485        return Some(LifecycleFailure::new(
486            spec,
487            LifecycleUpdatePhase::QuiesceForRollback,
488            "post-commit deadline exhausted before rollback quiescence",
489            None,
490        ));
491    }
492    let observed = match manager.inspect(spec) {
493        Ok(snapshot) => Some(snapshot),
494        Err(error) => {
495            return Some(LifecycleFailure::new(
496                spec,
497                LifecycleUpdatePhase::QuiesceForRollback,
498                format!("refusing to quiesce unobservable service before rollback: {error}"),
499                None,
500            ))
501        }
502    };
503    if observed
504        .as_ref()
505        .is_some_and(|s| s.ownership == Ownership::Owned && s.state == LifecycleState::Stopped)
506    {
507        return None;
508    }
509    if let Some(observation) = observed.as_ref() {
510        if observation.ownership != Ownership::Owned {
511            return Some(LifecycleFailure::new(
512                spec,
513                LifecycleUpdatePhase::QuiesceForRollback,
514                "refusing to quiesce non-owned service before rollback",
515                Some(observation),
516            ));
517        }
518    }
519    match manager.stop(spec, budget) {
520        Err(error) => Some(LifecycleFailure::new(
521            spec,
522            LifecycleUpdatePhase::QuiesceForRollback,
523            error,
524            observed.as_ref(),
525        )),
526        Ok(result) if !result.completed => Some(LifecycleFailure::new(
527            spec,
528            LifecycleUpdatePhase::QuiesceForRollback,
529            "stop did not complete before artifact rollback",
530            observed.as_ref(),
531        )),
532        Ok(_) => match manager.inspect(spec) {
533            Ok(after)
534                if after.ownership == Ownership::Owned
535                    && after.state == LifecycleState::Stopped =>
536            {
537                None
538            }
539            Ok(after) => Some(LifecycleFailure::new(
540                spec,
541                LifecycleUpdatePhase::QuiesceForRollback,
542                "stopped state could not be confirmed before artifact rollback",
543                Some(&after),
544            )),
545            Err(error) => Some(LifecycleFailure::new(
546                spec,
547                LifecycleUpdatePhase::QuiesceForRollback,
548                error,
549                None,
550            )),
551        },
552    }
553}
554
555/// Restores the wanted lifecycle state after a successful artifact update and
556/// then runs the caller's post-install check.
557///
558/// One implementation for the whole crate. The transition is panic-guarded at
559/// its own boundary, so a panicking `start`/`stop` is recorded under
560/// `RestoreNew` and never as a post-install check failure.
561pub(crate) fn restore_and_check<M: ServiceManager, C: PostInstallCheck>(
562    manager: &mut M,
563    spec: &ServiceSpec,
564    wanted: LifecycleState,
565    check: &C,
566    deadline: Instant,
567    policy: &CommitEnginePolicy,
568) -> Result<(), LifecycleFailure> {
569    safe_transition_to(
570        manager,
571        spec,
572        wanted,
573        remaining(deadline),
574        LifecycleUpdatePhase::RestoreNew,
575        policy,
576    )?;
577    let snapshot = safe_inspect(manager, spec, LifecycleUpdatePhase::RestoreNew)?;
578    if policy.post_transition_verification == PostTransitionVerification::Verify {
579        validate_observed(
580            spec,
581            &snapshot,
582            wanted,
583            LifecycleUpdatePhase::RestoreNew,
584            policy,
585        )?;
586    }
587    let budget = remaining(deadline);
588    if budget.is_zero() {
589        return Err(LifecycleFailure::new(
590            spec,
591            LifecycleUpdatePhase::PostInstallCheck,
592            "post-commit deadline exhausted before post-install check",
593            Some(&snapshot),
594        ));
595    }
596    check.check(spec, &snapshot, budget).map_err(|e| {
597        LifecycleFailure::new(
598            spec,
599            LifecycleUpdatePhase::PostInstallCheck,
600            e,
601            Some(&snapshot),
602        )
603    })
604}
605
606#[cfg(test)]
607mod tests {
608    use super::*;
609    use crate::{HealthState, ServiceError, ServiceId, TransitionResult};
610    use std::time::Duration;
611
612    fn spec() -> ServiceSpec {
613        ServiceSpec::new(
614            ServiceId::new("commit-engine").unwrap(),
615            std::env::current_exe().unwrap(),
616            Vec::new(),
617            None,
618        )
619        .unwrap()
620    }
621
622    /// Manager double that always reports `Running` and `Owned`.
623    #[derive(Debug)]
624    struct RunningManager;
625
626    impl ServiceManager for RunningManager {
627        fn inspect(&self, spec: &ServiceSpec) -> Result<LifecycleSnapshot, ServiceError> {
628            Ok(LifecycleSnapshot {
629                id: spec.id().clone(),
630                ownership: Ownership::Owned,
631                state: LifecycleState::Running,
632                health: HealthState::Unknown,
633                was_registered: true,
634                was_running: true,
635            })
636        }
637
638        fn install(&mut self, _spec: &ServiceSpec) -> Result<TransitionResult, ServiceError> {
639            unreachable!("not exercised")
640        }
641
642        fn start(
643            &mut self,
644            _spec: &ServiceSpec,
645            _timeout: Duration,
646        ) -> Result<TransitionResult, ServiceError> {
647            unreachable!("not exercised")
648        }
649
650        fn stop(
651            &mut self,
652            _spec: &ServiceSpec,
653            _timeout: Duration,
654        ) -> Result<TransitionResult, ServiceError> {
655            unreachable!("not exercised")
656        }
657
658        fn restart(
659            &mut self,
660            _spec: &ServiceSpec,
661            _timeout: Duration,
662        ) -> Result<TransitionResult, ServiceError> {
663            unreachable!("not exercised")
664        }
665
666        fn uninstall(&mut self, _spec: &ServiceSpec) -> Result<TransitionResult, ServiceError> {
667            unreachable!("not exercised")
668        }
669    }
670
671    /// A desired state outside `{Running, Stopped}` is a typed, bounded
672    /// failure — never a panic, never a fabricated success.
673    #[test]
674    fn non_running_stopped_desired_state_is_a_typed_failure() {
675        for desired in [LifecycleState::Transitioning, LifecycleState::Unknown] {
676            let mut manager = RunningManager;
677            let spec = spec();
678            let failure = transition_to(
679                &mut manager,
680                &spec,
681                desired,
682                Duration::from_secs(1),
683                LifecycleUpdatePhase::RestoreNew,
684                &CommitEnginePolicy::default(),
685            )
686            .expect_err("an invalid desired state must fail");
687            assert_eq!(failure.phase, LifecycleUpdatePhase::RestoreNew);
688            assert_eq!(failure.detail, INVALID_DESIRED_STATE);
689            assert!(failure.detail.len() <= crate::MAX_DIAGNOSTIC_BYTES);
690        }
691    }
692}