---
title: Relational Equality Saturation Techniques
url: https://www.emergentmind.com/topics/relational-equality-saturation
type: topic
---

# Relational Equality Saturation Techniques

Relational equality saturation is a family of program-optimization and reasoning techniques in which equality saturation is formulated over explicit relations rather than only over a single global congruence on expressions. In the classical formulation, optimizations take the form of equality analyses that add equality information to a common intermediate representation, and once the representation is saturated a profitability heuristic selects a final program [1012.1802]. Later work recast this process as a least-fixed-point computation over relational structures, unified it with Datalog-style fixpoint evaluation, embedded congruence closure in relational engines, and extended the approach to contexts, control flow, side effects, and relational algebra representations [2304.04332] [2501.02413] [2507.11897] [2002.07951] [2502.17075]. Across these formulations, rewrites add equalities monotonically, multiple equivalent programs are preserved non-destructively, and extraction is delayed until a cost model or query selects a representative [1012.1802].

## 1. From classical equality saturation to relational formulations

The point of departure is the 2010 formulation of equality saturation as an alternative to sequential compiler optimization passes. Instead of destructively rewriting a program and passing the result to the next optimization, optimizations are expressed as equality analyses that add equality information to a shared representation; the optimizer repeatedly applies these analyses to infer equivalences between program fragments, thus saturating the representation with equalities, and then a profitability heuristic picks the final optimized program [1012.1802]. The immediate consequence is that optimization ordering is no longer the central control mechanism, because the representation encodes multiple optimized versions of the input program simultaneously [1012.1802].

A relational reading of this idea appears already in the formal presentation of equality saturation as a computation over an equality relation \(R \subseteq N \times N\), where \(N\) is the set of nodes in the program expression graph. In that presentation, an e-graph is the relational structure \((N, R, \{\mathrm{congr}_f\}_f)\), equality analyses are inference rules that grow \(R\), and saturation computes a least fixed point \(R_\infty\) [1012.1802]. This move from “a data structure for rewrites” to “a relational structure closed under inference” is the conceptual bridge to later systems.

Later literature uses the phrase “relational equality saturation” in more than one precise sense. In one sense, it denotes an EqSat engine in which both the e-graph and rewrite rules are encoded in a Datalog-like language, so that congruence closure, matching, and derived equalities become database facts and rules [2507.11897]. In another sense, it denotes the use of explicitly relational target languages, as in the translation of linear-algebra expressions into relational-algebra expressions before saturation [2002.07951]. In a further sense, it denotes EqSat over richer program relations such as types, control-flow dominance, and side-effect structure, rather than over pure expression forests alone [2502.17075]. This suggests that “relational” names a generalization of EqSat in which equality is indexed, constrained, or mediated by additional relations.

## 2. Relational semantics, fixpoints, and the chase

A rigorous semantic account treats equality saturation as a least-fixed-point construction. One line of work defines an E-graph as a reachable, deterministic bottom-up tree automaton \(G=(Q,\Sigma,\Delta)\), identifies states \(Q\) with E-classes and transitions \(\Delta\) with E-nodes, and lets \(G\) induce a partial congruence relation \(\approx_G\) on ground terms by acceptance into the same state [2501.02413]. Rewriting is formalized by a Match/Apply operator \(T_\mathcal{R}\) that inserts right-hand sides for all rule matches, followed by rebuilding \(CC\) to restore determinism and congruence, yielding the immediate consequence operator
\[
ICO(G)=CC\bigl(T_\mathcal{R}(G)\bigr).
\]
Equality saturation is then
\[
EqSat(\mathcal{R},G)=\bigsqcup_{i\ge 0} ICO^i(G),
\]
the least fixpoint of \(ICO\) [2501.02413].

A closely related formulation casts saturation directly as monotone growth of an equality relation. Given a finite set \(A\) of analyses, one starts from an initial relation \(R_0\) and defines
\[
R_{i+1}=R_i \cup \{(u,v)\mid \exists r\in A.\ \text{all premises of }r \subseteq R_i\},
\]
stopping when \(R_{i+1}=R_i\); the limit \(R_\infty\) is the least fixed point [1012.1802]. In this form, equality saturation is recognizably a fixpoint engine over relations, with e-graph operations serving as an efficient implementation of congruence closure.

