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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//! Canonization strategies for node children during rebuild.
//!
//! Two traits:
//! - `FixedCanon<G, K>` — in-place canonization of `[G; K]` (never shrinks)
//! - `VarCanon<G, C>` — destination-passing canonization into a reusable buffer

use crate::containers::DenseId;

// ---------------------------------------------------------------------------
// Fixed-arity canonization
// ---------------------------------------------------------------------------

/// Canonize a fixed-size children array in place.
pub trait FixedCanon<G: DenseId, const K: usize> {
    fn canonize(children: &mut [G; K], find: impl Fn(G) -> G);
}

/// Plain: just apply find to each child, preserve order.
pub struct PlainCanon;

impl<G: DenseId, const K: usize> FixedCanon<G, K> for PlainCanon {
    #[inline]
    fn canonize(children: &mut [G; K], find: impl Fn(G) -> G) {
        for c in children.iter_mut() {
            *c = find(*c);
        }
    }
}

/// Commutative: apply find, then sort the pair.
pub struct CCanon;

impl<G: DenseId + Ord> FixedCanon<G, 2> for CCanon {
    #[inline]
    fn canonize(children: &mut [G; 2], find: impl Fn(G) -> G) {
        children[0] = find(children[0]);
        children[1] = find(children[1]);
        if children[0] > children[1] {
            children.swap(0, 1);
        }
    }
}

// ---------------------------------------------------------------------------
// Variable-arity canonization
// ---------------------------------------------------------------------------

/// The count clamp for a variadic op's canonical form (design "storage partition and clamp are
/// independent axes"). Passed to [`VarCanon::canonize`] so the clamp is applied *inside*
/// canonization (its output is always the canonical form), not fixed up afterward. Kept
/// clamp-mode-only here so `canon.rs` needs no `registry` dependency: the caller maps the op's
/// `Clamp` descriptor to this before canonizing. Only [`MSetCanon`] acts on a non-`None` value;
/// the clamp-free canonizers ([`OrderedCanon`]) and the ones whose clamp is structural
/// ([`SetCanon`]'s `dedup` = idempotent) ignore it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MSetClamp {
    /// No count clamp beyond what the canonizer bakes in (plain AC; also the value passed to the
    /// clamp-free / structurally-clamped canonizers).
    None,
    /// Nilpotent order `n`: counts reduce mod `n`, zeroed summands drop (`x∘x = e`).
    Nilpotent { order: u8 },
}

/// The full canonization mode for a variadic op: the count clamp plus the op's identity
/// (unit) **class**, if any. The unit is the second algebraic canonization law (`f(x,e) = x`:
/// drop the unit's class from the monomial) and, unlike the count clamp, it is
/// *class-relative* — the caller resolves the unit node to its current class (`find`) before
/// canonizing, so a summand that merged into the unit's class after the node was built is
/// dropped on recanonize exactly as it would have been at build (Kapur Lemma 4.3's standing
/// assumption that monomials are normalized by `f(x,e) → x`). `unit: None` for ops without a
/// declared identity, and for the clamp-free canonizers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CanonMode<G> {
    pub clamp: MSetClamp,
    pub unit: Option<G>,
}

impl<G> CanonMode<G> {
    /// No clamp, no unit — plain AC and the clamp-free canonizers.
    pub const PLAIN: Self = Self {
        clamp: MSetClamp::None,
        unit: None,
    };
}

/// `canonize` must *establish* the representation invariant: its output is, by definition, the
/// canonical child form for the op — never a temporarily-wrong form fixed up by a later pass.
/// Where an op's canonical form depends on an algebraic law — the count clamp (nilpotent:
/// counts mod n) or the identity unit-drop (`f(x,e) = x`) — the law is applied *inside*
/// `canonize` via the `mode` argument, exactly as [`SetCanon`] bakes its idempotent clamp
/// (`dedup`) into its own `canonize`. `mode` is a concrete parameter (not an associated type)
/// so it adds no `where`-clause bound anywhere; canonizers that do not act on it take it and
/// ignore it.
pub trait VarCanon<G: DenseId, C> {
    fn canonize(
        buf: &mut Vec<C>,
        start: usize,
        end: usize,
        get: impl Fn(usize) -> C,
        find: impl Fn(G) -> G,
        mode: CanonMode<G>,
    );
}

