semi-persistent-egraph 0.1.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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//! Generic node store facade — caches + typed routing, parameterized by id types.

use std::hash::Hash;

use crate::caches::*;
use crate::canon::{ACCanon, ACICanon, CCanon, OrderedCanon, PlainCanon, VarCanon};
use crate::containers::DenseId;
use crate::containers::ShrinkPolicy;
use crate::containers::Tagged;
use crate::multiplicity::Multiplicity;
use crate::registry::{OpKind, OpRegistry};
use crate::typed_routing::{NodeIds, NodeRef, RoutingToken, TypedRouting};

pub type ACChild<G> = (G, Multiplicity);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Added<G> {
    Existing(G),
    Fresh(G),
}

impl<G: Copy> Added<G> {
    pub fn id(&self) -> G {
        match *self {
            Added::Existing(id) | Added::Fresh(id) => id,
        }
    }
    pub fn is_fresh(&self) -> bool {
        matches!(self, Added::Fresh(_))
    }
}

pub struct NodeStore<
    G: DenseId,
    O: DenseId,
    V: DenseId,
    C: Tagged + Clone + Copy + Hash + Eq + core::fmt::Debug,
    I: NodeIds,
    const TRACK: bool = true,
    const PROOFS: bool = false,
> {
    routing: TypedRouting<G, I>,
    pub plain0: FixedArityCache<G, O, I::L0, 0, TRACK, PROOFS>,
    pub plain1: FixedArityCache<G, O, I::L1, 1, TRACK, PROOFS>,
    pub plain2: FixedArityCache<G, O, I::L2, 2, TRACK, PROOFS>,
    pub plain3: FixedArityCache<G, O, I::L3, 3, TRACK, PROOFS>,
    pub c: FixedArityCache<G, O, I::LC, 2, TRACK, PROOFS>,
    pub plain_n: VariableArityCache<G, O, G, I::LN, TRACK, PROOFS>,
    pub a: VariableArityCache<G, O, G, I::LA, TRACK, PROOFS>,
    pub ac: VariableArityCache<G, O, C, I::LAC, TRACK, PROOFS>,
    pub aci: VariableArityCache<G, O, G, I::LACI, TRACK, PROOFS>,
    pub lit: LitCache<G, O, V, I::LLit, TRACK>,
}

impl<G, O, V, C, I, const TRACK: bool, const PROOFS: bool> Default
    for NodeStore<G, O, V, C, I, TRACK, PROOFS>
where
    G: DenseId + Hash,
    O: DenseId + Hash,
    V: DenseId + Hash,
    C: Tagged + Clone + Copy + Hash + Eq + core::fmt::Debug,
    I: NodeIds,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<G, O, V, C, I, const TRACK: bool, const PROOFS: bool> NodeStore<G, O, V, C, I, TRACK, PROOFS>
