Skip to main content

bitwright/mba/
threaded.rs

1//! A hard deadline around any solver.
2
3use std::sync::Arc;
4use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering};
5use std::sync::mpsc;
6use std::time::Duration;
7
8use super::expr::MbaExpr;
9use super::solve::{MbaAnswer, MbaBudget, MbaSolver};
10
11/// Runs each question on its own thread and waits at most `timeout`: an answer that is late is
12/// abandoned and reported as [`MbaAnswer::Exhausted`] (never cached, so a later call may try
13/// again). While `max_abandoned` abandoned questions are still running, new ones are refused
14/// as exhausted, which bounds the threads left behind. The only threads are the ones this
15/// instance starts; nothing is global.
16///
17/// A deadline makes answers depend on timing; the engine treats an exhausted answer as not
18/// final, so a memoized result never depends on it. A panic inside the solver is answered as
19/// unsupported. The cap is checked before a question starts, so concurrent callers may briefly
20/// exceed it by their number.
21pub struct ThreadedSolver<S> {
22    inner: Arc<S>,
23    timeout: Duration,
24    max_abandoned: usize,
25    abandoned: Arc<AtomicUsize>,
26    id: String,
27}
28
29impl<S: MbaSolver + 'static> ThreadedSolver<S> {
30    /// Wraps `inner` with a deadline.
31    pub fn new(inner: S, timeout: Duration, max_abandoned: usize) -> Self {
32        let id = inner.id().to_string();
33        ThreadedSolver {
34            inner: Arc::new(inner),
35            timeout,
36            max_abandoned,
37            abandoned: Arc::new(AtomicUsize::new(0)),
38            id,
39        }
40    }
41
42    /// Questions abandoned and still running.
43    pub fn abandoned(&self) -> usize {
44        self.abandoned.load(Ordering::Acquire)
45    }
46}
47
48impl<S> core::fmt::Debug for ThreadedSolver<S> {
49    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
50        f.debug_struct("ThreadedSolver")
51            .field("id", &self.id)
52            .field("timeout", &self.timeout)
53            .field("max_abandoned", &self.max_abandoned)
54            .finish_non_exhaustive()
55    }
56}
57
58impl<S: MbaSolver + 'static> MbaSolver for ThreadedSolver<S> {
59    fn id(&self) -> &str {
60        // The deadline does not change answers that arrive, so the inner id keys the caches.
61        &self.id
62    }
63
64    fn polynomial_fragments(&self) -> bool {
65        self.inner.polynomial_fragments()
66    }
67
68    fn solve(&self, p: &MbaExpr, budget: &MbaBudget) -> MbaAnswer {
69        self.solve_counted(p, budget).0
70    }
71
72    /// The inner solver's steps; a question abandoned at the deadline is charged its limit (it
73    /// may still be running), one refused or not started nothing.
74    fn solve_counted(&self, p: &MbaExpr, budget: &MbaBudget) -> (MbaAnswer, u64) {
75        const RUNNING: u8 = 0;
76        const DONE: u8 = 1;
77        const ABANDONED: u8 = 2;
78        if self.abandoned.load(Ordering::Acquire) >= self.max_abandoned {
79            return (MbaAnswer::Exhausted, 0);
80        }
81        let (tx, rx) = mpsc::channel();
82        let (inner, p, budget) = (self.inner.clone(), p.clone(), *budget);
83        let abandoned = self.abandoned.clone();
84        // One state per question, decided once: whoever moves it out of RUNNING first wins.
85        let state = Arc::new(AtomicU8::new(RUNNING));
86        let st = state.clone();
87        let spawned = std::thread::Builder::new()
88            .name("bitwright-mba".into())
89            .spawn(move || {
90                // A panic in the solver is an answer, not a lost question.
91                let answer = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
92                    inner.solve_counted(&p, &budget)
93                }))
94                .unwrap_or_else(|_| {
95                    let why = MbaAnswer::Unsupported("the solver panicked".into());
96                    (why, budget.steps)
97                });
98                let _ = tx.send(answer);
99                if st
100                    .compare_exchange(RUNNING, DONE, Ordering::AcqRel, Ordering::Acquire)
101                    .is_err()
102                {
103                    // The caller gave up on it and counted it: uncount.
104                    abandoned.fetch_sub(1, Ordering::AcqRel);
105                }
106            });
107        if spawned.is_err() {
108            return (MbaAnswer::Exhausted, 0);
109        }
110        match rx.recv_timeout(self.timeout) {
111            Ok(a) => a,
112            Err(_) => {
113                // Count it first, so that the worker's uncount can never precede it.
114                self.abandoned.fetch_add(1, Ordering::AcqRel);
115                if state
116                    .compare_exchange(RUNNING, ABANDONED, Ordering::AcqRel, Ordering::Acquire)
117                    .is_ok()
118                {
119                    (MbaAnswer::Exhausted, budget.steps)
120                } else {
121                    // The worker finished (and sent) just in time.
122                    self.abandoned.fetch_sub(1, Ordering::AcqRel);
123                    rx.recv().unwrap_or((MbaAnswer::Exhausted, budget.steps))
124                }
125            }
126        }
127    }
128}