everystate 0.4.6

A lightning-fast TLA+ model checker (TLC-compatible, no Java needed)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! The state store: where the search keeps the states it has found, when that is not memory.
//!
//! By default there is no store: the search holds its states itself, as rows of value ids, as values or
//! as the parallel search's bytes (checker.rs, par.rs), and nothing here is called. With a store
//! (`CheckOptions::store`) the search hands every new state over as bytes and reads it back when its
//! turn in the queue comes, or when a trace, a temporal property or `-dump` asks for it. What stays in
//! memory then is per state the fingerprint set and a few small vectors (see ARCHITECTURE.md, "The
//! state store").
//!
//! Two layers:
//!
//! - `StateStore` is what a provider implements: it keeps chunks of bytes by the number of their first
//!   state. It knows nothing of states or values. The providers are `sql::SqlStore` over a SQLite file
//!   (`-store sqlite:PATH`, cargo feature `sqlite`) and over a SQL executor handed in from JavaScript
//!   (`wasm.rs`).
//! - `Stored` is the search's side: it encodes states (`codec.rs`), fills a chunk, hands a full one to
//!   the provider and reads chunks back.
//!
//! A chunk is consecutive records, then the offset of every record and of the end (u32, little-endian),
//! the number of records (u32) and a checksum of all of that and of the chunk's first state number
//! (u64): a provider that returns other bytes than it was given, or another chunk, is noticed. A record
//! is the state's parent + 1 and its action + 1 as varints (0 for an initial state), then its variables
//! as `codec::ser_state` writes them. Strings and model values in a record are ids of this process's
//! string table, so a store is the working storage of one run: nothing else can read it.
use crate::codec::{get_u, put_u, ser_var, De, Fx};
use crate::eval::StateRef;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::hash::Hasher;

/// What a provider of state storage does. A call may fail with a message; the search then stops with
/// that message.
pub trait StateStore {
    /// The size of chunk the provider wants, in bytes: a chunk is handed over once its records hold
    /// this much (so it is larger by the state that crossed the mark and by 4 bytes per state).
    fn chunk_bytes(&self) -> usize {
        64 << 10
    }
    /// Keeps `data`, the chunk whose first state is number `first`. Chunks come in increasing order,
    /// each once.
    fn put_chunk(&mut self, first: u64, data: &[u8]) -> Result<(), String>;
    /// Appends to `out` the chunk that holds state `state` (the one with the largest `first` not above
    /// it) and returns its `first`.
    fn get_chunk(&mut self, state: u64, out: &mut Vec<u8>) -> Result<u64, String>;
}

fn checksum(base: usize, bytes: &[u8]) -> u64 {
    let mut h = Fx(0);
    h.write_u64(base as u64);
    h.write(bytes);
    h.finish()
}

/// Consecutive records: state `base + k` is `bytes[offs[k]..offs[k + 1]]`.
struct Chunk {
    base: usize,
    offs: Vec<u32>,
    bytes: Vec<u8>,
}
impl Chunk {
    fn new(base: usize) -> Chunk {
        Chunk { base, offs: vec![0], bytes: Vec::new() }
    }
    fn n(&self) -> usize {
        self.offs.len() - 1
    }
    fn has(&self, i: usize) -> bool {
        i >= self.base && i < self.base + self.n()
    }
    fn rec(&self, i: usize) -> &[u8] {
        let k = i - self.base;
        &self.bytes[self.offs[k] as usize..self.offs[k + 1] as usize]
    }
    /// Reads the chunk a provider returned into `self`: `self.bytes` holds it, and its first state is `base`.
    fn parse(&mut self, base: usize) -> Result<(), String> {
        let bad = || "the store returned a chunk that is not the one it was given".to_string();
        let sum = self.bytes.len().checked_sub(8).ok_or_else(bad)?;
        if checksum(base, &self.bytes[..sum]) != u64::from_le_bytes(self.bytes[sum..].try_into().unwrap()) {
            return Err(bad());
        }
        let b = &self.bytes[..sum];
        let u32_at = |p: usize| u32::from_le_bytes(b[p..p + 4].try_into().unwrap());
        let end = b.len().checked_sub(4).ok_or_else(bad)?;
        let n = u32_at(end) as usize;
        let start = n.checked_add(1).and_then(|m| m.checked_mul(4)).and_then(|table| end.checked_sub(table)).ok_or_else(bad)?;
        self.offs.clear();
        self.offs.extend((0..=n).map(|k| u32_at(start + 4 * k)));
        if self.offs[n] as usize != start || self.offs.windows(2).any(|w| w[0] > w[1]) {
            return Err(bad());
        }
        self.bytes.truncate(start);
        self.base = base;
        Ok(())
    }
}

