semi-persistent-egraph 0.3.0

Semi-persistent equality saturation engine with e-matching, rewrite scheduling, and proof logging
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
476
477
478
479
480
481
482
483
484
485
486
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//! Leapfrog triejoin — intersect N sorted iterators.
//!
//! Implements the unary leapfrog join from:
//! Veldhuizen, "Leapfrog Triejoin: A Simple, Worst-Case Optimal Join Algorithm" (ICDT 2014)

pub use semi_persistent_containers::SortedCursor;
use smallvec::SmallVec;

pub mod seek_stats;

/// Cursor container for a single join.
///
/// Inline capacity 4: a join's arity is the number of index lookups the planner
/// emitted for one atom, which is 1 for `ByOp`/`ByRepr`, 2 for the bound-node
/// re-join, and (arity of the pattern node) for child-position joins. Every
/// pattern in the rule pools reaching this code has arity ≤ 3, so 4 keeps the
/// common case off the heap while staying spillable for wide variadic atoms.
pub type CursorVec<C> = SmallVec<[C; 4]>;

// `SortedCursor for SortedVecCursor` is not implemented here: both the trait and
// the cursor now live in `containers-verus`, which supplies the impl alongside
// the verified methods it delegates to (and the orphan rule would reject a
// second one). The delegation is the same three one-line bodies this module
// carried before the swap, guard included.

/// Cursor combinator yielding `full ∖ delta`: every key from `full` that is
/// absent from `delta`. Generic over any two `SortedCursor`s with the same
/// key type — works for `SortedVecCursor`, `BPlusCursor`, or nested
/// combinators, with no coupling to a backend. Itself a `SortedCursor`, so
/// leapfrog consumes it like any other cursor.
///
/// Used by semi-naive evaluation to restrict an atom to "old" nodes
/// (`full ∖ delta`) without materialising a third index.
///
/// Invariant: after construction and after every `step`/`seek`, the `full`
/// sub-cursor points at a non-excluded key or is exhausted, so `key()` just
/// reads `full`. Relies on leapfrog's monotonic-forward seeks — the `delta`
/// sub-cursor only ever advances, never rewinds. Cost is `O(|full|+|delta|)`
/// across a full scan.
pub struct Difference<A, B> {
    full: A,
    delta: B,
}

impl<K, A, B> Difference<A, B>
where
    K: Copy + Ord,
    A: SortedCursor<Key = K>,
    B: SortedCursor<Key = K>,
{
    /// Wrap `full` and `delta`, establishing the skip invariant.
    pub fn new(full: A, delta: B) -> Self {
        let mut d = Self { full, delta };
        d.skip();
        d
    }

    /// Advance `full` past any key currently present in `delta`.
    #[inline]
    fn skip(&mut self) {
        while let Some(k) = self.full.key() {
            self.delta.seek(k);
            if self.delta.key() == Some(k) {
                self.full.step();
            } else {
                break;
            }
        }
    }
}

impl<K, A, B> SortedCursor for Difference<A, B>
where
    K: Copy + Ord,
    A: SortedCursor<Key = K>,
    B: SortedCursor<Key = K>,
{
    type Key = K;
    #[inline]
    fn key(&self) -> Option<K> {
        self.full.key()
    }
    #[inline]
    fn step(&mut self) {
        self.full.step();
        self.skip();
    }
    #[inline]
    fn seek(&mut self, target: K) {
        self.full.seek(target);
        self.delta.seek(target);
        self.skip();
    }
}

/// Leapfrog join over k sorted iterators.
///
/// Maintains a ring of cursors. `p` is the index of the iterator at the
/// minimum key; `(p + k - 1) % k` is the index at the maximum key.
/// After `search()`, either all iterators point to the same key (a match)
/// or some iterator is exhausted.
pub struct LeapfrogJoin<C: SortedCursor> {
    iters: CursorVec<C>,
    p: usize,
    at_end: bool,
}

impl<C: SortedCursor> LeapfrogJoin<C> {
    /// leapfrog-init (Algorithm 1 in the paper).
    ///
    /// Takes anything convertible into a [`CursorVec`], so a caller that
    /// already has a `SmallVec` hands it over without touching the heap and a
    /// caller with a `Vec` donates its buffer rather than copying.
    pub fn new(iters: impl Into<CursorVec<C>>) -> Self {
        let mut iters = iters.into();
        assert!(!iters.is_empty());
        // If any cursor starts exhausted the intersection is empty; bail before
        // sorting. Checked by probing rather than by collecting the keys into a
        // `Vec<Option<_>>`, which is one allocation per join and this is on the
        // per-search-tree-node path.
        if iters.iter().any(|it| it.key().is_none()) {
            return Self {
                iters,
                p: 0,
                at_end: true,
            };
        }
        // Sort in place by current key. `sort_unstable_*` because the stable
        // sort allocates scratch space above a size threshold, and equal keys
        // are interchangeable here: Algorithm 1 needs the ring ordered by key,
        // not a particular order among ties.
        iters.sort_unstable_by_key(|it| it.key());

        let mut join = Self {
            iters,
            p: 0,
            at_end: false,
        };
        join.search();
        join
    }

