Skip to main content

stateknot_core/
run.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Durable, protocol-neutral lifecycle contracts for one admitted agent run.
5//!
6//! This module models business progress only. Worker attempts, leases, fencing
7//! epochs, journal sequence numbers, and transport-specific task states remain
8//! separate runtime concerns. That separation lets a process crash or a lease
9//! change without inventing a business-state transition.
10
11use std::fmt;
12
13use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
14use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
15use thiserror::Error;
16
17use crate::{
18    AgentResult, AgentResultProvenance, BudgetUsage, ExecutionCount, Failure, FailureCategory,
19    InterruptId, RetryAdvice, TimerId, Timestamp,
20};
21
22/// Monotonic optimistic revision of a run lifecycle snapshot.
23///
24/// The wire form is the same canonical unsigned decimal string used by other
25/// exact counters, but the distinct Rust type prevents an accounting value
26/// from being passed as a lifecycle revision accidentally.
27#[derive(
28    Clone,
29    Copy,
30    Debug,
31    Default,
32    Deserialize,
33    Eq,
34    Hash,
35    JsonSchema,
36    Ord,
37    PartialEq,
38    PartialOrd,
39    Serialize,
40)]
41#[serde(transparent)]
42pub struct RunRevision(ExecutionCount);
43
44impl RunRevision {
45    /// Initial revision assigned at successful run admission.
46    pub const ZERO: Self = Self(ExecutionCount::ZERO);
47
48    /// Largest representable revision.
49    pub const MAX: Self = Self(ExecutionCount::MAX);
50
51    /// Constructs a revision from its integer representation.
52    #[must_use]
53    pub const fn new(value: u64) -> Self {
54        Self(ExecutionCount::new(value))
55    }
56
57    /// Returns the underlying integer revision.
58    #[must_use]
59    pub const fn get(self) -> u64 {
60        self.0.get()
61    }
62
63    const fn checked_next(self) -> Option<Self> {
64        match self.0.checked_add(ExecutionCount::new(1)) {
65            Some(value) => Some(Self(value)),
66            None => None,
67        }
68    }
69}
70
71impl fmt::Display for RunRevision {
72    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
73        self.0.fmt(formatter)
74    }
75}
76
77/// Stable projection of a run's current business lifecycle.
78#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
79#[serde(rename_all = "snake_case")]
80pub enum RunStatus {
81    /// Admission committed, but semantic execution has not started.
82    Pending,
83    /// The run is allowed to make progress; a worker need not currently hold it.
84    Active,
85    /// Progress is durably suspended on one or more explicit conditions.
86    Waiting,
87    /// Cancellation intent committed and blocks every non-cancellation outcome.
88    CancellationRequested,
89    /// A validated successful result committed.
90    Succeeded,
91    /// A non-cancellation terminal failure committed.
92    Failed,
93    /// The committed cancellation request reached its terminal acknowledgement.
94    Cancelled,
95}
96
97impl RunStatus {
98    /// Returns whether this state can never transition again.
99    #[must_use]
100    pub const fn is_terminal(self) -> bool {
101        matches!(self, Self::Succeeded | Self::Failed | Self::Cancelled)
102    }
103}
104
105/// Semantic reason why a run needs an externally supplied resolution.
106#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
107#[serde(rename_all = "snake_case")]
108pub enum RunInterruptKind {
109    /// A principal must authorize an already bound action.
110    Approval,
111    /// Additional caller data is required.
112    Input,
113    /// Authentication or delegated authorization is required.
114    Authentication,
115    /// A named external signal or callback must arrive.
116    ExternalSignal,
117    /// An ambiguous external effect must be reconciled before progress.
118    Reconciliation,
119}
120
121/// Immutable lifecycle marker for one unresolved interrupt.
122///
123/// Request and resolution payloads, authorization requirements, action
124/// digests, and resolver provenance belong to the durable interrupt record.
125/// The runtime commits that record atomically with the lifecycle transition;
126/// this compact marker prevents large or sensitive payloads from being copied
127/// into every run snapshot.
128#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
129#[serde(deny_unknown_fields)]
130pub struct RunInterrupt {
131    interrupt_id: InterruptId,
132    kind: RunInterruptKind,
133    requested_at: Timestamp,
134    #[serde(skip_serializing_if = "Option::is_none")]
135    expires_at: Option<Timestamp>,
136}
137
138impl RunInterrupt {
139    /// Constructs an interrupt marker with an optional exclusive expiry.
140    ///
141    /// A resolution observed exactly at `expires_at` is expired.
142    ///
143    /// # Errors
144    ///
145    /// Returns [`RunInterruptError::ExpiryNotAfterRequest`] unless an expiry is
146    /// strictly later than the request observation.
147    pub fn new(
148        interrupt_id: InterruptId,
149        kind: RunInterruptKind,
150        requested_at: Timestamp,
151        expires_at: Option<Timestamp>,
152    ) -> Result<Self, RunInterruptError> {
153        if let Some(expires_at) = expires_at {
154            if expires_at <= requested_at {
155                return Err(RunInterruptError::ExpiryNotAfterRequest {
156                    requested_at,
157                    expires_at,
158                });
159            }
160        }
161        Ok(Self {
162            interrupt_id,
163            kind,
164            requested_at,
165            expires_at,
166        })
167    }
168
169    /// Returns the tenant-scoped interrupt identifier.
170    #[must_use]
171    pub const fn interrupt_id(&self) -> InterruptId {
172        self.interrupt_id
173    }
174
175    /// Returns the semantic interrupt kind.
176    #[must_use]
177    pub const fn kind(&self) -> RunInterruptKind {
178        self.kind
179    }
180
181    /// Returns the durable clock observation at registration.
182    #[must_use]
183    pub const fn requested_at(&self) -> Timestamp {
184        self.requested_at
185    }
186
187    /// Returns the exclusive resolution expiry, if configured.
188    #[must_use]
189    pub const fn expires_at(&self) -> Option<Timestamp> {
190        self.expires_at
191    }
192}
193
194impl fmt::Debug for RunInterrupt {
195    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
196        formatter
197            .debug_struct("RunInterrupt")
198            .field("interrupt_id", &self.interrupt_id)
199            .field("kind", &self.kind)
200            .field("requested_at", &self.requested_at)
201            .field("expires_at", &self.expires_at)
202            .finish_non_exhaustive()
203    }
204}
205
206impl<'de> Deserialize<'de> for RunInterrupt {
207    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
208    where
209        D: Deserializer<'de>,
210    {
211        #[derive(Deserialize)]
212        #[serde(deny_unknown_fields)]
213        struct Wire {
214            interrupt_id: InterruptId,
215            kind: RunInterruptKind,
216            requested_at: Timestamp,
217            expires_at: Option<Timestamp>,
218        }
219
220        let wire = Wire::deserialize(deserializer)?;
221        Self::new(
222            wire.interrupt_id,
223            wire.kind,
224            wire.requested_at,
225            wire.expires_at,
226        )
227        .map_err(de::Error::custom)
228    }
229}
230
231/// Invalid intrinsic timing for a run interrupt.
232#[derive(Clone, Debug, Eq, Error, PartialEq)]
233#[non_exhaustive]
234pub enum RunInterruptError {
235    /// An exclusive expiry was not later than registration.
236    #[error("interrupt expiry {expires_at} must be later than request {requested_at}")]
237    ExpiryNotAfterRequest {
238        /// Durable request observation.
239        requested_at: Timestamp,
240        /// Rejected exclusive expiry.
241        expires_at: Timestamp,
242    },
243}
244
245/// Semantic purpose of one durable run timer.
246#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
247#[serde(rename_all = "snake_case")]
248pub enum RunTimerKind {
249    /// A graph or agent deliberately sleeps until a scheduled instant.
250    Sleep,
251    /// Retry policy defers another attempt until a backoff instant.
252    RetryBackoff,
253}
254
255/// Immutable marker for one unresolved durable timer.
256#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
257#[serde(deny_unknown_fields)]
258pub struct RunTimer {
259    timer_id: TimerId,
260    kind: RunTimerKind,
261    scheduled_at: Timestamp,
262    due_at: Timestamp,
263}
264
265impl RunTimer {
266    /// Constructs a timer whose due instant is strictly after registration.
267    ///
268    /// # Errors
269    ///
270    /// Returns [`RunTimerError::DueNotAfterSchedule`] when the timer could fire
271    /// at or before its registration observation.
272    pub fn new(
273        timer_id: TimerId,
274        kind: RunTimerKind,
275        scheduled_at: Timestamp,
276        due_at: Timestamp,
277    ) -> Result<Self, RunTimerError> {
278        if due_at <= scheduled_at {
279            return Err(RunTimerError::DueNotAfterSchedule {
280                scheduled_at,
281                due_at,
282            });
283        }
284        Ok(Self {
285            timer_id,
286            kind,
287            scheduled_at,
288            due_at,
289        })
290    }
291
292    /// Returns the tenant-scoped timer identifier.
293    #[must_use]
294    pub const fn timer_id(&self) -> TimerId {
295        self.timer_id
296    }
297
298    /// Returns the semantic timer purpose.
299    #[must_use]
300    pub const fn kind(&self) -> RunTimerKind {
301        self.kind
302    }
303
304    /// Returns the durable clock observation at registration.
305    #[must_use]
306    pub const fn scheduled_at(&self) -> Timestamp {
307        self.scheduled_at
308    }
309
310    /// Returns the inclusive earliest firing instant.
311    #[must_use]
312    pub const fn due_at(&self) -> Timestamp {
313        self.due_at
314    }
315}
316
317impl fmt::Debug for RunTimer {
318    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
319        formatter
320            .debug_struct("RunTimer")
321            .field("timer_id", &self.timer_id)
322            .field("kind", &self.kind)
323            .field("scheduled_at", &self.scheduled_at)
324            .field("due_at", &self.due_at)
325            .finish_non_exhaustive()
326    }
327}
328
329impl<'de> Deserialize<'de> for RunTimer {
330    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
331    where
332        D: Deserializer<'de>,
333    {
334        #[derive(Deserialize)]
335        #[serde(deny_unknown_fields)]
336        struct Wire {
337            timer_id: TimerId,
338            kind: RunTimerKind,
339            scheduled_at: Timestamp,
340            due_at: Timestamp,
341        }
342
343        let wire = Wire::deserialize(deserializer)?;
344        Self::new(wire.timer_id, wire.kind, wire.scheduled_at, wire.due_at)
345            .map_err(de::Error::custom)
346    }
347}
348
349/// Invalid intrinsic timing for a durable run timer.
350#[derive(Clone, Debug, Eq, Error, PartialEq)]
351#[non_exhaustive]
352pub enum RunTimerError {
353    /// The due instant was not later than registration.
354    #[error("timer due instant {due_at} must be later than schedule {scheduled_at}")]
355    DueNotAfterSchedule {
356        /// Durable registration observation.
357        scheduled_at: Timestamp,
358        /// Rejected inclusive due instant.
359        due_at: Timestamp,
360    },
361}
362
363/// One explicit condition suspending semantic run progress.
364#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
365#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
366pub enum RunWait {
367    /// Wait for an authenticated and authorized interrupt resolution record.
368    Interrupt {
369        /// Immutable unresolved interrupt marker.
370        interrupt: RunInterrupt,
371    },
372    /// Wait for a durable scheduler observation at or after a due instant.
373    Timer {
374        /// Immutable unresolved timer marker.
375        timer: RunTimer,
376    },
377}
378
379impl RunWait {
380    /// Constructs an interrupt wait.
381    #[must_use]
382    pub const fn interrupt(interrupt: RunInterrupt) -> Self {
383        Self::Interrupt { interrupt }
384    }
385
386    /// Constructs a timer wait.
387    #[must_use]
388    pub const fn timer(timer: RunTimer) -> Self {
389        Self::Timer { timer }
390    }
391
392    /// Returns the interrupt marker when this is an interrupt wait.
393    #[must_use]
394    pub const fn as_interrupt(&self) -> Option<&RunInterrupt> {
395        match self {
396            Self::Interrupt { interrupt } => Some(interrupt),
397            Self::Timer { .. } => None,
398        }
399    }
400
401    /// Returns the timer marker when this is a timer wait.
402    #[must_use]
403    pub const fn as_timer(&self) -> Option<&RunTimer> {
404        match self {
405            Self::Timer { timer } => Some(timer),
406            Self::Interrupt { .. } => None,
407        }
408    }
409
410    const fn registered_at(&self) -> Timestamp {
411        match self {
412            Self::Interrupt { interrupt } => interrupt.requested_at(),
413            Self::Timer { timer } => timer.scheduled_at(),
414        }
415    }
416
417    fn identity_uuid(&self) -> uuid::Uuid {
418        match self {
419            Self::Interrupt { interrupt } => interrupt.interrupt_id().into_uuid(),
420            Self::Timer { timer } => timer.timer_id().into_uuid(),
421        }
422    }
423}
424
425/// Non-empty, bounded batch of conditions registered by one state transition.
426///
427/// Parallel graph branches may suspend on several conditions at the same
428/// barrier. Their markers retain stable semantic order, share one registration
429/// observation, and have globally unique UUID identities across interrupt and
430/// timer variants.
431#[derive(Clone, Eq, PartialEq)]
432pub struct RunWaits {
433    values: Box<[RunWait]>,
434    registered_at: Timestamp,
435}
436
437impl RunWaits {
438    /// Maximum simultaneous outstanding conditions for one run.
439    pub const MAX_LEN: usize = 64;
440
441    /// Validates a non-empty batch of wait conditions.
442    ///
443    /// # Errors
444    ///
445    /// Returns [`RunWaitsError`] for an empty or oversized batch, duplicate
446    /// identities, or conditions observed at different registration instants.
447    pub fn try_new<I>(values: I) -> Result<Self, RunWaitsError>
448    where
449        I: IntoIterator<Item = RunWait>,
450    {
451        let mut collected = Vec::new();
452        let mut registered_at = None;
453        for value in values {
454            if collected.len() == Self::MAX_LEN {
455                return Err(RunWaitsError::TooMany {
456                    maximum: Self::MAX_LEN,
457                    actual: Self::MAX_LEN + 1,
458                });
459            }
460            let value_registered_at = value.registered_at();
461            if let Some(expected) = registered_at {
462                if value_registered_at != expected {
463                    return Err(RunWaitsError::MixedRegistrationTimes {
464                        expected,
465                        actual: value_registered_at,
466                    });
467                }
468            } else {
469                registered_at = Some(value_registered_at);
470            }
471            if collected
472                .iter()
473                .any(|existing: &RunWait| existing.identity_uuid() == value.identity_uuid())
474            {
475                return Err(RunWaitsError::DuplicateIdentity);
476            }
477            collected.push(value);
478        }
479
480        let registered_at = registered_at.ok_or(RunWaitsError::Empty)?;
481        Ok(Self {
482            values: collected.into_boxed_slice(),
483            registered_at,
484        })
485    }
486
487    /// Returns the number of outstanding conditions.
488    #[must_use]
489    pub const fn len(&self) -> usize {
490        self.values.len()
491    }
492
493    /// Returns whether no conditions are present.
494    ///
495    /// This is always `false` for a valid value; the method is provided for
496    /// ordinary collection ergonomics and future-proof generic callers.
497    #[must_use]
498    pub const fn is_empty(&self) -> bool {
499        self.values.is_empty()
500    }
501
502    /// Returns the common registration observation.
503    #[must_use]
504    pub const fn registered_at(&self) -> Timestamp {
505        self.registered_at
506    }
507
508    /// Iterates conditions in deterministic semantic order.
509    pub fn iter(&self) -> impl ExactSizeIterator<Item = &RunWait> {
510        self.values.iter()
511    }
512
513    /// Looks up an outstanding interrupt by exact identifier.
514    #[must_use]
515    pub fn interrupt(&self, interrupt_id: InterruptId) -> Option<&RunInterrupt> {
516        self.values
517            .iter()
518            .filter_map(RunWait::as_interrupt)
519            .find(|interrupt| interrupt.interrupt_id() == interrupt_id)
520    }
521
522    /// Looks up an outstanding timer by exact identifier.
523    #[must_use]
524    pub fn timer(&self, timer_id: TimerId) -> Option<&RunTimer> {
525        self.values
526            .iter()
527            .filter_map(RunWait::as_timer)
528            .find(|timer| timer.timer_id() == timer_id)
529    }
530
531    /// Consumes the batch into stable ordered conditions.
532    #[must_use]
533    pub fn into_vec(self) -> Vec<RunWait> {
534        self.values.into_vec()
535    }
536
537    fn without_interrupt(self, interrupt_id: InterruptId) -> Option<Self> {
538        let values = self
539            .values
540            .into_vec()
541            .into_iter()
542            .filter(|wait| {
543                wait.as_interrupt()
544                    .is_none_or(|interrupt| interrupt.interrupt_id() != interrupt_id)
545            })
546            .collect::<Vec<_>>();
547        Self::from_remaining(values, self.registered_at)
548    }
549
550    fn without_timer(self, timer_id: TimerId) -> Option<Self> {
551        let values = self
552            .values
553            .into_vec()
554            .into_iter()
555            .filter(|wait| {
556                wait.as_timer()
557                    .is_none_or(|timer| timer.timer_id() != timer_id)
558            })
559            .collect::<Vec<_>>();
560        Self::from_remaining(values, self.registered_at)
561    }
562
563    fn from_remaining(values: Vec<RunWait>, registered_at: Timestamp) -> Option<Self> {
564        if values.is_empty() {
565            None
566        } else {
567            Some(Self {
568                values: values.into_boxed_slice(),
569                registered_at,
570            })
571        }
572    }
573}
574
575impl fmt::Debug for RunWaits {
576    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
577        formatter
578            .debug_struct("RunWaits")
579            .field("count", &self.len())
580            .field("registered_at", &self.registered_at)
581            .finish_non_exhaustive()
582    }
583}
584
585impl Serialize for RunWaits {
586    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
587    where
588        S: Serializer,
589    {
590        self.values.serialize(serializer)
591    }
592}
593
594impl<'de> Deserialize<'de> for RunWaits {
595    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
596    where
597        D: Deserializer<'de>,
598    {
599        deserializer.deserialize_seq(RunWaitsVisitor)
600    }
601}
602
603struct RunWaitsVisitor;
604
605impl<'de> de::Visitor<'de> for RunWaitsVisitor {
606    type Value = RunWaits;
607
608    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
609        write!(
610            formatter,
611            "one to {} unique run wait conditions registered together",
612            RunWaits::MAX_LEN
613        )
614    }
615
616    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
617    where
618        A: de::SeqAccess<'de>,
619    {
620        let mut values = Vec::with_capacity(
621            sequence
622                .size_hint()
623                .unwrap_or_default()
624                .min(RunWaits::MAX_LEN),
625        );
626        while let Some(value) = sequence.next_element::<RunWait>()? {
627            if values.len() == RunWaits::MAX_LEN {
628                return Err(de::Error::custom(RunWaitsError::TooMany {
629                    maximum: RunWaits::MAX_LEN,
630                    actual: RunWaits::MAX_LEN + 1,
631                }));
632            }
633            if values
634                .iter()
635                .any(|existing: &RunWait| existing.identity_uuid() == value.identity_uuid())
636            {
637                return Err(de::Error::custom(RunWaitsError::DuplicateIdentity));
638            }
639            values.push(value);
640        }
641        RunWaits::try_new(values).map_err(de::Error::custom)
642    }
643}
644
645impl JsonSchema for RunWaits {
646    fn schema_name() -> std::borrow::Cow<'static, str> {
647        "RunWaits".into()
648    }
649
650    fn schema_id() -> std::borrow::Cow<'static, str> {
651        concat!(module_path!(), "::RunWaits").into()
652    }
653
654    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
655        json_schema!({
656            "type": "array",
657            "items": generator.subschema_for::<RunWait>(),
658            "minItems": 1,
659            "maxItems": 64,
660            "uniqueItems": true,
661            "description": "Stable ordered outstanding conditions. UUID identity uniqueness and the common registration timestamp are enforced at runtime."
662        })
663    }
664}
665
666/// Invalid batch of run wait conditions.
667#[derive(Clone, Debug, Eq, Error, PartialEq)]
668#[non_exhaustive]
669pub enum RunWaitsError {
670    /// A waiting transition supplied no condition.
671    #[error("a waiting run must have at least one unresolved condition")]
672    Empty,
673    /// The hard simultaneous-condition ceiling was exceeded.
674    #[error("run has {actual} wait conditions; hard maximum is {maximum}")]
675    TooMany {
676        /// Absolute simultaneous-condition ceiling.
677        maximum: usize,
678        /// First observed count beyond the ceiling.
679        actual: usize,
680    },
681    /// Two wait variants reused the same UUID identity.
682    #[error("run wait condition identities must be globally unique")]
683    DuplicateIdentity,
684    /// One atomic wait registration contained multiple clock observations.
685    #[error("wait registration time {actual} does not match batch time {expected}")]
686    MixedRegistrationTimes {
687        /// Registration observation established by the first condition.
688        expected: Timestamp,
689        /// Rejected later condition observation.
690        actual: Timestamp,
691    },
692}
693
694/// Non-cancellation terminal failure with complete cumulative usage.
695#[derive(Clone, JsonSchema, Serialize)]
696#[serde(deny_unknown_fields)]
697pub struct RunFailure {
698    failure: Failure,
699    completed_at: Timestamp,
700    usage: BudgetUsage,
701}
702
703impl RunFailure {
704    /// Constructs a non-cancellation terminal failure.
705    ///
706    /// # Errors
707    ///
708    /// Returns [`RunFailureError::CancellationRequiresCancellationPath`] when
709    /// a cancellation-category failure tries to bypass the two-phase path.
710    pub fn new(
711        failure: Failure,
712        completed_at: Timestamp,
713        usage: BudgetUsage,
714    ) -> Result<Self, RunFailureError> {
715        if failure.category() == FailureCategory::Cancelled {
716            return Err(RunFailureError::CancellationRequiresCancellationPath);
717        }
718        Ok(Self {
719            failure,
720            completed_at,
721            usage,
722        })
723    }
724
725    /// Returns the public terminal failure.
726    #[must_use]
727    pub const fn failure(&self) -> &Failure {
728        &self.failure
729    }
730
731    /// Returns the durable clock observation at terminal commit.
732    #[must_use]
733    pub const fn completed_at(&self) -> Timestamp {
734        self.completed_at
735    }
736
737    /// Returns complete cumulative usage at terminal commit.
738    #[must_use]
739    pub const fn usage(&self) -> &BudgetUsage {
740        &self.usage
741    }
742
743    /// Consumes the terminal record into its durable components.
744    #[must_use]
745    pub fn into_parts(self) -> (Failure, Timestamp, BudgetUsage) {
746        (self.failure, self.completed_at, self.usage)
747    }
748}
749
750impl fmt::Debug for RunFailure {
751    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
752        formatter
753            .debug_struct("RunFailure")
754            .field("failure", &self.failure)
755            .field("completed_at", &self.completed_at)
756            .field("usage_recorded", &true)
757            .finish_non_exhaustive()
758    }
759}
760
761impl<'de> Deserialize<'de> for RunFailure {
762    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
763    where
764        D: Deserializer<'de>,
765    {
766        #[derive(Deserialize)]
767        #[serde(deny_unknown_fields)]
768        struct Wire {
769            failure: Failure,
770            completed_at: Timestamp,
771            usage: BudgetUsage,
772        }
773
774        let wire = Wire::deserialize(deserializer)?;
775        Self::new(wire.failure, wire.completed_at, wire.usage).map_err(de::Error::custom)
776    }
777}
778
779/// Invalid failure supplied to the ordinary failed terminal state.
780#[derive(Clone, Debug, Eq, Error, PartialEq)]
781#[non_exhaustive]
782pub enum RunFailureError {
783    /// A cancellation failure attempted to skip cancellation intent.
784    #[error(
785        "cancelled failures must use request-cancellation and confirm-cancellation transitions"
786    )]
787    CancellationRequiresCancellationPath,
788}
789
790/// Immutable cancellation intent committed before cooperative cleanup.
791///
792/// Once this value enters the lifecycle, only terminal cancellation may
793/// follow. The original failure occurrence is retained unchanged so a later
794/// acknowledgement cannot substitute a different reason.
795#[derive(Clone, JsonSchema, Serialize)]
796#[serde(deny_unknown_fields)]
797pub struct RunCancellationRequest {
798    failure: Failure,
799    requested_at: Timestamp,
800}
801
802impl RunCancellationRequest {
803    /// Constructs terminal-intent metadata from a non-retryable cancellation.
804    ///
805    /// # Errors
806    ///
807    /// Returns [`RunCancellationError`] unless the failure category is
808    /// `Cancelled` and its explicit retry advice is `Never`.
809    pub fn new(failure: Failure, requested_at: Timestamp) -> Result<Self, RunCancellationError> {
810        if failure.category() != FailureCategory::Cancelled {
811            return Err(RunCancellationError::CategoryNotCancelled {
812                actual: failure.category(),
813            });
814        }
815        if failure.retry_advice() != RetryAdvice::Never {
816            return Err(RunCancellationError::RetryAdviceNotNever {
817                actual: failure.retry_advice(),
818            });
819        }
820        Ok(Self {
821            failure,
822            requested_at,
823        })
824    }
825
826    /// Returns the immutable cancellation failure occurrence.
827    #[must_use]
828    pub const fn failure(&self) -> &Failure {
829        &self.failure
830    }
831
832    /// Returns the durable clock observation when cancellation won admission.
833    #[must_use]
834    pub const fn requested_at(&self) -> Timestamp {
835        self.requested_at
836    }
837}
838
839impl fmt::Debug for RunCancellationRequest {
840    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
841        formatter
842            .debug_struct("RunCancellationRequest")
843            .field("failure", &self.failure)
844            .field("requested_at", &self.requested_at)
845            .finish_non_exhaustive()
846    }
847}
848
849impl<'de> Deserialize<'de> for RunCancellationRequest {
850    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
851    where
852        D: Deserializer<'de>,
853    {
854        #[derive(Deserialize)]
855        #[serde(deny_unknown_fields)]
856        struct Wire {
857            failure: Failure,
858            requested_at: Timestamp,
859        }
860
861        let wire = Wire::deserialize(deserializer)?;
862        Self::new(wire.failure, wire.requested_at).map_err(de::Error::custom)
863    }
864}
865
866/// Terminal acknowledgement of an earlier immutable cancellation request.
867#[derive(Clone, JsonSchema, Serialize)]
868#[serde(deny_unknown_fields)]
869pub struct RunCancellation {
870    request: RunCancellationRequest,
871    completed_at: Timestamp,
872    usage: BudgetUsage,
873}
874
875impl RunCancellation {
876    /// Constructs a terminal cancellation acknowledgement.
877    ///
878    /// # Errors
879    ///
880    /// Returns [`RunCancellationError::CompletionBeforeRequest`] when the
881    /// completion observation precedes committed cancellation intent.
882    pub fn new(
883        request: RunCancellationRequest,
884        completed_at: Timestamp,
885        usage: BudgetUsage,
886    ) -> Result<Self, RunCancellationError> {
887        if completed_at < request.requested_at() {
888            return Err(RunCancellationError::CompletionBeforeRequest {
889                requested_at: request.requested_at(),
890                completed_at,
891            });
892        }
893        Ok(Self {
894            request,
895            completed_at,
896            usage,
897        })
898    }
899
900    /// Returns the exact cancellation request that won the race.
901    #[must_use]
902    pub const fn request(&self) -> &RunCancellationRequest {
903        &self.request
904    }
905
906    /// Returns the durable clock observation at terminal acknowledgement.
907    #[must_use]
908    pub const fn completed_at(&self) -> Timestamp {
909        self.completed_at
910    }
911
912    /// Returns complete cumulative usage at terminal acknowledgement.
913    #[must_use]
914    pub const fn usage(&self) -> &BudgetUsage {
915        &self.usage
916    }
917
918    /// Consumes the terminal record into its durable components.
919    #[must_use]
920    pub fn into_parts(self) -> (RunCancellationRequest, Timestamp, BudgetUsage) {
921        (self.request, self.completed_at, self.usage)
922    }
923}
924
925impl fmt::Debug for RunCancellation {
926    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
927        formatter
928            .debug_struct("RunCancellation")
929            .field("request", &self.request)
930            .field("completed_at", &self.completed_at)
931            .field("usage_recorded", &true)
932            .finish_non_exhaustive()
933    }
934}
935
936impl<'de> Deserialize<'de> for RunCancellation {
937    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
938    where
939        D: Deserializer<'de>,
940    {
941        #[derive(Deserialize)]
942        #[serde(deny_unknown_fields)]
943        struct Wire {
944            request: RunCancellationRequest,
945            completed_at: Timestamp,
946            usage: BudgetUsage,
947        }
948
949        let wire = Wire::deserialize(deserializer)?;
950        Self::new(wire.request, wire.completed_at, wire.usage).map_err(de::Error::custom)
951    }
952}
953
954/// Invalid cancellation intent or acknowledgement.
955#[derive(Clone, Debug, Eq, Error, PartialEq)]
956#[non_exhaustive]
957pub enum RunCancellationError {
958    /// Cancellation intent used a non-cancellation failure category.
959    #[error("cancellation request failure category is {actual:?}; expected cancelled")]
960    CategoryNotCancelled {
961        /// Rejected semantic category.
962        actual: FailureCategory,
963    },
964    /// Cancellation intent suggested another attempt.
965    #[error("cancellation request retry advice is {actual:?}; expected never")]
966    RetryAdviceNotNever {
967        /// Rejected recovery advice.
968        actual: RetryAdvice,
969    },
970    /// Terminal acknowledgement preceded the request observation.
971    #[error("cancellation completed at {completed_at} before request at {requested_at}")]
972    CompletionBeforeRequest {
973        /// Durable cancellation-request observation.
974        requested_at: Timestamp,
975        /// Rejected terminal observation.
976        completed_at: Timestamp,
977    },
978}
979
980#[derive(Clone, Deserialize, JsonSchema, Serialize)]
981#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
982enum RunState {
983    Pending,
984    Active {
985        activated_at: Timestamp,
986    },
987    Waiting {
988        waits: RunWaits,
989        changed_at: Timestamp,
990    },
991    CancellationRequested {
992        request: RunCancellationRequest,
993    },
994    Succeeded {
995        result: AgentResult,
996    },
997    Failed {
998        failure: RunFailure,
999    },
1000    Cancelled {
1001        cancellation: RunCancellation,
1002    },
1003}
1004
1005impl RunState {
1006    const fn status(&self) -> RunStatus {
1007        match self {
1008            Self::Pending => RunStatus::Pending,
1009            Self::Active { .. } => RunStatus::Active,
1010            Self::Waiting { .. } => RunStatus::Waiting,
1011            Self::CancellationRequested { .. } => RunStatus::CancellationRequested,
1012            Self::Succeeded { .. } => RunStatus::Succeeded,
1013            Self::Failed { .. } => RunStatus::Failed,
1014            Self::Cancelled { .. } => RunStatus::Cancelled,
1015        }
1016    }
1017
1018    const fn changed_at(&self, admitted_at: Timestamp) -> Timestamp {
1019        match self {
1020            Self::Pending => admitted_at,
1021            Self::Active { activated_at } => *activated_at,
1022            Self::Waiting { changed_at, .. } => *changed_at,
1023            Self::CancellationRequested { request } => request.requested_at(),
1024            Self::Succeeded { result } => result.completed_at(),
1025            Self::Failed { failure } => failure.completed_at(),
1026            Self::Cancelled { cancellation } => cancellation.completed_at(),
1027        }
1028    }
1029}
1030
1031/// Immutable snapshot of one admitted run's protocol-neutral business state.
1032///
1033/// Use [`Self::apply`] to obtain the next snapshot. The operation consumes the
1034/// old value, checks the closed transition graph and timestamps, and increments
1035/// the optimistic revision exactly once. Durable runtimes still perform the
1036/// transition and journal append atomically under an expected revision and a
1037/// valid fencing epoch.
1038#[derive(Clone, JsonSchema, Serialize)]
1039#[serde(deny_unknown_fields)]
1040pub struct RunLifecycle {
1041    provenance: AgentResultProvenance,
1042    admitted_at: Timestamp,
1043    revision: RunRevision,
1044    state: RunState,
1045}
1046
1047impl RunLifecycle {
1048    /// Creates the initial pending snapshot after admission has committed.
1049    #[must_use]
1050    pub const fn admitted(provenance: AgentResultProvenance, admitted_at: Timestamp) -> Self {
1051        Self {
1052            provenance,
1053            admitted_at,
1054            revision: RunRevision::ZERO,
1055            state: RunState::Pending,
1056        }
1057    }
1058
1059    /// Returns trusted tenant, run, thread, invocation, and agent identity.
1060    #[must_use]
1061    pub const fn provenance(&self) -> &AgentResultProvenance {
1062        &self.provenance
1063    }
1064
1065    /// Returns the durable clock observation at admission commit.
1066    #[must_use]
1067    pub const fn admitted_at(&self) -> Timestamp {
1068        self.admitted_at
1069    }
1070
1071    /// Returns the current optimistic lifecycle revision.
1072    #[must_use]
1073    pub const fn revision(&self) -> RunRevision {
1074        self.revision
1075    }
1076
1077    /// Returns the stable status projection.
1078    #[must_use]
1079    pub const fn status(&self) -> RunStatus {
1080        self.state.status()
1081    }
1082
1083    /// Returns the most recent committed lifecycle observation.
1084    #[must_use]
1085    pub const fn changed_at(&self) -> Timestamp {
1086        self.state.changed_at(self.admitted_at)
1087    }
1088
1089    /// Returns outstanding conditions only while waiting.
1090    #[must_use]
1091    pub const fn waits(&self) -> Option<&RunWaits> {
1092        match &self.state {
1093            RunState::Waiting { waits, .. } => Some(waits),
1094            _ => None,
1095        }
1096    }
1097
1098    /// Returns cancellation intent while requested or terminally cancelled.
1099    #[must_use]
1100    pub const fn cancellation_request(&self) -> Option<&RunCancellationRequest> {
1101        match &self.state {
1102            RunState::CancellationRequested { request } => Some(request),
1103            RunState::Cancelled { cancellation } => Some(cancellation.request()),
1104            _ => None,
1105        }
1106    }
1107
1108    /// Returns the successful terminal result, if committed.
1109    #[must_use]
1110    pub const fn result(&self) -> Option<&AgentResult> {
1111        match &self.state {
1112            RunState::Succeeded { result } => Some(result),
1113            _ => None,
1114        }
1115    }
1116
1117    /// Returns the terminal failure occurrence for failed or cancelled runs.
1118    #[must_use]
1119    pub const fn terminal_failure(&self) -> Option<&Failure> {
1120        match &self.state {
1121            RunState::Failed { failure } => Some(failure.failure()),
1122            RunState::Cancelled { cancellation } => Some(cancellation.request().failure()),
1123            _ => None,
1124        }
1125    }
1126
1127    /// Returns terminal cumulative usage for any completed outcome.
1128    #[must_use]
1129    pub const fn terminal_usage(&self) -> Option<&BudgetUsage> {
1130        match &self.state {
1131            RunState::Succeeded { result } => Some(result.usage()),
1132            RunState::Failed { failure } => Some(failure.usage()),
1133            RunState::Cancelled { cancellation } => Some(cancellation.usage()),
1134            _ => None,
1135        }
1136    }
1137
1138    /// Applies one intrinsically valid lifecycle transition.
1139    ///
1140    /// A successful result is rebound to the trusted run provenance here.
1141    /// Before a durable terminal commit, the runtime must also call
1142    /// [`AgentResult::validate_for`] with the exact admitted request,
1143    /// descriptor snapshot, resolved budget, and digest-pinned schema
1144    /// validation result. Those values intentionally are not duplicated in
1145    /// every lifecycle snapshot.
1146    ///
1147    /// # Errors
1148    ///
1149    /// Returns [`RunTransitionError`] for a transition outside the closed
1150    /// graph, a regressing clock, a stale/expired resolution, an early timer,
1151    /// substituted result provenance, or revision overflow.
1152    pub fn apply(self, transition: RunTransition) -> Result<Self, RunTransitionError> {
1153        let status = self.status();
1154        let transition_kind = transition.kind();
1155        if !transition_allowed(status, transition_kind) {
1156            return Err(RunTransitionError::InvalidTransition {
1157                status,
1158                transition: transition_kind,
1159            });
1160        }
1161
1162        let changed_at = transition.changed_at();
1163        let previous = self.changed_at();
1164        if changed_at < previous {
1165            return Err(RunTransitionError::ClockRegression {
1166                previous,
1167                actual: changed_at,
1168            });
1169        }
1170
1171        let RunLifecycle {
1172            provenance,
1173            admitted_at,
1174            revision,
1175            state,
1176        } = self;
1177        let next_state = apply_transition(&provenance, state, transition)?;
1178
1179        let revision = revision
1180            .checked_next()
1181            .ok_or(RunTransitionError::RevisionOverflow)?;
1182        Ok(Self {
1183            provenance,
1184            admitted_at,
1185            revision,
1186            state: next_state,
1187        })
1188    }
1189
1190    fn validate_snapshot(&self) -> Result<(), RunLifecycleError> {
1191        let status = self.status();
1192        if status == RunStatus::Pending && self.revision != RunRevision::ZERO {
1193            return Err(RunLifecycleError::PendingRevisionNotZero {
1194                actual: self.revision,
1195            });
1196        }
1197        if status != RunStatus::Pending && self.revision == RunRevision::ZERO {
1198            return Err(RunLifecycleError::AdvancedStateAtZeroRevision { status });
1199        }
1200
1201        let changed_at = self.changed_at();
1202        if changed_at < self.admitted_at {
1203            return Err(RunLifecycleError::StateBeforeAdmission {
1204                admitted_at: self.admitted_at,
1205                changed_at,
1206            });
1207        }
1208        if let RunState::Waiting { waits, changed_at } = &self.state {
1209            if *changed_at < waits.registered_at() {
1210                return Err(RunLifecycleError::WaitingChangeBeforeRegistration {
1211                    registered_at: waits.registered_at(),
1212                    changed_at: *changed_at,
1213                });
1214            }
1215        }
1216        if let RunState::Succeeded { result } = &self.state {
1217            if result.provenance() != &self.provenance {
1218                return Err(RunLifecycleError::ResultProvenanceMismatch {
1219                    expected: Box::new(self.provenance.clone()),
1220                    actual: Box::new(result.provenance().clone()),
1221                });
1222            }
1223        }
1224        Ok(())
1225    }
1226}
1227
1228fn apply_transition(
1229    provenance: &AgentResultProvenance,
1230    state: RunState,
1231    transition: RunTransition,
1232) -> Result<RunState, RunTransitionError> {
1233    let status = state.status();
1234    let transition_kind = transition.kind();
1235    Ok(match (state, transition) {
1236        (RunState::Pending, RunTransition::Start { started_at }) => RunState::Active {
1237            activated_at: started_at,
1238        },
1239        (RunState::Active { .. }, RunTransition::Wait { waits }) => RunState::Waiting {
1240            changed_at: waits.registered_at(),
1241            waits,
1242        },
1243        (
1244            RunState::Waiting { waits, .. },
1245            RunTransition::ResolveInterrupt {
1246                interrupt_id,
1247                resolved_at,
1248            },
1249        ) => resolve_interrupt(waits, interrupt_id, resolved_at)?,
1250        (RunState::Waiting { waits, .. }, RunTransition::FireTimer { timer_id, fired_at }) => {
1251            fire_timer(waits, timer_id, fired_at)?
1252        }
1253        (
1254            RunState::Pending | RunState::Active { .. } | RunState::Waiting { .. },
1255            RunTransition::RequestCancellation { request },
1256        ) => RunState::CancellationRequested { request },
1257        (
1258            RunState::CancellationRequested { request },
1259            RunTransition::ConfirmCancellation {
1260                completed_at,
1261                usage,
1262            },
1263        ) => RunState::Cancelled {
1264            cancellation: RunCancellation::new(request, completed_at, usage)
1265                .map_err(RunTransitionError::cancellation)?,
1266        },
1267        (RunState::Active { .. }, RunTransition::Succeed { result }) => {
1268            if result.provenance() != provenance {
1269                return Err(RunTransitionError::ResultProvenanceMismatch {
1270                    expected: Box::new(provenance.clone()),
1271                    actual: Box::new(result.provenance().clone()),
1272                });
1273            }
1274            RunState::Succeeded { result }
1275        }
1276        (
1277            RunState::Pending | RunState::Active { .. } | RunState::Waiting { .. },
1278            RunTransition::Fail { failure },
1279        ) => RunState::Failed { failure },
1280        _ => {
1281            return Err(RunTransitionError::InvalidTransition {
1282                status,
1283                transition: transition_kind,
1284            });
1285        }
1286    })
1287}
1288
1289fn resolve_interrupt(
1290    waits: RunWaits,
1291    interrupt_id: InterruptId,
1292    resolved_at: Timestamp,
1293) -> Result<RunState, RunTransitionError> {
1294    let interrupt = waits
1295        .interrupt(interrupt_id)
1296        .ok_or(RunTransitionError::InterruptNotOutstanding { interrupt_id })?;
1297    if let Some(expires_at) = interrupt.expires_at() {
1298        if resolved_at >= expires_at {
1299            return Err(RunTransitionError::InterruptExpired {
1300                interrupt_id,
1301                expires_at,
1302                resolved_at,
1303            });
1304        }
1305    }
1306    Ok(match waits.without_interrupt(interrupt_id) {
1307        Some(waits) => RunState::Waiting {
1308            waits,
1309            changed_at: resolved_at,
1310        },
1311        None => RunState::Active {
1312            activated_at: resolved_at,
1313        },
1314    })
1315}
1316
1317fn fire_timer(
1318    waits: RunWaits,
1319    timer_id: TimerId,
1320    fired_at: Timestamp,
1321) -> Result<RunState, RunTransitionError> {
1322    let timer = waits
1323        .timer(timer_id)
1324        .ok_or(RunTransitionError::TimerNotOutstanding { timer_id })?;
1325    if fired_at < timer.due_at() {
1326        return Err(RunTransitionError::TimerNotDue {
1327            timer_id,
1328            due_at: timer.due_at(),
1329            fired_at,
1330        });
1331    }
1332    Ok(match waits.without_timer(timer_id) {
1333        Some(waits) => RunState::Waiting {
1334            waits,
1335            changed_at: fired_at,
1336        },
1337        None => RunState::Active {
1338            activated_at: fired_at,
1339        },
1340    })
1341}
1342
1343impl fmt::Debug for RunLifecycle {
1344    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1345        formatter
1346            .debug_struct("RunLifecycle")
1347            .field("provenance", &self.provenance)
1348            .field("admitted_at", &self.admitted_at)
1349            .field("revision", &self.revision)
1350            .field("status", &self.status())
1351            .field("changed_at", &self.changed_at())
1352            .field("wait_count", &self.waits().map_or(0, RunWaits::len))
1353            .field(
1354                "has_cancellation_request",
1355                &self.cancellation_request().is_some(),
1356            )
1357            .field("has_result", &self.result().is_some())
1358            .field("has_failure", &self.terminal_failure().is_some())
1359            .field("usage_recorded", &self.terminal_usage().is_some())
1360            .finish_non_exhaustive()
1361    }
1362}
1363
1364impl<'de> Deserialize<'de> for RunLifecycle {
1365    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1366    where
1367        D: Deserializer<'de>,
1368    {
1369        #[derive(Deserialize)]
1370        #[serde(deny_unknown_fields)]
1371        struct Wire {
1372            provenance: AgentResultProvenance,
1373            admitted_at: Timestamp,
1374            revision: RunRevision,
1375            state: RunState,
1376        }
1377
1378        let wire = Wire::deserialize(deserializer)?;
1379        let lifecycle = Self {
1380            provenance: wire.provenance,
1381            admitted_at: wire.admitted_at,
1382            revision: wire.revision,
1383            state: wire.state,
1384        };
1385        lifecycle.validate_snapshot().map_err(de::Error::custom)?;
1386        Ok(lifecycle)
1387    }
1388}
1389
1390/// Intrinsically invalid serialized lifecycle snapshot.
1391#[derive(Clone, Debug, Eq, Error, PartialEq)]
1392#[non_exhaustive]
1393pub enum RunLifecycleError {
1394    /// Only the initial pending snapshot may use revision zero.
1395    #[error("pending run revision is {actual}; expected zero")]
1396    PendingRevisionNotZero {
1397        /// Rejected pending revision.
1398        actual: RunRevision,
1399    },
1400    /// An advanced state claimed to have applied no transition.
1401    #[error("run state {status:?} cannot exist at revision zero")]
1402    AdvancedStateAtZeroRevision {
1403        /// Rejected advanced status.
1404        status: RunStatus,
1405    },
1406    /// State time preceded durable admission.
1407    #[error("run state changed at {changed_at} before admission at {admitted_at}")]
1408    StateBeforeAdmission {
1409        /// Durable admission observation.
1410        admitted_at: Timestamp,
1411        /// Rejected state observation.
1412        changed_at: Timestamp,
1413    },
1414    /// A partially resolved wait claimed a change before registration.
1415    #[error("waiting state changed at {changed_at} before registration at {registered_at}")]
1416    WaitingChangeBeforeRegistration {
1417        /// Common wait registration observation.
1418        registered_at: Timestamp,
1419        /// Rejected latest change observation.
1420        changed_at: Timestamp,
1421    },
1422    /// A success snapshot substituted trusted run identity.
1423    #[error("successful result provenance does not match admitted run provenance")]
1424    ResultProvenanceMismatch {
1425        /// Trusted admission provenance.
1426        expected: Box<AgentResultProvenance>,
1427        /// Rejected result provenance.
1428        actual: Box<AgentResultProvenance>,
1429    },
1430}
1431
1432/// Stable name of an attempted lifecycle transition.
1433#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
1434#[serde(rename_all = "snake_case")]
1435pub enum RunTransitionKind {
1436    /// Start semantic execution after admission.
1437    Start,
1438    /// Suspend on a non-empty atomic condition batch.
1439    Wait,
1440    /// Commit one authorized interrupt resolution.
1441    ResolveInterrupt,
1442    /// Commit one timer firing at or after its due instant.
1443    FireTimer,
1444    /// Commit cancellation intent and block ordinary terminal outcomes.
1445    RequestCancellation,
1446    /// Acknowledge the already committed cancellation request.
1447    ConfirmCancellation,
1448    /// Commit a validated successful result.
1449    Succeed,
1450    /// Commit a non-cancellation terminal failure.
1451    Fail,
1452}
1453
1454/// One immutable input to the pure run lifecycle state machine.
1455#[derive(Clone, Deserialize, JsonSchema, Serialize)]
1456#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
1457pub enum RunTransition {
1458    /// Start an admitted pending run.
1459    Start {
1460        /// Durable execution-start observation.
1461        started_at: Timestamp,
1462    },
1463    /// Suspend an active run on one atomic condition batch.
1464    Wait {
1465        /// Non-empty, bounded outstanding conditions.
1466        waits: RunWaits,
1467    },
1468    /// Resolve exactly one outstanding unexpired interrupt.
1469    ResolveInterrupt {
1470        /// Exact interrupt selected by the durable resolution record.
1471        interrupt_id: InterruptId,
1472        /// Durable resolution observation.
1473        resolved_at: Timestamp,
1474    },
1475    /// Fire exactly one outstanding timer no earlier than its due instant.
1476    FireTimer {
1477        /// Exact durable timer selected by the scheduler.
1478        timer_id: TimerId,
1479        /// Durable firing observation.
1480        fired_at: Timestamp,
1481    },
1482    /// Commit immutable cancellation intent.
1483    RequestCancellation {
1484        /// Validated, non-retryable cancellation request.
1485        request: RunCancellationRequest,
1486    },
1487    /// Acknowledge cancellation after cooperative cleanup or enforced stop.
1488    ConfirmCancellation {
1489        /// Durable terminal observation.
1490        completed_at: Timestamp,
1491        /// Complete cumulative usage at terminal acknowledgement.
1492        usage: BudgetUsage,
1493    },
1494    /// Commit a successful agent result.
1495    Succeed {
1496        /// Intrinsically valid result; runtime context validation remains required.
1497        result: AgentResult,
1498    },
1499    /// Commit a non-cancellation terminal failure.
1500    Fail {
1501        /// Validated failure and complete cumulative usage.
1502        failure: RunFailure,
1503    },
1504}
1505
1506impl RunTransition {
1507    /// Returns the stable transition name.
1508    #[must_use]
1509    pub const fn kind(&self) -> RunTransitionKind {
1510        match self {
1511            Self::Start { .. } => RunTransitionKind::Start,
1512            Self::Wait { .. } => RunTransitionKind::Wait,
1513            Self::ResolveInterrupt { .. } => RunTransitionKind::ResolveInterrupt,
1514            Self::FireTimer { .. } => RunTransitionKind::FireTimer,
1515            Self::RequestCancellation { .. } => RunTransitionKind::RequestCancellation,
1516            Self::ConfirmCancellation { .. } => RunTransitionKind::ConfirmCancellation,
1517            Self::Succeed { .. } => RunTransitionKind::Succeed,
1518            Self::Fail { .. } => RunTransitionKind::Fail,
1519        }
1520    }
1521
1522    const fn changed_at(&self) -> Timestamp {
1523        match self {
1524            Self::Start { started_at } => *started_at,
1525            Self::Wait { waits } => waits.registered_at(),
1526            Self::ResolveInterrupt { resolved_at, .. } => *resolved_at,
1527            Self::FireTimer { fired_at, .. } => *fired_at,
1528            Self::RequestCancellation { request } => request.requested_at(),
1529            Self::ConfirmCancellation { completed_at, .. } => *completed_at,
1530            Self::Succeed { result } => result.completed_at(),
1531            Self::Fail { failure } => failure.completed_at(),
1532        }
1533    }
1534}
1535
1536impl fmt::Debug for RunTransition {
1537    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1538        let mut debug = formatter.debug_struct("RunTransition");
1539        debug.field("kind", &self.kind());
1540        match self {
1541            Self::Start { started_at } => {
1542                debug.field("changed_at", started_at);
1543            }
1544            Self::Wait { waits } => {
1545                debug
1546                    .field("changed_at", &waits.registered_at())
1547                    .field("wait_count", &waits.len());
1548            }
1549            Self::ResolveInterrupt {
1550                interrupt_id,
1551                resolved_at,
1552            } => {
1553                debug
1554                    .field("interrupt_id", interrupt_id)
1555                    .field("changed_at", resolved_at);
1556            }
1557            Self::FireTimer { timer_id, fired_at } => {
1558                debug
1559                    .field("timer_id", timer_id)
1560                    .field("changed_at", fired_at);
1561            }
1562            Self::RequestCancellation { request } => {
1563                debug
1564                    .field("failure", request.failure())
1565                    .field("changed_at", &request.requested_at());
1566            }
1567            Self::ConfirmCancellation { completed_at, .. } => {
1568                debug
1569                    .field("changed_at", completed_at)
1570                    .field("usage_recorded", &true);
1571            }
1572            Self::Succeed { result } => {
1573                debug
1574                    .field("result", result)
1575                    .field("changed_at", &result.completed_at());
1576            }
1577            Self::Fail { failure } => {
1578                debug
1579                    .field("failure", failure.failure())
1580                    .field("changed_at", &failure.completed_at())
1581                    .field("usage_recorded", &true);
1582            }
1583        }
1584        debug.finish_non_exhaustive()
1585    }
1586}
1587
1588const fn transition_allowed(status: RunStatus, transition: RunTransitionKind) -> bool {
1589    matches!(
1590        (status, transition),
1591        (RunStatus::Pending, RunTransitionKind::Start)
1592            | (
1593                RunStatus::Pending | RunStatus::Active | RunStatus::Waiting,
1594                RunTransitionKind::RequestCancellation | RunTransitionKind::Fail
1595            )
1596            | (
1597                RunStatus::Active,
1598                RunTransitionKind::Wait | RunTransitionKind::Succeed
1599            )
1600            | (
1601                RunStatus::Waiting,
1602                RunTransitionKind::ResolveInterrupt | RunTransitionKind::FireTimer
1603            )
1604            | (
1605                RunStatus::CancellationRequested,
1606                RunTransitionKind::ConfirmCancellation
1607            )
1608    )
1609}
1610
1611/// Rejected pure lifecycle transition.
1612#[derive(Clone, Debug, Eq, Error, PartialEq)]
1613#[non_exhaustive]
1614pub enum RunTransitionError {
1615    /// The current state has no edge for this transition.
1616    #[error("transition {transition:?} is invalid from run state {status:?}")]
1617    InvalidTransition {
1618        /// Current lifecycle status.
1619        status: RunStatus,
1620        /// Rejected transition kind.
1621        transition: RunTransitionKind,
1622    },
1623    /// A transition clock observation moved backward.
1624    #[error("transition time {actual} precedes current state time {previous}")]
1625    ClockRegression {
1626        /// Latest committed lifecycle observation.
1627        previous: Timestamp,
1628        /// Rejected transition observation.
1629        actual: Timestamp,
1630    },
1631    /// An interrupt resolution named no currently outstanding marker.
1632    #[error("interrupt {interrupt_id} is not outstanding for this run")]
1633    InterruptNotOutstanding {
1634        /// Stale, duplicate, or unrelated interrupt identifier.
1635        interrupt_id: InterruptId,
1636    },
1637    /// An interrupt resolution arrived at or after exclusive expiry.
1638    #[error(
1639        "interrupt {interrupt_id} expired at {expires_at}; resolution arrived at {resolved_at}"
1640    )]
1641    InterruptExpired {
1642        /// Exact expired interrupt identifier.
1643        interrupt_id: InterruptId,
1644        /// Exclusive expiry observation.
1645        expires_at: Timestamp,
1646        /// Rejected resolution observation.
1647        resolved_at: Timestamp,
1648    },
1649    /// A firing named no currently outstanding timer.
1650    #[error("timer {timer_id} is not outstanding for this run")]
1651    TimerNotOutstanding {
1652        /// Stale, duplicate, or unrelated timer identifier.
1653        timer_id: TimerId,
1654    },
1655    /// A timer firing preceded its inclusive due instant.
1656    #[error("timer {timer_id} is due at {due_at}; firing arrived at {fired_at}")]
1657    TimerNotDue {
1658        /// Exact early timer identifier.
1659        timer_id: TimerId,
1660        /// Inclusive earliest firing instant.
1661        due_at: Timestamp,
1662        /// Rejected firing observation.
1663        fired_at: Timestamp,
1664    },
1665    /// A successful result substituted trusted run identity.
1666    #[error("successful result provenance does not match admitted run provenance")]
1667    ResultProvenanceMismatch {
1668        /// Trusted admission provenance.
1669        expected: Box<AgentResultProvenance>,
1670        /// Rejected result provenance.
1671        actual: Box<AgentResultProvenance>,
1672    },
1673    /// Cancellation acknowledgement was intrinsically invalid.
1674    #[error("terminal cancellation is invalid: {source}")]
1675    Cancellation {
1676        /// Underlying cancellation timing failure.
1677        #[source]
1678        source: RunCancellationError,
1679    },
1680    /// No next optimistic revision can be represented.
1681    #[error("run lifecycle revision overflowed")]
1682    RevisionOverflow,
1683}
1684
1685impl RunTransitionError {
1686    const fn cancellation(source: RunCancellationError) -> Self {
1687        Self::Cancellation { source }
1688    }
1689}
1690
1691#[cfg(test)]
1692mod tests {
1693    use super::*;
1694    use crate::{FailureCode, FailureId, FailureMessage, FailureOrigin, RunId, TenantId, ThreadId};
1695    use proptest::{collection, prelude::*};
1696    use serde_json::{Value, from_value, json, to_value};
1697
1698    fn at(offset_micros: i64) -> Timestamp {
1699        let base = "2030-01-01T00:00:00.000000Z".parse::<Timestamp>().unwrap();
1700        Timestamp::from_unix_micros(base.unix_micros() + offset_micros).unwrap()
1701    }
1702
1703    fn canonical_runtime_fixture() -> Value {
1704        serde_json::from_str(include_str!("../tests/fixtures/core-agent-runtime-v1.json")).unwrap()
1705    }
1706
1707    fn provenance() -> AgentResultProvenance {
1708        let fixture = canonical_runtime_fixture();
1709        from_value(fixture["result_provenances"]["valid"][0].clone()).unwrap()
1710    }
1711
1712    fn other_provenance() -> AgentResultProvenance {
1713        let mut value = to_value(provenance()).unwrap();
1714        value["invocation_id"] = Value::from("01912345-6789-7abc-8def-0123456789bf");
1715        from_value(value).unwrap()
1716    }
1717
1718    fn result_at(completed_at: Timestamp, provenance: &AgentResultProvenance) -> AgentResult {
1719        let fixture = canonical_runtime_fixture();
1720        let mut value = fixture["results"]["valid"][0].clone();
1721        value["completed_at"] = Value::from(completed_at.to_string());
1722        value["provenance"] = to_value(provenance).unwrap();
1723        from_value(value).unwrap()
1724    }
1725
1726    fn failure(category: FailureCategory, advice: RetryAdvice) -> Failure {
1727        Failure::new(
1728            FailureId::generate(),
1729            category,
1730            "runtime.test".parse::<FailureCode>().unwrap(),
1731            "stateknot.runtime".parse::<FailureOrigin>().unwrap(),
1732            "The run reached a tested terminal condition."
1733                .parse::<FailureMessage>()
1734                .unwrap(),
1735            advice,
1736        )
1737        .unwrap()
1738    }
1739
1740    fn cancellation_request(requested_at: Timestamp) -> RunCancellationRequest {
1741        RunCancellationRequest::new(
1742            failure(FailureCategory::Cancelled, RetryAdvice::Never),
1743            requested_at,
1744        )
1745        .unwrap()
1746    }
1747
1748    fn ordinary_failure(completed_at: Timestamp) -> RunFailure {
1749        RunFailure::new(
1750            failure(FailureCategory::Internal, RetryAdvice::Never),
1751            completed_at,
1752            BudgetUsage::zero(),
1753        )
1754        .unwrap()
1755    }
1756
1757    fn interrupt(
1758        interrupt_id: InterruptId,
1759        requested_at: Timestamp,
1760        expires_at: Timestamp,
1761    ) -> RunInterrupt {
1762        RunInterrupt::new(
1763            interrupt_id,
1764            RunInterruptKind::Approval,
1765            requested_at,
1766            Some(expires_at),
1767        )
1768        .unwrap()
1769    }
1770
1771    fn timer(timer_id: TimerId, scheduled_at: Timestamp, due_at: Timestamp) -> RunTimer {
1772        RunTimer::new(timer_id, RunTimerKind::Sleep, scheduled_at, due_at).unwrap()
1773    }
1774
1775    #[test]
1776    fn admission_is_the_only_pending_zero_revision_snapshot() {
1777        let lifecycle = RunLifecycle::admitted(provenance(), at(0));
1778        assert_eq!(lifecycle.status(), RunStatus::Pending);
1779        assert_eq!(lifecycle.revision(), RunRevision::ZERO);
1780        assert_eq!(lifecycle.admitted_at(), at(0));
1781        assert_eq!(lifecycle.changed_at(), at(0));
1782        assert!(!lifecycle.status().is_terminal());
1783        assert!(lifecycle.waits().is_none());
1784        assert!(lifecycle.cancellation_request().is_none());
1785        assert!(lifecycle.result().is_none());
1786        assert!(lifecycle.terminal_failure().is_none());
1787        assert!(lifecycle.terminal_usage().is_none());
1788
1789        let wire = to_value(&lifecycle).unwrap();
1790        assert_eq!(wire["revision"], "0");
1791        assert_eq!(wire["state"], json!({"kind": "pending"}));
1792        assert_eq!(
1793            from_value::<RunLifecycle>(wire).unwrap().status(),
1794            RunStatus::Pending
1795        );
1796    }
1797
1798    #[test]
1799    fn multiple_waits_resolve_independently_and_resume_only_when_empty() {
1800        let interrupt_id = InterruptId::generate();
1801        let timer_id = TimerId::generate();
1802        let lifecycle = RunLifecycle::admitted(provenance(), at(0))
1803            .apply(RunTransition::Start { started_at: at(1) })
1804            .unwrap()
1805            .apply(RunTransition::Wait {
1806                waits: RunWaits::try_new([
1807                    RunWait::interrupt(interrupt(interrupt_id, at(2), at(8))),
1808                    RunWait::timer(timer(timer_id, at(2), at(6))),
1809                ])
1810                .unwrap(),
1811            })
1812            .unwrap();
1813
1814        assert_eq!(lifecycle.status(), RunStatus::Waiting);
1815        assert_eq!(lifecycle.revision(), RunRevision::new(2));
1816        assert_eq!(lifecycle.waits().unwrap().len(), 2);
1817
1818        let lifecycle = lifecycle
1819            .apply(RunTransition::ResolveInterrupt {
1820                interrupt_id,
1821                resolved_at: at(4),
1822            })
1823            .unwrap();
1824        assert_eq!(lifecycle.status(), RunStatus::Waiting);
1825        assert_eq!(lifecycle.changed_at(), at(4));
1826        assert_eq!(lifecycle.waits().unwrap().len(), 1);
1827        assert!(lifecycle.waits().unwrap().interrupt(interrupt_id).is_none());
1828        assert!(lifecycle.waits().unwrap().timer(timer_id).is_some());
1829
1830        let lifecycle = lifecycle
1831            .apply(RunTransition::FireTimer {
1832                timer_id,
1833                fired_at: at(6),
1834            })
1835            .unwrap();
1836        assert_eq!(lifecycle.status(), RunStatus::Active);
1837        assert_eq!(lifecycle.changed_at(), at(6));
1838        assert_eq!(lifecycle.revision(), RunRevision::new(4));
1839        assert!(lifecycle.waits().is_none());
1840    }
1841
1842    #[test]
1843    fn interrupt_expiry_is_exclusive_and_stale_resolution_is_rejected() {
1844        let interrupt_id = InterruptId::generate();
1845        let lifecycle = RunLifecycle::admitted(provenance(), at(0))
1846            .apply(RunTransition::Start { started_at: at(1) })
1847            .unwrap()
1848            .apply(RunTransition::Wait {
1849                waits: RunWaits::try_new([RunWait::interrupt(interrupt(
1850                    interrupt_id,
1851                    at(2),
1852                    at(5),
1853                ))])
1854                .unwrap(),
1855            })
1856            .unwrap();
1857
1858        assert_eq!(
1859            lifecycle
1860                .clone()
1861                .apply(RunTransition::ResolveInterrupt {
1862                    interrupt_id,
1863                    resolved_at: at(5),
1864                })
1865                .unwrap_err(),
1866            RunTransitionError::InterruptExpired {
1867                interrupt_id,
1868                expires_at: at(5),
1869                resolved_at: at(5),
1870            }
1871        );
1872        assert!(
1873            lifecycle
1874                .apply(RunTransition::ResolveInterrupt {
1875                    interrupt_id: InterruptId::generate(),
1876                    resolved_at: at(4),
1877                })
1878                .is_err()
1879        );
1880    }
1881
1882    #[test]
1883    fn timers_cannot_fire_early_or_twice() {
1884        let timer_id = TimerId::generate();
1885        let lifecycle = RunLifecycle::admitted(provenance(), at(0))
1886            .apply(RunTransition::Start { started_at: at(1) })
1887            .unwrap()
1888            .apply(RunTransition::Wait {
1889                waits: RunWaits::try_new([RunWait::timer(timer(timer_id, at(2), at(7)))]).unwrap(),
1890            })
1891            .unwrap();
1892
1893        assert_eq!(
1894            lifecycle
1895                .clone()
1896                .apply(RunTransition::FireTimer {
1897                    timer_id,
1898                    fired_at: at(6),
1899                })
1900                .unwrap_err(),
1901            RunTransitionError::TimerNotDue {
1902                timer_id,
1903                due_at: at(7),
1904                fired_at: at(6),
1905            }
1906        );
1907
1908        let active = lifecycle
1909            .apply(RunTransition::FireTimer {
1910                timer_id,
1911                fired_at: at(7),
1912            })
1913            .unwrap();
1914        assert_eq!(active.status(), RunStatus::Active);
1915        assert_eq!(
1916            active
1917                .apply(RunTransition::FireTimer {
1918                    timer_id,
1919                    fired_at: at(8),
1920                })
1921                .unwrap_err(),
1922            RunTransitionError::InvalidTransition {
1923                status: RunStatus::Active,
1924                transition: RunTransitionKind::FireTimer,
1925            }
1926        );
1927    }
1928
1929    #[test]
1930    fn wait_batches_are_non_empty_bounded_unique_and_atomic() {
1931        assert_eq!(RunWaits::try_new([]), Err(RunWaitsError::Empty));
1932
1933        let duplicate = uuid::Uuid::now_v7();
1934        let interrupt_id = InterruptId::from_uuid(duplicate).unwrap();
1935        let timer_id = TimerId::from_uuid(duplicate).unwrap();
1936        assert_eq!(
1937            RunWaits::try_new([
1938                RunWait::interrupt(interrupt(interrupt_id, at(1), at(4))),
1939                RunWait::timer(timer(timer_id, at(1), at(4))),
1940            ]),
1941            Err(RunWaitsError::DuplicateIdentity)
1942        );
1943
1944        assert_eq!(
1945            RunWaits::try_new([
1946                RunWait::interrupt(interrupt(InterruptId::generate(), at(1), at(4))),
1947                RunWait::timer(timer(TimerId::generate(), at(2), at(4))),
1948            ]),
1949            Err(RunWaitsError::MixedRegistrationTimes {
1950                expected: at(1),
1951                actual: at(2),
1952            })
1953        );
1954
1955        let too_many = (0..=RunWaits::MAX_LEN)
1956            .map(|_| RunWait::timer(timer(TimerId::generate(), at(1), at(4))));
1957        assert_eq!(
1958            RunWaits::try_new(too_many),
1959            Err(RunWaitsError::TooMany {
1960                maximum: RunWaits::MAX_LEN,
1961                actual: RunWaits::MAX_LEN + 1,
1962            })
1963        );
1964    }
1965
1966    #[test]
1967    fn wait_marker_constructors_reject_non_future_boundaries() {
1968        assert_eq!(
1969            RunInterrupt::new(
1970                InterruptId::generate(),
1971                RunInterruptKind::Input,
1972                at(3),
1973                Some(at(3)),
1974            ),
1975            Err(RunInterruptError::ExpiryNotAfterRequest {
1976                requested_at: at(3),
1977                expires_at: at(3),
1978            })
1979        );
1980        assert_eq!(
1981            RunTimer::new(
1982                TimerId::generate(),
1983                RunTimerKind::RetryBackoff,
1984                at(3),
1985                at(2),
1986            ),
1987            Err(RunTimerError::DueNotAfterSchedule {
1988                scheduled_at: at(3),
1989                due_at: at(2),
1990            })
1991        );
1992    }
1993
1994    #[test]
1995    fn cancellation_request_wins_over_every_uncommitted_outcome() {
1996        let provenance = provenance();
1997        let lifecycle = RunLifecycle::admitted(provenance.clone(), at(0))
1998            .apply(RunTransition::Start { started_at: at(1) })
1999            .unwrap()
2000            .apply(RunTransition::RequestCancellation {
2001                request: cancellation_request(at(2)),
2002            })
2003            .unwrap();
2004
2005        assert_eq!(lifecycle.status(), RunStatus::CancellationRequested);
2006        assert!(lifecycle.cancellation_request().is_some());
2007        assert_eq!(
2008            lifecycle
2009                .clone()
2010                .apply(RunTransition::Succeed {
2011                    result: result_at(at(3), &provenance),
2012                })
2013                .unwrap_err(),
2014            RunTransitionError::InvalidTransition {
2015                status: RunStatus::CancellationRequested,
2016                transition: RunTransitionKind::Succeed,
2017            }
2018        );
2019        assert_eq!(
2020            lifecycle
2021                .clone()
2022                .apply(RunTransition::Fail {
2023                    failure: ordinary_failure(at(3)),
2024                })
2025                .unwrap_err(),
2026            RunTransitionError::InvalidTransition {
2027                status: RunStatus::CancellationRequested,
2028                transition: RunTransitionKind::Fail,
2029            }
2030        );
2031
2032        let cancelled = lifecycle
2033            .apply(RunTransition::ConfirmCancellation {
2034                completed_at: at(4),
2035                usage: BudgetUsage::zero(),
2036            })
2037            .unwrap();
2038        assert_eq!(cancelled.status(), RunStatus::Cancelled);
2039        assert!(cancelled.status().is_terminal());
2040        assert_eq!(
2041            cancelled.terminal_failure().unwrap().category(),
2042            FailureCategory::Cancelled
2043        );
2044        assert!(cancelled.terminal_usage().is_some());
2045        assert!(cancelled.result().is_none());
2046        assert!(
2047            cancelled
2048                .apply(RunTransition::RequestCancellation {
2049                    request: cancellation_request(at(5)),
2050                })
2051                .is_err()
2052        );
2053    }
2054
2055    #[test]
2056    fn a_committed_success_wins_over_late_cancellation() {
2057        let provenance = provenance();
2058        let succeeded = RunLifecycle::admitted(provenance.clone(), at(0))
2059            .apply(RunTransition::Start { started_at: at(1) })
2060            .unwrap()
2061            .apply(RunTransition::Succeed {
2062                result: result_at(at(2), &provenance),
2063            })
2064            .unwrap();
2065        assert_eq!(succeeded.status(), RunStatus::Succeeded);
2066        assert!(succeeded.result().is_some());
2067        assert!(succeeded.terminal_failure().is_none());
2068        assert!(succeeded.terminal_usage().is_some());
2069        assert_eq!(
2070            succeeded
2071                .apply(RunTransition::RequestCancellation {
2072                    request: cancellation_request(at(3)),
2073                })
2074                .unwrap_err(),
2075            RunTransitionError::InvalidTransition {
2076                status: RunStatus::Succeeded,
2077                transition: RunTransitionKind::RequestCancellation,
2078            }
2079        );
2080    }
2081
2082    #[test]
2083    fn success_must_match_trusted_admission_provenance() {
2084        let expected = provenance();
2085        let actual = other_provenance();
2086        let error = RunLifecycle::admitted(expected.clone(), at(0))
2087            .apply(RunTransition::Start { started_at: at(1) })
2088            .unwrap()
2089            .apply(RunTransition::Succeed {
2090                result: result_at(at(2), &actual),
2091            })
2092            .unwrap_err();
2093        assert_eq!(
2094            error,
2095            RunTransitionError::ResultProvenanceMismatch {
2096                expected: Box::new(expected),
2097                actual: Box::new(actual),
2098            }
2099        );
2100    }
2101
2102    #[test]
2103    fn ordinary_failure_cannot_smuggle_cancellation() {
2104        assert_eq!(
2105            RunFailure::new(
2106                failure(FailureCategory::Cancelled, RetryAdvice::Never),
2107                at(1),
2108                BudgetUsage::zero(),
2109            )
2110            .unwrap_err(),
2111            RunFailureError::CancellationRequiresCancellationPath
2112        );
2113        assert_eq!(
2114            RunCancellationRequest::new(
2115                failure(FailureCategory::Internal, RetryAdvice::Never),
2116                at(1),
2117            )
2118            .unwrap_err(),
2119            RunCancellationError::CategoryNotCancelled {
2120                actual: FailureCategory::Internal,
2121            }
2122        );
2123    }
2124
2125    #[test]
2126    fn lifecycle_clock_never_moves_backward() {
2127        let lifecycle = RunLifecycle::admitted(provenance(), at(5));
2128        assert_eq!(
2129            lifecycle
2130                .apply(RunTransition::Start { started_at: at(4) })
2131                .unwrap_err(),
2132            RunTransitionError::ClockRegression {
2133                previous: at(5),
2134                actual: at(4),
2135            }
2136        );
2137    }
2138
2139    #[test]
2140    fn snapshot_deserialization_rejects_unreachable_cross_field_states() {
2141        let pending = RunLifecycle::admitted(provenance(), at(2));
2142        let mut value = to_value(&pending).unwrap();
2143        value["revision"] = Value::from("1");
2144        assert!(from_value::<RunLifecycle>(value).is_err());
2145
2146        let mut value = to_value(&pending).unwrap();
2147        value["state"] = json!({"kind": "active", "activated_at": at(2).to_string()});
2148        assert!(from_value::<RunLifecycle>(value).is_err());
2149
2150        let active = pending
2151            .clone()
2152            .apply(RunTransition::Start { started_at: at(3) })
2153            .unwrap();
2154        let mut value = to_value(active).unwrap();
2155        value["state"]["activated_at"] = Value::from(at(1).to_string());
2156        assert!(from_value::<RunLifecycle>(value).is_err());
2157
2158        let mut succeeded = to_value(
2159            RunLifecycle::admitted(provenance(), at(0))
2160                .apply(RunTransition::Start { started_at: at(1) })
2161                .unwrap()
2162                .apply(RunTransition::Succeed {
2163                    result: result_at(at(2), &provenance()),
2164                })
2165                .unwrap(),
2166        )
2167        .unwrap();
2168        succeeded["state"]["result"]["provenance"] = to_value(other_provenance()).unwrap();
2169        assert!(from_value::<RunLifecycle>(succeeded).is_err());
2170    }
2171
2172    #[test]
2173    fn wire_contracts_are_closed_and_revalidate_nested_values() {
2174        assert!(
2175            from_value::<RunInterrupt>(json!({
2176                "interrupt_id": InterruptId::generate().to_string(),
2177                "kind": "input",
2178                "requested_at": at(1).to_string(),
2179                "expires_at": at(2).to_string(),
2180                "payload": {}
2181            }))
2182            .is_err()
2183        );
2184        assert!(
2185            from_value::<RunTransition>(json!({
2186                "kind": "start",
2187                "started_at": at(1).to_string(),
2188                "extra": true
2189            }))
2190            .is_err()
2191        );
2192        assert!(from_value::<RunTransition>(json!({"kind": "unknown"})).is_err());
2193        assert!(from_value::<RunWaits>(json!([])).is_err());
2194    }
2195
2196    #[test]
2197    fn revision_overflow_fails_closed() {
2198        let active = RunLifecycle::admitted(provenance(), at(0))
2199            .apply(RunTransition::Start { started_at: at(1) })
2200            .unwrap();
2201        let mut value = to_value(active).unwrap();
2202        value["revision"] = Value::from(u64::MAX.to_string());
2203        let active = from_value::<RunLifecycle>(value).unwrap();
2204        assert_eq!(
2205            active
2206                .apply(RunTransition::Fail {
2207                    failure: ordinary_failure(at(2)),
2208                })
2209                .unwrap_err(),
2210            RunTransitionError::RevisionOverflow
2211        );
2212    }
2213
2214    fn transition_for(
2215        action: u8,
2216        lifecycle: &RunLifecycle,
2217        observed_at: Timestamp,
2218    ) -> RunTransition {
2219        match action {
2220            0 => RunTransition::Start {
2221                started_at: observed_at,
2222            },
2223            1 => RunTransition::Wait {
2224                waits: RunWaits::try_new([
2225                    RunWait::interrupt(interrupt(
2226                        InterruptId::generate(),
2227                        observed_at,
2228                        Timestamp::from_unix_micros(observed_at.unix_micros() + 10).unwrap(),
2229                    )),
2230                    RunWait::timer(timer(
2231                        TimerId::generate(),
2232                        observed_at,
2233                        Timestamp::from_unix_micros(observed_at.unix_micros() + 2).unwrap(),
2234                    )),
2235                ])
2236                .unwrap(),
2237            },
2238            2 => RunTransition::ResolveInterrupt {
2239                interrupt_id: lifecycle
2240                    .waits()
2241                    .and_then(|waits| waits.iter().find_map(RunWait::as_interrupt))
2242                    .map_or_else(InterruptId::generate, RunInterrupt::interrupt_id),
2243                resolved_at: observed_at,
2244            },
2245            3 => {
2246                let timer = lifecycle
2247                    .waits()
2248                    .and_then(|waits| waits.iter().find_map(RunWait::as_timer));
2249                RunTransition::FireTimer {
2250                    timer_id: timer.map_or_else(TimerId::generate, RunTimer::timer_id),
2251                    fired_at: timer.map_or(observed_at, RunTimer::due_at).max(observed_at),
2252                }
2253            }
2254            4 => RunTransition::RequestCancellation {
2255                request: cancellation_request(observed_at),
2256            },
2257            5 => RunTransition::ConfirmCancellation {
2258                completed_at: observed_at,
2259                usage: BudgetUsage::zero(),
2260            },
2261            6 => RunTransition::Succeed {
2262                result: result_at(observed_at, lifecycle.provenance()),
2263            },
2264            _ => RunTransition::Fail {
2265                failure: ordinary_failure(observed_at),
2266            },
2267        }
2268    }
2269
2270    proptest! {
2271        #[test]
2272        fn randomized_state_machine_never_skips_revision_or_revives_terminal_state(
2273            actions in collection::vec(0_u8..8, 0..128),
2274        ) {
2275            let mut lifecycle = RunLifecycle::admitted(provenance(), at(0));
2276            for (index, action) in actions.into_iter().enumerate() {
2277                let observed_at = at(i64::try_from(index + 1).unwrap());
2278                let previous_status = lifecycle.status();
2279                let previous_revision = lifecycle.revision();
2280                let previous_wire = to_value(&lifecycle).unwrap();
2281                let transition = transition_for(action, &lifecycle, observed_at);
2282                match lifecycle.clone().apply(transition) {
2283                    Ok(next) => {
2284                        prop_assert_eq!(next.revision().get(), previous_revision.get() + 1);
2285                        prop_assert!(next.changed_at() >= lifecycle.changed_at());
2286                        prop_assert!(!previous_status.is_terminal());
2287                        lifecycle = next;
2288                    }
2289                    Err(_) => {
2290                        prop_assert_eq!(to_value(&lifecycle).unwrap(), previous_wire);
2291                    }
2292                }
2293                if previous_status.is_terminal() {
2294                    prop_assert_eq!(lifecycle.status(), previous_status);
2295                }
2296            }
2297        }
2298    }
2299
2300    #[test]
2301    fn timer_id_is_a_strict_uuid_v7_wire_type() {
2302        let id = TimerId::generate();
2303        let wire = serde_json::to_string(&id).unwrap();
2304        assert_eq!(serde_json::from_str::<TimerId>(&wire).unwrap(), id);
2305        assert!(
2306            serde_json::from_str::<TimerId>(r#""550e8400-e29b-41d4-a716-446655440000""#).is_err()
2307        );
2308
2309        let run_id: RunId = "01912345-6789-7abc-8def-0123456789ae".parse().unwrap();
2310        let thread_id: ThreadId = "01912345-6789-7abc-8def-0123456789af".parse().unwrap();
2311        let tenant: TenantId = "tenant-production".parse().unwrap();
2312        assert_eq!(run_id.to_string().len(), 36);
2313        assert_eq!(thread_id.to_string().len(), 36);
2314        assert_eq!(tenant.as_str(), "tenant-production");
2315    }
2316}