where
    G: DenseId + Hash,
    O: DenseId + Hash,
    V: DenseId + Hash,
    C: Tagged + Clone + Copy + Hash + Eq + core::fmt::Debug,
    I: NodeIds,
{
    pub fn new() -> Self {
        Self {
            routing: TypedRouting::new(),
            plain0: FixedArityCache::new(),
            plain1: FixedArityCache::new(),
            plain2: FixedArityCache::new(),
            plain3: FixedArityCache::new(),
            c: FixedArityCache::new(),
            plain_n: VariableArityCache::new(),
            a: VariableArityCache::new(),
            ac: VariableArityCache::new(),
            aci: VariableArityCache::new(),
            lit: LitCache::new(),
        }
    }

    pub fn len(&self) -> usize {
        self.routing.len()
    }
    pub fn is_empty(&self) -> bool {
        self.routing.is_empty()
    }
    pub fn routing(&self) -> &TypedRouting<G, I> {
        &self.routing
    }

    // -----------------------------------------------------------------------
    // High-level dispatch
    // -----------------------------------------------------------------------

    pub fn add<S: crate::DenseId>(
        &mut self,
        op: O,
        children: &[G],
        ops: &OpRegistry<O, S, TRACK>,
    ) -> Added<G> {
        match ops.info(op).kind {
            OpKind::Normal { .. } => match children.len() {
                0 => self.add_plain0(op),
                1 => self.add_plain1(op, children[0]),
                2 => self.add_plain2(op, [children[0], children[1]]),
                3 => self.add_plain3(op, [children[0], children[1], children[2]]),
                _ => self.add_plain_n(op, children),
            },
            OpKind::Commutative { .. } => {
                assert_eq!(children.len(), 2);
                let pair = if children[0].to_usize() <= children[1].to_usize() {
                    [children[0], children[1]]
                } else {
                    [children[1], children[0]]
                };
                self.add_c(op, pair)
            }
            OpKind::A { .. } => self.add_a(op, children),
            OpKind::AC { .. } => panic!("use add_ac with pre-canonicalized children"),
            OpKind::ACI { .. } => panic!("use add_aci with pre-canonicalized children"),
            OpKind::Lit => panic!("use add_lit for literal operators"),
        }
    }

    // -----------------------------------------------------------------------
    // Per-kind insertion
    // -----------------------------------------------------------------------

    pub fn add_plain0(&mut self, op: O) -> Added<G> {
        let fresh = self.routing.reserve();
        match self.plain0.probe_or_insert(fresh, op, []) {
            InsertResult::Hit { global_id } => {
                self.routing.unreserve();
                Added::Existing(global_id)
            }
            InsertResult::Inserted { local_id } => {
                self.routing.finalize(fresh, NodeRef::Plain0(local_id));
                Added::Fresh(fresh)
            }
        }
    }

    pub fn add_plain1(&mut self, op: O, child: G) -> Added<G> {
        let fresh = self.routing.reserve();
        match self.plain1.probe_or_insert(fresh, op, [child]) {
            InsertResult::Hit { global_id } => {
                self.routing.unreserve();
                Added::Existing(global_id)
            }
            InsertResult::Inserted { local_id } => {
                self.routing.finalize(fresh, NodeRef::Plain1(local_id));
                Added::Fresh(fresh)
            }
        }
    }

    pub fn add_plain2(&mut self, op: O, children: [G; 2]) -> Added<G> {
        let fresh = self.routing.reserve();
        match self.plain2.probe_or_insert(fresh, op, children) {
            InsertResult::Hit { global_id } => {
                self.routing.unreserve();
                Added::Existing(global_id)
            }
            InsertResult::Inserted { local_id } => {
                self.routing.finalize(fresh, NodeRef::Plain2(local_id));
                Added::Fresh(fresh)
            }
        }
    }

    pub fn add_plain3(&mut self, op: O, children: [G; 3]) -> Added<G> {
        let fresh = self.routing.reserve();
        match self.plain3.probe_or_insert(fresh, op, children) {
            InsertResult::Hit { global_id } => {
                self.routing.unreserve();
                Added::Existing(global_id)
            }
            InsertResult::Inserted { local_id } => {
                self.routing.finalize(fresh, NodeRef::Plain3(local_id));
                Added::Fresh(fresh)
            }
        }
    }

    pub fn add_c(&mut self, op: O, children: [G; 2]) -> Added<G> {
        let fresh = self.routing.reserve();
        match self.c.probe_or_insert(fresh, op, children) {
            InsertResult::Hit { global_id } => {
                self.routing.unreserve();
                Added::Existing(global_id)
            }
            InsertResult::Inserted { local_id } => {
                self.routing.finalize(fresh, NodeRef::C(local_id));
                Added::Fresh(fresh)
            }
        }
    }

    pub fn add_plain_n(&mut self, op: O, children: &[G]) -> Added<G> {
        let fresh = self.routing.reserve();
        match self.plain_n.probe_or_insert(fresh, op, children) {
            InsertResult::Hit { global_id } => {
                self.routing.unreserve();
                Added::Existing(global_id)
            }
            InsertResult::Inserted { local_id } => {
                self.routing.finalize(fresh, NodeRef::PlainN(local_id));
                Added::Fresh(fresh)
            }
        }
    }

    pub fn add_a(&mut self, op: O, children: &[G]) -> Added<G> {
        let fresh = self.routing.reserve();
        match self.a.probe_or_insert(fresh, op, children) {
            InsertResult::Hit { global_id } => {
                self.routing.unreserve();
                Added::Existing(global_id)
            }
            InsertResult::Inserted { local_id } => {
                self.routing.finalize(fresh, NodeRef::A(local_id));
                Added::Fresh(fresh)
            }
        }
    }

    pub fn add_ac(&mut self, op: O, children: &[C]) -> Added<G> {
        let fresh = self.routing.reserve();
        match self.ac.probe_or_insert(fresh, op, children) {
            InsertResult::Hit { global_id } => {
                self.routing.unreserve();
                Added::Existing(global_id)
            }
            InsertResult::Inserted { local_id } => {
                self.routing.finalize(fresh, NodeRef::AC(local_id));
                Added::Fresh(fresh)
            }
        }
    }

    pub fn add_aci(&mut self, op: O, children: &[G]) -> Added<G> {
        let fresh = self.routing.reserve();
        match self.aci.probe_or_insert(fresh, op, children) {
            InsertResult::Hit { global_id } => {
                self.routing.unreserve();
                Added::Existing(global_id)
            }
            InsertResult::Inserted { local_id } => {
                self.routing.finalize(fresh, NodeRef::ACI(local_id));
                Added::Fresh(fresh)
            }
        }
    }

    pub fn add_lit(&mut self, op: O, lit: V) -> Added<G> {
        let fresh = self.routing.reserve();
        match self.lit.probe_or_insert(fresh, op, lit) {
            InsertResult::Hit { global_id } => {
                self.routing.unreserve();
                Added::Existing(global_id)
            }
            InsertResult::Inserted { local_id } => {
                self.routing.finalize(fresh, NodeRef::Lit(local_id));
                Added::Fresh(fresh)
            }
        }
    }

    // -----------------------------------------------------------------------
    // Recanonize
    // -----------------------------------------------------------------------

    /// Recanonize a single node's children after a union. Dispatches to the
    /// appropriate cache with the correct canonization strategy.
    /// `g_buf` — scratch for PlainN/A/ACI (child type G).
    /// `ac_buf` — scratch for AC (child type C).
    /// `collisions` — destination for collision pairs to push onto worklist.
    pub fn recanonize_node(
        &mut self,
        id: G,
        find: impl Fn(G) -> G,
        g_buf: &mut Vec<G>,
        ac_buf: &mut Vec<C>,
        collisions: &mut Vec<(G, G)>,
    ) where
        ACCanon: VarCanon<G, C>,
    {
        match self.routing.get(id) {
            NodeRef::Plain0(_) => {}
            NodeRef::Plain1(l) => self
                .plain1
                .recanonize_node::<PlainCanon>(l, &find, collisions),
            NodeRef::Plain2(l) => self
                .plain2
                .recanonize_node::<PlainCanon>(l, &find, collisions),
            NodeRef::Plain3(l) => self
                .plain3
                .recanonize_node::<PlainCanon>(l, &find, collisions),
            NodeRef::C(l) => self.c.recanonize_node::<CCanon>(l, &find, collisions),
            NodeRef::PlainN(l) => self
                .plain_n
                .recanonize_node::<OrderedCanon>(l, &find, g_buf, collisions),
            NodeRef::A(l) => self
                .a
                .recanonize_node::<OrderedCanon>(l, &find, g_buf, collisions),
            NodeRef::AC(l) => self
                .ac
                .recanonize_node::<ACCanon>(l, &find, ac_buf, collisions),
            NodeRef::ACI(l) => self
                .aci
                .recanonize_node::<ACICanon>(l, &find, g_buf, collisions),
            NodeRef::Lit(_) => {}
        }
    }

    // -----------------------------------------------------------------------
    // History lookup (PROOFS=true)
    // -----------------------------------------------------------------------

    /// Retrieve original (pre-recanonize) children of a node.
    /// Appends to `g_out` for all kinds except AC (which appends to `ac_out`).
    /// Returns true if history was found.
    pub fn original_children(&self, id: G, g_out: &mut Vec<G>, ac_out: &mut Vec<C>) -> bool
    where
        ACCanon: VarCanon<G, C>,
    {
        match self.routing.get(id) {
            NodeRef::Plain0(_) | NodeRef::Lit(_) => false,
            NodeRef::Plain1(_) => {
                if let Some(c) = self.plain1.original_children(id) {
                    g_out.extend_from_slice(&c);
                    true
                } else {
                    false
                }
            }
            NodeRef::Plain2(_) => {
                if let Some(c) = self.plain2.original_children(id) {
                    g_out.extend_from_slice(&c);
                    true
                } else {
                    false
                }
            }
            NodeRef::Plain3(_) => {
                if let Some(c) = self.plain3.original_children(id) {
                    g_out.extend_from_slice(&c);
                    true
                } else {
                    false
                }
            }
            NodeRef::C(_) => {
                if let Some(c) = self.c.original_children(id) {
                    g_out.extend_from_slice(&c);
                    true
                } else {
                    false
                }
            }
            NodeRef::PlainN(_) => self.plain_n.original_children(id, g_out),
            NodeRef::A(_) => self.a.original_children(id, g_out),
            NodeRef::AC(_) => self.ac.original_children(id, ac_out),
            NodeRef::ACI(_) => self.aci.original_children(id, g_out),
        }
    }

    // -----------------------------------------------------------------------
    // Semi-persistence
    // -----------------------------------------------------------------------

    pub fn mark(&mut self, shrink: ShrinkPolicy) -> NodeStoreToken {
        NodeStoreToken {
            routing: self.routing.mark(shrink),
            plain0: self.plain0.mark(shrink),
            plain1: self.plain1.mark(shrink),
            plain2: self.plain2.mark(shrink),
            plain3: self.plain3.mark(shrink),
            c: self.c.mark(shrink),
            plain_n: self.plain_n.mark(shrink),
            a: self.a.mark(shrink),
            ac: self.ac.mark(shrink),
            aci: self.aci.mark(shrink),
            lit: self.lit.mark(shrink),
        }
    }

    pub fn restore(&mut self, token: NodeStoreToken) {
        self.routing.restore(token.routing);
        self.plain0.restore(token.plain0);
        self.plain1.restore(token.plain1);
        self.plain2.restore(token.plain2);
        self.plain3.restore(token.plain3);
        self.c.restore(token.c);
        self.plain_n.restore(token.plain_n);
        self.a.restore(token.a);
        self.ac.restore(token.ac);
        self.aci.restore(token.aci);
        self.lit.restore(token.lit);
    }
}