    #[inline]
    pub fn is_valid(&self) -> bool {
        !self.at_end
    }

    #[inline]
    pub fn key(&self) -> C::Key {
        self.iters[self.p]
            .key()
            .expect("leapfrog: key on invalid cursor")
    }

    /// leapfrog-next (Algorithm 3).
    pub fn next(&mut self) {
        self.iters[self.p].step();
        if self.iters[self.p].key().is_none() {
            self.at_end = true;
            return;
        }
        self.p = (self.p + 1) % self.iters.len();
        self.search();
    }

    /// leapfrog-search (Algorithm 2).
    fn search(&mut self) {
        let k = self.iters.len();
        let mut max_key = self.iters[(self.p + k - 1) % k]
            .key()
            .expect("leapfrog: invariant broken");
        loop {
            let min_key = self.iters[self.p]
                .key()
                .expect("leapfrog: invariant broken");
            if min_key == max_key {
                return;
            }
            self.iters[self.p].seek(max_key);
            match self.iters[self.p].key() {
                Some(k) => max_key = k,
                None => {
                    self.at_end = true;
                    return;
                }
            }
            self.p = (self.p + 1) % k;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::containers::DenseId;
    use crate::index::SortedVecCursor;

    /// A bucket in the shape the index build produces: ascending, no repeats.
    /// The index itself hands out `&[G]` slices carved from one arena; this is
    /// the test's owner for them.
    struct Bucket<G>(Vec<G>);

    impl<G: DenseId> Bucket<G> {
        fn iter(&self) -> SortedVecCursor<'_, G> {
            SortedVecCursor::new(&self.0)
        }
    }

    fn svec<G: DenseId>(vals: &[usize]) -> Bucket<G> {
        let mut v: Vec<G> = vals.iter().map(|&x| G::from_usize(x)).collect();
        v.sort_unstable();
        v.dedup();
        Bucket(v)
    }

    fn collect<'a, G: DenseId>(j: &mut LeapfrogJoin<SortedVecCursor<'a, G>>) -> Vec<usize> {
        let mut out = Vec::new();
        while j.is_valid() {
            out.push(j.key().to_usize());
            j.next();
        }
        out
    }

    macro_rules! dual {
        ($(fn $name:ident<$G:ident>() $body:block)*) => {$(
            mod $name {
                use super::*;
                fn run<$G: DenseId>() $body
                #[test] fn bits31() { run::<crate::id::ENodeId>(); }
                #[test] fn bits63() { run::<crate::nodes::ENodeId64>(); }
            }
        )*};
    }

