Skip to main content

semi_persistent_egraph/
index.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Transient sorted indices for leapfrog triejoin, bulk-rebuilt from e-graph state.
4
5use crate::canon::{MSetCanon, VarCanon};
6use crate::config::EGraphConfig;
7use crate::containers::{DenseId, IndexLike};
8use crate::egraph::EGraph;
9use crate::literal::LitVal;
10use semi_persistent_containers::{DenseSpanMap, SpanArena};
11use std::collections::HashMap;
12
13/// Hasher for the statistics maps.
14///
15/// The index families themselves are no longer hashed: they are keyed by a
16/// dense integer and read by array index (see [`IndexStore`]). What is left
17/// hashed is per-operator bookkeeping, whose keys are dense op ids, and there
18/// std's default SipHash still buys DoS resistance no internal key needs.
19///
20/// foldhash rather than `rustc-hash` or a bespoke passthrough because it is
21/// already the workspace's hasher: hashbrown 0.17's default, hence what
22/// production `Map` and verified `SpMap` both hash with (see the note on
23/// `foldhash` in the workspace `Cargo.toml`). One hasher across the workspace is
24/// worth more than a marginal per-probe difference between the fast options.
25pub type FastMap<K, V> = HashMap<K, V, foldhash::fast::RandomState>;
26
27/// Cursor into a bucket slice: the **verified** galloping cursor from
28/// `containers-verus`, re-exported so this module's public surface is unchanged.
29///
30/// The seek is proven, not just tested: it lands on the first key `>= target`
31/// and skips no present key, for every slice and every target, with every slice
32/// index in bounds and no arithmetic overflow. The proof is stated against the
33/// same `seek_target_idx` spec function the verified B+tree cursor uses, which
34/// is what makes the two substitutable at the `SortedCursor` boundary.
35///
36/// See `containers-verus/doc/design/12-sorted-vec-cursor.md`. The algorithm and
37/// the `#[inline]` attributes match what this module previously defined inline;
38/// the erased build compiles the same doubling ladder and bounded bisection.
39pub use semi_persistent_containers::SortedVecCursor;
40
41/// Mean fan-out of each access path, measured on the nodes this index holds.
42///
43/// The scheduler charges a join by how many candidate nodes one probe yields.
44/// The three probe kinds can have very different distributions, so each is
45/// measured independently; chapter 20 states the model they feed.
46///
47/// Each number is the **size-biased** mean bucket size, `sum(b^2) / sum(b)`
48/// over the path's buckets, not the plain mean `sum(b) / count(b)`. A probe key
49/// is a variable the join bound from the data, so it lands in a bucket with
50/// probability proportional to that bucket's size: a class that is the child of
51/// a thousand nodes is probed a thousand times and a class that is the child of
52/// one is probed once. The plain mean answers "how big is a bucket picked at
53/// random", which no probe does, and on a distribution with one hub bucket of
54/// size H among K singletons it reports about 1 where the size-biased mean
55/// reports about H. This remains one number per path, so it prices the
56/// *expected* probe and not the individual one. Runtime atom scheduling reads
57/// concrete bucket lengths at execution; sampled cross-index selectivity
58/// replaces the expectation at plan time with the mean bucket selected by the
59/// emitter atom's own keys. See [`IndexSampler`].
60#[derive(Clone, Debug)]
61pub struct FanOuts<O> {
62    /// Nodes in the class a `ByRepr` probe lands in.
63    pub by_repr: f64,
64    /// Skew of each access path: size-biased mean over plain mean bucket size.
65    /// 1 on a flat distribution, about H*K/N on one hub bucket of size H among
66    /// K near-empty buckets. Drives per-rule scheduling-mode auto-selection
67    /// (`saturate::rule_skew`): a skewed path is where a per-round static atom
68    /// order is wrong for the bindings that hit the hub.
69    pub by_child_pos_skew: FastMap<(O, usize), f64>,
70    /// Skew counterpart of [`by_contains`](Self::by_contains).
71    pub by_contains_skew: FastMap<O, f64>,
72    /// `(op, position)` -> `op`-nodes in the bucket a `ByChildPos` probe lands
73    /// in, after its intersection with `by_op[op]`. Keyed per op because the
74    /// whole defect is that the two ops of one query differ here by three
75    /// orders of magnitude, and per position because an operator's arguments
76    /// are not drawn from the same classes.
77    pub by_child_pos: FastMap<(O, usize), f64>,
78    /// `op` -> variadic `op`-nodes in the bucket a `ByContains` probe lands in.
79    pub by_contains: FastMap<O, f64>,
80    /// Nodes the index holds, the denominator [`by_repr`](Self::by_repr) is a
81    /// fraction of.
82    pub nodes: usize,
83}
84
85impl<O> Default for FanOuts<O> {
86    fn default() -> Self {
87        Self {
88            by_repr: 1.0,
89            by_child_pos_skew: FastMap::default(),
90            by_contains_skew: FastMap::default(),
91            by_child_pos: FastMap::default(),
92            by_contains: FastMap::default(),
93            nodes: 0,
94        }
95    }
96}
97
98/// The `(key, value)` streams the four families are built from, kept alive
99/// across rounds.
100///
101/// A round builds a full index and, under semi-naive evaluation, a delta index;
102/// both are dropped at the end of the round. The streams are proportional to the
103/// node count and to the total arity, so allocating them per build would mean
104/// faulting in tens of megabytes eleven times over a saturation of
105/// `math-microbenchmark`. One scratch threaded through the round loop keeps the
106/// pages resident and the capacity at the high-water mark.
107///
108/// The stream buffers hold no state between builds: [`IndexStore::build_with`]
109/// clears them on entry, and the built [`DenseSpanMap`]s own copies of what they
110/// held. The **span arenas** are the opposite: they are kept precisely so their
111/// allocation and their generation stamp survive, and their leftover content is
112/// what the stamp invalidates.
113///
114/// Two index stores are alive at once under semi-naive evaluation (the full
115/// index and the round's delta), so the arenas are kept in two sets of four
116/// rather than one: a family's key space is stable across rounds, so pairing
117/// each family with its own arena keeps the table at the size that family needs
118/// instead of thrashing it between a 2 M-key and a 100-key build.
119///
120/// An arena is handed out by `IndexStore::build_from` and comes back through
121/// [`IndexStore::recycle_into`]. A caller that forgets to recycle loses only the
122/// reuse: the next build allocates a fresh arena and is correct, just slower.
123pub struct IndexScratch<Cfg: EGraphConfig> {
124    by_op: Vec<(usize, Cfg::G)>,
125    by_repr: Vec<(usize, Cfg::G)>,
126    by_child_pos: Vec<(usize, Cfg::G)>,
127    by_contains: Vec<(usize, Cfg::G)>,
128    /// Child classes already filed for the node being visited, so a variadic
129    /// node contributes each distinct child to `by_contains` once.
130    seen: Vec<Cfg::G>,
131    /// Span arenas for the full index's four families, indexed by
132    /// [`FAM_OP`]..[`FAM_CONTAINS`].
133    arenas_full: [Option<SpanArena>; 4],
134    /// Span arenas for the delta index's four families.
135    arenas_delta: [Option<SpanArena>; 4],
136}
137
138/// Family slots in [`IndexScratch`]'s arena arrays, in the order the build
139/// visits them.
140pub(crate) const FAM_OP: usize = 0;
141pub(crate) const FAM_REPR: usize = 1;
142pub(crate) const FAM_CHILD_POS: usize = 2;
143pub(crate) const FAM_CONTAINS: usize = 3;
144
145impl<Cfg: EGraphConfig> Default for IndexScratch<Cfg> {
146    fn default() -> Self {
147        Self::new()
148    }
149}
150
151impl<Cfg: EGraphConfig> IndexScratch<Cfg> {
152    pub fn new() -> Self {
153        Self {
154            by_op: Vec::new(),
155            by_repr: Vec::new(),
156            by_child_pos: Vec::new(),
157            by_contains: Vec::new(),
158            seen: Vec::new(),
159            arenas_full: [None, None, None, None],
160            arenas_delta: [None, None, None, None],
161        }
162    }
163
164    fn clear(&mut self) {
165        self.by_op.clear();
166        self.by_repr.clear();
167        self.by_child_pos.clear();
168        self.by_contains.clear();
169        self.seen.clear();
170    }
171
172    /// The arena for one family, or a fresh one the first time round.
173    fn take_arena(&mut self, full: bool, fam: usize) -> SpanArena {
174        let slot = if full {
175            &mut self.arenas_full[fam]
176        } else {
177            &mut self.arenas_delta[fam]
178        };
179        slot.take().unwrap_or_default()
180    }
181
182    /// Put a family's arena back for the next round to reuse.
183    fn put_arena(&mut self, full: bool, fam: usize, arena: SpanArena) {
184        let slot = if full {
185            &mut self.arenas_full[fam]
186        } else {
187            &mut self.arenas_delta[fam]
188        };
189        *slot = Some(arena);
190    }
191
192    /// Total span-table capacity held across all eight arenas, in entries.
193    ///
194    /// Read by `phase_timing` so the memory the reuse keeps resident is
195    /// reported rather than assumed; a recycled table is held for the whole run
196    /// where a per-build table was freed each round.
197    pub fn arena_capacity(&self) -> usize {
198        self.arenas_full
199            .iter()
200            .chain(self.arenas_delta.iter())
201            .filter_map(|a| a.as_ref())
202            .map(|a| a.capacity())
203            .sum()
204    }
205}
206
207/// All indices for leapfrog join, bulk-rebuilt after each e-graph rebuild.
208///
209/// Each family is a [`DenseSpanMap`]: one flat pool of node ids per family, plus
210/// a span table saying where each key's run starts and how long it is. Every key
211/// is a dense integer (an op id, a class id, or a `(position, class)` pair
212/// flattened into one), so a probe is an array index and a slice, not a hash and
213/// a pointer chase into a per-key `Vec`. The container's `refines()` pins each
214/// key's slice to the order-preserving filter of the build stream down to that
215/// key, which is what makes the two-pass counting build substitutable for the
216/// per-key push it replaces.
217pub struct IndexStore<Cfg: EGraphConfig> {
218    /// `by_op[op]` -> node ids with that operator, keyed by the op's dense id.
219    pub by_op: DenseSpanMap<Cfg::G>,
220    /// `by_repr[repr]` -> node ids in that e-class, keyed by the class
221    /// representative's id (see [`repr`](Self::repr) for which
222    /// canonicalization).
223    pub by_repr: DenseSpanMap<Cfg::G>,
224    /// `by_child_pos[pos * stride + child_repr]` -> parent node ids with
225    /// `child_repr` at `pos`.
226    ///
227    /// The two-dimensional key is flattened by `DenseSpanMap::composite_key`,
228    /// whose injectivity for a second component below the stride is
229    /// `lemma_composite_key_injective`. Position-major rather than class-major
230    /// so that one pattern position's keys are one contiguous run of the span
231    /// table, and so that the key is computable during the build's single walk:
232    /// the stride is the node bound, known before the walk, whereas the number
233    /// of distinct positions is only known after it.
234    ///
235    /// The position is [`Cfg::Index`](crate::config::EGraphConfig::Index)-wide: it is an
236    /// offset into one node's children, and a variadic node's children are a span in the
237    /// child pool, which that word already sizes. See [`IndexLookup::ByChildPos`].
238    ///
239    /// [`IndexLookup::ByChildPos`]: crate::schedule::IndexLookup::ByChildPos
240    pub by_child_pos: DenseSpanMap<Cfg::G>,
241    /// `by_contains[child_repr]` -> variadic parent node ids (A/AC/ACI/PlainN).
242    pub by_contains: DenseSpanMap<Cfg::G>,
243    /// Stride of the [`by_child_pos`](Self::by_child_pos) composite key: the
244    /// node bound this index was built at. A probe class at or above it belongs
245    /// to no bucket of this build and resolves to the empty slice, which is what
246    /// an absent key resolved to when the family was a hash map.
247    pub child_pos_stride: usize,
248    /// `repr[id]` — the class representative of every node id as of this build.
249    ///
250    /// The three keyed families above are keyed by *this* canonicalization, and
251    /// it stops being the e-graph's the moment the round's first rule merges a
252    /// class. A matcher that canonicalizes a lookup key with the live
253    /// union-find and then probes a bucket keyed at build time reads a bucket
254    /// that belongs to some other class, so the answer depends on which access
255    /// path the join order happened to use. Keeping the build's mapping makes
256    /// every access path agree; see [`round_repr`](Self::round_repr) and
257    /// chapter 09's snapshot contract.
258    ///
259    /// Filled by [`build`](Self::build) only. [`build_delta`](Self::build_delta)
260    /// leaves it empty: a delta is built in the same instant as its full index
261    /// and shares that index's canonicalization, so the mapping is stored once.
262    pub repr: Vec<Cfg::G>,
263    /// `op[id]` — the operator of every node id as of this build.
264    ///
265    /// A join that demotes its `ByOp` lookup to a per-candidate operator test
266    /// (`ematch::run_join`) reads this instead of [`EGraph::node_op`], which
267    /// resolves the routing table and then the arity-specific arena: two
268    /// dependent random loads over 10 MB and 20 MB against one over `4 ·
269    /// node_count` bytes. The build pays for it with a sequential pass, where
270    /// the same two loads stream.
271    ///
272    /// Filled by [`build`](Self::build) only, like [`repr`](Self::repr): the
273    /// delta's ids are a subset of the full index's, so one table serves both.
274    pub op: Vec<Cfg::O>,
275    /// Measured selectivity of each access path, read by the scheduler through
276    /// [`IndexStats::from_index`](crate::schedule::IndexStats::from_index).
277    ///
278    /// Filled by [`build`](Self::build) only, for the same reason as
279    /// [`repr`](Self::repr): a variant prices its delta atom by the delta's
280    /// cardinality against the full index's fan-outs, so measuring the delta's
281    /// own would buy nothing and cost a pass per round.
282    pub fanouts: FanOuts<Cfg::O>,
283}
284
285/// Build one family from its stream into a caller-owned span arena.
286///
287/// `num_keys` is the largest key the stream carries plus one, accumulated as the
288/// stream is written, so `try_build_in`'s range check cannot fail and the span
289/// table is no longer than the keys in use.
290///
291/// The arena is the recycled span table: it outlives the map built into it, and
292/// a build bumps its generation stamp and writes only the keys its stream
293/// carries, so a key an earlier build left behind carries an older stamp and
294/// reads as empty. With a sufficiently large retained table, ordinary work is
295/// proportional to the stream and occupied keys; growth writes missing key
296/// slots, and stamp exhaustion exceptionally clears the retained table. The
297/// container states stale-reads-empty in `build_in`'s ensures, so this caller
298/// performs no separate clear.
299fn build_family<G: DenseId>(
300    arena: SpanArena,
301    stream: &[(usize, G)],
302    num_keys: usize,
303) -> DenseSpanMap<G> {
304    DenseSpanMap::try_build_in(arena, stream, num_keys).unwrap_or_else(|_| {
305        panic!("num_keys is the stream's own key bound, accumulated as it was written")
306    })
307}
308
309/// Visit every key with at least one value.
310///
311/// Iterates the map's occupancy list rather than scanning `0..len()`, so the
312/// pass costs the occupied keys and not the key space — the last place the
313/// stamped build's `O(stream + occupied)` shape was not carried through to the
314/// consumer. `occupied_keys` ensures the list holds exactly the occupied keys
315/// and that every one of them is in range, and `lemma_occ_injective` that it
316/// holds each of them once, so this visits what the scan visited.
317///
318/// The order is first occurrence in the build stream rather than ascending key.
319/// Every caller here is a count or a sum over the buckets, so the order does not
320/// reach the result; a caller that needed ascending keys would have to sort.
321#[inline]
322fn for_each_occupied<G: DenseId>(m: &DenseSpanMap<G>, mut f: impl FnMut(usize, &[G])) {
323    for &k in m.occupied_keys() {
324        f(k, m.get(k));
325    }
326}
327
328/// Debug-only check that every bucket is ascending in node id.
329///
330/// The join relies on it: `SortedVecCursor::seek` is specified against a sorted
331/// slice, and `Difference`'s delta cursor and chapter 20's delta-suffix logic
332/// both assume a bucket is a monotone run. It holds by construction, because the
333/// build stream is written in ascending node id and `lemma_view_sorted` carries
334/// any ordering of the stream into every per-key slice: the slice *is* the
335/// stream's order-preserving filter. So this asserts the hypothesis of that
336/// lemma's conclusion rather than re-deriving it. Strictness additionally
337/// records that no node is filed under one key twice, which is what makes the
338/// per-bucket `dedup` this build no longer performs unnecessary.
339#[inline]
340fn debug_assert_id_sorted<G: DenseId>(m: &DenseSpanMap<G>, family: &str) {
341    #[cfg(debug_assertions)]
342    for_each_occupied(m, |k, b| {
343        debug_assert!(
344            b.windows(2).all(|w| w[0] < w[1]),
345            "{family}: bucket {k} is not strictly ascending in node id \
346             (lemma_view_sorted's hypothesis, the ascending build stream, was violated)"
347        );
348    });
349    #[cfg(not(debug_assertions))]
350    let _ = (m, family);
351}
352
353impl<Cfg: EGraphConfig> IndexStore<Cfg>
354where
355    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
356{
357    /// Bulk-rebuild all indices from the current e-graph state.
358    /// Call after `eg.rebuild()`.
359    ///
360    /// Allocates its own scratch; a caller that builds an index per round should
361    /// use [`build_with`](Self::build_with) and keep one.
362    pub fn build<L: LitVal, const TRACK: bool, const PROOFS: bool>(
363        eg: &EGraph<Cfg, L, TRACK, PROOFS>,
364    ) -> Self {
365        Self::build_with(eg, &mut IndexScratch::new())
366    }
367
368    /// [`build`](Self::build), reusing `scratch`'s stream buffers.
369    pub fn build_with<L: LitVal, const TRACK: bool, const PROOFS: bool>(
370        eg: &EGraph<Cfg, L, TRACK, PROOFS>,
371        scratch: &mut IndexScratch<Cfg>,
372    ) -> Self {
373        // `node_ids`, not a bare `from_usize` scan: the bound argument (every
374        // routing entry was minted through `TypedRouting::reserve`'s checked
375        // path) lives with `node_ids`; an inline scan here would restate the
376        // unchecked spelling without the justification.
377        Self::build_from(eg, eg.node_ids(), true, scratch)
378    }
379
380    /// Build the per-round **delta** index from the touched-node log: the
381    /// same four crosscutting families as [`build`](Self::build), but restricted
382    /// to the nodes that were created or recanonicalized this round.
383    ///
384    /// `touched` may contain duplicates (a node added then recanonicalized);
385    /// they are deduplicated here. Subsumed nodes are skipped, exactly as in
386    /// `build`, so for every key `k` the delta is a subset of the full
387    /// index's `k` bucket — `build_delta(eg, eg.touched())` ⊆ `build(eg)`.
388    pub fn build_delta<L: LitVal, const TRACK: bool, const PROOFS: bool>(
389        eg: &EGraph<Cfg, L, TRACK, PROOFS>,
390        touched: &[Cfg::G],
391    ) -> Self {
392        Self::build_delta_with(eg, touched, &mut IndexScratch::new())
393    }
394
395    /// [`build_delta`](Self::build_delta), reusing `scratch`'s stream buffers.
396    pub fn build_delta_with<L: LitVal, const TRACK: bool, const PROOFS: bool>(
397        eg: &EGraph<Cfg, L, TRACK, PROOFS>,
398        touched: &[Cfg::G],
399        scratch: &mut IndexScratch<Cfg>,
400    ) -> Self {
401        let ids: Vec<Cfg::G> = {
402            let _t = crate::phase_timing::Timer::start(crate::phase_timing::DELTA_DEDUP);
403            let mut ids: Vec<Cfg::G> = touched.to_vec();
404            ids.sort_unstable();
405            ids.dedup();
406            ids
407        };
408        Self::build_from(eg, ids.into_iter(), false, scratch)
409    }
410
411    /// Hand this store's four span arenas back to `scratch` for the next round.
412    ///
413    /// `full` says which set of slots they came from, which the caller knows
414    /// because it chose which build produced this store. Consuming `self` is
415    /// what makes the hand-back safe: the maps' pools and the arenas' span
416    /// tables are separate allocations, and only the arenas survive.
417    ///
418    /// Not calling this is a performance bug and not a correctness one — the
419    /// next build allocates a fresh arena — so it is deliberately an ordinary
420    /// method rather than a `Drop` impl, which could not name the scratch.
421    pub fn recycle_into(self, scratch: &mut IndexScratch<Cfg>, full: bool) {
422        scratch.put_arena(full, FAM_OP, self.by_op.recycle());
423        scratch.put_arena(full, FAM_REPR, self.by_repr.recycle());
424        scratch.put_arena(full, FAM_CHILD_POS, self.by_child_pos.recycle());
425        scratch.put_arena(full, FAM_CONTAINS, self.by_contains.recycle());
426    }
427
428    /// Shared bucketing core for [`build`](Self::build) and
429    /// [`build_delta`](Self::build_delta): stream the given node ids into the
430    /// four families' `(key, value)` buffers, then hand each buffer to the
431    /// container's two-pass counting build.
432    ///
433    /// Skips subsumed nodes. `full` additionally records the per-id
434    /// [`repr`](Self::repr) and [`op`](Self::op) tables and accumulates
435    /// [`FanOuts`], which only the full index needs; it is sound only for the
436    /// whole-graph id stream, whose ids arrive in ascending order with no gaps.
437    ///
438    /// Ids are visited in ascending order in both callers, because `node_ids()`
439    /// is ascending and `build_delta` sorts, so every family's stream is
440    /// ascending in its value and the container's filter refinement hands that
441    /// ordering to each bucket unchanged (see [`debug_assert_id_sorted`]).
442    fn build_from<L: LitVal, const TRACK: bool, const PROOFS: bool>(
443        eg: &EGraph<Cfg, L, TRACK, PROOFS>,
444        ids: impl Iterator<Item = Cfg::G>,
445        full: bool,
446        scratch: &mut IndexScratch<Cfg>,
447    ) -> Self {
448        scratch.clear();
449        // Stride of the `by_child_pos` composite key. Read before the walk,
450        // because the key must be computable as each child is visited.
451        let stride = eg.node_count();
452        let mut indexed = 0usize;
453
454        // Largest key each family's stream carries, plus one. Accumulated
455        // rather than assumed so the span tables are no longer than the keys in
456        // use: an op registry of 113 entries gets 113 spans, not one per node.
457        let (mut op_keys, mut repr_keys, mut cp_keys, mut ct_keys) = (0usize, 0, 0, 0);
458
459        // Per-id tables, filled only for the whole-graph stream. Both reads are
460        // made anyway for the bucketing below, so recording them here costs a
461        // push; a separate pass would repeat 1.2 M routing-table walks a round.
462        // A subsumed node is skipped for bucketing but still needs its slot, so
463        // the tables stay indexable by node id.
464        let mut repr_tab: Vec<Cfg::G> = Vec::new();
465        let mut op_tab: Vec<Cfg::O> = Vec::new();
466        if full {
467            repr_tab.reserve(eg.node_count());
468            op_tab.reserve(eg.node_count());
469        }
470
471        let (walk_slot, span_base) = if full {
472            (
473                crate::phase_timing::FULL_WALK,
474                crate::phase_timing::FULL_SPAN_OP,
475            )
476        } else {
477            (
478                crate::phase_timing::DELTA_WALK,
479                crate::phase_timing::DELTA_SPAN_OP,
480            )
481        };
482        let walk_timer = crate::phase_timing::Timer::start(walk_slot);
483
484        for gid in ids {
485            let op = eg.node_op(gid);
486            let repr = eg.class_repr(gid);
487            if full {
488                debug_assert_eq!(repr_tab.len(), gid.to_usize());
489                repr_tab.push(repr);
490                op_tab.push(op);
491            }
492            if eg.node_flags(gid) & crate::node_types::FLAG_SUBSUMED != 0 {
493                continue;
494            }
495
496            let ok = op.to_usize();
497            op_keys = op_keys.max(ok + 1);
498            scratch.by_op.push((ok, gid));
499            let rk = repr.to_usize();
500            repr_keys = repr_keys.max(rk + 1);
501            scratch.by_repr.push((rk, gid));
502            indexed += 1;
503
504            // The position counter is `Cfg::Index`-wide and checked. A variadic node's
505            // arity is a span in the child pool, so it is bounded by this word and by
506            // nothing narrower; as a `u32` this wrapped, and the child at position 2^32
507            // was filed in bucket 0, where a pattern written for the first argument
508            // would match it.
509            let arity = {
510                let cp = &mut scratch.by_child_pos;
511                let mut pos = <Cfg::Index as IndexLike>::min();
512                eg.for_each_child(gid, |child, _mult| {
513                    let child_repr = eg.class_repr(child).to_usize();
514                    let key =
515                        DenseSpanMap::<Cfg::G>::composite_key(pos.as_usize(), child_repr, stride)
516                            .expect("child class is below the node bound and the product fits");
517                    cp_keys = cp_keys.max(key + 1);
518                    cp.push((key, gid));
519                    pos = crate::containers::index_like::checked_incr(pos).expect(
520                        "node arity exceeds EGraphConfig::Index; configure a wider index word",
521                    );
522                })
523            };
524            // For variadic nodes (arity > 3 from PlainN/A/AC/ACI), also populate by_contains
525            if arity > 3
526                || matches!(
527                    eg.node_ref(gid),
528                    crate::typed_routing::NodeRef::Seq(_)
529                        | crate::typed_routing::NodeRef::MSet(_)
530                        | crate::typed_routing::NodeRef::Set(_)
531                        | crate::typed_routing::NodeRef::PlainN(_)
532                )
533            {
534                let seen = &mut scratch.seen;
535                let ct = &mut scratch.by_contains;
536                seen.clear(); // dedup within one node
537                eg.for_each_child(gid, |child, _mult| {
538                    let cr = eg.class_repr(child);
539                    if !seen.contains(&cr) {
540                        seen.push(cr);
541                        let k = cr.to_usize();
542                        ct_keys = ct_keys.max(k + 1);
543                        ct.push((k, gid));
544                    }
545                });
546            }
547        }
548
549        walk_timer.stop();
550
551        // Take all four arenas before the builds: each build borrows its stream
552        // out of the same scratch, so the mutable borrows have to be finished
553        // first.
554        let (a_op, a_repr, a_cp, a_ct) = (
555            scratch.take_arena(full, FAM_OP),
556            scratch.take_arena(full, FAM_REPR),
557            scratch.take_arena(full, FAM_CHILD_POS),
558            scratch.take_arena(full, FAM_CONTAINS),
559        );
560        let by_op = {
561            let _t = crate::phase_timing::Timer::start(span_base);
562            build_family(a_op, &scratch.by_op, op_keys)
563        };
564        let by_repr = {
565            let _t = crate::phase_timing::Timer::start(span_base + 1);
566            build_family(a_repr, &scratch.by_repr, repr_keys)
567        };
568        let by_child_pos = {
569            let _t = crate::phase_timing::Timer::start(span_base + 2);
570            build_family(a_cp, &scratch.by_child_pos, cp_keys)
571        };
572        let by_contains = {
573            let _t = crate::phase_timing::Timer::start(span_base + 3);
574            build_family(a_ct, &scratch.by_contains, ct_keys)
575        };
576        Self::record_shape(full, indexed, &by_child_pos);
577        debug_assert_id_sorted(&by_op, "by_op");
578        debug_assert_id_sorted(&by_repr, "by_repr");
579        debug_assert_id_sorted(&by_child_pos, "by_child_pos");
580        debug_assert_id_sorted(&by_contains, "by_contains");
581
582        let fanouts = if full {
583            let _t = crate::phase_timing::Timer::start(crate::phase_timing::FULL_FANOUTS);
584            Self::measure_fanouts(
585                &op_tab,
586                &by_repr,
587                &by_child_pos,
588                &by_contains,
589                stride,
590                indexed,
591            )
592        } else {
593            FanOuts::default()
594        };
595
596        Self {
597            by_op,
598            by_repr,
599            by_child_pos,
600            by_contains,
601            child_pos_stride: stride,
602            repr: repr_tab,
603            op: op_tab,
604            fanouts,
605        }
606    }
607
608    /// Record the `by_child_pos` key-space shape for `phase_timing`.
609    ///
610    /// The span table is dense over the composite key space, so its length is
611    /// what a build pays whether or not the keys occur, and the ratio of that
612    /// length to the values it addresses is the sparsity this measures. The
613    /// occupied-key count is a pass over the map's occupancy list, so the whole
614    /// helper is still skipped unless the accounting is switched on.
615    #[inline]
616    fn record_shape(full: bool, indexed: usize, by_child_pos: &DenseSpanMap<Cfg::G>) {
617        use crate::phase_timing as pt;
618        if !pt::enabled() {
619            return;
620        }
621        let (nodes, keys, values, nonempty) = if full {
622            (
623                pt::C_FULL_NODES,
624                pt::C_FULL_CP_KEYS,
625                pt::C_FULL_CP_VALUES,
626                pt::C_FULL_CP_NONEMPTY,
627            )
628        } else {
629            (
630                pt::C_DELTA_IDS,
631                pt::C_DELTA_CP_KEYS,
632                pt::C_DELTA_CP_VALUES,
633                pt::C_DELTA_CP_NONEMPTY,
634            )
635        };
636        pt::count(nodes, indexed as u64);
637        pt::count(keys, by_child_pos.len() as u64);
638        pt::count(values, by_child_pos.total() as u64);
639        let mut occupied = 0u64;
640        for_each_occupied(by_child_pos, |_, _| occupied += 1);
641        pt::count(nonempty, occupied);
642    }
643
644    /// Measure each access path's size-biased mean bucket size from the
645    /// finished families.
646    ///
647    /// One pass over the occupied keys of `by_child_pos` and `by_contains`,
648    /// tallying each bucket's parents by operator, because those two families
649    /// are keyed by child class
650    /// alone (`by_contains`) or by child class and position (`by_child_pos`)
651    /// while the join always intersects them with `by_op[op]`: the quantity the
652    /// scheduler needs is the bucket restricted to one operator, and on
653    /// `math-microbenchmark` the two operators of one query differ in it by
654    /// three orders of magnitude. The tally is an array indexed by the
655    /// operator's dense id, so a bucket costs one increment per parent and no
656    /// hashing.
657    ///
658    /// `by_repr`'s number reads no bucket entry: a size-biased mean over bucket
659    /// sizes is a sum of span lengths over the occupied keys.
660    ///
661    /// The operator of each bucket entry comes from `op_tab` — the [`op`](Self::op)
662    /// table this build just filled — rather than from `EGraph::node_op`: the
663    /// pass visits every bucket entry, which is several times the node count.
664    fn measure_fanouts(
665        op_tab: &[Cfg::O],
666        by_repr: &DenseSpanMap<Cfg::G>,
667        by_child_pos: &DenseSpanMap<Cfg::G>,
668        by_contains: &DenseSpanMap<Cfg::G>,
669        stride: usize,
670        indexed: usize,
671    ) -> FanOuts<Cfg::O> {
672        // (sum of bucket sizes, sum of their squares, bucket count) per key set.
673        let mut cp: FastMap<(Cfg::O, usize), (u128, u128, u128)> = FastMap::default();
674        let mut ct: FastMap<Cfg::O, (u128, u128, u128)> = FastMap::default();
675        // Indexed by the operator's dense id, grown on demand rather than sized
676        // from the registry: the registry exposes no count, and the ids that
677        // occur here are exactly the ones the buckets hold.
678        // u64, not u32: a bucket's per-op count is bounded by the node count,
679        // which the 63-bit configuration allows past 2^32.
680        let mut tally: Vec<u64> = Vec::new();
681        let mut touched: Vec<usize> = Vec::new();
682
683        let tally_bucket = |bucket: &[Cfg::G], tally: &mut Vec<u64>, touched: &mut Vec<usize>| {
684            touched.clear();
685            for &gid in bucket {
686                let o = op_tab[gid.to_usize()].to_usize();
687                if o >= tally.len() {
688                    tally.resize(o + 1, 0);
689                }
690                if tally[o] == 0 {
691                    touched.push(o);
692                }
693                tally[o] += 1;
694            }
695        };
696
697        for_each_occupied(by_child_pos, |k, bucket| {
698            // Position-major key: the position is the quotient, and `stride` is
699            // nonzero because a non-empty bucket means the graph has a node.
700            let pos = k / stride;
701            tally_bucket(bucket, &mut tally, &mut touched);
702            for &o in touched.iter() {
703                let c = u128::from(tally[o]);
704                let e = cp.entry((Cfg::O::from_usize(o), pos)).or_insert((0, 0, 0));
705                e.0 += c;
706                e.1 += c * c;
707                e.2 += 1;
708                tally[o] = 0;
709            }
710        });
711        for_each_occupied(by_contains, |_, bucket| {
712            tally_bucket(bucket, &mut tally, &mut touched);
713            for &o in touched.iter() {
714                let c = u128::from(tally[o]);
715                let e = ct.entry(Cfg::O::from_usize(o)).or_insert((0, 0, 0));
716                e.0 += c;
717                e.1 += c * c;
718                e.2 += 1;
719                tally[o] = 0;
720            }
721        });
722
723        let biased = |(sum, sq, _): &(u128, u128, u128)| -> f64 {
724            if *sum == 0 {
725                1.0
726            } else {
727                *sq as f64 / *sum as f64
728            }
729        };
730        // Skew = size-biased mean / plain mean = sq * count / sum^2.
731        let skew = |(sum, sq, count): &(u128, u128, u128)| -> f64 {
732            if *sum == 0 {
733                1.0
734            } else {
735                (*sq as f64 * *count as f64) / (*sum as f64 * *sum as f64)
736            }
737        };
738        let (mut class_sum, mut class_sq) = (0u128, 0u128);
739        for_each_occupied(by_repr, |_, b| {
740            let c = b.len() as u128;
741            class_sum += c;
742            class_sq += c * c;
743        });
744
745        FanOuts {
746            by_repr: biased(&(class_sum, class_sq, 0)),
747            by_child_pos_skew: cp.iter().map(|(&k, v)| (k, skew(v))).collect(),
748            by_contains_skew: ct.iter().map(|(&k, v)| (k, skew(v))).collect(),
749            by_child_pos: cp.iter().map(|(&k, v)| (k, biased(v))).collect(),
750            by_contains: ct.iter().map(|(&k, v)| (k, biased(v))).collect(),
751            nodes: indexed,
752        }
753    }
754
755    /// This build's class representative for `id`, or `None` for an id minted
756    /// after the build (and so present in no bucket) or on a delta store, which
757    /// defers the mapping to its full index.
758    #[inline]
759    pub fn round_repr(&self, id: Cfg::G) -> Option<Cfg::G> {
760        self.repr.get(id.to_usize()).copied()
761    }
762
763    /// The operator of `id` as of this build, or `None` when the table is not
764    /// filled (a delta store) or `id` postdates the build. See [`op`](Self::op).
765    #[inline]
766    pub fn round_op(&self, id: Cfg::G) -> Option<Cfg::O> {
767        self.op.get(id.to_usize()).copied()
768    }
769
770    /// Nodes with the given operator; empty when the operator files no node.
771    #[inline]
772    pub fn nodes_by_op(&self, op: Cfg::O) -> &[Cfg::G] {
773        self.by_op.try_get(op.to_usize()).unwrap_or(&[])
774    }
775
776    /// Nodes in the given e-class, as this build canonicalized it.
777    #[inline]
778    pub fn nodes_by_repr(&self, repr: Cfg::G) -> &[Cfg::G] {
779        self.by_repr.try_get(repr.to_usize()).unwrap_or(&[])
780    }
781
782    /// Parent nodes that have `child_repr` at position `pos`.
783    ///
784    /// A class at or above the stride, or a position past the deepest one this
785    /// build saw, names no key of the span table and yields the empty slice: the
786    /// same answer the hash-map family gave for a key it had never inserted.
787    #[inline]
788    pub fn nodes_by_child_pos(&self, child_repr: Cfg::G, pos: Cfg::Index) -> &[Cfg::G] {
789        match DenseSpanMap::<Cfg::G>::composite_key(
790            pos.as_usize(),
791            child_repr.to_usize(),
792            self.child_pos_stride,
793        ) {
794            Some(k) => self.by_child_pos.try_get(k).unwrap_or(&[]),
795            None => &[],
796        }
797    }
798
799    /// Variadic nodes containing `child_repr`.
800    #[inline]
801    pub fn nodes_by_contains(&self, child_repr: Cfg::G) -> &[Cfg::G] {
802        self.by_contains
803            .try_get(child_repr.to_usize())
804            .unwrap_or(&[])
805    }
806
807    /// Get an iterator over nodes with the given operator.
808    pub fn iter_by_op(&self, op: Cfg::O) -> SortedVecCursor<'_, Cfg::G> {
809        SortedVecCursor::new(self.nodes_by_op(op))
810    }
811
812    /// Get an iterator over nodes in the given e-class.
813    pub fn iter_by_repr(&self, repr: Cfg::G) -> SortedVecCursor<'_, Cfg::G> {
814        SortedVecCursor::new(self.nodes_by_repr(repr))
815    }
816
817    /// Get an iterator over parent nodes that have `child_repr` at position `pos`.
818    pub fn iter_by_child_pos(
819        &self,
820        child_repr: Cfg::G,
821        pos: Cfg::Index,
822    ) -> SortedVecCursor<'_, Cfg::G> {
823        SortedVecCursor::new(self.nodes_by_child_pos(child_repr, pos))
824    }
825
826    /// Get an iterator over variadic nodes containing `child_repr`.
827    pub fn iter_by_contains(&self, child_repr: Cfg::G) -> SortedVecCursor<'_, Cfg::G> {
828        SortedVecCursor::new(self.nodes_by_contains(child_repr))
829    }
830
831    /// Per-operator driver-scan cardinalities, for
832    /// [`IndexStats`](crate::schedule::IndexStats).
833    ///
834    /// Only operators that file at least one node are listed, so an absent
835    /// operator stays absent rather than arriving with a zero, which is the
836    /// distinction the cost model's `or_else` chain reads.
837    pub fn op_cardinalities(&self) -> impl Iterator<Item = (Cfg::O, usize)> + '_ {
838        (0..self.by_op.len()).filter_map(|k| {
839            let n = self.by_op.key_len(k);
840            (n > 0).then(|| (Cfg::O::from_usize(k), n))
841        })
842    }
843}
844
845// ---------------------------------------------------------------------------
846// Semi-naive: per-variant index view
847// ---------------------------------------------------------------------------
848
849/// Which slice an atom reads, in a given semi-naive variant.
850#[derive(Clone, Copy, PartialEq, Eq, Debug)]
851pub enum IndexMode {
852    /// Read the full index (naive, or an atom after the delta atom).
853    Full,
854    /// Read the delta index (the variant's delta atom).
855    Delta,
856    /// Read full minus delta (an atom before the delta atom — "old only").
857    FullMinusDelta,
858}
859
860/// The context one semi-naive variant needs: the full and delta indices,
861/// and which atom (by stable `atom_id`) is the delta-restricted one.
862///
863/// Not a new abstraction — just the bundle the matcher needs in place of a
864/// bare `&IndexStore`. A `delta_atom` of `None` is the **naive** view: every
865/// atom reads `full` (and `delta` is never consulted).
866pub struct VariantIndex<'a, Cfg: EGraphConfig> {
867    pub full: &'a IndexStore<Cfg>,
868    pub delta: &'a IndexStore<Cfg>,
869    pub delta_atom: Option<usize>,
870}
871
872// Hand-written rather than derived: a derive would bound `Cfg: Clone`, and the
873// view is three references whatever `Cfg` is.
874impl<Cfg: EGraphConfig> Clone for VariantIndex<'_, Cfg> {
875    fn clone(&self) -> Self {
876        *self
877    }
878}
879impl<Cfg: EGraphConfig> Copy for VariantIndex<'_, Cfg> {}
880
881impl<'a, Cfg: EGraphConfig> VariantIndex<'a, Cfg> {
882    /// Naive view: every atom reads `full`. `delta` is aliased to `full` and
883    /// never read (mode is always `Full`).
884    pub fn naive(full: &'a IndexStore<Cfg>) -> Self {
885        Self {
886            full,
887            delta: full,
888            delta_atom: None,
889        }
890    }
891
892    /// Variant `i`: atom `i` reads delta, atoms `< i` read full∖delta, atoms
893    /// `> i` read full.
894    pub fn variant(
895        full: &'a IndexStore<Cfg>,
896        delta: &'a IndexStore<Cfg>,
897        delta_atom: usize,
898    ) -> Self {
899        Self {
900            full,
901            delta,
902            delta_atom: Some(delta_atom),
903        }
904    }
905
906    /// Mode for an atom given its stable `atom_id`. Independent of the
907    /// scheduler's execution order — purely a function of the numbering.
908    #[inline]
909    pub fn mode(&self, atom_id: usize) -> IndexMode {
910        match self.delta_atom {
911            None => IndexMode::Full,
912            Some(i) if atom_id == i => IndexMode::Delta,
913            Some(i) if atom_id < i => IndexMode::FullMinusDelta,
914            Some(_) => IndexMode::Full,
915        }
916    }
917}
918
919// ---------------------------------------------------------------------------
920// Plan-time sampling
921// ---------------------------------------------------------------------------
922
923/// Entries of a bucket read to estimate its operator-restricted length.
924///
925/// `by_child_pos` and `by_contains` are keyed by child class while every
926/// join intersects them with `by_op[op]`, so the length the scheduler needs is
927/// the bucket restricted to one operator — the same quantity
928/// [`IndexStore::measure_fanouts`] tallies, and for the same reason: the two
929/// operators of one query differ in it by three orders of magnitude. Counting
930/// it exactly is a pass over the bucket, which on a hub class is hundreds of
931/// thousands of loads for one sampled key. Past this many entries the count is
932/// taken over an evenly-strided subsample of the bucket and scaled back up,
933/// which is the estimator the emitter draw already is, applied once more.
934const PROBE_SCAN_CAP: usize = 256;
935
936/// [`CrossSampler`] over one round's indices: the implementation the scheduler
937/// gets its samples from.
938///
939/// Emitter draws come from the slice the atom's semi-naive mode reads, which is
940/// the relation it will actually enumerate. Probe buckets come from the full
941/// index in every mode, matching [`FanOuts`], which the full build measures and
942/// every variant prices against: a variant's delta shows up in the atom's base
943/// cardinality, and applying it again to the probe would charge it twice.
944///
945/// [`CrossSampler`]: crate::schedule::CrossSampler
946pub struct IndexSampler<'a, Cfg: EGraphConfig, L: LitVal, const TRACK: bool, const PROOFS: bool> {
947    eg: &'a EGraph<Cfg, L, TRACK, PROOFS>,
948    index: VariantIndex<'a, Cfg>,
949}
950
951impl<'a, Cfg: EGraphConfig, L: LitVal, const TRACK: bool, const PROOFS: bool>
952    IndexSampler<'a, Cfg, L, TRACK, PROOFS>
953where
954    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
955{
956    pub fn new(eg: &'a EGraph<Cfg, L, TRACK, PROOFS>, index: VariantIndex<'a, Cfg>) -> Self {
957        Self { eg, index }
958    }
959
960    /// The class of `id` as the round's buckets are keyed, mirroring
961    /// `ematch::canon`: the build's mapping where it has one, the live
962    /// union-find for an id minted after the build.
963    #[inline]
964    fn canon(&self, id: Cfg::G) -> Cfg::G {
965        match self.index.full.round_repr(id) {
966            Some(r) => r,
967            None => self.eg.find_const(id),
968        }
969    }
970
971    /// Nodes of `op` in `bucket`, exactly when the bucket is short enough and
972    /// by a strided subsample scaled to the bucket's length when it is not.
973    fn op_restricted(&self, s: &[Cfg::G], op: Cfg::O) -> usize {
974        let n = s.len();
975        let op_tab = &self.index.full.op;
976        let hits = |g: &Cfg::G| op_tab.get(g.to_usize()).is_some_and(|&o| o == op);
977        if n <= PROBE_SCAN_CAP {
978            return s.iter().filter(|g| hits(g)).count();
979        }
980        let seen = (0..PROBE_SCAN_CAP)
981            .filter(|j| hits(&s[j * n / PROBE_SCAN_CAP]))
982            .count();
983        seen * n / PROBE_SCAN_CAP
984    }
985}
986
987impl<Cfg: EGraphConfig, L: LitVal, const TRACK: bool, const PROOFS: bool>
988    crate::schedule::CrossSampler<Cfg::O> for IndexSampler<'_, Cfg, L, TRACK, PROOFS>
989where
990    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
991{
992    fn driver_sample(&self, atom_id: usize, op: Cfg::O, k: usize, out: &mut Vec<usize>) {
993        out.clear();
994        // `FullMinusDelta` draws from the full side, an upper bound on
995        // `full ∖ delta`, for the reason `ematch::cursor_len` gives: a tighter
996        // draw would cost the overlap, which is the work being priced.
997        let store = match self.index.mode(atom_id) {
998            IndexMode::Delta => self.index.delta,
999            IndexMode::Full | IndexMode::FullMinusDelta => self.index.full,
1000        };
1001        let s = store.nodes_by_op(op);
1002        let n = s.len();
1003        if n == 0 || k == 0 {
1004            return;
1005        }
1006        let take = k.min(n);
1007        out.extend((0..take).map(|j| s[j * n / take].to_usize()));
1008    }
1009
1010    fn key_classes(&self, node: usize, site: crate::schedule::KeySite, out: &mut Vec<usize>) {
1011        use crate::schedule::KeySite;
1012        let g = Cfg::G::from_usize(node);
1013        match site {
1014            KeySite::Node => out.push(self.canon(g).to_usize()),
1015            // Read through `for_each_child` with a position counter, the same
1016            // walk `IndexStore::build_from` keys `by_child_pos` with, rather
1017            // than `EGraph::child_at`, which panics on a multiset node.
1018            KeySite::Child(pos) => {
1019                let mut i = 0usize;
1020                self.eg.for_each_child(g, |c, _| {
1021                    if i == pos {
1022                        out.push(self.canon(c).to_usize());
1023                    }
1024                    i += 1;
1025                });
1026            }
1027            KeySite::Element => {
1028                self.eg.for_each_child(g, |c, _| {
1029                    let cr = self.canon(c).to_usize();
1030                    if !out.contains(&cr) {
1031                        out.push(cr);
1032                    }
1033                });
1034            }
1035        }
1036    }
1037
1038    fn probe_len(&self, class: usize, path: crate::schedule::ProbePath, op: Cfg::O) -> usize {
1039        use crate::schedule::ProbePath;
1040        let c = Cfg::G::from_usize(class);
1041        let bucket = match path {
1042            ProbePath::ChildPos(pos) => {
1043                let Some(p) = <Cfg::Index as IndexLike>::try_from_usize(pos) else {
1044                    return 0;
1045                };
1046                self.index.full.nodes_by_child_pos(c, p)
1047            }
1048            ProbePath::Contains => self.index.full.nodes_by_contains(c),
1049        };
1050        self.op_restricted(bucket, op)
1051    }
1052}
1053
1054#[cfg(test)]
1055mod tests {
1056    use super::*;
1057    // The inherent cursor `step` is now crate-private in containers-verus
1058    // (it shadowed this guarded trait impl); tests step through the trait.
1059    use crate::egraph::EGraph31;
1060    use crate::leapfrog::SortedCursor;
1061    use crate::literal::NiraLitVal;
1062
1063    #[test]
1064    fn by_op_index() {
1065        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1066        let int = eg.intern_sort("Int");
1067        let f = eg.register_op1("f", int, int);
1068        let g = eg.register_op1("g", int, int);
1069        let x_op = eg.register_op0("x", int);
1070
1071        let x = eg.add(x_op, &[]);
1072        let fx = eg.add(f, &[x]);
1073        let gx = eg.add(g, &[x]);
1074        let ffx = eg.add(f, &[fx]);
1075
1076        let idx = IndexStore::build(&eg);
1077
1078        // Two f-nodes: fx, ffx
1079        let f_nodes = idx.nodes_by_op(f);
1080        assert_eq!(f_nodes.len(), 2);
1081        assert!(f_nodes.contains(&fx));
1082        assert!(f_nodes.contains(&ffx));
1083
1084        // One g-node
1085        assert_eq!(idx.nodes_by_op(g).len(), 1);
1086        assert!(idx.nodes_by_op(g).contains(&gx));
1087
1088        // One x-node
1089        assert_eq!(idx.nodes_by_op(x_op).len(), 1);
1090    }
1091
1092    #[test]
1093    fn by_repr_after_merge() {
1094        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1095        let int = eg.intern_sort("Int");
1096        let x_op = eg.register_op0("x", int);
1097        let y_op = eg.register_op0("y", int);
1098
1099        let x = eg.add(x_op, &[]);
1100        let y = eg.add(y_op, &[]);
1101        eg.merge(x, y);
1102        eg.rebuild();
1103
1104        let idx = IndexStore::build(&eg);
1105        let repr = eg.class_repr(x);
1106        let class_nodes = idx.nodes_by_repr(repr);
1107        assert_eq!(class_nodes.len(), 2);
1108    }
1109
1110    #[test]
1111    fn by_child_pos_index() {
1112        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1113        let int = eg.intern_sort("Int");
1114        let f = eg.register_op1("f", int, int);
1115        let g = eg.register_op2("g", int, int, int);
1116        let x_op = eg.register_op0("x", int);
1117        let y_op = eg.register_op0("y", int);
1118
1119        let x = eg.add(x_op, &[]);
1120        let y = eg.add(y_op, &[]);
1121        let fx = eg.add(f, &[x]);
1122        let gxy = eg.add(g, &[x, y]);
1123
1124        let idx = IndexStore::build(&eg);
1125
1126        // x is child at pos 0 of both fx and gxy
1127        let parents_x_0 = idx.nodes_by_child_pos(x, 0);
1128        assert_eq!(parents_x_0.len(), 2);
1129        assert!(parents_x_0.contains(&fx));
1130        assert!(parents_x_0.contains(&gxy));
1131
1132        // y is child at pos 1 of gxy only
1133        let parents_y_1 = idx.nodes_by_child_pos(y, 1);
1134        assert_eq!(parents_y_1.len(), 1);
1135        assert!(parents_y_1.contains(&gxy));
1136    }
1137
1138    #[test]
1139    fn seek_and_step() {
1140        let data = vec![
1141            crate::id::ENodeId::from_usize(2),
1142            crate::id::ENodeId::from_usize(5),
1143            crate::id::ENodeId::from_usize(8),
1144            crate::id::ENodeId::from_usize(12),
1145        ];
1146        let mut it = SortedVecCursor::new(&data);
1147        assert!(it.is_valid());
1148        assert_eq!(it.key().to_usize(), 2);
1149
1150        it.seek(crate::id::ENodeId::from_usize(5));
1151        assert_eq!(it.key().to_usize(), 5);
1152
1153        it.seek(crate::id::ENodeId::from_usize(7));
1154        assert_eq!(it.key().to_usize(), 8);
1155
1156        it.step();
1157        assert_eq!(it.key().to_usize(), 12);
1158
1159        it.step();
1160        assert!(!it.is_valid());
1161    }
1162
1163    /// Property tests for the galloping `seek` (perf doc E7).
1164    ///
1165    /// `seek` is the one place in the join layer that does index arithmetic —
1166    /// a doubling ladder, a `min`, and a bisection over a computed window — so
1167    /// it is the one place an off-by-one silently drops join results instead of
1168    /// panicking. These pin the four properties the join relies on:
1169    ///
1170    /// 1. **Correctness**: `seek(t)` lands on the first key ≥ `t`, or exhausts.
1171    /// 2. **Monotonicity**: `pos` never decreases, so leapfrog's forward-only
1172    ///    contract holds and `Difference`'s delta cursor cannot rewind.
1173    /// 3. **No skipping**: stepping through a cursor after any seek sequence
1174    ///    yields exactly the tail of the data, in order — nothing is jumped over.
1175    /// 4. **In-bounds**: `pos` stays ≤ `len`, and no index arithmetic overflows,
1176    ///    including on the widest ids and on empty slices.
1177    ///
1178    /// Both id widths are covered, since `ENodeId` is 31-bit and `ENodeId64` is
1179    /// 63-bit and the bisection arithmetic is over `usize`.
1180    mod seek_props {
1181        use super::*;
1182        use crate::containers::DenseId;
1183        use proptest::prelude::*;
1184
1185        /// A sorted, duplicate-free key vector: the shape of every bucket the
1186        /// build produces, `IndexStore::build_from` streams ids in ascending order
1187        /// and files each id under a key at most once, and the container's filter
1188        /// refinement hands that order to the bucket.
1189        fn sorted_unique() -> impl Strategy<Value = Vec<usize>> {
1190            proptest::collection::vec(0usize..200, 0..64).prop_map(|mut v| {
1191                v.sort_unstable();
1192                v.dedup();
1193                v
1194            })
1195        }
1196
1197        /// Targets drawn from beyond the data's range as well as inside it, so
1198        /// the "no such key" path and the `hi = n` clamp are both hit.
1199        fn targets() -> impl Strategy<Value = Vec<usize>> {
1200            proptest::collection::vec(0usize..220, 0..16)
1201        }
1202
1203        /// The reference implementation: linear scan from the cursor.
1204        fn expected_pos(data: &[usize], from: usize, target: usize) -> usize {
1205            let mut p = from;
1206            while p < data.len() && data[p] < target {
1207                p += 1;
1208            }
1209            p
1210        }
1211
1212        fn run_seek_lands_on_first_ge<G: DenseId>(vals: &[usize], ts: &[usize]) {
1213            let data: Vec<G> = vals.iter().map(|&v| G::from_usize(v)).collect();
1214            for &t in ts {
1215                let mut c = SortedVecCursor::new(&data);
1216                c.seek(G::from_usize(t));
1217                assert_eq!(
1218                    c.pos(),
1219                    expected_pos(vals, 0, t),
1220                    "seek({t}) on {vals:?} landed at {}",
1221                    c.pos()
1222                );
1223                if c.is_valid() {
1224                    assert!(c.key().to_usize() >= t, "landed below target");
1225                    // First such key: the predecessor must be strictly below.
1226                    if c.pos() > 0 {
1227                        assert!(vals[c.pos() - 1] < t, "skipped a key ≥ target");
1228                    }
1229                }
1230            }
1231        }
1232
1233        fn run_seek_sequence_is_monotone<G: DenseId>(vals: &[usize], ts: &[usize]) {
1234            let data: Vec<G> = vals.iter().map(|&v| G::from_usize(v)).collect();
1235            let mut c = SortedVecCursor::new(&data);
1236            let mut prev = c.pos();
1237            let mut from = 0usize;
1238            for &t in ts {
1239                c.seek(G::from_usize(t));
1240                assert!(c.pos() >= prev, "pos went backwards: {prev} -> {}", c.pos());
1241                assert!(c.pos() <= data.len(), "pos {} out of bounds", c.pos());
1242                // Against the linear reference, from wherever the cursor was.
1243                assert_eq!(
1244                    c.pos(),
1245                    expected_pos(vals, from, t),
1246                    "seek({t}) mid-sequence"
1247                );
1248                prev = c.pos();
1249                from = c.pos();
1250            }
1251        }
1252
1253        /// Interleave seeks and steps, then drain: the keys observed must be
1254        /// exactly the surviving tail of `vals`, with nothing skipped and
1255        /// nothing repeated.
1256        fn run_no_keys_are_skipped<G: DenseId>(vals: &[usize], ops: &[(bool, usize)]) {
1257            let data: Vec<G> = vals.iter().map(|&v| G::from_usize(v)).collect();
1258            let mut c = SortedVecCursor::new(&data);
1259            let mut model = 0usize;
1260
1261            for &(is_seek, arg) in ops {
1262                if is_seek {
1263                    c.seek(G::from_usize(arg));
1264                    model = expected_pos(vals, model, arg);
1265                } else if c.is_valid() {
1266                    c.step();
1267                    model += 1;
1268                }
1269                assert_eq!(c.pos(), model, "cursor diverged from the model");
1270            }
1271
1272            // Draining from here must yield exactly vals[model..].
1273            let mut seen = Vec::new();
1274            while c.is_valid() {
1275                seen.push(c.key().to_usize());
1276                c.step();
1277            }
1278            assert_eq!(seen, vals[model.min(vals.len())..], "tail mismatch");
1279        }
1280
1281        proptest! {
1282            #![proptest_config(ProptestConfig::with_cases(2000))]
1283
1284            #[test]
1285            fn seek_lands_on_first_ge_31(vals in sorted_unique(), ts in targets()) {
1286                run_seek_lands_on_first_ge::<crate::id::ENodeId>(&vals, &ts);
1287            }
1288
1289            #[test]
1290            fn seek_lands_on_first_ge_63(vals in sorted_unique(), ts in targets()) {
1291                run_seek_lands_on_first_ge::<crate::nodes::ENodeId64>(&vals, &ts);
1292            }
1293
1294            #[test]
1295            fn seek_sequence_is_monotone_31(vals in sorted_unique(), ts in targets()) {
1296                run_seek_sequence_is_monotone::<crate::id::ENodeId>(&vals, &ts);
1297            }
1298
1299            #[test]
1300            fn seek_sequence_is_monotone_63(vals in sorted_unique(), ts in targets()) {
1301                run_seek_sequence_is_monotone::<crate::nodes::ENodeId64>(&vals, &ts);
1302            }
1303
1304            #[test]
1305            fn no_keys_are_skipped_31(
1306                vals in sorted_unique(),
1307                ops in proptest::collection::vec((any::<bool>(), 0usize..220), 0..24),
1308            ) {
1309                run_no_keys_are_skipped::<crate::id::ENodeId>(&vals, &ops);
1310            }
1311
1312            #[test]
1313            fn no_keys_are_skipped_63(
1314                vals in sorted_unique(),
1315                ops in proptest::collection::vec((any::<bool>(), 0usize..220), 0..24),
1316            ) {
1317                run_no_keys_are_skipped::<crate::nodes::ENodeId64>(&vals, &ops);
1318            }
1319        }
1320
1321        /// The gallop ladder doubles `step` without bound and computes
1322        /// `lo + step`, so a long run of misses on a large slice is where an
1323        /// overflow would live. 4096 keys forces ~12 doublings.
1324        #[test]
1325        fn long_gallop_does_not_overflow() {
1326            let data: Vec<crate::id::ENodeId> = (0..4096)
1327                .map(|i| crate::id::ENodeId::from_usize(i * 2))
1328                .collect();
1329            let mut c = SortedVecCursor::new(&data);
1330            // Target past every key: the ladder runs to the end and clamps.
1331            c.seek(crate::id::ENodeId::from_usize(100_000));
1332            assert_eq!(c.pos(), data.len());
1333            assert!(!c.is_valid());
1334
1335            // And a target reachable only after a full-length gallop.
1336            let mut c = SortedVecCursor::new(&data);
1337            c.seek(crate::id::ENodeId::from_usize(8190));
1338            assert_eq!(c.key().to_usize(), 8190);
1339        }
1340
1341        /// Degenerate shapes, each of which exercises a different early exit.
1342        #[test]
1343        fn edge_shapes() {
1344            let empty: [crate::id::ENodeId; 0] = [];
1345            let mut c = SortedVecCursor::new(&empty);
1346            c.seek(crate::id::ENodeId::from_usize(7));
1347            assert_eq!(c.pos(), 0);
1348            assert!(!c.is_valid());
1349
1350            let one = [crate::id::ENodeId::from_usize(5)];
1351            for (t, want) in [(0usize, 0usize), (5, 0), (6, 1)] {
1352                let mut c = SortedVecCursor::new(&one);
1353                c.seek(crate::id::ENodeId::from_usize(t));
1354                assert_eq!(c.pos(), want, "single-element seek({t})");
1355            }
1356
1357            // Seeking on an already-exhausted cursor is a no-op, not a panic.
1358            let mut c = SortedVecCursor::new(&one);
1359            c.step();
1360            assert!(!c.is_valid());
1361            c.seek(crate::id::ENodeId::from_usize(0));
1362            assert_eq!(c.pos(), 1);
1363            c.seek(crate::id::ENodeId::from_usize(99));
1364            assert_eq!(c.pos(), 1);
1365        }
1366
1367        /// The largest id each width admits, seeked to and past. `from_usize` is
1368        /// the id's own constructor, so this is the top of its representable
1369        /// range rather than an arbitrary large number.
1370        #[test]
1371        fn saturated_ids() {
1372            fn run<G: DenseId>(max: usize) {
1373                let data: Vec<G> = [max - 2, max - 1, max]
1374                    .iter()
1375                    .map(|&v| G::from_usize(v))
1376                    .collect();
1377                let mut c = SortedVecCursor::new(&data);
1378                c.seek(G::from_usize(max));
1379                assert_eq!(c.pos(), 2);
1380                assert_eq!(c.key().to_usize(), max);
1381                c.step();
1382                assert!(!c.is_valid());
1383
1384                let mut c = SortedVecCursor::new(&data);
1385                c.seek(G::from_usize(max - 1));
1386                assert_eq!(c.key().to_usize(), max - 1);
1387            }
1388            run::<crate::id::ENodeId>((1usize << 31) - 1);
1389            run::<crate::nodes::ENodeId64>((1usize << 63) - 1);
1390        }
1391    }
1392
1393    /// The `by_child_pos` key is `position * stride + class`, flattened by
1394    /// `DenseSpanMap::composite_key`; `lemma_composite_key_injective` is why a
1395    /// parent filed at one position never surfaces in another position's
1396    /// bucket. A wide node stretches the key space past the binary ops beside
1397    /// it, which is where a stride mistake would show, and the two negative
1398    /// cases are the ones an absent hash-map key used to cover: a position
1399    /// deeper than any node has, and a class at or above the build's node bound.
1400    #[test]
1401    fn child_pos_key_separates_positions_and_absent_keys() {
1402        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1403        let int = eg.intern_sort("Int");
1404        let wide = eg.register_opn("w", &[int; 6], int);
1405        let g = eg.register_op2("g", int, int, int);
1406        let leaves: Vec<_> = ["a", "b", "c", "d", "e", "f"]
1407            .iter()
1408            .map(|n| {
1409                let o = eg.register_op0(n, int);
1410                eg.add(o, &[])
1411            })
1412            .collect();
1413        let w = eg.add(wide, &leaves);
1414        let gg = eg.add(g, &[leaves[0], leaves[5]]);
1415
1416        let idx = IndexStore::build(&eg);
1417        // `a` is child 0 of both parents; buckets are ascending in node id.
1418        assert_eq!(idx.nodes_by_child_pos(leaves[0], 0), &[w, gg]);
1419        // Position 1 of the wide node is `b`, of `gg` is `f`: neither leaks.
1420        assert_eq!(idx.nodes_by_child_pos(leaves[1], 1), &[w]);
1421        assert_eq!(idx.nodes_by_child_pos(leaves[5], 1), &[gg]);
1422        // The deepest position in use, and the same class one position off it.
1423        assert_eq!(idx.nodes_by_child_pos(leaves[5], 5), &[w]);
1424        assert!(idx.nodes_by_child_pos(leaves[0], 5).is_empty());
1425        // Past the deepest position, and past the node bound.
1426        assert!(idx.nodes_by_child_pos(leaves[0], 6).is_empty());
1427        assert!(
1428            idx.nodes_by_child_pos(crate::id::ENodeId::from_usize(eg.node_count()), 0)
1429                .is_empty()
1430        );
1431    }
1432
1433    #[test]
1434    fn by_child_pos_after_merge() {
1435        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1436        let int = eg.intern_sort("Int");
1437        let f = eg.register_op1("f", int, int);
1438        let x_op = eg.register_op0("x", int);
1439        let y_op = eg.register_op0("y", int);
1440
1441        let x = eg.add(x_op, &[]);
1442        let y = eg.add(y_op, &[]);
1443        let fx = eg.add(f, &[x]);
1444        let _fy = eg.add(f, &[y]);
1445        eg.merge(x, y);
1446        eg.rebuild();
1447
1448        let idx = IndexStore::build(&eg);
1449        let repr = eg.class_repr(x);
1450
1451        // Both fx and fy should appear under the canonical repr at pos 0
1452        let parents = idx.nodes_by_child_pos(repr, 0);
1453        // After merge, fx and fy are congruent — same node. So 1 entry.
1454        assert!(parents.contains(&eg.find_const(fx)));
1455    }
1456
1457    #[test]
1458    fn by_contains_variadic() {
1459        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1460        let int = eg.intern_sort("Int");
1461        let plus = eg.register_mset("plus", int, int);
1462        let x_op = eg.register_op0("x", int);
1463        let y_op = eg.register_op0("y", int);
1464        let z_op = eg.register_op0("z", int);
1465
1466        let x = eg.add(x_op, &[]);
1467        let y = eg.add(y_op, &[]);
1468        let z = eg.add(z_op, &[]);
1469        let pxy = eg.add(plus, &[x, y]);
1470        let pxz = eg.add(plus, &[x, z]);
1471
1472        let idx = IndexStore::build(&eg);
1473
1474        // x is contained in both pxy and pxz
1475        let contains_x = idx.nodes_by_contains(x);
1476        assert_eq!(contains_x.len(), 2);
1477        assert!(contains_x.contains(&pxy));
1478        assert!(contains_x.contains(&pxz));
1479
1480        // y is contained only in pxy
1481        let contains_y = idx.nodes_by_contains(y);
1482        assert_eq!(contains_y.len(), 1);
1483    }
1484}