egglog_core_relations/action/
mod.rs

1//! Instructions that are executed on the results of a query.
2//!
3//! This allows us to execute the "right-hand-side" of a rule. The
4//! implementation here is optimized to execute on a batch of rows at a time.
5use std::{
6    any::Any,
7    hash::Hasher,
8    sync::{
9        Arc,
10        atomic::{AtomicBool, Ordering},
11    },
12};
13
14use crate::{
15    free_join::{get_column_index_from_tableinfo, invoke_batch, invoke_batch_assign},
16    numeric_id::{DenseIdMap, NumericId},
17};
18use egglog_concurrency::NotificationList;
19use hashbrown::HashTable;
20use rustc_hash::FxHasher;
21use smallvec::SmallVec;
22
23use crate::{
24    BaseValues, ContainerValues, ExternalFunctionId, Offset, WrappedTable,
25    common::Value,
26    free_join::{
27        CounterId, CounterReservation, Counters, ExternalFunctions, TableId, TableInfo, Variable,
28    },
29    offsets::Subset,
30    pool::{Clear, Pooled, with_pool_set},
31    row_buffer::TaggedRowBuffer,
32    table_spec::{ColumnId, Constraint, MutationBuffer},
33};
34
35use self::mask::{Mask, MaskIter, ValueSource};
36
37#[macro_use]
38pub(crate) mod mask;
39
40#[cfg(test)]
41mod tests;
42
43/// A representation of a value within a query or rule.
44///
45/// A QueryEntry is either a variable bound in a join, or an untyped constant.
46#[derive(Copy, Clone, Debug)]
47pub enum QueryEntry {
48    Var(Variable),
49    Const(Value),
50}
51
52impl From<Variable> for QueryEntry {
53    fn from(var: Variable) -> Self {
54        QueryEntry::Var(var)
55    }
56}
57
58impl From<Value> for QueryEntry {
59    fn from(val: Value) -> Self {
60        QueryEntry::Const(val)
61    }
62}
63
64/// A value that can be written to a table in an action.
65#[derive(Debug, Clone, Copy)]
66pub enum WriteVal {
67    /// A variable or a constant.
68    QueryEntry(QueryEntry),
69    /// A fresh value from the given counter.
70    IncCounter(CounterId),
71    /// The value of the current row index.
72    CurrentVal(usize),
73}
74
75impl<T> From<T> for WriteVal
76where
77    T: Into<QueryEntry>,
78{
79    fn from(val: T) -> Self {
80        WriteVal::QueryEntry(val.into())
81    }
82}
83
84impl From<CounterId> for WriteVal {
85    fn from(ctr: CounterId) -> Self {
86        WriteVal::IncCounter(ctr)
87    }
88}
89
90/// A value that can be written to the database during a merge action.
91#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
92pub enum MergeVal {
93    /// A fresh value from the given counter.
94    Counter(CounterId),
95    /// A standard constant value.
96    Constant(Value),
97}
98
99impl From<CounterId> for MergeVal {
100    fn from(ctr: CounterId) -> Self {
101        MergeVal::Counter(ctr)
102    }
103}
104
105impl From<Value> for MergeVal {
106    fn from(val: Value) -> Self {
107        MergeVal::Constant(val)
108    }
109}
110
111/// Bindings store a sequence of values for a given set of variables.
112///
113/// The intent of bindings is to store a sequence of mappings from [`Variable`] to [`Value`], in a
114/// struct-of-arrays style that is better laid out for processing bindings in batches.
115pub(crate) struct Bindings {
116    matches: usize,
117    /// The maximum number of calls to `push` that we can receive before we clear the
118    /// [`Bindings`].
119    // This is used to preallocate chunks of the flat `data` vector.
120    max_batch_size: usize,
121    data: Pooled<Vec<Value>>,
122    /// Points into `data`. `data[vars[var].. vars[var]+matches]` contains the values for `data`.
123    var_offsets: DenseIdMap<Variable, usize>,
124}
125
126impl std::ops::Index<Variable> for Bindings {
127    type Output = [Value];
128    fn index(&self, var: Variable) -> &[Value] {
129        self.get(var).unwrap()
130    }
131}
132
133impl std::fmt::Debug for Bindings {
134    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135        let mut table = f.debug_map();
136        for (var, start) in self.var_offsets.iter() {
137            table.entry(&var, &&self.data[*start..*start + self.matches]);
138        }
139        table.finish()
140    }
141}
142
143impl Bindings {
144    pub(crate) fn new(max_batch_size: usize) -> Self {
145        Bindings {
146            matches: 0,
147            max_batch_size,
148            data: Default::default(),
149            var_offsets: DenseIdMap::new(),
150        }
151    }
152    fn assert_invariant(&self) {
153        #[cfg(debug_assertions)]
154        {
155            assert!(self.matches <= self.max_batch_size);
156            for (var, start) in self.var_offsets.iter() {
157                assert!(
158                    start + self.matches <= self.data.len(),
159                    "Variable {:?} starts at {}, but data only has {} elements",
160                    var,
161                    start,
162                    self.data.len()
163                );
164            }
165        }
166    }
167
168    pub(crate) fn clear(&mut self) {
169        self.matches = 0;
170        self.var_offsets.clear();
171        self.data.clear();
172        self.assert_invariant();
173    }
174
175    fn get(&self, var: Variable) -> Option<&[Value]> {
176        let start = self.var_offsets.get(var)?;
177        Some(&self.data[*start..*start + self.matches])
178    }
179
180    fn add_mapping(&mut self, var: Variable, vals: &[Value]) {
181        let start = self.data.len();
182        self.data.extend_from_slice(vals);
183        // We have a flat representation of the data, meaning that writing more than
184        // `max_batch_size` values to `var` could overwrite values for a different variable, which
185        // would produce some mysterious results that are hard to debug.
186        debug_assert!(vals.len() <= self.max_batch_size);
187        if vals.len() < self.max_batch_size {
188            let target_len = self.data.len() + self.max_batch_size - vals.len();
189            self.data.resize(target_len, Value::stale());
190        }
191        self.var_offsets.insert(var, start);
192    }
193
194    pub(crate) fn insert(&mut self, var: Variable, vals: &[Value]) {
195        if self.var_offsets.n_ids() == 0 {
196            self.matches = vals.len();
197        } else {
198            assert_eq!(self.matches, vals.len());
199        }
200        self.add_mapping(var, vals);
201        self.assert_invariant();
202    }
203
204    /// Push a new set of bindings for the given variables.
205    ///
206    /// # Safety:
207    /// This method assumes that all calls to `push`:
208    /// * Have a mapping for every member of `used_vars`.
209    /// * Are passed the same `used_vars`.
210    ///
211    /// It is unsafe to avoid bounds-checking. This method is called extremely frequently and the
212    /// overhead of boundschecking is noticeable.
213    pub(crate) unsafe fn push(
214        &mut self,
215        map: &DenseIdMap<Variable, Value>,
216        used_vars: &[Variable],
217    ) {
218        if self.matches != 0 {
219            assert!(self.matches < self.max_batch_size);
220            #[cfg(debug_assertions)]
221            {
222                for var in used_vars {
223                    assert!(
224                        self.var_offsets.get(*var).is_some(),
225                        "Variable {:?} not found in bindings {:?}",
226                        var,
227                        self.var_offsets
228                    );
229                }
230            }
231            for var in used_vars {
232                let var = var.index();
233                // Safe version: this degrades some benchmarks by ~6%
234                // let start = self.var_offsets.raw()[var].unwrap();
235                // self.data[start + self.matches] = map.raw()[var].unwrap();
236                unsafe {
237                    let start = self.var_offsets.raw().get_unchecked(var).unwrap_unchecked();
238                    *self.data.get_unchecked_mut(start + self.matches) =
239                        map.raw().get_unchecked(var).unwrap_unchecked();
240                }
241            }
242        } else {
243            for (var, val) in map.iter() {
244                self.add_mapping(var, &[*val]);
245            }
246        }
247
248        self.matches += 1;
249        self.assert_invariant();
250    }
251
252    /// A method that removes the bindings for the given variable and allows for its values to be
253    /// used independently from the [`Bindings`] struct. This is helpful when an operation needs to
254    /// mutably borrow the values for one value while reading the values for another.
255    ///
256    /// To add the values back, use [`Bindings::replace`].
257    pub(crate) fn take(&mut self, var: Variable) -> Option<ExtractedBinding> {
258        let mut vals: Pooled<Vec<Value>> = with_pool_set(|ps| ps.get());
259        vals.extend_from_slice(self.get(var)?);
260        let start = self.var_offsets.take(var)?;
261        Some(ExtractedBinding {
262            var,
263            offset: start,
264            vals,
265        })
266    }
267
268    /// Replace a binding extracted with [`Bindings::take`].
269    ///
270    /// # Panics
271    /// This method will panic if the length of the values in `bdg` does not match the current
272    /// number of matches in `Bindings`. It may panic if `bdg` was extracted from a different
273    /// [`Bindings`] than the one it is being replaced in.
274    pub(crate) fn replace(&mut self, bdg: ExtractedBinding) {
275        // Replace the binding with the new values.
276        let ExtractedBinding {
277            var,
278            offset,
279            mut vals,
280        } = bdg;
281        assert_eq!(vals.len(), self.matches);
282        self.data
283            .splice(offset..offset + self.matches, vals.drain(..));
284        self.var_offsets.insert(var, offset);
285    }
286}
287
288/// A binding that has been extracted from a [`Bindings`] struct via the [`Bindings::take`] method.
289///
290/// This allows for a variable's contents to be read while the [`Bindings`] struct has been
291/// borrowed mutably. The contents will not be readable until [`Bindings::replace`] is called.
292pub(crate) struct ExtractedBinding {
293    var: Variable,
294    offset: usize,
295    pub(crate) vals: Pooled<Vec<Value>>,
296}
297
298#[derive(Clone, Copy)]
299struct PredictedEntry {
300    hash: u64,
301    index: usize,
302    table: TableId,
303    key_arity: u32,
304}
305
306#[derive(Default)]
307pub(crate) struct PredictedVals {
308    index: HashTable<PredictedEntry>,
309    values: Vec<Value>,
310}
311
312impl Clear for PredictedVals {
313    fn reuse(&self) -> bool {
314        self.index.capacity() > 0 || self.values.capacity() > 0
315    }
316    fn clear(&mut self) {
317        self.index.clear();
318        self.values.clear();
319    }
320    fn bytes(&self) -> usize {
321        self.index.capacity() * std::mem::size_of::<PredictedEntry>()
322            + self.values.capacity() * std::mem::size_of::<Value>()
323    }
324}
325
326impl PredictedVals {
327    fn hash(table: TableId, key: &[Value]) -> u64 {
328        let mut hasher = FxHasher::default();
329        hasher.write_u32(table.rep());
330        hasher.write_usize(key.len());
331        for value in key {
332            hasher.write_u32(value.rep());
333        }
334        hasher.finish()
335    }
336
337    fn row(&self, entry: PredictedEntry, row_arity: usize) -> &[Value] {
338        &self.values[entry.index..entry.index + row_arity]
339    }
340
341    fn matches(&self, entry: &PredictedEntry, hash: u64, table: TableId, key: &[Value]) -> bool {
342        if entry.hash != hash || entry.table != table || entry.key_arity as usize != key.len() {
343            return false;
344        }
345        self.values[entry.index..entry.index + key.len()] == *key
346    }
347
348    pub(crate) fn get_or_insert_with(
349        &mut self,
350        table: TableId,
351        key: &[Value],
352        row_arity: usize,
353        default: impl FnOnce(&mut Vec<Value>, usize),
354    ) -> (&[Value], bool) {
355        let hash = Self::hash(table, key);
356        if let Some(entry) = self
357            .index
358            .find(hash, |entry| self.matches(entry, hash, table, key))
359            .copied()
360        {
361            return (self.row(entry, row_arity), false);
362        }
363
364        let entry = PredictedEntry {
365            hash,
366            index: self.values.len(),
367            table,
368            key_arity: u32::try_from(key.len()).expect("predicted key arity must fit in u32"),
369        };
370        self.values.reserve(row_arity);
371        let row_start = self.values.len();
372        self.values.extend_from_slice(key);
373        default(&mut self.values, row_start);
374        assert_eq!(
375            self.values.len() - row_start,
376            row_arity,
377            "predicted row builder produced the wrong arity"
378        );
379        self.index.insert_unique(hash, entry, |entry| entry.hash);
380        (self.row(entry, row_arity), true)
381    }
382}
383
384#[derive(Copy, Clone)]
385pub(crate) struct DbView<'a> {
386    pub(crate) external_context: ExternalContext<'a>,
387    pub(crate) table_info: &'a DenseIdMap<TableId, TableInfo>,
388    pub(crate) counters: &'a Counters,
389    pub(crate) external_funcs: &'a ExternalFunctions,
390    pub(crate) bases: &'a BaseValues,
391    pub(crate) containers: &'a ContainerValues,
392    pub(crate) notification_list: &'a NotificationList<TableId>,
393}
394
395/// A borrowed value an embedder can make visible to every [`ExecutionState`]
396/// created for one operation, for its [`ExternalFunction`]s to read back with
397/// [`ExecutionState::external_context`].
398///
399/// It is borrowed for exactly the operation that supplied it, so an embedder
400/// cannot mutate the state it shared while that operation runs.
401///
402/// [`ExternalFunction`]: crate::ExternalFunction
403pub type ExternalContext<'a> = Option<&'a (dyn Any + Send + Sync)>;
404
405/// A handle on a database that may be in the process of running a rule.
406///
407/// An ExecutionState grants immutable access to the (much of) the database, and also provides a
408/// limited API to mutate database contents.
409///
410/// A few important notes:
411///
412/// ## Some tables may be missing
413/// Callers external to this crate cannot construct an `ExecutionState` directly. Depending on the
414/// context, some tables may not be available. In particular, when running [`crate::Table::merge`]
415/// operations, only a table's read-side dependencies are available for reading (sim. for writing).
416/// This allows tables that do not need access to one another to be merged in parallel.
417///
418/// When executing a rule, ExecutionState has access to all tables.
419///
420/// ## Limited Mutability
421/// Callers can only stage insertsions and deletions to tables. These changes are not applied until
422/// the next call to `merge` on the underlying table.
423///
424/// ## Predicted Values
425/// ExecutionStates provide a means of synchronizing the results of a pending write across
426/// different executions of a rule. This is particularly important in the case where the result of
427/// an operation (such as "lookup or insert new id" operatiosn) is a fresh id. A common
428/// ExecutionState ensures that future lookups will see the same id (even across calls to
429/// [`ExecutionState::clone`]).
430pub struct ExecutionState<'a> {
431    pub(crate) predicted: PredictedVals,
432    pub(crate) db: DbView<'a>,
433    counter_reservations: CounterReservations,
434    buffers: MutationBuffers<'a>,
435    /// Whether any mutations have been staged via this ExecutionState.
436    pub(crate) changed: bool,
437    /// Atomic flag for early stopping of rule execution.
438    /// This flag is shared across all handles (clones) of this ExecutionState.
439    stop_match: Arc<AtomicBool>,
440}
441
442#[derive(Default)]
443struct CounterReservations {
444    ranges: DenseIdMap<CounterId, CounterReservation>,
445}
446
447impl CounterReservations {
448    fn next(&mut self, counters: &Counters, ctr: CounterId) -> usize {
449        self.ranges
450            .get_or_insert(ctr, || counters.take_reservation(ctr))
451            .next()
452    }
453}
454
455/// Copyable query-side view of an [`ExecutionState`]. Join tasks only need
456/// immutable database access and the shared early-stop flag; an owned state is
457/// materialized lazily when an action batch actually executes.
458#[derive(Copy, Clone)]
459pub(crate) struct ExecutionStateSeed<'db, 'state> {
460    db: DbView<'db>,
461    stop_match: &'state Arc<AtomicBool>,
462}
463
464impl<'db> ExecutionStateSeed<'db, '_> {
465    pub(crate) fn to_execution_state(self) -> ExecutionState<'db> {
466        ExecutionState {
467            predicted: Default::default(),
468            db: self.db,
469            counter_reservations: Default::default(),
470            buffers: MutationBuffers::new(self.db.notification_list, Default::default()),
471            changed: false,
472            stop_match: Arc::clone(self.stop_match),
473        }
474    }
475
476    pub(crate) fn should_stop(self) -> bool {
477        self.stop_match.load(Ordering::Acquire)
478    }
479}
480
481/// A basic wrapper around an map from table id to a mutation buffer for that table that also
482/// tracks if a table has been modified.
483struct MutationBuffers<'a> {
484    notify_list: &'a NotificationList<TableId>,
485    buffers: DenseIdMap<TableId, Box<dyn MutationBuffer>>,
486}
487
488impl Clone for MutationBuffers<'_> {
489    fn clone(&self) -> Self {
490        let mut res = MutationBuffers::new(self.notify_list, Default::default());
491        for (id, buf) in self.buffers.iter() {
492            res.buffers.insert(id, buf.fresh_handle());
493        }
494        res
495    }
496}
497
498impl<'a> MutationBuffers<'a> {
499    fn new(
500        notify_list: &'a NotificationList<TableId>,
501        buffers: DenseIdMap<TableId, Box<dyn MutationBuffer>>,
502    ) -> MutationBuffers<'a> {
503        MutationBuffers {
504            notify_list,
505            buffers,
506        }
507    }
508    fn lazy_init(&mut self, table_id: TableId, f: impl FnOnce() -> Box<dyn MutationBuffer>) {
509        self.buffers.get_or_insert(table_id, f);
510    }
511    fn stage_insert(&mut self, table_id: TableId, row: &[Value]) {
512        self.buffers[table_id].stage_insert(row);
513        self.notify_list.notify(table_id);
514    }
515
516    fn stage_remove(&mut self, table_id: TableId, key: &[Value]) {
517        self.buffers[table_id].stage_remove(key);
518        self.notify_list.notify(table_id);
519    }
520}
521
522impl Clone for ExecutionState<'_> {
523    fn clone(&self) -> Self {
524        ExecutionState {
525            predicted: Default::default(),
526            db: self.db,
527            counter_reservations: Default::default(),
528            buffers: self.buffers.clone(),
529            changed: false,
530            stop_match: Arc::clone(&self.stop_match),
531        }
532    }
533}
534
535impl<'a> ExecutionState<'a> {
536    pub(crate) fn new(
537        db: DbView<'a>,
538        buffers: DenseIdMap<TableId, Box<dyn MutationBuffer>>,
539    ) -> Self {
540        ExecutionState {
541            predicted: Default::default(),
542            db,
543            counter_reservations: Default::default(),
544            buffers: MutationBuffers::new(db.notification_list, buffers),
545            changed: false,
546            stop_match: Arc::new(AtomicBool::new(false)),
547        }
548    }
549
550    /// Borrow the immutable seed used by rule-search tasks. Rule execution
551    /// starts from an empty mutation-buffer set; action batches create their own
552    /// fresh state from this seed only when they are ready to run.
553    pub(crate) fn seed(&self) -> ExecutionStateSeed<'a, '_> {
554        debug_assert!(self.buffers.buffers.is_empty());
555        ExecutionStateSeed {
556            db: self.db,
557            stop_match: &self.stop_match,
558        }
559    }
560
561    /// Stage an insertion of the given row into `table`.
562    ///
563    /// If you are using `egglog`, consider using `egglog_bridge::TableAction`.
564    pub fn stage_insert(&mut self, table: TableId, row: &[Value]) {
565        self.buffers
566            .lazy_init(table, || self.db.table_info[table].table.new_buffer());
567        self.buffers.stage_insert(table, row);
568        self.changed = true;
569    }
570
571    /// Stage a removal of the given row from `table` if it is present.
572    ///
573    /// If you are using `egglog`, consider using `egglog_bridge::TableAction`.
574    pub fn stage_remove(&mut self, table: TableId, key: &[Value]) {
575        self.buffers
576            .lazy_init(table, || self.db.table_info[table].table.new_buffer());
577        self.buffers.stage_remove(table, key);
578        self.changed = true;
579    }
580
581    /// Call an external function.
582    pub fn call_external_func(
583        &mut self,
584        func: ExternalFunctionId,
585        args: &[Value],
586    ) -> Option<Value> {
587        self.db.external_funcs[func].invoke(self, args)
588    }
589
590    /// The value the caller of this operation supplied as its
591    /// [`ExternalContext`], if any.
592    pub fn external_context(&self) -> ExternalContext<'a> {
593        self.db.external_context
594    }
595
596    pub fn inc_counter(&mut self, ctr: CounterId) -> usize {
597        self.counter_reservations.next(self.db.counters, ctr)
598    }
599
600    pub fn read_counter(&self, ctr: CounterId) -> usize {
601        self.db.counters.read(ctr)
602    }
603
604    /// Iterate over the identifiers of all tables visible to this execution state.
605    pub fn table_ids(&self) -> impl Iterator<Item = TableId> + '_ {
606        self.db.table_info.iter().map(|(id, _)| id)
607    }
608
609    /// Return the stable identity of `table`, or `None` if it is not visible to
610    /// this execution state.
611    #[doc(hidden)]
612    pub fn table_identity(&self, table: TableId) -> Option<crate::TableIdentity> {
613        self.db.table_info.get(table).map(TableInfo::identity)
614    }
615
616    /// Get an immutable reference to the table with id `table`.
617    /// Dangerous: Reading from a table during action execution may break the semi-naive evaluation
618    pub fn get_table(&self, table: TableId) -> &'a WrappedTable {
619        &self.db.table_info[table].table
620    }
621
622    /// Call `f` on each visible row in `table` whose `col` equals `value`,
623    /// with the whole row as a value slice.
624    pub fn for_each_matching_col(
625        &self,
626        table: TableId,
627        col: ColumnId,
628        value: Value,
629        mut f: impl FnMut(&[Value]),
630    ) {
631        let table_info = &self.db.table_info[table];
632        let constraint = Constraint::EqConst { col, val: value };
633
634        // Same order of preference as `Database::process_constraints`, for the
635        // one equality this takes: a sort the table already has, else an index
636        // on the column if it can be cached, else the constraint applied during
637        // the scan.
638        let cacheable = !*table_info
639            .spec
640            .uncacheable_columns
641            .get(col)
642            .unwrap_or(&false);
643        let (subset, slow) = if let Some(subset) = table_info.table.fast_subset(&constraint) {
644            (subset, Vec::new())
645        } else if cacheable {
646            let index = get_column_index_from_tableinfo(table_info, col);
647            let subset = match index.get().unwrap().get_subset(&value) {
648                Some(subset) => with_pool_set(|ps| subset.to_owned(&ps.get_pool())),
649                // No rows hold this key.
650                None => Subset::empty(),
651            };
652            (subset, Vec::new())
653        } else {
654            (table_info.table.all(), vec![constraint])
655        };
656
657        let imp = &table_info.table;
658        let cols: SmallVec<[_; 8]> = (0..imp.spec().arity()).map(ColumnId::from_usize).collect();
659        let mut cur = Offset::new(0);
660        let mut buf = TaggedRowBuffer::new_inline(imp.spec().arity());
661
662        macro_rules! drain_buf {
663            ($buf:expr) => {
664                for (_, row) in $buf.iter() {
665                    f(row);
666                }
667                $buf.clear();
668            };
669        }
670
671        while let Some(next) = imp.scan_project(subset.as_ref(), &cols, cur, 1024, &slow, &mut buf)
672        {
673            drain_buf!(buf);
674            cur = next;
675        }
676        drain_buf!(buf);
677    }
678
679    /// Get the human-readable name for a table, if one exists.
680    pub fn table_name(&self, table: TableId) -> Option<&'a str> {
681        self.db.table_info.get(table).and_then(TableInfo::name)
682    }
683
684    pub fn base_values(&self) -> &'a BaseValues {
685        self.db.bases
686    }
687
688    pub fn container_values(&self) -> &'a ContainerValues {
689        self.db.containers
690    }
691
692    /// Get the _current_ value for a given key in `table`, or otherwise insert
693    /// the unique _next_ value.
694    ///
695    /// Insertions into tables are not performed immediately, but rules and
696    /// merge functions sometimes need to get the result of an insertion. For
697    /// such cases, executions keep a cache of "predicted" values for a given
698    /// mapping that manage the insertions, etc.
699    ///
700    /// If you are using `egglog`, consider using `egglog_bridge::TableAction`.
701    pub fn predict_val(
702        &mut self,
703        table: TableId,
704        key: &[Value],
705        vals: impl ExactSizeIterator<Item = MergeVal>,
706    ) -> Pooled<Vec<Value>> {
707        if let Some(row) = self.db.table_info[table].table.get_row(key) {
708            return row.vals;
709        }
710        let row_arity = key.len() + vals.len();
711        let counters = self.db.counters;
712        let counter_reservations = &mut self.counter_reservations;
713        let (row, inserted) =
714            self.predicted
715                .get_or_insert_with(table, key, row_arity, |values, _| {
716                    for val in vals {
717                        values.push(match val {
718                            MergeVal::Counter(ctr) => {
719                                Value::from_usize(counter_reservations.next(counters, ctr))
720                            }
721                            MergeVal::Constant(c) => c,
722                        });
723                    }
724                });
725        if inserted {
726            self.buffers
727                .lazy_init(table, || self.db.table_info[table].table.new_buffer());
728            self.buffers.stage_insert(table, row);
729            self.changed = true;
730        }
731        with_pool_set(|ps| {
732            let mut result = ps.get::<Vec<Value>>();
733            result.extend_from_slice(row);
734            result
735        })
736    }
737
738    /// A variant of [`ExecutionState::predict_val`] that avoids materializing the full row, and
739    /// instead only returns the value in the given column.
740    pub fn predict_col(
741        &mut self,
742        table: TableId,
743        key: &[Value],
744        vals: impl ExactSizeIterator<Item = MergeVal>,
745        col: ColumnId,
746    ) -> Value {
747        if let Some(val) = self.db.table_info[table].table.get_row_column(key, col) {
748            return val;
749        }
750        let row_arity = key.len() + vals.len();
751        let counters = self.db.counters;
752        let counter_reservations = &mut self.counter_reservations;
753        let (row, inserted) =
754            self.predicted
755                .get_or_insert_with(table, key, row_arity, |values, _| {
756                    for val in vals {
757                        values.push(match val {
758                            MergeVal::Counter(ctr) => {
759                                Value::from_usize(counter_reservations.next(counters, ctr))
760                            }
761                            MergeVal::Constant(c) => c,
762                        });
763                    }
764                });
765        if inserted {
766            self.buffers
767                .lazy_init(table, || self.db.table_info[table].table.new_buffer());
768            self.buffers.stage_insert(table, row);
769            self.changed = true;
770        }
771        row[col.index()]
772    }
773
774    /// Trigger early stopping by setting the stop_match flag.
775    /// This causes rule execution to halt at the next opportunity.
776    ///
777    /// Uses Release ordering to ensure all prior writes are visible to threads that observe this flag.
778    pub fn trigger_early_stop(&self) {
779        self.stop_match.store(true, Ordering::Release);
780    }
781
782    /// Check if early stopping has been requested.
783    ///
784    /// Uses Acquire ordering to ensure we see all writes that happened before the flag was set.
785    pub fn should_stop(&self) -> bool {
786        self.stop_match.load(Ordering::Acquire)
787    }
788}
789
790impl ExecutionState<'_> {
791    /// Returns the number of matches that make it to the end of the instructions
792    pub(crate) fn run_instrs(&mut self, instrs: &[Instr], bindings: &mut Bindings) -> usize {
793        if bindings.var_offsets.next_id().rep() == 0 {
794            // If we have no variables, we want to run the rules once.
795            bindings.matches = 1;
796        }
797
798        // Vectorized execution for larger batch sizes
799        let mut mask = with_pool_set(|ps| Mask::new(0..bindings.matches, ps));
800        for instr in instrs {
801            if mask.is_empty() {
802                return 0;
803            }
804            self.run_instr(&mut mask, instr, bindings);
805        }
806        mask.count_ones()
807    }
808    fn run_instr(&mut self, mask: &mut Mask, inst: &Instr, bindings: &mut Bindings) {
809        fn assert_impl(
810            bindings: &mut Bindings,
811            mask: &mut Mask,
812            l: &QueryEntry,
813            r: &QueryEntry,
814            op: impl Fn(Value, Value) -> bool,
815        ) {
816            match (l, r) {
817                (QueryEntry::Var(v1), QueryEntry::Var(v2)) => {
818                    mask.iter(&bindings[*v1])
819                        .zip(&bindings[*v2])
820                        .retain(|(v1, v2)| op(*v1, *v2));
821                }
822                (QueryEntry::Var(v), QueryEntry::Const(c))
823                | (QueryEntry::Const(c), QueryEntry::Var(v)) => {
824                    mask.iter(&bindings[*v]).retain(|v| op(*v, *c));
825                }
826                (QueryEntry::Const(c1), QueryEntry::Const(c2)) => {
827                    if !op(*c1, *c2) {
828                        mask.clear();
829                    }
830                }
831            }
832        }
833
834        match inst {
835            Instr::LookupOrInsertDefault {
836                table: table_id,
837                args,
838                default,
839                dst_col,
840                dst_var,
841            } => {
842                self.buffers.lazy_init(*table_id, || {
843                    self.db.table_info[*table_id].table.new_buffer()
844                });
845                let table = &self.db.table_info[*table_id].table;
846                // Do two passes over the current vector. First, do a round of lookups. Then, for
847                // any offsets where the lookup failed, insert the default value.
848                let mut mask_copy = mask.clone();
849                table.lookup_row_vectorized(&mut mask_copy, bindings, args, *dst_col, *dst_var);
850                mask_copy.symmetric_difference(mask);
851                if mask_copy.is_empty() {
852                    return;
853                }
854                let mut out = bindings.take(*dst_var).unwrap();
855                for_each_binding_with_mask!(mask_copy, args.as_slice(), bindings, |iter| {
856                    iter.assign_vec(&mut out.vals, |offset, key| {
857                        // First, check if the entry is already in the table:
858                        // if let Some(row) = table.get_row_column(&key, *dst_col) {
859                        //     return row;
860                        // }
861                        // If not, insert the default value.
862                        //
863                        // We avoid doing this more than once by using the
864                        // `predicted` map.
865                        let buffers = &mut self.buffers;
866                        // Bind some mutable references because the closure passed
867                        // to or_insert_with is `move`.
868                        let ctrs = self.db.counters;
869                        let counter_reservations = &mut self.counter_reservations;
870                        let bindings = &bindings;
871                        let row_arity = key.as_slice().len() + default.len();
872                        let (row, inserted) = self.predicted.get_or_insert_with(
873                            *table_id,
874                            key.as_slice(),
875                            row_arity,
876                            |values, row_start| {
877                                // Extend the key with the default values.
878                                for val in default {
879                                    let val = match val {
880                                        WriteVal::QueryEntry(QueryEntry::Const(c)) => *c,
881                                        WriteVal::QueryEntry(QueryEntry::Var(v)) => {
882                                            bindings[*v][offset]
883                                        }
884                                        WriteVal::IncCounter(ctr) => {
885                                            Value::from_usize(counter_reservations.next(ctrs, *ctr))
886                                        }
887                                        WriteVal::CurrentVal(ix) => values[row_start + *ix],
888                                    };
889                                    values.push(val)
890                                }
891                            },
892                        );
893                        if inserted {
894                            buffers.stage_insert(*table_id, row);
895                        }
896                        row[dst_col.index()]
897                    });
898                });
899                bindings.replace(out);
900            }
901            Instr::LookupWithDefault {
902                table,
903                args,
904                dst_col,
905                dst_var,
906                default,
907            } => {
908                let table = &self.db.table_info[*table].table;
909                table.lookup_with_default_vectorized(
910                    mask, bindings, args, *dst_col, *default, *dst_var,
911                );
912            }
913            Instr::Lookup {
914                table,
915                args,
916                dst_col,
917                dst_var,
918            } => {
919                let table = &self.db.table_info[*table].table;
920                table.lookup_row_vectorized(mask, bindings, args, *dst_col, *dst_var);
921            }
922
923            Instr::LookupWithFallback {
924                table: table_id,
925                table_key,
926                func,
927                func_args,
928                dst_col,
929                dst_var,
930            } => {
931                let table = &self.db.table_info[*table_id].table;
932                let mut lookup_result = mask.clone();
933                table.lookup_row_vectorized(
934                    &mut lookup_result,
935                    bindings,
936                    table_key,
937                    *dst_col,
938                    *dst_var,
939                );
940                let mut to_call_func = lookup_result.clone();
941                to_call_func.symmetric_difference(mask);
942                if to_call_func.is_empty() {
943                    return;
944                }
945
946                // Call the given external function on all entries where the lookup failed.
947                invoke_batch_assign(
948                    self.db.external_funcs[*func].as_ref(),
949                    self,
950                    &mut to_call_func,
951                    bindings,
952                    func_args,
953                    *dst_var,
954                );
955                // The new mask should be the lanes where the lookup succeeded or where `func`
956                // succeeded.
957                lookup_result.union(&to_call_func);
958                *mask = lookup_result;
959            }
960            Instr::Insert { table, vals } => {
961                for_each_binding_with_mask!(mask, vals.as_slice(), bindings, |iter| {
962                    iter.for_each(|vals| {
963                        self.stage_insert(*table, vals.as_slice());
964                    })
965                });
966            }
967            Instr::InsertIfEq { table, l, r, vals } => match (l, r) {
968                (QueryEntry::Var(v1), QueryEntry::Var(v2)) => {
969                    for_each_binding_with_mask!(mask, vals.as_slice(), bindings, |iter| {
970                        iter.zip(&bindings[*v1])
971                            .zip(&bindings[*v2])
972                            .for_each(|((vals, v1), v2)| {
973                                if v1 == v2 {
974                                    self.stage_insert(*table, &vals);
975                                }
976                            })
977                    })
978                }
979                (QueryEntry::Var(v), QueryEntry::Const(c))
980                | (QueryEntry::Const(c), QueryEntry::Var(v)) => {
981                    for_each_binding_with_mask!(mask, vals.as_slice(), bindings, |iter| {
982                        iter.zip(&bindings[*v]).for_each(|(vals, cond)| {
983                            if cond == c {
984                                self.stage_insert(*table, &vals);
985                            }
986                        })
987                    })
988                }
989                (QueryEntry::Const(c1), QueryEntry::Const(c2)) => {
990                    if c1 == c2 {
991                        for_each_binding_with_mask!(mask, vals.as_slice(), bindings, |iter| iter
992                            .for_each(|vals| {
993                                self.stage_insert(*table, &vals);
994                            }))
995                    }
996                }
997            },
998            Instr::Remove { table, args } => {
999                for_each_binding_with_mask!(mask, args.as_slice(), bindings, |iter| {
1000                    iter.for_each(|args| {
1001                        self.stage_remove(*table, args.as_slice());
1002                    })
1003                });
1004            }
1005            Instr::External { func, args, dst } => {
1006                invoke_batch(
1007                    self.db.external_funcs[*func].as_ref(),
1008                    self,
1009                    mask,
1010                    bindings,
1011                    args,
1012                    *dst,
1013                );
1014            }
1015            Instr::ExternalWithFallback {
1016                f1,
1017                args1,
1018                f2,
1019                args2,
1020                dst,
1021            } => {
1022                let mut f1_result = mask.clone();
1023                invoke_batch(
1024                    self.db.external_funcs[*f1].as_ref(),
1025                    self,
1026                    &mut f1_result,
1027                    bindings,
1028                    args1,
1029                    *dst,
1030                );
1031                let mut to_call_f2 = f1_result.clone();
1032                to_call_f2.symmetric_difference(mask);
1033                if to_call_f2.is_empty() {
1034                    return;
1035                }
1036                // Call the given external function on all entries where the first call failed.
1037                invoke_batch_assign(
1038                    self.db.external_funcs[*f2].as_ref(),
1039                    self,
1040                    &mut to_call_f2,
1041                    bindings,
1042                    args2,
1043                    *dst,
1044                );
1045                // The new mask should be the lanes where either `f1` or `f2` succeeded.
1046                f1_result.union(&to_call_f2);
1047                *mask = f1_result;
1048            }
1049            Instr::AssertAnyNe { ops, divider } => {
1050                for_each_binding_with_mask!(mask, ops.as_slice(), bindings, |iter| {
1051                    iter.retain(|vals| {
1052                        vals[0..*divider]
1053                            .iter()
1054                            .zip(&vals[*divider..])
1055                            .any(|(l, r)| l != r)
1056                    })
1057                })
1058            }
1059            Instr::AssertEq(l, r) => assert_impl(bindings, mask, l, r, |l, r| l == r),
1060            Instr::AssertNe(l, r) => assert_impl(bindings, mask, l, r, |l, r| l != r),
1061            Instr::ReadCounter { counter, dst } => {
1062                let mut vals = with_pool_set(|ps| ps.get::<Vec<Value>>());
1063                let ctr_val = Value::from_usize(self.read_counter(*counter));
1064                vals.resize(bindings.matches, ctr_val);
1065                bindings.insert(*dst, &vals);
1066            }
1067        }
1068    }
1069}
1070
1071#[derive(Debug, Clone)]
1072pub(crate) enum Instr {
1073    /// Look up the value of the given table, inserting a new entry with a
1074    /// default value if it is not there.
1075    LookupOrInsertDefault {
1076        table: TableId,
1077        args: Vec<QueryEntry>,
1078        default: Vec<WriteVal>,
1079        dst_col: ColumnId,
1080        dst_var: Variable,
1081    },
1082
1083    /// Look up the value of the given table; if the value is not there, use the
1084    /// given default.
1085    LookupWithDefault {
1086        table: TableId,
1087        args: Vec<QueryEntry>,
1088        dst_col: ColumnId,
1089        dst_var: Variable,
1090        default: QueryEntry,
1091    },
1092
1093    /// Look up a value of the given table, halting execution if it is not
1094    /// there.
1095    Lookup {
1096        table: TableId,
1097        args: Vec<QueryEntry>,
1098        dst_col: ColumnId,
1099        dst_var: Variable,
1100    },
1101
1102    /// Look up the given key in the table: if the value is not present in the given table, then
1103    /// call the given external function with the given arguments. If the external function returns
1104    /// a value, that value is returned in the given `dst_var`. If the lookup fails and the
1105    /// external function does not return a value, then execution is halted.
1106    LookupWithFallback {
1107        table: TableId,
1108        table_key: Vec<QueryEntry>,
1109        func: ExternalFunctionId,
1110        func_args: Vec<QueryEntry>,
1111        dst_col: ColumnId,
1112        dst_var: Variable,
1113    },
1114
1115    /// Insert the given return value value with the provided arguments into the
1116    /// table.
1117    Insert {
1118        table: TableId,
1119        vals: Vec<QueryEntry>,
1120    },
1121
1122    /// Insert `vals` into `table` if `l` and `r` are equal.
1123    InsertIfEq {
1124        table: TableId,
1125        l: QueryEntry,
1126        r: QueryEntry,
1127        vals: Vec<QueryEntry>,
1128    },
1129
1130    /// Remove the entry corresponding to `args` in `func`.
1131    Remove {
1132        table: TableId,
1133        args: Vec<QueryEntry>,
1134    },
1135
1136    /// Bind the result of the external function to a variable.
1137    External {
1138        func: ExternalFunctionId,
1139        args: Vec<QueryEntry>,
1140        dst: Variable,
1141    },
1142
1143    /// Bind the result of the external function to a variable. If the first external function
1144    /// fails, then use the second external function. If both fail, execution is haulted, (as in a
1145    /// single failure of `External`).
1146    ExternalWithFallback {
1147        f1: ExternalFunctionId,
1148        args1: Vec<QueryEntry>,
1149        f2: ExternalFunctionId,
1150        args2: Vec<QueryEntry>,
1151        dst: Variable,
1152    },
1153
1154    /// Continue execution iff the two variables are equal.
1155    AssertEq(QueryEntry, QueryEntry),
1156
1157    /// Continue execution iff the two variables are not equal.
1158    AssertNe(QueryEntry, QueryEntry),
1159
1160    /// For the two slices: ops[0..divider] and ops[divider..], continue
1161    /// execution iff there is one pair of values at the same offset that are
1162    /// not equal.
1163    AssertAnyNe {
1164        ops: Vec<QueryEntry>,
1165        divider: usize,
1166    },
1167
1168    /// Read the value of a counter and write it to the given variable.
1169    ReadCounter {
1170        /// The counter to broadcast.
1171        counter: CounterId,
1172        /// The variable to write the value to.
1173        dst: Variable,
1174    },
1175}