/// How many chunks read out of queue order are kept (traces and temporal properties read states in
/// no order).
const KEPT: usize = 64;

/// The states of a search, kept by a provider.
pub(crate) struct Stored {
    provider: RefCell<Box<dyn StateStore>>,
    nvars: usize,
    /// a tail whose records hold this many bytes is full
    limit: usize,
    /// the states not handed to the provider yet
    tail: Chunk,
    /// the chunk the queue is reading, and the chunks last read out of order
    head: RefCell<Chunk>,
    kept: RefCell<Vec<Chunk>>,
    turn: Cell<usize>,
    de: RefCell<De>,
    tmp: Vec<u8>,
    /// States with a value that has no encoding (an operator, a lazy function, a set defined by a
    /// predicate) stay in memory; their records hold the parent and the action only.
    odd: HashMap<usize, StateRef>,
    /// What the provider said when it first failed. Nothing is asked of it after that: what it holds is
    /// not to be relied on (a full disk loses what was being written).
    failed: RefCell<Option<String>>,
}

impl Stored {
    pub(crate) fn new(provider: Box<dyn StateStore>, nvars: usize) -> Stored {
        let limit = provider.chunk_bytes().max(1);
        // (the decoder shares function domains between the states it rebuilds: with a bound, because
        // the states themselves are not kept)
        Stored { provider: RefCell::new(provider), nvars, limit, tail: Chunk::new(0), head: RefCell::new(Chunk::new(0)), kept: RefCell::new(vec![]), turn: Cell::new(0), de: RefCell::new(De::bounded(4 << 20)), tmp: vec![], odd: HashMap::new(), failed: RefCell::new(None) }
    }
    fn len(&self) -> usize {
        self.tail.base + self.tail.n()
    }
    /// The provider's first failure, if it has failed.
    pub(crate) fn failed(&self) -> Option<String> {
        self.failed.borrow().clone()
    }
    fn fail<T>(&self, e: String) -> Result<T, String> {
        Err(self.failed.borrow_mut().get_or_insert(e).clone())
    }
    /// Appends the next state, found from state `parent` by action `act` (`NO_PARENT` and -1 for an
    /// initial state).
    pub(crate) fn push(&mut self, s: &StateRef, parent: u32, act: i32) -> Result<(), String> {
        if self.tail.bytes.len() >= self.limit {
            self.seal()?;
        }
        let id = self.len();
        let (out, tmp, nvars) = (&mut self.tail.bytes, &mut self.tmp, self.nvars);
        put_u(out, parent.wrapping_add(1) as u64);
        put_u(out, (act + 1) as u64);
        let mark = out.len();
        if !s.with(|vals| vals[..nvars].iter().all(|v| ser_var(v, out, tmp))) {
            out.truncate(mark);
            self.odd.insert(id, s.clone());
        }
        if out.len() > u32::MAX as usize {
            return self.fail("a state of more than 4 GB".into());
        }
        self.tail.offs.push(out.len() as u32);
        Ok(())
    }
    /// Hands the tail to the provider.
    fn seal(&mut self) -> Result<(), String> {
        if let Some(e) = self.failed() {
            return Err(e);
        }
        let t = &mut self.tail;
        let records = t.bytes.len();
        for o in &t.offs {
            t.bytes.extend_from_slice(&o.to_le_bytes());
        }
        t.bytes.extend_from_slice(&(t.n() as u32).to_le_bytes());
        let sum = checksum(t.base, &t.bytes);
        t.bytes.extend_from_slice(&sum.to_le_bytes());
        let r = self.provider.get_mut().put_chunk(t.base as u64, &t.bytes);
        t.bytes.truncate(records);
        if let Err(e) = r {
            return self.fail(e);
        }
        let t = &mut self.tail;
        t.base += t.n();
        t.offs.truncate(1);
        t.bytes.clear();
        Ok(())
    }
    fn decode(&self, i: usize, rec: &[u8]) -> StateRef {
        if let Some(s) = self.odd.get(&i) {
            return s.clone();
        }
        let mut pos = 0;
        get_u(rec, &mut pos);
        get_u(rec, &mut pos);
        self.de.borrow_mut().state(&rec[pos..], self.nvars)
    }
    fn load(&self, i: usize, c: &mut Chunk) -> Result<(), String> {
        if let Some(e) = self.failed() {
            return Err(e);
        }
        c.bytes.clear();
        let r = self.provider.borrow_mut().get_chunk(i as u64, &mut c.bytes).and_then(|base| c.parse(base as usize));
        if r.is_ok() && c.has(i) {
            return Ok(());
        }
        // (a chunk that failed to load holds no state)
        c.offs.clear();
        c.offs.push(0);
        self.fail(r.err().unwrap_or_else(|| format!("the store has no state {}", i)))
    }
    /// State `i` for expansion. The search asks in increasing order of `i`.
    pub(crate) fn next(&mut self, i: usize) -> Result<StateRef, String> {
        if i >= self.tail.base {
            return Ok(self.decode(i, self.tail.rec(i)));
        }
        let mut h = self.head.borrow_mut();
        if !h.has(i) {
            self.load(i, &mut h)?;
        }
        Ok(self.decode(i, h.rec(i)))
    }
    /// State `i`, in any order.
    pub(crate) fn get(&self, i: usize) -> Result<StateRef, String> {
        if i >= self.tail.base {
            return Ok(self.decode(i, self.tail.rec(i)));
        }
        if let Ok(h) = self.head.try_borrow() {
            if h.has(i) {
                return Ok(self.decode(i, h.rec(i)));
            }
        }
        let mut kept = self.kept.borrow_mut();
        let k = match kept.iter().position(|c| c.has(i)) {
            Some(k) => k,
            None => {
                let k = if kept.len() < KEPT {
                    kept.push(Chunk::new(0));
                    kept.len() - 1
                } else {
                    self.turn.set((self.turn.get() + 1) % KEPT);
                    self.turn.get()
                };
                self.load(i, &mut kept[k])?;
                k
            }
        };
        Ok(self.decode(i, kept[k].rec(i)))
    }
}