The semantic-foundations literature then connects EqSat to the chase. It shows a translation from TGDs and EGDs to a signature \(\Sigma\), a TRS \(\mathcal{R}\), and an initial term \(t\) such that \(EqSat(\mathcal{R},t)\) corresponds to the Skolem chase, both in result and in termination behavior; conversely, an E-graph can be encoded as a relational instance \(\xi(G)\), rewrite rules can be converted into TGDs and EGDs plus functional dependencies for congruence closure, and EqSat termination is equivalent to termination of suitable EGD-fair chase sequences [2501.02413]. This places relational equality saturation within the same semantic landscape as dependency-driven database reasoning.

The same work gives termination classifications. Single-instance termination, \(\mathcal{T}^{EqSat}_G\), is r.e.-complete; all-term-instance termination, \(\mathcal{T}^{EqSat}_{\forall t}\), is \(\Pi_2\)-complete; and all-E-graph-instance termination, \(\mathcal{T}^{EqSat}_{\forall G}\), is undecidable [2501.02413]. As a syntactic sufficient condition, weak term acyclicity is defined on a dependency graph of term positions, and if a rewrite system is weakly term acyclic then equality saturation terminates for every finite initial E-graph in a polynomial number of \(ICO\) iterations [2501.02413]. The significance is that relational EqSat inherits the expressive power of chase-like fixpoint reasoning, but also its delicate termination landscape.

## 3. Context, types, control flow, and effects

