Skip to main content

semi_persistent_egraph/au/
session.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! SearchSession: the public API for anti-unification (§4.7, §6).
4//!
5//! A session is built from a frozen e-graph, runs Exact or UCT, and returns the
6//! best anti-unifier found.
7
8use crate::canon::{MSetCanon, VarCanon};
9use crate::config::EGraphConfig;
10use crate::literal::LitVal;
11
12use super::actions::{ActionCache, ActionCacheToken};
13use super::egraph_api::{AuSnapshot, ClassOf};
14use super::mcgs::{self, AndSelector, HybridStats, McgsConfig};
15use super::results::{BestResults, BestResultsToken};
16use super::space::{CycleMode, SearchSpace, SpaceToken};
17use super::terms::{TermOp, TermPool, TermPoolToken};
18use crate::config::AuIds;
19
20/// Term id projected from a config's AU family.
21pub type TermOf<Cfg> = <<Cfg as EGraphConfig>::Au as AuIds>::Term;
22
23/// Which algorithm to run.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub enum AuAlgorithm {
26    /// The exact DP solver (§3.2).
27    Exact,
28    /// MCGS with UCT selection (§3.3).
29    #[default]
30    Uct,
31}
32
33/// Configuration for an anti-unification session.
34#[derive(Debug, Clone)]
35pub struct AuConfig {
36    pub algorithm: AuAlgorithm,
37    /// Cycle breaking for every algorithm. The side modes track left and
38    /// right classes independently; [`CycleMode::Pair`] tracks ordered class
39    /// pairs and selects bounded pair relaxation for root Exact.
40    pub cycle_mode: CycleMode,
41    pub playouts: u64,
42    pub exploration_constant: f64,
43    pub x_target: f64,
44    /// Effort allocation at AND nodes (§3.3.5). Default `AndSelector::LctAnd`.
45    pub and_selector: AndSelector,
46    /// Wall-clock budget for the exact solver. `None` (the default) runs to
47    /// completion and returns `Completion::Exact`. `Some(d)` makes exact
48    /// anytime: on expiry it returns the root's best incumbent so far — at
49    /// minimum the generalize seed, always a feasible anti-unifier — with
50    /// `Completion::BudgetExhausted`, never claiming optimality. Ignored by
51    /// the UCT algorithm, whose budget is `playouts`.
52    pub exact_deadline: Option<std::time::Duration>,
53    /// Branch-and-bound in Exact: skip a structural action or AC
54    /// representation pair when its projection lower bound
55    /// (`estimates::lb_pair`) strictly exceeds the pair's achieved incumbent.
56    /// The comparison is size-only and strict because equal size can still
57    /// improve variant mass. Contextual exact calls delegated by UCT also
58    /// tighten this bound with completed children. Default `false`;
59    /// `au_differential.rs::pruned_exact_matches_reference` asserts the
60    /// flag-on qualities equal the unpruned reference. Ignored by UCT
61    /// selection itself.
62    pub exact_pruning: bool,
63    /// Context-subsumption reuse for side-context Exact. Pair-mode root Exact
64    /// already has one state per bare ordered pair, so reuse is inherent
65    /// there. Pair-context hybrid calls currently leave this optimization off
66    /// because their support proof must preserve pair correlations.
67    pub context_subsumption: bool,
68    /// Dominance pruning in the UCT/MCGS solver: at OR-stats creation, drop
69    /// every action whose
70    /// projection lower bound strictly exceeds the node's generalize value —
71    /// the exact value of an always-available alternative — so a dropped
72    /// action can never be optimal at that node, and a node whose every
73    /// action is dropped closes at its generalize value. Shrinks the
74    /// certification budget without touching soundness: the certificate's
75    /// claim becomes "every action was realized or proven non-optimal", the
76    /// same claim exact-side pruning makes. Default `false`: the unpruned
77    /// search is the reference the differential fixture was captured
78    /// against; `au_differential.rs::dominant_pruned_mcgs_is_sound` gates
79    /// the flag-on behavior. Ignored by the exact algorithm.
80    pub dominance_pruning: bool,
81    /// The MCTS-solver closed bit: every OR node carries a bit that is set once
82    /// its subgraph is fully resolved, maintained incrementally through
83    /// reverse edges, and selection descends only into open subtrees. A closed
84    /// subtree's value and stored result are exact and final, so the skipped
85    /// visits could not have changed any answer; the freed playouts go to
86    /// actions that are still unrealized, which is what makes the
87    /// certification budget track the action census on deep search graphs
88    /// instead of growing exponentially in their depth. Certification reads
89    /// the
90    /// root's bit and the run stops as soon as it is set. Every closed node is
91    /// also marked exact in the session's result table, so a later run on the
92    /// same session inherits the proof (that node is terminal at creation) and
93    /// the proof rolls back with `restore`. Default `false`: the
94    /// unrestricted search is the reference the differential fixture was
95    /// captured against; `au_differential.rs::closed_bit_mcgs_is_sound` gates
96    /// the flag-on behavior. Ignored by the exact algorithm.
97    pub closed_bit: bool,
98    /// Hybrid exact subproblems in the UCT/MCGS solver: when a new OR node's
99    /// reachable-pair estimate is
100    /// at or below [`Self::hybrid_threshold`], the exact solver (with
101    /// `exact_pruning` and `context_subsumption` on) solves that node's own
102    /// state (same class pair, same cycle contexts, same cycle mode). Its term
103    /// is offered, and a completed call is marked contextually exact in the
104    /// session's result table.
105    /// Since an exact-marked node is terminal at creation, and terminal nodes
106    /// are born closed, the proof is a closed subtree the search never enters:
107    /// what would have cost `sum A(v)` playouts below that node costs one
108    /// exact call. The admission thresholds estimate workload but do not bound
109    /// descendant contextual states or fan-out; only `hybrid_node_budget`
110    /// hard-bounds one call. Default `false`: the pure playout search is the
111    /// reference the differential fixture was captured against;
112    /// `au_differential.rs::hybrid_exact_mcgs_is_sound` gates the flag-on
113    /// behavior. Ignored by the exact algorithm.
114    pub hybrid_exact: bool,
115    /// Admission estimate for [`Self::hybrid_exact`], in reachable bare class
116    /// pairs (`estimates::reachable_pairs`). This can undercount contextual
117    /// states and is not a hard work bound. The default is a historical
118    /// compatibility value pending a current Criterion calibration.
119    pub hybrid_threshold: u64,
120    /// Live-incumbent arm pruning in the UCT/MCGS solver: every arm carries
121    /// its admissible size
122    /// lower bound, and an arm whose bound STRICTLY exceeds the node's
123    /// current incumbent is excluded from selection and counts as resolved
124    /// toward the certificate ("realized or proven non-optimal", the
125    /// `dominance_pruning` claim evaluated against the live incumbent
126    /// instead of the creation-time generalize value). Strict, size-only:
127    /// an equal-size arm can still win the lexicographic tie on variant
128    /// mass. Requires `closed_bit`; the run refuses the flag without it.
129    /// Default `false`;
130    /// `au_differential.rs::live_incumbent_pruning_is_sound` gates the
131    /// flag-on behavior. Ignored by the exact algorithm.
132    pub live_incumbent_pruning: bool,
133    /// Hybrid exact calls fired from inside the initial rollout: every rollout
134    /// frame whose subproblem passes [`Self::hybrid_exact`]'s admission gate is
135    /// delegated and becomes the completed suffix of that rollout. A completed
136    /// call supplies a contextually certified exact suffix; a call that
137    /// exhausts `hybrid_node_budget` supplies only a feasible uncertified
138    /// suffix. Only completed frames are terminal and certified when expansion
139    /// reaches them. Same soundness argument as
140    /// `hybrid_exact` (same class pair, context, and cycle mode). Requires
141    /// `hybrid_exact`; the run refuses the flag without it. Default `false`;
142    /// `au_differential.rs::rollout_hybrid_mcgs_is_sound` gates the flag-on
143    /// behavior. Ignored by the exact algorithm.
144    pub rollout_hybrid: bool,
145    /// Session-level exact memo:
146    /// side-context hybrid exact calls share one bare-pair memo of
147    /// context-clean solves across the whole session, so calls over overlapping
148    /// subgraphs reuse instead of re-solving (the context-clean entry merely
149    /// outlives the call). Pair-context calls leave it unused until support
150    /// records preserve pair correlations. The memo rolls back with the session token. Requires
151    /// `hybrid_exact`. Default `false`;
152    /// `au_differential.rs::persistent_memo_exact_is_sound` gates the
153    /// flag-on behavior. Ignored by the exact algorithm.
154    pub session_exact_memo: bool,
155    /// Second admission gate for hybrid exact calls: the node's own
156    /// action count must be at or below this. It complements the bare-pair
157    /// rectangle estimate, but neither estimate bounds descendant contextual
158    /// states or fan-out. Default `u64::MAX` (admission by rectangle alone,
159    /// the reference behavior).
160    /// Ignored by the exact algorithm.
161    pub hybrid_action_threshold: u64,
162    /// Deterministic in-call backstop for hybrid exact calls, in
163    /// node entries: on exhaustion the call returns its incumbent
164    /// uncertified (and keeps completed subframes under
165    /// `session_exact_memo`). Default `None`. Ignored by the exact
166    /// algorithm (use `exact_deadline` there).
167    pub hybrid_node_budget: Option<u64>,
168    /// Static child seeding:
169    /// expansion seeds fresh children with their stored best size and the
170    /// full initial rollout runs on a child's first selection instead of at
171    /// expansion, so a k-child expansion stops paying k greedy descents for
172    /// children selection may never enter. Default `false`;
173    /// `au_differential.rs::static_child_seed_mcgs_is_sound` gates the
174    /// flag-on soundness (matched-playout quality may legitimately differ:
175    /// the flag trades estimate quality per playout for cost per playout).
176    /// Ignored by the exact algorithm.
177    pub static_child_seed: bool,
178    /// Interval labels: every arm
179    /// carries a lower bound that TIGHTENS as the search discovers its
180    /// subtree is expensive (`L(and) = 1 + Σ count · L(child)`,
181    /// `L(or) = min over live arms`), instead of freezing at the static
182    /// creation bound. Exclusion then fires on the dynamic bound, which
183    /// dominates `live_incumbent_pruning`'s static one: identical where the
184    /// static bound is tight, decisive where it is loose (subterms with
185    /// equal size profiles, hence equal `lb_pair`, whose anti-unifiers cost
186    /// very differently). Requires `live_incumbent_pruning`. Default
187    /// `false`; `au_differential.rs::interval_bounds_mcgs_is_sound` gates
188    /// the flag-on behavior. Ignored by the exact algorithm.
189    pub interval_bounds: bool,
190}
191
192impl Default for AuConfig {
193    fn default() -> Self {
194        AuConfig {
195            algorithm: AuAlgorithm::Uct,
196            cycle_mode: CycleMode::AncestorOnly,
197            playouts: 1000,
198            exploration_constant: std::f64::consts::SQRT_2,
199            x_target: 0.8,
200            and_selector: AndSelector::default(),
201            exact_deadline: None,
202            exact_pruning: false,
203            context_subsumption: false,
204            dominance_pruning: false,
205            closed_bit: false,
206            hybrid_exact: false,
207            hybrid_threshold: mcgs::DEFAULT_HYBRID_THRESHOLD,
208            live_incumbent_pruning: false,
209            rollout_hybrid: false,
210            session_exact_memo: false,
211            hybrid_action_threshold: u64::MAX,
212            hybrid_node_budget: None,
213            static_child_seed: false,
214            interval_bounds: false,
215        }
216    }
217}
218
219/// Whether the solver structurally completed its declared action space.
220#[derive(Debug, Clone, Copy, PartialEq, Eq)]
221pub enum Completion {
222    /// Every reachable subproblem in the configured action space was solved.
223    /// Pair-mode root Exact covers the finite class-pair graph. Side-mode
224    /// Exact and every UCT mode certify their configured contextual graph. Transport
225    /// representation pairs whose margins exceed the solver's `u32` capacity
226    /// are outside every mode's supported domain.
227    Exact,
228    /// The playout budget expired before the search graph was fully resolved.
229    BudgetExhausted { playouts_used: u64 },
230}
231
232/// The result of an anti-unification run. Configuration-based: the id family,
233/// operator, and value types all project from `Cfg`.
234pub struct AuResult<Cfg: EGraphConfig> {
235    pub term_id: TermOf<Cfg>,
236    pub pool: TermPool<Cfg::O, Cfg::V, Cfg::Au>,
237    pub size: u32,
238    pub algorithm: AuAlgorithm,
239    pub completion: Completion,
240    /// What `AuConfig::hybrid_exact` did during the run; all zeros for the
241    /// exact algorithm and for a UCT run with the flag off.
242    pub hybrid: HybridStats,
243}
244
245/// Width aliases for downstream convenience.
246pub type AuResult31 = AuResult<crate::nodes::DefaultConfig>;
247pub type AuResult63 = AuResult<crate::nodes::Config64>;
248
249impl<Cfg: EGraphConfig> core::fmt::Debug for AuResult<Cfg> {
250    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
251        f.debug_struct("AuResult")
252            .field("term_id", &self.term_id)
253            .field("size", &self.size)
254            .field("algorithm", &self.algorithm)
255            .field("completion", &self.completion)
256            .finish()
257    }
258}
259
260impl<Cfg: EGraphConfig> AuResult<Cfg> {
261    /// Get the operator of the root term.
262    pub fn root_op(&self) -> &TermOp<Cfg::O, Cfg::V> {
263        self.pool.op(self.term_id)
264    }
265
266    /// Get the children of the root term.
267    pub fn root_children(&self) -> &[TermOf<Cfg>] {
268        self.pool.children(self.term_id)
269    }
270
271    /// Render the term as a flat one-line s-expression.
272    pub fn to_string_with<F>(&self, op_name: F) -> String
273    where
274        F: Fn(&TermOp<Cfg::O, Cfg::V>) -> String + Copy,
275    {
276        super::pretty::pretty_print(&self.pool, self.term_id, op_name, usize::MAX)
277    }
278
279    /// Pretty-print the term with indentation, breaking lines that exceed
280    /// `col_limit` characters.
281    pub fn pretty_print_with<F>(&self, op_name: F, col_limit: usize) -> String
282    where
283        F: Fn(&TermOp<Cfg::O, Cfg::V>) -> String + Copy,
284    {
285        super::pretty::pretty_print(&self.pool, self.term_id, op_name, col_limit)
286    }
287}
288
289/// Run anti-unification on a frozen e-graph between two classes.
290///
291/// This is the main entry point. Build a snapshot, pick an algorithm, and get back
292/// the best anti-unifier found.
293pub fn anti_unify<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
294    snap: &AuSnapshot<Cfg, L, T, P>,
295    left: Cfg::G,
296    right: Cfg::G,
297    config: &AuConfig,
298) -> Result<AuResult<Cfg>, super::AuError>
299where
300    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
301{
302    let l = snap
303        .class_of(left)
304        .ok_or(super::AuError::NoFiniteRepresentative(0))?;
305    let r = snap
306        .class_of(right)
307        .ok_or(super::AuError::NoFiniteRepresentative(0))?;
308
309    match config.algorithm {
310        AuAlgorithm::Exact => {
311            let (term, pool, complete) = if config.cycle_mode == CycleMode::Pair {
312                let (run, pool) = super::exact_fixed::run(
313                    snap,
314                    l,
315                    r,
316                    config.exact_deadline,
317                    config.exact_pruning,
318                )?;
319                (run.term, pool, run.complete)
320            } else {
321                let run = super::exact::run_exact(
322                    snap,
323                    l,
324                    r,
325                    config.cycle_mode,
326                    config.exact_deadline,
327                    config.exact_pruning,
328                    config.context_subsumption,
329                )?;
330                (run.term, run.pool, run.complete)
331            };
332            let size = pool.size(term);
333            // A deadline expiry surfaces the root incumbent uncertified:
334            // feasible by construction, optimal only on completion. The
335            // budget the exact solver exhausts is wall clock, not playouts.
336            let completion = if complete {
337                Completion::Exact
338            } else {
339                Completion::BudgetExhausted { playouts_used: 0 }
340            };
341            Ok(AuResult {
342                term_id: term,
343                pool,
344                size,
345                algorithm: AuAlgorithm::Exact,
346                completion,
347                hybrid: HybridStats::default(),
348            })
349        }
350        AuAlgorithm::Uct => {
351            let mcgs_config = McgsConfig {
352                playouts: config.playouts,
353                cycle_mode: config.cycle_mode,
354                exploration_constant: config.exploration_constant,
355                x_target: config.x_target,
356                and_selector: config.and_selector,
357                dominance_pruning: config.dominance_pruning,
358                closed_bit: config.closed_bit,
359                hybrid_exact: config.hybrid_exact,
360                live_incumbent_pruning: config.live_incumbent_pruning,
361                rollout_hybrid: config.rollout_hybrid,
362                session_exact_memo: config.session_exact_memo,
363                hybrid_action_threshold: config.hybrid_action_threshold,
364                hybrid_node_budget: config.hybrid_node_budget,
365                static_child_seed: config.static_child_seed,
366                interval_bounds: config.interval_bounds,
367                hybrid_threshold: config.hybrid_threshold,
368            };
369            let (term_id, pool, completion, hybrid) = mcgs::run_mcgs(snap, l, r, &mcgs_config)?;
370            let size = pool.size(term_id);
371            Ok(AuResult {
372                term_id,
373                pool,
374                size,
375                algorithm: AuAlgorithm::Uct,
376                completion,
377                hybrid,
378            })
379        }
380    }
381}
382
383/// Compute the linear compression ratio (§2.5):
384/// `(size(t) - min(best_l, best_r)) / max(best_l, best_r)`
385pub fn compression_ratio<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
386    snap: &AuSnapshot<Cfg, L, T, P>,
387    left: ClassOf<Cfg>,
388    right: ClassOf<Cfg>,
389    au_size: u32,
390) -> f64
391where
392    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
393{
394    let best_l = snap.best_size(left) as f64;
395    let best_r = snap.best_size(right) as f64;
396    let min_size = best_l.min(best_r);
397    let max_size = best_l.max(best_r);
398    if max_size == 0.0 {
399        return 0.0;
400    }
401    (au_size as f64 - min_size) / max_size
402}
403
404// ---------------------------------------------------------------------------
405// SearchSession: the semi-persistent owner of all search state (§4.7)
406// ---------------------------------------------------------------------------
407
408/// Opaque token capturing the entire search state at one point in time.
409/// Created by `SearchSession::mark()`; consumed by `SearchSession::restore()`.
410/// Component tokens are private; callers cannot restore individual layers.
411#[derive(Debug)]
412pub struct SearchToken {
413    space: SpaceToken,
414    terms: TermPoolToken,
415    results: BestResultsToken,
416    actions: ActionCacheToken,
417    mcgs: super::mcgs::McgsToken,
418}
419
420/// A search session owns the search-space layer, term pool, best-result table,
421/// action cache, and the MCGS statistics overlay. It provides one coherent
422/// `mark()`/`restore(token)` that snapshots and rolls back all layers together.
423/// The e-graph snapshot is borrowed immutably for the session's lifetime; later
424/// e-graph mutations are not observed (§4.1).
425pub struct SearchSession<'eg, Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>
426where
427    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
428{
429    pub(crate) snap: &'eg AuSnapshot<'eg, Cfg, L, T, P>,
430    pub(crate) space: SearchSpace<Cfg::Au>,
431    pub(crate) pool: TermPool<Cfg::O, Cfg::V, Cfg::Au>,
432    pub(crate) results: BestResults<Cfg::Au>,
433    pub(crate) action_cache: ActionCache<Cfg::O, Cfg::Au, Cfg::M>,
434    pub(crate) mcgs: super::mcgs::McgsState<Cfg::Au, Cfg::O>,
435}
436
437impl<'eg, Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>
438    SearchSession<'eg, Cfg, L, T, P>
439where
440    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
441{
442    /// Create a new session from a snapshot. The snapshot must outlive the session.
443    pub fn new(snap: &'eg AuSnapshot<'eg, Cfg, L, T, P>, cycle_mode: CycleMode) -> Self {
444        SearchSession {
445            snap,
446            space: SearchSpace::new(cycle_mode),
447            pool: TermPool::new(),
448            results: BestResults::new(),
449            // MCGS uses transport-AND-nodes for AC/ACI (no matrix actions).
450            action_cache: ActionCache::without_ac_actions(usize::MAX),
451            mcgs: super::mcgs::McgsState::new(),
452        }
453    }
454
455    /// Snapshot the entire search state. Returns one opaque token; component
456    /// tokens are not accessible. Layers are marked in dependency order.
457    pub fn mark(&mut self) -> SearchToken {
458        SearchToken {
459            space: self.space.mark(),
460            terms: self.pool.mark(),
461            results: self.results.mark(),
462            actions: self.action_cache.mark(),
463            mcgs: self.mcgs.mark(),
464        }
465    }
466
467    /// Restore the entire search state to a previous mark. Two-phase: every
468    /// component token is validated against its container and branch genealogy
469    /// BEFORE any layer is mutated, so a foreign or abandoned token cannot
470    /// cause a partial restore. Then restores in reverse dependency order
471    /// (statistics first, then results/terms, then structure).
472    pub fn restore(&mut self, token: SearchToken) {
473        // Phase 1: validate all (no mutation). If any check fails the panic
474        // leaves all layers intact.
475        assert!(
476            self.mcgs.is_valid_token(&token.mcgs),
477            "SearchSession: mcgs token is invalid (foreign or abandoned)"
478        );
479        assert!(
480            self.action_cache.is_valid_token(&token.actions),
481            "SearchSession: action_cache token is invalid (foreign or abandoned)"
482        );
483        assert!(
484            self.results.is_valid_token(&token.results),
485            "SearchSession: results token is invalid (foreign or abandoned)"
486        );
487        assert!(
488            self.pool.is_valid_token(&token.terms),
489            "SearchSession: term pool token is invalid (foreign or abandoned)"
490        );
491        assert!(
492            self.space.is_valid_token(&token.space),
493            "SearchSession: space token is invalid (foreign or abandoned)"
494        );
495        // Phase 2: restore all (all validated, cannot fail).
496        self.mcgs.restore(token.mcgs);
497        self.action_cache.restore(token.actions);
498        self.results.restore(token.results);
499        self.pool.restore(token.terms);
500        self.space.restore(token.space);
501    }
502
503    /// Exact solve of the root pair on this session's persistent layers:
504    /// terms intern into the session pool, and the solve warm-starts from the
505    /// session's stored incumbent for the pair. The session's cycle mode
506    /// chooses side-context Exact or ordered-pair fixed-point Exact.
507    /// `deadline` makes the solve anytime.
508    pub fn run_exact_warm(
509        &mut self,
510        left: Cfg::G,
511        right: Cfg::G,
512        pruning: bool,
513        subsumption: bool,
514        deadline: Option<std::time::Duration>,
515    ) -> Result<(TermOf<Cfg>, Completion), super::AuError> {
516        let l = self
517            .snap
518            .class_of(left)
519            .ok_or(super::AuError::NoFiniteRepresentative(0))?;
520        let r = self
521            .snap
522            .class_of(right)
523            .ok_or(super::AuError::NoFiniteRepresentative(0))?;
524        self.snap.validate_finite_from(l)?;
525        self.snap.validate_finite_from(r)?;
526        let (empty_l, empty_r) = self.space.empty_contexts();
527        let (root_or, _) = self.space.get_or_insert_or_node(
528            l,
529            r,
530            empty_l,
531            empty_r,
532            self.snap.best_size(l),
533            self.snap.best_size(r),
534        );
535        self.results.ensure_capacity(root_or);
536        if self.space.cycle_mode != CycleMode::Pair {
537            if self.results.is_exact(root_or) {
538                let term = self
539                    .results
540                    .best_term(root_or)
541                    .expect("an exact result has an achieved term");
542                return Ok((term, Completion::Exact));
543            }
544            let context = self.space.cycle_context(root_or);
545            let warm = self.results.best_term(root_or);
546            let run = super::exact::run_exact_at(
547                self.snap,
548                &mut self.pool,
549                l,
550                r,
551                &context,
552                self.space.cycle_mode,
553                deadline,
554                pruning,
555                subsumption,
556                Some(self.mcgs.exact_memo_mut()),
557                None,
558                warm,
559            );
560            self.results
561                .offer(root_or, run.term, self.pool.quality(run.term));
562            if run.complete {
563                self.results.mark_exact(root_or);
564            }
565            let completion = if run.complete {
566                Completion::Exact
567            } else {
568                Completion::BudgetExhausted { playouts_used: 0 }
569            };
570            return Ok((run.term, completion));
571        }
572        if self.results.is_global_exact(root_or) {
573            let term = self
574                .results
575                .best_global_term(root_or)
576                .expect("a globally exact result has an achieved term");
577            return Ok((term, Completion::Exact));
578        }
579        let contextual = self.results.best_term(root_or);
580        let global = self.results.best_global_term(root_or);
581        let warm = match (contextual, global) {
582            (Some(contextual), Some(global)) => {
583                if self.results.best_global_quality(root_or) < self.results.best_quality(root_or) {
584                    Some(global)
585                } else {
586                    Some(contextual)
587                }
588            }
589            (contextual @ Some(_), None) => contextual,
590            (None, global @ Some(_)) => global,
591            (None, None) => None,
592        };
593        let run =
594            super::exact_fixed::run_in(self.snap, &mut self.pool, l, r, deadline, pruning, warm)?;
595        self.results
596            .offer_global(root_or, run.term, self.pool.quality(run.term));
597        if run.complete {
598            self.results.mark_global_exact(root_or);
599        }
600        let completion = if run.complete {
601            Completion::Exact
602        } else {
603            Completion::BudgetExhausted { playouts_used: 0 }
604        };
605        Ok((run.term, completion))
606    }
607
608    /// Run MCGS on this session's persistent layers. Statistics, search space,
609    /// terms, and results accumulate across calls and roll back with
610    /// `restore(token)`.
611    ///
612    /// Errors with `AuError::CycleModeMismatch` if `config.cycle_mode` differs
613    /// from the mode this session's search space was created with: cycle
614    /// contexts already interned under one mode cannot be reused under the
615    /// other, and silently ignoring the requested mode would be worse.
616    pub fn run_uct(
617        &mut self,
618        left: Cfg::G,
619        right: Cfg::G,
620        config: &McgsConfig,
621    ) -> Result<(TermOf<Cfg>, Completion), super::AuError> {
622        if config.cycle_mode != self.space.cycle_mode {
623            return Err(super::AuError::CycleModeMismatch);
624        }
625        let l = self
626            .snap
627            .class_of(left)
628            .ok_or(super::AuError::NoFiniteRepresentative(0))?;
629        let r = self
630            .snap
631            .class_of(right)
632            .ok_or(super::AuError::NoFiniteRepresentative(0))?;
633        mcgs::run_mcgs_in(
634            self.snap,
635            &mut self.space,
636            &mut self.pool,
637            &mut self.action_cache,
638            &mut self.results,
639            &mut self.mcgs,
640            l,
641            r,
642            config,
643        )
644    }
645
646    /// What `McgsConfig::hybrid_exact` did, cumulative over every `run_uct`
647    /// call on this session.
648    pub fn hybrid_stats(&self) -> HybridStats {
649        self.mcgs.hybrid_stats()
650    }
651
652    /// The lexicographic quality of a term in this session's pool.
653    pub fn pool_quality(&self, term: TermOf<Cfg>) -> (u32, u32) {
654        self.pool.quality(term)
655    }
656
657    /// The snapshot this session was built from.
658    pub fn snapshot(&self) -> &AuSnapshot<'eg, Cfg, L, T, P> {
659        self.snap
660    }
661}
662
663#[cfg(test)]
664mod tests {
665    use super::*;
666    use crate::au::egraph_api::AuSnapshot;
667    use crate::au::terms::TermId;
668    use crate::containers::DenseId;
669    use crate::egraph::EGraph31;
670    use crate::literal::NiraLitVal;
671
672    /// run_uct must reject a config whose cycle mode differs from the mode
673    /// the session's search space was created with, instead of silently
674    /// ignoring the requested mode.
675    #[test]
676    fn run_uct_rejects_cycle_mode_mismatch() {
677        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
678        let sort = eg.intern_sort("E");
679        let a_op = eg.register_op0("a", sort);
680        let b_op = eg.register_op0("b", sort);
681        let a = eg.add(a_op, &[]);
682        let b = eg.add(b_op, &[]);
683        eg.rebuild();
684
685        let snap = AuSnapshot::new(&eg).unwrap();
686        let mut session = SearchSession::new(&snap, CycleMode::AncestorOnly);
687        let config = McgsConfig {
688            cycle_mode: CycleMode::CurrentInclusive,
689            playouts: 1,
690            ..Default::default()
691        };
692        let err = session
693            .run_uct(a, b, &config)
694            .expect_err("mismatched cycle mode must be rejected");
695        assert_eq!(err, crate::au::AuError::CycleModeMismatch);
696    }
697
698    #[test]
699    fn default_algorithm_is_uct() {
700        assert_eq!(AuAlgorithm::default(), AuAlgorithm::Uct);
701        assert_eq!(AuConfig::default().algorithm, AuAlgorithm::Uct);
702    }
703
704    #[test]
705    fn session_exact() {
706        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
707        let int = eg.intern_sort("Int");
708        let a_op = eg.register_op0("a", int);
709        let b_op = eg.register_op0("b", int);
710        let c_op = eg.register_op0("c", int);
711        let f_op = eg.register_op2("f", int, int, int);
712
713        let a = eg.add(a_op, &[]);
714        let b = eg.add(b_op, &[]);
715        let c = eg.add(c_op, &[]);
716        let fab = eg.add(f_op, &[a, b]);
717        let fac = eg.add(f_op, &[a, c]);
718        eg.rebuild();
719
720        let snap = AuSnapshot::new(&eg).unwrap();
721        let config = AuConfig {
722            algorithm: AuAlgorithm::Exact,
723            ..Default::default()
724        };
725        let result = anti_unify(&snap, fab, fac, &config).unwrap();
726        assert_eq!(result.size, 4);
727    }
728
729    #[test]
730    fn session_uct_matches_exact() {
731        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
732        let int = eg.intern_sort("Int");
733        let a_op = eg.register_op0("a", int);
734        let b_op = eg.register_op0("b", int);
735        let c_op = eg.register_op0("c", int);
736        let f_op = eg.register_op2("f", int, int, int);
737
738        let a = eg.add(a_op, &[]);
739        let b = eg.add(b_op, &[]);
740        let c = eg.add(c_op, &[]);
741        let fab = eg.add(f_op, &[a, b]);
742        let fac = eg.add(f_op, &[a, c]);
743        eg.rebuild();
744
745        let snap = AuSnapshot::new(&eg).unwrap();
746
747        let exact_config = AuConfig {
748            algorithm: AuAlgorithm::Exact,
749            ..Default::default()
750        };
751        let exact_result = anti_unify(&snap, fab, fac, &exact_config).unwrap();
752
753        let uct_config = AuConfig {
754            algorithm: AuAlgorithm::Uct,
755            playouts: 500,
756            ..Default::default()
757        };
758        let uct_result = anti_unify(&snap, fab, fac, &uct_config).unwrap();
759
760        assert_eq!(uct_result.completion, Completion::Exact);
761        assert_eq!(
762            uct_result.pool.quality(uct_result.term_id),
763            exact_result.pool.quality(exact_result.term_id)
764        );
765    }
766
767    /// A session uses the same cycle policy for UCT and warm Exact. Side mode
768    /// writes a contextual certificate; pair mode additionally writes the
769    /// cycle-global certificate produced by bounded pair relaxation.
770    #[test]
771    fn warm_exact_honors_the_session_cycle_mode() {
772        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
773        let sort = eg.intern_sort("E");
774        let a_op = eg.register_op0("a", sort);
775        let f = eg.register_op1("f", sort, sort);
776        let h = eg.register_op2("h", sort, sort, sort);
777
778        let c0 = eg.add(a_op, &[]);
779        let c3 = eg.add(f, &[c0]);
780        let c1 = eg.add(h, &[c3, c3]);
781        let c2 = eg.add(h, &[c0, c1]);
782        let c3_h = eg.add(h, &[c0, c3]);
783        eg.merge(c3, c3_h);
784        eg.rebuild();
785
786        let snap = AuSnapshot::new(&eg).unwrap();
787        let l = snap.class_of(c2).unwrap();
788        let r = snap.class_of(c3).unwrap();
789        for (cycle_mode, expected) in [
790            (CycleMode::AncestorOnly, (9, 7)),
791            (CycleMode::CurrentInclusive, (9, 9)),
792            (CycleMode::Pair, (8, 3)),
793        ] {
794            let mut session = SearchSession::new(&snap, cycle_mode);
795            let config = McgsConfig {
796                playouts: 10_000,
797                cycle_mode,
798                closed_bit: true,
799                ..Default::default()
800            };
801
802            let (uct, uct_completion) = session.run_uct(c2, c3, &config).unwrap();
803            assert_eq!(uct_completion, Completion::Exact);
804            assert_eq!(session.pool_quality(uct), expected);
805
806            let (exact, exact_completion) =
807                session.run_exact_warm(c2, c3, false, false, None).unwrap();
808            assert_eq!(exact_completion, Completion::Exact);
809            assert_eq!(session.pool_quality(exact), expected);
810
811            let (empty_l, empty_r) = session.space.empty_contexts();
812            let (root_or, _) = session.space.get_or_insert_or_node(
813                l,
814                r,
815                empty_l,
816                empty_r,
817                snap.best_size(l),
818                snap.best_size(r),
819            );
820            assert!(session.results.is_exact(root_or));
821            assert_eq!(
822                session.results.is_global_exact(root_or),
823                cycle_mode == CycleMode::Pair
824            );
825        }
826    }
827
828    #[test]
829    fn session_identical_returns_size_1() {
830        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
831        let int = eg.intern_sort("Int");
832        let a_op = eg.register_op0("a", int);
833        let a = eg.add(a_op, &[]);
834        eg.rebuild();
835
836        let snap = AuSnapshot::new(&eg).unwrap();
837
838        for alg in [AuAlgorithm::Exact, AuAlgorithm::Uct] {
839            let config = AuConfig {
840                algorithm: alg,
841                playouts: 10,
842                ..Default::default()
843            };
844            let result = anti_unify(&snap, a, a, &config).unwrap();
845            assert_eq!(result.size, 1, "algorithm {:?} failed", alg);
846        }
847    }
848
849    /// Gate: for both public algorithms, both projections of the result must contain
850    /// no Variants and match a term of the source class (validity oracle, §2.7).
851    #[test]
852    fn projections_are_variant_free_all_algorithms() {
853        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
854        let int = eg.intern_sort("Int");
855        let a_op = eg.register_op0("a", int);
856        let b_op = eg.register_op0("b", int);
857        let c_op = eg.register_op0("c", int);
858        let f_op = eg.register_op2("f", int, int, int);
859        let and_op = eg.register_set("and", int, int);
860
861        let a = eg.add(a_op, &[]);
862        let b = eg.add(b_op, &[]);
863        let c = eg.add(c_op, &[]);
864        let fab = eg.add(f_op, &[a, b]);
865        let fcb = eg.add(f_op, &[c, b]);
866        let left = eg.add(and_op, &[fab, a]);
867        let right = eg.add(and_op, &[fcb, c]);
868        eg.rebuild();
869
870        let snap = AuSnapshot::new(&eg).unwrap();
871
872        for alg in [AuAlgorithm::Exact, AuAlgorithm::Uct] {
873            let config = AuConfig {
874                algorithm: alg,
875                playouts: 200,
876                ..Default::default()
877            };
878            let mut result = anti_unify(&snap, left, right, &config).unwrap();
879            let l_proj = result.pool.project(result.term_id, 0);
880            let r_proj = result.pool.project(result.term_id, 1);
881            assert!(
882                !result.pool.has_variants(l_proj),
883                "{alg:?}: left projection still has Variants"
884            );
885            assert!(
886                !result.pool.has_variants(r_proj),
887                "{alg:?}: right projection still has Variants"
888            );
889        }
890    }
891
892    /// Gate: the exact solver must not truncate AC matrix enumeration. With 5
893    /// distinct children per side there are 5! = 120 bijections (> the MCGS
894    /// A_max of 32); the optimum pairs the 4 shared children diagonally.
895    #[test]
896    fn exact_large_ac_not_truncated() {
897        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
898        let int = eg.intern_sort("Int");
899        let ops: Vec<_> = (0..6)
900            .map(|i| eg.register_op0(&format!("k{i}"), int))
901            .collect();
902        let and_op = eg.register_set("and", int, int);
903
904        let ks: Vec<_> = ops.iter().map(|&o| eg.add(o, &[])).collect();
905        // left = {k0..k4}, right = {k1..k5}: 4 shared children.
906        let left = eg.add(and_op, &[ks[0], ks[1], ks[2], ks[3], ks[4]]);
907        let right = eg.add(and_op, &[ks[1], ks[2], ks[3], ks[4], ks[5]]);
908        eg.rebuild();
909
910        let snap = AuSnapshot::new(&eg).unwrap();
911        let config = AuConfig {
912            algorithm: AuAlgorithm::Exact,
913            ..Default::default()
914        };
915        let result = anti_unify(&snap, left, right, &config).unwrap();
916        // and(k1, k2, k3, k4, Variants(k0, k5)): 1 + 4 + 0 + 1 + 1 = 7.
917        assert_eq!(result.size, 7);
918    }
919
920    #[test]
921    fn compression_ratio_basic() {
922        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
923        let int = eg.intern_sort("Int");
924        let a_op = eg.register_op0("a", int);
925        let b_op = eg.register_op0("b", int);
926        let a = eg.add(a_op, &[]);
927        let b = eg.add(b_op, &[]);
928        eg.rebuild();
929
930        let snap = AuSnapshot::new(&eg).unwrap();
931        let ac = snap.class_of(a).unwrap();
932        let bc = snap.class_of(b).unwrap();
933
934        // AU(a,b) = Variants(a,b), size 2. Both inputs are size 1.
935        // cr = (2 - 1) / 1 = 1.0
936        let cr = compression_ratio(&snap, ac, bc, 2);
937        assert!((cr - 1.0).abs() < 1e-10);
938    }
939
940    #[test]
941    fn search_session_mark_restore() {
942        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
943        let int = eg.intern_sort("Int");
944        let a_op = eg.register_op0("a", int);
945        let b_op = eg.register_op0("b", int);
946        let c_op = eg.register_op0("c", int);
947        let f_op = eg.register_op2("f", int, int, int);
948
949        let a = eg.add(a_op, &[]);
950        let b = eg.add(b_op, &[]);
951        let c = eg.add(c_op, &[]);
952        let fab = eg.add(f_op, &[a, b]);
953        let fac = eg.add(f_op, &[a, c]);
954        eg.rebuild();
955
956        let snap = AuSnapshot::new(&eg).unwrap();
957        let mut session = SearchSession::new(&snap, CycleMode::AncestorOnly);
958
959        // Mark with empty state.
960        let token = session.mark();
961
962        // Do some work: insert an OR node and a term.
963        let lc = snap.class_of(fab).unwrap();
964        let rc = snap.class_of(fac).unwrap();
965        let ctx = session.space.contexts.empty();
966        let (or_id, _) = session.space.get_or_insert_or_node(
967            lc,
968            rc,
969            ctx,
970            ctx,
971            snap.best_size(lc),
972            snap.best_size(rc),
973        );
974        assert_eq!(session.space.or_arena.len(), 1);
975        assert_eq!(session.pool.len(), 0);
976
977        // Intern a term.
978        let term = session.pool.intern(TermOp::EGraph(a_op), &[]);
979        assert_eq!(session.pool.len(), 1);
980        assert!(
981            session
982                .results
983                .offer_global(or_id, term, session.pool.quality(term))
984        );
985        session.results.mark_global_exact(or_id);
986        assert_eq!(session.results.best_global_term(or_id), Some(term));
987        assert!(session.results.is_global_exact(or_id));
988
989        // Restore: all state rolled back to empty.
990        session.restore(token);
991        assert_eq!(session.space.or_arena.len(), 0);
992        assert_eq!(session.pool.len(), 0);
993        assert_eq!(session.results.best_global_term(or_id), None);
994        assert!(!session.results.is_global_exact(or_id));
995    }
996
997    #[test]
998    fn search_session_rejects_abandoned_token_atomically() {
999        use crate::au::space::OrId;
1000
1001        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1002        let sort = eg.intern_sort("E");
1003        let a_op = eg.register_op0("a", sort);
1004        let b_op = eg.register_op0("b", sort);
1005        let a = eg.add(a_op, &[]);
1006        let b = eg.add(b_op, &[]);
1007        eg.rebuild();
1008
1009        let snap = AuSnapshot::new(&eg).unwrap();
1010        let mut session = SearchSession::new(&snap, CycleMode::AncestorOnly);
1011        let ac = snap.class_of(a).unwrap();
1012        let bc = snap.class_of(b).unwrap();
1013        let or0 = OrId::from_usize(0);
1014        let or1 = OrId::from_usize(1);
1015        let t0 = TermId::from_usize(0);
1016        let t1 = TermId::from_usize(1);
1017
1018        let outer = session.mark();
1019        session.action_cache.insert(ac, ac, Vec::new());
1020        session.results.offer(or0, t0, (2, 2));
1021        let abandoned = session.mark();
1022        session.action_cache.insert(bc, bc, Vec::new());
1023        session.results.offer(or1, t1, (1, 1));
1024
1025        // Returning to the outer frame abandons the inner token's history.
1026        session.restore(outer);
1027
1028        // Establish a distinct current branch whose state must survive rejection.
1029        session.action_cache.insert(ac, ac, Vec::new());
1030        session.action_cache.insert(bc, bc, Vec::new());
1031        session.results.offer(or0, t0, (2, 2));
1032        session.results.offer(or1, t1, (1, 1));
1033
1034        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1035            session.restore(abandoned);
1036        }));
1037        assert!(outcome.is_err(), "an abandoned token must be rejected");
1038        assert!(
1039            session.action_cache.get(bc, bc).is_some(),
1040            "failed validation must not truncate the current action-cache branch"
1041        );
1042        assert_eq!(
1043            session.results.best_term(or1),
1044            Some(t1),
1045            "failed validation must not truncate current best results"
1046        );
1047    }
1048}