Skip to main content

dive_stdlib/
host.rs

1//! A ready-made [`dive_eval::Host`] for a model-checking run: the run's random
2//! streams (C5), the level of the state being evaluated, the live counters
3//! and `TLCGet("config")`, and `TLCSet("exit")`.
4//!
5//! The engine owns a [`RunHost`], passes it to the binding stage
6//! (`dive_model::BindOptions::host`) so that start-up definitions and
7//! `ASSUME`s already draw from the run's start-up stream, and then drives it:
8//! [`RunHost::expand`] before expanding a state (TLC reseeds its generator
9//! with `fingerprint(state) ^ seed`), [`RunHost::set_level`] before each
10//! check, [`RunHost::set_counter`] for the live counters, and
11//! [`RunHost::exit_requested`] after each state.
12//!
13//! One `RunHost` serves one evaluating thread at a time: the stream and the
14//! level are the current worker's. A parallel engine keeps one per worker.
15
16use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
17use std::sync::{Mutex, PoisonError};
18
19use dive_eval::{Counter, Host, HostError, RunConfig};
20use dive_ir::StdOp;
21use dive_value::{Ctx, ErrorKind, Value};
22
23use crate::random::{
24    RandomError, RandomSource, Stream, Streams, random_element, random_set_of_subsets,
25    random_subset,
26};
27
28/// No value: the host does not provide it at this point of the run.
29const UNSET: i64 = i64::MIN;
30
31/// A model-checking run's [`Host`].
32#[derive(Debug)]
33pub struct RunHost {
34    inputs: Option<std::sync::Arc<dyn dive_eval::inputs::InputSource>>,
35    streams: Streams,
36    stream: Mutex<Stream>,
37    level: AtomicI64,
38    counters: [AtomicI64; 6],
39    config: Mutex<Option<RunConfig>>,
40    exit: AtomicBool,
41}
42
43fn counter_index(c: Counter) -> usize {
44    match c {
45        Counter::Generated => 0,
46        Counter::Distinct => 1,
47        Counter::Queue => 2,
48        Counter::Diameter => 3,
49        Counter::Initial => 4,
50        Counter::DurationSecs => 5,
51    }
52}
53
54impl RunHost {
55    /// A host drawing from `streams` (start-up stream first) and reporting
56    /// `config` for `TLCGet("config")`. No level and no counter is set.
57    #[must_use]
58    pub fn new(streams: Streams, config: Option<RunConfig>) -> Self {
59        Self {
60            inputs: None,
61            streams,
62            stream: Mutex::new(streams.startup()),
63            level: AtomicI64::new(UNSET),
64            counters: std::array::from_fn(|_| AtomicI64::new(UNSET)),
65            config: Mutex::new(config),
66            exit: AtomicBool::new(false),
67        }
68    }
69
70    /// Installs explicit external input ownership before binding starts.
71    #[must_use]
72    pub fn with_inputs(
73        mut self,
74        inputs: std::sync::Arc<dyn dive_eval::inputs::InputSource>,
75    ) -> Self {
76        self.inputs = Some(inputs);
77        self
78    }
79
80    /// The run's streams.
81    #[must_use]
82    pub fn streams(&self) -> Streams {
83        self.streams
84    }
85
86    /// Restarts the start-up stream (trace reconstruction regenerates the
87    /// initial states from a fresh one, as TLC does).
88    pub fn restart(&self) {
89        *self.stream.lock().unwrap_or_else(PoisonError::into_inner) = self.streams.startup();
90    }
91
92    /// Switches to the stream of the state with fingerprint `fp`, before the
93    /// state is expanded (`RandomEnumerableValues`' per-state reseeding).
94    pub fn expand(&self, fp: u64) {
95        *self.stream.lock().unwrap_or_else(PoisonError::into_inner) = self.streams.state(fp);
96    }
97
98    /// The current stream, at its current position.
99    #[must_use]
100    pub fn stream(&self) -> Stream {
101        *self.stream.lock().unwrap_or_else(PoisonError::into_inner)
102    }
103
104    /// Continues from `stream` (a snapshot taken with [`RunHost::stream`]).
105    pub fn set_stream(&self, stream: Stream) {
106        *self.stream.lock().unwrap_or_else(PoisonError::into_inner) = stream;
107    }
108
109    /// Advances the current stream by `words` generator steps, as that many
110    /// draws of one word each would (one `java.util.Random.next` call, or
111    /// one counter step of dive's stream). The trace validator uses it to
112    /// look for a check's draws later in a stream.
113    pub fn skip(&self, words: u64) {
114        let mut s = self.stream.lock().unwrap_or_else(PoisonError::into_inner);
115        for _ in 0..words {
116            let _ = s.next_bits(32);
117        }
118    }
119
120    /// The level `TLCGet("level")` reports from now on (TLC's `s0.getLevel()`).
121    pub fn set_level(&self, level: i64) {
122        self.level.store(level, Ordering::Relaxed);
123    }
124
125    /// Stops providing `TLCGet("level")`, restoring the state before the
126    /// engine supplied a level. Other host capabilities are unchanged.
127    ///
128    /// ```
129    /// use dive_eval::Host;
130    /// use dive_stdlib::{host::RunHost, random::{RandomMode, Streams}};
131    /// let host = RunHost::new(Streams::new(0, RandomMode::Dive), None);
132    /// host.set_level(3);
133    /// host.clear_level();
134    /// assert_eq!(host.level(), None);
135    /// ```
136    pub fn clear_level(&self) {
137        self.level.store(UNSET, Ordering::Relaxed);
138    }
139
140    /// Sets a live counter (`None`: not provided, so reading it is refused).
141    pub fn set_counter(&self, c: Counter, value: Option<i64>) {
142        self.counters[counter_index(c)].store(value.unwrap_or(UNSET), Ordering::Relaxed);
143    }
144
145    /// Sets what `TLCGet("config")` reports.
146    pub fn set_config(&self, config: Option<RunConfig>) {
147        *self.config.lock().unwrap_or_else(PoisonError::into_inner) = config;
148    }
149
150    /// Whether the specification asked to stop (`TLCSet("exit", TRUE)`).
151    #[must_use]
152    pub fn exit_requested(&self) -> bool {
153        self.exit.load(Ordering::Relaxed)
154    }
155}
156
157fn host_error(e: &RandomError) -> HostError {
158    match e {
159        RandomError::Value(v) if v.kind() == ErrorKind::DiveLimit => HostError {
160            code: 0,
161            message: v.message().to_owned(),
162        },
163        _ => HostError {
164            code: e.tlc_code(),
165            message: e.message(),
166        },
167    }
168}
169
170impl Host for RunHost {
171    fn input(
172        &self,
173        request: &dive_eval::inputs::InputRequest,
174    ) -> Option<Result<dive_eval::inputs::InputResponse, HostError>> {
175        self.inputs.as_ref().map(|inputs| inputs.request(request))
176    }
177    fn random(&self, op: StdOp, args: &[Value], ctx: Ctx) -> Option<Result<Value, HostError>> {
178        let mut stream = self.stream.lock().unwrap_or_else(PoisonError::into_inner);
179        let mut bits = |n| stream.next_bits(n);
180        let r = match (op, args) {
181            (StdOp::TlcRandomElement, [s]) => random_element(s, ctx, &mut bits),
182            (StdOp::RandomizationRandomSubset, [k, s]) => random_subset(k, s, ctx, &mut bits),
183            (StdOp::RandomizationRandomSetOfSubsets, [k, n, s]) => {
184                random_set_of_subsets(k, n, s, ctx, &mut bits)
185            }
186            _ => return None,
187        };
188        Some(r.map_err(|e| host_error(&e)))
189    }
190
191    fn level(&self) -> Option<i64> {
192        let l = self.level.load(Ordering::Relaxed);
193        (l != UNSET).then_some(l)
194    }
195
196    fn counter(&self, c: Counter) -> Option<i64> {
197        let v = self.counters[counter_index(c)].load(Ordering::Relaxed);
198        (v != UNSET).then_some(v)
199    }
200
201    fn config(&self) -> Option<RunConfig> {
202        self.config
203            .lock()
204            .unwrap_or_else(PoisonError::into_inner)
205            .clone()
206    }
207
208    fn request_exit(&self) -> bool {
209        self.exit.store(true, Ordering::Relaxed);
210        true
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use crate::random::RandomMode;
218    use dive_value::Int;
219
220    #[test]
221    fn draws_from_the_startup_stream_then_the_state_stream() {
222        let ctx = Ctx::tlc();
223        let host = RunHost::new(Streams::new(7, RandomMode::Tlc), None);
224        let s = Value::interval(Int::Small(1), Int::Small(1_000_000), ctx);
225        let first = host
226            .random(StdOp::TlcRandomElement, std::slice::from_ref(&s), ctx)
227            .and_then(Result::ok);
228        // TLC -seed 7: `RandomElement(1..1000000)` is 730700 (probe P9).
229        assert_eq!(first, Some(Value::Int(730_700)));
230        host.restart();
231        let again = host
232            .random(StdOp::TlcRandomElement, std::slice::from_ref(&s), ctx)
233            .and_then(Result::ok);
234        assert_eq!(again, first);
235        assert_eq!(host.level(), None);
236        host.set_level(3);
237        assert_eq!(host.level(), Some(3));
238        host.clear_level();
239        assert_eq!(host.level(), None);
240        assert!(!host.exit_requested());
241        assert!(host.request_exit());
242        assert!(host.exit_requested());
243    }
244
245    #[test]
246    fn skipping_matches_drawing_one_word_at_a_time() {
247        for mode in [RandomMode::Tlc, RandomMode::Dive] {
248            let host = RunHost::new(Streams::new(7, mode), None);
249            host.expand(42);
250            let start = host.stream();
251            let mut by_hand = start;
252            for _ in 0..5 {
253                let _ = by_hand.next_bits(31);
254            }
255            host.skip(5);
256            assert_eq!(host.stream(), by_hand);
257            host.set_stream(start);
258            assert_eq!(host.stream(), host.streams().state(42));
259        }
260    }
261}