One of the clearest relational extensions introduces a ternary relation
\[
eq(c,a,b),
\]
read as “in context \(c\), term \(a\) is congruent to term \(b\)” [2507.11897]. Classical, context-insensitive EqSat is recovered by a single distinguished context \(c_0\), while contextual EqSat uses a finite meet-semilattice \((C,\sqcap,\sqcup,\bot)\) and a monotonic mapping \(\phi:C \to Equiv(T(\Sigma))\) so that higher contexts impose at least as many equalities as lower ones [2507.11897]. Rewrite rules become contextual facts \(crewrite(c_1,c_2,L,R)\), and matching is refined to \(match\_in\_context\), with context propagated top-down by a \(push(c,f,i)\) function satisfying \(c \sqsubseteq c'\) [2507.11897]. The relational gain is that validity can depend on where a term appears.

A distinct but related usage appears in optimization of high-level Julia IR. There, the “relational” character comes from tracking and exploiting three orthogonal relations: type relations via an E-class analysis \(\tau(c)\), control-flow relations via a separate CFG skeleton \(S\) and the dominator relation \(d(i)\), and side-effect relations via classification of operations as pure or effectful [2502.17075]. Rewrite rules may constrain pattern variables by Julia argument types, including \(Comptime\{T\}\) for literal matching, and `unsafe` rules may remove side-effecting calls from the CFG skeleton through “CFG skeleton relaxation” [2502.17075]. This extends equality saturation beyond pure ASTs to a setting in which equalities hold only under joint constraints of type, flow, and effect.

A further extension targets arbitrary control-flow graphs through the E-Path data structure. Instead of taking individual expressions as the unit of congruence, E-Path takes instruction sequences embedded within a compiler intermediate representation, defines equivalence \( \equiv \subseteq Seq \times Seq \) as the reflexive-symmetric-transitive closure of sound rewrite-generated pairs, and stores a monotonic set \(P\) of equivalent E-Sequences [2605.28694]. Each rewrite adds a new sequence; no sequence is deleted or overwritten [2605.28694]. The result is equality-saturation-style optimization over CFGs without first normalizing the program into a tree-like form.

These developments indicate that relational equality saturation is not confined to one architecture. It can mean “EqSat executed by a relational engine,” but it can also mean “EqSat indexed by a lattice of contexts,” “EqSat constrained by type/flow/effect relations,” or “EqSat lifted from terms to control-flow sequences.” This suggests a common theme: congruence is no longer treated as a single unconditional equivalence, but as a relation governed by additional structure.

## 4. Engines, matching, and extraction

The most explicit unification of Datalog and EqSat is "Better Together: Unifying Datalog and Equality Saturation" [2304.04332]. An egglog instance is \(I=(DB,\equiv)\), where \(DB\) is a finite set of entries of the form \(f(v_1,\dots,v_k)\mapsto v\) and \(\equiv\) is an equivalence relation on uninterpreted ids and interpreted constants; evaluation alternates between a rule operator \(T_P\) and a rebuild operator \(R^\infty\), giving
\[
I_{i+1}=R^\infty(T_P(I_i)),
\]
and the overall fixpoint is \((R^\infty \circ T_P)^\infty(I_0)\) [2304.04332]. The implementation uses a functional database backed by hash maps, union-find over uninterpreted ids, hash-consed E-nodes keyed by function and child-class ids, lattice-valued functions with merge expressions, and a unified agenda comprising a relational incremental frontier \(\Delta DB\) and a queue of pending merges [2304.04332]. Semi-naïve evaluation is used to avoid re-firing rules over facts that have already been used [2304.04332].

The contextual-relational formulation of egglog makes the same design visible through database vocabulary. E-classes are identified by ids \(e\), E-nodes are stored as \(enode(f,[c_1,\dots,c_n],e)\), contextual occurrence is tracked by \(ctx(e,c)\), and relational E-matching is implemented as conjunctive queries over \(enode\) and \(eq\) [2507.11897]. The stated benefit is worst-case optimality by leveraging triangle-join and DB-style query planning techniques [2507.11897]. The least fixpoint arises from a monotonic Datalog program whose extensional facts are base E-nodes and contextual rewrite facts, and whose derived facts are context propagation and congruence closure [2507.11897].

Classical extraction is also expressed relationally. In the original EqSat presentation, extraction introduces binary variables \(B_n\) for nodes and \(B_{[n]}\) for equivalence classes, constrains selection by return-value, congruence, and class-coverage requirements, and minimizes \(\sum_n B_n \cdot cost(n)\) as a 0–1 ILP [1012.1802]. egglog provides an `extract` command that compiles cost relationships into a Datalog query over e-graph relations, returning the minimal cost and a witness E-node [2304.04332].

The Julia system extends extraction to control flow and reuse. After saturation over high-level Julia SSA IR, it extracts a linear, acyclic SSA IR by an ILP over binary variables \(w_n^{(i)}\), interpreted as “\(n\) is selected in the extraction rooted at \(i\),” together with cycle-elimination variables \(v_{\Psi,c}^{(i)}\); the objective minimizes \(\sum_{i\in I}\sum_{n\in N} M(n)\cdot w_n^{(i)}\), and the constraints encode child covering with reuse from dominators, absence of dangling selects, root materialization, and acyclicity [2502.17075]. The dominance-aware formulation is specifically intended to account for code reuse across dominated statements [2502.17075]. In E-Path, by contrast, extraction is stated as
\[
S^*=\arg\min_{S\in P} C(S),
\]
so that the best instruction sequence is selected after saturation rather than during rewrite application [2605.28694].

## 5. Domain-specific instantiations

The earliest prominent use of the phrase “Relational Equality Saturation” for a specific domain is SPORES, which optimizes linear-algebra expressions by translating them into relational-algebra expressions, saturating under relational-algebra identities, extracting the cheapest member, and translating the result back to linear algebra [2002.07951]. In that system, matrices and vectors are treated as \(K\)-relations over the real semiring, the LA-to-RA translation introduces bind and unbind operators, and exactly seven core RA identities serve as the rewrite basis, including distributivity of join over union, distributivity of aggregation over union, pushing join through aggregation, merging nested aggregations, pulling out aggregation on a fresh dimension, and associativity/commutativity of union and join [2002.07951]. The paper states that this basis is complete: every RA expression can be rewritten into a unique canonical form, and two RA expressions are semantically equivalent iff they have isomorphic canonical forms [2002.07951]. Integrated into SystemML, SPORES derived all existing hand-coded optimizations in SystemML and performed new optimizations that led to speedups from 1.2X to 5X [2002.07951].

Relational query optimization is another major instantiation. In the ongoing work on contextual relational EqSat, physical properties such as sort order or partitioning are treated as contexts in the lattice \(C\), so that equivalences like merge-join \(\equiv\) hash-join can hold only under a “sort-on-column-\(i\)” context, and conditional simplification is expressed by pushing “then” and “else” contexts into branch subterms [2507.11897]. The same paper treats lambda application by pushing an environment into the context and performing simple \(\beta\)-reductions when free-variable side conditions can be checked by analysis [2507.11897].

Aurora addresses relational query rewrite by interleaving EqSat with Graph Reinforcement Learning. The action space is the set of relational rewrite rules \(\mathcal{R}=\{r_1,\dots,r_{37}\}\) plus a special `Reset` action; the state is the current e-graph together with catalog statistics; the transition either applies a rewrite rule or extracts the best plan and rebuilds the e-graph from it; and the reward is
\[
r_t = [C(p_{t-1})-C(p_t)] - \lambda(|G_t|-|G_{t-1}|) - \mu \mathbf{1}\{\text{saturating/no-op}\}
\]
[2407.12794]. The neural policy uses a 3-layer GAT, global add-pool, an LSTM over rewrite history, and PPO for actor-critic training [2407.12794]. Reported results state that Aurora finds plans whose median cost is orders of magnitude lower than egg or random, achieves \(>99\%\) improvement on \(33\%\) of queries, executes all benchmark queries under SLA where egg times out on \(4/6\) queries, incurs planning cost in the low milliseconds—over \(100\times\) faster than egg’s heavy ILP extraction on large e-graphs—and rewrote a PostgreSQL “Alternative” query into an “Optimal” form with an \(11\%\) execution-time gain over PostgreSQL’s native optimizer [2407.12794].

Compiler-oriented instantiations emphasize richer IR structure. In the Julia system, a running example rewrites `tr(A)` to `sum(eigen(A).values)` and `det(A)` to `prod(eigen(A).values)` under the type constraint `~A::AbstractMatrix`, after which ILP extraction materializes `eig = eigen(A)` once and reuses it in both branches, yielding one shared eigen decomposition rather than separate `tr` and `det` computations [2502.17075]. In E-Path, classical CFG optimizations such as LICM and loop unrolling are encoded as monotonic rewrites over instruction sequences; because every rewrite adds a sequence and never deletes one, the framework preserves multiple equivalent loop and branch variants and avoids phase ordering by selecting the cheapest sequence only at extraction time [2605.28694].

The application scope also extends beyond optimization into program analysis and numerically sound rewriting. egglog reimplemented a unification-based Steensgaard points-to analysis and a floating-point term rewriter with relational guards; in the former, no explicit `eqrel` relation is required because union-find canonicalization merges equivalent locations, and in the latter interval analyses and a “not-equals” analysis make rewrites such as \(x/x \to 1\) conditional on sound side conditions [2304.04332]. Reported results include egglog being ~4.96× faster than the best patched Datalog+eqrel encoding and ~1.94× faster than cclyzer++ on the points-to benchmarks, and on 289 Herbie benchmarks running in ~74 min vs ~82 min originally while finding strictly more accurate solutions in 104 cases [2304.04332].

## 6. Limits, misconceptions, and open problems

A recurring misconception is that relational equality saturation simply means “running equality saturation on relational query plans.” The literature is broader. It includes EqSat encoded inside relational fixpoint engines, EqSat over relational-algebra normal forms, EqSat parameterized by context lattices, and EqSat over compiler relations such as type, dominance, and side-effect structure [2507.11897] [2002.07951] [2502.17075]. Another misconception is that relationalization automatically resolves termination. The semantic account shows the opposite: EqSat termination remains r.e.-complete, \(\Pi_2\)-complete, or undecidable depending on the quantification over inputs, and only specific syntactic criteria such as weak term acyclicity provide general guarantees [2501.02413].

The implementation literature identifies several concrete open problems. In contextual relational EqSat, adding context-sensitive equalities can only merge E-classes, which would violate monotonicity if user queries could observe the absolute number of classes; egglog therefore exposes only monotonic predicates such as \(eq(c,a,b)\) [2507.11897]. Naïve contextual EqSat may duplicate subgraphs across contexts, motivating “colored union-find”; efficient context indexing is still needed when programs generate thousands of contexts; scoped variable elimination for lambda terms requires a negative-context or pattern-negation test that remains open; and extracting the best equivalent under mixed global and local contexts requires new cost models that account for context reapplication costs [2507.11897].

General EqSat engines also retain the familiar danger of non-termination when rewrites are not well-founded [2304.04332]. In database-oriented systems, learned guidance mitigates rather than removes the search problem: Aurora explicitly caps e-graph growth by node budgets and a `Reset` action, but generalization to unseen query shapes remains hard, some SQL constructs are omitted, and ILP extraction can still be a bottleneck for very large e-graphs [2407.12794]. In CFG-oriented systems, current prototypes may support reducible loops only, with no alias or memory modeling and no speculative transforms [2605.28694]. These caveats indicate that the central challenge is not merely representing more equalities, but doing so while preserving monotonic reasoning, tractable matching, sound effect modeling, and extractable cost structure.

Relational equality saturation therefore occupies an intermediate position between compiler rewriting, deductive databases, and term-rewriting semantics. It inherits the non-destructive search space of classical EqSat, the least-fixed-point viewpoint of relational reasoning, the context sensitivity of lattice-indexed analyses, and the extraction problems of combinatorial optimization. Its current forms already encompass query optimization, linear algebra, high-level compiler IR, control-flow graphs, points-to analysis, and floating-point rewriting [1012.1802] [2002.07951] [2304.04332] [2502.17075] [2507.11897] [2605.28694]. The technical trajectory suggests continued convergence between e-graphs, Datalog engines, and semantically constrained rewrite systems.

Source: https://www.emergentmind.com/topics/relational-equality-saturation