/// The state store failed where no result can say so (a trace or a temporal property was reading a
/// state): the run ends here.
#[cold]
pub(crate) fn fatal(e: &str) -> ! {
    panic!("the state store failed: {}", e)
}

pub mod sql {
    //! The SQL providers: one table and three statements for every SQLite, restricted to what a
    //! Cloudflare Durable Object's SQLite storage accepts (a plain table, `INTEGER PRIMARY KEY`, `BLOB`,
    //! single-table statements). What differs is who runs a statement (`Sql`): rusqlite on a file, or
    //! the `exec` of a storage object handed in from JavaScript.
    use super::StateStore;

    /// The chunks by first state number. A store holds one run: a new check empties the table.
    pub const SETUP: [&str; 2] = ["CREATE TABLE IF NOT EXISTS everystate_chunks (first INTEGER PRIMARY KEY, data BLOB NOT NULL)", "DELETE FROM everystate_chunks"];
    pub const PUT_CHUNK: &str = "INSERT INTO everystate_chunks (first, data) VALUES (?, ?)";
    pub const GET_CHUNK: &str = "SELECT first, data FROM everystate_chunks WHERE first <= ? ORDER BY first DESC LIMIT 1";

    pub enum Arg<'a> {
        Int(i64),
        Blob(&'a [u8]),
    }

    /// Runs statements on a SQLite database.
    pub trait Sql {
        /// Runs `query` with `args` bound to its `?`s, and calls `row` with the two columns (an integer
        /// and a blob) of every row of the result.
        fn exec(&mut self, query: &'static str, args: &[Arg], row: &mut dyn FnMut(i64, &[u8])) -> Result<(), String>;
        /// See `StateStore::chunk_bytes`.
        fn chunk_bytes(&self) -> usize {
            64 << 10
        }
    }

