tatara_process/lifetime_clock.rs
1//! Ephemeral lifetime clock — TTL expiry + teardown-policy decisions.
2//!
3//! The reconciler consults this module at each phase tick to decide
4//! whether a Process should auto-terminate:
5//! - TTL is measured from `metadata.creation_timestamp` (the most
6//! deterministic anchor — phaseSince resets per phase).
7//! - Teardown policy applies on `Attested` or `Failed` per
8//! `EphemeralLifetime.teardown_policy`.
9//!
10//! Returning `AutoTerminate::Now { reason }` tells the caller to transition
11//! the Process to `Exiting`. The phase machine handles the SIGTERM path
12//! from there (children drained, finalizer guards owned resources).
13
14use chrono::{DateTime, Utc};
15use std::fmt;
16use std::time::Duration;
17
18use crate::crd::Process;
19use crate::lifetime::TeardownPolicy;
20use crate::phase::ProcessPhase;
21
22/// Decision the phase machine acts on.
23///
24/// Two-variant payload-carrying enum: `Skip` carries no payload (no-op
25/// signal to the controller), `Now` carries the typed [`TerminateReason`]
26/// that the controller stamps onto `status.message`. The
27/// (payload-carrying-enum, payload-stripped-typed-discriminator) split
28/// — `Now(reason)` on the wire-shape, [`AutoTerminateKind::Now`] for
29/// closed dispatch — is the same shape every sibling closed-set lift
30/// in this crate carries (see [`crate::lifetime_clock::TerminateReason`]
31/// → [`TerminateReasonKind`], [`crate::matrix::SelectStrategy`] →
32/// [`crate::matrix::SelectStrategyKind`]).
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum AutoTerminate {
35 /// No auto-terminate signal — continue with the normal phase handler.
36 Skip,
37 /// Transition the Process to `Exiting` with the given operator-visible reason.
38 Now { reason: TerminateReason },
39}
40
41impl AutoTerminate {
42 /// Discriminator projection — strips the [`Now`]-variant payload and
43 /// returns the closed-set kind. Used by the kind-sweep tests and by
44 /// any future consumer that groups decisions by category (metrics
45 /// labels, dashboard enumeration, `status.conditions[].reason`
46 /// reason-keys) without pattern-matching the full payload.
47 ///
48 /// [`Now`]: AutoTerminate::Now
49 pub const fn kind(&self) -> AutoTerminateKind {
50 match self {
51 Self::Skip => AutoTerminateKind::Skip,
52 Self::Now { .. } => AutoTerminateKind::Now,
53 }
54 }
55
56 /// Reason projection — `Some(&reason)` when the decision is
57 /// [`Now`], `None` when [`Skip`]. The closed-set predicate dual:
58 /// callers that need only the payload (e.g. to stamp
59 /// `status.message`) reach through this projection instead of the
60 /// inline `if let AutoTerminate::Now { reason } = …` destructure,
61 /// so the variant-name → payload-field binding lives at ONE site.
62 /// Adding a third payload-carrying variant in the future updates
63 /// every consumer through this method's exhaustiveness check
64 /// rather than scattering destructures across the call graph.
65 ///
66 /// [`Now`]: AutoTerminate::Now
67 /// [`Skip`]: AutoTerminate::Skip
68 pub const fn reason(&self) -> Option<&TerminateReason> {
69 match self {
70 Self::Skip => None,
71 Self::Now { reason } => Some(reason),
72 }
73 }
74
75 /// `true` iff the decision is [`Now`]. Symmetric to [`Self::is_skip`].
76 ///
77 /// [`Now`]: AutoTerminate::Now
78 pub const fn is_now(&self) -> bool {
79 matches!(self, Self::Now { .. })
80 }
81
82 /// `true` iff the decision is [`Skip`]. Symmetric to [`Self::is_now`].
83 ///
84 /// [`Skip`]: AutoTerminate::Skip
85 pub const fn is_skip(&self) -> bool {
86 matches!(self, Self::Skip)
87 }
88}
89
90/// The closed set of [`AutoTerminate`] kinds — the discriminator view,
91/// payload-stripped, that sibling closed-set enums in this crate carry
92/// (see [`TerminateReasonKind`], [`crate::matrix::SelectStrategyKind`],
93/// [`crate::lifetime::LifetimeKind`]).
94///
95/// Drives the `as_str` / Display / `FromStr` triad over [`Self::ALL`] so
96/// a new variant added with an `ALL` entry automatically extends the
97/// parser, the canonical wire-format projection, and any future
98/// metrics-label / dashboard / `status.conditions[].reason` enumeration
99/// that needs to enumerate the decision categories. The `[Self; 2]`
100/// array literal forces the arity so a third variant cannot land
101/// without bumping the constant.
102#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
103#[closed_set(via = "as_str", display, generate_unknown = "auto-terminate kind")]
104pub enum AutoTerminateKind {
105 /// The kind-view of [`AutoTerminate::Skip`].
106 Skip,
107 /// The kind-view of [`AutoTerminate::Now`] — the payload is
108 /// stripped at this projection.
109 Now,
110}
111
112impl AutoTerminateKind {
113 /// The closed set — single source of truth for `as_str` / Display /
114 /// `FromStr`.
115 pub const ALL: [Self; 2] = [Self::Skip, Self::Now];
116
117 /// Canonical PascalCase wire-format projection. Mirrors the
118 /// `tatara-process` PascalCase idiom used by every other closed-set
119 /// enum's `as_str` projection (e.g. [`ProcessPhase::as_str`],
120 /// [`TerminateReasonKind::as_str`]). A future metrics-label /
121 /// `status.conditions[].reason` field reads this projection
122 /// directly.
123 pub const fn as_str(self) -> &'static str {
124 match self {
125 Self::Skip => "Skip",
126 Self::Now => "Now",
127 }
128 }
129}
130
131// `impl fmt::Display for AutoTerminateKind` + `impl FromStr for
132// AutoTerminateKind` + `impl tatara_lisp::ClosedSet for
133// AutoTerminateKind` + `pub struct UnknownAutoTerminateKind(pub
134// String)` are generated by `#[derive(tatara_closed_set::DeriveClosedSet)]` +
135// `#[closed_set(via = "as_str", display, generate_unknown =
136// "auto-terminate kind")]` on the enum declaration above. The explicit
137// label pins the pre-lift wording (with hyphen) against the auto-
138// projection `pascal_to_spaced_lowercase("AutoTerminateKind")` →
139// "auto terminate kind" (no hyphen) — the operator-facing
140// `#[error("unknown auto-terminate kind: {0}")]` annotation stays byte-
141// for-byte identical to the pre-lift hand-roll. The inherent `as_str`
142// projection stays load-bearing — the PascalCase wire-format the
143// `evaluate` decision-projection's emitted reason reads — while the
144// trait method `label` gives generic consumers a STABLE name across
145// the workspace-wide closed-set implementors.
146
147/// Why the ephemeral lifetime clock fired.
148///
149/// Typed image of the two reason strings the pre-lift evaluator composed
150/// inline with `format!(…)`. Each variant carries the typed payload its
151/// `Display` formats against the canonical PascalCase projection of
152/// [`TeardownPolicy`] / [`ProcessPhase`], so the operator-visible reason
153/// is read off the typed surface rather than a free-form template that
154/// could drift on a variant rename. The reason string is the deliverable
155/// the reconciler stamps onto `status.message`; this enum is the source
156/// of truth.
157///
158/// Adding a third cause (e.g. parent-cascade from a SIGKILL'd parent in
159/// the hierarchical PID model, OOM-style memory-pressure pre-emption, or
160/// a future ResourceQuota gate) lands at one variant + one [`Display`]
161/// arm + one [`TerminateReasonKind`] entry — exhaustively checked by the
162/// compiler AND by the per-variant truth-table tests.
163///
164/// Sibling closed-set lifts on the same `tatara-process` axis:
165/// [`crate::intent::IntentKind::ALL`], [`crate::LifetimeKind::ALL`],
166/// [`crate::lifetime::TeardownPolicy::ALL`],
167/// [`crate::boundary::ConditionKind::ALL`],
168/// [`crate::phase::ProcessPhase::ALL`],
169/// [`crate::signal::ProcessSignal::ALL`].
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub enum TerminateReason {
172 /// The Process reached a terminal-gate phase ([`ProcessPhase::Attested`]
173 /// or [`ProcessPhase::Failed`]) and the ephemeral lifetime's
174 /// [`TeardownPolicy`] elected to fire on that phase.
175 TeardownPolicy {
176 policy: TeardownPolicy,
177 phase: ProcessPhase,
178 },
179 /// The ephemeral lifetime's TTL elapsed in a non-terminal phase.
180 /// `ttl` carries the operator-authored `humantime` string verbatim
181 /// (e.g. `"1h"`, `"30m"`) so the reason surfaces the spec field as
182 /// it was written, not as it parsed. `elapsed` is the wall-clock
183 /// distance from `metadata.creation_timestamp` at evaluation time.
184 TtlExpired { ttl: String, elapsed: Duration },
185}
186
187impl TerminateReason {
188 /// Discriminator projection — strips the payload, yielding the
189 /// closed-set kind. Used by the reason-kind sweep tests and by any
190 /// future consumer that wants to group reasons by cause without
191 /// pattern-matching the full payload (e.g. metrics labels, future
192 /// `status.conditions` reason-keys).
193 pub const fn kind(&self) -> TerminateReasonKind {
194 match self {
195 Self::TeardownPolicy { .. } => TerminateReasonKind::TeardownPolicy,
196 Self::TtlExpired { .. } => TerminateReasonKind::TtlExpired,
197 }
198 }
199}
200
201impl fmt::Display for TerminateReason {
202 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203 // LOAD-BEARING CONTRACT: the strings produced here are the
204 // operator-visible reasons the reconciler stamps onto
205 // `status.message` and `status.conditions[…].message`. They
206 // must match the pre-lift `format!(…)` output byte-for-byte
207 // so existing alerts, dashboards, and operator runbooks keep
208 // matching. Pinned by `terminate_reason_display_matches_pre_lift`.
209 match self {
210 Self::TeardownPolicy { policy, phase } => {
211 write!(
212 f,
213 "ephemeral lifetime: teardown_policy={} fired on {}",
214 policy.as_str(),
215 phase.as_str(),
216 )
217 }
218 Self::TtlExpired { ttl, elapsed } => {
219 write!(
220 f,
221 "ephemeral lifetime: ttl={} expired (elapsed={}s)",
222 ttl,
223 elapsed.as_secs(),
224 )
225 }
226 }
227 }
228}
229
230/// The closed set of [`TerminateReason`] kinds — the discriminator
231/// view, payload-stripped, that sibling closed-set enums in this
232/// crate carry (see [`ProcessPhase`], [`TeardownPolicy`]).
233///
234/// Drives the `as_str` / Display / `FromStr` triad over [`Self::ALL`] so
235/// a new variant added with an `ALL` entry automatically extends the
236/// parser, the canonical wire-format projection, and any future
237/// metrics-label / `status.conditions[].reason` enumeration that needs
238/// to enumerate the reason categories.
239#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
240#[closed_set(via = "as_str", display, generate_unknown)]
241pub enum TerminateReasonKind {
242 TeardownPolicy,
243 TtlExpired,
244}
245
246impl TerminateReasonKind {
247 /// The closed set — single source of truth for `as_str` / Display /
248 /// `FromStr`. The `[Self; 2]` array literal forces the arity so a
249 /// third variant added without an `ALL` entry fails at the type
250 /// level before the test sweep below runs.
251 pub const ALL: [Self; 2] = [Self::TeardownPolicy, Self::TtlExpired];
252
253 /// Canonical PascalCase wire-format projection. Mirrors the
254 /// `tatara-process` PascalCase idiom used by every other closed-set
255 /// enum's `as_str` projection (e.g. [`ProcessPhase::as_str`],
256 /// [`TeardownPolicy::as_str`]). A future `status.conditions[].reason`
257 /// field reads this projection directly.
258 pub const fn as_str(self) -> &'static str {
259 match self {
260 Self::TeardownPolicy => "TeardownPolicy",
261 Self::TtlExpired => "TtlExpired",
262 }
263 }
264}
265
266// `impl fmt::Display for TerminateReasonKind` + `impl FromStr for
267// TerminateReasonKind` + `impl tatara_lisp::ClosedSet for
268// TerminateReasonKind` + `pub struct UnknownTerminateReasonKind(pub
269// String)` are generated by `#[derive(tatara_closed_set::DeriveClosedSet)]` +
270// `#[closed_set(via = "as_str", display, generate_unknown)]` on the
271// enum declaration above. The auto-derived label `"terminate reason
272// kind"` matches the prior hand-rolled `#[error("unknown terminate
273// reason kind: {0}")]` verbatim. The inherent `as_str` projection
274// stays load-bearing — the PascalCase wire-format the
275// `crate::lifetime_clock::evaluate` decision-projection's emitted
276// reason reads — while the trait method `label` gives generic
277// consumers a STABLE name across the workspace-wide closed-set
278// implementors.
279
280/// Inspect a Process at the given current phase and return whether the
281/// ephemeral lifetime clock fires now.
282///
283/// `now` is injected so unit tests can drive the clock deterministically.
284pub fn evaluate(
285 process: &Process,
286 current_phase: ProcessPhase,
287 now: DateTime<Utc>,
288) -> AutoTerminate {
289 // Closed-set projection: ambiguous → no-op; permanent → no-op;
290 // ephemeral → fall through to teardown / TTL checks. ONE
291 // `as_ephemeral` gate replaces the previous two-step
292 // match-then-match dance and shares the projection with
293 // `requeue_with_ttl` below.
294 let Ok(variant) = process.spec.lifetime.variant() else {
295 return AutoTerminate::Skip;
296 };
297 let Some(ephemeral) = variant.as_ephemeral() else {
298 return AutoTerminate::Skip;
299 };
300
301 // 1. Teardown policy on terminal phases — ONE typed dispatch over
302 // `(TeardownPolicy, ProcessPhase)` replaces the previous pair of
303 // near-identical Attested/Failed branches. Non-terminal phases
304 // short-circuit inside `should_teardown_on`. The reason is the
305 // typed `TerminateReason::TeardownPolicy` variant whose `Display`
306 // composes the operator-visible string against the canonical
307 // PascalCase projection (`TeardownPolicy::as_str` +
308 // `ProcessPhase::as_str`), not a free-form template.
309 if ephemeral.teardown_policy.should_teardown_on(current_phase) {
310 return AutoTerminate::Now {
311 reason: TerminateReason::TeardownPolicy {
312 policy: ephemeral.teardown_policy,
313 phase: current_phase,
314 },
315 };
316 }
317
318 // 2. TTL expiry — applies in any non-terminal phase.
319 if !is_terminal_or_exit(current_phase) {
320 if let Some(creation) = process.metadata.creation_timestamp.as_ref() {
321 if let Ok(ttl) = humantime::parse_duration(&ephemeral.ttl) {
322 let elapsed = now.signed_duration_since(creation.0).to_std().ok();
323 if let Some(elapsed) = elapsed {
324 if elapsed >= ttl {
325 return AutoTerminate::Now {
326 reason: TerminateReason::TtlExpired {
327 ttl: ephemeral.ttl.clone(),
328 elapsed,
329 },
330 };
331 }
332 }
333 }
334 }
335 }
336
337 AutoTerminate::Skip
338}
339
340/// Phases past which TTL cannot meaningfully fire — the SIGTERM path
341/// is already in progress.
342fn is_terminal_or_exit(p: ProcessPhase) -> bool {
343 matches!(
344 p,
345 ProcessPhase::Exiting | ProcessPhase::Zombie | ProcessPhase::Reaped
346 )
347}
348
349/// Sleep budget the controller should requeue with for a Process whose
350/// `evaluate()` returned `Skip` — picks the smaller of HEARTBEAT and
351/// TTL-remaining so we don't oversleep past expiry.
352pub fn requeue_with_ttl(process: &Process, now: DateTime<Utc>, default: Duration) -> Duration {
353 // Shared `as_ephemeral` projection with [`evaluate`] — the
354 // "give me only the ephemeral case" shape lives at one site.
355 let Ok(variant) = process.spec.lifetime.variant() else {
356 return default;
357 };
358 let Some(e) = variant.as_ephemeral() else {
359 return default;
360 };
361 let Some(creation) = process.metadata.creation_timestamp.as_ref() else {
362 return default;
363 };
364 let Ok(ttl) = humantime::parse_duration(&e.ttl) else {
365 return default;
366 };
367 let elapsed = match now.signed_duration_since(creation.0).to_std() {
368 Ok(d) => d,
369 Err(_) => return default,
370 };
371 let remaining = ttl.checked_sub(elapsed).unwrap_or(Duration::from_secs(0));
372 // Never sleep less than 1s; never longer than the default heartbeat.
373 let pick = std::cmp::min(default, remaining);
374 std::cmp::max(pick, Duration::from_secs(1))
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380 use crate::classification::{Classification, ConvergencePointType, SubstrateType};
381 use crate::crd::ProcessSpec;
382 use crate::intent::{AplicacaoIntent, Intent};
383 use crate::lifetime::{EphemeralLifetime, Lifetime, TeardownPolicy};
384 use k8s_openapi::apimachinery::pkg::apis::meta::v1::Time;
385
386 fn ephemeral_process(ttl: &str, teardown: TeardownPolicy, age_secs: i64) -> Process {
387 let spec = ProcessSpec {
388 identity: Default::default(),
389 classification: Classification {
390 point_type: ConvergencePointType::Gate,
391 substrate: SubstrateType::Compute,
392 horizon: Default::default(),
393 calm: Default::default(),
394 data_classification: Default::default(),
395 },
396 intent: Intent {
397 aplicacao: Some(AplicacaoIntent {
398 chart_ref: "oci://x".into(),
399 version: "1".into(),
400 profile: String::new(),
401 values_overlay: serde_json::Value::Null,
402 release_name: None,
403 target_namespace: None,
404 install_timeout: None,
405 }),
406 ..Intent::default()
407 },
408 boundary: Default::default(),
409 compliance: Default::default(),
410 depends_on: vec![],
411 signals: Default::default(),
412 lifetime: Lifetime {
413 ephemeral: Some(EphemeralLifetime {
414 ttl: ttl.into(),
415 teardown_policy: teardown,
416 max_concurrent: 1,
417 exports: vec![],
418 }),
419 ..Lifetime::default()
420 },
421 routing: None,
422 encapsulates: None,
423 suspended: false,
424 };
425 let mut p = Process::new("e", spec);
426 p.metadata.namespace = Some("ns".into());
427 let creation = Utc::now() - chrono::Duration::seconds(age_secs);
428 p.metadata.creation_timestamp = Some(Time(creation));
429 p
430 }
431
432 fn permanent_process() -> Process {
433 let spec = ProcessSpec {
434 identity: Default::default(),
435 classification: Classification {
436 point_type: ConvergencePointType::Gate,
437 substrate: SubstrateType::Compute,
438 horizon: Default::default(),
439 calm: Default::default(),
440 data_classification: Default::default(),
441 },
442 intent: Intent {
443 aplicacao: Some(AplicacaoIntent {
444 chart_ref: "oci://x".into(),
445 version: "1".into(),
446 profile: String::new(),
447 values_overlay: serde_json::Value::Null,
448 release_name: None,
449 target_namespace: None,
450 install_timeout: None,
451 }),
452 ..Intent::default()
453 },
454 boundary: Default::default(),
455 compliance: Default::default(),
456 depends_on: vec![],
457 signals: Default::default(),
458 lifetime: Lifetime::default(),
459 routing: None,
460 encapsulates: None,
461 suspended: false,
462 };
463 Process::new("e", spec)
464 }
465
466 #[test]
467 fn permanent_never_auto_terminates() {
468 let p = permanent_process();
469 for phase in [
470 ProcessPhase::Pending,
471 ProcessPhase::Execing,
472 ProcessPhase::Running,
473 ProcessPhase::Attested,
474 ProcessPhase::Failed,
475 ] {
476 assert_eq!(evaluate(&p, phase, Utc::now()), AutoTerminate::Skip);
477 }
478 }
479
480 #[test]
481 fn always_teardown_fires_on_attested_and_failed() {
482 let p = ephemeral_process("1h", TeardownPolicy::Always, 60);
483 let now = Utc::now();
484 assert!(matches!(
485 evaluate(&p, ProcessPhase::Attested, now),
486 AutoTerminate::Now { .. }
487 ));
488 assert!(matches!(
489 evaluate(&p, ProcessPhase::Failed, now),
490 AutoTerminate::Now { .. }
491 ));
492 assert_eq!(
493 evaluate(&p, ProcessPhase::Running, now),
494 AutoTerminate::Skip
495 );
496 }
497
498 #[test]
499 fn on_attested_only_fires_on_attested() {
500 let p = ephemeral_process("1h", TeardownPolicy::OnAttested, 60);
501 let now = Utc::now();
502 assert!(matches!(
503 evaluate(&p, ProcessPhase::Attested, now),
504 AutoTerminate::Now { .. }
505 ));
506 assert_eq!(evaluate(&p, ProcessPhase::Failed, now), AutoTerminate::Skip);
507 }
508
509 #[test]
510 fn on_failed_only_fires_on_failed() {
511 let p = ephemeral_process("1h", TeardownPolicy::OnFailed, 60);
512 let now = Utc::now();
513 assert_eq!(
514 evaluate(&p, ProcessPhase::Attested, now),
515 AutoTerminate::Skip
516 );
517 assert!(matches!(
518 evaluate(&p, ProcessPhase::Failed, now),
519 AutoTerminate::Now { .. }
520 ));
521 }
522
523 #[test]
524 fn never_skips_phase_terminations_but_still_honors_ttl() {
525 let p = ephemeral_process("30s", TeardownPolicy::Never, 60);
526 let now = Utc::now();
527 // TTL elapsed → TTL fires regardless of policy.
528 assert!(matches!(
529 evaluate(&p, ProcessPhase::Running, now),
530 AutoTerminate::Now { .. }
531 ));
532 // But not on a terminal phase (already exiting).
533 assert_eq!(
534 evaluate(&p, ProcessPhase::Exiting, now),
535 AutoTerminate::Skip
536 );
537 }
538
539 #[test]
540 fn ttl_not_yet_elapsed_is_skip() {
541 let p = ephemeral_process("1h", TeardownPolicy::Never, 60);
542 assert_eq!(
543 evaluate(&p, ProcessPhase::Running, Utc::now()),
544 AutoTerminate::Skip
545 );
546 }
547
548 /// REASON-STRING CONTRACT: the operator-visible reason composes
549 /// the canonical PascalCase projection of `TeardownPolicy` and
550 /// `ProcessPhase` (via Display) rather than the Debug formatting
551 /// used pre-lift. A future variant rename of either enum updates
552 /// the reason string at ONE site (the `as_str` arm) instead of
553 /// drifting between the typed surface and the operator log.
554 #[test]
555 fn teardown_reason_string_uses_canonical_projection() {
556 let p = ephemeral_process("1h", TeardownPolicy::OnAttested, 60);
557 match evaluate(&p, ProcessPhase::Attested, Utc::now()) {
558 AutoTerminate::Now { reason } => {
559 let rendered = reason.to_string();
560 assert!(
561 rendered.contains("teardown_policy=OnAttested"),
562 "expected canonical PascalCase policy, got: {rendered}",
563 );
564 assert!(
565 rendered.contains("fired on Attested"),
566 "expected canonical PascalCase phase, got: {rendered}",
567 );
568 }
569 other => panic!("expected AutoTerminate::Now, got {other:?}"),
570 }
571
572 let p = ephemeral_process("1h", TeardownPolicy::Always, 60);
573 match evaluate(&p, ProcessPhase::Failed, Utc::now()) {
574 AutoTerminate::Now { reason } => {
575 let rendered = reason.to_string();
576 assert!(rendered.contains("teardown_policy=Always"));
577 assert!(rendered.contains("fired on Failed"));
578 }
579 other => panic!("expected AutoTerminate::Now, got {other:?}"),
580 }
581 }
582
583 // ── TerminateReason / TerminateReasonKind closed-set contracts ────
584
585 /// BYTE-FOR-BYTE PRE-LIFT CONTRACT: the Display impl on
586 /// `TerminateReason` must produce the exact string the pre-lift
587 /// inline `format!(…)` calls produced. Existing alerts, dashboards,
588 /// and operator runbooks that grep `status.message` for these
589 /// substrings keep matching. A future variant rename of
590 /// `TeardownPolicy` / `ProcessPhase` updates the rendered string
591 /// here automatically (Display reads `as_str` projection), but the
592 /// template — `"ephemeral lifetime: teardown_policy={} fired on {}"`
593 /// vs `"ephemeral lifetime: ttl={} expired (elapsed={}s)"` — is
594 /// pinned at the Display site.
595 #[test]
596 fn terminate_reason_display_matches_pre_lift() {
597 // TeardownPolicy variant — every combination of policy × phase
598 // sweeps both PascalCase projections.
599 for policy in TeardownPolicy::ALL {
600 for phase in ProcessPhase::ALL {
601 let reason = TerminateReason::TeardownPolicy { policy, phase };
602 let expected = format!(
603 "ephemeral lifetime: teardown_policy={} fired on {}",
604 policy.as_str(),
605 phase.as_str(),
606 );
607 assert_eq!(
608 reason.to_string(),
609 expected,
610 "Display drifted for ({policy:?}, {phase:?})",
611 );
612 }
613 }
614 // TtlExpired variant — pins the ttl-verbatim + elapsed-secs
615 // template against representative humantime strings the
616 // EphemeralLifetime.ttl field accepts.
617 for (ttl, elapsed_secs) in [("1h", 0u64), ("30m", 60), ("90s", 100), ("5m30s", 3600)] {
618 let reason = TerminateReason::TtlExpired {
619 ttl: ttl.to_string(),
620 elapsed: Duration::from_secs(elapsed_secs),
621 };
622 assert_eq!(
623 reason.to_string(),
624 format!("ephemeral lifetime: ttl={ttl} expired (elapsed={elapsed_secs}s)"),
625 );
626 }
627 }
628
629 /// Reason `kind()` projection — closed-set match so a future
630 /// variant triggers exhaustiveness checking at the projection
631 /// site rather than silently bucketing through a wildcard. Every
632 /// variant's `kind()` matches its `TerminateReasonKind` peer.
633 #[test]
634 fn terminate_reason_kind_truth_table() {
635 assert_eq!(
636 TerminateReason::TeardownPolicy {
637 policy: TeardownPolicy::Always,
638 phase: ProcessPhase::Attested,
639 }
640 .kind(),
641 TerminateReasonKind::TeardownPolicy,
642 );
643 assert_eq!(
644 TerminateReason::TtlExpired {
645 ttl: "1h".to_string(),
646 elapsed: Duration::from_secs(0),
647 }
648 .kind(),
649 TerminateReasonKind::TtlExpired,
650 );
651 }
652
653 /// `ALL` is the source of truth; a variant added without an `ALL`
654 /// entry fails here (uniqueness check) before any sweep test below
655 /// runs. Arity is asserted by the array type itself (`[Self; 2]`).
656 /// Exercise the substrate-wide [`tatara_lisp::ClosedSet`] contract on
657 /// [`TerminateReasonKind`] — pins the structural three-plus-one
658 /// (`ALL` is non-empty, every variant round-trips through
659 /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
660 /// outside the closed set) at ONE call site. Replaces the
661 /// hand-derived `terminate_reason_kind_all_is_unique_and_complete`
662 /// + `terminate_reason_kind_roundtrip_via_as_str` + the empty-input
663 /// arm of `unknown_terminate_reason_kind_errors`. `FromStr`
664 /// delegates to `<Self as tatara_closed_set::ClosedSet>::parse_label`,
665 /// so this helper exercises the same code path the lifetime-clock
666 /// evaluator hits when parsing a typed reason back out of a
667 /// `status.conditions[].reason` slot.
668 #[test]
669 fn terminate_reason_kind_is_well_formed_closed_set() {
670 tatara_closed_set::assert_closed_set_well_formed::<TerminateReasonKind>();
671 }
672
673 /// `Display` IS `as_str` — pinning this lets future callers reach
674 /// for either projection without drift.
675 #[test]
676 fn terminate_reason_kind_display_matches_as_str() {
677 for kind in TerminateReasonKind::ALL {
678 assert_eq!(kind.to_string(), kind.as_str());
679 }
680 }
681
682 /// Every kind's `as_str` is in canonical PascalCase. The first
683 /// character is uppercase; no whitespace; no separators. The
684 /// `tatara-process` PascalCase idiom holds at one test site.
685 #[test]
686 fn terminate_reason_kind_as_str_is_pascal_case() {
687 for kind in TerminateReasonKind::ALL {
688 let s = kind.as_str();
689 assert!(!s.is_empty(), "as_str empty for {kind:?}");
690 assert!(
691 s.chars().next().unwrap().is_ascii_uppercase(),
692 "as_str not PascalCase for {kind:?}: {s}",
693 );
694 assert!(
695 !s.contains(|c: char| c.is_whitespace() || c == '_' || c == '-'),
696 "as_str carries separator for {kind:?}: {s}",
697 );
698 }
699 }
700
701 /// `FromStr` rejects strings outside the canonical projection
702 /// (lowercased / typo / cross-axis-leaked) and echoes the input
703 /// verbatim. The empty-string arm is covered by
704 /// `terminate_reason_kind_is_well_formed_closed_set` via the
705 /// [`tatara_lisp::ClosedSet`] contract; the verbatim-echo arms
706 /// stay here because they pin the `UnknownTerminateReasonKind`
707 /// newtype payload contract the trait's `make_unknown` cannot
708 /// see. Cross-axis inputs (ProcessPhase / TeardownPolicy variant
709 /// names) MUST fail — `TerminateReasonKind` is its own axis, not
710 /// a transparent reflection of either.
711 #[test]
712 fn unknown_terminate_reason_kind_errors() {
713 use std::str::FromStr;
714 for bad in [
715 "teardownPolicy",
716 "TEARDOWN_POLICY",
717 "Teardown",
718 "TtlExpire",
719 "ttl_expired",
720 "ttlExpired",
721 // Cross-axis-leaked — must NOT cross axes.
722 "Attested",
723 "Failed",
724 "Always",
725 "OnAttested",
726 "OnFailed",
727 "Never",
728 "Permanent",
729 "Ephemeral",
730 ] {
731 let err = TerminateReasonKind::from_str(bad).unwrap_err();
732 assert_eq!(err.0, bad, "error payload should echo input verbatim");
733 }
734 }
735
736 /// The reason `evaluate` returns under teardown maps to
737 /// `TerminateReasonKind::TeardownPolicy` AND its payload reflects
738 /// the spec's `(teardown_policy, current_phase)` verbatim — the
739 /// typed surface IS the source of truth, not an inline format
740 /// template. A future consumer that wants to group reasons by
741 /// kind in metrics labels reads `reason.kind()`, not a substring
742 /// match.
743 #[test]
744 fn evaluate_typed_reason_carries_teardown_payload() {
745 for (policy, phase) in [
746 (TeardownPolicy::Always, ProcessPhase::Attested),
747 (TeardownPolicy::Always, ProcessPhase::Failed),
748 (TeardownPolicy::OnAttested, ProcessPhase::Attested),
749 (TeardownPolicy::OnFailed, ProcessPhase::Failed),
750 ] {
751 let p = ephemeral_process("1h", policy, 60);
752 match evaluate(&p, phase, Utc::now()) {
753 AutoTerminate::Now { reason } => {
754 assert_eq!(reason.kind(), TerminateReasonKind::TeardownPolicy);
755 assert_eq!(
756 reason,
757 TerminateReason::TeardownPolicy { policy, phase },
758 "typed payload drift for ({policy:?}, {phase:?})",
759 );
760 }
761 other => {
762 panic!("expected AutoTerminate::Now for ({policy:?}, {phase:?}), got {other:?}",)
763 }
764 }
765 }
766 }
767
768 /// TTL expiry returns a `TtlExpired` reason whose `ttl` field is
769 /// the operator-authored humantime string verbatim (NOT the
770 /// parsed `Duration`'s pretty-print) and whose `elapsed` is the
771 /// wall-clock distance. Pinned here so a future evaluator change
772 /// that re-formats the ttl through `humantime::format_duration`
773 /// would fail.
774 #[test]
775 fn evaluate_typed_reason_carries_ttl_payload() {
776 let p = ephemeral_process("30s", TeardownPolicy::Never, 60);
777 let now = Utc::now();
778 match evaluate(&p, ProcessPhase::Running, now) {
779 AutoTerminate::Now { reason } => {
780 assert_eq!(reason.kind(), TerminateReasonKind::TtlExpired);
781 match reason {
782 TerminateReason::TtlExpired { ttl, elapsed } => {
783 assert_eq!(ttl, "30s", "ttl should be verbatim spec string");
784 assert!(
785 elapsed >= Duration::from_secs(30),
786 "elapsed should be at least the ttl",
787 );
788 }
789 other => panic!("expected TtlExpired, got {other:?}"),
790 }
791 }
792 other => panic!("expected AutoTerminate::Now, got {other:?}"),
793 }
794 }
795
796 // ── AutoTerminate / AutoTerminateKind closed-set contracts ────────
797
798 /// Exercise the substrate-wide [`tatara_lisp::ClosedSet`] contract on
799 /// [`AutoTerminateKind`] — pins the structural three-plus-one
800 /// (`ALL` is non-empty, every variant round-trips through
801 /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
802 /// outside the closed set) at ONE call site. Replaces the
803 /// hand-derived uniqueness sweep in
804 /// `auto_terminate_kind_kind_projection_is_exhaustive_over_all`'s
805 /// pre-lift form + the `auto_terminate_kind_roundtrip_via_as_str`
806 /// hand-rolled sweep + the empty-input arm of
807 /// `unknown_auto_terminate_kind_errors`. `FromStr` delegates to
808 /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this
809 /// helper exercises the same code path the lifetime-clock
810 /// evaluator hits when parsing a typed kind back out of a
811 /// `status.conditions[].reason` slot.
812 #[test]
813 fn auto_terminate_kind_is_well_formed_closed_set() {
814 tatara_closed_set::assert_closed_set_well_formed::<AutoTerminateKind>();
815 }
816
817 /// Every entry in `ALL` is reachable through a concrete
818 /// [`AutoTerminate`] value via [`AutoTerminate::kind`] — the
819 /// projection is exhaustive across the variant set. Pre-lift this
820 /// pin was bundled with a uniqueness HashSet sweep that
821 /// [`auto_terminate_kind_is_well_formed_closed_set`] now covers
822 /// generically through the [`tatara_lisp::ClosedSet`] contract;
823 /// post-lift this test keeps only the domain-specific
824 /// `kind()`-exhaustiveness contract (the (variant-name →
825 /// payload-stripped kind) binding the [`AutoTerminate`] surface
826 /// projects through). A future third payload-carrying
827 /// `AutoTerminate` variant updates this pin AND
828 /// [`AutoTerminate::kind`]'s exhaustiveness match together,
829 /// exhaustively checked by the compiler.
830 #[test]
831 fn auto_terminate_kind_kind_projection_is_exhaustive_over_all() {
832 let by_all: std::collections::HashSet<_> = AutoTerminateKind::ALL.iter().copied().collect();
833 let sample_reason = TerminateReason::TtlExpired {
834 ttl: "1h".into(),
835 elapsed: Duration::from_secs(0),
836 };
837 let by_concrete: std::collections::HashSet<_> = [
838 AutoTerminate::Skip.kind(),
839 AutoTerminate::Now {
840 reason: sample_reason,
841 }
842 .kind(),
843 ]
844 .into_iter()
845 .collect();
846 assert_eq!(
847 by_concrete, by_all,
848 "kind() projection not exhaustive over ALL"
849 );
850 }
851
852 /// BYTE-EXACT canonical wire-format pin — renaming either of the two
853 /// canonical strings is a wire-format change that fails this test
854 /// FIRST so it stays a deliberate change, not a silent rename that
855 /// drifts existing alerts / dashboards / operator runbooks.
856 #[test]
857 fn auto_terminate_kind_canonical_names_pinned() {
858 assert_eq!(AutoTerminateKind::Skip.as_str(), "Skip");
859 assert_eq!(AutoTerminateKind::Now.as_str(), "Now");
860 }
861
862 /// Every kind's `as_str` is in canonical PascalCase. The first
863 /// character is uppercase; no whitespace; no separators. The
864 /// `tatara-process` PascalCase idiom holds at one test site.
865 #[test]
866 fn auto_terminate_kind_as_str_is_pascal_case() {
867 for kind in AutoTerminateKind::ALL {
868 let s = kind.as_str();
869 assert!(!s.is_empty(), "as_str empty for {kind:?}");
870 assert!(
871 s.chars().next().unwrap().is_ascii_uppercase(),
872 "as_str not PascalCase for {kind:?}: {s}",
873 );
874 assert!(
875 !s.contains(|c: char| c.is_whitespace() || c == '_' || c == '-'),
876 "as_str carries separator for {kind:?}: {s}",
877 );
878 }
879 }
880
881 /// `Display` IS `as_str` — pinning this lets future callers reach
882 /// for either projection without drift.
883 #[test]
884 fn auto_terminate_kind_display_matches_as_str() {
885 for kind in AutoTerminateKind::ALL {
886 assert_eq!(kind.to_string(), kind.as_str());
887 }
888 }
889
890 /// `FromStr` rejects strings outside the canonical projection
891 /// (lowercased / typo / cross-axis-leaked) and echoes the input
892 /// verbatim. The empty-string arm AND the round-trip sweep are
893 /// covered by `auto_terminate_kind_is_well_formed_closed_set` via
894 /// the [`tatara_lisp::ClosedSet`] contract; the cases here pin the
895 /// `UnknownAutoTerminateKind` newtype payload contract the
896 /// trait's `make_unknown` cannot see. Cross-axis inputs
897 /// (ProcessPhase / TeardownPolicy / TerminateReasonKind variant
898 /// names) MUST fail — `AutoTerminateKind` is its own axis, not
899 /// a transparent reflection of any sibling enum.
900 #[test]
901 fn unknown_auto_terminate_kind_errors() {
902 use std::str::FromStr;
903 for bad in [
904 "skip",
905 "now",
906 "SKIP",
907 "NOW",
908 "S",
909 "N",
910 "no-op",
911 "terminate",
912 // Cross-axis-leaked — must NOT cross axes.
913 "Attested",
914 "Failed",
915 "TeardownPolicy",
916 "TtlExpired",
917 "Always",
918 "Permanent",
919 "Ephemeral",
920 ] {
921 let err = AutoTerminateKind::from_str(bad).unwrap_err();
922 assert_eq!(err.0, bad, "error payload should echo input verbatim");
923 }
924 }
925
926 /// `reason()` projection: `Now { reason }` returns `Some(&reason)`,
927 /// `Skip` returns `None`. The (variant-name → payload-field)
928 /// binding lives at ONE site so a future third payload-carrying
929 /// variant updates every consumer through this method's
930 /// exhaustiveness check rather than scattering destructures across
931 /// the call graph.
932 #[test]
933 fn auto_terminate_reason_projection() {
934 assert!(AutoTerminate::Skip.reason().is_none());
935
936 let reason = TerminateReason::TtlExpired {
937 ttl: "1h".into(),
938 elapsed: Duration::from_secs(0),
939 };
940 let now = AutoTerminate::Now {
941 reason: reason.clone(),
942 };
943 assert_eq!(now.reason(), Some(&reason));
944
945 let teardown = TerminateReason::TeardownPolicy {
946 policy: TeardownPolicy::OnAttested,
947 phase: ProcessPhase::Attested,
948 };
949 let now = AutoTerminate::Now {
950 reason: teardown.clone(),
951 };
952 assert_eq!(now.reason(), Some(&teardown));
953 }
954
955 /// `is_now` / `is_skip` are exact complements over the closed set —
956 /// `is_now ⊕ is_skip = true` for every variant. Locks the predicate
957 /// pair so a future third variant that's neither Skip nor Now must
958 /// extend BOTH predicates in lockstep (or this contract fails).
959 #[test]
960 fn auto_terminate_predicate_pair_is_exhaustive_complement() {
961 let reason = TerminateReason::TtlExpired {
962 ttl: "1h".into(),
963 elapsed: Duration::from_secs(0),
964 };
965 for decision in [
966 AutoTerminate::Skip,
967 AutoTerminate::Now {
968 reason: reason.clone(),
969 },
970 ] {
971 assert_ne!(
972 decision.is_now(),
973 decision.is_skip(),
974 "predicate pair drift for {decision:?}",
975 );
976 // The kind projection agrees with each predicate.
977 assert_eq!(decision.is_now(), decision.kind() == AutoTerminateKind::Now);
978 assert_eq!(
979 decision.is_skip(),
980 decision.kind() == AutoTerminateKind::Skip
981 );
982 // `reason()` agrees with `is_now`.
983 assert_eq!(decision.reason().is_some(), decision.is_now());
984 }
985 }
986
987 /// The `kind()` projection on the typed result of `evaluate` agrees
988 /// with the behavioural expectation: ephemeral-on-Attested with an
989 /// OnAttested policy returns `Now`, permanent never does. Closes
990 /// the loop between the closed-set view and the live decision so
991 /// any future kind-keyed metrics label (e.g.
992 /// `tatara_lifetime_clock_decisions_total{kind="Now"}`) reads the
993 /// typed projection rather than the inline destructure.
994 #[test]
995 fn evaluate_decision_kind_agrees_with_runtime_behaviour() {
996 let p = permanent_process();
997 for phase in [
998 ProcessPhase::Pending,
999 ProcessPhase::Running,
1000 ProcessPhase::Attested,
1001 ProcessPhase::Failed,
1002 ] {
1003 let decision = evaluate(&p, phase, Utc::now());
1004 assert_eq!(
1005 decision.kind(),
1006 AutoTerminateKind::Skip,
1007 "permanent Process must always Skip; got Now for phase={phase:?}",
1008 );
1009 assert!(decision.reason().is_none());
1010 }
1011
1012 let p = ephemeral_process("1h", TeardownPolicy::OnAttested, 60);
1013 let now = Utc::now();
1014 assert_eq!(
1015 evaluate(&p, ProcessPhase::Attested, now).kind(),
1016 AutoTerminateKind::Now,
1017 );
1018 assert_eq!(
1019 evaluate(&p, ProcessPhase::Running, now).kind(),
1020 AutoTerminateKind::Skip,
1021 );
1022 }
1023
1024 #[test]
1025 fn requeue_picks_min_of_default_and_remaining() {
1026 let p = ephemeral_process("5m", TeardownPolicy::Always, 60);
1027 let now = Utc::now();
1028 let d = requeue_with_ttl(&p, now, Duration::from_secs(30));
1029 // 5m total - 60s elapsed = 240s remaining; default 30s wins.
1030 assert_eq!(d, Duration::from_secs(30));
1031
1032 let p = ephemeral_process("90s", TeardownPolicy::Always, 80);
1033 let d = requeue_with_ttl(&p, now, Duration::from_secs(30));
1034 // 90s - 80s = 10s remaining; remaining wins.
1035 assert!(d <= Duration::from_secs(11) && d >= Duration::from_secs(9));
1036
1037 let p = ephemeral_process("90s", TeardownPolicy::Always, 91);
1038 let d = requeue_with_ttl(&p, now, Duration::from_secs(30));
1039 // Already past TTL — clamp to 1s, not 0.
1040 assert_eq!(d, Duration::from_secs(1));
1041 }
1042}