#[derive(Clone, Copy, Debug)]
pub struct NodeStoreToken {
    routing: RoutingToken,
    plain0: CacheToken,
    plain1: CacheToken,
    plain2: CacheToken,
    plain3: CacheToken,
    c: CacheToken,
    plain_n: PoolCacheToken,
    a: PoolCacheToken,
    ac: PoolCacheToken,
    aci: PoolCacheToken,
    lit: CacheToken,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::id::{ENodeId, OpId, SortId};
    use crate::nodes::*;
    use crate::registry::SortRegistry;

    struct TestIds;
    impl NodeIds for TestIds {
        type L0 = Plain0Id;
        type L1 = Plain1Id;
        type L2 = Plain2Id;
        type L3 = Plain3Id;
        type LC = CNodeId;
        type LN = PlainNId;
        type LA = ANodeId;
        type LAC = ACNodeId;
        type LACI = ACINodeId;
        type LLit = LitNodeId;
    }

    type NS = NodeStore<ENodeId, OpId, LitValId, ACChild<ENodeId>, TestIds, false>;

    fn setup() -> (NS, OpRegistry<OpId, SortId, false>) {
        let mut sorts: SortRegistry<SortId, false> = SortRegistry::new();
        let int = sorts.intern("Int");
        let bool_ = sorts.intern("Bool");

        let mut ops: OpRegistry<OpId, SortId, false> = OpRegistry::new();
        ops.register("Zero", &[], int);
        ops.register("Neg", &[int], int);
        ops.register("Div", &[int, int], int);
        ops.register("ITE", &[bool_, int, int], int);
        ops.register_c("Eq", [int, int], bool_);
        ops.register_a("Sub", int, int, crate::registry::AssocDir::Left);
        ops.register_ac("Add", int, int);
        ops.register_aci("And", bool_, bool_);
        ops.register_lit("ILit", int);

        (NS::new(), ops)
    }

