Skip to main content

feral_ordering_core/
interrupt.rs

1//! Cooperative interruption of long-running orderings (feral issue #246).
2//!
3//! An [`Interrupt`] carries an optional wall-clock deadline and an optional
4//! cancel flag. [`scope`] installs one for the duration of a closure on the
5//! current thread. Long-running loops in the ordering crates call [`poll`]
6//! or [`check`] at safe points (between pivots, levels, trials and passes)
7//! with no change to their signatures.
8//!
9//! **Single-thread assumption.** A thread-local is sound here because every
10//! ordering in this family (`feral-amd`, `-amf`, `-metis`, `-scotch`,
11//! `-kahip`), and feral's symbolic pipeline and MC64 matching, run
12//! entirely on the thread that called [`scope`]. If any of them ever moves
13//! work onto rayon or spawned threads, polls on those workers see *no*
14//! active interrupt, and the deadline silently stops working there. Code
15//! that goes parallel must capture the interrupt with [`current`] and
16//! re-install it on each worker with [`scope`]. Each ordering crate has a
17//! `tests/interrupt_threads.rs` that uses the [`census`] to fail if an
18//! ordering polls from a thread with no scope while its caller has one, so
19//! such a change cannot slip in unnoticed.
20//!
21//! **Sticky.** Once a poll inside a scope has seen the interrupt trigger,
22//! every later poll in that scope reports it, even if the flag is cleared.
23//! A loop that breaks out early on [`poll`] can therefore rely on the next
24//! [`check`] up the stack returning [`OrderingError::Interrupted`], so a
25//! partially computed intermediate is never used as a result.
26//!
27//! With no interrupt installed, a poll costs one thread-local read.
28
29use crate::OrderingError;
30use std::cell::{Cell, RefCell};
31use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
32use std::sync::Arc;
33use std::time::{Duration, Instant};
34
35/// A deadline and/or a cancel flag. `Interrupt::default()` never triggers.
36#[derive(Debug, Clone, Default)]
37pub struct Interrupt {
38    deadline: Option<Instant>,
39    flag: Option<Arc<AtomicBool>>,
40}
41
42impl Interrupt {
43    /// An interrupt that never triggers.
44    pub fn none() -> Self {
45        Self::default()
46    }
47
48    /// Trigger once `deadline` has passed.
49    pub fn at(deadline: Instant) -> Self {
50        Self {
51            deadline: Some(deadline),
52            flag: None,
53        }
54    }
55
56    /// Trigger once `budget` has elapsed from now.
57    pub fn after(budget: Duration) -> Self {
58        Self::at(Instant::now() + budget)
59    }
60
61    /// Also trigger when `flag` is set (from any thread).
62    pub fn with_flag(mut self, flag: Arc<AtomicBool>) -> Self {
63        self.flag = Some(flag);
64        self
65    }
66
67    /// Also trigger at `deadline` (replacing any earlier deadline).
68    pub fn with_deadline(mut self, deadline: Instant) -> Self {
69        self.deadline = Some(deadline);
70        self
71    }
72
73    /// The deadline, if any.
74    pub fn deadline(&self) -> Option<Instant> {
75        self.deadline
76    }
77
78    /// True when a deadline is set and has passed. Lets a host that set
79    /// both a deadline and a flag tell which one fired.
80    pub fn deadline_passed(&self) -> bool {
81        self.deadline.is_some_and(|d| Instant::now() >= d)
82    }
83
84    /// True when the cancel flag is set.
85    pub fn flag_set(&self) -> bool {
86        self.flag
87            .as_ref()
88            .is_some_and(|f| f.load(Ordering::Relaxed))
89    }
90
91    /// True when either the deadline has passed or the flag is set.
92    pub fn is_triggered(&self) -> bool {
93        self.flag_set() || self.deadline_passed()
94    }
95
96    /// True when this interrupt can never trigger.
97    pub fn is_inert(&self) -> bool {
98        self.deadline.is_none() && self.flag.is_none()
99    }
100}
101
102thread_local! {
103    static ACTIVE: RefCell<Option<Interrupt>> = const { RefCell::new(None) };
104    static TRIPPED: Cell<bool> = const { Cell::new(false) };
105}
106
107/// Restores the previous scope state on drop, including during unwinding.
108struct ScopeGuard {
109    prev: Option<Interrupt>,
110    prev_tripped: bool,
111}
112
113impl Drop for ScopeGuard {
114    fn drop(&mut self) {
115        let prev = self.prev.take();
116        ACTIVE.with(|a| *a.borrow_mut() = prev);
117        TRIPPED.with(|t| t.set(self.prev_tripped));
118    }
119}
120
121/// Run `f` with `interrupt` active on this thread, then restore whatever
122/// was active before (also on panic). An inert interrupt still opens a
123/// scope, which shields `f` from an outer interrupt; use [`scope_if`] to
124/// keep the outer one.
125pub fn scope<R>(interrupt: &Interrupt, f: impl FnOnce() -> R) -> R {
126    let prev = ACTIVE.with(|a| a.borrow_mut().replace(interrupt.clone()));
127    let prev_tripped = TRIPPED.with(|t| t.replace(false));
128    let _guard = ScopeGuard { prev, prev_tripped };
129    f()
130}
131
132/// [`scope`] when `interrupt` is `Some`, otherwise run `f` under whatever
133/// is already active.
134pub fn scope_if<R>(interrupt: Option<&Interrupt>, f: impl FnOnce() -> R) -> R {
135    match interrupt {
136        Some(i) => scope(i, f),
137        None => f(),
138    }
139}
140
141/// True when the active interrupt has triggered (sticky within its scope).
142/// With no active interrupt, returns false.
143pub fn poll() -> bool {
144    if TRIPPED.with(|t| t.get()) {
145        census::record(true);
146        return true;
147    }
148    let (present, hit) = ACTIVE.with(|a| {
149        let a = a.borrow();
150        (a.is_some(), a.as_ref().is_some_and(Interrupt::is_triggered))
151    });
152    census::record(present);
153    if hit {
154        TRIPPED.with(|t| t.set(true));
155    }
156    hit
157}
158
159/// The interrupt active on this thread, if any. Parallel code captures it
160/// here and re-installs it on each worker with [`scope`] (see the module
161/// docs on the single-thread assumption).
162pub fn current() -> Option<Interrupt> {
163    ACTIVE.with(|a| a.borrow().clone())
164}
165
166/// Opt-in poll census for tests that guard the single-thread assumption
167/// (PR #247 review).
168///
169/// While armed, every [`poll`]/[`check`] on any thread is counted as either
170/// *scoped* (its thread had a [`scope`] installed) or *unscoped*. A test arms
171/// it, runs an ordering inside a scope, and asserts `unscoped == 0` and
172/// `scoped > 0`. A non-zero `unscoped` means some poll ran on a thread the
173/// interrupt never reached. Disarmed (always, outside such tests), the cost
174/// is one relaxed atomic load per poll. Run each census test in its own
175/// test binary, so that no unrelated thread polls while it is armed.
176pub mod census {
177    use super::{AtomicBool, AtomicUsize, Ordering};
178
179    static ARMED: AtomicBool = AtomicBool::new(false);
180    static SCOPED: AtomicUsize = AtomicUsize::new(0);
181    static UNSCOPED: AtomicUsize = AtomicUsize::new(0);
182
183    #[inline]
184    pub(super) fn record(scoped: bool) {
185        if ARMED.load(Ordering::Relaxed) {
186            let c = if scoped { &SCOPED } else { &UNSCOPED };
187            c.fetch_add(1, Ordering::Relaxed);
188        }
189    }
190
191    /// Poll counts gathered by [`take`].
192    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
193    pub struct Counts {
194        /// Polls from a thread with a scope installed.
195        pub scoped: usize,
196        /// Polls from a thread with no scope installed.
197        pub unscoped: usize,
198    }
199
200    /// Zero the counters and start counting.
201    pub fn arm() {
202        SCOPED.store(0, Ordering::Relaxed);
203        UNSCOPED.store(0, Ordering::Relaxed);
204        ARMED.store(true, Ordering::SeqCst);
205    }
206
207    /// Stop counting and return what was counted since [`arm`].
208    pub fn take() -> Counts {
209        ARMED.store(false, Ordering::SeqCst);
210        Counts {
211            scoped: SCOPED.load(Ordering::Relaxed),
212            unscoped: UNSCOPED.load(Ordering::Relaxed),
213        }
214    }
215}
216
217/// `Err(OrderingError::Interrupted)` when [`poll`] is true.
218pub fn check() -> Result<(), OrderingError> {
219    if poll() {
220        Err(OrderingError::Interrupted)
221    } else {
222        Ok(())
223    }
224}
225
226/// True when an interrupt that can trigger is active on this thread.
227pub fn is_active() -> bool {
228    ACTIVE.with(|a| a.borrow().as_ref().is_some_and(|i| !i.is_inert()))
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    fn expired() -> Interrupt {
236        Interrupt::at(Instant::now() - Duration::from_secs(1))
237    }
238
239    #[test]
240    fn none_never_triggers_and_poll_without_scope_is_false() {
241        assert!(!Interrupt::none().is_triggered());
242        assert!(Interrupt::none().is_inert());
243        assert!(!poll());
244        assert!(check().is_ok());
245        assert!(!is_active());
246        assert!(!scope(&Interrupt::none(), poll));
247    }
248
249    #[test]
250    fn deadline_and_flag_trigger() {
251        assert!(expired().is_triggered());
252        assert!(expired().deadline_passed());
253        let far = Interrupt::after(Duration::from_secs(3600));
254        assert!(!far.is_triggered());
255        let flag = Arc::new(AtomicBool::new(false));
256        let i = far.with_flag(flag.clone());
257        assert!(!i.is_triggered());
258        flag.store(true, Ordering::Relaxed);
259        assert!(i.is_triggered());
260        assert!(i.flag_set());
261        assert!(!i.deadline_passed());
262    }
263
264    #[test]
265    fn scope_nests_and_restores() {
266        scope(&expired(), || {
267            assert!(poll());
268            assert_eq!(check(), Err(OrderingError::Interrupted));
269            // An inner inert scope shields from the outer interrupt...
270            scope(&Interrupt::none(), || assert!(!poll()));
271            // ...and the outer one (still tripped) is back afterwards.
272            assert!(poll());
273            // scope_if(None) keeps the outer interrupt.
274            scope_if(None, || assert!(poll()));
275        });
276        assert!(!poll());
277        assert!(!is_active());
278    }
279
280    #[test]
281    fn scope_restores_on_panic() {
282        let r = std::panic::catch_unwind(|| {
283            scope(&expired(), || {
284                assert!(poll());
285                panic!("boom");
286            })
287        });
288        assert!(r.is_err());
289        assert!(!poll(), "the panicking scope must not leak its interrupt");
290    }
291
292    #[test]
293    fn trigger_is_sticky_within_a_scope() {
294        let flag = Arc::new(AtomicBool::new(true));
295        let i = Interrupt::none().with_flag(flag.clone());
296        scope(&i, || {
297            assert!(poll());
298            flag.store(false, Ordering::Relaxed);
299            assert!(poll(), "a seen trigger must stay seen in its scope");
300        });
301        // A fresh scope with the cleared flag starts untripped.
302        scope(&i, || assert!(!poll()));
303    }
304
305    /// A path graph 0-1-...-(n-1) as a full symmetric CSC pattern.
306    fn path(n: usize) -> (Vec<i32>, Vec<i32>) {
307        let mut cp = vec![0i32];
308        let mut ri = Vec::new();
309        for j in 0..n {
310            if j > 0 {
311                ri.push((j - 1) as i32);
312            }
313            ri.push(j as i32);
314            if j + 1 < n {
315                ri.push((j + 1) as i32);
316            }
317            cp.push(ri.len() as i32);
318        }
319        (cp, ri)
320    }
321
322    #[test]
323    fn elimination_loops_stop_on_an_expired_interrupt() {
324        use crate::quotient_graph::{order, MinDegree, MinFill, WorkspaceOptions};
325        let (cp, ri) = path(500);
326        let pat = crate::CscPattern::new(500, &cp, &ri).expect("pattern");
327        let opts = WorkspaceOptions::default();
328        let amd = scope(&expired(), || order::<MinDegree>(&pat, &opts, true));
329        assert_eq!(amd.err(), Some(OrderingError::Interrupted));
330        let amf = scope(&expired(), || order::<MinFill>(&pat, &opts, true));
331        assert_eq!(amf.err(), Some(OrderingError::Interrupted));
332        // No interrupt: unchanged result.
333        let base = order::<MinDegree>(&pat, &opts, true).expect("amd").0;
334        let inert = scope(&Interrupt::none(), || order::<MinDegree>(&pat, &opts, true))
335            .expect("amd")
336            .0;
337        assert_eq!(base, inert);
338    }
339
340    /// The census catches exactly the failure the single-thread assumption
341    /// guards against: a worker thread polling while its parent has a scope.
342    /// (Other tests may poll concurrently while it is armed; counts only grow,
343    /// so `unscoped >= 1` stays a sound assertion. The `== 0` direction lives
344    /// in each ordering crate's own `tests/interrupt_threads.rs` binary.)
345    #[test]
346    fn census_detects_a_worker_thread_without_a_scope() {
347        census::arm();
348        scope(&Interrupt::after(Duration::from_secs(3600)), || {
349            assert!(current().is_some());
350            std::thread::spawn(|| {
351                assert!(current().is_none(), "scopes do not cross threads");
352                let _ = poll();
353            })
354            .join()
355            .expect("worker");
356            let _ = poll();
357        });
358        let c = census::take();
359        assert!(c.unscoped >= 1, "{c:?}");
360        assert!(c.scoped >= 1, "{c:?}");
361    }
362}