/// Ordered: apply find, preserve order. (PlainN, A). No clamp; `mode` ignored.
///
/// An A-only op's two algebraic laws — flatten a nested same-op child into the sequence, and
/// collapse a one-element sequence to its element — run at **build** time only
/// (`EGraph::add`'s `flatten_seq_children` and its `OpKind::A` degeneracy arm), so they are
/// deliberately absent here. Two reasons, and they agree: recanonization writes children back
/// into the node's existing span, which can shrink but not grow, so a splice could not be
/// expressed; and the AC counterpart makes the same choice, where §6c of
/// `ac-congruence-completeness.md` gives a paper argument that recanon-time flattening is
/// vacuous. See
/// `doc/design/04-canonization.md`, "A-Only Operators", for what the build-only placement
/// leaves open.
pub struct OrderedCanon;

impl<G: DenseId> VarCanon<G, G> for OrderedCanon {
    #[inline]
    fn canonize(
        buf: &mut Vec<G>,
        start: usize,
        end: usize,
        get: impl Fn(usize) -> G,
        find: impl Fn(G) -> G,
        _mode: CanonMode<G>,
    ) {
        for i in start..end {
            buf.push(find(get(i)));
        }
    }
}

/// AC: apply find to G component, sort by G, merge duplicate G's by summing multiplicities, then
/// apply the op's count clamp. The two named steps — [`update_multiset`](Self::update_multiset)
/// (raw representation: find+sort+coalesce, ℕ counts) and [`clamp_multiset`](Self::clamp_multiset)
/// (the algebraic clamp) — are sequenced by `canonize`, so its output is always the canonical form.
pub struct MSetCanon;

impl MSetCanon {
    /// Raw multiset maintenance: find each child, sort by class id, coalesce duplicates by summing
    /// multiplicities. Produces a sorted, duplicate-free multiset with ℕ counts — the
    /// representation, before any algebraic clamp.
    pub fn update_multiset<G: DenseId + Ord, M: crate::multiplicity::MultiplicityLike>(
        buf: &mut Vec<crate::containers::Pair<G, M>>,
        start: usize,
        end: usize,
        get: impl Fn(usize) -> crate::containers::Pair<G, M>,
        find: impl Fn(G) -> G,
    ) {
        for i in start..end {
            let crate::containers::Pair { a: g, b: m } = get(i);
            buf.push(crate::containers::Pair { a: find(g), b: m });
        }
        buf.sort_by_key(|a| a.a);
        // merge adjacent duplicates
        let mut w = 0;
        for r in 1..buf.len() {
            if buf[r].a == buf[w].a {
                // Coalescing is the one place the representation *grows* a
                // multiplicity, so it is the one place a configured width can be
                // exceeded. Detected rather than wrapped: a wrapped sum would
                // shrink the monomial — to zero at exactly the wrong values —
                // and `retain`-style clamps would then delete summands, making
                // the e-graph assert equalities that do not hold.
                buf[w].b = buf[w].b.checked_add(buf[r].b).expect(
                    "multiset coalescing overflowed EGraphConfig::M; \
                     the configured multiplicity width is too narrow for this e-graph",
                );
            } else {
                w += 1;
                buf[w] = buf[r];
            }
        }
        if !buf.is_empty() {
            buf.truncate(w + 1);
        }
    }

