Skip to main content

tatara_process/
signal.rs

1//! First-class CRD signals — Unix semantics over Kubernetes.
2//!
3//! Signals are delivered via annotation (`tatara.pleme.io/signal=SIGHUP`) or
4//! via the MCP `signal_process` tool; the reconciler consumes them,
5//! enqueues on `status.signalQueue`, and drains in phase order.
6
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9
10use crate::phase::ProcessPhase;
11
12/// The first-class signals the controller honors.
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
14#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
15pub enum ProcessSignal {
16    /// Reconfigure — re-enter Execing without termination.
17    /// Fires on spec change, drift detection, or manual invocation.
18    Sighup,
19    /// Graceful terminate — finalizer path with children draining first.
20    Sigterm,
21    /// Force terminate — `grace_period_seconds: 0` on all owned resources.
22    Sigkill,
23    /// Force re-attestation without spec change — recomputes three-pillar hash.
24    Sigusr1,
25    /// Force remediation — invokes kensa remediation hooks.
26    Sigusr2,
27    /// Pause reconciliation — fixed-point driver is suspended.
28    Sigstop,
29    /// Resume reconciliation after SIGSTOP.
30    Sigcont,
31}
32
33impl ProcessSignal {
34    /// The closed set of signals — single source of truth that
35    /// drives `as_str` / `short_str` / `FromStr` so adding a variant
36    /// updates every projection at once (and the
37    /// `short_str_strips_sig_prefix` + `all_signals_roundtrip_*`
38    /// tests pin the bridge).
39    pub const ALL: [Self; 7] = [
40        Self::Sighup,
41        Self::Sigterm,
42        Self::Sigkill,
43        Self::Sigusr1,
44        Self::Sigusr2,
45        Self::Sigstop,
46        Self::Sigcont,
47    ];
48
49    pub const fn as_str(self) -> &'static str {
50        match self {
51            Self::Sighup => "SIGHUP",
52            Self::Sigterm => "SIGTERM",
53            Self::Sigkill => "SIGKILL",
54            Self::Sigusr1 => "SIGUSR1",
55            Self::Sigusr2 => "SIGUSR2",
56            Self::Sigstop => "SIGSTOP",
57            Self::Sigcont => "SIGCONT",
58        }
59    }
60
61    /// The short alias accepted by `FromStr` — the canonical
62    /// `as_str()` form with the leading `"SIG"` stripped (`"HUP"`,
63    /// `"TERM"`, …). The `short_str_strips_sig_prefix` test asserts
64    /// this contract structurally so the two projections cannot
65    /// drift.
66    pub const fn short_str(self) -> &'static str {
67        match self {
68            Self::Sighup => "HUP",
69            Self::Sigterm => "TERM",
70            Self::Sigkill => "KILL",
71            Self::Sigusr1 => "USR1",
72            Self::Sigusr2 => "USR2",
73            Self::Sigstop => "STOP",
74            Self::Sigcont => "CONT",
75        }
76    }
77}
78
79impl std::fmt::Display for ProcessSignal {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        f.write_str(self.as_str())
82    }
83}
84
85impl std::str::FromStr for ProcessSignal {
86    type Err = UnknownSignal;
87    fn from_str(s: &str) -> Result<Self, Self::Err> {
88        let upper = s.to_ascii_uppercase();
89        for sig in Self::ALL {
90            if upper == sig.as_str() || upper == sig.short_str() {
91                return Ok(sig);
92            }
93        }
94        Err(UnknownSignal(upper))
95    }
96}
97
98#[derive(Debug, thiserror::Error)]
99#[error("unknown signal: {0}")]
100pub struct UnknownSignal(pub String);
101
102/// How a Process handles SIGHUP.
103///
104/// Sibling closed-set lifts on the same `ProcessSpec` axis:
105/// [`ProcessSignal::ALL`] (parser triad), [`crate::phase::ProcessPhase::ALL`]
106/// (target codomain), [`crate::spec::MustReachPhase::ALL`] (typed subset of
107/// ProcessPhase).
108#[derive(
109    Clone,
110    Copy,
111    Debug,
112    PartialEq,
113    Eq,
114    Hash,
115    Serialize,
116    Deserialize,
117    JsonSchema,
118    Default,
119    tatara_closed_set::DeriveClosedSet,
120)]
121#[serde(rename_all = "PascalCase")]
122#[closed_set(via = "as_str", generate_unknown, display)]
123pub enum SighupStrategy {
124    /// Running → Reconverging → Execing without tearing down resources.
125    #[default]
126    Reconverge,
127    /// Running → Exiting → Reaped → Pending (full respawn).
128    Restart,
129    /// Ignore the signal.
130    Noop,
131}
132
133impl SighupStrategy {
134    /// The closed set of SIGHUP strategies — single source of truth that
135    /// drives the `as_str` / Display / `FromStr` triad and the typed
136    /// `sighup_target` projection. Adding a fourth strategy (e.g. a
137    /// future `Suspend` that maps SIGHUP to `SignalEffect::Suspend`)
138    /// lands at one `ALL` entry, one `as_str` arm, and one
139    /// `sighup_target` arm — exhaustively checked by the compiler
140    /// (the `[Self; 3]` array literal forces the arity).
141    pub const ALL: [Self; 3] = [Self::Reconverge, Self::Restart, Self::Noop];
142
143    /// Canonical PascalCase wire-format projection — matches the serde
144    /// `rename_all = "PascalCase"` output verbatim. Used by Display
145    /// (single source of truth), by `FromStr` to identify the variant
146    /// from its annotation / status-field representation, and by
147    /// operator-facing diagnostic strings without re-serializing
148    /// through `serde_json`. Pinned by
149    /// `sighup_strategy_as_str_matches_serde`.
150    pub const fn as_str(self) -> &'static str {
151        match self {
152            Self::Reconverge => "Reconverge",
153            Self::Restart => "Restart",
154            Self::Noop => "Noop",
155        }
156    }
157
158    /// Typed projection: when this Process receives SIGHUP while in a
159    /// `is_running()` phase, which `ProcessPhase` does the reconciler
160    /// transition into? `None` means SIGHUP is a no-op (the `Noop`
161    /// strategy). The phase guard lives at the call site (the strategy
162    /// itself doesn't know about phase), so the codomain is purely a
163    /// function of the strategy variant.
164    ///
165    /// Used by `tatara_reconciler::signals::apply` to lift the three
166    /// SIGHUP arms (Reconverge / Restart / Noop) into one
167    /// projection-driven arm. A future variant lands at one
168    /// `sighup_target` arm; `apply` doesn't change.
169    ///
170    /// Pinned by `sighup_target_truth_table` (per-variant codomain)
171    /// AND by `sighup_target_projects_only_to_legal_sighup_transitions`
172    /// (every `Some(target)` must be reachable from `Running` /
173    /// `Attested` via `ProcessPhase::can_transition_to`).
174    pub const fn sighup_target(self) -> Option<ProcessPhase> {
175        match self {
176            Self::Reconverge => Some(ProcessPhase::Reconverging),
177            Self::Restart => Some(ProcessPhase::Exiting),
178            Self::Noop => None,
179        }
180    }
181}
182
183// `impl FromStr for SighupStrategy` +
184// `impl tatara_lisp::ClosedSet for SighupStrategy` +
185// `impl std::fmt::Display for SighupStrategy` +
186// `pub struct UnknownSighupStrategy(pub String)` are all generated
187// by `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(via =
188// "as_str", generate_unknown, display)]` on the enum declaration
189// above. `label` delegates to the inherent
190// `SighupStrategy::as_str` — the PascalCase wire-vocabulary
191// projection stays load-bearing (matches the serde
192// `rename_all = "PascalCase"` projection verbatim), while generic
193// `T: ClosedSet` consumers reach the STABLE workspace-wide name
194// (`label`). The auto-derived carrier label "sighup strategy"
195// matches the prior hand-rolled `#[error("unknown sighup strategy:
196// {0}")]` annotation byte-for-byte.
197//
198// [`ProcessSignal`] is NOT a `ClosedSet` implementor — its
199// `FromStr` keys on a compound projection (`as_str` || `short_str`)
200// with case-insensitive uppercase normalization rather than a
201// single canonical label, the same exemption pattern as
202// [`tatara_lisp::CompilerSpecIoStage`]'s compound `(operation,
203// label)` key. Only [`SighupStrategy`] (single PascalCase label, no
204// normalization) plugs into the derive here.
205
206#[cfg(test)]
207mod tests {
208    use super::{ProcessSignal, SighupStrategy, UnknownSighupStrategy};
209    use crate::phase::ProcessPhase;
210    use std::str::FromStr;
211
212    #[test]
213    fn all_signals_roundtrip_canonical() {
214        for sig in ProcessSignal::ALL {
215            assert_eq!(ProcessSignal::from_str(sig.as_str()).unwrap(), sig);
216        }
217    }
218
219    #[test]
220    fn all_signals_roundtrip_short() {
221        for sig in ProcessSignal::ALL {
222            assert_eq!(ProcessSignal::from_str(sig.short_str()).unwrap(), sig);
223        }
224    }
225
226    /// The structural contract that lets `FromStr` parse off two
227    /// projections without drift: `short_str()` is exactly
228    /// `as_str()` minus the leading `"SIG"`. Any new variant whose
229    /// canonical form doesn't follow the `SIG*` convention has to
230    /// either rename or override this test deliberately.
231    #[test]
232    fn short_str_strips_sig_prefix() {
233        for sig in ProcessSignal::ALL {
234            assert_eq!(sig.as_str().strip_prefix("SIG"), Some(sig.short_str()));
235        }
236    }
237
238    /// `ALL` is the source of truth for the parser table — pin its
239    /// closure so a variant added without an `ALL` entry fails here
240    /// (via the uniqueness check) before drifting `FromStr`.
241    #[test]
242    fn all_is_unique_and_complete() {
243        let mut seen = std::collections::HashSet::new();
244        for sig in ProcessSignal::ALL {
245            assert!(seen.insert(sig), "duplicate variant in ALL: {sig:?}");
246        }
247        // The arity is asserted by the array type itself (`[Self; 7]`),
248        // but the uniqueness check above + the const-array length is
249        // what makes ALL a closed set rather than just a list.
250        assert_eq!(seen.len(), ProcessSignal::ALL.len());
251    }
252
253    #[test]
254    fn lowercase_short_form_accepted() {
255        assert_eq!(
256            ProcessSignal::from_str("hup").unwrap(),
257            ProcessSignal::Sighup
258        );
259        assert_eq!(
260            ProcessSignal::from_str("term").unwrap(),
261            ProcessSignal::Sigterm
262        );
263    }
264
265    #[test]
266    fn unknown_errors() {
267        let err = ProcessSignal::from_str("sigfoo").unwrap_err();
268        // The error carries the uppercased input — preserves the
269        // pre-refactor contract that `UnknownSignal` echoes the
270        // normalized form, not the operator's casing.
271        assert_eq!(err.0, "SIGFOO");
272    }
273
274    // ── closed-set algebra for SighupStrategy (ALL × as_str × FromStr ×
275    //    sighup_target) ────────────────────────────────────────────────
276
277    /// Structural well-formedness of [`SighupStrategy`] as a
278    /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
279    /// testkit lift that pins all three structural invariants (`ALL`
280    /// is non-empty, every variant round-trips through `label ↔
281    /// parse_label`, labels are pairwise distinct, `""` is outside the
282    /// closed set) at ONE call site. Replaces the hand-derived
283    /// `sighup_strategy_all_is_unique_and_complete` +
284    /// `sighup_strategy_roundtrip_via_as_str` + the empty-input arm of
285    /// `unknown_sighup_strategy_errors`. `FromStr` delegates to
286    /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this helper
287    /// exercises the same code path the reconciler hits when parsing a
288    /// CRD `enum:`-validated value back to the typed strategy.
289    #[test]
290    fn sighup_strategy_is_well_formed_closed_set() {
291        tatara_closed_set::assert_closed_set_well_formed::<SighupStrategy>();
292    }
293
294    /// CANONICAL-KEY CONTRACT: `as_str` matches serde's PascalCase
295    /// output verbatim for every variant. A future variant rename (or
296    /// an `as_str` arm typo) lands here at one site, not in a CRD
297    /// `enum:` enumeration that quietly drifted away from the typed
298    /// surface.
299    #[test]
300    fn sighup_strategy_as_str_matches_serde() {
301        crate::tagged_union::assert_label_matches_serde_serialization::<SighupStrategy>();
302    }
303
304    /// The Display impl IS `as_str` — pinning this lets future callers
305    /// reach for either projection without drift.
306    #[test]
307    fn sighup_strategy_display_matches_as_str() {
308        crate::tagged_union::assert_display_matches_label::<SighupStrategy>();
309    }
310
311    /// `FromStr` rejects strings outside the canonical projection
312    /// (lowercased / typo / unrelated) — and the error echoes the
313    /// input verbatim so the operator-facing diagnostic carries the
314    /// offending value, not a normalized form. The empty-input arm is
315    /// pinned by [`sighup_strategy_is_well_formed_closed_set`] via the
316    /// `tatara_lisp::ClosedSet` testkit; the cases here pin the
317    /// verbatim-echo contract on the [`UnknownSighupStrategy`]
318    /// newtype, which the trait's `make_unknown` can't see.
319    #[test]
320    fn unknown_sighup_strategy_errors() {
321        for bad in ["reconverge", "RESTART", "Suspend", "noop "] {
322            let err = SighupStrategy::from_str(bad).unwrap_err();
323            let UnknownSighupStrategy(payload) = &err;
324            assert_eq!(payload, bad, "error payload should echo input verbatim");
325        }
326    }
327
328    /// PROJECTION TRUTH TABLE: pin the per-variant codomain of
329    /// `sighup_target`. A future variant addition lands here at one
330    /// arm — and the compiler's closed-set match in `sighup_target`
331    /// catches the missing arm before this test runs.
332    #[test]
333    fn sighup_target_truth_table() {
334        assert_eq!(
335            SighupStrategy::Reconverge.sighup_target(),
336            Some(ProcessPhase::Reconverging)
337        );
338        assert_eq!(
339            SighupStrategy::Restart.sighup_target(),
340            Some(ProcessPhase::Exiting)
341        );
342        assert_eq!(SighupStrategy::Noop.sighup_target(), None);
343    }
344
345    /// SEMANTIC SUBSET CONTRACT: every `Some(target)` produced by
346    /// `sighup_target` must be reachable from a `is_running()` phase
347    /// (`Running` or `Attested`) via `ProcessPhase::can_transition_to`.
348    /// This pins the contract `tatara_reconciler::signals::apply`
349    /// relies on: the typed projection produces only phases the
350    /// reconciler is allowed to transition into from the SIGHUP
351    /// reception sites. A future `SighupStrategy::Refresh` that
352    /// projected to `ProcessPhase::Pending` would FAIL here (Pending
353    /// is not a legal successor of Running/Attested), forcing the
354    /// author to either pick a legal target phase or extend
355    /// `ProcessPhase::can_transition_to` deliberately.
356    #[test]
357    fn sighup_target_projects_only_to_legal_sighup_transitions() {
358        for strat in SighupStrategy::ALL {
359            if let Some(target) = strat.sighup_target() {
360                let reachable_from_running = ProcessPhase::Running.can_transition_to(target);
361                let reachable_from_attested = ProcessPhase::Attested.can_transition_to(target);
362                assert!(
363                    reachable_from_running || reachable_from_attested,
364                    "{strat:?}.sighup_target() = {target:?} must be reachable from \
365                     Running or Attested via can_transition_to",
366                );
367            }
368        }
369    }
370
371    /// PROJECTION INJECTIVITY: distinct variants that produce `Some`
372    /// project to distinct `ProcessPhase`s. Pairing this with the
373    /// reachability contract above forces a future SIGHUP strategy
374    /// variant to land on a fresh legal SIGHUP-target phase (or to
375    /// project to `None` and be a deliberate no-op).
376    #[test]
377    fn sighup_target_projection_is_injective() {
378        let mut seen = std::collections::HashSet::new();
379        for strat in SighupStrategy::ALL {
380            if let Some(target) = strat.sighup_target() {
381                assert!(
382                    seen.insert(target),
383                    "two variants project to the same ProcessPhase: {target:?}",
384                );
385            }
386        }
387    }
388}