    #[test]
    fn add_and_dedup() {
        let (mut ns, ops) = setup();
        let zero = ops.id_by_name("Zero").unwrap();

        let a = ns.add(zero, &[], &ops);
        assert!(a.is_fresh());
        let b = ns.add(zero, &[], &ops);
        assert!(!b.is_fresh());
        assert_eq!(a.id(), b.id());
        assert_eq!(ns.len(), 1);
    }

    #[test]
    fn commutative_dedup() {
        let (mut ns, ops) = setup();
        let eq = ops.id_by_name("Eq").unwrap();
        let ilit = ops.id_by_name("ILit").unwrap();

        let a = ns.add_lit(ilit, LitValId::new(0));
        let b = ns.add_lit(ilit, LitValId::new(1));

        let e1 = ns.add(eq, &[a.id(), b.id()], &ops);
        let e2 = ns.add(eq, &[b.id(), a.id()], &ops);
        assert!(e1.is_fresh());
        assert!(!e2.is_fresh());
        assert_eq!(e1.id(), e2.id());
    }

    #[test]
    fn routing_roundtrip() {
        let (mut ns, ops) = setup();
        let neg = ops.id_by_name("Neg").unwrap();
        let ilit = ops.id_by_name("ILit").unwrap();

        let lit = ns.add_lit(ilit, LitValId::new(42));
        let n = ns.add(neg, &[lit.id()], &ops);
        let r = ns.routing().get(n.id());
        assert!(matches!(r, NodeRef::Plain1(_)));
    }

