egglog/
extract.rs

1//! Cost models used by extraction.
2//!
3//! [`Cost`] is the minimum requirement for ranking extracted terms.
4//! [`TreeCostModel`] computes a node annotation and then folds it with selected
5//! child costs. The annotation can carry context that should not be part of the
6//! final cost, so tree extraction does not require costs to support addition.
7//!
8//! [`MonoidCost`] adds the associative and commutative combination operation
9//! needed to charge shared dependencies once. [`DagCostModel`] computes the
10//! marginal costs consumed by DAG extractors. [`TreeCostModelFromDag`] adapts
11//! such a model to tree extraction by combining each node's marginal cost with
12//! its selected child costs. [`DEFAULT_COST_MODEL`] is the default additive
13//! tree model.
14
15use crate::termdag::{TermDag, TermId};
16use crate::util::{HashMap, HashSet};
17use crate::*;
18use numeric_id::NumericId;
19use std::collections::VecDeque;
20
21/// A value that can be used to rank extraction candidates.
22pub trait Cost: Clone + Ord {}
23
24impl<T: Clone + Ord> Cost for T {}
25
26/// An extraction cost with an identity and a combination operation.
27///
28/// Implementations must make `identity` a two-sided identity and `combine`
29/// associative, commutative, deterministic, non-panicking, and monotone with
30/// respect to [`Cost`]'s ordering. Rust cannot enforce these laws.
31pub trait MonoidCost: Cost {
32    /// The identity cost, usually zero.
33    fn identity() -> Self;
34
35    /// Combines two costs without overflowing or panicking.
36    fn combine(self, other: &Self) -> Self;
37}
38
39macro_rules! monoid_unsigned_cost {
40    ($($cost:ty),* $(,)?) => {$(
41        impl MonoidCost for $cost {
42            fn identity() -> Self {
43                0
44            }
45
46            fn combine(self, other: &Self) -> Self {
47                self.saturating_add(*other)
48            }
49        }
50    )*};
51}
52
53monoid_unsigned_cost!(u8, u16, u32, u64, u128, usize);
54
55macro_rules! monoid_exact_cost {
56    ($($cost:ty),* $(,)?) => {$(
57        impl MonoidCost for $cost {
58            fn identity() -> Self {
59                use num::Zero;
60                Self::zero()
61            }
62
63            fn combine(self, other: &Self) -> Self {
64                self + other
65            }
66        }
67    )*};
68}
69
70monoid_exact_cost!(num::BigInt, num::BigRational);
71
72/// Computes marginal costs for extraction that charges shared dependencies once.
73///
74/// The returned costs exclude selected child and container-element costs.
75/// Implementations must return equal costs for equivalent arguments during one
76/// extraction.
77pub trait DagCostModel<C: MonoidCost> {
78    /// Computes the cost of a non-container primitive value.
79    fn base_value_cost(&self, egraph: &EGraph, sort: &ArcSort, value: Value) -> C;
80    /// Computes an enode's cost, excluding its children.
81    fn enode_cost(&self, egraph: &EGraph, func: &Function, enode: &Enode<'_>) -> C;
82
83    /// Computes a container's cost, excluding its elements.
84    fn container_cost(&self, egraph: &EGraph, sort: &ArcSort, value: Value) -> C {
85        let _ = (egraph, sort, value);
86        C::identity()
87    }
88}
89
90/// Computes tree-extraction costs from node annotations and selected child costs.
91///
92/// Models used by [`TreeExtractor`] must be deterministic and satisfy optimal
93/// substructure: replacing a child with a lower-cost extraction must not make
94/// its parent more expensive. They must also avoid making cyclic terms improve
95/// indefinitely. Otherwise extraction may be non-optimal, fail to converge, or
96/// fail during reconstruction. The annotation types let the first stage retain
97/// context, such as the constructor kind, without encoding it in `C`.
98pub trait TreeCostModel<C: Cost> {
99    /// Context retained between [`TreeCostModel::enode_cost`] and its fold.
100    type EnodeCost;
101    /// Context retained between [`TreeCostModel::container_cost`] and its fold.
102    type ContainerCost;
103
104    /// Computes the cost of a non-container primitive value.
105    fn base_value_cost(&self, egraph: &EGraph, sort: &ArcSort, value: Value) -> C;
106
107    /// Computes the annotation folded with an enode's selected child costs.
108    fn enode_cost(&self, egraph: &EGraph, func: &Function, enode: &Enode<'_>) -> Self::EnodeCost;
109
110    /// Computes the annotation folded with a container's selected element costs.
111    fn container_cost(&self, egraph: &EGraph, sort: &ArcSort, value: Value) -> Self::ContainerCost;
112
113    /// Produces an enode's total cost from its annotation and child costs.
114    fn fold_enode_cost(&self, enode_cost: Self::EnodeCost, child_costs: &[C]) -> C;
115
116    /// Produces a container's total cost from its annotation and element costs.
117    fn fold_container_cost(&self, container_cost: Self::ContainerCost, element_costs: &[C]) -> C;
118}
119
120trait TreeExtractorCostModel<C: Cost> {
121    fn base_value_cost(&self, egraph: &EGraph, sort: &ArcSort, value: Value) -> C;
122    fn total_enode_cost(
123        &self,
124        egraph: &EGraph,
125        func: &Function,
126        enode: &Enode<'_>,
127        child_costs: &[C],
128    ) -> C;
129    fn total_container_cost(
130        &self,
131        egraph: &EGraph,
132        sort: &ArcSort,
133        value: Value,
134        element_costs: &[C],
135    ) -> C;
136}
137
138impl<C: Cost, M: TreeCostModel<C>> TreeExtractorCostModel<C> for M {
139    fn base_value_cost(&self, egraph: &EGraph, sort: &ArcSort, value: Value) -> C {
140        TreeCostModel::base_value_cost(self, egraph, sort, value)
141    }
142
143    fn total_enode_cost(
144        &self,
145        egraph: &EGraph,
146        func: &Function,
147        enode: &Enode<'_>,
148        child_costs: &[C],
149    ) -> C {
150        self.fold_enode_cost(self.enode_cost(egraph, func, enode), child_costs)
151    }
152
153    fn total_container_cost(
154        &self,
155        egraph: &EGraph,
156        sort: &ArcSort,
157        value: Value,
158        element_costs: &[C],
159    ) -> C {
160        self.fold_container_cost(self.container_cost(egraph, sort, value), element_costs)
161    }
162}
163
164/// Adapts a [`DagCostModel`] to tree extraction by combining marginal costs.
165#[derive(Clone, Debug)]
166pub struct TreeCostModelFromDag<M>(pub M);
167
168impl<C: MonoidCost, M: DagCostModel<C>> TreeCostModel<C> for TreeCostModelFromDag<M> {
169    type EnodeCost = C;
170    type ContainerCost = C;
171
172    fn base_value_cost(&self, egraph: &EGraph, sort: &ArcSort, value: Value) -> C {
173        self.0.base_value_cost(egraph, sort, value)
174    }
175
176    fn enode_cost(&self, egraph: &EGraph, func: &Function, enode: &Enode<'_>) -> C {
177        self.0.enode_cost(egraph, func, enode)
178    }
179
180    fn container_cost(&self, egraph: &EGraph, sort: &ArcSort, value: Value) -> C {
181        self.0.container_cost(egraph, sort, value)
182    }
183
184    fn fold_enode_cost(&self, enode_cost: C, child_costs: &[C]) -> C {
185        child_costs
186            .iter()
187            .fold(enode_cost, |cost, child| cost.combine(child))
188    }
189
190    fn fold_container_cost(&self, container_cost: C, element_costs: &[C]) -> C {
191        element_costs
192            .iter()
193            .fold(container_cost, |cost, element| cost.combine(element))
194    }
195}
196
197/// The default extraction cost type.
198pub type DefaultCost = u64;
199
200/// The marginal-cost model underlying default tree and DAG extraction.
201///
202/// With [`DefaultCost`], constructor `:cost` declarations override `node_cost`
203/// and selected child costs are combined with each constructor's cost.
204#[derive(Clone, Debug)]
205pub struct AdditiveCostModel {
206    /// The fallback cost for primitive values and constructors without `:cost`.
207    pub node_cost: DefaultCost,
208}
209
210impl Default for AdditiveCostModel {
211    fn default() -> Self {
212        Self { node_cost: 1 }
213    }
214}
215
216/// The default additive model used by tree extraction.
217pub const DEFAULT_COST_MODEL: TreeCostModelFromDag<AdditiveCostModel> =
218    TreeCostModelFromDag(AdditiveCostModel { node_cost: 1 });
219
220impl DagCostModel<DefaultCost> for AdditiveCostModel {
221    fn base_value_cost(&self, _egraph: &EGraph, _sort: &ArcSort, _value: Value) -> DefaultCost {
222        self.node_cost
223    }
224
225    fn enode_cost(&self, egraph: &EGraph, func: &Function, _enode: &Enode<'_>) -> DefaultCost {
226        func.extraction_head_cost(egraph).unwrap_or(self.node_cost)
227    }
228}
229
230/// One extracted root or root variant.
231///
232/// The cost is the objective value assigned by the selected extractor. Tree
233/// extraction reports tree cost; DAG extractors may instead report a per-root
234/// or per-variant DAG cost. `term` indexes the enclosing result's shared
235/// [`TermDag`].
236#[derive(Clone, Debug)]
237pub struct ExtractedTerm<C> {
238    /// The selected extractor's cost for this result.
239    pub cost: C,
240    /// The extracted root in the enclosing result's [`TermDag`].
241    pub term: TermId,
242}
243
244/// Best-extraction results for a batch of requested roots.
245///
246/// All returned term ids index the shared [`ExtractedTerms::termdag`].
247#[derive(Clone, Debug)]
248pub struct ExtractedTerms<C> {
249    /// Shared term storage for every extracted root.
250    pub termdag: TermDag,
251    /// One extraction result per requested root, in request order.
252    ///
253    /// `None` means that root is unextractable with the selected cost model and
254    /// available constructors.
255    pub terms: Vec<Option<ExtractedTerm<C>>>,
256}
257
258/// Root-variant extraction results for a batch of requested roots.
259///
260/// All returned term ids index the shared [`ExtractedTermVariants::termdag`].
261#[derive(Clone, Debug)]
262pub struct ExtractedTermVariants<C> {
263    /// Shared term storage for every extracted variant.
264    pub termdag: TermDag,
265    /// Outer vector follows requested-root order; each inner vector contains that root's variants.
266    pub variants: Vec<Vec<ExtractedTerm<C>>>,
267}
268
269/// Bellman-Ford-like tree extraction with reusable cost preparation.
270///
271/// The prepared state borrows the e-graph because reconstruction still needs
272/// its sort storage and constructor metadata. This prevents prepared costs from
273/// being used after the e-graph is mutated.
274pub struct TreeExtractor<'g, C: Cost> {
275    egraph: &'g EGraph,
276    funcs: Vec<String>,
277    cost_model: Box<dyn TreeExtractorCostModel<C> + 'g>,
278    /// Dense id assigned to each eq sort that some extractable function outputs;
279    /// indexes into `costs` and `parent_edge`.
280    sort_ids: HashMap<String, usize>,
281    costs: Vec<HashMap<Value, RankedCost<C>>>,
282    parent_edge: Vec<HashMap<Value, (usize, Vec<Value>)>>,
283}
284
285/// Every successful relaxation updates the cost and chronological rank together.
286struct RankedCost<C> {
287    cost: C,
288    rank: usize,
289}
290
291/// How extraction treats one child column of a function, resolved once so the
292/// per-row cost loops avoid repeated sort dispatch and name-keyed lookups.
293enum ChildKind {
294    /// An eq-sort column; `Some` holds the sort's dense id, `None` means no
295    /// extractable function outputs this sort (its terms have no cost).
296    EqSort(Option<usize>),
297    Container(ArcSort),
298    Base(ArcSort),
299}
300
301/// Per-function data for [`TreeExtractor::bellman_ford`]: resolved schema facts
302/// plus a flat materialized copy of the table's non-subsumed rows, so each
303/// relaxation pass iterates memory instead of re-scanning the table.
304struct FuncData<'a> {
305    func: &'a Function,
306    /// The function whose `:cost` prices this table (a view table's term constructor).
307    cost_func: &'a Function,
308    /// Row width in `rows`: the function's inputs plus its output column.
309    arity: usize,
310    output_idx: usize,
311    output_sort_id: usize,
312    child_kinds: Vec<ChildKind>,
313    rows: Vec<Value>,
314}
315
316/// The rows reading each eq value as a child, directly or inside a container.
317///
318/// Eq-sort ids come from one backend counter, so a value alone names its class.
319struct ChildIndex {
320    /// Each read value's local id, an index into `offsets`.
321    ids: HashMap<Value, u32>,
322    /// `offsets[l]..offsets[l + 1]` is the run in `readers` for local id `l`.
323    offsets: Vec<u32>,
324    /// `(function, row)` pairs, one run per value.
325    readers: Vec<(u32, u32)>,
326}
327
328impl ChildIndex {
329    /// Indexes the `(value, function, row)` triples that `reads` yields. Each
330    /// call to `reads` must yield the same triples in the same order. Panics
331    /// past 2^32 triples.
332    fn new<I: Iterator<Item = (Value, u32, u32)>>(reads: impl Fn() -> I) -> Self {
333        // `locals` holds each read's value, then its local id. A value's offset
334        // counts its reads, then holds its run's end; the fill pass moves it back
335        // to the run's start.
336        let mut ids: HashMap<Value, u32> = HashMap::default();
337        let mut offsets: Vec<u32> = Vec::new();
338        let mut locals: Vec<u32> = Vec::new();
339        reads().for_each(|(value, _, _)| locals.push(value.rep()));
340        for read in &mut locals {
341            let local = *ids.entry(Value::new(*read)).or_insert_with(|| {
342                offsets.push(0);
343                (offsets.len() - 1) as u32
344            });
345            offsets[local as usize] += 1;
346            *read = local;
347        }
348        assert!(
349            u32::try_from(locals.len()).is_ok(),
350            "extraction index exceeds 2^32 child reads"
351        );
352        let mut end = 0;
353        for offset in offsets.iter_mut() {
354            end += *offset;
355            *offset = end;
356        }
357        offsets.reserve_exact(1);
358        offsets.push(end);
359        let mut readers = vec![(0, 0); locals.len()];
360        let mut read = 0;
361        reads().for_each(|(_, function, row)| {
362            let start = &mut offsets[locals[read] as usize];
363            read += 1;
364            *start -= 1;
365            readers[*start as usize] = (function, row);
366        });
367        ChildIndex {
368            ids,
369            offsets,
370            readers,
371        }
372    }
373
374    /// The `(function, row)` pairs reading `value`, in no particular order.
375    fn readers(&self, value: Value) -> &[(u32, u32)] {
376        self.ids.get(&value).map_or(&[], |&local| {
377            let local = local as usize;
378            &self.readers[self.offsets[local] as usize..self.offsets[local + 1] as usize]
379        })
380    }
381}
382
383/// Dirty rows are visited in sweep order.
384struct DirtyRows {
385    words: Vec<u64>,
386    count: usize,
387}
388
389impl DirtyRows {
390    fn full(len: usize) -> Self {
391        let mut words = vec![u64::MAX; len.div_ceil(64)];
392        if let Some(last) = words.last_mut() {
393            *last >>= len.div_ceil(64) * 64 - len; // clear the padding bits
394        }
395        Self { words, count: len }
396    }
397
398    fn insert(&mut self, row: usize) {
399        let bit = 1 << (row % 64);
400        let word = &mut self.words[row / 64];
401        if *word & bit == 0 {
402            *word |= bit;
403            self.count += 1;
404        }
405    }
406
407    fn pop_from(&mut self, cursor: usize) -> Option<usize> {
408        if self.count == 0 {
409            return None;
410        }
411        let mut wi = cursor / 64;
412        let mut pending = *self.words.get(wi)? & (u64::MAX << (cursor % 64));
413        while pending == 0 {
414            wi += 1;
415            pending = *self.words.get(wi)?;
416        }
417        let bit = pending.trailing_zeros() as usize;
418        self.words[wi] &= !(1 << bit);
419        self.count -= 1;
420        Some(wi * 64 + bit)
421    }
422}
423
424impl<'g, C: Cost> TreeExtractor<'g, C> {
425    /// Prepares extraction costs for constructors reachable from `rootsorts`.
426    ///
427    /// Pass `None` to prepare every extractable root sort. Later calls to
428    /// [`TreeExtractor::extract_best_with_sort`] and
429    /// [`TreeExtractor::extract_variants_with_sort`] reuse the prepared best
430    /// costs and producer choices.
431    ///
432    /// Primitive and container roots are costed when extracted. Variant
433    /// extraction also uses the model to rescore candidate root enodes, so the
434    /// model must return stable results for the extractor's lifetime.
435    pub fn compute_costs_from_rootsorts(
436        rootsorts: Option<Vec<ArcSort>>,
437        egraph: &'g EGraph,
438        cost_model: impl TreeCostModel<C> + 'g,
439    ) -> Self {
440        // We filter out tables unreachable from the root sorts
441        let extract_all_sorts = rootsorts.is_none();
442
443        let mut rootsorts = rootsorts.unwrap_or_default();
444
445        // Built a reverse index from output sort to function head symbols
446        // Only include constructors (not regular functions), and respect the user-facing
447        // hidden and unextractable flags.
448        let mut rev_index: HashMap<String, Vec<String>> = Default::default();
449        for func in egraph.functions.iter() {
450            let unextractable = func.1.decl.unextractable;
451            let hidden = func.1.decl.internal_hidden;
452
453            // Only extract constructors and view tables, which reconstruct as their
454            // term_constructor. Proof extraction uses its own root-directed extractor
455            // and does not need alternate behavior here.
456            if !unextractable
457                && !hidden
458                && (func.1.decl.subtype == FunctionSubtype::Constructor
459                    || func.1.decl.term_constructor.is_some())
460            {
461                let func_name = func.0.clone();
462                // For view tables (with term_constructor in proof mode), the e-class is the last input column
463                let output_sort_name = func.1.extraction_output_sort().name();
464                if let Some(v) = rev_index.get_mut(output_sort_name) {
465                    v.push(func_name);
466                } else {
467                    rev_index.insert(output_sort_name.to_owned(), vec![func_name]);
468                    if extract_all_sorts {
469                        rootsorts.push(func.1.extraction_output_sort().clone());
470                    }
471                }
472            }
473        }
474
475        // Do a BFS to find reachable tables
476        let mut q: VecDeque<ArcSort> = VecDeque::new();
477        let mut seen: HashSet<String> = Default::default();
478        for rootsort in rootsorts.iter() {
479            if seen.insert(rootsort.name().to_owned()) {
480                q.push_back(rootsort.clone());
481            }
482        }
483
484        let mut funcs_set: HashSet<String> = Default::default();
485        let mut funcs: Vec<String> = Vec::new();
486        while !q.is_empty() {
487            let sort = q.pop_front().unwrap();
488            if sort.is_container_sort() {
489                let inner_sorts = sort.inner_sorts();
490                for s in inner_sorts {
491                    if !seen.contains(s.name()) {
492                        q.push_back(s.clone());
493                        seen.insert(s.name().to_owned());
494                    }
495                }
496            } else if sort.is_eq_sort()
497                && let Some(head_symbols) = rev_index.get(sort.name())
498            {
499                for h in head_symbols {
500                    if !funcs_set.contains(h) {
501                        let func = egraph.functions.get(h).unwrap();
502                        // For view tables, children are all but the last input (which is the e-class)
503                        let num_children = func.extraction_num_children();
504                        for ch in func.func_type.input.iter().take(num_children) {
505                            let ch_name = ch.name();
506                            if !seen.contains(ch_name) {
507                                q.push_back(ch.clone());
508                                seen.insert(ch_name.to_owned());
509                            }
510                        }
511                        funcs_set.insert(h.clone());
512                        funcs.push(h.clone());
513                    }
514                }
515            }
516        }
517
518        // Initialize the tables to have the reachable entries
519        let mut sort_ids: HashMap<String, usize> = Default::default();
520        for func_name in funcs.iter() {
521            let func = egraph.functions.get(func_name).unwrap();
522            let output_sort_name = func.extraction_output_sort().name();
523            let next_id = sort_ids.len();
524            sort_ids
525                .entry(output_sort_name.to_owned())
526                .or_insert(next_id);
527        }
528        let n_sorts = sort_ids.len();
529
530        let mut extractor = TreeExtractor {
531            egraph,
532            funcs,
533            cost_model: Box::new(cost_model),
534            sort_ids,
535            costs: (0..n_sorts).map(|_| Default::default()).collect(),
536            parent_edge: (0..n_sorts).map(|_| Default::default()).collect(),
537        };
538
539        extractor.bellman_ford(egraph);
540
541        extractor
542    }
543
544    /// Compute the cost of a single enode
545    /// Recurse if container
546    /// Returns None if contains an undefined eqsort term (potentially after unfolding)
547    fn compute_cost_node(&self, egraph: &EGraph, value: Value, sort: &ArcSort) -> Option<C> {
548        if sort.is_container_sort() {
549            let elements = sort.inner_values(egraph.backend.container_values(), value);
550            let mut ch_costs: Vec<C> = Vec::new();
551            for ch in elements.iter() {
552                ch_costs.push(self.compute_cost_node(egraph, ch.1, &ch.0)?);
553            }
554            Some(
555                self.cost_model
556                    .total_container_cost(egraph, sort, value, &ch_costs),
557            )
558        } else if sort.is_eq_sort() {
559            self.costs[*self.sort_ids.get(sort.name())?]
560                .get(&value)
561                .map(|entry| entry.cost.clone())
562        } else {
563            // Primitive
564            Some(self.cost_model.base_value_cost(egraph, sort, value))
565        }
566    }
567
568    /// A row in a constructor table is a hyperedge from the set of input terms to the constructed output term.
569    fn compute_cost_hyperedge(
570        &self,
571        egraph: &EGraph,
572        row: &egglog_bridge::ScanEntry,
573        func: &Function,
574    ) -> Option<C> {
575        let mut ch_costs: Vec<C> = Vec::new();
576        let sorts = &func.func_type.input;
577        let num_children = func.extraction_num_children();
578        for (value, sort) in row.vals.iter().take(num_children).zip(sorts.iter()) {
579            ch_costs.push(self.compute_cost_node(egraph, *value, sort)?);
580        }
581        let head_name = func.extraction_term_name();
582        let output_idx = func.extraction_output_index();
583        let enode = Enode {
584            name: head_name,
585            children: &row.vals[..output_idx],
586            eclass: row.vals[output_idx],
587            subsumed: row.subsumed,
588        };
589        let cost_func = func
590            .decl
591            .term_constructor
592            .as_ref()
593            .and_then(|name| egraph.functions.get(name))
594            .unwrap_or(func);
595        Some(
596            self.cost_model
597                .total_enode_cost(egraph, cost_func, &enode, &ch_costs),
598        )
599    }
600
601    fn compute_topo_rnk_node(&self, egraph: &EGraph, value: Value, sort: &ArcSort) -> usize {
602        if sort.is_container_sort() {
603            sort.inner_values(egraph.backend.container_values(), value)
604                .iter()
605                .fold(0, |ret, (sort, value)| {
606                    usize::max(ret, self.compute_topo_rnk_node(egraph, *value, sort))
607                })
608        } else if sort.is_eq_sort() {
609            if let Some(id) = self.sort_ids.get(sort.name()) {
610                self.costs[*id]
611                    .get(&value)
612                    .map_or(usize::MAX, |entry| entry.rank)
613            } else {
614                usize::MAX
615            }
616        } else {
617            0
618        }
619    }
620
621    /// Compute the child costs of one materialized row into `ch_costs`, and fold them
622    /// into the row's total cost. Returns `None` if any child is uncomputed so far.
623    fn row_cost(
624        &self,
625        egraph: &EGraph,
626        f: &FuncData,
627        row: &[Value],
628        ch_costs: &mut Vec<C>,
629    ) -> Option<C> {
630        ch_costs.clear();
631        for (kind, value) in f.child_kinds.iter().zip(row) {
632            ch_costs.push(match kind {
633                ChildKind::EqSort(Some(id)) => self.costs[*id].get(value)?.cost.clone(),
634                ChildKind::EqSort(None) => return None,
635                ChildKind::Container(sort) => self.compute_cost_node(egraph, *value, sort)?,
636                ChildKind::Base(sort) => self.cost_model.base_value_cost(egraph, sort, *value),
637            });
638        }
639        let enode = Enode {
640            name: f.func.extraction_term_name(),
641            children: &row[..f.output_idx],
642            eclass: row[f.output_idx],
643            subsumed: false,
644        };
645        Some(
646            self.cost_model
647                .total_enode_cost(egraph, f.cost_func, &enode, ch_costs),
648        )
649    }
650
651    /// The chronological rank of one child; a row's edge rank is its children's maximum.
652    fn child_rank(&self, egraph: &EGraph, kind: &ChildKind, value: Value) -> usize {
653        match kind {
654            ChildKind::EqSort(Some(id)) => self.costs[*id]
655                .get(&value)
656                .map_or(usize::MAX, |entry| entry.rank),
657            ChildKind::EqSort(None) => usize::MAX,
658            ChildKind::Container(sort) => self.compute_topo_rnk_node(egraph, value, sort),
659            ChildKind::Base(_) => 0,
660        }
661    }
662
663    /// Report every eq value a container value's cost depends on, found by
664    /// recursing through nested container values.
665    fn register_container_deps(
666        &self,
667        egraph: &EGraph,
668        sort: &ArcSort,
669        value: Value,
670        register: &mut impl FnMut(Value),
671    ) {
672        if sort.is_container_sort() {
673            for (inner_sort, inner_value) in
674                sort.inner_values(egraph.backend.container_values(), value)
675            {
676                self.register_container_deps(egraph, &inner_sort, inner_value, register);
677            }
678        } else if sort.is_eq_sort() && self.sort_ids.contains_key(sort.name()) {
679            register(value);
680        }
681    }
682
683    /// Builds the [`ChildIndex`] of `func_data`.
684    fn child_index(&self, egraph: &EGraph, func_data: &[FuncData]) -> ChildIndex {
685        // Walking a container allocates, so each is walked once and its reads kept.
686        let mut container_reads = Vec::new();
687        for (fi, f) in func_data.iter().enumerate() {
688            if !f
689                .child_kinds
690                .iter()
691                .any(|k| matches!(k, ChildKind::Container(_)))
692            {
693                continue;
694            }
695            for (ri, row) in f.rows.chunks_exact(f.arity).enumerate() {
696                for (kind, value) in f.child_kinds.iter().zip(row) {
697                    if let ChildKind::Container(sort) = kind {
698                        self.register_container_deps(egraph, sort, *value, &mut |v| {
699                            container_reads.push((v, fi as u32, ri as u32))
700                        });
701                    }
702                }
703            }
704        }
705        ChildIndex::new(|| {
706            func_data
707                .iter()
708                .enumerate()
709                .flat_map(|(fi, f)| {
710                    f.rows
711                        .chunks_exact(f.arity)
712                        .enumerate()
713                        .flat_map(move |(ri, row)| {
714                            f.child_kinds
715                                .iter()
716                                .zip(row)
717                                .filter_map(move |(kind, value)| {
718                                    matches!(kind, ChildKind::EqSort(Some(_)))
719                                        .then_some((*value, fi as u32, ri as u32))
720                                })
721                        })
722                })
723                .chain(container_reads.iter().copied())
724        })
725    }
726
727    /// We use Bellman-Ford to compute the costs of the relevant eq sorts' terms
728    /// [Bellman-Ford](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) is a shortest path algorithm.
729    /// The version implemented here computes the shortest path from any node in a set of sources to all the reachable nodes.
730    /// Computing the minimum cost for terms is treated as a shortest path problem on a hypergraph here.
731    /// In this hypergraph, the nodes corresponde to eclasses, the distances are the costs to extract a term of those eclasses,
732    /// and each enode is a hyperedge that goes from the set of children eclasses to the enode's eclass.
733    /// The sources are the eclasses with known costs from the cost model.
734    /// Additionally, to avoid cycles in the extraction even when the cost model can assign an equal cost to a term and its subterm.
735    /// It computes a topological rank for each eclass
736    /// and only allows each eclass to have children of classes of strictly smaller ranks in the extraction.
737    fn bellman_ford(&mut self, egraph: &EGraph) {
738        // Materialize each function's non-subsumed rows once, so the relaxation
739        // passes below iterate plain memory instead of re-scanning every table.
740        let func_data: Vec<FuncData> = self
741            .funcs
742            .iter()
743            .map(|func_name| {
744                let func = egraph.functions.get(func_name).unwrap();
745                let num_children = func.extraction_num_children();
746                let child_kinds = func.func_type.input[..num_children]
747                    .iter()
748                    .map(|sort| {
749                        if sort.is_container_sort() {
750                            ChildKind::Container(sort.clone())
751                        } else if sort.is_eq_sort() {
752                            ChildKind::EqSort(self.sort_ids.get(sort.name()).copied())
753                        } else {
754                            ChildKind::Base(sort.clone())
755                        }
756                    })
757                    .collect();
758                let arity = func.func_type.input.len() + 1;
759                // Reserved from the table's size at the first live row, so the copy never
760                // regrows and a fully subsumed table allocates nothing.
761                let reserve = egraph.backend.table_size(func.backend_id) * arity;
762                let mut rows = Vec::new();
763                egraph.backend.for_each(func.backend_id, |row| {
764                    if !row.subsumed {
765                        if rows.is_empty() {
766                            rows.reserve_exact(reserve);
767                        }
768                        rows.extend_from_slice(row.vals);
769                    }
770                });
771                FuncData {
772                    func,
773                    cost_func: func
774                        .decl
775                        .term_constructor
776                        .as_ref()
777                        .and_then(|name| egraph.functions.get(name))
778                        .unwrap_or(func),
779                    arity,
780                    output_idx: func.extraction_output_index(),
781                    output_sort_id: self.sort_ids[func.extraction_output_sort().name()],
782                    child_kinds,
783                    rows,
784                }
785            })
786            .collect();
787
788        let child_index = self.child_index(egraph, &func_data);
789
790        let mut topo_rnk_cnt = 0usize;
791        // Semi-naive relaxation: a row recomputes exactly the same cost against a
792        // never-increasing target unless one of its child (sort, value) costs
793        // changed since the row was last evaluated, so only such "dirty" rows are
794        // (re)visited.
795        let mut dirty: Vec<DirtyRows> = func_data
796            .iter()
797            .map(|f| DirtyRows::full(f.rows.len() / f.arity))
798            .collect();
799
800        let mut ch_costs: Vec<C> = Vec::new();
801        loop {
802            let mut any = false;
803            for (fi, f) in func_data.iter().enumerate() {
804                if dirty[fi].count == 0 {
805                    continue;
806                }
807                any = true;
808                // Marks set at or behind the sweep cursor (including a row
809                // re-marking itself) stay for the next sweep; marks ahead of it
810                // are picked up in this one, matching the naive pass exactly.
811                let mut cursor = 0;
812                while let Some(ri) = dirty[fi].pop_from(cursor) {
813                    cursor = ri + 1;
814                    let row = &f.rows[ri * f.arity..(ri + 1) * f.arity];
815                    let Some(new_cost) = self.row_cost(egraph, f, row, &mut ch_costs) else {
816                        continue;
817                    };
818                    let target = row[f.output_idx];
819                    let entry = self.costs[f.output_sort_id].entry(target);
820                    if let HEntry::Occupied(old) = &entry
821                        && new_cost >= old.get().cost
822                    {
823                        continue;
824                    }
825                    // record the chronological order of the updates
826                    // which serves as a topological order that avoids cycles
827                    // even when a term has a cost equal to its subterms
828                    topo_rnk_cnt += 1;
829                    entry.insert(RankedCost {
830                        cost: new_cost,
831                        rank: topo_rnk_cnt,
832                    });
833                    for &(dfi, dri) in child_index.readers(target) {
834                        dirty[dfi as usize].insert(dri as usize);
835                    }
836                }
837            }
838            if !any {
839                break;
840            }
841        }
842
843        // Free the scheduler's state before the parent edges allocate.
844        drop((child_index, dirty));
845
846        // Save the edges for reconstruction
847        for (parents, costs) in self.parent_edge.iter_mut().zip(&self.costs) {
848            parents.reserve(costs.len());
849        }
850        for (fi, f) in func_data.into_iter().enumerate() {
851            for row in f.rows.chunks_exact(f.arity) {
852                let target = row[f.output_idx];
853                let Some(best) = self.costs[f.output_sort_id].get(&target) else {
854                    continue;
855                };
856                // one of the possible best parent edges
857                if self.row_cost(egraph, &f, row, &mut ch_costs).as_ref() != Some(&best.cost) {
858                    continue;
859                }
860                let edge_rank = f
861                    .child_kinds
862                    .iter()
863                    .zip(row)
864                    .map(|(kind, value)| self.child_rank(egraph, kind, *value))
865                    .max()
866                    .unwrap_or(0);
867                // one of the parent edges that avoids cycles
868                if best.rank > edge_rank
869                    && let HEntry::Vacant(e) = self.parent_edge[f.output_sort_id].entry(target)
870                {
871                    e.insert((fi, row.to_vec()));
872                }
873            }
874        }
875    }
876
877    /// This recursively reconstruct the termdag that gives the minimum cost for eclass value.
878    fn reconstruct_termdag_node_helper(
879        &self,
880        egraph: &EGraph,
881        termdag: &mut TermDag,
882        value: Value,
883        sort: &ArcSort,
884        cache: &mut HashMap<(Value, String), TermId>,
885    ) -> TermId {
886        let key = (value, sort.name().to_owned());
887        if let Some(term) = cache.get(&key) {
888            return *term;
889        }
890
891        let term = if sort.is_container_sort() {
892            let elements = sort.inner_values(egraph.backend.container_values(), value);
893            let mut ch_terms: Vec<TermId> = Vec::new();
894            for ch in elements.iter() {
895                ch_terms.push(
896                    self.reconstruct_termdag_node_helper(egraph, termdag, ch.1, &ch.0, cache),
897                );
898            }
899            sort.reconstruct_termdag_container(
900                egraph.backend.container_values(),
901                value,
902                termdag,
903                ch_terms,
904            )
905        } else if sort.is_eq_sort() {
906            let (function, hyperedge) = self.parent_edge[self.sort_ids[sort.name()]]
907                .get(&value)
908                .unwrap();
909            let func = egraph.functions.get(&self.funcs[*function]).unwrap();
910            let ch_sorts = &func.func_type.input;
911
912            let num_children = func.extraction_num_children();
913            let output_name = func.extraction_term_name();
914
915            let mut ch_terms: Vec<TermId> = Vec::new();
916            for (value, sort) in hyperedge.iter().take(num_children).zip(ch_sorts.iter()) {
917                ch_terms.push(
918                    self.reconstruct_termdag_node_helper(egraph, termdag, *value, sort, cache),
919                );
920            }
921            termdag.app(output_name.to_string(), ch_terms)
922        } else {
923            // Base value case
924            sort.reconstruct_termdag_base(egraph.backend.base_values(), value, termdag)
925        };
926
927        cache.insert(key, term);
928        term
929    }
930
931    /// Extracts the best term for `value` from a prepared sort.
932    ///
933    /// `sort` may be a requested root sort, a sort reachable from those roots,
934    /// a primitive sort, or a container of prepared sorts.
935    pub fn extract_best_with_sort(
936        &self,
937        termdag: &mut TermDag,
938        value: Value,
939        sort: ArcSort,
940    ) -> Option<ExtractedTerm<C>> {
941        self.extract_best_with_sort_cached(termdag, &mut Default::default(), value, sort)
942    }
943
944    fn extract_best_with_sort_cached(
945        &self,
946        termdag: &mut TermDag,
947        cache: &mut HashMap<(Value, String), TermId>,
948        value: Value,
949        sort: ArcSort,
950    ) -> Option<ExtractedTerm<C>> {
951        let egraph = self.egraph;
952        // Canonicalize the value using the union-find if available (for term-encoding mode)
953        let canonical_value = self.find_canonical(egraph, value, &sort);
954
955        let best_cost = self.compute_cost_node(egraph, canonical_value, &sort)?;
956        let term =
957            self.reconstruct_termdag_node_helper(egraph, termdag, canonical_value, &sort, cache);
958
959        Some(ExtractedTerm {
960            cost: best_cost,
961            term,
962        })
963    }
964
965    /// Find the canonical representative of a value using the union-find table.
966    /// If no UF is registered for this sort, returns the original value.
967    /// The UF table stores (value, canonical) pairs - one hop lookup.
968    fn find_canonical(&self, egraph: &EGraph, value: Value, sort: &ArcSort) -> Value {
969        // Check if there's a UF registered for this sort
970        let Some(uf_name) = egraph.proof_state.uf_parent.get(sort.name()) else {
971            return value;
972        };
973
974        // Get the UF function
975        let Some(uf_func) = egraph.functions.get(uf_name) else {
976            return value;
977        };
978
979        // Single lookup in UF table - it's guaranteed to be one hop to canonical
980        let mut canonical = value;
981        egraph
982            .backend
983            .for_each(uf_func.backend_id, |row: egglog_bridge::ScanEntry| {
984                // UF table has (child, parent) as inputs
985                if row.vals[0] == value {
986                    canonical = row.vals[1];
987                }
988            });
989
990        canonical
991    }
992
993    /// Extracts up to `nvariants` root variants for `value` from a prepared sort.
994    ///
995    /// Variants are selected by first picking the lowest-cost root e-nodes and
996    /// then extracting each e-node's children with their best prepared terms.
997    pub fn extract_variants_with_sort(
998        &self,
999        termdag: &mut TermDag,
1000        value: Value,
1001        nvariants: usize,
1002        sort: ArcSort,
1003    ) -> Vec<ExtractedTerm<C>> {
1004        if nvariants == 0 {
1005            return vec![];
1006        }
1007
1008        let egraph = self.egraph;
1009        if sort.is_eq_sort() {
1010            // Canonicalize the value using the union-find if available
1011            let canonical_value = self.find_canonical(egraph, value, &sort);
1012
1013            let mut root_variants: Vec<(C, String, Vec<Value>)> = Vec::new();
1014
1015            for func_name in self.funcs.iter().filter(|func_name| {
1016                // Need an eq on sorts - use extraction_output_sort for view table support
1017                sort.name()
1018                    == egraph
1019                        .functions
1020                        .get(*func_name)
1021                        .unwrap()
1022                        .extraction_output_sort()
1023                        .name()
1024            }) {
1025                let func = egraph.functions.get(func_name).unwrap();
1026                let output_idx = func.extraction_output_index();
1027
1028                let find_root_variants = |row: egglog_bridge::ScanEntry| {
1029                    if !row.subsumed {
1030                        let target = &row.vals[output_idx];
1031                        // A variant whose cost is `None` has a child e-class with no
1032                        // finite extraction (e.g. a purely cyclic child); such a variant
1033                        // can never appear in a minimal extraction, so we skip it. The
1034                        // target e-class still extracts via its other, costed variants.
1035                        if *target == canonical_value
1036                            && let Some(cost) = self.compute_cost_hyperedge(egraph, &row, func)
1037                        {
1038                            root_variants.push((cost, func_name.clone(), row.vals.to_vec()));
1039                        }
1040                    }
1041                };
1042
1043                egraph.backend.for_each(func.backend_id, find_root_variants);
1044            }
1045
1046            let mut res: Vec<ExtractedTerm<C>> = Vec::new();
1047            let mut cache: HashMap<(Value, String), TermId> = Default::default();
1048            root_variants.sort();
1049            root_variants.truncate(nvariants);
1050            for (cost, func_name, hyperedge) in root_variants {
1051                let mut ch_terms: Vec<TermId> = Vec::new();
1052                let func = egraph.functions.get(&func_name).unwrap();
1053                let ch_sorts = &func.func_type.input;
1054                let num_children = func.extraction_num_children();
1055                // For view tables, children are all but the last input (which is the e-class)
1056                for (value, sort) in hyperedge.iter().zip(ch_sorts.iter()).take(num_children) {
1057                    ch_terms.push(self.reconstruct_termdag_node_helper(
1058                        egraph, termdag, *value, sort, &mut cache,
1059                    ));
1060                }
1061                // Use extraction_term_name for view tables (maps to the original constructor)
1062                res.push(ExtractedTerm {
1063                    cost,
1064                    term: termdag.app(func.extraction_term_name().to_string(), ch_terms),
1065                });
1066            }
1067
1068            res
1069        } else {
1070            log::warn!(
1071                "extracting multiple variants for containers or primitives is not implemented, returning a single variant."
1072            );
1073            if let Some(res) = self.extract_best_with_sort(termdag, value, sort) {
1074                vec![res]
1075            } else {
1076                vec![]
1077            }
1078        }
1079    }
1080}
1081
1082impl Function {
1083    /// Returns the configured extraction head cost for this table.
1084    ///
1085    /// View tables inherit the cost of their referenced hidden term constructor.
1086    pub(crate) fn extraction_head_cost(&self, egraph: &EGraph) -> Option<DefaultCost> {
1087        if let Some(term_constructor) = &self.decl.term_constructor {
1088            egraph
1089                .functions
1090                .get(term_constructor)
1091                .and_then(|func| func.decl.cost)
1092        } else {
1093            self.decl.cost
1094        }
1095    }
1096
1097    /// For view tables (with term_constructor), the effective output sort is the last input column.
1098    /// For regular tables, it's the output sort.
1099    /// This is used by extraction to determine which sort a table produces values for.
1100    pub(crate) fn extraction_output_sort(&self) -> &ArcSort {
1101        if self.decl.term_constructor.is_some() {
1102            self.func_type.input.last().unwrap()
1103        } else {
1104            &self.func_type.output
1105        }
1106    }
1107
1108    /// Returns the number of children for extraction purposes.
1109    /// For view tables, this excludes the last column (the e-class).
1110    pub(crate) fn extraction_num_children(&self) -> usize {
1111        if self.decl.term_constructor.is_some() {
1112            self.func_type.input.len() - 1
1113        } else {
1114            self.func_type.input.len()
1115        }
1116    }
1117
1118    /// Returns the name to use when building terms during extraction.
1119    /// For view tables, this is the term_constructor name.
1120    pub(crate) fn extraction_term_name(&self) -> &str {
1121        self.decl
1122            .term_constructor
1123            .as_ref()
1124            .unwrap_or(&self.decl.name)
1125    }
1126
1127    /// Returns the index of the output value in a row for extraction purposes.
1128    /// For view tables, the e-class is the last input column (second-to-last in the row).
1129    /// For regular tables, it's the last column (the actual output).
1130    pub(crate) fn extraction_output_index(&self) -> usize {
1131        if self.decl.term_constructor.is_some() {
1132            // For view tables: input is [children..., eclass], output is view_sort
1133            // Row is [children..., eclass, view_sort]
1134            // We want eclass which is at index input.len() - 1
1135            self.func_type.input.len() - 1
1136        } else {
1137            // For regular tables: row is [inputs..., output]
1138            self.func_type.input.len()
1139        }
1140    }
1141}
1142
1143impl EGraph {
1144    /// Extracts the best tree term for each requested `(sort, value)` root
1145    /// using [`DEFAULT_COST_MODEL`].
1146    pub fn extract_best(
1147        &self,
1148        roots: Vec<(ArcSort, Value)>,
1149    ) -> Result<ExtractedTerms<DefaultCost>, Error> {
1150        self.extract_best_with_cost_model(roots, DEFAULT_COST_MODEL)
1151    }
1152
1153    /// Extracts the best tree term for each requested `(sort, value)` root.
1154    ///
1155    /// This is the normal user extraction path: it respects `:unextractable`
1156    /// and hidden internal functions. The cost model must satisfy the
1157    /// optimal-substructure and convergence requirements on [`TreeExtractor`].
1158    pub fn extract_best_with_cost_model<C: Cost, M: TreeCostModel<C>>(
1159        &self,
1160        roots: Vec<(ArcSort, Value)>,
1161        cost_model: M,
1162    ) -> Result<ExtractedTerms<C>, Error> {
1163        let rootsorts = roots.iter().map(|(sort, _)| sort.clone()).collect();
1164        let extractor =
1165            TreeExtractor::compute_costs_from_rootsorts(Some(rootsorts), self, cost_model);
1166        let mut termdag = TermDag::default();
1167        let mut cache = Default::default();
1168        let extracted_roots = roots
1169            .into_iter()
1170            .map(|(sort, value)| {
1171                extractor.extract_best_with_sort_cached(&mut termdag, &mut cache, value, sort)
1172            })
1173            .collect();
1174
1175        Ok(ExtractedTerms {
1176            termdag,
1177            terms: extracted_roots,
1178        })
1179    }
1180
1181    /// Extracts up to `nvariants` tree root variants for each requested root
1182    /// using [`DEFAULT_COST_MODEL`].
1183    pub fn extract_variants(
1184        &self,
1185        roots: Vec<(ArcSort, Value)>,
1186        nvariants: usize,
1187    ) -> Result<ExtractedTermVariants<DefaultCost>, Error> {
1188        self.extract_variants_with_cost_model(roots, nvariants, DEFAULT_COST_MODEL)
1189    }
1190
1191    /// Extracts up to `nvariants` tree root variants for each requested root.
1192    ///
1193    /// The cost model must satisfy the optimal-substructure and convergence
1194    /// requirements on [`TreeExtractor`].
1195    pub fn extract_variants_with_cost_model<C: Cost, M: TreeCostModel<C>>(
1196        &self,
1197        roots: Vec<(ArcSort, Value)>,
1198        nvariants: usize,
1199        cost_model: M,
1200    ) -> Result<ExtractedTermVariants<C>, Error> {
1201        if nvariants == 0 {
1202            return Ok(ExtractedTermVariants {
1203                termdag: TermDag::default(),
1204                variants: roots.iter().map(|_| Vec::new()).collect(),
1205            });
1206        }
1207
1208        let rootsorts = roots.iter().map(|(sort, _)| sort.clone()).collect();
1209        let extractor =
1210            TreeExtractor::compute_costs_from_rootsorts(Some(rootsorts), self, cost_model);
1211        let mut termdag = TermDag::default();
1212        let variants = roots
1213            .into_iter()
1214            .map(|(sort, value)| {
1215                extractor.extract_variants_with_sort(&mut termdag, value, nvariants, sort)
1216            })
1217            .collect();
1218
1219        Ok(ExtractedTermVariants { termdag, variants })
1220    }
1221
1222    /// Extracts the best term for one value using the default additive cost model.
1223    pub fn extract_value(
1224        &self,
1225        sort: &ArcSort,
1226        value: Value,
1227    ) -> Result<(TermDag, TermId, DefaultCost), Error> {
1228        let sort_name = sort.name().to_owned();
1229        let mut extracted = self.extract_best(vec![(sort.clone(), value)])?;
1230        let root = extracted
1231            .terms
1232            .pop()
1233            .expect("one requested root produces one result")
1234            .ok_or_else(|| {
1235                Error::ExtractError(format!(
1236                    "Unable to find any valid extraction for sort {sort_name}"
1237                ))
1238            })?;
1239        Ok((extracted.termdag, root.term, root.cost))
1240    }
1241
1242    /// For constructors and relations, the output column can be ignored
1243    pub fn function_to_dag(
1244        &self,
1245        sym: &str,
1246        n: usize,
1247        include_output: bool,
1248    ) -> Result<(Vec<TermId>, Option<Vec<TermId>>, TermDag), Error> {
1249        let func = self
1250            .functions
1251            .get(sym)
1252            .ok_or(TypeError::UnboundFunction(sym.to_owned(), span!()))?;
1253        let mut rootsorts = func.func_type.input.clone();
1254        if include_output {
1255            rootsorts.push(func.func_type.output.clone());
1256        }
1257        let extractor =
1258            TreeExtractor::compute_costs_from_rootsorts(Some(rootsorts), self, DEFAULT_COST_MODEL);
1259
1260        let mut termdag = TermDag::default();
1261        let mut inputs: Vec<TermId> = Vec::new();
1262        let mut output: Option<Vec<TermId>> = if include_output {
1263            Some(Vec::new())
1264        } else {
1265            None
1266        };
1267
1268        let extract_row = |row: egglog_bridge::ScanEntry| {
1269            if inputs.len() < n {
1270                // include subsumed rows
1271                let mut children: Vec<TermId> = Vec::new();
1272                for (value, sort) in row.vals.iter().zip(&func.func_type.input) {
1273                    let term = extractor
1274                        .extract_best_with_sort(&mut termdag, *value, sort.clone())
1275                        .map(|extracted| extracted.term)
1276                        .unwrap_or_else(|| termdag.var("Unextractable".into()));
1277                    children.push(term);
1278                }
1279                inputs.push(termdag.app(sym.to_owned(), children));
1280                if include_output {
1281                    let value = row.vals[func.func_type.input.len()];
1282                    let term = extractor
1283                        .extract_best_with_sort(&mut termdag, value, func.func_type.output.clone())
1284                        .map(|extracted| extracted.term)
1285                        .unwrap_or_else(|| termdag.var("Unextractable".into()));
1286                    output.as_mut().unwrap().push(term);
1287                }
1288                true
1289            } else {
1290                false
1291            }
1292        };
1293
1294        self.backend.for_each_while(func.backend_id, extract_row);
1295
1296        Ok((inputs, output, termdag))
1297    }
1298}
1299
1300#[cfg(test)]
1301mod tests {
1302    use super::*;
1303
1304    #[test]
1305    fn dirty_rows_have_no_padding_rows() {
1306        for len in [0, 1, 63, 64, 65, 127, 128, 129] {
1307            let mut rows = DirtyRows::full(len);
1308            for row in 0..len {
1309                assert_eq!(rows.pop_from(row), Some(row));
1310            }
1311            assert_eq!(rows.pop_from(len), None);
1312            assert_eq!(rows.pop_from(0), None);
1313            assert_eq!(rows.count, 0);
1314        }
1315    }
1316
1317    #[test]
1318    fn child_index_groups_every_read_under_its_value() {
1319        // A fixed linear congruential stream, so values repeat across functions.
1320        let mut state = 12345u64;
1321        let mut next = |bound: u64| {
1322            state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
1323            ((state >> 33) % bound) as u32
1324        };
1325        let reads: Vec<(Value, u32, u32)> = (0..2000)
1326            .map(|_| (Value::new_const(next(300)), next(5), next(400)))
1327            .collect();
1328        let index = ChildIndex::new(|| reads.iter().copied());
1329        let mut expected: HashMap<Value, Vec<(u32, u32)>> = HashMap::default();
1330        for &(value, function, row) in &reads {
1331            expected.entry(value).or_default().push((function, row));
1332        }
1333        for v in 0..310 {
1334            let value = Value::new_const(v);
1335            let mut got = index.readers(value).to_vec();
1336            got.sort_unstable();
1337            let mut want = expected.remove(&value).unwrap_or_default();
1338            want.sort_unstable();
1339            assert_eq!(got, want, "readers of {v}");
1340        }
1341        assert!(expected.is_empty());
1342        assert_eq!(index.readers.len(), reads.len());
1343        assert!(
1344            ChildIndex::new(std::iter::empty)
1345                .readers(Value::new_const(0))
1346                .is_empty()
1347        );
1348    }
1349
1350    #[test]
1351    fn dirty_rows_defer_marks_behind_the_cursor() {
1352        let mut rows = DirtyRows::full(130);
1353        for row in 0..130 {
1354            assert_eq!(rows.pop_from(row), Some(row));
1355        }
1356        rows.insert(63);
1357        rows.insert(129);
1358        rows.insert(129);
1359        assert_eq!(rows.count, 2);
1360        assert_eq!(rows.pop_from(0), Some(63));
1361        rows.insert(0);
1362        rows.insert(63);
1363        rows.insert(64);
1364        assert_eq!(rows.pop_from(64), Some(64));
1365        assert_eq!(rows.pop_from(65), Some(129));
1366        assert_eq!(rows.pop_from(130), None);
1367        assert_eq!(rows.count, 2);
1368        assert_eq!(rows.pop_from(0), Some(0));
1369        assert_eq!(rows.pop_from(1), Some(63));
1370        assert_eq!(rows.count, 0);
1371    }
1372}