    pub struct SqlStore<S: Sql>(S);
    impl<S: Sql> SqlStore<S> {
        /// Creates the table in the database `sql` runs on, or empties it.
        pub fn new(mut sql: S) -> Result<SqlStore<S>, String> {
            for q in SETUP {
                sql.exec(q, &[], &mut |_, _| {})?;
            }
            Ok(SqlStore(sql))
        }
    }
    impl<S: Sql> StateStore for SqlStore<S> {
        fn chunk_bytes(&self) -> usize {
            self.0.chunk_bytes()
        }
        fn put_chunk(&mut self, first: u64, data: &[u8]) -> Result<(), String> {
            self.0.exec(PUT_CHUNK, &[Arg::Int(first as i64), Arg::Blob(data)], &mut |_, _| {})
        }
        fn get_chunk(&mut self, state: u64, out: &mut Vec<u8>) -> Result<u64, String> {
            let mut first = None;
            self.0.exec(GET_CHUNK, &[Arg::Int(state as i64)], &mut |f, data| {
                first = Some(f as u64);
                out.extend_from_slice(data);
            })?;
            first.ok_or_else(|| format!("the store has no state {}", state))
        }
    }

    /// A SQLite file (`-store sqlite:PATH`). It is working storage for one run, so nothing waits for
    /// the disk: every statement is its own transaction, with the rollback journal in memory.
    #[cfg(feature = "sqlite")]
    pub struct File {
        db: rusqlite::Connection,
        chunk: usize,
    }
    #[cfg(feature = "sqlite")]
    impl File {
        /// `chunk`: bytes per chunk, when not the default (a test hook: small chunks are read back
        /// even by small models).
        pub fn open(path: &str, chunk: Option<usize>) -> Result<SqlStore<File>, String> {
            let at = |e: String| format!("{}: {}", path, e);
            let db = rusqlite::Connection::open(path).map_err(|e| at(e.to_string()))?;
            db.execute_batch("PRAGMA journal_mode = MEMORY; PRAGMA synchronous = OFF").map_err(|e| at(e.to_string()))?;
            SqlStore::new(File { db, chunk: chunk.unwrap_or(64 << 10) }).map_err(at)
        }
    }
    #[cfg(feature = "sqlite")]
    impl Sql for File {
        fn exec(&mut self, query: &'static str, args: &[Arg], row: &mut dyn FnMut(i64, &[u8])) -> Result<(), String> {
            use rusqlite::types::{ToSqlOutput, ValueRef};
            let mut st = self.db.prepare_cached(query).map_err(|e| e.to_string())?;
            let bound = args.iter().map(|a| match a {
                Arg::Int(i) => ToSqlOutput::Borrowed(ValueRef::Integer(*i)),
                Arg::Blob(b) => ToSqlOutput::Borrowed(ValueRef::Blob(b)),
            });
            let mut rows = st.query(rusqlite::params_from_iter(bound)).map_err(|e| e.to_string())?;
            while let Some(r) = rows.next().map_err(|e| e.to_string())? {
                let first: i64 = r.get(0).map_err(|e| e.to_string())?;
                row(first, r.get_ref(1).map_err(|e| e.to_string())?.as_blob().map_err(|e| e.to_string())?);
            }
            Ok(())
        }
        fn chunk_bytes(&self) -> usize {
            self.chunk
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::eval::StateData;
    use crate::intern::str_id;
    use crate::value::*;
    use std::rc::Rc;

    /// A provider that keeps what it is given in a vector; `full`: it takes no chunk after this many.
    #[derive(Default)]
    struct Kept {
        chunks: Vec<(u64, Vec<u8>)>,
        reads: usize,
        full: Option<usize>,
    }
    struct InMemory(Rc<RefCell<Kept>>);
    impl StateStore for InMemory {
        fn chunk_bytes(&self) -> usize {
            100
        }
        fn put_chunk(&mut self, first: u64, data: &[u8]) -> Result<(), String> {
            let mut k = self.0.borrow_mut();
            if k.full.is_some_and(|n| k.chunks.len() >= n) {
                return Err("disk full".into());
            }
            k.chunks.push((first, data.to_vec()));
            Ok(())
        }
        fn get_chunk(&mut self, state: u64, out: &mut Vec<u8>) -> Result<u64, String> {
            let mut k = self.0.borrow_mut();
            k.reads += 1;
            let c = k.chunks.iter().rev().find(|c| c.0 <= state).ok_or("no such chunk")?;
            out.extend_from_slice(&c.1);
            Ok(c.0)
        }
    }

    fn state(i: i64) -> StateRef {
        let set = SetV::of((0..i % 5).map(Value::Int).collect());
        let tuple = Value::Tuple(TupleV::rc(vec![Value::Str(str_id(if i % 2 == 0 { "even" } else { "odd" })), Value::Bool(i % 3 == 0)]));
        StateData::new(vec![Value::Int(i), set, tuple, Value::Set(Rc::new(SetV::new(SetK::Interval(1, i))))])
    }
    fn same(a: &StateRef, b: &StateRef) -> bool {
        (0..4).all(|k| val_eq(&a.get(k), &b.get(k)).unwrap())
    }
    /// The number of records of a chunk as the provider holds it.
    fn records(chunk: &[u8]) -> usize {
        u32::from_le_bytes(chunk[chunk.len() - 12..chunk.len() - 8].try_into().unwrap()) as usize
    }

    #[test]
    fn states_come_back_from_chunks() {
        let kept = Rc::new(RefCell::new(Kept::default()));
        let mut st = Stored::new(Box::new(InMemory(kept.clone())), 4);
        // interleaved as the search does it: the queue reads behind the states being appended
        let mut head = 0;
        for i in 0..2000 {
            st.push(&state(i), if i == 0 { u32::MAX } else { (i / 2) as u32 }, (i % 3) as i32 - 1).unwrap();
            if i % 3 == 2 {
                assert!(same(&st.next(head).unwrap(), &state(head as i64)));
                head += 1;
            }
        }
        // every state is in exactly one chunk, the chunks in order, and the queue read each chunk once
        let chunks = kept.borrow().chunks.len();
        assert!(chunks > 100);
        assert!(kept.borrow().reads <= chunks);
        assert_eq!(kept.borrow().chunks.iter().map(|c| records(&c.1)).sum::<usize>(), st.tail.base);
        // any order: the tail, chunks written, the chunk the queue is in
        for i in [1999usize, 0, 1234, 7, 1998, 600, 601, 5, head, 1999] {
            assert!(same(&st.get(i).unwrap(), &state(i as i64)), "state {}", i);
        }
    }

    #[test]
    fn a_state_without_an_encoding_stays_in_memory() {
        let kept = Rc::new(RefCell::new(Kept::default()));
        let mut st = Stored::new(Box::new(InMemory(kept.clone())), 1);
        let lazy = StateData::new(vec![Value::Undef]);
        for i in 0..300 {
            if i == 150 {
                st.push(&lazy, 0, 0).unwrap();
            } else {
                st.push(&StateData::new(vec![Value::Int(i)]), 0, 0).unwrap();
            }
        }
        assert!(Rc::ptr_eq(&st.get(150).unwrap(), &lazy) && Rc::ptr_eq(&st.next(150).unwrap(), &lazy));
        assert!(matches!(st.get(151).unwrap().get(0), Value::Int(151)));
    }

    #[test]
    fn a_chunk_that_is_not_the_one_given_is_refused() {
        let kept = Rc::new(RefCell::new(Kept::default()));
        let mut st = Stored::new(Box::new(InMemory(kept.clone())), 1);
        for i in 0..300 {
            st.push(&StateData::new(vec![Value::Int(i)]), 0, 0).unwrap();
        }
        // one byte of a record changed, a chunk cut short, and another chunk under this one's number
        let whole = kept.borrow().chunks.clone();
        for damage in 0..3 {
            let mut c = whole.clone();
            match damage {
                0 => c[0].1[1] ^= 1,
                1 => c[0].1.truncate(9),
                _ => c[0].1 = whole[1].1.clone(),
            }
            kept.borrow_mut().chunks = c;
            let mut st = Stored::new(Box::new(InMemory(kept.clone())), 1);
            st.tail.base = 300;
            assert!(st.get(0).is_err() && st.next(0).is_err(), "damage {}", damage);
            // and nothing is asked of a provider that has failed
            let reads = kept.borrow().reads;
            assert!(st.get(200).is_err() && kept.borrow().reads == reads);
        }
    }

    #[test]
    fn a_failed_write_is_reported_and_stays() {
        let kept = Rc::new(RefCell::new(Kept { full: Some(3), ..Default::default() }));
        let mut st = Stored::new(Box::new(InMemory(kept.clone())), 1);
        let e = (0..1000).find_map(|i| st.push(&StateData::new(vec![Value::Int(i)]), 0, 0).err()).unwrap();
        assert_eq!(e, "disk full");
        assert_eq!(st.failed().as_deref(), Some("disk full"));
        assert_eq!(st.get(0).err().as_deref(), Some("disk full"));
    }
}