    dual! {
        fn single<G>() {
            let s = svec::<G>(&[1, 3, 5, 7]);
            let mut j = LeapfrogJoin::new(vec![s.iter()]);
            assert_eq!(collect(&mut j), [1, 3, 5, 7]);
        }

        fn two_way<G>() {
            let a = svec::<G>(&[1, 2, 3, 5, 8]);
            let b = svec::<G>(&[2, 3, 6, 8, 9]);
            let mut j = LeapfrogJoin::new(vec![a.iter(), b.iter()]);
            assert_eq!(collect(&mut j), [2, 3, 8]);
        }

        fn three_way<G>() {
            let a = svec::<G>(&[1, 2, 3, 5, 8, 10]);
            let b = svec::<G>(&[2, 3, 6, 8, 9, 10]);
            let c = svec::<G>(&[0, 3, 4, 8, 10, 11]);
            let mut j = LeapfrogJoin::new(vec![a.iter(), b.iter(), c.iter()]);
            assert_eq!(collect(&mut j), [3, 8, 10]);
        }

        fn disjoint<G>() {
            let a = svec::<G>(&[1, 3, 5]);
            let b = svec::<G>(&[2, 4, 6]);
            let mut j = LeapfrogJoin::new(vec![a.iter(), b.iter()]);
            assert_eq!(collect(&mut j), Vec::<usize>::new());
        }

        fn all_same<G>() {
            let a = svec::<G>(&[5]);
            let b = svec::<G>(&[5]);
            let c = svec::<G>(&[5]);
            let mut j = LeapfrogJoin::new(vec![a.iter(), b.iter(), c.iter()]);
            assert_eq!(collect(&mut j), [5]);
        }

        fn one_empty<G>() {
            let a = svec::<G>(&[1, 2, 3]);
            let b = svec::<G>(&[]);
            let mut j = LeapfrogJoin::new(vec![a.iter(), b.iter()]);
            assert_eq!(collect(&mut j), Vec::<usize>::new());
        }

        fn large_sparse<G>() {
            let av: Vec<usize> = (0..1000).step_by(3).collect();
            let bv: Vec<usize> = (0..1000).step_by(7).collect();
            let a = svec::<G>(&av);
            let b = svec::<G>(&bv);
            let mut j = LeapfrogJoin::new(vec![a.iter(), b.iter()]);
            let expected: Vec<usize> = (0..1000).filter(|x| x % 3 == 0 && x % 7 == 0).collect();
            assert_eq!(collect(&mut j), expected);
        }

        fn five_way<G>() {
            let a = svec::<G>(&[1, 2, 3, 5, 7, 10, 15, 20]);
            let b = svec::<G>(&[2, 3, 5, 10, 15, 20, 25]);
            let c = svec::<G>(&[3, 5, 10, 15, 30]);
            let d = svec::<G>(&[5, 10, 15, 20, 30, 40]);
            let e = svec::<G>(&[0, 5, 10, 15, 50]);
            let mut j = LeapfrogJoin::new(vec![a.iter(), b.iter(), c.iter(), d.iter(), e.iter()]);
            assert_eq!(collect(&mut j), [5, 10, 15]);
        }

        fn all_empty<G>() {
            let a = svec::<G>(&[]);
            let b = svec::<G>(&[]);
            let c = svec::<G>(&[]);
            let mut j = LeapfrogJoin::new(vec![a.iter(), b.iter(), c.iter()]);
            assert_eq!(collect(&mut j), Vec::<usize>::new());
        }

        fn large_overlap<G>() {
            // Two sets sharing 90% of elements
            let av: Vec<usize> = (0..1000).collect();
            let bv: Vec<usize> = (0..900).chain(1000..1100).collect();
            let a = svec::<G>(&av);
            let b = svec::<G>(&bv);
            let mut j = LeapfrogJoin::new(vec![a.iter(), b.iter()]);
            let expected: Vec<usize> = (0..900).collect();
            assert_eq!(collect(&mut j), expected);
        }

        fn needle_in_haystack<G>() {
            // One element in common across three large sets
            let av: Vec<usize> = (0..10000).step_by(2).collect();       // evens
            let bv: Vec<usize> = (0..10000).step_by(3).collect();       // mult of 3
            let cv: Vec<usize> = (0..10000).step_by(5000).collect();    // [0, 5000]
            let a = svec::<G>(&av);
            let b = svec::<G>(&bv);
            let c = svec::<G>(&cv);
            let mut j = LeapfrogJoin::new(vec![a.iter(), b.iter(), c.iter()]);
            // 0 is in all three; 5000 is even and not mult of 3
            assert_eq!(collect(&mut j), [0]);
        }

        fn adjacent_miss<G>() {
            // Evens vs odds — no intersection
            let av: Vec<usize> = (0..10000).step_by(2).collect();
            let bv: Vec<usize> = (1..10000).step_by(2).collect();
            let a = svec::<G>(&av);
            let b = svec::<G>(&bv);
            let mut j = LeapfrogJoin::new(vec![a.iter(), b.iter()]);
            assert_eq!(collect(&mut j), Vec::<usize>::new());
        }

        fn asymmetric_sizes<G>() {
            // Tiny set vs huge set
            let small = svec::<G>(&[500, 5000, 50000]);
            let bigv: Vec<usize> = (0..100000).collect();
            let big = svec::<G>(&bigv);
            let mut j = LeapfrogJoin::new(vec![small.iter(), big.iter()]);
            assert_eq!(collect(&mut j), [500, 5000, 50000]);
        }

        fn identical_sets<G>() {
            // Four copies of the same set — intersection is the full set
            let v: Vec<usize> = (0..500).collect();
            let a = svec::<G>(&v);
            let b = svec::<G>(&v);
            let c = svec::<G>(&v);
            let d = svec::<G>(&v);
            let mut j = LeapfrogJoin::new(vec![a.iter(), b.iter(), c.iter(), d.iter()]);
            assert_eq!(collect(&mut j), v);
        }

        fn million_two_way<G>() {
            let av: Vec<usize> = (0..1_000_000).step_by(2).collect();
            let bv: Vec<usize> = (0..1_000_000).step_by(3).collect();
            let a = svec::<G>(&av);
            let b = svec::<G>(&bv);
            let mut j = LeapfrogJoin::new(vec![a.iter(), b.iter()]);
            let result = collect(&mut j);
            let expected: Vec<usize> = (0..1_000_000).step_by(6).collect();
            assert_eq!(result, expected);
        }

        fn million_three_way_sparse<G>() {
            // Multiples of 97, 101, 103 — very sparse intersection
            let av: Vec<usize> = (0..2_000_000).step_by(97).collect();
            let bv: Vec<usize> = (0..2_000_000).step_by(101).collect();
            let cv: Vec<usize> = (0..2_000_000).step_by(103).collect();
            let a = svec::<G>(&av);
            let b = svec::<G>(&bv);
            let c = svec::<G>(&cv);
            let mut j = LeapfrogJoin::new(vec![a.iter(), b.iter(), c.iter()]);
            let result = collect(&mut j);
            let lcm = 97 * 101 * 103; // 1_009_691
            let expected: Vec<usize> = (0..2_000_000).step_by(lcm).collect();
            assert_eq!(result, expected);
        }
    }