    /// Apply the op's count clamp to an already-`update_multiset`'d buffer, in place. `None` is a
    /// no-op (plain AC). `Nilpotent { order: n }` reduces each count mod `n` and drops the summands
    /// that vanish, so `xor(a,a)` (`{a:2}`) becomes `{}`. Preserves sort order (`retain`), so the
    /// result stays canonical.
    pub fn clamp_multiset<G: DenseId, M: crate::multiplicity::MultiplicityLike>(
        buf: &mut Vec<crate::containers::Pair<G, M>>,
        mode: MSetClamp,
    ) {
        if let MSetClamp::Nilpotent { order } = mode {
            for p in buf.iter_mut() {
                p.b = p.b.rem_order(order);
            }
            buf.retain(|p| p.b != M::ZERO);
        }
    }
}

impl<G: DenseId + Ord, M: crate::multiplicity::MultiplicityLike>
    VarCanon<G, crate::containers::Pair<G, M>> for MSetCanon
{
    fn canonize(
        buf: &mut Vec<crate::containers::Pair<G, M>>,
        start: usize,
        end: usize,
        get: impl Fn(usize) -> crate::containers::Pair<G, M>,
        find: impl Fn(G) -> G,
        mode: CanonMode<G>,
    ) {
        Self::update_multiset(buf, start, end, get, find);
        // Identity unit-drop (`f(x,e) = x`) before the count clamp, matching the build
        // path (`EGraph::add` drops the unit before the nilpotent clamp). `mode.unit` is
        // the unit's *class* as of this rebuild, resolved by the caller through `find`.
        if let Some(u) = mode.unit {
            buf.retain(|p| p.a != u);
        }
        Self::clamp_multiset(buf, mode.clamp);
    }
}

/// ACI: apply find, sort, dedup. The `dedup` *is* the idempotent clamp, baked into canonize (no
/// separate mode) — the precedent for keeping a clamp inside canonize rather than after it.
/// `mode` is ignored (idempotence is structural here, not a count clamp).
pub struct SetCanon;

