egglog_core_relations/free_join/
mod.rs

1//! Execute queries against a database using a variant of Free Join.
2use std::{
3    mem,
4    sync::{
5        Arc,
6        atomic::{AtomicUsize, Ordering},
7    },
8};
9
10use crate::{
11    common::IndexSet,
12    hash_index::IndexCatalog,
13    numeric_id::{DenseIdMap, DenseIdMapWithReuse, NumericId, define_id},
14};
15use crossbeam_queue::SegQueue;
16use egglog_concurrency::{NotificationList, ResettableOnceLock};
17use smallvec::SmallVec;
18
19use crate::{
20    BaseValues, ContainerRebuildSummary, ContainerValues, PoolSet, QueryEntry, TupleIndex, Value,
21    action::{
22        Bindings, DbView,
23        mask::{Mask, MaskIter, ValueSource},
24    },
25    dependency_graph::DependencyGraph,
26    hash_index::{ColumnIndex, Index, IndexBase},
27    offsets::Subset,
28    parallel,
29    parallel_heuristics::parallelize_db_level_op,
30    pool::{Pool, Pooled, with_pool_set},
31    query::{Query, RuleSetBuilder},
32    table_spec::{
33        ColumnId, Constraint, MutationBuffer, Table, TableSpec, WrappedTable, WrappedTableRef,
34    },
35};
36
37use self::packed_cache::{AccessFamilies, FamilyId, SuccessorSig, canonical_constraints};
38use self::packed_trie::ChildShape;
39use self::plan::{Plan, SharedHeaderSubset};
40use crate::action::{ExecutionState, ExternalContext};
41use crate::common::HashMap;
42
43pub(crate) mod execute;
44pub(crate) mod frame_update;
45mod join_tail;
46mod packed_cache;
47mod prepared_index;
48mod probe;
49mod residual_index;
50// The packed trie is exercised independently before it is wired into execution.
51#[allow(dead_code)]
52pub(crate) mod packed_trie;
53pub(crate) mod plan;
54
55define_id!(
56    pub AtomId,
57    u32,
58    "A component of a query consisting of a function and a list of variables or constants"
59);
60define_id!(pub Variable, u32, "a variable in a query", pretty "Var");
61
62impl Variable {
63    pub fn placeholder() -> Variable {
64        Variable::new(!0)
65    }
66}
67
68define_id!(pub TableId, u32, "a table in the database");
69
70impl TableId {
71    pub fn dummy() -> TableId {
72        TableId::new(u32::MAX)
73    }
74
75    pub fn is_dummy(&self) -> bool {
76        self.rep == u32::MAX
77    }
78}
79
80define_id!(pub(crate) ActionId, u32, "an identifier picking out the RHS of a rule");
81
82#[derive(Debug)]
83pub(crate) struct ProcessedConstraints {
84    /// The subset of the table matching the fast constraints. If there are no
85    /// fast constraints then this is the full table. The result is immutable
86    /// after processing and shared with atom clones and plan headers.
87    pub(crate) subset: SharedHeaderSubset,
88    /// The constraints that can be evaluated quickly (O(log(n)) or O(1)).
89    pub(crate) fast: Pooled<Vec<Constraint>>,
90    /// The constraints that require an O(n) scan to evaluate.
91    pub(crate) slow: Pooled<Vec<Constraint>>,
92}
93
94impl Clone for ProcessedConstraints {
95    fn clone(&self) -> Self {
96        ProcessedConstraints {
97            subset: self.subset.clone(),
98            fast: Pooled::cloned(&self.fast),
99            slow: Pooled::cloned(&self.slow),
100        }
101    }
102}
103
104impl ProcessedConstraints {
105    /// The size of the subset of the table matching the fast constraints.
106    fn approx_size(&self) -> usize {
107        self.subset.size()
108    }
109
110    pub(crate) fn dummy() -> ProcessedConstraints {
111        ProcessedConstraints {
112            subset: Subset::empty().into(),
113            fast: Pooled::new(Vec::new()),
114            slow: Pooled::new(Vec::new()),
115        }
116    }
117}
118
119/// Ordered column identifiers shared by join planning, probing, and index caches.
120/// The inline capacity is kept consistent across these paths; longer keys spill
121/// to the heap.
122pub(crate) type ColumnIds = SmallVec<[ColumnId; 4]>;
123
124#[derive(Clone, Debug, PartialEq, Eq)]
125pub(crate) struct SubAtom {
126    pub(crate) atom: AtomId,
127    pub(crate) vars: ColumnIds,
128}
129
130impl SubAtom {
131    pub(crate) fn new(atom: AtomId) -> SubAtom {
132        SubAtom {
133            atom,
134            vars: Default::default(),
135        }
136    }
137}
138
139#[derive(Debug, Clone)]
140pub(crate) struct VarInfo {
141    pub(crate) occurrences: Vec<SubAtom>,
142    /// Whether or not this variable shows up in the "actions" portion of a
143    /// rule.
144    pub(crate) used_in_rhs: bool,
145    pub(crate) defined_in_rhs: bool,
146    pub(crate) name: Option<Arc<str>>,
147}
148
149pub(crate) type HashIndex = Arc<ResettableOnceLock<Index<TupleIndex>>>;
150pub(crate) type HashColumnIndex = Arc<ResettableOnceLock<Index<ColumnIndex>>>;
151
152static NEXT_TABLE_IDENTITY: AtomicUsize = AtomicUsize::new(0);
153
154/// An opaque identity for one table allocation.
155///
156/// Unlike [`TableId`], identities are not reused after a database snapshot is
157/// restored. This is exposed for workspace crates that retain table handles
158/// across snapshots; most users should use [`TableId`] instead.
159#[doc(hidden)]
160#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
161pub struct TableIdentity(usize);
162
163impl TableIdentity {
164    fn fresh() -> Self {
165        Self(NEXT_TABLE_IDENTITY.fetch_add(1, Ordering::Relaxed))
166    }
167}
168
169pub struct TableInfo {
170    identity: TableIdentity,
171    pub(crate) name: Option<Arc<str>>,
172    pub(crate) spec: TableSpec,
173    pub(crate) table: WrappedTable,
174    pub(crate) indexes: IndexCatalog<ColumnIds, HashIndex>,
175    pub(crate) column_indexes: IndexCatalog<ColumnId, HashColumnIndex>,
176    /// Every way a built plan indexes rows below this table's shared trie
177    /// nodes, interned in plan-build order; see [`FamilyId`].
178    successor_families: HashMap<SuccessorSig, FamilyId>,
179}
180
181impl TableInfo {
182    /// Intern the family that indexes `column` after applying `constraints`.
183    fn successor_family(&mut self, column: ColumnId, constraints: &[Constraint]) -> FamilyId {
184        let next = FamilyId::from_usize(self.successor_families.len());
185        *self
186            .successor_families
187            .entry((column, canonical_constraints(constraints)))
188            .or_insert(next)
189    }
190
191    /// The child storage of every trie node shared below this table's roots:
192    /// one family per interned successor, or a leaf if no plan indexes below
193    /// them. Plans are built before a rule set runs, so the count is fixed for
194    /// the whole run.
195    pub(crate) fn shared_child_shape(&self) -> ChildShape {
196        if self.successor_families.is_empty() {
197            ChildShape::Leaf
198        } else {
199            ChildShape::Dynamic {
200                families: self.successor_families.len(),
201            }
202        }
203    }
204
205    #[doc(hidden)]
206    pub fn identity(&self) -> TableIdentity {
207        self.identity
208    }
209
210    pub fn table(&self) -> &WrappedTable {
211        &self.table
212    }
213
214    pub fn name(&self) -> Option<&str> {
215        self.name.as_deref()
216    }
217
218    pub fn spec(&self) -> &TableSpec {
219        &self.spec
220    }
221}
222
223impl Clone for TableInfo {
224    fn clone(&self) -> Self {
225        fn deep_clone_map<K: Clone + std::hash::Hash + Eq, TI: IndexBase + Clone>(
226            map: &IndexCatalog<K, Arc<ResettableOnceLock<Index<TI>>>>,
227            table: WrappedTableRef,
228        ) -> IndexCatalog<K, Arc<ResettableOnceLock<Index<TI>>>> {
229            map.map(|table_ref| {
230                let (k, v) = table_ref;
231                let v: Index<TI> = v
232                    .get_or_update(|index| {
233                        index.refresh(table);
234                    })
235                    .clone();
236                (k.clone(), Arc::new(ResettableOnceLock::new(v)))
237            })
238        }
239        TableInfo {
240            identity: self.identity,
241            name: self.name.clone(),
242            spec: self.spec.clone(),
243            table: self.table.dyn_clone(),
244            indexes: deep_clone_map(&self.indexes, self.table.as_ref()),
245            column_indexes: deep_clone_map(&self.column_indexes, self.table.as_ref()),
246            successor_families: self.successor_families.clone(),
247        }
248    }
249}
250
251define_id!(pub CounterId, u32, "A counter accessible to actions, useful for generating unique Ids.");
252define_id!(pub ExternalFunctionId, u32, "A user-defined operation that can be invoked from a query");
253
254/// External functions allow external callers to manipulate database state in
255/// near-arbitrary ways.
256///
257/// This is a useful, if low-level, interface for extending this database with
258/// functionality and state not built into the core model.
259pub trait ExternalFunction: dyn_clone::DynClone + Send + Sync {
260    /// Invoke the function with mutable access to the database. If a value is
261    /// not returned, halt the execution of the current rule.
262    fn invoke(&self, state: &mut ExecutionState, args: &[Value]) -> Option<Value>;
263}
264
265/// Automatically generate an `ExternalFunction` implementation from a function.
266pub fn make_external_func<
267    F: Fn(&mut ExecutionState, &[Value]) -> Option<Value> + Clone + Send + Sync,
268>(
269    f: F,
270) -> impl ExternalFunction {
271    #[derive(Clone)]
272    struct Wrapped<F>(F);
273    impl<F> ExternalFunction for Wrapped<F>
274    where
275        F: Fn(&mut ExecutionState, &[Value]) -> Option<Value> + Clone + Send + Sync,
276    {
277        fn invoke(&self, state: &mut ExecutionState, args: &[Value]) -> Option<Value> {
278            (self.0)(state, args)
279        }
280    }
281    Wrapped(f)
282}
283
284/// A vectorized variant of [`ExternalFunction::invoke`] to avoid repeated dynamic dispatch.
285pub(crate) fn invoke_batch(
286    this: &dyn ExternalFunction,
287    state: &mut ExecutionState,
288    mask: &mut Mask,
289    bindings: &mut Bindings,
290    args: &[QueryEntry],
291    out_var: Variable,
292) {
293    let pool: Pool<Vec<Value>> = with_pool_set(|ps| ps.get_pool());
294    let mut out = pool.get();
295    out.reserve(mask.len());
296    for_each_binding_with_mask!(mask, args, bindings, |iter| {
297        iter.fill_vec(&mut out, Value::stale, |_, args| {
298            this.invoke(state, args.as_slice())
299        });
300    });
301    bindings.insert(out_var, &out);
302}
303
304/// A variant of [`invoke_batch`] that overwrites the output variable,
305/// rather than assigning all new values.
306///
307/// *Panics* This method will panic if `out_var` doesn't already have an appropriately-sized
308/// vector bound in `bindings`.
309pub(crate) fn invoke_batch_assign(
310    this: &dyn ExternalFunction,
311    state: &mut ExecutionState,
312    mask: &mut Mask,
313    bindings: &mut Bindings,
314    args: &[QueryEntry],
315    out_var: Variable,
316) {
317    let mut out = bindings.take(out_var).expect("out_var must be bound");
318    for_each_binding_with_mask!(mask, args, bindings, |iter| {
319        iter.assign_vec_and_retain(&mut out.vals, |_, args| this.invoke(state, &args))
320    });
321    bindings.replace(out);
322}
323
324// Implements `Clone` for `Box<dyn ExternalFunction>`.
325dyn_clone::clone_trait_object!(ExternalFunction);
326
327pub(crate) type ExternalFunctions =
328    DenseIdMapWithReuse<ExternalFunctionId, Box<dyn ExternalFunction>>;
329
330// Reservable counters give each execution state a disjoint range of values.
331// Values are then handed out by advancing the state's local `range`, avoiding
332// a shared atomic operation per value. Dropping the reservation returns its
333// unused suffix to `recycled`, and future states reuse those suffixes before
334// advancing the atomic high-water mark. A reservation size of one retains the
335// exact increment/read behavior needed by observable counters.
336struct Counter {
337    next: AtomicUsize,
338    reservation_size: usize,
339    recycled: SegQueue<std::ops::Range<usize>>,
340}
341
342impl Counter {
343    fn new(reservation_size: usize) -> Self {
344        assert!(reservation_size > 0);
345        Self {
346            next: AtomicUsize::new(0),
347            reservation_size,
348            recycled: SegQueue::new(),
349        }
350    }
351
352    fn take_reservation(&self) -> std::ops::Range<usize> {
353        if self.reservation_size == 1 {
354            let start = self.next.fetch_add(1, Ordering::Release);
355            return start..start + 1;
356        }
357        self.recycled.pop().unwrap_or_else(|| {
358            let start = self
359                .next
360                .fetch_add(self.reservation_size, Ordering::Release);
361            start..start + self.reservation_size
362        })
363    }
364}
365
366pub(crate) struct CounterReservation {
367    counter: Arc<Counter>,
368    range: std::ops::Range<usize>,
369}
370
371impl CounterReservation {
372    fn new(counter: Arc<Counter>) -> Self {
373        let range = counter.take_reservation();
374        Self { counter, range }
375    }
376
377    pub(crate) fn next(&mut self) -> usize {
378        if self.range.start == self.range.end {
379            self.range = self.counter.take_reservation();
380        }
381        let result = self.range.start;
382        self.range.start += 1;
383        result
384    }
385}
386
387impl Drop for CounterReservation {
388    fn drop(&mut self) {
389        if !self.range.is_empty() {
390            self.counter.recycled.push(self.range.clone());
391        }
392    }
393}
394
395#[derive(Default)]
396pub(crate) struct Counters(DenseIdMap<CounterId, Arc<Counter>>);
397
398impl Clone for Counters {
399    fn clone(&self) -> Counters {
400        let mut map = DenseIdMap::new();
401        for (k, v) in self.0.iter() {
402            // NB: we may want to experiment with Ordering::Relaxed here.
403            let cloned = Counter {
404                next: AtomicUsize::new(v.next.load(Ordering::SeqCst)),
405                reservation_size: v.reservation_size,
406                // The high-water mark already includes every recycled range,
407                // so omitting the free list is safe and avoids sharing
408                // reservations between independent database snapshots.
409                recycled: SegQueue::new(),
410            };
411            map.insert(k, Arc::new(cloned));
412        }
413        Counters(map)
414    }
415}
416
417impl Counters {
418    pub(crate) fn read(&self, ctr: CounterId) -> usize {
419        self.0[ctr].next.load(Ordering::Acquire)
420    }
421    pub(crate) fn inc(&self, ctr: CounterId) -> usize {
422        // We synchronize with `read_counter` but not with other increments.
423        // NB: we may want to experiment with Ordering::Relaxed here.
424        self.0[ctr].next.fetch_add(1, Ordering::Release)
425    }
426    pub(crate) fn take_reservation(&self, ctr: CounterId) -> CounterReservation {
427        CounterReservation::new(Arc::clone(&self.0[ctr]))
428    }
429}
430
431/// A collection of tables and indexes over them.
432///
433/// A database also owns the memory pools used by its tables.
434#[derive(Clone, Default)]
435pub struct Database {
436    // NB: some fields are pub(crate) to allow some internal modules to avoid
437    // borrowing the whole table.
438    pub(crate) tables: DenseIdMap<TableId, TableInfo>,
439    // Reservable counters amortize shared atomic increments across an
440    // ExecutionState. Exact counters retain one atomic increment per value.
441    pub(crate) counters: Counters,
442    pub(crate) external_functions: ExternalFunctions,
443    container_values: ContainerValues,
444    /// `notification_list` contains the list of tables that have been modified since the last call
445    /// to [`Database::merge_all`].
446    notification_list: NotificationList<TableId>,
447    // Tracks the relative dependencies between tables during merge operations.
448    deps: DependencyGraph,
449    base_values: BaseValues,
450    /// A rough estimate of the total size of the database.
451    ///
452    /// This is primarily used to determine whether or not to attempt to do some operations in
453    /// parallel.
454    total_size_estimate: usize,
455}
456
457impl Database {
458    /// Create an empty Database.
459    ///
460    /// Queries use the currently installed egglog thread pool. If no pool is
461    /// installed, queries run single-threaded.
462    pub fn new() -> Database {
463        Database::default()
464    }
465
466    /// Initialize a new rulse set to run against this database.
467    pub fn new_rule_set(&mut self) -> RuleSetBuilder<'_> {
468        RuleSetBuilder::new(self)
469    }
470
471    /// Add a new external function to the database.
472    pub fn add_external_function(
473        &mut self,
474        f: Box<dyn ExternalFunction + 'static>,
475    ) -> ExternalFunctionId {
476        self.external_functions.push(f)
477    }
478
479    /// Free an existing external function. Make sure not to use `id` afterwards.
480    pub fn free_external_function(&mut self, id: ExternalFunctionId) {
481        self.external_functions.take(id);
482    }
483
484    pub fn base_values(&self) -> &BaseValues {
485        &self.base_values
486    }
487
488    pub fn base_values_mut(&mut self) -> &mut BaseValues {
489        &mut self.base_values
490    }
491
492    pub fn container_values(&self) -> &ContainerValues {
493        &self.container_values
494    }
495
496    pub fn container_values_mut(&mut self) -> &mut ContainerValues {
497        &mut self.container_values
498    }
499
500    pub fn rebuild_containers(&mut self, table_id: TableId) -> ContainerRebuildSummary {
501        let mut containers = mem::take(&mut self.container_values);
502        let table = &self.tables[table_id].table;
503        let res =
504            self.with_execution_state(None, |state| containers.rebuild_all(table_id, table, state));
505        self.container_values = containers;
506        res
507    }
508
509    /// Apply the value-level rebuild encoded by `func_id` to all the tables in `to_rebuild`.
510    ///
511    /// The native [`Table::apply_rebuild`] method takes a `next_ts` argument for filling in new
512    /// values in a table like [`crate::SortedWritesTable`] where values in a certain column need
513    /// to be inserted in sorted order; the `next_ts` argument to this method is passed to
514    /// `apply_rebuild` for this purpose.
515    pub fn apply_rebuild(
516        &mut self,
517        func_id: TableId,
518        to_rebuild: &[TableId],
519        next_ts: Value,
520    ) -> bool {
521        let func = self.tables.take(func_id).unwrap();
522        self.run_on_tables(to_rebuild, |_, info, view| {
523            info.table.apply_rebuild(
524                func_id,
525                &func.table,
526                next_ts,
527                &mut ExecutionState::new(*view, Default::default()),
528            )
529        });
530        self.tables.insert(func_id, func);
531        self.merge_all()
532    }
533
534    pub fn refresh_rows_for_values(
535        &mut self,
536        to_refresh: &[TableId],
537        dirty_ids: &[Value],
538        next_ts: Value,
539    ) -> bool {
540        if dirty_ids.is_empty() {
541            return false;
542        }
543        // This is the follow-up for `ContainerRebuildSummary::dirty_ids()`.
544        // These ids changed semantics without changing identity, so parent
545        // rows can become newly matchable without getting an ordinary table
546        // delta.
547        //
548        // It must run after ordinary table rebuild, which already handles
549        // changed-id cases by rewriting parent rows to the new id.
550        self.run_on_tables(to_refresh, |_, info, _| {
551            info.table.refresh_rows_for_values(dirty_ids, next_ts)
552        });
553        self.merge_all()
554    }
555
556    fn run_on_tables(
557        &mut self,
558        table_ids: &[TableId],
559        run: impl for<'a> Fn(TableId, &mut TableInfo, &DbView<'a>) -> bool + Sync,
560    ) {
561        if parallelize_db_level_op(self.total_size_estimate) {
562            let mut tables = Vec::with_capacity(table_ids.len());
563            for id in table_ids {
564                tables.push((*id, self.tables.take(*id).unwrap()));
565            }
566            let view = self.read_only_view();
567            parallel::for_each_mut(&mut tables, |_, (id, info)| {
568                if run(*id, info, &view) {
569                    self.notification_list.notify(*id);
570                }
571            });
572            for (id, info) in tables {
573                self.tables.insert(id, info);
574            }
575        } else {
576            for id in table_ids {
577                let mut info = self.tables.take(*id).unwrap();
578                let changed = {
579                    let view = self.read_only_view();
580                    run(*id, &mut info, &view)
581                };
582                if changed {
583                    self.notification_list.notify(*id);
584                }
585                self.tables.insert(*id, info);
586            }
587        }
588    }
589
590    /// Run `f` with access to an `ExecutionState` mapped to this database.
591    ///
592    /// `context` is visible to any external function the closure reaches; pass
593    /// `None` if there is nothing to share.
594    pub fn with_execution_state<R>(
595        &self,
596        context: ExternalContext<'_>,
597        f: impl FnOnce(&mut ExecutionState) -> R,
598    ) -> R {
599        let mut state = ExecutionState::new(self.read_only_view_with(context), Default::default());
600        f(&mut state)
601    }
602
603    /// Like [`Database::with_execution_state`], including its `context`, but
604    /// also reports whether `f` staged any mutation through the execution
605    /// state. Callers can use the flag to skip a subsequent `merge_all` when
606    /// the closure was read-only.
607    pub fn with_execution_state_tracked<R>(
608        &self,
609        context: ExternalContext<'_>,
610        f: impl FnOnce(&mut ExecutionState) -> R,
611    ) -> (R, bool) {
612        let mut state = ExecutionState::new(self.read_only_view_with(context), Default::default());
613        let result = f(&mut state);
614        (result, state.changed)
615    }
616
617    pub(crate) fn read_only_view(&self) -> DbView<'_> {
618        self.read_only_view_with(None)
619    }
620
621    /// Like [`Database::read_only_view`], but with an [`ExternalContext`] that
622    /// every [`ExecutionState`] built from the view will expose.
623    pub(crate) fn read_only_view_with<'a>(&'a self, context: ExternalContext<'a>) -> DbView<'a> {
624        DbView {
625            external_context: context,
626            table_info: &self.tables,
627            counters: &self.counters,
628            external_funcs: &self.external_functions,
629            bases: &self.base_values,
630            containers: &self.container_values,
631            notification_list: &self.notification_list,
632        }
633    }
634
635    /// Estimate the size of the table. If a constraint is provided, return an
636    /// estimate of the size of the subset of the table matching the constraint.
637    pub fn estimate_size(&self, table: TableId, c: Option<Constraint>) -> usize {
638        let table_info = self
639            .tables
640            .get(table)
641            .expect("table must be declared in the current database");
642        let table = &table_info.table;
643        if let Some(c) = c {
644            if let Some(sub) = table.fast_subset(&c) {
645                // In the case where a the constraint can be computed quickly,
646                // we do not filter for staleness, which may over-approximate.
647                sub.size()
648            } else {
649                table.refine_one(table.refine_live(table.all()), &c).size()
650            }
651        } else {
652            table.len()
653        }
654    }
655
656    /// Create a new counter for this database.
657    ///
658    /// These counters can be used to generate unique ids as part of an action.
659    pub fn add_counter(&mut self) -> CounterId {
660        self.counters.0.push(Arc::new(Counter::new(1)))
661    }
662
663    /// Create a counter whose increments from one [`ExecutionState`] are
664    /// allocated in local reservations.
665    ///
666    /// This is intended for fresh identifiers, where uniqueness matters but a
667    /// concurrent read need not equal the number of identifiers already
668    /// returned. Ordinary counters created by [`Database::add_counter`] retain
669    /// exact increment/read behavior.
670    ///
671    /// # Panics
672    ///
673    /// Panics if `reservation_size` is zero.
674    pub fn add_reservable_counter(&mut self, reservation_size: usize) -> CounterId {
675        self.counters
676            .0
677            .push(Arc::new(Counter::new(reservation_size)))
678    }
679
680    /// Increment the given counter and return its previous value.
681    pub fn inc_counter(&self, counter: CounterId) -> usize {
682        self.counters.inc(counter)
683    }
684
685    /// Get the current value of the given counter.
686    pub fn read_counter(&self, counter: CounterId) -> usize {
687        self.counters.read(counter)
688    }
689
690    /// A helper for merging all pending updates. Used to write to the database after updates have
691    /// been staged. Returns true if any tuples were added.
692    ///
693    /// Exposed for testing purposes.
694    ///
695    /// Useful for out-of-band insertions into the database.
696    pub fn merge_all(&mut self) -> bool {
697        let mut ever_changed = false;
698        let do_parallel = parallelize_db_level_op(self.total_size_estimate);
699        let mut to_merge = IndexSet::default();
700        // Tables modified during this `merge_all` call. Only these need their cached indexes reset
701        // at the end so future reads refresh them.
702        let mut touched: IndexSet<TableId> = IndexSet::default();
703        loop {
704            to_merge.clear();
705            let to_merge_vec = self.notification_list.reset();
706            touched.extend(to_merge_vec.iter().copied());
707            if to_merge_vec.len() < 4 {
708                ever_changed |= self.merge_simple(to_merge_vec, &mut touched);
709                break;
710            }
711            for table in to_merge_vec {
712                to_merge.insert(table);
713            }
714
715            let mut changed = false;
716            let mut tables_merging = DenseIdMap::<
717                TableId,
718                (
719                    // The info needed to merge this table.
720                    Option<TableInfo>,
721                    // Pre-allocated write buffers, according to the tables declared write
722                    // dependencies.
723                    DenseIdMap<TableId, Box<dyn MutationBuffer>>,
724                ),
725            >::with_capacity(self.tables.n_ids());
726            for stratum in self.deps.strata() {
727                // Initialize the write dependencies first.
728                for table in stratum.intersection(&to_merge).copied() {
729                    let mut bufs = DenseIdMap::default();
730                    for dep in self.deps.write_deps(table) {
731                        if let Some(info) = self.tables.get(dep) {
732                            bufs.insert(dep, info.table.new_buffer());
733                        }
734                    }
735                    tables_merging.insert(table, (None, bufs));
736                }
737                // Then initialize read dependencies (this two-phase structure is why we have an
738                // Option in the tables_merging map).
739                for table in stratum.intersection(&to_merge).copied() {
740                    let val = self.tables.unwrap_val(table);
741                    // Maintain `total_size_estimate` incrementally (subtract now, add
742                    // the post-merge length on drain below) so the reset loop no
743                    // longer re-sums every table.
744                    self.total_size_estimate =
745                        self.total_size_estimate.wrapping_sub(val.table.len());
746                    tables_merging[table].0 = Some(val);
747                }
748                let db = self.read_only_view();
749                changed |= if do_parallel {
750                    parallel::map_dense_id_map_mut(&mut tables_merging, |_, (info, buffers)| {
751                        let mut es = ExecutionState::new(db, mem::take(buffers));
752                        info.as_mut().unwrap().table.merge(&mut es).added || es.changed
753                    })
754                    .into_iter()
755                    .any(|changed| changed)
756                } else {
757                    tables_merging
758                        .iter_mut()
759                        .map(|(_, (info, buffers))| {
760                            let mut es = ExecutionState::new(db, mem::take(buffers));
761                            info.as_mut().unwrap().table.merge(&mut es).added || es.changed
762                        })
763                        .max()
764                        .unwrap_or(false)
765                };
766                for (id, (table, _)) in tables_merging.drain() {
767                    let val = table.unwrap();
768                    self.total_size_estimate =
769                        self.total_size_estimate.wrapping_add(val.table.len());
770                    self.tables.insert(id, val);
771                }
772            }
773            ever_changed |= changed;
774        }
775        // Reset the cached indexes of only the tables modified during this call so
776        // they refresh on next access; unmodified tables keep their still-valid
777        // cached indexes. `touched` must contain *every* table whose version bumped
778        // this call: `ResettableOnceLock::get_or_update` runs the index `refresh`
779        // only after a `reset()`, so a modified-but-unreset table would keep serving
780        // a stale cached index. It does — every merged table comes from
781        // `notification_list.reset()`, which is exactly what `touched` accumulates.
782        // `total_size_estimate` was maintained incrementally at each merge (above and
783        // in `merge_simple`), so we no longer re-sum every table here.
784        for table in touched.iter().copied() {
785            if let Some(info) = self.tables.get_mut(table) {
786                info.column_indexes.update(|_, ti| {
787                    Arc::get_mut(ti).unwrap().reset();
788                });
789                info.indexes.update(|_, ti| {
790                    Arc::get_mut(ti).unwrap().reset();
791                });
792            }
793        }
794        ever_changed
795    }
796
797    /// A "fast path" merge method that is not optimized for parallelism and does not respect read
798    /// and write dependencies. This ends up being faster than the full "strata-aware" option in
799    /// the body of `merge_all`.
800    fn merge_simple(
801        &mut self,
802        mut to_merge: SmallVec<[TableId; 4]>,
803        touched: &mut IndexSet<TableId>,
804    ) -> bool {
805        let mut changed = false;
806        while !to_merge.is_empty() {
807            for table_id in to_merge.iter().copied() {
808                let mut info = self.tables.unwrap_val(table_id);
809                // Maintain `total_size_estimate` incrementally (see `merge_all`'s
810                // reset loop, which no longer re-sums every table).
811                self.total_size_estimate = self.total_size_estimate.wrapping_sub(info.table.len());
812                let mut es = ExecutionState::new(self.read_only_view(), Default::default());
813                changed |= info.table.merge(&mut es).added || es.changed;
814                self.total_size_estimate = self.total_size_estimate.wrapping_add(info.table.len());
815                self.tables.insert(table_id, info);
816            }
817            to_merge = self.notification_list.reset();
818            touched.extend(to_merge.iter().copied());
819        }
820        changed
821    }
822
823    /// A low-level helper for merging pending updates to a particular function.
824    ///
825    /// Callers should prefer `merge_all`, as the process of merging the data
826    /// for a particular table may cause other updates to be buffered
827    /// elesewhere. The `merge_all` method runs merges to a fixed point to avoid
828    /// surprises here.
829    pub fn merge_table(&mut self, table: TableId) -> bool {
830        let mut info = self.tables.unwrap_val(table);
831        self.total_size_estimate = self.total_size_estimate.wrapping_sub(info.table.len());
832        let table_changed = info.table.merge(&mut ExecutionState::new(
833            self.read_only_view(),
834            Default::default(),
835        ));
836        self.total_size_estimate = self.total_size_estimate.wrapping_add(info.table.len());
837        self.tables.insert(table, info);
838        table_changed.added
839    }
840
841    /// Get id of the next table to be added to the database.
842    ///
843    /// This can be useful for "knot tying", when tables need to reference their
844    /// own id.
845    pub fn next_table_id(&self) -> TableId {
846        self.tables.next_id()
847    }
848
849    /// Add a table with the given schema to the database.
850    ///
851    /// The table must have a compatible spec with `types` (e.g. same number of
852    /// columns).
853    pub fn add_table<T: Table + Sized + 'static>(
854        &mut self,
855        table: T,
856        read_deps: impl IntoIterator<Item = TableId>,
857        write_deps: impl IntoIterator<Item = TableId>,
858    ) -> TableId {
859        self.add_table_impl(table, None, read_deps, write_deps)
860    }
861
862    pub fn add_table_named<T: Table + Sized + 'static>(
863        &mut self,
864        table: T,
865        name: Arc<str>,
866        read_deps: impl IntoIterator<Item = TableId>,
867        write_deps: impl IntoIterator<Item = TableId>,
868    ) -> TableId {
869        self.add_table_impl(table, Some(name), read_deps, write_deps)
870    }
871
872    fn add_table_impl<T: Table + Sized + 'static>(
873        &mut self,
874        table: T,
875        name: Option<Arc<str>>,
876        read_deps: impl IntoIterator<Item = TableId>,
877        write_deps: impl IntoIterator<Item = TableId>,
878    ) -> TableId {
879        let spec = table.spec();
880        let table = WrappedTable::new(table);
881        let res = self.tables.push(TableInfo {
882            identity: TableIdentity::fresh(),
883            name,
884            spec,
885            table,
886            indexes: IndexCatalog::new(),
887            column_indexes: IndexCatalog::new(),
888            successor_families: HashMap::default(),
889        });
890        self.deps.add_table(res, read_deps, write_deps);
891        res
892    }
893
894    /// Get direct mutable access to the table.
895    ///
896    /// This method is useful for out-of-band access to databse state.
897    ///
898    /// **NOTE:** It is legal to call [`Table::new_buffer`] on the returned table handle, and use
899    /// that to stage updates to the given table via [`MutationBuffer::stage_insert`] or
900    /// [`MutationBuffer::stage_remove`], however this is *likely to be a source of bugs*.
901    ///
902    /// Updates staged in this way will not cause `table` to be marked as having pending changes in
903    /// the next call to [`Database::merge_all`]. Instead, such users should use
904    /// [`Database::new_buffer`], which plumbs this signal through correctly, or better yet,
905    /// perform all updates through an [`ExecutionState`] or a [`crate::RuleBuilder`]. If these
906    /// options do not work, then calling [`Database::merge_table`] directly will force a merge
907    /// call on the table.
908    pub fn get_table(&self, table: TableId) -> &WrappedTable {
909        &self
910            .tables
911            .get(table)
912            .expect("must access a table that has been declared in this database")
913            .table
914    }
915
916    /// Get a handle on the given table along with metadata about it.
917    ///
918    ///
919    /// **NOTE:** See the note on [`Database::get_table`] around manually staging updates.
920    pub fn get_table_info(&self, table: TableId) -> &TableInfo {
921        self.tables
922            .get(table)
923            .expect("must access a table that has been declared in this database")
924    }
925
926    /// Create a new mutation buffer for the table with id `id`.
927    ///
928    /// This will marked the given table as potentially changed for the next round of merging.
929    /// Unlike calling [`Table::new_buffer`] on a table returned from a getter, this method also
930    /// triggers change notification metadata that is read by [`Database::merge_all`].
931    pub fn new_buffer(&self, id: TableId) -> Box<dyn MutationBuffer> {
932        self.notification_list.notify(id);
933        self.get_table(id).new_buffer()
934    }
935
936    pub(crate) fn process_constraints(
937        &self,
938        table: TableId,
939        cs: &[Constraint],
940    ) -> ProcessedConstraints {
941        let table_info = &self.tables[table];
942        let (mut subset, mut fast, mut slow) = table_info.table.split_fast_slow(cs);
943        slow.retain(|c| {
944            let (col, val) = match c {
945                Constraint::EqConst { col, val } => (*col, *val),
946                Constraint::Eq { .. }
947                | Constraint::LtConst { .. }
948                | Constraint::GtConst { .. }
949                | Constraint::LeConst { .. }
950                | Constraint::GeConst { .. } => return true,
951            };
952            // We are looking up by a constant: this is something we can build
953            // an index for as long as the column is cacheable.
954            if *table_info
955                .spec
956                .uncacheable_columns
957                .get(col)
958                .unwrap_or(&false)
959            {
960                return true;
961            }
962            // We have or will build an index: upgrade this constraint to
963            // 'fast'.
964            fast.push(c.clone());
965            let index = get_column_index_from_tableinfo(table_info, col);
966            match index.get().unwrap().get_subset(&val) {
967                Some(s) => {
968                    with_pool_set(|ps| subset.intersect(s, &ps.get_pool()));
969                }
970                None => {
971                    // There are no rows matching this key! We can constrain this to nothing.
972                    subset = Subset::empty();
973                }
974            }
975            // Remove this constraint from the slow list.
976            false
977        });
978        ProcessedConstraints {
979            subset: subset.into(),
980            fast,
981            slow,
982        }
983    }
984
985    /// Get direct mutable access to the table.
986    ///
987    /// This method is useful for out-of-band access to databse state.
988    ///
989    /// **NOTE:** See the warning around staging updates to handles returned through this method in
990    /// the documentation for [`Database::get_table`].
991    pub fn get_table_mut(&mut self, id: TableId) -> &mut dyn Table {
992        &mut *self
993            .tables
994            .get_mut(id)
995            .expect("must access a table that has been declared in this database")
996            .table
997    }
998
999    /// Remove every row from the given table.
1000    ///
1001    /// This is intended as a faster alternative to staging a per-row
1002    /// `stage_remove` for every key in the table. The underlying [`Table::clear`]
1003    /// implementation drops the row storage in bulk and bumps the table's major
1004    /// generation, so any cached indexes/subsets observed by future readers will
1005    /// be lazily rebuilt against the now-empty table. Any pending staged
1006    /// inserts or removes for this table are dropped (they pre-dated the clear,
1007    /// so they no longer make sense once the table is empty).
1008    ///
1009    /// This method also resets the cached column- and key-indexes for the
1010    /// table so subsequent merges can take the `Arc::get_mut`-based reset path,
1011    /// matching the invariant maintained by [`Database::merge_all`].
1012    ///
1013    /// This does **not** flush pending changes for *other* tables; it is the
1014    /// caller's responsibility to call [`Database::merge_all`] beforehand if
1015    /// they need staged updates from a previous step to land before the clear.
1016    pub fn clear_table(&mut self, table: TableId) {
1017        let info = self
1018            .tables
1019            .get_mut(table)
1020            .expect("must access a table that has been declared in this database");
1021        let prev_len = info.table.len();
1022        info.table.clear();
1023        // The version bump from `clear` is enough on its own to make the
1024        // indexes self-refresh on next access (see `Index::refresh`). We still
1025        // reset them eagerly here so that the next `merge_all` sees the same
1026        // "indexes are resettable" state it expects after a successful merge.
1027        info.column_indexes.update(|_, ti| {
1028            if let Some(arc) = Arc::get_mut(ti) {
1029                arc.reset();
1030            }
1031        });
1032        info.indexes.update(|_, ti| {
1033            if let Some(arc) = Arc::get_mut(ti) {
1034                arc.reset();
1035            }
1036        });
1037        self.total_size_estimate = self.total_size_estimate.wrapping_sub(prev_len);
1038    }
1039
1040    pub(crate) fn plan_query(&mut self, query: Query) -> Plan {
1041        let mut plan = plan::plan_query(query, ColumnCardEst::new(self));
1042        // Intern the successor family of every indexed access now, so nodes
1043        // shared across plans publish their children under ids that are fixed
1044        // before any rule set runs.
1045        let atoms = plan.atoms();
1046        plan.for_each_stages_mut(|stages| {
1047            let mut families = Vec::new();
1048            stages.for_each_indexed_access(|atom, columns, constraints| {
1049                let info = &mut self.tables[atoms[atom].table];
1050                let mut access = AccessFamilies::new();
1051                access.push(info.successor_family(columns[0], constraints));
1052                access.extend(
1053                    columns[1..]
1054                        .iter()
1055                        .map(|column| info.successor_family(*column, &[])),
1056                );
1057                families.push(access);
1058            });
1059            stages.set_families(families.into());
1060        });
1061        plan
1062    }
1063}
1064
1065impl Drop for Database {
1066    fn drop(&mut self) {
1067        // Clean up this thread's ambient memory pool.
1068        with_pool_set(PoolSet::clear);
1069    }
1070}
1071
1072/// The core logic behind getting and updating a hash index.
1073///
1074/// This is in a separate function to allow us to reuse it while already
1075/// borrowing a `TableInfo`.
1076fn get_index_from_tableinfo(table_info: &TableInfo, cols: &[ColumnId]) -> HashIndex {
1077    let index: Arc<_> = table_info.indexes.get_or_insert(cols.into(), || {
1078        Arc::new(ResettableOnceLock::new(Index::new(
1079            cols.to_vec(),
1080            TupleIndex::new(cols.len()),
1081        )))
1082    });
1083    index.get_or_update(|index| {
1084        index.refresh(table_info.table.as_ref());
1085    });
1086    debug_assert!(
1087        !index
1088            .get()
1089            .unwrap()
1090            .needs_refresh(table_info.table.as_ref())
1091    );
1092    index
1093}
1094
1095/// The core logic behind getting and updating a column index.
1096///
1097/// This is the single-column analog to [`get_index_from_tableinfo`].
1098pub(crate) fn get_column_index_from_tableinfo(
1099    table_info: &TableInfo,
1100    col: ColumnId,
1101) -> HashColumnIndex {
1102    let index: Arc<_> = table_info.column_indexes.get_or_insert(col, || {
1103        Arc::new(ResettableOnceLock::new(Index::new(
1104            vec![col],
1105            ColumnIndex::new(),
1106        )))
1107    });
1108    index.get_or_update(|index| {
1109        index.refresh(table_info.table.as_ref());
1110    });
1111    debug_assert!(
1112        !index
1113            .get()
1114            .unwrap()
1115            .needs_refresh(table_info.table.as_ref())
1116    );
1117    index
1118}
1119
1120#[derive(Clone)]
1121pub struct ColumnCardEst<'a> {
1122    db: &'a Database,
1123}
1124
1125impl ColumnCardEst<'_> {
1126    pub fn new(db: &Database) -> ColumnCardEst<'_> {
1127        ColumnCardEst { db }
1128    }
1129
1130    pub fn col_uniqueness(&self, table: TableId, col: ColumnId) -> ColUniqueness {
1131        let col_idx = get_column_index_from_tableinfo(&self.db.tables[table], col);
1132        let table = &self.db.tables[table].table;
1133        ColUniqueness {
1134            col_size: col_idx.get().unwrap().len(),
1135            table_size: table.len(),
1136        }
1137    }
1138}
1139
1140impl std::fmt::Debug for ColumnCardEst<'_> {
1141    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1142        f.debug_struct("ColumnCardEst").finish_non_exhaustive()
1143    }
1144}
1145
1146/// A coarse cardinality estimate for a column of a table, used by the query
1147/// planner to decide which variable to eliminate next during tree
1148/// decomposition.
1149///
1150/// `table_size` is the number of rows in the (sub)table and `col_size` is the
1151/// number of distinct values in the column. Their ratio
1152/// (`table_size / col_size`) approximates the average number of rows that share
1153/// a given value of the column: a smaller ratio means the column is closer to
1154/// being unique and therefore cheaper to join on. [`ColUniqueness`] is ordered
1155/// by this ratio (see the [`Ord`] impl), so the planner prefers variables with
1156/// the most selective (most unique) columns.
1157#[derive(Copy, Clone, Debug)]
1158pub struct ColUniqueness {
1159    table_size: usize,
1160    col_size: usize,
1161}
1162
1163impl Default for ColUniqueness {
1164    fn default() -> ColUniqueness {
1165        ColUniqueness {
1166            table_size: 1,
1167            col_size: 1,
1168        }
1169    }
1170}
1171
1172impl ColUniqueness {
1173    #[allow(dead_code)] // not yet wired up into the planner
1174    fn scale(&self, subset_size: usize) -> ColUniqueness {
1175        if self.table_size == 0 || subset_size == 0 {
1176            return ColUniqueness {
1177                table_size: 0,
1178                col_size: 0,
1179            };
1180        }
1181        ColUniqueness {
1182            table_size: subset_size,
1183            col_size: self.col_size.saturating_mul(subset_size) / self.table_size,
1184        }
1185    }
1186    fn join(&self, other: &ColUniqueness) -> ColUniqueness {
1187        ColUniqueness {
1188            table_size: self.table_size.saturating_mul(other.table_size),
1189            col_size: self.col_size.max(other.col_size),
1190        }
1191    }
1192
1193    #[allow(dead_code)] // not yet wired up into the planner
1194    fn col_size(&self) -> usize {
1195        self.col_size
1196    }
1197}
1198
1199impl PartialEq for ColUniqueness {
1200    fn eq(&self, other: &Self) -> bool {
1201        self.cmp(other) == std::cmp::Ordering::Equal
1202    }
1203}
1204
1205impl Eq for ColUniqueness {}
1206
1207impl PartialOrd for ColUniqueness {
1208    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1209        Some(self.cmp(other))
1210    }
1211}
1212
1213impl Ord for ColUniqueness {
1214    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1215        (self.table_size.saturating_mul(other.col_size))
1216            .cmp(&(other.table_size.saturating_mul(self.col_size)))
1217    }
1218}