    // -- A4: Difference combinator (full ∖ delta) tests --
    mod difference {
        use super::*;
        use crate::id::ENodeId;
        use proptest::prelude::*;

        /// Iterate a `Difference` by `step` and collect the keys.
        fn diff_step(full: &[usize], delta: &[usize]) -> Vec<usize> {
            let fv = svec::<ENodeId>(full);
            let dv = svec::<ENodeId>(delta);
            let mut d = Difference::new(fv.iter(), dv.iter());
            let mut out = Vec::new();
            while let Some(k) = d.key() {
                out.push(k.to_usize());
                d.step();
            }
            out
        }

        #[test]
        fn basic_step() {
            assert_eq!(diff_step(&[1, 2, 3, 4, 5], &[2, 4]), vec![1, 3, 5]);
        }

        #[test]
        fn empty_delta_is_identity() {
            assert_eq!(diff_step(&[1, 2, 3], &[]), vec![1, 2, 3]);
        }

        #[test]
        fn delta_covers_all() {
            assert_eq!(diff_step(&[1, 2, 3], &[1, 2, 3]), Vec::<usize>::new());
        }

        #[test]
        fn delta_outside_full_ignored() {
            // delta entries not in full simply match nothing.
            assert_eq!(diff_step(&[1, 3, 5], &[2, 4, 6]), vec![1, 3, 5]);
        }

        #[test]
        fn basic_seek() {
            // For every target, seek lands on the first key ≥ target in [1,3,5].
            let fv = svec::<ENodeId>(&[1, 2, 3, 4, 5]);
            let dv = svec::<ENodeId>(&[2, 4]);
            let present = [1usize, 3, 5];
            for t in 0..7usize {
                let mut d = Difference::new(fv.iter(), dv.iter());
                d.seek(ENodeId::from_usize(t));
                let got = d.key().map(|k| k.to_usize());
                let exp = present.iter().copied().find(|&x| x >= t);
                assert_eq!(got, exp, "seek({t})");
            }
        }

        fn sorted_unique() -> impl Strategy<Value = Vec<usize>> {
            proptest::collection::vec(0usize..60, 0..30).prop_map(|mut v| {
                v.sort_unstable();
                v.dedup();
                v
            })
        }

        proptest! {
            #![proptest_config(ProptestConfig::with_cases(2000))]

            /// `Difference` by step == `full.filter(|x| !delta.contains(x))`,
            /// for arbitrary sorted-unique full and delta (delta need not be
            /// a subset of full).
            #[test]
            fn matches_filter(full in sorted_unique(), delta in sorted_unique()) {
                let got = diff_step(&full, &delta);
                let expected: Vec<usize> =
                    full.iter().copied().filter(|x| !delta.contains(x)).collect();
                prop_assert_eq!(got, expected);
            }

            /// Seek to every possible target and confirm it lands on the first
            /// non-excluded key ≥ target.
            #[test]
            fn seek_matches_filter(full in sorted_unique(), delta in sorted_unique()) {
                let present: Vec<usize> =
                    full.iter().copied().filter(|x| !delta.contains(x)).collect();
                let fv = svec::<ENodeId>(&full);
                let dv = svec::<ENodeId>(&delta);
                for t in 0..62usize {
                    let mut d = Difference::new(fv.iter(), dv.iter());
                    d.seek(ENodeId::from_usize(t));
                    let got = d.key().map(|k| k.to_usize());
                    let exp = present.iter().copied().find(|&x| x >= t);
                    prop_assert_eq!(got, exp, "seek({})", t);
                }
            }
        }
    }
}