Skip to main content

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/// Wall-clock-anchored peer of [`evaluate`] — pins the `now` argument
375/// to [`chrono::Utc::now`] so every production reconciler tick reads a
376/// single-shape 2-arg call rather than restating the wall-clock
377/// projection at each phase handler.
378///
379/// # Why it exists
380///
381/// Pre-lift the 3-arg `evaluate(p, ProcessPhase::X, chrono::Utc::now())`
382/// chain was hand-authored at THREE sites past the ★★ PRIME-DIRECTIVE
383/// ≥ 2 duplication threshold in `tatara-reconciler::phase_machine`,
384/// each pairing an ephemeral-lifetime clock check against wall-clock
385/// time inside a `handle_<phase>` async fn:
386///
387/// * `handle_running` — VERIFY-phase clock check on `ProcessPhase::
388///   Running`; a `Now` verdict force-transitions to `Exiting`
389///   regardless of postcondition state.
390/// * `handle_attested` — ATTEST-heartbeat clock check on `ProcessPhase::
391///   Attested`; a `Now` verdict routes through Releasing when exports
392///   are declared, otherwise straight to `Exiting`.
393/// * `handle_failed` — Failed-phase clock check on `ProcessPhase::
394///   Failed`; a `Now` verdict routes through Releasing when post-mortem
395///   exports are declared, otherwise straight to `Zombie`.
396///
397/// All three sites walked the SAME 3-arg call with the SAME
398/// `chrono::Utc::now()` third argument — the wall-clock projection had
399/// no per-callsite variation. Post-lift the three consumers share ONE
400/// substrate owner for the wall-clock-at-tick projection; a future
401/// clock swap (a monotonic clock cross-check, a per-reconciler
402/// injected time source, a test-only override at the production
403/// callsite via feature flag) lands at ONE substrate function and
404/// every phase handler inherits the upgrade mechanically.
405///
406/// The 3-arg [`evaluate`] peer stays load-bearing for test callers —
407/// the injected-`now` shape is what unit tests use to drive the clock
408/// deterministically (every `evaluate(&p, phase, Utc::now())` /
409/// `evaluate(&p, phase, seeded_now)` in this module's own test suite
410/// reads that surface). This peer is production-only: pinning the
411/// wall-clock at the substrate site means no test can accidentally
412/// consume it without the deterministic-clock injection that makes
413/// the test meaningful.
414///
415/// # Invariants
416///
417/// - **Same decision shape:** returns the SAME [`AutoTerminate`] the
418///   3-arg [`evaluate`] returns when passed `chrono::Utc::now()` as the
419///   third argument. This is a delegation, not a re-implementation.
420/// - **Wall-clock read once:** `Utc::now()` is called exactly ONCE per
421///   invocation, at the primitive's body, so a future consumer that
422///   chains two `evaluate_now` calls back-to-back still sees monotonic
423///   `now` reads (each call reads a fresh instant, not a cached one) —
424///   matches the pre-lift shape where each of the three phase
425///   handlers computed its own `chrono::Utc::now()` at its own line.
426///
427/// # `#[must_use]`
428///
429/// Every consumer either destructures the returned `AutoTerminate` at
430/// an `if let AutoTerminate::Now { reason } = …` guard (the three
431/// pre-lift phase-handler shapes) or feeds it into a downstream
432/// dispatcher that gates on `AutoTerminate::is_now`. Dropping the
433/// return means the clock check fired for no observable reason — the
434/// attribute surfaces that as a warning at every call site.
435///
436/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
437/// 3-arg call with `chrono::Utc::now()` as the third argument recurred
438/// at 3 hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
439/// duplication trigger, lifted onto the ONE workspace-wide substrate
440/// owner here). THEORY.md §II.1 invariant 5 (composition preserves
441/// proofs — the wall-clock projection lives at ONE site so a future
442/// clock swap reaches all three consumers through one edit).
443#[must_use]
444pub fn evaluate_now(process: &Process, current_phase: ProcessPhase) -> AutoTerminate {
445    evaluate(process, current_phase, Utc::now())
446}
447
448/// Phases past which TTL cannot meaningfully fire — the SIGTERM path
449/// is already in progress.
450fn is_terminal_or_exit(p: ProcessPhase) -> bool {
451    matches!(
452        p,
453        ProcessPhase::Exiting | ProcessPhase::Zombie | ProcessPhase::Reaped
454    )
455}
456
457/// Sleep budget the controller should requeue with for a Process whose
458/// `evaluate()` returned `Skip` — picks the smaller of HEARTBEAT and
459/// TTL-remaining so we don't oversleep past expiry.
460pub fn requeue_with_ttl(process: &Process, now: DateTime<Utc>, default: Duration) -> Duration {
461    // Shared `Process::resolved_ephemeral` projection with
462    // [`evaluate`] — the "give me only the unambiguous ephemeral case"
463    // compound-lift primitive on `impl Process` that composes through
464    // `impl Lifetime`'s `resolved_ephemeral` and closes drift with the
465    // export-Job render arm at ONE substrate site.
466    let Some(e) = process.resolved_ephemeral() else {
467        return default;
468    };
469    // Creation-anchor probe rides through the ONE substrate
470    // `Process::created_at` primitive (sibling to the TTL-expiry gate
471    // in `evaluate` above); the `let-else` short-circuits on the
472    // missing-slot corner to the caller's `default` sleep budget.
473    let Some(creation) = process.created_at() else {
474        return default;
475    };
476    // Shared TTL-parse projection with [`evaluate`] above — the
477    // `humantime::parse_duration(&<eph>.ttl).ok()` chain rides through
478    // the ONE substrate primitive
479    // [`crate::lifetime::EphemeralLifetime::ttl_duration`]. The
480    // `let-else` short-circuits on the parse-failure corner (typo,
481    // unsupported unit, non-humantime literal on the wire) to the
482    // caller's `default` sleep budget — the same "no ttl data → do
483    // not fire the timed decision" interpretation the TTL-expiry
484    // gate in [`evaluate`] gives to the `None` arm.
485    let Some(ttl) = e.ttl_duration() else {
486        return default;
487    };
488    // Sibling to the TTL-expiry gate in [`evaluate`] above: the
489    // `(now, creation) → Option<std::time::Duration>` projection rides
490    // through the ONE substrate primitive [`crate::time::elapsed_since`].
491    // The `let-else` short-circuits on the negative-anchor corner
492    // (clock skew or a creation timestamp stamped past `now`) to the
493    // caller's `default` sleep budget — the same "no elapsed data → do
494    // not fire the timed decision" interpretation every other consumer
495    // gives to the `None` arm.
496    let Some(elapsed) = crate::time::elapsed_since(now, creation) else {
497        return default;
498    };
499    let remaining = ttl.checked_sub(elapsed).unwrap_or(Duration::from_secs(0));
500    // Never sleep less than 1s; never longer than the default heartbeat.
501    let pick = std::cmp::min(default, remaining);
502    std::cmp::max(pick, Duration::from_secs(1))
503}
504
505#[cfg(test)]
506mod tests {
507    use super::*;
508    use crate::crd::ProcessSpec;
509    use crate::intent::{AplicacaoIntent, Intent};
510    use crate::lifetime::{EphemeralLifetime, Lifetime, TeardownPolicy};
511    use k8s_openapi::apimachinery::pkg::apis::meta::v1::Time;
512
513    fn ephemeral_process(ttl: &str, teardown: TeardownPolicy, age_secs: i64) -> Process {
514        // Struct-update through the ONE substrate composer
515        // `ProcessSpec::gate_compute_defaults` — pre-lift the nine
516        // other slots were hand-authored inline alongside the `intent`
517        // + `lifetime` overrides; post-lift the substrate owns them.
518        let spec = ProcessSpec {
519            intent: Intent {
520                aplicacao: Some(AplicacaoIntent::chart_only("oci://x", "1")),
521                ..Intent::default()
522            },
523            // Routes through the ONE substrate composer
524            // [`Lifetime::ephemeral`] — see the composer's doc-comment
525            // for the full migration rationale.
526            lifetime: Lifetime::ephemeral(EphemeralLifetime {
527                ttl: ttl.into(),
528                teardown_policy: teardown,
529                max_concurrent: 1,
530                exports: vec![],
531            }),
532            ..ProcessSpec::gate_compute_defaults()
533        };
534        let mut p = Process::new("e", spec);
535        p.metadata.namespace = Some("ns".into());
536        // Routes through the ONE substrate primitive `crate::time::
537        // seconds_ago` — one of 21 pre-lift exact-match sites past the
538        // ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold.
539        let creation = crate::time::seconds_ago(age_secs);
540        p.metadata.creation_timestamp = Some(Time(creation));
541        p
542    }
543
544    fn permanent_process() -> Process {
545        // Struct-update through the ONE substrate composer
546        // `ProcessSpec::gate_compute_defaults` — the ten other slots
547        // (identity / classification / boundary / compliance /
548        // depends_on / signals / lifetime / routing / encapsulates /
549        // suspended) ride the substrate; only `intent` is overridden.
550        let spec = ProcessSpec {
551            intent: Intent {
552                aplicacao: Some(AplicacaoIntent::chart_only("oci://x", "1")),
553                ..Intent::default()
554            },
555            ..ProcessSpec::gate_compute_defaults()
556        };
557        Process::new("e", spec)
558    }
559
560    #[test]
561    fn permanent_never_auto_terminates() {
562        let p = permanent_process();
563        for phase in [
564            ProcessPhase::Pending,
565            ProcessPhase::Execing,
566            ProcessPhase::Running,
567            ProcessPhase::Attested,
568            ProcessPhase::Failed,
569        ] {
570            assert_eq!(evaluate(&p, phase, Utc::now()), AutoTerminate::Skip);
571        }
572    }
573
574    #[test]
575    fn always_teardown_fires_on_attested_and_failed() {
576        let p = ephemeral_process("1h", TeardownPolicy::Always, 60);
577        let now = Utc::now();
578        assert!(matches!(
579            evaluate(&p, ProcessPhase::Attested, now),
580            AutoTerminate::Now { .. }
581        ));
582        assert!(matches!(
583            evaluate(&p, ProcessPhase::Failed, now),
584            AutoTerminate::Now { .. }
585        ));
586        assert_eq!(
587            evaluate(&p, ProcessPhase::Running, now),
588            AutoTerminate::Skip
589        );
590    }
591
592    #[test]
593    fn on_attested_only_fires_on_attested() {
594        let p = ephemeral_process("1h", TeardownPolicy::OnAttested, 60);
595        let now = Utc::now();
596        assert!(matches!(
597            evaluate(&p, ProcessPhase::Attested, now),
598            AutoTerminate::Now { .. }
599        ));
600        assert_eq!(evaluate(&p, ProcessPhase::Failed, now), AutoTerminate::Skip);
601    }
602
603    #[test]
604    fn on_failed_only_fires_on_failed() {
605        let p = ephemeral_process("1h", TeardownPolicy::OnFailed, 60);
606        let now = Utc::now();
607        assert_eq!(
608            evaluate(&p, ProcessPhase::Attested, now),
609            AutoTerminate::Skip
610        );
611        assert!(matches!(
612            evaluate(&p, ProcessPhase::Failed, now),
613            AutoTerminate::Now { .. }
614        ));
615    }
616
617    #[test]
618    fn never_skips_phase_terminations_but_still_honors_ttl() {
619        let p = ephemeral_process("30s", TeardownPolicy::Never, 60);
620        let now = Utc::now();
621        // TTL elapsed → TTL fires regardless of policy.
622        assert!(matches!(
623            evaluate(&p, ProcessPhase::Running, now),
624            AutoTerminate::Now { .. }
625        ));
626        // But not on a terminal phase (already exiting).
627        assert_eq!(
628            evaluate(&p, ProcessPhase::Exiting, now),
629            AutoTerminate::Skip
630        );
631    }
632
633    #[test]
634    fn ttl_not_yet_elapsed_is_skip() {
635        let p = ephemeral_process("1h", TeardownPolicy::Never, 60);
636        assert_eq!(
637            evaluate(&p, ProcessPhase::Running, Utc::now()),
638            AutoTerminate::Skip
639        );
640    }
641
642    // ─── evaluate_now substrate pins ────────────────────────────────
643    //
644    // The wall-clock-anchored peer [`evaluate_now`] pins the 3-arg
645    // `evaluate(p, phase, chrono::Utc::now())` chain at ONE substrate
646    // site across THREE consumer callsites in
647    // `tatara-reconciler::phase_machine` (handle_running,
648    // handle_attested, handle_failed). These pins bind the peer at
649    // fail-before-pass-after granularity so a regression that swapped
650    // the delegated clock (a monotonic-clock read, a stale cached
651    // instant, a fixed epoch) or drifted the decision shape (returning
652    // a different `AutoTerminate` variant than the 3-arg peer would on
653    // the same wall-clock instant) surfaces HERE rather than as silent
654    // ephemeral-teardown skew at three phase handlers simultaneously.
655
656    #[test]
657    fn evaluate_now_permanent_process_returns_skip() {
658        // Peer-parity witness on the permanent-process corner: the
659        // 3-arg [`evaluate`] returns `Skip` for a permanent Process on
660        // every phase; the wall-clock-anchored [`evaluate_now`] must
661        // return the SAME `Skip` — the delegation must not silently
662        // trip a teardown branch on a Process that lacks an
663        // `EphemeralLifetime` block at all.
664        let p = permanent_process();
665        for phase in [
666            ProcessPhase::Pending,
667            ProcessPhase::Execing,
668            ProcessPhase::Running,
669            ProcessPhase::Attested,
670            ProcessPhase::Failed,
671        ] {
672            assert_eq!(
673                evaluate_now(&p, phase),
674                AutoTerminate::Skip,
675                "evaluate_now must delegate to evaluate on permanent-process corner (phase={phase:?})",
676            );
677        }
678    }
679
680    #[test]
681    fn evaluate_now_agrees_with_evaluate_on_teardown_policy_corner() {
682        // Peer-parity witness on the teardown-policy corner: for a
683        // Process whose ephemeral teardown policy fires on
684        // `Attested` / `Failed`, both peers must return an
685        // `AutoTerminate::Now` verdict. The reason payload IS allowed
686        // to differ by microseconds (`TtlExpired`'s `elapsed` field
687        // reads a fresh `Utc::now()` inside `evaluate_now`), but the
688        // teardown-policy corner emits `TerminateReason::TeardownPolicy`
689        // whose payload is (policy, phase) — no wall-clock drift.
690        let p = ephemeral_process("1h", TeardownPolicy::Always, 60);
691        for phase in [ProcessPhase::Attested, ProcessPhase::Failed] {
692            let via_now = evaluate_now(&p, phase);
693            let via_evaluate = evaluate(&p, phase, Utc::now());
694            assert_eq!(
695                via_now, via_evaluate,
696                "evaluate_now teardown-policy verdict must match evaluate's on {phase:?}",
697            );
698            assert!(
699                matches!(via_now, AutoTerminate::Now { .. }),
700                "expected AutoTerminate::Now on {phase:?}, got {via_now:?}",
701            );
702        }
703        // Non-terminal phase → both must return Skip (teardown policy
704        // gates on terminal phases only).
705        assert_eq!(
706            evaluate_now(&p, ProcessPhase::Running),
707            AutoTerminate::Skip,
708            "teardown policy must not fire on non-terminal Running phase",
709        );
710    }
711
712    #[test]
713    fn evaluate_now_fires_ttl_when_elapsed() {
714        // Wall-clock-anchored TTL fires when the creation-anchored
715        // TTL has elapsed against the pinned `Utc::now()` read. The
716        // fixture stamps `metadata.creation_timestamp` 60s ago and
717        // sets a 30s TTL — so `evaluate_now` at reconcile time
718        // reads `Utc::now()`, subtracts the 60s-ago anchor, and
719        // returns `Now(TtlExpired{...})` on the VERIFY-phase read.
720        // A regression that pinned the delegated `now` to a stale
721        // constant (e.g. `DateTime::default()`) would silently miss
722        // the elapsed-TTL corner and return `Skip` here — the pin
723        // surfaces that drift at this test rather than as silent
724        // never-terminating ephemeral envs in production.
725        let p = ephemeral_process("30s", TeardownPolicy::Never, 60);
726        assert!(
727            matches!(
728                evaluate_now(&p, ProcessPhase::Running),
729                AutoTerminate::Now { .. }
730            ),
731            "TTL elapsed via wall-clock must fire Now verdict",
732        );
733    }
734
735    #[test]
736    fn evaluate_now_skips_when_ttl_not_yet_elapsed() {
737        // Peer of the elapsed-TTL pin above: a 1h TTL against a
738        // 60s-old creation anchor must NOT fire; the pinned
739        // `Utc::now()` read stays within the TTL window and
740        // `evaluate_now` returns `Skip`. A regression that pinned
741        // the delegated `now` to a far-future constant would trip
742        // the elapsed corner unconditionally and force-terminate
743        // every ephemeral Process before its TTL — the pin
744        // surfaces that drift here.
745        let p = ephemeral_process("1h", TeardownPolicy::Never, 60);
746        assert_eq!(
747            evaluate_now(&p, ProcessPhase::Running),
748            AutoTerminate::Skip,
749            "TTL not yet elapsed via wall-clock must not fire",
750        );
751    }
752
753    /// REASON-STRING CONTRACT: the operator-visible reason composes
754    /// the canonical PascalCase projection of `TeardownPolicy` and
755    /// `ProcessPhase` (via Display) rather than the Debug formatting
756    /// used pre-lift. A future variant rename of either enum updates
757    /// the reason string at ONE site (the `as_str` arm) instead of
758    /// drifting between the typed surface and the operator log.
759    #[test]
760    fn teardown_reason_string_uses_canonical_projection() {
761        let p = ephemeral_process("1h", TeardownPolicy::OnAttested, 60);
762        match evaluate(&p, ProcessPhase::Attested, Utc::now()) {
763            AutoTerminate::Now { reason } => {
764                let rendered = reason.to_string();
765                assert!(
766                    rendered.contains("teardown_policy=OnAttested"),
767                    "expected canonical PascalCase policy, got: {rendered}",
768                );
769                assert!(
770                    rendered.contains("fired on Attested"),
771                    "expected canonical PascalCase phase, got: {rendered}",
772                );
773            }
774            other => panic!("expected AutoTerminate::Now, got {other:?}"),
775        }
776
777        let p = ephemeral_process("1h", TeardownPolicy::Always, 60);
778        match evaluate(&p, ProcessPhase::Failed, Utc::now()) {
779            AutoTerminate::Now { reason } => {
780                let rendered = reason.to_string();
781                assert!(rendered.contains("teardown_policy=Always"));
782                assert!(rendered.contains("fired on Failed"));
783            }
784            other => panic!("expected AutoTerminate::Now, got {other:?}"),
785        }
786    }
787
788    // ── TerminateReason / TerminateReasonKind closed-set contracts ────
789
790    /// BYTE-FOR-BYTE PRE-LIFT CONTRACT: the Display impl on
791    /// `TerminateReason` must produce the exact string the pre-lift
792    /// inline `format!(…)` calls produced. Existing alerts, dashboards,
793    /// and operator runbooks that grep `status.message` for these
794    /// substrings keep matching. A future variant rename of
795    /// `TeardownPolicy` / `ProcessPhase` updates the rendered string
796    /// here automatically (Display reads `as_str` projection), but the
797    /// template — `"ephemeral lifetime: teardown_policy={} fired on {}"`
798    /// vs `"ephemeral lifetime: ttl={} expired (elapsed={}s)"` — is
799    /// pinned at the Display site.
800    #[test]
801    fn terminate_reason_display_matches_pre_lift() {
802        // TeardownPolicy variant — every combination of policy × phase
803        // sweeps both PascalCase projections.
804        for policy in TeardownPolicy::ALL {
805            for phase in ProcessPhase::ALL {
806                let reason = TerminateReason::TeardownPolicy { policy, phase };
807                let expected = format!(
808                    "ephemeral lifetime: teardown_policy={} fired on {}",
809                    policy.as_str(),
810                    phase.as_str(),
811                );
812                assert_eq!(
813                    reason.to_string(),
814                    expected,
815                    "Display drifted for ({policy:?}, {phase:?})",
816                );
817            }
818        }
819        // TtlExpired variant — pins the ttl-verbatim + elapsed-secs
820        // template against representative humantime strings the
821        // EphemeralLifetime.ttl field accepts.
822        for (ttl, elapsed_secs) in [("1h", 0u64), ("30m", 60), ("90s", 100), ("5m30s", 3600)] {
823            let reason = TerminateReason::TtlExpired {
824                ttl: ttl.to_string(),
825                elapsed: Duration::from_secs(elapsed_secs),
826            };
827            assert_eq!(
828                reason.to_string(),
829                format!("ephemeral lifetime: ttl={ttl} expired (elapsed={elapsed_secs}s)"),
830            );
831        }
832    }
833
834    /// Reason `kind()` projection — closed-set match so a future
835    /// variant triggers exhaustiveness checking at the projection
836    /// site rather than silently bucketing through a wildcard. Every
837    /// variant's `kind()` matches its `TerminateReasonKind` peer.
838    #[test]
839    fn terminate_reason_kind_truth_table() {
840        assert_eq!(
841            TerminateReason::TeardownPolicy {
842                policy: TeardownPolicy::Always,
843                phase: ProcessPhase::Attested,
844            }
845            .kind(),
846            TerminateReasonKind::TeardownPolicy,
847        );
848        assert_eq!(
849            TerminateReason::TtlExpired {
850                ttl: "1h".to_string(),
851                elapsed: Duration::from_secs(0),
852            }
853            .kind(),
854            TerminateReasonKind::TtlExpired,
855        );
856    }
857
858    /// `ALL` is the source of truth; a variant added without an `ALL`
859    /// entry fails here (uniqueness check) before any sweep test below
860    /// runs. Arity is asserted by the array type itself (`[Self; 2]`).
861    /// Exercise the substrate-wide [`tatara_lisp::ClosedSet`] contract on
862    /// [`TerminateReasonKind`] — pins the structural three-plus-one
863    /// (`ALL` is non-empty, every variant round-trips through
864    /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
865    /// outside the closed set) at ONE call site. Replaces the
866    /// hand-derived `terminate_reason_kind_all_is_unique_and_complete`
867    /// + `terminate_reason_kind_roundtrip_via_as_str` + the empty-input
868    /// arm of `unknown_terminate_reason_kind_errors`. `FromStr`
869    /// delegates to `<Self as tatara_closed_set::ClosedSet>::parse_label`,
870    /// so this helper exercises the same code path the lifetime-clock
871    /// evaluator hits when parsing a typed reason back out of a
872    /// `status.conditions[].reason` slot.
873    #[test]
874    fn terminate_reason_kind_is_well_formed_closed_set() {
875        tatara_closed_set::assert_closed_set_well_formed::<TerminateReasonKind>();
876    }
877
878    /// `Display` IS `as_str` — pinning this lets future callers reach
879    /// for either projection without drift.
880    #[test]
881    fn terminate_reason_kind_display_matches_as_str() {
882        crate::tagged_union::assert_display_matches_label::<TerminateReasonKind>();
883    }
884
885    /// Every kind's `as_str` is in canonical PascalCase. The first
886    /// character is uppercase; no whitespace; no separators. The
887    /// `tatara-process` PascalCase idiom holds at one test site.
888    #[test]
889    fn terminate_reason_kind_as_str_is_pascal_case() {
890        for kind in TerminateReasonKind::ALL {
891            let s = kind.as_str();
892            assert!(!s.is_empty(), "as_str empty for {kind:?}");
893            assert!(
894                s.chars().next().unwrap().is_ascii_uppercase(),
895                "as_str not PascalCase for {kind:?}: {s}",
896            );
897            assert!(
898                !s.contains(|c: char| c.is_whitespace() || c == '_' || c == '-'),
899                "as_str carries separator for {kind:?}: {s}",
900            );
901        }
902    }
903
904    /// `FromStr` rejects strings outside the canonical projection
905    /// (lowercased / typo / cross-axis-leaked) and echoes the input
906    /// verbatim. The empty-string arm is covered by
907    /// `terminate_reason_kind_is_well_formed_closed_set` via the
908    /// [`tatara_lisp::ClosedSet`] contract; the verbatim-echo arms
909    /// stay here because they pin the `UnknownTerminateReasonKind`
910    /// newtype payload contract the trait's `make_unknown` cannot
911    /// see. Cross-axis inputs (ProcessPhase / TeardownPolicy variant
912    /// names) MUST fail — `TerminateReasonKind` is its own axis, not
913    /// a transparent reflection of either.
914    #[test]
915    fn unknown_terminate_reason_kind_errors() {
916        use std::str::FromStr;
917        for bad in [
918            "teardownPolicy",
919            "TEARDOWN_POLICY",
920            "Teardown",
921            "TtlExpire",
922            "ttl_expired",
923            "ttlExpired",
924            // Cross-axis-leaked — must NOT cross axes.
925            "Attested",
926            "Failed",
927            "Always",
928            "OnAttested",
929            "OnFailed",
930            "Never",
931            "Permanent",
932            "Ephemeral",
933        ] {
934            let err = TerminateReasonKind::from_str(bad).unwrap_err();
935            assert_eq!(err.0, bad, "error payload should echo input verbatim");
936        }
937    }
938
939    /// The reason `evaluate` returns under teardown maps to
940    /// `TerminateReasonKind::TeardownPolicy` AND its payload reflects
941    /// the spec's `(teardown_policy, current_phase)` verbatim — the
942    /// typed surface IS the source of truth, not an inline format
943    /// template. A future consumer that wants to group reasons by
944    /// kind in metrics labels reads `reason.kind()`, not a substring
945    /// match.
946    #[test]
947    fn evaluate_typed_reason_carries_teardown_payload() {
948        for (policy, phase) in [
949            (TeardownPolicy::Always, ProcessPhase::Attested),
950            (TeardownPolicy::Always, ProcessPhase::Failed),
951            (TeardownPolicy::OnAttested, ProcessPhase::Attested),
952            (TeardownPolicy::OnFailed, ProcessPhase::Failed),
953        ] {
954            let p = ephemeral_process("1h", policy, 60);
955            match evaluate(&p, phase, Utc::now()) {
956                AutoTerminate::Now { reason } => {
957                    assert_eq!(reason.kind(), TerminateReasonKind::TeardownPolicy);
958                    assert_eq!(
959                        reason,
960                        TerminateReason::TeardownPolicy { policy, phase },
961                        "typed payload drift for ({policy:?}, {phase:?})",
962                    );
963                }
964                other => {
965                    panic!("expected AutoTerminate::Now for ({policy:?}, {phase:?}), got {other:?}",)
966                }
967            }
968        }
969    }
970
971    /// TTL expiry returns a `TtlExpired` reason whose `ttl` field is
972    /// the operator-authored humantime string verbatim (NOT the
973    /// parsed `Duration`'s pretty-print) and whose `elapsed` is the
974    /// wall-clock distance. Pinned here so a future evaluator change
975    /// that re-formats the ttl through `humantime::format_duration`
976    /// would fail.
977    #[test]
978    fn evaluate_typed_reason_carries_ttl_payload() {
979        let p = ephemeral_process("30s", TeardownPolicy::Never, 60);
980        let now = Utc::now();
981        match evaluate(&p, ProcessPhase::Running, now) {
982            AutoTerminate::Now { reason } => {
983                assert_eq!(reason.kind(), TerminateReasonKind::TtlExpired);
984                match reason {
985                    TerminateReason::TtlExpired { ttl, elapsed } => {
986                        assert_eq!(ttl, "30s", "ttl should be verbatim spec string");
987                        assert!(
988                            elapsed >= Duration::from_secs(30),
989                            "elapsed should be at least the ttl",
990                        );
991                    }
992                    other => panic!("expected TtlExpired, got {other:?}"),
993                }
994            }
995            other => panic!("expected AutoTerminate::Now, got {other:?}"),
996        }
997    }
998
999    // ── AutoTerminate / AutoTerminateKind closed-set contracts ────────
1000
1001    /// Exercise the substrate-wide [`tatara_lisp::ClosedSet`] contract on
1002    /// [`AutoTerminateKind`] — pins the structural three-plus-one
1003    /// (`ALL` is non-empty, every variant round-trips through
1004    /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
1005    /// outside the closed set) at ONE call site. Replaces the
1006    /// hand-derived uniqueness sweep in
1007    /// `auto_terminate_kind_kind_projection_is_exhaustive_over_all`'s
1008    /// pre-lift form + the `auto_terminate_kind_roundtrip_via_as_str`
1009    /// hand-rolled sweep + the empty-input arm of
1010    /// `unknown_auto_terminate_kind_errors`. `FromStr` delegates to
1011    /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this
1012    /// helper exercises the same code path the lifetime-clock
1013    /// evaluator hits when parsing a typed kind back out of a
1014    /// `status.conditions[].reason` slot.
1015    #[test]
1016    fn auto_terminate_kind_is_well_formed_closed_set() {
1017        tatara_closed_set::assert_closed_set_well_formed::<AutoTerminateKind>();
1018    }
1019
1020    /// Every entry in `ALL` is reachable through a concrete
1021    /// [`AutoTerminate`] value via [`AutoTerminate::kind`] — the
1022    /// projection is exhaustive across the variant set. Pre-lift this
1023    /// pin was bundled with a uniqueness HashSet sweep that
1024    /// [`auto_terminate_kind_is_well_formed_closed_set`] now covers
1025    /// generically through the [`tatara_lisp::ClosedSet`] contract;
1026    /// post-lift this test keeps only the domain-specific
1027    /// `kind()`-exhaustiveness contract (the (variant-name →
1028    /// payload-stripped kind) binding the [`AutoTerminate`] surface
1029    /// projects through). A future third payload-carrying
1030    /// `AutoTerminate` variant updates this pin AND
1031    /// [`AutoTerminate::kind`]'s exhaustiveness match together,
1032    /// exhaustively checked by the compiler.
1033    #[test]
1034    fn auto_terminate_kind_kind_projection_is_exhaustive_over_all() {
1035        let by_all: std::collections::HashSet<_> = AutoTerminateKind::ALL.iter().copied().collect();
1036        let sample_reason = TerminateReason::TtlExpired {
1037            ttl: "1h".into(),
1038            elapsed: Duration::from_secs(0),
1039        };
1040        let by_concrete: std::collections::HashSet<_> = [
1041            AutoTerminate::Skip.kind(),
1042            AutoTerminate::Now {
1043                reason: sample_reason,
1044            }
1045            .kind(),
1046        ]
1047        .into_iter()
1048        .collect();
1049        assert_eq!(
1050            by_concrete, by_all,
1051            "kind() projection not exhaustive over ALL"
1052        );
1053    }
1054
1055    /// BYTE-EXACT canonical wire-format pin — renaming either of the two
1056    /// canonical strings is a wire-format change that fails this test
1057    /// FIRST so it stays a deliberate change, not a silent rename that
1058    /// drifts existing alerts / dashboards / operator runbooks.
1059    #[test]
1060    fn auto_terminate_kind_canonical_names_pinned() {
1061        assert_eq!(AutoTerminateKind::Skip.as_str(), "Skip");
1062        assert_eq!(AutoTerminateKind::Now.as_str(), "Now");
1063    }
1064
1065    /// Every kind's `as_str` is in canonical PascalCase. The first
1066    /// character is uppercase; no whitespace; no separators. The
1067    /// `tatara-process` PascalCase idiom holds at one test site.
1068    #[test]
1069    fn auto_terminate_kind_as_str_is_pascal_case() {
1070        for kind in AutoTerminateKind::ALL {
1071            let s = kind.as_str();
1072            assert!(!s.is_empty(), "as_str empty for {kind:?}");
1073            assert!(
1074                s.chars().next().unwrap().is_ascii_uppercase(),
1075                "as_str not PascalCase for {kind:?}: {s}",
1076            );
1077            assert!(
1078                !s.contains(|c: char| c.is_whitespace() || c == '_' || c == '-'),
1079                "as_str carries separator for {kind:?}: {s}",
1080            );
1081        }
1082    }
1083
1084    /// `Display` IS `as_str` — pinning this lets future callers reach
1085    /// for either projection without drift.
1086    #[test]
1087    fn auto_terminate_kind_display_matches_as_str() {
1088        crate::tagged_union::assert_display_matches_label::<AutoTerminateKind>();
1089    }
1090
1091    /// `FromStr` rejects strings outside the canonical projection
1092    /// (lowercased / typo / cross-axis-leaked) and echoes the input
1093    /// verbatim. The empty-string arm AND the round-trip sweep are
1094    /// covered by `auto_terminate_kind_is_well_formed_closed_set` via
1095    /// the [`tatara_lisp::ClosedSet`] contract; the cases here pin the
1096    /// `UnknownAutoTerminateKind` newtype payload contract the
1097    /// trait's `make_unknown` cannot see. Cross-axis inputs
1098    /// (ProcessPhase / TeardownPolicy / TerminateReasonKind variant
1099    /// names) MUST fail — `AutoTerminateKind` is its own axis, not
1100    /// a transparent reflection of any sibling enum.
1101    #[test]
1102    fn unknown_auto_terminate_kind_errors() {
1103        use std::str::FromStr;
1104        for bad in [
1105            "skip",
1106            "now",
1107            "SKIP",
1108            "NOW",
1109            "S",
1110            "N",
1111            "no-op",
1112            "terminate",
1113            // Cross-axis-leaked — must NOT cross axes.
1114            "Attested",
1115            "Failed",
1116            "TeardownPolicy",
1117            "TtlExpired",
1118            "Always",
1119            "Permanent",
1120            "Ephemeral",
1121        ] {
1122            let err = AutoTerminateKind::from_str(bad).unwrap_err();
1123            assert_eq!(err.0, bad, "error payload should echo input verbatim");
1124        }
1125    }
1126
1127    /// `reason()` projection: `Now { reason }` returns `Some(&reason)`,
1128    /// `Skip` returns `None`. The (variant-name → payload-field)
1129    /// binding lives at ONE site so a future third payload-carrying
1130    /// variant updates every consumer through this method's
1131    /// exhaustiveness check rather than scattering destructures across
1132    /// the call graph.
1133    #[test]
1134    fn auto_terminate_reason_projection() {
1135        assert!(AutoTerminate::Skip.reason().is_none());
1136
1137        let reason = TerminateReason::TtlExpired {
1138            ttl: "1h".into(),
1139            elapsed: Duration::from_secs(0),
1140        };
1141        let now = AutoTerminate::Now {
1142            reason: reason.clone(),
1143        };
1144        assert_eq!(now.reason(), Some(&reason));
1145
1146        let teardown = TerminateReason::TeardownPolicy {
1147            policy: TeardownPolicy::OnAttested,
1148            phase: ProcessPhase::Attested,
1149        };
1150        let now = AutoTerminate::Now {
1151            reason: teardown.clone(),
1152        };
1153        assert_eq!(now.reason(), Some(&teardown));
1154    }
1155
1156    /// `is_now` / `is_skip` are exact complements over the closed set —
1157    /// `is_now ⊕ is_skip = true` for every variant. Locks the predicate
1158    /// pair so a future third variant that's neither Skip nor Now must
1159    /// extend BOTH predicates in lockstep (or this contract fails).
1160    #[test]
1161    fn auto_terminate_predicate_pair_is_exhaustive_complement() {
1162        let reason = TerminateReason::TtlExpired {
1163            ttl: "1h".into(),
1164            elapsed: Duration::from_secs(0),
1165        };
1166        for decision in [
1167            AutoTerminate::Skip,
1168            AutoTerminate::Now {
1169                reason: reason.clone(),
1170            },
1171        ] {
1172            assert_ne!(
1173                decision.is_now(),
1174                decision.is_skip(),
1175                "predicate pair drift for {decision:?}",
1176            );
1177            // The kind projection agrees with each predicate.
1178            assert_eq!(decision.is_now(), decision.kind() == AutoTerminateKind::Now);
1179            assert_eq!(
1180                decision.is_skip(),
1181                decision.kind() == AutoTerminateKind::Skip
1182            );
1183            // `reason()` agrees with `is_now`.
1184            assert_eq!(decision.reason().is_some(), decision.is_now());
1185        }
1186    }
1187
1188    /// The `kind()` projection on the typed result of `evaluate` agrees
1189    /// with the behavioural expectation: ephemeral-on-Attested with an
1190    /// OnAttested policy returns `Now`, permanent never does. Closes
1191    /// the loop between the closed-set view and the live decision so
1192    /// any future kind-keyed metrics label (e.g.
1193    /// `tatara_lifetime_clock_decisions_total{kind="Now"}`) reads the
1194    /// typed projection rather than the inline destructure.
1195    #[test]
1196    fn evaluate_decision_kind_agrees_with_runtime_behaviour() {
1197        let p = permanent_process();
1198        for phase in [
1199            ProcessPhase::Pending,
1200            ProcessPhase::Running,
1201            ProcessPhase::Attested,
1202            ProcessPhase::Failed,
1203        ] {
1204            let decision = evaluate(&p, phase, Utc::now());
1205            assert_eq!(
1206                decision.kind(),
1207                AutoTerminateKind::Skip,
1208                "permanent Process must always Skip; got Now for phase={phase:?}",
1209            );
1210            assert!(decision.reason().is_none());
1211        }
1212
1213        let p = ephemeral_process("1h", TeardownPolicy::OnAttested, 60);
1214        let now = Utc::now();
1215        assert_eq!(
1216            evaluate(&p, ProcessPhase::Attested, now).kind(),
1217            AutoTerminateKind::Now,
1218        );
1219        assert_eq!(
1220            evaluate(&p, ProcessPhase::Running, now).kind(),
1221            AutoTerminateKind::Skip,
1222        );
1223    }
1224
1225    #[test]
1226    fn requeue_picks_min_of_default_and_remaining() {
1227        let p = ephemeral_process("5m", TeardownPolicy::Always, 60);
1228        let now = Utc::now();
1229        let d = requeue_with_ttl(&p, now, Duration::from_secs(30));
1230        // 5m total - 60s elapsed = 240s remaining; default 30s wins.
1231        assert_eq!(d, Duration::from_secs(30));
1232
1233        let p = ephemeral_process("90s", TeardownPolicy::Always, 80);
1234        let d = requeue_with_ttl(&p, now, Duration::from_secs(30));
1235        // 90s - 80s = 10s remaining; remaining wins.
1236        assert!(d <= Duration::from_secs(11) && d >= Duration::from_secs(9));
1237
1238        let p = ephemeral_process("90s", TeardownPolicy::Always, 91);
1239        let d = requeue_with_ttl(&p, now, Duration::from_secs(30));
1240        // Already past TTL — clamp to 1s, not 0.
1241        assert_eq!(d, Duration::from_secs(1));
1242    }
1243}