    #[test]
    fn recanonize_plain_collision() {
        let (mut ns, ops) = setup();
        let neg = ops.id_by_name("Neg").unwrap();
        let ilit = ops.id_by_name("ILit").unwrap();

        let a = ns.add_lit(ilit, LitValId::new(0)).id(); // e0
        let b = ns.add_lit(ilit, LitValId::new(1)).id(); // e1
        let na = ns.add(neg, &[a], &ops).id(); // neg(e0) = e2
        let nb = ns.add(neg, &[b], &ops).id(); // neg(e1) = e3

        // simulate union(a, b) → find(b) = a
        let mut g_buf = Vec::new();
        let mut ac_buf = Vec::new();
        let mut collisions = Vec::new();
        ns.recanonize_node(
            nb,
            |g| if g == b { a } else { g },
            &mut g_buf,
            &mut ac_buf,
            &mut collisions,
        );
        // neg(e1) became neg(e0) → collision with na
        assert_eq!(collisions, vec![(nb, na)]);
    }

    #[test]
    fn recanonize_no_change() {
        let (mut ns, ops) = setup();
        let neg = ops.id_by_name("Neg").unwrap();
        let ilit = ops.id_by_name("ILit").unwrap();

        let a = ns.add_lit(ilit, LitValId::new(0)).id();
        let _na = ns.add(neg, &[a], &ops).id();

        let mut g_buf = Vec::new();
        let mut ac_buf = Vec::new();
        let mut collisions = Vec::new();
        ns.recanonize_node(_na, |g| g, &mut g_buf, &mut ac_buf, &mut collisions);
        assert!(collisions.is_empty());
    }
}