1use 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#[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 pub const ZERO: Self = Self(ExecutionCount::ZERO);
47
48 pub const MAX: Self = Self(ExecutionCount::MAX);
50
51 #[must_use]
53 pub const fn new(value: u64) -> Self {
54 Self(ExecutionCount::new(value))
55 }
56
57 #[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#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
79#[serde(rename_all = "snake_case")]
80pub enum RunStatus {
81 Pending,
83 Active,
85 Waiting,
87 CancellationRequested,
89 Succeeded,
91 Failed,
93 Cancelled,
95}
96
97impl RunStatus {
98 #[must_use]
100 pub const fn is_terminal(self) -> bool {
101 matches!(self, Self::Succeeded | Self::Failed | Self::Cancelled)
102 }
103}
104
105#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
107#[serde(rename_all = "snake_case")]
108pub enum RunInterruptKind {
109 Approval,
111 Input,
113 Authentication,
115 ExternalSignal,
117 Reconciliation,
119}
120
121#[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 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 #[must_use]
171 pub const fn interrupt_id(&self) -> InterruptId {
172 self.interrupt_id
173 }
174
175 #[must_use]
177 pub const fn kind(&self) -> RunInterruptKind {
178 self.kind
179 }
180
181 #[must_use]
183 pub const fn requested_at(&self) -> Timestamp {
184 self.requested_at
185 }
186
187 #[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#[derive(Clone, Debug, Eq, Error, PartialEq)]
233#[non_exhaustive]
234pub enum RunInterruptError {
235 #[error("interrupt expiry {expires_at} must be later than request {requested_at}")]
237 ExpiryNotAfterRequest {
238 requested_at: Timestamp,
240 expires_at: Timestamp,
242 },
243}
244
245#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
247#[serde(rename_all = "snake_case")]
248pub enum RunTimerKind {
249 Sleep,
251 RetryBackoff,
253}
254
255#[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 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 #[must_use]
294 pub const fn timer_id(&self) -> TimerId {
295 self.timer_id
296 }
297
298 #[must_use]
300 pub const fn kind(&self) -> RunTimerKind {
301 self.kind
302 }
303
304 #[must_use]
306 pub const fn scheduled_at(&self) -> Timestamp {
307 self.scheduled_at
308 }
309
310 #[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#[derive(Clone, Debug, Eq, Error, PartialEq)]
351#[non_exhaustive]
352pub enum RunTimerError {
353 #[error("timer due instant {due_at} must be later than schedule {scheduled_at}")]
355 DueNotAfterSchedule {
356 scheduled_at: Timestamp,
358 due_at: Timestamp,
360 },
361}
362
363#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
365#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
366pub enum RunWait {
367 Interrupt {
369 interrupt: RunInterrupt,
371 },
372 Timer {
374 timer: RunTimer,
376 },
377}
378
379impl RunWait {
380 #[must_use]
382 pub const fn interrupt(interrupt: RunInterrupt) -> Self {
383 Self::Interrupt { interrupt }
384 }
385
386 #[must_use]
388 pub const fn timer(timer: RunTimer) -> Self {
389 Self::Timer { timer }
390 }
391
392 #[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 #[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#[derive(Clone, Eq, PartialEq)]
432pub struct RunWaits {
433 values: Box<[RunWait]>,
434 registered_at: Timestamp,
435}
436
437impl RunWaits {
438 pub const MAX_LEN: usize = 64;
440
441 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 #[must_use]
489 pub const fn len(&self) -> usize {
490 self.values.len()
491 }
492
493 #[must_use]
498 pub const fn is_empty(&self) -> bool {
499 self.values.is_empty()
500 }
501
502 #[must_use]
504 pub const fn registered_at(&self) -> Timestamp {
505 self.registered_at
506 }
507
508 pub fn iter(&self) -> impl ExactSizeIterator<Item = &RunWait> {
510 self.values.iter()
511 }
512
513 #[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 #[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 #[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#[derive(Clone, Debug, Eq, Error, PartialEq)]
668#[non_exhaustive]
669pub enum RunWaitsError {
670 #[error("a waiting run must have at least one unresolved condition")]
672 Empty,
673 #[error("run has {actual} wait conditions; hard maximum is {maximum}")]
675 TooMany {
676 maximum: usize,
678 actual: usize,
680 },
681 #[error("run wait condition identities must be globally unique")]
683 DuplicateIdentity,
684 #[error("wait registration time {actual} does not match batch time {expected}")]
686 MixedRegistrationTimes {
687 expected: Timestamp,
689 actual: Timestamp,
691 },
692}
693
694#[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 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 #[must_use]
727 pub const fn failure(&self) -> &Failure {
728 &self.failure
729 }
730
731 #[must_use]
733 pub const fn completed_at(&self) -> Timestamp {
734 self.completed_at
735 }
736
737 #[must_use]
739 pub const fn usage(&self) -> &BudgetUsage {
740 &self.usage
741 }
742
743 #[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#[derive(Clone, Debug, Eq, Error, PartialEq)]
781#[non_exhaustive]
782pub enum RunFailureError {
783 #[error(
785 "cancelled failures must use request-cancellation and confirm-cancellation transitions"
786 )]
787 CancellationRequiresCancellationPath,
788}
789
790#[derive(Clone, JsonSchema, Serialize)]
796#[serde(deny_unknown_fields)]
797pub struct RunCancellationRequest {
798 failure: Failure,
799 requested_at: Timestamp,
800}
801
802impl RunCancellationRequest {
803 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 #[must_use]
828 pub const fn failure(&self) -> &Failure {
829 &self.failure
830 }
831
832 #[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#[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 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 #[must_use]
902 pub const fn request(&self) -> &RunCancellationRequest {
903 &self.request
904 }
905
906 #[must_use]
908 pub const fn completed_at(&self) -> Timestamp {
909 self.completed_at
910 }
911
912 #[must_use]
914 pub const fn usage(&self) -> &BudgetUsage {
915 &self.usage
916 }
917
918 #[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#[derive(Clone, Debug, Eq, Error, PartialEq)]
956#[non_exhaustive]
957pub enum RunCancellationError {
958 #[error("cancellation request failure category is {actual:?}; expected cancelled")]
960 CategoryNotCancelled {
961 actual: FailureCategory,
963 },
964 #[error("cancellation request retry advice is {actual:?}; expected never")]
966 RetryAdviceNotNever {
967 actual: RetryAdvice,
969 },
970 #[error("cancellation completed at {completed_at} before request at {requested_at}")]
972 CompletionBeforeRequest {
973 requested_at: Timestamp,
975 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#[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 #[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 #[must_use]
1061 pub const fn provenance(&self) -> &AgentResultProvenance {
1062 &self.provenance
1063 }
1064
1065 #[must_use]
1067 pub const fn admitted_at(&self) -> Timestamp {
1068 self.admitted_at
1069 }
1070
1071 #[must_use]
1073 pub const fn revision(&self) -> RunRevision {
1074 self.revision
1075 }
1076
1077 #[must_use]
1079 pub const fn status(&self) -> RunStatus {
1080 self.state.status()
1081 }
1082
1083 #[must_use]
1085 pub const fn changed_at(&self) -> Timestamp {
1086 self.state.changed_at(self.admitted_at)
1087 }
1088
1089 #[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 #[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 #[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 #[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 #[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 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#[derive(Clone, Debug, Eq, Error, PartialEq)]
1392#[non_exhaustive]
1393pub enum RunLifecycleError {
1394 #[error("pending run revision is {actual}; expected zero")]
1396 PendingRevisionNotZero {
1397 actual: RunRevision,
1399 },
1400 #[error("run state {status:?} cannot exist at revision zero")]
1402 AdvancedStateAtZeroRevision {
1403 status: RunStatus,
1405 },
1406 #[error("run state changed at {changed_at} before admission at {admitted_at}")]
1408 StateBeforeAdmission {
1409 admitted_at: Timestamp,
1411 changed_at: Timestamp,
1413 },
1414 #[error("waiting state changed at {changed_at} before registration at {registered_at}")]
1416 WaitingChangeBeforeRegistration {
1417 registered_at: Timestamp,
1419 changed_at: Timestamp,
1421 },
1422 #[error("successful result provenance does not match admitted run provenance")]
1424 ResultProvenanceMismatch {
1425 expected: Box<AgentResultProvenance>,
1427 actual: Box<AgentResultProvenance>,
1429 },
1430}
1431
1432#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
1434#[serde(rename_all = "snake_case")]
1435pub enum RunTransitionKind {
1436 Start,
1438 Wait,
1440 ResolveInterrupt,
1442 FireTimer,
1444 RequestCancellation,
1446 ConfirmCancellation,
1448 Succeed,
1450 Fail,
1452}
1453
1454#[derive(Clone, Deserialize, JsonSchema, Serialize)]
1456#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
1457pub enum RunTransition {
1458 Start {
1460 started_at: Timestamp,
1462 },
1463 Wait {
1465 waits: RunWaits,
1467 },
1468 ResolveInterrupt {
1470 interrupt_id: InterruptId,
1472 resolved_at: Timestamp,
1474 },
1475 FireTimer {
1477 timer_id: TimerId,
1479 fired_at: Timestamp,
1481 },
1482 RequestCancellation {
1484 request: RunCancellationRequest,
1486 },
1487 ConfirmCancellation {
1489 completed_at: Timestamp,
1491 usage: BudgetUsage,
1493 },
1494 Succeed {
1496 result: AgentResult,
1498 },
1499 Fail {
1501 failure: RunFailure,
1503 },
1504}
1505
1506impl RunTransition {
1507 #[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#[derive(Clone, Debug, Eq, Error, PartialEq)]
1613#[non_exhaustive]
1614pub enum RunTransitionError {
1615 #[error("transition {transition:?} is invalid from run state {status:?}")]
1617 InvalidTransition {
1618 status: RunStatus,
1620 transition: RunTransitionKind,
1622 },
1623 #[error("transition time {actual} precedes current state time {previous}")]
1625 ClockRegression {
1626 previous: Timestamp,
1628 actual: Timestamp,
1630 },
1631 #[error("interrupt {interrupt_id} is not outstanding for this run")]
1633 InterruptNotOutstanding {
1634 interrupt_id: InterruptId,
1636 },
1637 #[error(
1639 "interrupt {interrupt_id} expired at {expires_at}; resolution arrived at {resolved_at}"
1640 )]
1641 InterruptExpired {
1642 interrupt_id: InterruptId,
1644 expires_at: Timestamp,
1646 resolved_at: Timestamp,
1648 },
1649 #[error("timer {timer_id} is not outstanding for this run")]
1651 TimerNotOutstanding {
1652 timer_id: TimerId,
1654 },
1655 #[error("timer {timer_id} is due at {due_at}; firing arrived at {fired_at}")]
1657 TimerNotDue {
1658 timer_id: TimerId,
1660 due_at: Timestamp,
1662 fired_at: Timestamp,
1664 },
1665 #[error("successful result provenance does not match admitted run provenance")]
1667 ResultProvenanceMismatch {
1668 expected: Box<AgentResultProvenance>,
1670 actual: Box<AgentResultProvenance>,
1672 },
1673 #[error("terminal cancellation is invalid: {source}")]
1675 Cancellation {
1676 #[source]
1678 source: RunCancellationError,
1679 },
1680 #[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}