feral_ordering_core/
interrupt.rs1use 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#[derive(Debug, Clone, Default)]
37pub struct Interrupt {
38 deadline: Option<Instant>,
39 flag: Option<Arc<AtomicBool>>,
40}
41
42impl Interrupt {
43 pub fn none() -> Self {
45 Self::default()
46 }
47
48 pub fn at(deadline: Instant) -> Self {
50 Self {
51 deadline: Some(deadline),
52 flag: None,
53 }
54 }
55
56 pub fn after(budget: Duration) -> Self {
58 Self::at(Instant::now() + budget)
59 }
60
61 pub fn with_flag(mut self, flag: Arc<AtomicBool>) -> Self {
63 self.flag = Some(flag);
64 self
65 }
66
67 pub fn with_deadline(mut self, deadline: Instant) -> Self {
69 self.deadline = Some(deadline);
70 self
71 }
72
73 pub fn deadline(&self) -> Option<Instant> {
75 self.deadline
76 }
77
78 pub fn deadline_passed(&self) -> bool {
81 self.deadline.is_some_and(|d| Instant::now() >= d)
82 }
83
84 pub fn flag_set(&self) -> bool {
86 self.flag
87 .as_ref()
88 .is_some_and(|f| f.load(Ordering::Relaxed))
89 }
90
91 pub fn is_triggered(&self) -> bool {
93 self.flag_set() || self.deadline_passed()
94 }
95
96 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
107struct 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
121pub 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
132pub 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
141pub 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
159pub fn current() -> Option<Interrupt> {
163 ACTIVE.with(|a| a.borrow().clone())
164}
165
166pub 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 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
193 pub struct Counts {
194 pub scoped: usize,
196 pub unscoped: usize,
198 }
199
200 pub fn arm() {
202 SCOPED.store(0, Ordering::Relaxed);
203 UNSCOPED.store(0, Ordering::Relaxed);
204 ARMED.store(true, Ordering::SeqCst);
205 }
206
207 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
217pub fn check() -> Result<(), OrderingError> {
219 if poll() {
220 Err(OrderingError::Interrupted)
221 } else {
222 Ok(())
223 }
224}
225
226pub 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 scope(&Interrupt::none(), || assert!(!poll()));
271 assert!(poll());
273 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 scope(&i, || assert!(!poll()));
303 }
304
305 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 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 #[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}