Skip to main content

semi_persistent_egraph/au/
mod.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Anti-unification over the frozen e-graph.
4//!
5//! Implements `doc/design/19-anti-unification.md`: cycle-policy-parameterized
6//! Exact and Monte-Carlo graph search, plus contextual Exact delegation.
7//! Pair-mode root Exact uses bounded relaxation over the finite ordered-pair
8//! graph; side-mode Exact and every MCGS mode use contextual graphs. A
9//! `SearchSession` shares terms and scoped result certificates between them.
10//!
11//! Both algorithms handle AC/ACI operators through min-cost transportation
12//! (`transport.rs`, `ac_repr.rs`): pair-mode root Exact relaxes cell-pair
13//! values, contextual Exact solves cell states recursively, and both find each
14//! representation's optimal matching by flow; MCGS uses one
15//! transport-AND-node per feasible representation pair, with all legal cells as
16//! bandit arms and the flow recomputed from cell Q estimates on every
17//! backpropagation. Neither path enumerates matching permutations.
18//!
19//! Search state is semi-persistent (`SearchSession`/`SearchToken` in
20//! `session.rs`): the space, term pool, best-result table, action cache, and
21//! MCGS statistics all mark/restore together through bundled underlying
22//! container tokens. `Completion::Exact` is cycle-global for pair-mode root
23//! Exact over its supported action domain and policy-relative for contextual
24//! searches; otherwise a run reports `BudgetExhausted`.
25//! Interpreter commands `(antiunify)` and `(checkau)` expose the system from
26//! .egg programs.
27//!
28//! The implemented policies are UCT OR-selection and three AND-node effort
29//! selectors — `lct_and` (default), `uct_and`, and `round_robin` (§3.3.5)
30//! (alternatives such as PUCT and priors are future work; see
31//! `doc/future/au-associative-operators.md`). AU id widths follow
32//! `EGraphConfig::Au`: every container instantiates its id family from
33//! the configuration (`AuIds31` for DefaultConfig, `AuIds64` for Config64).
34//!
35//! Results are ranked by the lexicographic key `(size, variant_mass)` — at equal
36//! size, the term with less structure under `Variants` nodes (= more shared
37//! backbone) wins, so `f(Variants(x,y))` beats `Variants(x, f(y))`. See `terms.rs`
38//! and Appendix C.1 of the design chapter.
39
40pub mod ac_repr;
41pub mod actions;
42pub mod census;
43#[cfg(test)]
44mod dump;
45pub mod egraph_api;
46pub mod estimates;
47pub mod exact;
48mod exact_fixed;
49pub mod exact_memo;
50pub mod mcgs;
51pub mod pretty;
52pub mod results;
53pub mod reward;
54pub mod session;
55pub mod space;
56pub mod terms;
57pub mod transport;
58
59use crate::containers;
60
61containers::define_id31! {
62    /// Dense index of a live e-class inside one AU snapshot (§5.3). Minted only by
63    /// the snapshot's representative-to-dense map, so a non-canonical id or an id
64    /// from another snapshot cannot enter search state.
65    pub struct AuClassId / StoredAuClassId, "auc";
66}
67
68containers::define_id31! {
69    /// Index of a strongly connected component in the snapshot's class graph (§2.4).
70    pub struct SccId / StoredSccId, "scc";
71}
72
73// --- 31-bit AU id family (DefaultConfig) ---
74
75containers::define_id31! { pub struct SnapshotMemberId / StoredSnapshotMemberId, "sm"; }
76containers::define_id31! { pub struct ContextElemId / StoredContextElemId, "ce"; }
77containers::define_id31! { pub struct TermChildId / StoredTermChildId, "tc"; }
78containers::define_id31! { pub struct ReachBlockId / StoredReachBlockId, "rb"; }
79containers::define_id31! { pub struct OrStatsId / StoredOrStatsId, "os"; }
80containers::define_id31! { pub struct AndStatsId / StoredAndStatsId, "as"; }
81containers::define_id31! { pub struct OrEdgeStatId / StoredOrEdgeStatId, "oes"; }
82containers::define_id31! { pub struct AndChildStatId / StoredAndChildStatId, "acs"; }
83
84/// The 31-bit AU id family. Used by `DefaultConfig`.
85pub struct AuIds31;
86impl crate::config::AuIds for AuIds31 {
87    type Index = u32;
88    type Class = AuClassId;
89    type Scc = SccId;
90    type Or = space::OrId;
91    type Action = space::ActionId;
92    type Context = space::CtxId;
93    type Term = terms::TermId;
94    type OrStats = OrStatsId;
95    type AndStats = AndStatsId;
96    type OrEdgeStat = OrEdgeStatId;
97    type AndChildStat = AndChildStatId;
98    type SnapshotMember = SnapshotMemberId;
99    type ContextElem = ContextElemId;
100    type TermChild = TermChildId;
101    type ReachBlock = ReachBlockId;
102}
103
104// --- 63-bit AU id family (Config64) ---
105
106containers::define_id63! { pub struct AuClassId64 / StoredAuClassId64, "auc64"; }
107containers::define_id63! { pub struct SccId64 / StoredSccId64, "scc64"; }
108containers::define_id63! { pub struct OrId64 / StoredOrId64, "or64"; }
109containers::define_id63! { pub struct ActionId64 / StoredActionId64, "act64"; }
110containers::define_id63! { pub struct CtxId64 / StoredCtxId64, "ctx64"; }
111containers::define_id63! { pub struct TermId64 / StoredTermId64, "t64"; }
112containers::define_id63! { pub struct OrStatsId64 / StoredOrStatsId64, "os64"; }
113containers::define_id63! { pub struct AndStatsId64 / StoredAndStatsId64, "as64"; }
114containers::define_id63! { pub struct OrEdgeStatId64 / StoredOrEdgeStatId64, "oes64"; }
115containers::define_id63! { pub struct AndChildStatId64 / StoredAndChildStatId64, "acs64"; }
116containers::define_id63! { pub struct SnapshotMemberId64 / StoredSnapshotMemberId64, "sm64"; }
117containers::define_id63! { pub struct ContextElemId64 / StoredContextElemId64, "ce64"; }
118containers::define_id63! { pub struct TermChildId64 / StoredTermChildId64, "tc64"; }
119containers::define_id63! { pub struct ReachBlockId64 / StoredReachBlockId64, "rb64"; }
120
121/// The 63-bit AU id family. Used by `Config64`.
122pub struct AuIds64;
123impl crate::config::AuIds for AuIds64 {
124    type Index = u64;
125    type Class = AuClassId64;
126    type Scc = SccId64;
127    type Or = OrId64;
128    type Action = ActionId64;
129    type Context = CtxId64;
130    type Term = TermId64;
131    type OrStats = OrStatsId64;
132    type AndStats = AndStatsId64;
133    type OrEdgeStat = OrEdgeStatId64;
134    type AndChildStat = AndChildStatId64;
135    type SnapshotMember = SnapshotMemberId64;
136    type ContextElem = ContextElemId64;
137    type TermChild = TermChildId64;
138    type ReachBlock = ReachBlockId64;
139}
140
141// ---------------------------------------------------------------------------
142// Config-projected type aliases (readability in Cfg-generic signatures)
143// ---------------------------------------------------------------------------
144
145/// The AU class id selected by a config.
146pub type ClassOf<Cfg> = <<Cfg as crate::config::EGraphConfig>::Au as crate::config::AuIds>::Class;
147/// The OR-node id selected by a config.
148pub type OrOf<Cfg> = <<Cfg as crate::config::EGraphConfig>::Au as crate::config::AuIds>::Or;
149/// The term id selected by a config.
150pub type TermOf<Cfg> = <<Cfg as crate::config::EGraphConfig>::Au as crate::config::AuIds>::Term;
151
152/// A typed span into a flattened persistent pool: `start` is a typed position
153/// in the target pool (so spans cannot be applied to the wrong pool), `len`
154/// is in the configured index width. All conversions are checked.
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
156pub struct Span<I: containers::DenseId> {
157    pub start: I,
158    pub len: I::Index,
159}
160
161impl<I: containers::DenseId> Span<I> {
162    /// Build a span from usize bounds, panicking if either exceeds the
163    /// configured AU capacity.
164    ///
165    /// `start` goes through `DenseId::try_new`, not `from_usize`: the latter is
166    /// documented as unchecked and masks, so a start past `I::id_bound()` would
167    /// silently become a position inside the pool and the span would read some other
168    /// entry's elements as its own. `I` spans twice the id space (the top bit is the
169    /// inline tag), so a pool that outgrows the id bound is representable as a length
170    /// but not as a start.
171    #[inline]
172    pub fn new(start: usize, len: usize) -> Self {
173        use crate::containers::IndexLike;
174        Span {
175            start: I::try_new(start)
176                .unwrap_or_else(|| panic!("span start {start} exceeds the configured AU capacity")),
177            len: I::Index::try_from_usize(len).expect("span length exceeds configured AU capacity"),
178        }
179    }
180
181    #[inline]
182    pub fn start_usize(&self) -> usize {
183        self.start.to_usize()
184    }
185
186    #[inline]
187    pub fn len_usize(&self) -> usize {
188        use crate::containers::IndexLike;
189        self.len.as_usize()
190    }
191
192    #[inline]
193    pub fn end_usize(&self) -> usize {
194        self.start_usize() + self.len_usize()
195    }
196}
197
198/// Errors surfaced while building an AU snapshot (§4.1).
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub enum AuError {
201    /// A class transitively needed by a root has no admissible finite member
202    /// after filtering `FLAG_SUBSUMED` nodes. The payload is the raw dense
203    /// class index, carried as `u64` for DIAGNOSTIC DISPLAY ONLY: it is not a
204    /// typed id and must never flow back into AU indexing operations.
205    NoFiniteRepresentative(u64),
206    // There is deliberately no `MultiplicityOverflow` variant. Snapshot construction
207    // used to narrow every multiplicity to a hardcoded `u32` and fail here; nothing
208    // narrows now. Multiplicities are read at [`EGraphConfig::M`] and widened losslessly
209    // to `u64` where the AU search needs a common width, so the read cannot overflow.
210    // What *can* still exceed a width is a *sum* of multiplicities, and that is not an
211    // error: [`actions::generate_actions`] answers a summation overflow by enumerating no
212    // actions from the offending member, which costs search completeness rather than
213    // soundness and so has no business aborting the caller's snapshot.
214    //
215    // [`EGraphConfig::M`]: crate::config::EGraphConfig::M
216    /// A session method received a config whose cycle mode differs from the
217    /// mode the session's search space was created with. The space's cycle
218    /// contexts are derived under one mode; mixing modes would silently
219    /// corrupt cycle filtering.
220    CycleModeMismatch,
221}
222
223impl core::fmt::Display for AuError {
224    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
225        match self {
226            AuError::NoFiniteRepresentative(c) => {
227                write!(f, "class auc{c} has no admissible finite member")
228            }
229            AuError::CycleModeMismatch => write!(
230                f,
231                "config cycle mode differs from the session's search-space mode"
232            ),
233        }
234    }
235}
236
237impl std::error::Error for AuError {}