impl<G: DenseId + Ord> VarCanon<G, G> for SetCanon {
    fn canonize(
        buf: &mut Vec<G>,
        start: usize,
        end: usize,
        get: impl Fn(usize) -> G,
        find: impl Fn(G) -> G,
        mode: CanonMode<G>,
    ) {
        for i in start..end {
            buf.push(find(get(i)));
        }
        buf.sort();
        buf.dedup();
        // Identity unit-drop, mirroring the build path (`and(a, true) → {a}`).
        if let Some(u) = mode.unit {
            buf.retain(|&g| g != u);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::containers::Pair;
    fn mp(g: u32, m: u32) -> Pair<crate::id::ENodeId, Multiplicity> {
        Pair {
            a: id(g),
            b: Multiplicity(m),
        }
    }
    use crate::id::ENodeId;
    use crate::multiplicity::Multiplicity;

    fn id(n: u32) -> ENodeId {
        ENodeId::new(n)
    }

    #[test]
    fn plain_canon_preserves_order() {
        let mut ch = [id(2), id(4), id(6)];
        // find: even → half
        PlainCanon::canonize(&mut ch, |g| ENodeId::new(g.raw() / 2));
        assert_eq!(ch, [id(1), id(2), id(3)]);
    }

    #[test]
    fn c_canon_sorts() {
        let mut ch = [id(5), id(2)];
        CCanon::canonize(&mut ch, |g| g);
        assert_eq!(ch, [id(2), id(5)]);
    }

    #[test]
    fn c_canon_find_then_sort() {
        // find maps 10→1, 20→2
        let mut ch = [id(20), id(10)];
        CCanon::canonize(&mut ch, |g| ENodeId::new(g.raw() / 10));
        assert_eq!(ch, [id(1), id(2)]);
    }

    #[test]
    fn mset_canon_merges() {
        let pool = [mp(3, 1), mp(1, 2), mp(3, 1)];
        let mut buf = Vec::new();
        MSetCanon::canonize(&mut buf, 0, 3, |i| pool[i], |g| g, CanonMode::PLAIN);
        assert_eq!(buf, vec![mp(1, 2), mp(3, 2)]);
    }

    #[test]
    fn mset_canon_nilpotent_clamps_mod_order() {
        // xor(a,a) → {a:2} → {} at order 2; xor(a,a,a,b) → {a:3,b:1} → {a:1,b:1}.
        let pool = [mp(1, 1), mp(1, 1), mp(1, 1), mp(2, 1)];
        let mut buf = Vec::new();
        MSetCanon::canonize(
            &mut buf,
            0,
            4,
            |i| pool[i],
            |g| g,
            CanonMode {
                clamp: MSetClamp::Nilpotent { order: 2 },
                unit: None,
            },
        );
        assert_eq!(buf, vec![mp(1, 1), mp(2, 1)]);
        // A fully-even monomial empties to {}.
        let even = [mp(1, 1), mp(1, 1)];
        let mut b2 = Vec::new();
        MSetCanon::canonize(
            &mut b2,
            0,
            2,
            |i| even[i],
            |g| g,
            CanonMode {
                clamp: MSetClamp::Nilpotent { order: 2 },
                unit: None,
            },
        );
        assert!(b2.is_empty());
    }

    #[test]
    fn mset_canon_find_and_merge() {
        // find: 2→1, 3→1, 4→4
        let pool = [mp(2, 1), mp(3, 1), mp(4, 1)];
        let mut buf = Vec::new();
        MSetCanon::canonize(
            &mut buf,
            0,
            3,
            |i| pool[i],
            |g| {
                if g.raw() <= 3 { id(1) } else { g }
            },
            CanonMode::PLAIN,
        );
        assert_eq!(buf, vec![mp(1, 2), mp(4, 1)]);
    }

    #[test]
    fn aci_canon_dedup() {
        let pool = [id(3), id(1), id(3), id(2), id(1)];
        let mut buf = Vec::new();
        SetCanon::canonize(&mut buf, 0, 5, |i| pool[i], |g| g, CanonMode::PLAIN);
        assert_eq!(buf, vec![id(1), id(2), id(3)]);
    }

    #[test]
    fn mset_canon_drops_unit_class() {
        // add(a, u, u) after the unit resolves to class 7: {1:1, 7:2} → {1:1}.
        let pool = [mp(1, 1), mp(7, 2)];
        let mut buf = Vec::new();
        MSetCanon::canonize(
            &mut buf,
            0,
            2,
            |i| pool[i],
            |g| g,
            CanonMode {
                clamp: MSetClamp::None,
                unit: Some(id(7)),
            },
        );
        assert_eq!(buf, vec![mp(1, 1)]);
    }

    #[test]
    fn mset_canon_unit_drop_before_nilpotent_clamp() {
        // xor(a, a, u) with unit class 7 at order 2: drop u, then {a:2} clamps to {}.
        let pool = [mp(1, 2), mp(7, 1)];
        let mut buf = Vec::new();
        MSetCanon::canonize(
            &mut buf,
            0,
            2,
            |i| pool[i],
            |g| g,
            CanonMode {
                clamp: MSetClamp::Nilpotent { order: 2 },
                unit: Some(id(7)),
            },
        );
        assert!(buf.is_empty());
    }

    #[test]
    fn set_canon_drops_unit_class() {
        let pool = [id(1), id(7), id(2)];
        let mut buf = Vec::new();
        SetCanon::canonize(
            &mut buf,
            0,
            3,
            |i| pool[i],
            |g| g,
            CanonMode {
                clamp: MSetClamp::None,
                unit: Some(id(7)),
            },
        );
        assert_eq!(buf, vec![id(1), id(2)]);
    }

    #[test]
    fn aci_canon_find_and_dedup() {
        // find: 2→1, 3→1
        let pool = [id(1), id(2), id(3)];
        let mut buf = Vec::new();
        SetCanon::canonize(
            &mut buf,
            0,
            3,
            |i| pool[i],
            |g| {
                if g.raw() <= 3 { id(1) } else { g }
            },
            CanonMode::PLAIN,
        );
        assert_eq!(buf, vec![id(1)]);
    }
}