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 // `Process::resolved_ephemeral` gate — the compound spec-projection
292 // primitive on `impl Process` that owns the ambiguity-aware
293 // `variant().ok() + as_ephemeral` chain — replaces the previous
294 // 4-step `process.spec.lifetime.resolved_ephemeral()` walk and
295 // shares the primitive with `requeue_with_ttl` below AND with
296 // `tatara-reconciler::render::render_export_jobs` (which pre-
297 // lift walked the naked `.spec.lifetime.ephemeral.as_ref()`
298 // raw-field access that disagreed on the ambiguous corner).
299 let Some(ephemeral) = process.resolved_ephemeral() else {
300 return AutoTerminate::Skip;
301 };
302
303 // 1. Teardown policy on terminal phases — ONE typed dispatch over
304 // `(TeardownPolicy, ProcessPhase)` replaces the previous pair of
305 // near-identical Attested/Failed branches. Non-terminal phases
306 // short-circuit inside `should_teardown_on`. The reason is the
307 // typed `TerminateReason::TeardownPolicy` variant whose `Display`
308 // composes the operator-visible string against the canonical
309 // PascalCase projection (`TeardownPolicy::as_str` +
310 // `ProcessPhase::as_str`), not a free-form template.
311 if ephemeral.teardown_policy.should_teardown_on(current_phase) {
312 return AutoTerminate::Now {
313 reason: TerminateReason::TeardownPolicy {
314 policy: ephemeral.teardown_policy,
315 phase: current_phase,
316 },
317 };
318 }
319
320 // 2. TTL expiry — applies in any non-terminal phase.
321 // The creation-anchor probe rides through the ONE substrate
322 // `Process::created_at` primitive, sibling to the same-corner
323 // requeue-budget picker in `requeue_with_ttl` below and the
324 // stable-name claim-arbiter tie-break seed in
325 // `tatara-reconciler::table_controller`. Post-lift the two
326 // consumers here + downstream share the ONE
327 // `Option<DateTime<Utc>>` return shape.
328 if !is_terminal_or_exit(current_phase) {
329 if let Some(creation) = process.created_at() {
330 // TTL parse rides through the ONE substrate primitive
331 // [`crate::lifetime::EphemeralLifetime::ttl_duration`] —
332 // the `humantime::parse_duration(&<eph>.ttl).ok()` chain
333 // pre-lift hand-authored at TWO workspace-wide sites past
334 // the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold
335 // (peer at [`requeue_with_ttl`] below). Post-lift both
336 // consumers share ONE typed owner returning the same
337 // `Option<Duration>` shape [`crate::time::elapsed_since`]
338 // returns, so the `elapsed >= ttl` comparator lands with
339 // both operands on the same axis; a future TTL-side
340 // normalization (per-fleet minimum floor, canonical
341 // unit-normalization, warn-log on unparseable strings)
342 // lands at ONE substrate site.
343 if let Some(ttl) = ephemeral.ttl_duration() {
344 // The `(now, creation) → Option<std::time::Duration>`
345 // projection rides through the ONE substrate primitive
346 // [`crate::time::elapsed_since`], sibling to the same-
347 // chain sleep-budget picker in [`requeue_with_ttl`]
348 // below and the pool-staleness gate in
349 // `tatara-pool-reconciler::pool_decide`. Pre-lift each
350 // of the three sites hand-authored `now
351 // .signed_duration_since(<anchor>).to_std().ok()` past
352 // the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold;
353 // post-lift each routes through ONE typed owner and a
354 // future normalization (monotonic-clock cross-check,
355 // per-fleet skew tolerance, subsecond truncation) lands
356 // at ONE substrate site.
357 if let Some(elapsed) = crate::time::elapsed_since(now, creation) {
358 if elapsed >= ttl {
359 return AutoTerminate::Now {
360 reason: TerminateReason::TtlExpired {
361 ttl: ephemeral.ttl.clone(),
362 elapsed,
363 },
364 };
365 }
366 }
367 }
368 }
369 }
370
371 AutoTerminate::Skip
372}
373
374/// Phases past which TTL cannot meaningfully fire — the SIGTERM path
375/// is already in progress.
376fn is_terminal_or_exit(p: ProcessPhase) -> bool {
377 matches!(
378 p,
379 ProcessPhase::Exiting | ProcessPhase::Zombie | ProcessPhase::Reaped
380 )
381}
382
383/// Sleep budget the controller should requeue with for a Process whose
384/// `evaluate()` returned `Skip` — picks the smaller of HEARTBEAT and
385/// TTL-remaining so we don't oversleep past expiry.
386pub fn requeue_with_ttl(process: &Process, now: DateTime<Utc>, default: Duration) -> Duration {
387 // Shared `Process::resolved_ephemeral` projection with
388 // [`evaluate`] — the "give me only the unambiguous ephemeral case"
389 // compound-lift primitive on `impl Process` that composes through
390 // `impl Lifetime`'s `resolved_ephemeral` and closes drift with the
391 // export-Job render arm at ONE substrate site.
392 let Some(e) = process.resolved_ephemeral() else {
393 return default;
394 };
395 // Creation-anchor probe rides through the ONE substrate
396 // `Process::created_at` primitive (sibling to the TTL-expiry gate
397 // in `evaluate` above); the `let-else` short-circuits on the
398 // missing-slot corner to the caller's `default` sleep budget.
399 let Some(creation) = process.created_at() else {
400 return default;
401 };
402 // Shared TTL-parse projection with [`evaluate`] above — the
403 // `humantime::parse_duration(&<eph>.ttl).ok()` chain rides through
404 // the ONE substrate primitive
405 // [`crate::lifetime::EphemeralLifetime::ttl_duration`]. The
406 // `let-else` short-circuits on the parse-failure corner (typo,
407 // unsupported unit, non-humantime literal on the wire) to the
408 // caller's `default` sleep budget — the same "no ttl data → do
409 // not fire the timed decision" interpretation the TTL-expiry
410 // gate in [`evaluate`] gives to the `None` arm.
411 let Some(ttl) = e.ttl_duration() else {
412 return default;
413 };
414 // Sibling to the TTL-expiry gate in [`evaluate`] above: the
415 // `(now, creation) → Option<std::time::Duration>` projection rides
416 // through the ONE substrate primitive [`crate::time::elapsed_since`].
417 // The `let-else` short-circuits on the negative-anchor corner
418 // (clock skew or a creation timestamp stamped past `now`) to the
419 // caller's `default` sleep budget — the same "no elapsed data → do
420 // not fire the timed decision" interpretation every other consumer
421 // gives to the `None` arm.
422 let Some(elapsed) = crate::time::elapsed_since(now, creation) else {
423 return default;
424 };
425 let remaining = ttl.checked_sub(elapsed).unwrap_or(Duration::from_secs(0));
426 // Never sleep less than 1s; never longer than the default heartbeat.
427 let pick = std::cmp::min(default, remaining);
428 std::cmp::max(pick, Duration::from_secs(1))
429}
430
431#[cfg(test)]
432mod tests {
433 use super::*;
434 use crate::classification::Classification;
435 use crate::crd::ProcessSpec;
436 use crate::intent::{AplicacaoIntent, Intent};
437 use crate::lifetime::{EphemeralLifetime, Lifetime, TeardownPolicy};
438 use k8s_openapi::apimachinery::pkg::apis::meta::v1::Time;
439
440 fn ephemeral_process(ttl: &str, teardown: TeardownPolicy, age_secs: i64) -> Process {
441 let spec = ProcessSpec {
442 identity: Default::default(),
443 classification: Classification::gate_compute(),
444 intent: Intent {
445 aplicacao: Some(AplicacaoIntent {
446 chart_ref: "oci://x".into(),
447 version: "1".into(),
448 profile: String::new(),
449 values_overlay: serde_json::Value::Null,
450 release_name: None,
451 target_namespace: None,
452 install_timeout: None,
453 }),
454 ..Intent::default()
455 },
456 boundary: Default::default(),
457 compliance: Default::default(),
458 depends_on: vec![],
459 signals: Default::default(),
460 lifetime: Lifetime {
461 ephemeral: Some(EphemeralLifetime {
462 ttl: ttl.into(),
463 teardown_policy: teardown,
464 max_concurrent: 1,
465 exports: vec![],
466 }),
467 ..Lifetime::default()
468 },
469 routing: None,
470 encapsulates: None,
471 suspended: false,
472 };
473 let mut p = Process::new("e", spec);
474 p.metadata.namespace = Some("ns".into());
475 let creation = Utc::now() - chrono::Duration::seconds(age_secs);
476 p.metadata.creation_timestamp = Some(Time(creation));
477 p
478 }
479
480 fn permanent_process() -> Process {
481 let spec = ProcessSpec {
482 identity: Default::default(),
483 classification: Classification::gate_compute(),
484 intent: Intent {
485 aplicacao: Some(AplicacaoIntent {
486 chart_ref: "oci://x".into(),
487 version: "1".into(),
488 profile: String::new(),
489 values_overlay: serde_json::Value::Null,
490 release_name: None,
491 target_namespace: None,
492 install_timeout: None,
493 }),
494 ..Intent::default()
495 },
496 boundary: Default::default(),
497 compliance: Default::default(),
498 depends_on: vec![],
499 signals: Default::default(),
500 lifetime: Lifetime::default(),
501 routing: None,
502 encapsulates: None,
503 suspended: false,
504 };
505 Process::new("e", spec)
506 }
507
508 #[test]
509 fn permanent_never_auto_terminates() {
510 let p = permanent_process();
511 for phase in [
512 ProcessPhase::Pending,
513 ProcessPhase::Execing,
514 ProcessPhase::Running,
515 ProcessPhase::Attested,
516 ProcessPhase::Failed,
517 ] {
518 assert_eq!(evaluate(&p, phase, Utc::now()), AutoTerminate::Skip);
519 }
520 }
521
522 #[test]
523 fn always_teardown_fires_on_attested_and_failed() {
524 let p = ephemeral_process("1h", TeardownPolicy::Always, 60);
525 let now = Utc::now();
526 assert!(matches!(
527 evaluate(&p, ProcessPhase::Attested, now),
528 AutoTerminate::Now { .. }
529 ));
530 assert!(matches!(
531 evaluate(&p, ProcessPhase::Failed, now),
532 AutoTerminate::Now { .. }
533 ));
534 assert_eq!(
535 evaluate(&p, ProcessPhase::Running, now),
536 AutoTerminate::Skip
537 );
538 }
539
540 #[test]
541 fn on_attested_only_fires_on_attested() {
542 let p = ephemeral_process("1h", TeardownPolicy::OnAttested, 60);
543 let now = Utc::now();
544 assert!(matches!(
545 evaluate(&p, ProcessPhase::Attested, now),
546 AutoTerminate::Now { .. }
547 ));
548 assert_eq!(evaluate(&p, ProcessPhase::Failed, now), AutoTerminate::Skip);
549 }
550
551 #[test]
552 fn on_failed_only_fires_on_failed() {
553 let p = ephemeral_process("1h", TeardownPolicy::OnFailed, 60);
554 let now = Utc::now();
555 assert_eq!(
556 evaluate(&p, ProcessPhase::Attested, now),
557 AutoTerminate::Skip
558 );
559 assert!(matches!(
560 evaluate(&p, ProcessPhase::Failed, now),
561 AutoTerminate::Now { .. }
562 ));
563 }
564
565 #[test]
566 fn never_skips_phase_terminations_but_still_honors_ttl() {
567 let p = ephemeral_process("30s", TeardownPolicy::Never, 60);
568 let now = Utc::now();
569 // TTL elapsed → TTL fires regardless of policy.
570 assert!(matches!(
571 evaluate(&p, ProcessPhase::Running, now),
572 AutoTerminate::Now { .. }
573 ));
574 // But not on a terminal phase (already exiting).
575 assert_eq!(
576 evaluate(&p, ProcessPhase::Exiting, now),
577 AutoTerminate::Skip
578 );
579 }
580
581 #[test]
582 fn ttl_not_yet_elapsed_is_skip() {
583 let p = ephemeral_process("1h", TeardownPolicy::Never, 60);
584 assert_eq!(
585 evaluate(&p, ProcessPhase::Running, Utc::now()),
586 AutoTerminate::Skip
587 );
588 }
589
590 /// REASON-STRING CONTRACT: the operator-visible reason composes
591 /// the canonical PascalCase projection of `TeardownPolicy` and
592 /// `ProcessPhase` (via Display) rather than the Debug formatting
593 /// used pre-lift. A future variant rename of either enum updates
594 /// the reason string at ONE site (the `as_str` arm) instead of
595 /// drifting between the typed surface and the operator log.
596 #[test]
597 fn teardown_reason_string_uses_canonical_projection() {
598 let p = ephemeral_process("1h", TeardownPolicy::OnAttested, 60);
599 match evaluate(&p, ProcessPhase::Attested, Utc::now()) {
600 AutoTerminate::Now { reason } => {
601 let rendered = reason.to_string();
602 assert!(
603 rendered.contains("teardown_policy=OnAttested"),
604 "expected canonical PascalCase policy, got: {rendered}",
605 );
606 assert!(
607 rendered.contains("fired on Attested"),
608 "expected canonical PascalCase phase, got: {rendered}",
609 );
610 }
611 other => panic!("expected AutoTerminate::Now, got {other:?}"),
612 }
613
614 let p = ephemeral_process("1h", TeardownPolicy::Always, 60);
615 match evaluate(&p, ProcessPhase::Failed, Utc::now()) {
616 AutoTerminate::Now { reason } => {
617 let rendered = reason.to_string();
618 assert!(rendered.contains("teardown_policy=Always"));
619 assert!(rendered.contains("fired on Failed"));
620 }
621 other => panic!("expected AutoTerminate::Now, got {other:?}"),
622 }
623 }
624
625 // ── TerminateReason / TerminateReasonKind closed-set contracts ────
626
627 /// BYTE-FOR-BYTE PRE-LIFT CONTRACT: the Display impl on
628 /// `TerminateReason` must produce the exact string the pre-lift
629 /// inline `format!(…)` calls produced. Existing alerts, dashboards,
630 /// and operator runbooks that grep `status.message` for these
631 /// substrings keep matching. A future variant rename of
632 /// `TeardownPolicy` / `ProcessPhase` updates the rendered string
633 /// here automatically (Display reads `as_str` projection), but the
634 /// template — `"ephemeral lifetime: teardown_policy={} fired on {}"`
635 /// vs `"ephemeral lifetime: ttl={} expired (elapsed={}s)"` — is
636 /// pinned at the Display site.
637 #[test]
638 fn terminate_reason_display_matches_pre_lift() {
639 // TeardownPolicy variant — every combination of policy × phase
640 // sweeps both PascalCase projections.
641 for policy in TeardownPolicy::ALL {
642 for phase in ProcessPhase::ALL {
643 let reason = TerminateReason::TeardownPolicy { policy, phase };
644 let expected = format!(
645 "ephemeral lifetime: teardown_policy={} fired on {}",
646 policy.as_str(),
647 phase.as_str(),
648 );
649 assert_eq!(
650 reason.to_string(),
651 expected,
652 "Display drifted for ({policy:?}, {phase:?})",
653 );
654 }
655 }
656 // TtlExpired variant — pins the ttl-verbatim + elapsed-secs
657 // template against representative humantime strings the
658 // EphemeralLifetime.ttl field accepts.
659 for (ttl, elapsed_secs) in [("1h", 0u64), ("30m", 60), ("90s", 100), ("5m30s", 3600)] {
660 let reason = TerminateReason::TtlExpired {
661 ttl: ttl.to_string(),
662 elapsed: Duration::from_secs(elapsed_secs),
663 };
664 assert_eq!(
665 reason.to_string(),
666 format!("ephemeral lifetime: ttl={ttl} expired (elapsed={elapsed_secs}s)"),
667 );
668 }
669 }
670
671 /// Reason `kind()` projection — closed-set match so a future
672 /// variant triggers exhaustiveness checking at the projection
673 /// site rather than silently bucketing through a wildcard. Every
674 /// variant's `kind()` matches its `TerminateReasonKind` peer.
675 #[test]
676 fn terminate_reason_kind_truth_table() {
677 assert_eq!(
678 TerminateReason::TeardownPolicy {
679 policy: TeardownPolicy::Always,
680 phase: ProcessPhase::Attested,
681 }
682 .kind(),
683 TerminateReasonKind::TeardownPolicy,
684 );
685 assert_eq!(
686 TerminateReason::TtlExpired {
687 ttl: "1h".to_string(),
688 elapsed: Duration::from_secs(0),
689 }
690 .kind(),
691 TerminateReasonKind::TtlExpired,
692 );
693 }
694
695 /// `ALL` is the source of truth; a variant added without an `ALL`
696 /// entry fails here (uniqueness check) before any sweep test below
697 /// runs. Arity is asserted by the array type itself (`[Self; 2]`).
698 /// Exercise the substrate-wide [`tatara_lisp::ClosedSet`] contract on
699 /// [`TerminateReasonKind`] — pins the structural three-plus-one
700 /// (`ALL` is non-empty, every variant round-trips through
701 /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
702 /// outside the closed set) at ONE call site. Replaces the
703 /// hand-derived `terminate_reason_kind_all_is_unique_and_complete`
704 /// + `terminate_reason_kind_roundtrip_via_as_str` + the empty-input
705 /// arm of `unknown_terminate_reason_kind_errors`. `FromStr`
706 /// delegates to `<Self as tatara_closed_set::ClosedSet>::parse_label`,
707 /// so this helper exercises the same code path the lifetime-clock
708 /// evaluator hits when parsing a typed reason back out of a
709 /// `status.conditions[].reason` slot.
710 #[test]
711 fn terminate_reason_kind_is_well_formed_closed_set() {
712 tatara_closed_set::assert_closed_set_well_formed::<TerminateReasonKind>();
713 }
714
715 /// `Display` IS `as_str` — pinning this lets future callers reach
716 /// for either projection without drift.
717 #[test]
718 fn terminate_reason_kind_display_matches_as_str() {
719 crate::tagged_union::assert_display_matches_label::<TerminateReasonKind>();
720 }
721
722 /// Every kind's `as_str` is in canonical PascalCase. The first
723 /// character is uppercase; no whitespace; no separators. The
724 /// `tatara-process` PascalCase idiom holds at one test site.
725 #[test]
726 fn terminate_reason_kind_as_str_is_pascal_case() {
727 for kind in TerminateReasonKind::ALL {
728 let s = kind.as_str();
729 assert!(!s.is_empty(), "as_str empty for {kind:?}");
730 assert!(
731 s.chars().next().unwrap().is_ascii_uppercase(),
732 "as_str not PascalCase for {kind:?}: {s}",
733 );
734 assert!(
735 !s.contains(|c: char| c.is_whitespace() || c == '_' || c == '-'),
736 "as_str carries separator for {kind:?}: {s}",
737 );
738 }
739 }
740
741 /// `FromStr` rejects strings outside the canonical projection
742 /// (lowercased / typo / cross-axis-leaked) and echoes the input
743 /// verbatim. The empty-string arm is covered by
744 /// `terminate_reason_kind_is_well_formed_closed_set` via the
745 /// [`tatara_lisp::ClosedSet`] contract; the verbatim-echo arms
746 /// stay here because they pin the `UnknownTerminateReasonKind`
747 /// newtype payload contract the trait's `make_unknown` cannot
748 /// see. Cross-axis inputs (ProcessPhase / TeardownPolicy variant
749 /// names) MUST fail — `TerminateReasonKind` is its own axis, not
750 /// a transparent reflection of either.
751 #[test]
752 fn unknown_terminate_reason_kind_errors() {
753 use std::str::FromStr;
754 for bad in [
755 "teardownPolicy",
756 "TEARDOWN_POLICY",
757 "Teardown",
758 "TtlExpire",
759 "ttl_expired",
760 "ttlExpired",
761 // Cross-axis-leaked — must NOT cross axes.
762 "Attested",
763 "Failed",
764 "Always",
765 "OnAttested",
766 "OnFailed",
767 "Never",
768 "Permanent",
769 "Ephemeral",
770 ] {
771 let err = TerminateReasonKind::from_str(bad).unwrap_err();
772 assert_eq!(err.0, bad, "error payload should echo input verbatim");
773 }
774 }
775
776 /// The reason `evaluate` returns under teardown maps to
777 /// `TerminateReasonKind::TeardownPolicy` AND its payload reflects
778 /// the spec's `(teardown_policy, current_phase)` verbatim — the
779 /// typed surface IS the source of truth, not an inline format
780 /// template. A future consumer that wants to group reasons by
781 /// kind in metrics labels reads `reason.kind()`, not a substring
782 /// match.
783 #[test]
784 fn evaluate_typed_reason_carries_teardown_payload() {
785 for (policy, phase) in [
786 (TeardownPolicy::Always, ProcessPhase::Attested),
787 (TeardownPolicy::Always, ProcessPhase::Failed),
788 (TeardownPolicy::OnAttested, ProcessPhase::Attested),
789 (TeardownPolicy::OnFailed, ProcessPhase::Failed),
790 ] {
791 let p = ephemeral_process("1h", policy, 60);
792 match evaluate(&p, phase, Utc::now()) {
793 AutoTerminate::Now { reason } => {
794 assert_eq!(reason.kind(), TerminateReasonKind::TeardownPolicy);
795 assert_eq!(
796 reason,
797 TerminateReason::TeardownPolicy { policy, phase },
798 "typed payload drift for ({policy:?}, {phase:?})",
799 );
800 }
801 other => {
802 panic!("expected AutoTerminate::Now for ({policy:?}, {phase:?}), got {other:?}",)
803 }
804 }
805 }
806 }
807
808 /// TTL expiry returns a `TtlExpired` reason whose `ttl` field is
809 /// the operator-authored humantime string verbatim (NOT the
810 /// parsed `Duration`'s pretty-print) and whose `elapsed` is the
811 /// wall-clock distance. Pinned here so a future evaluator change
812 /// that re-formats the ttl through `humantime::format_duration`
813 /// would fail.
814 #[test]
815 fn evaluate_typed_reason_carries_ttl_payload() {
816 let p = ephemeral_process("30s", TeardownPolicy::Never, 60);
817 let now = Utc::now();
818 match evaluate(&p, ProcessPhase::Running, now) {
819 AutoTerminate::Now { reason } => {
820 assert_eq!(reason.kind(), TerminateReasonKind::TtlExpired);
821 match reason {
822 TerminateReason::TtlExpired { ttl, elapsed } => {
823 assert_eq!(ttl, "30s", "ttl should be verbatim spec string");
824 assert!(
825 elapsed >= Duration::from_secs(30),
826 "elapsed should be at least the ttl",
827 );
828 }
829 other => panic!("expected TtlExpired, got {other:?}"),
830 }
831 }
832 other => panic!("expected AutoTerminate::Now, got {other:?}"),
833 }
834 }
835
836 // ── AutoTerminate / AutoTerminateKind closed-set contracts ────────
837
838 /// Exercise the substrate-wide [`tatara_lisp::ClosedSet`] contract on
839 /// [`AutoTerminateKind`] — pins the structural three-plus-one
840 /// (`ALL` is non-empty, every variant round-trips through
841 /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
842 /// outside the closed set) at ONE call site. Replaces the
843 /// hand-derived uniqueness sweep in
844 /// `auto_terminate_kind_kind_projection_is_exhaustive_over_all`'s
845 /// pre-lift form + the `auto_terminate_kind_roundtrip_via_as_str`
846 /// hand-rolled sweep + the empty-input arm of
847 /// `unknown_auto_terminate_kind_errors`. `FromStr` delegates to
848 /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this
849 /// helper exercises the same code path the lifetime-clock
850 /// evaluator hits when parsing a typed kind back out of a
851 /// `status.conditions[].reason` slot.
852 #[test]
853 fn auto_terminate_kind_is_well_formed_closed_set() {
854 tatara_closed_set::assert_closed_set_well_formed::<AutoTerminateKind>();
855 }
856
857 /// Every entry in `ALL` is reachable through a concrete
858 /// [`AutoTerminate`] value via [`AutoTerminate::kind`] — the
859 /// projection is exhaustive across the variant set. Pre-lift this
860 /// pin was bundled with a uniqueness HashSet sweep that
861 /// [`auto_terminate_kind_is_well_formed_closed_set`] now covers
862 /// generically through the [`tatara_lisp::ClosedSet`] contract;
863 /// post-lift this test keeps only the domain-specific
864 /// `kind()`-exhaustiveness contract (the (variant-name →
865 /// payload-stripped kind) binding the [`AutoTerminate`] surface
866 /// projects through). A future third payload-carrying
867 /// `AutoTerminate` variant updates this pin AND
868 /// [`AutoTerminate::kind`]'s exhaustiveness match together,
869 /// exhaustively checked by the compiler.
870 #[test]
871 fn auto_terminate_kind_kind_projection_is_exhaustive_over_all() {
872 let by_all: std::collections::HashSet<_> = AutoTerminateKind::ALL.iter().copied().collect();
873 let sample_reason = TerminateReason::TtlExpired {
874 ttl: "1h".into(),
875 elapsed: Duration::from_secs(0),
876 };
877 let by_concrete: std::collections::HashSet<_> = [
878 AutoTerminate::Skip.kind(),
879 AutoTerminate::Now {
880 reason: sample_reason,
881 }
882 .kind(),
883 ]
884 .into_iter()
885 .collect();
886 assert_eq!(
887 by_concrete, by_all,
888 "kind() projection not exhaustive over ALL"
889 );
890 }
891
892 /// BYTE-EXACT canonical wire-format pin — renaming either of the two
893 /// canonical strings is a wire-format change that fails this test
894 /// FIRST so it stays a deliberate change, not a silent rename that
895 /// drifts existing alerts / dashboards / operator runbooks.
896 #[test]
897 fn auto_terminate_kind_canonical_names_pinned() {
898 assert_eq!(AutoTerminateKind::Skip.as_str(), "Skip");
899 assert_eq!(AutoTerminateKind::Now.as_str(), "Now");
900 }
901
902 /// Every kind's `as_str` is in canonical PascalCase. The first
903 /// character is uppercase; no whitespace; no separators. The
904 /// `tatara-process` PascalCase idiom holds at one test site.
905 #[test]
906 fn auto_terminate_kind_as_str_is_pascal_case() {
907 for kind in AutoTerminateKind::ALL {
908 let s = kind.as_str();
909 assert!(!s.is_empty(), "as_str empty for {kind:?}");
910 assert!(
911 s.chars().next().unwrap().is_ascii_uppercase(),
912 "as_str not PascalCase for {kind:?}: {s}",
913 );
914 assert!(
915 !s.contains(|c: char| c.is_whitespace() || c == '_' || c == '-'),
916 "as_str carries separator for {kind:?}: {s}",
917 );
918 }
919 }
920
921 /// `Display` IS `as_str` — pinning this lets future callers reach
922 /// for either projection without drift.
923 #[test]
924 fn auto_terminate_kind_display_matches_as_str() {
925 crate::tagged_union::assert_display_matches_label::<AutoTerminateKind>();
926 }
927
928 /// `FromStr` rejects strings outside the canonical projection
929 /// (lowercased / typo / cross-axis-leaked) and echoes the input
930 /// verbatim. The empty-string arm AND the round-trip sweep are
931 /// covered by `auto_terminate_kind_is_well_formed_closed_set` via
932 /// the [`tatara_lisp::ClosedSet`] contract; the cases here pin the
933 /// `UnknownAutoTerminateKind` newtype payload contract the
934 /// trait's `make_unknown` cannot see. Cross-axis inputs
935 /// (ProcessPhase / TeardownPolicy / TerminateReasonKind variant
936 /// names) MUST fail — `AutoTerminateKind` is its own axis, not
937 /// a transparent reflection of any sibling enum.
938 #[test]
939 fn unknown_auto_terminate_kind_errors() {
940 use std::str::FromStr;
941 for bad in [
942 "skip",
943 "now",
944 "SKIP",
945 "NOW",
946 "S",
947 "N",
948 "no-op",
949 "terminate",
950 // Cross-axis-leaked — must NOT cross axes.
951 "Attested",
952 "Failed",
953 "TeardownPolicy",
954 "TtlExpired",
955 "Always",
956 "Permanent",
957 "Ephemeral",
958 ] {
959 let err = AutoTerminateKind::from_str(bad).unwrap_err();
960 assert_eq!(err.0, bad, "error payload should echo input verbatim");
961 }
962 }
963
964 /// `reason()` projection: `Now { reason }` returns `Some(&reason)`,
965 /// `Skip` returns `None`. The (variant-name → payload-field)
966 /// binding lives at ONE site so a future third payload-carrying
967 /// variant updates every consumer through this method's
968 /// exhaustiveness check rather than scattering destructures across
969 /// the call graph.
970 #[test]
971 fn auto_terminate_reason_projection() {
972 assert!(AutoTerminate::Skip.reason().is_none());
973
974 let reason = TerminateReason::TtlExpired {
975 ttl: "1h".into(),
976 elapsed: Duration::from_secs(0),
977 };
978 let now = AutoTerminate::Now {
979 reason: reason.clone(),
980 };
981 assert_eq!(now.reason(), Some(&reason));
982
983 let teardown = TerminateReason::TeardownPolicy {
984 policy: TeardownPolicy::OnAttested,
985 phase: ProcessPhase::Attested,
986 };
987 let now = AutoTerminate::Now {
988 reason: teardown.clone(),
989 };
990 assert_eq!(now.reason(), Some(&teardown));
991 }
992
993 /// `is_now` / `is_skip` are exact complements over the closed set —
994 /// `is_now ⊕ is_skip = true` for every variant. Locks the predicate
995 /// pair so a future third variant that's neither Skip nor Now must
996 /// extend BOTH predicates in lockstep (or this contract fails).
997 #[test]
998 fn auto_terminate_predicate_pair_is_exhaustive_complement() {
999 let reason = TerminateReason::TtlExpired {
1000 ttl: "1h".into(),
1001 elapsed: Duration::from_secs(0),
1002 };
1003 for decision in [
1004 AutoTerminate::Skip,
1005 AutoTerminate::Now {
1006 reason: reason.clone(),
1007 },
1008 ] {
1009 assert_ne!(
1010 decision.is_now(),
1011 decision.is_skip(),
1012 "predicate pair drift for {decision:?}",
1013 );
1014 // The kind projection agrees with each predicate.
1015 assert_eq!(decision.is_now(), decision.kind() == AutoTerminateKind::Now);
1016 assert_eq!(
1017 decision.is_skip(),
1018 decision.kind() == AutoTerminateKind::Skip
1019 );
1020 // `reason()` agrees with `is_now`.
1021 assert_eq!(decision.reason().is_some(), decision.is_now());
1022 }
1023 }
1024
1025 /// The `kind()` projection on the typed result of `evaluate` agrees
1026 /// with the behavioural expectation: ephemeral-on-Attested with an
1027 /// OnAttested policy returns `Now`, permanent never does. Closes
1028 /// the loop between the closed-set view and the live decision so
1029 /// any future kind-keyed metrics label (e.g.
1030 /// `tatara_lifetime_clock_decisions_total{kind="Now"}`) reads the
1031 /// typed projection rather than the inline destructure.
1032 #[test]
1033 fn evaluate_decision_kind_agrees_with_runtime_behaviour() {
1034 let p = permanent_process();
1035 for phase in [
1036 ProcessPhase::Pending,
1037 ProcessPhase::Running,
1038 ProcessPhase::Attested,
1039 ProcessPhase::Failed,
1040 ] {
1041 let decision = evaluate(&p, phase, Utc::now());
1042 assert_eq!(
1043 decision.kind(),
1044 AutoTerminateKind::Skip,
1045 "permanent Process must always Skip; got Now for phase={phase:?}",
1046 );
1047 assert!(decision.reason().is_none());
1048 }
1049
1050 let p = ephemeral_process("1h", TeardownPolicy::OnAttested, 60);
1051 let now = Utc::now();
1052 assert_eq!(
1053 evaluate(&p, ProcessPhase::Attested, now).kind(),
1054 AutoTerminateKind::Now,
1055 );
1056 assert_eq!(
1057 evaluate(&p, ProcessPhase::Running, now).kind(),
1058 AutoTerminateKind::Skip,
1059 );
1060 }
1061
1062 #[test]
1063 fn requeue_picks_min_of_default_and_remaining() {
1064 let p = ephemeral_process("5m", TeardownPolicy::Always, 60);
1065 let now = Utc::now();
1066 let d = requeue_with_ttl(&p, now, Duration::from_secs(30));
1067 // 5m total - 60s elapsed = 240s remaining; default 30s wins.
1068 assert_eq!(d, Duration::from_secs(30));
1069
1070 let p = ephemeral_process("90s", TeardownPolicy::Always, 80);
1071 let d = requeue_with_ttl(&p, now, Duration::from_secs(30));
1072 // 90s - 80s = 10s remaining; remaining wins.
1073 assert!(d <= Duration::from_secs(11) && d >= Duration::from_secs(9));
1074
1075 let p = ephemeral_process("90s", TeardownPolicy::Always, 91);
1076 let d = requeue_with_ttl(&p, now, Duration::from_secs(30));
1077 // Already past TTL — clamp to 1s, not 0.
1078 assert_eq!(d, Duration::from_secs(1));
1079 }
1080}