Skip to main content

nmbrs_runtime/
phase_end_triggers.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Phase-end trigger registry.
5//!
6//! A simple event/callback registry that any subsystem can
7//! attach a callback to. Callbacks fire after every
8//! `phase_completed` and `phase_failed` event from the
9//! executor. Triggers are dispatched on a background worker
10//! thread so a slow callback (e.g. re-rendering a plot
11//! against the live session.db) never blocks the run loop.
12//!
13//! ## Why a separate registry instead of new `RunObserver`
14//! methods
15//!
16//! `RunObserver` is the surface for *display* observers (TUI,
17//! log-only, stderr). A trigger is *behavioral* — it runs work
18//! in response to lifecycle events without contributing to
19//! display rendering. Trying to merge the two via a generic
20//! observer interface forces every plot author to implement
21//! the noisy `phase_starting` / `set_status_line` / `reporters`
22//! surface. The registry is the focused alternative.
23//!
24//! ## Lifecycle
25//!
26//! - [`register`](crate::phase_end_triggers::register) adds a trigger
27//!   and returns a [`TriggerId`](crate::phase_end_triggers::TriggerId).
28//! - [`unregister`](crate::phase_end_triggers::unregister) removes a
29//!   trigger by id (no-op if absent).
30//! - The executor calls
31//!   [`fire_phase_completed`](crate::phase_end_triggers::fire_phase_completed) /
32//!   [`fire_phase_failed`](crate::phase_end_triggers::fire_phase_failed)
33//!   immediately after the observer's
34//!   matching callback. Triggers run on a single worker
35//!   thread in FIFO registration order so a panic in one
36//!   trigger doesn't take down the others (each call is
37//!   `catch_unwind`-guarded).
38//!
39//! ## Synchronization
40//!
41//! The registry sits behind a `std::sync::Mutex` for
42//! registration; the worker thread snapshots the trigger
43//! list on each event so a registration / unregistration mid-
44//! event won't dirty the dispatch. Total cost per phase end
45//! is one channel send + one Vec clone of `Arc<Trigger>`.
46
47use std::any::Any;
48use std::panic;
49use std::sync::Arc;
50use std::sync::Mutex;
51use std::sync::OnceLock;
52use std::sync::atomic::{AtomicUsize, Ordering};
53use std::sync::mpsc;
54use std::time::Duration;
55
56/// Trigger callback. Implementors fire whenever a phase
57/// completes (success or failure). The implementation should
58/// be cheap to set up — long work runs on the worker thread,
59/// not the executor.
60pub trait PhaseEndTrigger: Send + Sync + 'static {
61    /// Fire the trigger. `event` carries the phase identity
62    /// and outcome; the implementation reads whatever live
63    /// state it needs (the session db, the metrics dir) on
64    /// its own.
65    fn fire(&self, event: &PhaseEndEvent);
66
67    /// Human-readable trigger name for logging / debugging.
68    /// Default returns the type name via `Any` downcast hint.
69    fn name(&self) -> &str {
70        "phase-end-trigger"
71    }
72}
73
74/// What the executor knows about a finished phase.
75#[derive(Debug, Clone)]
76pub struct PhaseEndEvent {
77    pub phase_name: String,
78    pub phase_labels: String,
79    pub outcome: PhaseOutcome,
80    pub duration_secs: f64,
81}
82
83/// Outcome flavor — success, failure, or skip-equivalent.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub enum PhaseOutcome {
86    Completed,
87    Failed { error: String },
88}
89
90/// Opaque registration handle returned by [`register`]. Pass
91/// to [`unregister`] to remove the trigger.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
93pub struct TriggerId(u64);
94
95struct Entry {
96    id: TriggerId,
97    trigger: Arc<dyn PhaseEndTrigger>,
98}
99
100struct Registry {
101    next_id: u64,
102    triggers: Vec<Entry>,
103    dispatch: Option<mpsc::Sender<PhaseEndEvent>>,
104}
105
106static REGISTRY: OnceLock<Mutex<Registry>> = OnceLock::new();
107
108/// Lock-free mirror of `Registry::triggers.len()`, kept in sync under the
109/// registry lock by [`register`] / [`unregister`]. [`fire`] reads this
110/// FIRST so the common case — no triggers registered, which is every
111/// concurrent-workload session today — is a single relaxed atomic load
112/// with **no lock**: concurrent executions never synchronize on the
113/// global registry when firing phase-end events (SRD-88 "session
114/// services are lock-free for concurrent workloads").
115static TRIGGER_COUNT: AtomicUsize = AtomicUsize::new(0);
116
117fn registry() -> &'static Mutex<Registry> {
118    REGISTRY.get_or_init(|| {
119        Mutex::new(Registry {
120            next_id: 1,
121            triggers: Vec::new(),
122            dispatch: None,
123        })
124    })
125}
126
127/// Register a phase-end trigger. Returns a [`TriggerId`] the
128/// caller can pass to [`unregister`] later. Idempotent within
129/// a single registration — the same trigger object registered
130/// twice fires twice.
131///
132/// The first registration also spawns the worker thread; it
133/// stays alive for the rest of the process so subsequent
134/// registrations are cheap.
135pub fn register(trigger: Arc<dyn PhaseEndTrigger>) -> TriggerId {
136    let mut reg = registry()
137        .lock()
138        .expect("phase-end-triggers registry poisoned");
139    let id = TriggerId(reg.next_id);
140    reg.next_id += 1;
141    reg.triggers.push(Entry { id, trigger });
142    TRIGGER_COUNT.store(reg.triggers.len(), Ordering::Release);
143    // Lazy worker startup — only when there's at least one
144    // trigger. The thread reads events forever; it shuts down
145    // when the channel sender is dropped (process exit).
146    if reg.dispatch.is_none() {
147        let (tx, rx) = mpsc::channel::<PhaseEndEvent>();
148        reg.dispatch = Some(tx);
149        std::thread::Builder::new()
150            .name("phase-end-trigger-worker".into())
151            .spawn(move || dispatch_loop(rx))
152            .expect("spawn phase-end-trigger worker");
153    }
154    id
155}
156
157/// Remove a previously-registered trigger. No-op when the id
158/// doesn't match anything currently registered (already
159/// removed, never registered, or freed by another caller).
160pub fn unregister(id: TriggerId) {
161    let mut reg = registry()
162        .lock()
163        .expect("phase-end-triggers registry poisoned");
164    reg.triggers.retain(|e| e.id != id);
165    TRIGGER_COUNT.store(reg.triggers.len(), Ordering::Release);
166}
167
168/// Drain the registry — used by integration tests that need
169/// trigger isolation between cases. Production code should
170/// not call this.
171#[cfg(test)]
172pub fn reset_for_tests() {
173    let mut reg = registry()
174        .lock()
175        .expect("phase-end-triggers registry poisoned");
176    reg.triggers.clear();
177    TRIGGER_COUNT.store(0, Ordering::Release);
178    reg.next_id = 1;
179    // We deliberately leave the dispatch channel alive — the
180    // worker thread is fine sitting idle on an empty channel.
181}
182
183/// Fire the trigger chain for a successful phase. Called by
184/// the executor right after `observer.phase_completed(...)`.
185pub fn fire_phase_completed(name: &str, labels: &str, duration_secs: f64) {
186    fire(PhaseEndEvent {
187        phase_name: name.to_string(),
188        phase_labels: labels.to_string(),
189        outcome: PhaseOutcome::Completed,
190        duration_secs,
191    });
192}
193
194/// Fire the trigger chain for a failed phase. Called by the
195/// executor right after `observer.phase_failed(...)`.
196pub fn fire_phase_failed(name: &str, labels: &str, error: &str) {
197    fire(PhaseEndEvent {
198        phase_name: name.to_string(),
199        phase_labels: labels.to_string(),
200        outcome: PhaseOutcome::Failed {
201            error: error.to_string(),
202        },
203        duration_secs: 0.0,
204    });
205}
206
207fn fire(event: PhaseEndEvent) {
208    // Lock-free fast path: no triggers registered ⇒ a relaxed atomic
209    // load and return. Concurrent executions firing phase-end events
210    // never contend on the global registry lock in the common case.
211    if TRIGGER_COUNT.load(Ordering::Acquire) == 0 {
212        return;
213    }
214    let reg = registry()
215        .lock()
216        .expect("phase-end-triggers registry poisoned");
217    if reg.triggers.is_empty() {
218        return;
219    }
220    if let Some(tx) = reg.dispatch.as_ref() {
221        // Send to the worker. A full channel would only
222        // happen if the worker is wedged for many seconds;
223        // we'd rather drop a single event than block the
224        // executor.
225        let _ = tx.send(event);
226    }
227}
228
229fn dispatch_loop(rx: mpsc::Receiver<PhaseEndEvent>) {
230    // Bounded snapshot to limit memory in long-running runs.
231    loop {
232        match rx.recv_timeout(Duration::from_secs(60)) {
233            Ok(event) => {
234                // Snapshot the trigger list so a registration
235                // / unregistration during dispatch can't
236                // mutate the slice underneath us.
237                let snap: Vec<Arc<dyn PhaseEndTrigger>> = {
238                    let reg = match registry().lock() {
239                        Ok(r) => r,
240                        Err(_) => return, // registry poisoned — worker exits
241                    };
242                    reg.triggers.iter().map(|e| e.trigger.clone()).collect()
243                };
244                for trigger in snap {
245                    // Per-trigger catch_unwind so a panic in
246                    // one doesn't drop subsequent ones.
247                    let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
248                        trigger.fire(&event);
249                    }));
250                    if let Err(payload) = result {
251                        let msg = payload_to_message(payload);
252                        // Surface the failure but don't take
253                        // the worker down. The session log
254                        // sink picks this up via diag!.
255                        crate::diag!(
256                            crate::observer::LogLevel::Warn,
257                            "phase-end trigger '{name}' panicked: {msg}",
258                            name = trigger.name(),
259                        );
260                    }
261                }
262            }
263            Err(mpsc::RecvTimeoutError::Timeout) => {
264                // Idle wakeup — loop back. Keeps the thread
265                // responsive to a clean process shutdown
266                // without spamming CPU on busy waits.
267            }
268            Err(mpsc::RecvTimeoutError::Disconnected) => {
269                // Sender dropped — process is exiting. Quiet
270                // exit.
271                return;
272            }
273        }
274    }
275}
276
277fn payload_to_message(payload: Box<dyn Any + Send>) -> String {
278    if let Some(s) = payload.downcast_ref::<&'static str>() {
279        (*s).to_string()
280    } else if let Some(s) = payload.downcast_ref::<String>() {
281        s.clone()
282    } else {
283        "<non-string panic payload>".to_string()
284    }
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290    use std::sync::Mutex as StdMutex;
291    use std::sync::atomic::{AtomicUsize, Ordering};
292    use std::time::Instant;
293
294    /// Counter trigger — records how many times it fired and
295    /// the names of the phases it saw.
296    struct CountingTrigger {
297        count: Arc<AtomicUsize>,
298        names: Arc<StdMutex<Vec<String>>>,
299        name: &'static str,
300    }
301    impl PhaseEndTrigger for CountingTrigger {
302        fn name(&self) -> &str {
303            self.name
304        }
305        fn fire(&self, event: &PhaseEndEvent) {
306            self.count.fetch_add(1, Ordering::Release);
307            self.names.lock().unwrap().push(event.phase_name.clone());
308        }
309    }
310
311    /// Wait for `count` to reach `target` or `timeout` to
312    /// elapse. The worker is async — tests synchronize via
313    /// the counter, not via channel polling.
314    fn wait_for(count: &AtomicUsize, target: usize, timeout: Duration) -> bool {
315        let start = Instant::now();
316        while count.load(Ordering::Acquire) < target {
317            if start.elapsed() > timeout {
318                return false;
319            }
320            std::thread::sleep(Duration::from_millis(5));
321        }
322        true
323    }
324
325    /// Locking across test cases — the registry is global, so
326    /// concurrent tests would step on each other.
327    static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
328
329    #[test]
330    fn registered_trigger_fires_for_completed_phase() {
331        let _g = TEST_LOCK.lock().unwrap();
332        reset_for_tests();
333        let count = Arc::new(AtomicUsize::new(0));
334        let names = Arc::new(StdMutex::new(Vec::new()));
335        let trig = Arc::new(CountingTrigger {
336            count: count.clone(),
337            names: names.clone(),
338            name: "test",
339        });
340        let _id = register(trig);
341
342        fire_phase_completed("setup", "", 1.5);
343        assert!(
344            wait_for(&count, 1, Duration::from_secs(2)),
345            "trigger did not fire within 2s"
346        );
347        assert_eq!(*names.lock().unwrap(), vec!["setup".to_string()]);
348        reset_for_tests();
349    }
350
351    #[test]
352    fn registered_trigger_fires_for_failed_phase() {
353        let _g = TEST_LOCK.lock().unwrap();
354        reset_for_tests();
355        let count = Arc::new(AtomicUsize::new(0));
356        let names = Arc::new(StdMutex::new(Vec::new()));
357        let trig = Arc::new(CountingTrigger {
358            count: count.clone(),
359            names: names.clone(),
360            name: "test",
361        });
362        let _id = register(trig);
363
364        fire_phase_failed("query", "k=10", "timeout");
365        assert!(wait_for(&count, 1, Duration::from_secs(2)));
366        assert_eq!(*names.lock().unwrap(), vec!["query".to_string()]);
367        reset_for_tests();
368    }
369
370    #[test]
371    fn unregister_stops_subsequent_dispatches() {
372        let _g = TEST_LOCK.lock().unwrap();
373        reset_for_tests();
374        let count = Arc::new(AtomicUsize::new(0));
375        let names = Arc::new(StdMutex::new(Vec::new()));
376        let trig = Arc::new(CountingTrigger {
377            count: count.clone(),
378            names: names.clone(),
379            name: "test",
380        });
381        let id = register(trig);
382
383        fire_phase_completed("a", "", 0.1);
384        assert!(wait_for(&count, 1, Duration::from_secs(2)));
385
386        unregister(id);
387        fire_phase_completed("b", "", 0.2);
388        // Worker is async — give it time to (not) fire.
389        std::thread::sleep(Duration::from_millis(100));
390        assert_eq!(
391            count.load(Ordering::Acquire),
392            1,
393            "trigger fired after unregister"
394        );
395        reset_for_tests();
396    }
397
398    #[test]
399    fn multiple_triggers_fire_in_registration_order() {
400        let _g = TEST_LOCK.lock().unwrap();
401        reset_for_tests();
402        let count_a = Arc::new(AtomicUsize::new(0));
403        let count_b = Arc::new(AtomicUsize::new(0));
404        let names = Arc::new(StdMutex::new(Vec::new()));
405        let _id_a = register(Arc::new(CountingTrigger {
406            count: count_a.clone(),
407            names: names.clone(),
408            name: "a",
409        }));
410        let _id_b = register(Arc::new(CountingTrigger {
411            count: count_b.clone(),
412            names: names.clone(),
413            name: "b",
414        }));
415
416        fire_phase_completed("phase1", "", 0.0);
417        assert!(wait_for(&count_a, 1, Duration::from_secs(2)));
418        assert!(wait_for(&count_b, 1, Duration::from_secs(2)));
419        assert_eq!(
420            *names.lock().unwrap(),
421            vec!["phase1".to_string(), "phase1".to_string()]
422        );
423        reset_for_tests();
424    }
425
426    #[test]
427    fn panic_in_one_trigger_does_not_stop_others() {
428        let _g = TEST_LOCK.lock().unwrap();
429        reset_for_tests();
430        struct PanickingTrigger;
431        impl PhaseEndTrigger for PanickingTrigger {
432            fn name(&self) -> &str {
433                "panicker"
434            }
435            fn fire(&self, _: &PhaseEndEvent) {
436                panic!("boom");
437            }
438        }
439        let count = Arc::new(AtomicUsize::new(0));
440        let names = Arc::new(StdMutex::new(Vec::new()));
441        let _a = register(Arc::new(PanickingTrigger));
442        let _b = register(Arc::new(CountingTrigger {
443            count: count.clone(),
444            names: names.clone(),
445            name: "after-panic",
446        }));
447        fire_phase_completed("phase", "", 0.0);
448        // The downstream counter must still see its fire.
449        assert!(
450            wait_for(&count, 1, Duration::from_secs(2)),
451            "downstream trigger lost to upstream panic"
452        );
453        reset_for_tests();
454    }
455
456    #[test]
457    fn fire_with_no_triggers_is_noop() {
458        let _g = TEST_LOCK.lock().unwrap();
459        reset_for_tests();
460        // No registrations, no panic, no channel send.
461        fire_phase_completed("x", "", 1.0);
462        fire_phase_failed("y", "", "oops");
463        // Nothing to assert — the call returns without
464        // touching the worker. Implicit pass.
465    }
466}