egglog_core_relations/free_join/
execute.rs

1//! Core free join execution.
2//!
3//! The probe layer in `probe.rs` adapts every physical representation of an
4//! atom's current rows to the two operations needed by join execution: look up
5//! one key, or enumerate all keys. A probe may read a persistent table index, a
6//! tiny residual index, or an arena-allocated packed trie shared across plans
7//! when their roots match. It returns the matching rows in a representation
8//! that later stages can refine without copying them. This separation keeps the
9//! stage executor independent of the storage strategy selected for each access.
10//!
11//! The join-tail layer in `join_tail.rs` manages the state needed after
12//! execution enters the recursive portion of a plan. Its helpers determine
13//! which atom rows and materializations remain live, reorder the remaining
14//! stages with dynamic variable ordering (DVO), identify results that can stay
15//! factorized until action execution, and clone only the live state when work
16//! moves to another task. Index selection and probing remain in the probe
17//! layer; the join-tail layer decides their order and lifetime.
18
19use std::{cell::RefCell, cmp, mem, sync::Arc};
20
21use dashmap::mapref::{entry::Entry, one::RefMut};
22use egglog_concurrency::{Scope, SharedArena};
23use egglog_reports::{ReportLevel, RuleReport, RuleSetReport};
24use smallvec::SmallVec;
25use web_time::Instant;
26
27use crate::{
28    Constraint, OffsetRange, Pool, SubsetRef,
29    action::{Bindings, ExecutionState, ExecutionStateSeed, ExternalContext},
30    common::{DashMap, HashMap, IndexMap, Value},
31    numeric_id::{DenseIdMap, NumericId},
32    offsets::{Offsets, RowId, SortedOffsetVector, Subset},
33    parallel_heuristics::{
34        MIN_TOP_INDEX_KEYS_PER_WORKER, action_batch_size, free_join_can_fork,
35        free_join_fork_min_frames, parallelize_db_level_op, top_index_shape_is_eligible,
36    },
37    query::{Atom, RuleSet},
38    row_buffer::{RowBuffer, TaggedRowBuffer},
39    table_spec::{ColumnId, Offset, WrappedTableRef},
40};
41
42use super::{
43    ActionId, AtomId, ColumnIds, Database, TableId, Variable,
44    frame_update::{FrameUpdates, UpdateInstr},
45    join_tail::{
46        BindingInfo, BindingSet, BorrowedLocalState, InstrOrder, LeafScans, LocalState,
47        MatchCounter, RetiredLocalStates, SubsetClonePlan, atom_tail_use, estimate_size,
48        is_reorder_barrier, materialization_is_live_in_tail, select_next_stage,
49    },
50    packed_cache::{OwnedAtomRows, TrieCache},
51    packed_trie::{ChildShape, TrieNode},
52    plan::{JoinHeader, JoinStage, JoinStages, MatId, MatScanMode, MatSpec, Plan},
53    prepared_index::{
54        PreparedIndexRef, PreparedJoinIndexes, PreparedPlanIndexes, StageMask,
55        columns_are_cacheable,
56    },
57    probe::{
58        AtomRows, AtomRowsKind, CatalogFilter, Descent, LazyArenaHandle, PackedProbe, ProbeIndex,
59        ProbeRequest, Prober, SortedScalarProbe, seek_sorted_key,
60    },
61    residual_index::{SMALL_RESIDUAL, SmallColumnIndex, SmallExactProbe},
62    with_pool_set,
63};
64
65const TOP_COVER_PARTITIONS_PER_WORKER: usize = 4;
66const MIN_TOP_COVER_ROWS_PER_PARTITION: usize = 256;
67const TOP_INDEX_RANGES_PER_WORKER: usize = 32;
68
69/// Split a cover subset into bounded ordinal ranges without materializing its
70/// row IDs. Keeping several ranges per worker gives work stealing room to
71/// absorb join-selectivity skew while the minimum size keeps handoff coarse.
72fn top_cover_partitions(
73    cover_rows: usize,
74    workers: usize,
75    min_rows_per_partition: usize,
76) -> Option<Vec<TopLevelPartition>> {
77    if workers <= 1 || cover_rows < min_rows_per_partition.saturating_mul(workers) {
78        return None;
79    }
80
81    let target_partitions = workers.saturating_mul(TOP_COVER_PARTITIONS_PER_WORKER);
82    let rows_per_partition = cover_rows
83        .div_ceil(target_partitions)
84        .max(min_rows_per_partition);
85    let mut partitions = Vec::with_capacity(cover_rows.div_ceil(rows_per_partition));
86    for start in (0..cover_rows).step_by(rows_per_partition) {
87        partitions.push(TopLevelPartition::CoverRange {
88            start,
89            scan_size: cmp::min(rows_per_partition, cover_rows - start),
90        });
91    }
92    Some(partitions)
93}
94
95/// Split an unsharded scalar index into disjoint key-ordinal ranges.
96///
97/// Unlike scan-and-project partitioning, this borrows the scalar index that
98/// normal join execution has already built for the filtered root. It therefore
99/// adds no row-ID copy or second sort for seminaive and constrained subsets.
100/// The aggressive overpartitioning leaves enough independent work to absorb
101/// skew in the number of join results produced by each leading key.
102fn top_index_range_partitions(
103    leader_keys: usize,
104    workers: usize,
105    min_keys_per_worker: usize,
106) -> Option<Vec<TopLevelPartition>> {
107    if workers <= 1 || leader_keys < min_keys_per_worker.saturating_mul(workers) {
108        return None;
109    }
110
111    let target_partitions = workers.saturating_mul(TOP_INDEX_RANGES_PER_WORKER);
112    let keys_per_partition = leader_keys
113        .div_ceil(target_partitions)
114        .max(min_keys_per_worker);
115    let mut partitions = Vec::with_capacity(leader_keys.div_ceil(keys_per_partition));
116    for start in (0..leader_keys).step_by(keys_per_partition) {
117        partitions.push(TopLevelPartition::IndexRange {
118            start,
119            scan_size: cmp::min(keys_per_partition, leader_keys - start),
120        });
121    }
122    Some(partitions)
123}
124
125/// One coarse, disjoint partition used to drive the top join level.
126///
127/// Cached scalar intersections naturally partition by physical index shard.
128/// Filtered scalar indexes use borrowed key-ordinal ranges, and fused
129/// intersections use ordinal ranges of their cover subset. The range forms
130/// work for dense, sparse, whole-table, and seminaive subsets without copying
131/// row IDs. `scan_size` is the number of leader keys or cover rows in the
132/// partition.
133#[derive(Clone, Copy, Debug, Eq, PartialEq)]
134enum TopLevelPartition {
135    IndexShard { shard: usize, scan_size: usize },
136    IndexRange { start: usize, scan_size: usize },
137    CoverRange { start: usize, scan_size: usize },
138}
139
140impl TopLevelPartition {
141    fn scan_size(self) -> usize {
142        match self {
143            Self::IndexShard { scan_size, .. }
144            | Self::IndexRange { scan_size, .. }
145            | Self::CoverRange { scan_size, .. } => scan_size,
146        }
147    }
148}
149
150fn cover_scan_bounds(partition: Option<TopLevelPartition>, cover_rows: usize) -> (Offset, usize) {
151    match partition {
152        Some(TopLevelPartition::CoverRange { start, scan_size }) => {
153            debug_assert!(start <= cover_rows);
154            debug_assert!(scan_size <= cover_rows - start);
155            (Offset::from_usize(start), scan_size)
156        }
157        None => (Offset::new(0), cover_rows),
158        Some(TopLevelPartition::IndexShard { .. } | TopLevelPartition::IndexRange { .. }) => {
159            unreachable!("an index partition can only drive a scalar intersection")
160        }
161    }
162}
163
164impl Database {
165    /// Run `rule_set` to completion.
166    ///
167    /// `context` is visible to any external function the rules reach; pass
168    /// `None` if there is nothing to share.
169    pub fn run_rule_set(
170        &mut self,
171        rule_set: &RuleSet,
172        report_level: ReportLevel,
173        context: ExternalContext<'_>,
174    ) -> RuleSetReport {
175        if rule_set.plans.is_empty() {
176            return RuleSetReport::default();
177        }
178        let match_counter = Arc::new(MatchCounter::new(rule_set.actions.n_ids()));
179        // Every packed trie node of this run lives in one arena. Nodes below a
180        // shared root are published to every plan, so they must outlive the
181        // plan that built them; the arena is dropped with the trie cache
182        // after all plans finish and before catalog indexes reset.
183        let arena = SharedArena::new();
184        // Trie roots and everything built below them are shared across all
185        // plans in this run. Tables are frozen for the duration, so a given
186        // root key always denotes the same subset; the cache is scoped to (and
187        // dropped at the end of) this call. Only roots used by more than one
188        // plan are shared: `None` means `root_node` builds fresh per-plan roots
189        // with zero added work — no signature machinery and (crucially on
190        // many-core hosts) no DashMap allocation. The pre-pass is a cheap scan
191        // of the plans' atoms; the shard count is matched to the thread count
192        // (see `with_shared`).
193        let trie_cache: Option<Arc<TrieCache>> = {
194            let shared =
195                TrieCache::compute_shared(rule_set.plans.values().map(|(plan, _, _)| plan));
196            (!shared.is_empty()).then(|| Arc::new(TrieCache::with_shared(shared)))
197        };
198
199        let search_and_apply_timer = Instant::now();
200        // let mut rule_reports: HashMap<String, Vec<RuleReport>>;
201        let mut rule_reports: HashMap<Arc<str>, Vec<RuleReport>>;
202        let exec_state = ExecutionState::new(self.read_only_view_with(context), Default::default());
203        if parallelize_db_level_op(self.total_size_estimate) {
204            let dash_rule_reports: Arc<DashMap<Arc<str>, Vec<RuleReport>>> =
205                Arc::new(DashMap::default());
206            let db: &Database = self;
207            egglog_concurrency::scope(|scope| {
208                for (plan, desc, symbol_map) in rule_set.plans.values() {
209                    let report_plan = match report_level {
210                        ReportLevel::TimeOnly => None,
211                        ReportLevel::WithPlan | ReportLevel::StageInfo => {
212                            Some(plan.to_report(symbol_map))
213                        }
214                    };
215
216                    let dash_rule_reports = dash_rule_reports.clone();
217                    let desc = desc.clone();
218                    let exec_state = exec_state.seed();
219                    let match_counter = match_counter.clone();
220                    let trie_cache = trie_cache.clone();
221                    let arena = &arena;
222                    scope.spawn(move |_| {
223                        let search_and_apply_timer = Instant::now();
224                        let join_state = JoinState::new(db, exec_state, trie_cache, arena);
225                        let mut binding_info = BindingInfo::default();
226                        let mut roots_ready = true;
227                        for (id, info) in plan.atoms().iter() {
228                            let headers: SmallVec<[&JoinHeader; 2]> =
229                                plan.header().iter().filter(|h| h.atom == id).collect();
230                            match join_state.root_node(info.table, &headers) {
231                                Some(node) => binding_info.insert_node(id, node),
232                                None => {
233                                    roots_ready = false;
234                                    break;
235                                }
236                            }
237                        }
238
239                        // Prepared slots are execution-local and can be large.
240                        // Empty roots are common in fixpoint confirmation
241                        // passes, so do not construct the sidecar until the
242                        // query can actually run.
243                        let prepared_index =
244                            roots_ready.then(|| PreparedPlanIndexes::new(db, plan));
245                        let search_and_apply_time = egglog_concurrency::scope(|query_scope| {
246                            let mut action_buf = ScopedActionBuffer::new(
247                                query_scope,
248                                rule_set,
249                                match_counter.clone(),
250                            );
251
252                            'eval: {
253                                let Some(prepared_index) = prepared_index.as_ref() else {
254                                    break 'eval;
255                                };
256                                match (plan, prepared_index) {
257                                    (
258                                        Plan::SinglePlan(plan),
259                                        PreparedPlanIndexes::Single(prepared),
260                                    ) => {
261                                        join_state.run_join_stages(
262                                            &plan.stages,
263                                            prepared,
264                                            &plan.atoms,
265                                            plan.actions,
266                                            &mut binding_info,
267                                            &mut action_buf,
268                                        );
269                                    }
270                                    (
271                                        Plan::DecomposedPlan(plan),
272                                        PreparedPlanIndexes::Decomposed {
273                                            blocks: prepared_blocks,
274                                            result: prepared_result,
275                                        },
276                                    ) => {
277                                        let mut materializations: DenseIdMap<
278                                            MatId,
279                                            Arc<DashMap<Vec<Value>, RowBuffer>>,
280                                        > = DenseIdMap::with_capacity(plan.stages.blocks.len());
281                                        for i in 0..plan.stages.blocks.len() {
282                                            materializations.insert(
283                                                MatId::from_usize(i),
284                                                Arc::new(Default::default()),
285                                            );
286                                        }
287                                        let specs: Arc<DenseIdMap<MatId, MatSpec>> = Arc::new(
288                                            plan.stages
289                                                .blocks
290                                                .iter()
291                                                .enumerate()
292                                                .map(|(i, block)| {
293                                                    (MatId::from_usize(i), block.1.clone())
294                                                })
295                                                .collect(),
296                                        );
297                                        let mut materializations = Arc::new(materializations);
298
299                                        for (mat_id, (stage_block, prepared_block)) in plan
300                                            .stages
301                                            .blocks
302                                            .iter()
303                                            .zip(prepared_blocks)
304                                            .enumerate()
305                                        {
306                                            let mat_id = MatId::from_usize(mat_id);
307                                            // Keep task-local join state alive until the stage has
308                                            // quiesced. Besides making destruction deterministic,
309                                            // this prevents many workers from concurrently decrementing
310                                            // the same plan-state Arc counters as their tasks finish.
311                                            let retired_states = RetiredLocalStates::default();
312                                            egglog_concurrency::scope(|stage_scope| {
313                                                let mut materializer = ScopedMaterializer {
314                                                    scope: stage_scope,
315                                                    retired_states: &retired_states,
316                                                    specs: specs.clone(),
317                                                    materializations: materializations.clone(),
318                                                    scratch_key: Default::default(),
319                                                    scratch_val: Default::default(),
320                                                };
321                                                join_state.run_join_stages(
322                                                    &stage_block.0,
323                                                    prepared_block,
324                                                    &plan.atoms,
325                                                    mat_id,
326                                                    &mut binding_info,
327                                                    &mut materializer,
328                                                );
329                                            });
330                                            if materializations[mat_id].is_empty() {
331                                                break 'eval;
332                                            }
333                                            assert_eq!(Arc::strong_count(&materializations), 1);
334                                            let mut materializations_dearc =
335                                                Arc::unwrap_or_clone(materializations);
336                                            let materialization = mem::take(
337                                                Arc::get_mut(&mut materializations_dearc[mat_id])
338                                                    .unwrap(),
339                                            )
340                                            .into_iter()
341                                            .collect::<IndexMap<_, _>>();
342                                            binding_info
343                                                .materializations
344                                                .insert(mat_id, Arc::new(materialization));
345                                            materializations = Arc::new(materializations_dearc);
346                                        }
347                                        join_state.run_join_stages(
348                                            &plan.result_block,
349                                            prepared_result,
350                                            &plan.atoms,
351                                            plan.actions,
352                                            &mut binding_info,
353                                            &mut action_buf,
354                                        );
355                                    }
356                                    _ => {
357                                        unreachable!("prepared plan shape must match logical plan")
358                                    }
359                                }
360                            }
361                            // Preserve the historical per-rule timing boundary: the
362                            // ruleset-wide timer includes this final flush, but the
363                            // individual rule report does not.
364                            let search_and_apply_time = search_and_apply_timer.elapsed();
365                            if action_buf.needs_flush {
366                                action_buf.flush(&mut exec_state.to_execution_state());
367                            }
368                            search_and_apply_time
369                        });
370
371                        drop(binding_info);
372                        drop(prepared_index);
373                        drop(join_state);
374
375                        let mut rule_report: RefMut<'_, Arc<str>, Vec<RuleReport>> =
376                            dash_rule_reports.entry(desc).or_default();
377                        rule_report.value_mut().push(RuleReport {
378                            plan: report_plan,
379                            search_and_apply_time,
380                            num_matches: usize::MAX,
381                        });
382                    });
383                }
384            });
385            rule_reports = dash_rule_reports
386                .iter()
387                .map(|entry| (entry.key().clone(), entry.value().clone()))
388                .collect();
389        } else {
390            rule_reports = HashMap::default();
391            // Serial plans share the worker's scratch and arena handle, as in
392            // the original executor. Bindings and prepared index handles stay
393            // plan-local; packed nodes already live for the entire ruleset.
394            let join_state = JoinState::new(self, exec_state.seed(), trie_cache.clone(), &arena);
395            // Just run all of the plans in order with a single in-place action
396            // buffer.
397            let mut action_buf = InPlaceActionBuffer {
398                rule_set,
399                match_counter: match_counter.as_ref(),
400                batches: Default::default(),
401            };
402            for (plan, desc, symbol_map) in rule_set.plans.values() {
403                let report_plan = match report_level {
404                    ReportLevel::TimeOnly => None,
405                    ReportLevel::WithPlan | ReportLevel::StageInfo => {
406                        Some(plan.to_report(symbol_map))
407                    }
408                };
409
410                let search_and_apply_timer = Instant::now();
411                {
412                    let mut binding_info = BindingInfo::default();
413                    'eval: {
414                        for (id, info) in plan.atoms().iter() {
415                            let headers: SmallVec<[&JoinHeader; 2]> =
416                                plan.header().iter().filter(|h| h.atom == id).collect();
417                            match join_state.root_node(info.table, &headers) {
418                                Some(node) => binding_info.insert_node(id, node),
419                                None => break 'eval,
420                            }
421                        }
422                        // See the parallel path above.
423                        let prepared_index = PreparedPlanIndexes::new(self, plan);
424                        match (plan, &prepared_index) {
425                            (Plan::SinglePlan(plan), PreparedPlanIndexes::Single(prepared)) => {
426                                join_state.run_join_stages(
427                                    &plan.stages,
428                                    prepared,
429                                    &plan.atoms,
430                                    plan.actions,
431                                    &mut binding_info,
432                                    &mut action_buf,
433                                );
434                            }
435                            (
436                                Plan::DecomposedPlan(plan),
437                                PreparedPlanIndexes::Decomposed {
438                                    blocks: prepared_blocks,
439                                    result: prepared_result,
440                                },
441                            ) => {
442                                let mut materializations =
443                                    DenseIdMap::with_capacity(plan.stages.blocks.len());
444                                for i in 0..plan.stages.blocks.len() {
445                                    materializations
446                                        .insert(MatId::from_usize(i), Default::default());
447                                }
448                                let mut materializer = InPlaceMaterializer {
449                                    specs: &plan
450                                        .stages
451                                        .blocks
452                                        .iter()
453                                        .enumerate()
454                                        .map(|(i, block)| (MatId::from_usize(i), block.1.clone()))
455                                        .collect(),
456                                    materializations,
457                                    scratch_key: Default::default(),
458                                    scratch_val: Default::default(),
459                                };
460
461                                for (mat_id, (stage_block, prepared_block)) in
462                                    plan.stages.blocks.iter().zip(prepared_blocks).enumerate()
463                                {
464                                    let mat_id = MatId::from_usize(mat_id);
465                                    join_state.run_join_stages(
466                                        &stage_block.0,
467                                        prepared_block,
468                                        &plan.atoms,
469                                        mat_id,
470                                        &mut binding_info,
471                                        &mut materializer,
472                                    );
473                                    if materializer.materializations[mat_id].is_empty() {
474                                        break 'eval;
475                                    }
476                                    binding_info.materializations.insert(
477                                        mat_id,
478                                        Arc::new(
479                                            materializer.materializations.take(mat_id).unwrap(),
480                                        ),
481                                    );
482                                }
483                                join_state.run_join_stages(
484                                    &plan.result_block,
485                                    prepared_result,
486                                    &plan.atoms,
487                                    plan.actions,
488                                    &mut binding_info,
489                                    &mut action_buf,
490                                );
491                            }
492                            _ => unreachable!("prepared plan shape must match logical plan"),
493                        }
494                    }
495                }
496                let search_and_apply_time = search_and_apply_timer.elapsed();
497
498                // TODO: unnecessary cloning in many cases
499                let rule_report = rule_reports.entry(desc.clone()).or_default();
500                rule_report.push(RuleReport {
501                    plan: report_plan,
502                    search_and_apply_time,
503                    num_matches: usize::MAX,
504                });
505            }
506            action_buf.flush(&mut exec_state.clone());
507        }
508
509        for (plan, desc, _symbol_map) in rule_set.plans.values() {
510            let reports = rule_reports.get_mut(desc).unwrap();
511            let i = reports
512                .iter()
513                // HACK: Since the order of visiting queries is fixed and # matches need to be obtained
514                // seperately from rule execution, we first set all # matches to be usize::MAX and then fill
515                // them in one by one.
516                .position(|r| r.num_matches == usize::MAX)
517                .unwrap();
518            // NB: This requires each action ID correspond to only one query.
519            // If an action is used by multiple queries, then we can't tell how many matches are
520            // caused by individual queries.
521            reports[i].num_matches = match_counter.read_matches(plan.actions());
522        }
523        // No query can use the shared tries after the execution scopes above
524        // have joined. Release them before merging table updates so the two
525        // allocation peaks do not overlap and no arena address outlives its
526        // catalog index.
527        drop(trie_cache);
528        drop(arena);
529        let search_and_apply_time = search_and_apply_timer.elapsed();
530
531        let merge_timer = Instant::now();
532        let changed = self.merge_all();
533        let merge_time = merge_timer.elapsed();
534
535        RuleSetReport {
536            changed,
537            rule_reports,
538            search_and_apply_time,
539            merge_time,
540        }
541    }
542}
543
544struct ActionState {
545    n_runs: usize,
546    len: usize,
547    bindings: Bindings,
548}
549
550impl ActionState {
551    fn new(batch_size: usize) -> Self {
552        Self {
553            n_runs: 0,
554            len: 0,
555            bindings: Bindings::new(batch_size),
556        }
557    }
558}
559
560/// Worker-local resources for joins in one ruleset run.
561///
562/// Serial plans and recursive calls to [`JoinState::run_plan`] reuse the frozen
563/// database view, early-stop state, allocation handle, and scan/sort scratch.
564/// Parallel tasks construct their own `JoinState`, sharing the database,
565/// cross-plan root cache, and query arena while retaining independent handles
566/// and scratch storage.
567///
568/// The current variable bindings and atom row subsets are deliberately not
569/// stored here: they describe one recursive branch and live in `BindingInfo`.
570/// Likewise, the logical stages and their current physical order are explicit
571/// arguments to `run_plan`.
572struct JoinState<'db, 'state, 'exec> {
573    /// Database owning the frozen tables queried by this plan.
574    db: &'db Database,
575    /// Copyable query-side database view and shared early-stop flag.
576    exec_state: ExecutionStateSeed<'db, 'state>,
577    /// Cached thread-local pool for SortedOffsetVector allocations.
578    /// Stored here to avoid a per-call `with_pool_set` TLS access in `get_index`.
579    pool: Pool<SortedOffsetVector>,
580    /// Cross-plan trie cache for the current `run_rule_set`, or `None` when
581    /// nothing is reused across plans.
582    trie_cache: Option<Arc<TrieCache>>,
583    /// Run-scoped arena holding every packed trie node of this `run_rule_set`.
584    arena: &'exec SharedArena,
585    /// This worker's lazily initialized allocation handle into `arena`.
586    handle: LazyArenaHandle<'exec>,
587    /// Reused `(value, row)` workspace for constructing packed trie nodes.
588    packed_scratch: RefCell<Vec<(Value, RowId)>>,
589}
590
591impl<'a, 'state, 'exec> JoinState<'a, 'state, 'exec> {
592    fn new(
593        db: &'a Database,
594        exec_state: ExecutionStateSeed<'a, 'state>,
595        trie_cache: Option<Arc<TrieCache>>,
596        arena: &'exec SharedArena,
597    ) -> Self {
598        Self {
599            db,
600            exec_state,
601            pool: with_pool_set(|ps| ps.get_pool()),
602            trie_cache,
603            arena,
604            handle: LazyArenaHandle::new(arena),
605            packed_scratch: RefCell::new(Vec::new()),
606        }
607    }
608
609    /// Look up (or create) the root trie node for `atom` given all of its
610    /// headers.
611    ///
612    /// An atom may carry more than one header (e.g. seminaive adds a timestamp
613    /// constraint on top of the plan's original fast constraints); the root
614    /// subset is the whole table intersected with every header subset. Returns
615    /// `None` when that subset is empty.
616    ///
617    /// Roots whose signature is used by more than one plan (see
618    /// [`TrieCache::shared`]) are shared through the cache; the rest are built
619    /// fresh per plan so the pool can recycle them.
620    fn root_node(&self, table_id: TableId, headers: &[&JoinHeader]) -> Option<Arc<OwnedAtomRows>> {
621        // Fast path: when sharing is disabled this run (small database, or no
622        // root reused across plans), skip the root-signature machinery entirely
623        // and build a fresh per-plan root — matching the pre-sharing behavior at
624        // no added cost.
625        let Some(trie_cache) = self.trie_cache.as_ref() else {
626            return Some(Arc::new(OwnedAtomRows::new(
627                self.build_root_subset(table_id, headers)?,
628            )));
629        };
630        // The base identity is the union of all fast constraints on this atom.
631        let mut fast: SmallVec<[Constraint; 2]> = SmallVec::new();
632        for h in headers {
633            fast.extend(h.constraints.iter().cloned());
634        }
635        fast.sort_unstable();
636        let sig = (table_id, fast);
637
638        if !trie_cache.shared.contains(&sig) {
639            // Not reused across plans: build a fresh, unshared root.
640            return Some(Arc::new(OwnedAtomRows::new(
641                self.build_root_subset(table_id, headers)?,
642            )));
643        }
644
645        let header = trie_cache.header_id(&sig.1);
646        let key = (table_id, header);
647        if let Some(node) = trie_cache.roots.get(&key) {
648            return (!node.subset.is_empty()).then(|| node.clone());
649        }
650        let subset = self.build_root_subset(table_id, headers)?;
651        let node = match trie_cache.roots.entry(key) {
652            Entry::Occupied(o) => o.get().clone(),
653            Entry::Vacant(v) => {
654                let node = Arc::new(OwnedAtomRows::new_shared(subset));
655                v.insert(node.clone());
656                node
657            }
658        };
659        (!node.subset.is_empty()).then_some(node)
660    }
661
662    /// The root subset for `table_id`: the whole table intersected with every
663    /// header subset. Returns `None` if the result is empty.
664    fn build_root_subset(&self, table_id: TableId, headers: &[&JoinHeader]) -> Option<Subset> {
665        let mut subset = self.db.get_table(table_id).all();
666        for h in headers {
667            if h.subset.is_empty() {
668                return None;
669            }
670            subset.intersect(h.subset.as_ref(), &self.pool);
671            if subset.is_empty() {
672                return None;
673            }
674        }
675        Some(subset)
676    }
677
678    /// Build a packed index for one column of `subset` after applying the slow
679    /// `constraints`. `shared` marks a node published to every plan of the run.
680    ///
681    /// `subset_may_contain_stale_rows` describes the source subset, not the
682    /// resulting node. Physical root ranges, dense ranges, and persistent
683    /// catalog groups can contain tombstoned row ids, whereas packed child
684    /// subsets and filtered residuals already contain only live rows. When
685    /// constraints require materializing a filtered subset, potentially stale
686    /// inputs are refined to live rows first. With no constraints, the table
687    /// scan used by `TrieNode::build_from_subset` already skips stale rows.
688    #[allow(clippy::too_many_arguments)]
689    fn build_packed_node(
690        &self,
691        table: WrappedTableRef<'_>,
692        subset: SubsetRef<'_>,
693        subset_may_contain_stale_rows: bool,
694        constraints: &[Constraint],
695        column: ColumnId,
696        child_shape: ChildShape,
697        shared: bool,
698    ) -> &'exec TrieNode<'exec> {
699        if constraints.is_empty() {
700            // Table scans already omit stale SortedWritesTable rows, so a
701            // separate live-subset pass would only scan the same root twice.
702            return TrieNode::build_from_subset(
703                self.handle.get(),
704                table,
705                subset,
706                column,
707                child_shape,
708                shared,
709                &mut self.packed_scratch.borrow_mut(),
710            );
711        }
712        let mut filtered = subset.to_owned(&self.pool);
713        if subset_may_contain_stale_rows && table.has_stale_rows() {
714            filtered = table.refine_live(filtered);
715        }
716        filtered = table.refine(filtered, constraints);
717        TrieNode::build_from_subset(
718            self.handle.get(),
719            table,
720            filtered.as_ref(),
721            column,
722            child_shape,
723            shared,
724            &mut self.packed_scratch.borrow_mut(),
725        )
726    }
727
728    /// `shared_child_shape` is the table's child storage for shared nodes
729    /// (see `TableInfo::shared_child_shape`).
730    #[allow(clippy::too_many_arguments)]
731    fn packed_index_for_rows<'rows>(
732        &self,
733        rows: &AtomRows<'rows, 'exec>,
734        table: WrappedTableRef<'_>,
735        constraints: &[Constraint],
736        column: ColumnId,
737        child_shape: ChildShape,
738        shared_child_shape: ChildShape,
739        prepared: PreparedIndexRef<'rows>,
740    ) -> &'exec TrieNode<'exec>
741    where
742        'exec: 'rows,
743    {
744        // Below a shared node or continuation cache, the child is published
745        // under this access's table-wide family with the table's shared shape, so every
746        // plan reaching these rows finds the same node. Otherwise the child is
747        // plan-local, keyed by access id with the plan's own tail shape.
748        let shared_child = |shared: bool| {
749            if shared {
750                (prepared.families[0].index(), shared_child_shape)
751            } else {
752                (prepared.access.index(), child_shape)
753            }
754        };
755        match rows.kind() {
756            AtomRowsKind::Owned(root) if !root.is_plan_root() => self.build_packed_node(
757                table,
758                root.subset.as_ref(),
759                false,
760                constraints,
761                column,
762                child_shape,
763                false,
764            ),
765            AtomRowsKind::Owned(root) => {
766                let shared = root.is_shared();
767                let child_shape = if shared {
768                    shared_child_shape
769                } else {
770                    child_shape
771                };
772                let address = prepared.packed_root(|| {
773                    let build = || {
774                        self.build_packed_node(
775                            table,
776                            root.subset.as_ref(),
777                            true,
778                            constraints,
779                            column,
780                            child_shape,
781                            shared,
782                        ) as *const TrieNode<'exec> as usize
783                    };
784                    if shared {
785                        let ChildShape::Dynamic { families } = shared_child_shape else {
786                            unreachable!("an indexed shared root has successor families")
787                        };
788                        *root
789                            .packed_root_slot(prepared.families[0], families)
790                            .unwrap()
791                            .get_or_init(build)
792                    } else {
793                        build()
794                    }
795                });
796                // SAFETY: the slot is plan-execution scoped and can only be
797                // initialized with a node from the run's SharedArena.
798                let node = unsafe { &*(address as *const TrieNode<'exec>) };
799                assert_eq!(node.child_shape(), child_shape);
800                node
801            }
802            AtomRowsKind::Catalog {
803                subset,
804                continuation,
805            } => {
806                let continuation = continuation
807                    .expect("catalog rows needed a continuation slot for a later atom probe");
808                let shared = continuation.cache.is_shared();
809                let (family, child_shape) = shared_child(shared);
810                let slot = continuation.cache.slot(continuation.position, family);
811                let address = *slot.get_or_init(|| {
812                    self.build_packed_node(
813                        table,
814                        *subset,
815                        true,
816                        constraints,
817                        column,
818                        child_shape,
819                        shared,
820                    ) as *const TrieNode<'exec> as usize
821                });
822                // SAFETY: root continuation slots only publish nodes from the
823                // run's SharedArena.
824                let node = unsafe { &*(address as *const TrieNode<'exec>) };
825                assert_eq!(node.child_shape(), child_shape);
826                node
827            }
828            AtomRowsKind::Packed(cursor) => {
829                let shared = cursor.node().is_shared();
830                let (family, child_shape) = shared_child(shared);
831                cursor.child_index_with(self.handle.get(), family, child_shape, || {
832                    self.build_packed_node(
833                        table,
834                        cursor.subset(),
835                        false,
836                        constraints,
837                        column,
838                        child_shape,
839                        shared,
840                    )
841                })
842            }
843            AtomRowsKind::Inline(..) => {
844                unreachable!("inline residuals must use a stack-owned probe")
845            }
846            AtomRowsKind::Dense(range) => self.build_packed_node(
847                table,
848                SubsetRef::Dense(*range),
849                true,
850                constraints,
851                column,
852                child_shape,
853                false,
854            ),
855        }
856    }
857
858    fn get_index<'ctx, 'rows>(
859        &'ctx self,
860        atoms: &Arc<DenseIdMap<AtomId, Atom>>,
861        binding_info: &mut BindingInfo<'rows, 'exec>,
862        request: ProbeRequest<'ctx, 'rows>,
863    ) -> Prober<'ctx, 'rows, 'exec>
864    where
865        'exec: 'rows,
866    {
867        let ProbeRequest {
868            atom,
869            columns: cols,
870            constraints,
871            keep_rows,
872            terminal_child_shape,
873            prepared,
874        } = request;
875        assert!(
876            !cols.is_empty(),
877            "a join index must project at least one column"
878        );
879        let source = binding_info.subsets.unwrap_val(atom);
880
881        let table_id = atoms[atom].table;
882        let info = &self.db.tables[table_id];
883        // Match the original executor's ordering: residual probes do not
884        // consult table-wide catalog metadata or obtain the whole-table range.
885        // A tiny source is cheaper to index on the stack than as a packed
886        // node, unless it has a publication slot: the same packed cursor or
887        // continuation key is typically probed many times per run, so the
888        // packed node built once is reused from the slot.
889        let has_slot = matches!(
890            source.kind(),
891            AtomRowsKind::Packed(_)
892                | AtomRowsKind::Catalog {
893                    continuation: Some(_),
894                    ..
895                }
896        );
897        if cols.len() == 1 && source.size() <= SMALL_RESIDUAL && !has_slot {
898            let ix = ProbeIndex::SmallColumn(SmallColumnIndex::new(
899                info.table.as_ref(),
900                source.subset(),
901                constraints,
902                cols[0],
903            ));
904            return Prober {
905                source,
906                ix,
907                keep_rows,
908            };
909        }
910        if let AtomRowsKind::Inline(rows) = source.kind() {
911            let ix = ProbeIndex::SmallExact(SmallExactProbe::new(
912                info.table.as_ref(),
913                *rows,
914                cols,
915                constraints,
916            ));
917            return Prober {
918                source,
919                ix,
920                keep_rows,
921            };
922        }
923        let shared_child_shape = info.shared_child_shape();
924        // Only a dense root can use a table-wide catalog. Residual packed
925        // cursors already select their continuation index, so do not repeat
926        // whole-table metadata work for them (including tiny cached groups).
927        let catalog_intersection = match source.kind() {
928            AtomRowsKind::Owned(root) if constraints.is_empty() || !root.is_shared() => {
929                if let Subset::Dense(range) = &root.subset
930                    && columns_are_cacheable(info, &cols)
931                {
932                    let whole_table = info.table.all();
933                    (whole_table.size() / 2 < source.size()).then(|| {
934                        let needs_intersect = !(whole_table.is_dense()
935                            && root.subset.bounds() == whole_table.bounds());
936                        needs_intersect.then_some(*range)
937                    })
938                } else {
939                    None
940                }
941            }
942            _ => None,
943        };
944
945        let ix = if let Some(intersect_outer) = catalog_intersection {
946            // Below a shared root, the catalog key positions identify the same
947            // rows for every plan, so the continuation cache is shared too. A
948            // terminal probe never continues, so it skips the lookup.
949            let shared_continuations = match source.kind() {
950                AtomRowsKind::Owned(root)
951                    if terminal_child_shape != ChildShape::Leaf && self.trie_cache.is_some() =>
952                {
953                    prepared.shared_catalog_continuations(root, &cols)
954                }
955                _ => None,
956            };
957            let (continuations, continuation_shape) = if terminal_child_shape == ChildShape::Leaf {
958                (None, ChildShape::Leaf)
959            } else {
960                match shared_continuations {
961                    Some(continuations) => (Some(continuations), shared_child_shape),
962                    None => (Some(prepared.local_continuations()), terminal_child_shape),
963                }
964            };
965            let filter = CatalogFilter {
966                table: info.table.as_ref(),
967                constraints,
968                check_live: info.table.has_stale_rows(),
969            };
970            if cols.len() == 1 {
971                let index = prepared.column_index(info, cols[0]);
972                if let Some(continuations) = continuations {
973                    continuations.prepare(continuation_shape, index.shard_count(), |shard| {
974                        index.shard_len(shard)
975                    });
976                }
977                ProbeIndex::CachedColumn {
978                    intersect_outer,
979                    table: index,
980                    continuations,
981                    child_shape: terminal_child_shape,
982                    filter,
983                }
984            } else {
985                let index = prepared.tuple_index(info, cols.as_slice());
986                if let Some(continuations) = continuations {
987                    continuations.prepare(continuation_shape, index.shard_count(), |shard| {
988                        index.shard_len(shard)
989                    });
990                }
991                ProbeIndex::CachedTuple {
992                    intersect_outer,
993                    table: index,
994                    continuations,
995                    child_shape: terminal_child_shape,
996                    filter,
997                }
998            }
999        } else {
1000            let first_child_shape = if cols.len() > 1 {
1001                ChildShape::Direct
1002            } else {
1003                terminal_child_shape
1004            };
1005            let first = self.packed_index_for_rows(
1006                &source,
1007                info.table.as_ref(),
1008                constraints,
1009                cols[0],
1010                first_child_shape,
1011                shared_child_shape,
1012                prepared,
1013            );
1014            if cols.len() == 1 {
1015                ProbeIndex::PackedColumn(first)
1016            } else {
1017                let descent = if first.is_shared() {
1018                    Descent::Shared {
1019                        child_shape: shared_child_shape,
1020                        families: prepared.families,
1021                    }
1022                } else {
1023                    Descent::Local {
1024                        terminal_child_shape,
1025                    }
1026                };
1027                ProbeIndex::Packed(PackedProbe {
1028                    first,
1029                    columns: cols,
1030                    table: info.table.as_ref(),
1031                    handle: &self.handle,
1032                    scratch: &self.packed_scratch,
1033                    descent,
1034                })
1035            }
1036        };
1037        Prober {
1038            source,
1039            ix,
1040            keep_rows,
1041        }
1042    }
1043
1044    /// Describe an eligible scalar index that could drive a top-level
1045    /// generic-join intersection.
1046    ///
1047    /// This mirrors leader selection and child-index shape in
1048    /// [`Self::run_plan`]. Probers move trie nodes out of `binding_info`, so
1049    /// restore every node before returning. Persistent catalog indexes use
1050    /// their physical hash shards, including when a dense timestamp range is
1051    /// intersected at probe time. Packed filtered roots use
1052    /// disjoint ordinal ranges of the already-built scalar index, avoiding a
1053    /// scan-and-project handoff copy. Tiny leaders stay on the existing path.
1054    #[allow(clippy::too_many_arguments)]
1055    fn top_index_partitions<'rows, M: StageMask>(
1056        &self,
1057        stages: &JoinStages,
1058        stage_index: usize,
1059        prepared: &'rows PreparedJoinIndexes,
1060        atoms: &Arc<DenseIdMap<AtomId, Atom>>,
1061        order: &InstrOrder,
1062        binding_info: &mut BindingInfo<'rows, 'exec>,
1063        workers: usize,
1064    ) -> Option<Vec<TopLevelPartition>>
1065    where
1066        'exec: 'rows,
1067    {
1068        let JoinStage::Intersect { scans, .. } = &stages.instrs[stage_index] else {
1069            return None;
1070        };
1071        if scans.is_empty()
1072            || workers <= 1
1073            || estimate_size(&stages.instrs[stage_index], binding_info)
1074                < MIN_TOP_INDEX_KEYS_PER_WORKER.saturating_mul(workers)
1075        {
1076            return None;
1077        }
1078        let stage_prepared = prepared.stage(stage_index);
1079        debug_assert_eq!(scans.len(), stage_prepared.len());
1080        let remaining_after_current = prepared
1081            .all_stage_mask::<M>()
1082            .map(|remaining| remaining & !M::stage_bit(stage_index));
1083
1084        let mut leader = 0;
1085        let mut leader_size = usize::MAX;
1086        let mut probers = Vec::with_capacity(scans.len());
1087        for (i, (scan, prepared_slot)) in scans.iter().zip(stage_prepared).enumerate() {
1088            let tail = atom_tail_use(
1089                scan.atom,
1090                &stages.instrs,
1091                prepared,
1092                remaining_after_current,
1093                order,
1094                1,
1095            );
1096            let prober = self.get_index(
1097                atoms,
1098                binding_info,
1099                ProbeRequest::column(
1100                    scan,
1101                    false,
1102                    tail.child_shape,
1103                    prepared.resolve(prepared_slot),
1104                ),
1105            );
1106            let size = prober.len();
1107            if size < leader_size {
1108                leader = i;
1109                leader_size = size;
1110            }
1111            probers.push(prober);
1112        }
1113        let partitions = if let Some(shard_count) = probers[leader].shard_count() {
1114            let shards = (0..shard_count)
1115                .filter_map(|shard| {
1116                    let scan_size = probers[leader].shard_len(shard).unwrap_or(0);
1117                    (scan_size != 0).then_some(TopLevelPartition::IndexShard { shard, scan_size })
1118                })
1119                .collect::<Vec<_>>();
1120            top_index_shape_is_eligible(
1121                workers,
1122                leader_size,
1123                shards.len(),
1124                MIN_TOP_INDEX_KEYS_PER_WORKER,
1125            )
1126            .then_some(shards)
1127        } else {
1128            top_index_range_partitions(leader_size, workers, MIN_TOP_INDEX_KEYS_PER_WORKER)
1129        };
1130        for (scan, prober) in scans.iter().zip(probers) {
1131            binding_info.move_back(scan.atom, prober);
1132        }
1133        partitions
1134    }
1135
1136    /// Return coarse partitions for the stage already sorted to the top of the
1137    /// join. Cached scalar intersections use physical index shards, while
1138    /// fused intersections use ordinal ranges of their cover subset. Later
1139    /// stages are deliberately not promoted.
1140    fn select_top_partitions<'rows, M: StageMask>(
1141        &self,
1142        stages: &JoinStages,
1143        prepared: &'rows PreparedJoinIndexes,
1144        atoms: &Arc<DenseIdMap<AtomId, Atom>>,
1145        order: &InstrOrder,
1146        binding_info: &mut BindingInfo<'rows, 'exec>,
1147    ) -> Option<Vec<TopLevelPartition>>
1148    where
1149        'exec: 'rows,
1150    {
1151        if order.len() == 0 {
1152            return None;
1153        }
1154
1155        let stage_index = order.get(0);
1156        let workers = crate::parallel::current_num_threads();
1157        let stage = &stages.instrs[stage_index];
1158        match stage {
1159            JoinStage::Intersect { .. } => self.top_index_partitions::<M>(
1160                stages,
1161                stage_index,
1162                prepared,
1163                atoms,
1164                order,
1165                binding_info,
1166                workers,
1167            ),
1168            JoinStage::FusedIntersect { cover, .. } => top_cover_partitions(
1169                binding_info.subsets[cover.to_index.atom].size(),
1170                workers,
1171                MIN_TOP_COVER_ROWS_PER_PARTITION,
1172            ),
1173            JoinStage::FusedIntersectMat { .. } => None,
1174        }
1175    }
1176
1177    /// Runs the free join plan, starting with the header.
1178    ///
1179    /// A bit about the `instr_order` parameter: This defines the order in which the [`JoinStage`]
1180    /// instructions will run. We want to support cached [`SinglePlan`]s that may be based on stale
1181    /// ordering information. `instr_order` allows us to specify a new ordering of the instructions
1182    /// without mutating the plan itself: `run_plan` simply executes
1183    /// `plan.stages.instrs[instr_order[i]]` at stage `i`.
1184    ///
1185    /// This provides execution-local dynamic variable ordering while leaving
1186    /// the cached plan immutable.
1187    ///
1188    /// The [`StageMask`] width is chosen here, once per plan.
1189    fn run_join_stages<
1190        'plan,
1191        'rows,
1192        'scope,
1193        A: NumericId + 'scope,
1194        BUF: ActionBuffer<'scope, 'exec, A>,
1195    >(
1196        &self,
1197        stages: &'plan JoinStages,
1198        prepared: &'rows PreparedJoinIndexes,
1199        atoms: &'plan Arc<DenseIdMap<AtomId, Atom>>,
1200        action: A,
1201        binding_info: &mut BindingInfo<'rows, 'exec>,
1202        action_buf: &mut BUF,
1203    ) where
1204        'a: 'scope,
1205        'state: 'scope,
1206        'exec: 'rows,
1207        'rows: 'scope,
1208        'plan: 'scope,
1209    {
1210        if prepared.uses_wide_stage_mask() {
1211            self.run_join_stages_with::<_, _, u128>(
1212                stages,
1213                prepared,
1214                atoms,
1215                action,
1216                binding_info,
1217                action_buf,
1218            )
1219        } else {
1220            self.run_join_stages_with::<_, _, u64>(
1221                stages,
1222                prepared,
1223                atoms,
1224                action,
1225                binding_info,
1226                action_buf,
1227            )
1228        }
1229    }
1230
1231    fn run_join_stages_with<
1232        'plan,
1233        'rows,
1234        'scope,
1235        A: NumericId + 'scope,
1236        BUF: ActionBuffer<'scope, 'exec, A>,
1237        M: StageMask,
1238    >(
1239        &self,
1240        stages: &'plan JoinStages,
1241        prepared: &'rows PreparedJoinIndexes,
1242        atoms: &'plan Arc<DenseIdMap<AtomId, Atom>>,
1243        action: A,
1244        binding_info: &mut BindingInfo<'rows, 'exec>,
1245        action_buf: &mut BUF,
1246    ) where
1247        'a: 'scope,
1248        'state: 'scope,
1249        'exec: 'rows,
1250        'rows: 'scope,
1251        'plan: 'scope,
1252    {
1253        if log::log_enabled!(log::Level::Trace) {
1254            log::trace!("Starting running query stages:\n{stages:#?}");
1255        }
1256        for (_, node) in binding_info.subsets.iter() {
1257            if node.is_empty() {
1258                return;
1259            }
1260        }
1261        let mut order = InstrOrder::from_iter(0..stages.instrs.len());
1262        let mut leaf_scans: LeafScans = smallvec::smallvec![false; stages.instrs.len()];
1263        select_next_stage(&mut order, &mut leaf_scans, 0, &stages.instrs, binding_info);
1264        let all_stages = prepared.all_stage_mask::<M>();
1265        debug_assert!(
1266            all_stages.is_some()
1267                || (prepared.tail_masks::<u64>().is_none()
1268                    && prepared.tail_masks::<u128>().is_none()),
1269            "the join must run at the width its tail masks were prepared at"
1270        );
1271
1272        // Schedule each coarse top partition as a global job and run its
1273        // complete subtree inline: `recur_global_serial` supplies a serial
1274        // buffer whose recursive work stays inline. Cached scalar indexes
1275        // provide physical hash shards; filtered scalar indexes and fused
1276        // covers use borrowed ordinal ranges, avoiding row-ID copies. Buffers
1277        // that cannot construct an independent partition decline this path.
1278        if !stages.instrs.is_empty()
1279            && action_buf.supports_global_partition()
1280            && let Some(partitions) =
1281                self.select_top_partitions::<M>(stages, prepared, atoms, &order, binding_info)
1282        {
1283            log::debug!(
1284                "free join action={} stages={} root_rows={} top_partitions={}",
1285                action.index(),
1286                order.len(),
1287                estimate_size(&stages.instrs[order.get(0)], binding_info),
1288                partitions.len(),
1289            );
1290            let mut updates = FrameUpdates::with_capacity(0);
1291            for partition in partitions {
1292                let db = self.db;
1293                let exec_state_for_factory = self.exec_state;
1294                let exec_state_for_work = self.exec_state;
1295                let trie_cache = self.trie_cache.clone();
1296                let arena = self.arena;
1297                action_buf.recur_global_serial(
1298                    BorrowedLocalState {
1299                        binding_info,
1300                        instr_order: &mut order,
1301                        leaf_scans: &mut leaf_scans,
1302                        updates: &mut updates,
1303                    },
1304                    SubsetClonePlan {
1305                        stages: &stages.instrs,
1306                        resume_pos: 0,
1307                    },
1308                    move || exec_state_for_factory.to_execution_state(),
1309                    move |BorrowedLocalState {
1310                              binding_info,
1311                              instr_order,
1312                              leaf_scans,
1313                              ..
1314                          },
1315                          buf| {
1316                        let join_state: JoinState<'a, 'state, 'exec> =
1317                            JoinState::new(db, exec_state_for_work, trie_cache, arena);
1318                        join_state.run_plan(
1319                            stages,
1320                            prepared,
1321                            atoms,
1322                            action,
1323                            instr_order,
1324                            leaf_scans,
1325                            0,
1326                            Some(partition),
1327                            all_stages,
1328                            binding_info,
1329                            buf,
1330                        );
1331                    },
1332                );
1333            }
1334            return;
1335        }
1336        log::debug!(
1337            "free join action={} stages={} root_rows={} top_partitions=0",
1338            action.index(),
1339            order.len(),
1340            if order.len() == 0 {
1341                0
1342            } else {
1343                estimate_size(&stages.instrs[order.get(0)], binding_info)
1344            },
1345        );
1346        self.run_plan(
1347            stages,
1348            prepared,
1349            atoms,
1350            action,
1351            &mut order,
1352            &mut leaf_scans,
1353            0,
1354            None,
1355            all_stages,
1356            binding_info,
1357            action_buf,
1358        );
1359    }
1360
1361    /// Recursively execute the remaining stages of a free-join plan.
1362    ///
1363    /// The `JoinState` supplies the frozen database view, query arena, caches,
1364    /// and early-stop flag. The parameters describe the plan and the current
1365    /// recursive branch:
1366    ///
1367    /// - `stages` is the immutable logical join program being executed.
1368    /// - `prepared` contains execution-local cache slots and liveness metadata
1369    ///   aligned with the logical stages.
1370    /// - `atoms` maps the atom ids referenced by the stages to their tables and
1371    ///   column metadata.
1372    /// - `action` identifies the rule action to run for each complete binding.
1373    /// - `instr_order` maps each physical execution position to a logical stage;
1374    ///   dynamic ordering may reorder its unexecuted suffix.
1375    /// - `leaf_scans` is aligned with physical execution positions and records
1376    ///   which stages may produce factorized leaf bindings. It is updated when
1377    ///   `instr_order` changes.
1378    /// - `cur` is the physical position to execute next. Reaching the end sends
1379    ///   the completed binding to `action_buf`.
1380    /// - `top_partition` optionally restricts the first intersection or fused
1381    ///   cover scan to a disjoint shard or ordinal range. Recursive calls clear
1382    ///   it; the action buffer determines whether later work can run in parallel.
1383    /// - `remaining_stages` is a bit set of logical stages in the unexecuted
1384    ///   suffix. It enables constant-time child-shape and value-liveness checks;
1385    ///   plans with more than `M::BITS` stages use `None` and scan the suffix
1386    ///   instead.
1387    /// - `binding_info` owns the partial scalar and factorized bindings, current
1388    ///   row subsets for each atom, and branch-local materializations.
1389    /// - `action_buf` receives complete bindings and controls whether recursive
1390    ///   work is run inline or divided into parallel morsels.
1391    #[allow(clippy::too_many_arguments)]
1392    fn run_plan<
1393        'plan,
1394        'rows,
1395        'scope,
1396        A: NumericId + 'scope,
1397        BUF: ActionBuffer<'scope, 'exec, A>,
1398        M: StageMask,
1399    >(
1400        &self,
1401        stages: &'plan JoinStages,
1402        prepared: &'rows PreparedJoinIndexes,
1403        atoms: &'plan Arc<DenseIdMap<AtomId, Atom>>,
1404        action: A,
1405        instr_order: &mut InstrOrder,
1406        leaf_scans: &mut LeafScans,
1407        cur: usize,
1408        top_partition: Option<TopLevelPartition>,
1409        remaining_stages: Option<M>,
1410        binding_info: &mut BindingInfo<'rows, 'exec>,
1411        action_buf: &mut BUF,
1412    ) where
1413        'a: 'scope,
1414        'state: 'scope,
1415        'exec: 'rows,
1416        'rows: 'scope,
1417        'plan: 'scope,
1418    {
1419        if self.exec_state.should_stop() {
1420            return;
1421        }
1422
1423        #[cfg(debug_assertions)]
1424        if let Some(remaining_stages) = remaining_stages {
1425            debug_assert_eq!(
1426                remaining_stages,
1427                super::join_tail::suffix_stage_mask::<M>(instr_order, cur),
1428                "the remaining-stage mask must describe the current physical suffix"
1429            );
1430        }
1431
1432        if cur >= instr_order.len() {
1433            action_buf.push_bindings_factorized(
1434                action,
1435                &mut binding_info.bindings,
1436                &binding_info.binding_sets,
1437                &self.exec_state,
1438            );
1439            return;
1440        }
1441        let mut cur_size = top_partition.map_or_else(
1442            || estimate_size(&stages.instrs[instr_order.get(cur)], binding_info),
1443            TopLevelPartition::scan_size,
1444        );
1445        let mut chunk_size = action_buf.morsel_size(cur, instr_order.len());
1446        if action_buf.supports_parallel_drain() {
1447            // Even root morsels must accumulate enough successful frames to
1448            // amortize a handoff into a wide join tail.
1449            chunk_size = chunk_size.max(free_join_fork_min_frames());
1450        }
1451        // For very small residuals, keep the existing schedule instead of
1452        // paying for another candidate scan.
1453        if cur_size > 1
1454            && cur > 0
1455            && cur < instr_order.len() - 1
1456            && !is_reorder_barrier(&stages.instrs[instr_order.get(cur)])
1457            && !is_reorder_barrier(&stages.instrs[instr_order.get(cur + 1)])
1458        {
1459            // A barrier or the sole stage before one has no alternative.
1460            // Leaving its order unchanged also preserves the leaf flags.
1461            // Select only the next stage from fresh residual sizes.
1462            // Leave later choices until their inputs exist.
1463            // Keep cur=0 fixed: top-level partitions describe that first
1464            // stage's scan, so changing it would invalidate their boundaries.
1465            // Packed child families support each new successor choice.
1466            select_next_stage(instr_order, leaf_scans, cur, &stages.instrs, binding_info);
1467            cur_size = estimate_size(&stages.instrs[instr_order.get(cur)], binding_info);
1468        }
1469
1470        let stage_index = instr_order.get(cur);
1471        let stage = &stages.instrs[stage_index];
1472        let prepared_indexes = prepared.stage(stage_index);
1473        let remaining_after_current = remaining_stages.map(|remaining| {
1474            let stage_bit = M::stage_bit(stage_index);
1475            debug_assert_ne!(
1476                remaining & stage_bit,
1477                M::EMPTY,
1478                "the current stage must still be present in the remaining-stage mask"
1479            );
1480            remaining & !stage_bit
1481        });
1482
1483        macro_rules! drain_updates_parallel {
1484            ($updates:expr) => {{
1485                if self.exec_state.should_stop() {
1486                    return;
1487                }
1488                let db = self.db;
1489                let exec_state_for_factory = self.exec_state;
1490                let exec_state_for_work = self.exec_state;
1491                let trie_cache = self.trie_cache.clone();
1492                let arena = self.arena;
1493                action_buf.recur(
1494                    BorrowedLocalState {
1495                        binding_info,
1496                        instr_order,
1497                        leaf_scans,
1498                        updates: &mut $updates,
1499                    },
1500                    SubsetClonePlan {
1501                        stages: &stages.instrs,
1502                        resume_pos: cur + 1,
1503                    },
1504                    move || exec_state_for_factory.to_execution_state(),
1505                    move |BorrowedLocalState {
1506                              binding_info,
1507                              instr_order,
1508                              leaf_scans,
1509                              updates,
1510                          },
1511                          buf| {
1512                        let join_state: JoinState<'a, 'state, 'exec> =
1513                            JoinState::new(db, exec_state_for_work, trie_cache, arena);
1514                        updates.drain(|update| match update {
1515                            UpdateInstr::PushBinding(var, val) => {
1516                                binding_info.bindings.insert(var, val);
1517                            }
1518                            UpdateInstr::RefineAtom(atom, subset) => {
1519                                binding_info.insert_node(atom, subset);
1520                            }
1521                            UpdateInstr::RefineAtomDense(atom, range) => {
1522                                binding_info.insert_subset(atom, Subset::Dense(range));
1523                            }
1524                            UpdateInstr::EndFrame => {
1525                                join_state.run_plan(
1526                                    stages,
1527                                    prepared,
1528                                    atoms,
1529                                    action,
1530                                    instr_order,
1531                                    leaf_scans,
1532                                    cur + 1,
1533                                    None,
1534                                    remaining_after_current,
1535                                    binding_info,
1536                                    buf,
1537                                );
1538                            }
1539                        })
1540                    },
1541                );
1542                $updates.clear();
1543            }};
1544        }
1545        // Helper macros (not their own methods to appease the borrow checker).
1546        macro_rules! drain_updates_body {
1547            ($updates:expr) => {{
1548                if self.exec_state.should_stop() {
1549                    return;
1550                }
1551                // Reject serial buffers first so coarse partition jobs avoid
1552                // policy lookups as well as live-state cloning.
1553                if action_buf.supports_parallel_drain()
1554                    && free_join_can_fork(cur, instr_order.len(), cur_size, $updates.frames())
1555                    && action_buf.has_available_parallelism()
1556                {
1557                    drain_updates_parallel!($updates)
1558                } else {
1559                    $updates.drain(|update| match update {
1560                        UpdateInstr::PushBinding(var, val) => {
1561                            binding_info.bindings.insert(var, val);
1562                        }
1563                        UpdateInstr::RefineAtom(atom, subset) => {
1564                            binding_info.insert_node(atom, subset);
1565                        }
1566                        UpdateInstr::RefineAtomDense(atom, range) => {
1567                            binding_info.insert_subset(atom, Subset::Dense(range));
1568                        }
1569                        UpdateInstr::EndFrame => {
1570                            // Inline leaf-level: if cur+1 is the leaf (no more
1571                            // join stages), call push_bindings directly without
1572                            // a recursive run_plan call, avoiding function call
1573                            // overhead + an extra should_stop() check.
1574                            if cur + 1 >= instr_order.len() {
1575                                action_buf.push_bindings_factorized(
1576                                    action,
1577                                    &mut binding_info.bindings,
1578                                    &binding_info.binding_sets,
1579                                    &self.exec_state,
1580                                );
1581                            } else {
1582                                self.run_plan(
1583                                    stages,
1584                                    prepared,
1585                                    atoms,
1586                                    action,
1587                                    instr_order,
1588                                    leaf_scans,
1589                                    cur + 1,
1590                                    None,
1591                                    remaining_after_current,
1592                                    binding_info,
1593                                    action_buf,
1594                                );
1595                            }
1596                        }
1597                    })
1598                }
1599            }};
1600        }
1601        macro_rules! drain_updates {
1602            ($updates:expr) => {{
1603                drain_updates_body!($updates);
1604            }};
1605            ($updates:expr, false) => {{
1606                drain_updates_body!($updates);
1607            }};
1608        }
1609
1610        // A leaf group has already supplied its bindings and can advance
1611        // directly. Keep early returns inside the closure so
1612        // the caller always restores its cover and factorized binding stack.
1613        macro_rules! advance_leaf {
1614            () => {{
1615                (|| {
1616                    if self.exec_state.should_stop() {
1617                        return;
1618                    }
1619                    if cur + 1 >= instr_order.len() {
1620                        action_buf.push_bindings_factorized(
1621                            action,
1622                            &mut binding_info.bindings,
1623                            &binding_info.binding_sets,
1624                            &self.exec_state,
1625                        );
1626                    } else {
1627                        self.run_plan(
1628                            stages,
1629                            prepared,
1630                            atoms,
1631                            action,
1632                            instr_order,
1633                            leaf_scans,
1634                            cur + 1,
1635                            None,
1636                            remaining_after_current,
1637                            binding_info,
1638                            action_buf,
1639                        );
1640                    }
1641                })();
1642            }};
1643        }
1644
1645        // A singleton has no Cartesian product to defer. Store its values
1646        // directly to avoid an Arc and later expansion. Multirow groups
1647        // retain factorized execution.
1648        macro_rules! bind_leaf_rows {
1649            ($rows:expr, $bind:expr) => {{
1650                let singleton = $rows.len() == 1;
1651                if singleton {
1652                    let (_, row) = $rows.iter().next().unwrap();
1653                    for ((_, var), value) in $bind.iter().zip(row) {
1654                        binding_info.bindings.insert(*var, *value);
1655                    }
1656                } else {
1657                    let vars = $bind.iter().map(|(_, var)| *var).collect();
1658                    binding_info.binding_sets.push((vars, Arc::new($rows)));
1659                }
1660                advance_leaf!();
1661                if !singleton {
1662                    binding_info.binding_sets.pop();
1663                }
1664            }};
1665        }
1666
1667        // A sharded top-level job enumerates only its assigned physical index
1668        // shard. Every recursive call clears `top_partition`, so this macro is
1669        // used only by the leading prober of the initial `Intersect` stage.
1670        macro_rules! for_each_leader {
1671            ($prober:expr, $callback:expr) => {
1672                match top_partition {
1673                    Some(TopLevelPartition::IndexShard { shard, .. }) => {
1674                        $prober.for_each_shard(shard, $callback)
1675                    }
1676                    Some(TopLevelPartition::IndexRange {
1677                        start, scan_size, ..
1678                    }) => $prober.for_each_range(start, scan_size, $callback),
1679                    None => $prober.for_each($callback),
1680                    Some(TopLevelPartition::CoverRange { .. }) => {
1681                        unreachable!("a cover range can only drive a fused intersection")
1682                    }
1683                }
1684            };
1685        }
1686
1687        debug_assert_eq!(
1688            prepared_indexes.len(),
1689            match stage {
1690                JoinStage::Intersect { scans, .. } => scans.len(),
1691                JoinStage::FusedIntersect { to_intersect, .. }
1692                | JoinStage::FusedIntersectMat { to_intersect, .. } => to_intersect.len(),
1693            }
1694        );
1695        match stage {
1696            JoinStage::Intersect { var, scans } => match scans.as_slice() {
1697                [] => {}
1698                [a] => {
1699                    if binding_info.has_empty_subset(a.atom) {
1700                        return;
1701                    }
1702                    let tail = atom_tail_use(
1703                        a.atom,
1704                        &stages.instrs,
1705                        prepared,
1706                        remaining_after_current,
1707                        instr_order,
1708                        cur + 1,
1709                    );
1710                    let prober = self.get_index(
1711                        atoms,
1712                        binding_info,
1713                        ProbeRequest::column(
1714                            a,
1715                            tail.keep_rows,
1716                            tail.child_shape,
1717                            prepared.resolve(&prepared_indexes[0]),
1718                        ),
1719                    );
1720                    let mut updates = FrameUpdates::with_capacity(cmp::min(chunk_size, cur_size));
1721                    for_each_leader!(prober, |val, x| {
1722                        updates.push_binding(*var, val[0]);
1723                        x.refine(a.atom, &mut updates);
1724                        updates.finish_frame();
1725                        if updates.frames() >= chunk_size {
1726                            drain_updates!(updates);
1727                        }
1728                    });
1729                    drain_updates!(updates);
1730                    binding_info.move_back(a.atom, prober);
1731                }
1732                [a, b] => {
1733                    let a_tail = atom_tail_use(
1734                        a.atom,
1735                        &stages.instrs,
1736                        prepared,
1737                        remaining_after_current,
1738                        instr_order,
1739                        cur + 1,
1740                    );
1741                    let a_prober = self.get_index(
1742                        atoms,
1743                        binding_info,
1744                        ProbeRequest::column(
1745                            a,
1746                            a_tail.keep_rows,
1747                            a_tail.child_shape,
1748                            prepared.resolve(&prepared_indexes[0]),
1749                        ),
1750                    );
1751                    let b_tail = atom_tail_use(
1752                        b.atom,
1753                        &stages.instrs,
1754                        prepared,
1755                        remaining_after_current,
1756                        instr_order,
1757                        cur + 1,
1758                    );
1759                    let b_prober = self.get_index(
1760                        atoms,
1761                        binding_info,
1762                        ProbeRequest::column(
1763                            b,
1764                            b_tail.keep_rows,
1765                            b_tail.child_shape,
1766                            prepared.resolve(&prepared_indexes[1]),
1767                        ),
1768                    );
1769
1770                    let ((smaller, smaller_scan), (larger, larger_scan)) =
1771                        if a_prober.len() <= b_prober.len() {
1772                            ((&a_prober, a), (&b_prober, b))
1773                        } else {
1774                            ((&b_prober, b), (&a_prober, a))
1775                        };
1776
1777                    let mut updates = FrameUpdates::with_capacity(cmp::min(chunk_size, cur_size));
1778                    if let (Some(smaller_keys), Some(larger_keys)) =
1779                        (smaller.sorted_scalar_probe(), larger.sorted_scalar_probe())
1780                    {
1781                        // Both sides expose sorted scalar arrays. Leapfrog through the larger
1782                        // side directly, preserving the selected leader and its top-level ordinal
1783                        // partition. Successful ordinals reconstruct the same ProbeMatch as a
1784                        // scalar lookup, including row-carrying continuations needed by the tail.
1785                        let leader_range = match top_partition {
1786                            Some(TopLevelPartition::IndexRange {
1787                                start, scan_size, ..
1788                            }) => start..start + scan_size,
1789                            None => 0..smaller_keys.len(),
1790                            Some(TopLevelPartition::IndexShard { .. }) => {
1791                                unreachable!("a sorted scalar leader is never hash-sharded")
1792                            }
1793                            Some(TopLevelPartition::CoverRange { .. }) => {
1794                                unreachable!("a cover range cannot drive an intersection")
1795                            }
1796                        };
1797                        debug_assert!(leader_range.end <= smaller_keys.len());
1798                        let both_tiny = matches!(smaller_keys, SortedScalarProbe::Small(..))
1799                            && matches!(larger_keys, SortedScalarProbe::Small(..));
1800                        let comparable_sizes =
1801                            larger_keys.len() <= leader_range.len().saturating_mul(4);
1802                        if both_tiny || comparable_sizes {
1803                            // A plain two-finger merge is cheaper for tiny recursive residuals
1804                            // and similarly sized packed arrays, where a linear pass has better
1805                            // locality than setting up galloping bounds for every key.
1806                            let mut leader_index = leader_range.start;
1807                            let mut target_index = 0;
1808                            if leader_index != 0 && leader_index < leader_range.end {
1809                                let first_key = smaller_keys.value_at(leader_index);
1810                                seek_sorted_key(
1811                                    first_key,
1812                                    larger_keys.len(),
1813                                    &mut target_index,
1814                                    |key_index| larger_keys.value_at(key_index),
1815                                );
1816                            }
1817                            while leader_index < leader_range.end
1818                                && target_index < larger_keys.len()
1819                            {
1820                                let leader_key = smaller_keys.value_at(leader_index);
1821                                let target_key = larger_keys.value_at(target_index);
1822                                match leader_key.cmp(&target_key) {
1823                                    cmp::Ordering::Less => leader_index += 1,
1824                                    cmp::Ordering::Greater => target_index += 1,
1825                                    cmp::Ordering::Equal => {
1826                                        updates.push_binding(*var, leader_key);
1827                                        smaller
1828                                            .sorted_match_at(leader_index)
1829                                            .refine(smaller_scan.atom, &mut updates);
1830                                        larger
1831                                            .sorted_match_at(target_index)
1832                                            .refine(larger_scan.atom, &mut updates);
1833                                        updates.finish_frame();
1834                                        if updates.frames() >= chunk_size {
1835                                            drain_updates!(updates);
1836                                        }
1837                                        leader_index += 1;
1838                                        target_index += 1;
1839                                    }
1840                                }
1841                            }
1842                        } else {
1843                            // Retain one target cursor, but gallop across gaps rather than
1844                            // scanning the larger side. This protects highly skewed joins where
1845                            // the smaller sorted side has only a few widely spaced keys.
1846                            let mut target_cursor = 0;
1847                            for leader_index in leader_range {
1848                                let key = smaller_keys.value_at(leader_index);
1849                                if seek_sorted_key(
1850                                    key,
1851                                    larger_keys.len(),
1852                                    &mut target_cursor,
1853                                    |key_index| larger_keys.value_at(key_index),
1854                                ) {
1855                                    updates.push_binding(*var, key);
1856                                    smaller
1857                                        .sorted_match_at(leader_index)
1858                                        .refine(smaller_scan.atom, &mut updates);
1859                                    larger
1860                                        .sorted_match_at(target_cursor)
1861                                        .refine(larger_scan.atom, &mut updates);
1862                                    updates.finish_frame();
1863                                    if updates.frames() >= chunk_size {
1864                                        drain_updates!(updates);
1865                                    }
1866                                    target_cursor += 1;
1867                                } else if target_cursor == larger_keys.len() {
1868                                    break;
1869                                }
1870                            }
1871                        }
1872                    } else {
1873                        // Catalog hash indexes and unsupported shapes retain the scalar path.
1874                        for_each_leader!(smaller, |val, small_sub| {
1875                            if let Some(large_sub) = larger.get_subset(val) {
1876                                updates.push_binding(*var, val[0]);
1877                                small_sub.refine(smaller_scan.atom, &mut updates);
1878                                large_sub.refine(larger_scan.atom, &mut updates);
1879                                updates.finish_frame();
1880                                if updates.frames() >= chunk_size {
1881                                    drain_updates!(updates);
1882                                }
1883                            }
1884                        });
1885                    }
1886                    drain_updates!(updates, false);
1887
1888                    binding_info.move_back(a.atom, a_prober);
1889                    binding_info.move_back(b.atom, b_prober);
1890                }
1891                rest => {
1892                    let mut smallest = 0;
1893                    let mut smallest_size = usize::MAX;
1894                    let mut probers = Vec::with_capacity(rest.len());
1895                    for (i, (scan, prepared_slot)) in rest.iter().zip(prepared_indexes).enumerate()
1896                    {
1897                        let tail = atom_tail_use(
1898                            scan.atom,
1899                            &stages.instrs,
1900                            prepared,
1901                            remaining_after_current,
1902                            instr_order,
1903                            cur + 1,
1904                        );
1905                        let prober = self.get_index(
1906                            atoms,
1907                            binding_info,
1908                            ProbeRequest::column(
1909                                scan,
1910                                tail.keep_rows,
1911                                tail.child_shape,
1912                                prepared.resolve(prepared_slot),
1913                            ),
1914                        );
1915                        let size = prober.len();
1916                        if size < smallest_size {
1917                            smallest = i;
1918                            smallest_size = size;
1919                        }
1920                        probers.push(prober);
1921                    }
1922
1923                    let main_spec = &rest[smallest];
1924
1925                    if smallest_size != 0 {
1926                        // Smallest leads the scan
1927                        let mut updates =
1928                            FrameUpdates::with_capacity(cmp::min(chunk_size, cur_size));
1929                        for_each_leader!(probers[smallest], |key, sub| {
1930                            updates.push_binding(*var, key[0]);
1931                            for (i, scan) in rest.iter().enumerate() {
1932                                if i == smallest {
1933                                    continue;
1934                                }
1935                                if let Some(sub) = probers[i].get_subset(key) {
1936                                    sub.refine(scan.atom, &mut updates);
1937                                } else {
1938                                    updates.rollback();
1939                                    // Empty intersection.
1940                                    return;
1941                                }
1942                            }
1943                            sub.refine(main_spec.atom, &mut updates);
1944                            updates.finish_frame();
1945                            if updates.frames() >= chunk_size {
1946                                drain_updates!(updates);
1947                            }
1948                        });
1949                        drain_updates!(updates);
1950                    }
1951                    for (spec, prober) in rest.iter().zip(probers.into_iter()) {
1952                        binding_info.move_back(spec.atom, prober);
1953                    }
1954                }
1955            },
1956            JoinStage::FusedIntersect {
1957                cover,
1958                bind,
1959                to_intersect,
1960            } if to_intersect.is_empty() => {
1961                let is_leaf_scan = leaf_scans[cur];
1962                let cover_atom = cover.to_index.atom;
1963                if binding_info.has_empty_subset(cover_atom) {
1964                    return;
1965                }
1966                if is_leaf_scan {
1967                    let table = self.db.tables[atoms[cover_atom].table].table.as_ref();
1968                    let cover_node = binding_info.unwrap_val(cover_atom);
1969                    let cover_subset = cover_node.subset();
1970
1971                    let proj = ColumnIds::from_iter(bind.iter().map(|(col, _)| *col));
1972                    let mut buf = TaggedRowBuffer::new_inline(bind.len());
1973                    let (scan_start, scan_size) =
1974                        cover_scan_bounds(top_partition, cover_subset.size());
1975                    table.scan_project(
1976                        cover_subset,
1977                        &proj,
1978                        scan_start,
1979                        scan_size,
1980                        &cover.constraints,
1981                        &mut buf,
1982                    );
1983
1984                    if buf.is_empty() {
1985                        binding_info.move_back_node(cover_atom, cover_node);
1986                        return;
1987                    }
1988
1989                    bind_leaf_rows!(buf, bind);
1990                    binding_info.move_back_node(cover_atom, cover_node);
1991                } else {
1992                    let keep_cover = atom_tail_use(
1993                        cover_atom,
1994                        &stages.instrs,
1995                        prepared,
1996                        remaining_after_current,
1997                        instr_order,
1998                        cur + 1,
1999                    )
2000                    .keep_rows;
2001                    let proj = ColumnIds::from_iter(bind.iter().map(|(col, _)| *col));
2002                    let cover_node = binding_info.unwrap_val(cover_atom);
2003                    let cover_subset = cover_node.subset();
2004                    let (mut offset, mut scan_remaining) =
2005                        cover_scan_bounds(top_partition, cover_subset.size());
2006                    let mut buffer = TaggedRowBuffer::new(bind.len());
2007                    let mut updates = FrameUpdates::with_capacity(cmp::min(chunk_size, cur_size));
2008                    while scan_remaining != 0 {
2009                        buffer.clear();
2010                        let table = &self.db.tables[atoms[cover_atom].table].table;
2011                        let scan_size = cmp::min(chunk_size, scan_remaining);
2012                        let next = table.scan_project(
2013                            cover_subset,
2014                            &proj,
2015                            offset,
2016                            scan_size,
2017                            &cover.constraints,
2018                            &mut buffer,
2019                        );
2020                        scan_remaining -= scan_size;
2021                        for (row, key) in buffer.iter() {
2022                            if keep_cover {
2023                                updates.refine_atom_dense(
2024                                    cover_atom,
2025                                    OffsetRange::new(row, row.inc()),
2026                                );
2027                            }
2028                            // bind the values
2029                            for (i, (_, var)) in bind.iter().enumerate() {
2030                                updates.push_binding(*var, key[i]);
2031                            }
2032                            updates.finish_frame();
2033                            if updates.frames() >= chunk_size {
2034                                drain_updates!(updates);
2035                            }
2036                        }
2037                        if scan_remaining != 0 {
2038                            let Some(next) = next else {
2039                                break;
2040                            };
2041                            offset = next;
2042                        }
2043                    }
2044                    drain_updates!(updates);
2045                    // Restore the subsets we swapped out.
2046                    binding_info.move_back_node(cover_atom, cover_node);
2047                }
2048            }
2049            JoinStage::FusedIntersect {
2050                cover,
2051                bind,
2052                to_intersect,
2053            } => {
2054                let cover_atom = cover.to_index.atom;
2055                let keep_cover = atom_tail_use(
2056                    cover_atom,
2057                    &stages.instrs,
2058                    prepared,
2059                    remaining_after_current,
2060                    instr_order,
2061                    cur + 1,
2062                )
2063                .keep_rows;
2064                if binding_info.has_empty_subset(cover_atom) {
2065                    return;
2066                }
2067                let index_probers = to_intersect
2068                    .iter()
2069                    .enumerate()
2070                    .map(|(i, (spec, _))| {
2071                        let tail = atom_tail_use(
2072                            spec.to_index.atom,
2073                            &stages.instrs,
2074                            prepared,
2075                            remaining_after_current,
2076                            instr_order,
2077                            cur + 1,
2078                        );
2079                        (
2080                            i,
2081                            spec.to_index.atom,
2082                            self.get_index(
2083                                atoms,
2084                                binding_info,
2085                                ProbeRequest::tuple(
2086                                    spec,
2087                                    tail.keep_rows,
2088                                    tail.child_shape,
2089                                    prepared.resolve(&prepared_indexes[i]),
2090                                ),
2091                            ),
2092                        )
2093                    })
2094                    .collect::<SmallVec<[(usize, AtomId, Prober<'_, 'rows, 'exec>); 4]>>();
2095                let proj = ColumnIds::from_iter(bind.iter().map(|(col, _)| *col));
2096                let cover_node = binding_info.unwrap_val(cover_atom);
2097                let cover_subset = cover_node.subset();
2098                let (mut scan_offset, mut scan_remaining) =
2099                    cover_scan_bounds(top_partition, cover_subset.size());
2100                let mut buffer = TaggedRowBuffer::new(bind.len());
2101                let mut updates = FrameUpdates::with_capacity(cmp::min(chunk_size, cur_size));
2102                while scan_remaining != 0 {
2103                    buffer.clear();
2104                    let table = &self.db.tables[atoms[cover_atom].table].table;
2105                    let scan_size = cmp::min(chunk_size, scan_remaining);
2106                    let next = table.scan_project(
2107                        cover_subset,
2108                        &proj,
2109                        scan_offset,
2110                        scan_size,
2111                        &cover.constraints,
2112                        &mut buffer,
2113                    );
2114                    scan_remaining -= scan_size;
2115                    'mid: for (row, key) in buffer.iter() {
2116                        if keep_cover {
2117                            updates.refine_atom_dense(cover_atom, OffsetRange::new(row, row.inc()));
2118                        }
2119                        // bind the values
2120                        for (i, (_, var)) in bind.iter().enumerate() {
2121                            updates.push_binding(*var, key[i]);
2122                        }
2123                        // now probe each remaining indexes
2124                        for (i, atom, prober) in &index_probers {
2125                            // create a key: to_intersect indexes into the key from the cover
2126                            let index_cols = &to_intersect[*i].1;
2127                            // Fast path for the common single-column case: avoid SmallVec collect.
2128                            let index_key_buf: SmallVec<[Value; 4]>;
2129                            let index_key: &[Value] = if let [col] = index_cols.as_slice() {
2130                                std::slice::from_ref(&key[col.index()])
2131                            } else {
2132                                index_key_buf =
2133                                    index_cols.iter().map(|col| key[col.index()]).collect();
2134                                &index_key_buf
2135                            };
2136                            let Some(subset) = prober.get_subset(index_key) else {
2137                                updates.rollback();
2138                                // There are no possible values for this subset
2139                                continue 'mid;
2140                            };
2141                            subset.refine(*atom, &mut updates);
2142                        }
2143                        updates.finish_frame();
2144                        if updates.frames() >= chunk_size {
2145                            drain_updates!(updates);
2146                        }
2147                    }
2148                    if scan_remaining != 0 {
2149                        let Some(next) = next else {
2150                            break;
2151                        };
2152                        scan_offset = next;
2153                    }
2154                }
2155                // TODO: special-case the scenario when the cover doesn't need
2156                // deduping (and hence we can do a straight scan: e.g. when the
2157                // cover is binding a superset of the primary key for the
2158                // table).
2159                drain_updates!(updates);
2160                // Restore the subsets we swapped out.
2161                binding_info.move_back_node(cover_atom, cover_node);
2162                for (_, atom, prober) in index_probers {
2163                    binding_info.move_back(atom, prober);
2164                }
2165            }
2166            JoinStage::FusedIntersectMat {
2167                cover,
2168                mode,
2169                bind,
2170                to_intersect,
2171            } if leaf_scans[cur]
2172                && to_intersect.is_empty()
2173                && matches!(
2174                    mode,
2175                    MatScanMode::Full | MatScanMode::KeyOnly | MatScanMode::Value(_)
2176                ) =>
2177            {
2178                // Leaf-scan factorization for FusedIntersectMat: flatten the materialization into
2179                // one `TaggedRowBuffer`, push it onto `binding_sets`, and recurse to the leaf once.
2180                let keep_for_tail =
2181                    materialization_is_live_in_tail(&stages.instrs, instr_order, cur + 1, *cover);
2182                let restore_materialization = !keep_for_tail;
2183                let cover_mat = if keep_for_tail {
2184                    Arc::clone(&binding_info.materializations[*cover])
2185                } else {
2186                    binding_info.materializations.unwrap_val(*cover)
2187                };
2188                (|| {
2189                    let mut buf = TaggedRowBuffer::new_inline(bind.len());
2190                    let mut row_scratch: SmallVec<[Value; 8]> = SmallVec::new();
2191                    match mode {
2192                        MatScanMode::Full => {
2193                            for group in cover_mat.iter() {
2194                                let group_key = group.0;
2195                                let group_key_len = group_key.len();
2196                                for non_keys in group.1.iter() {
2197                                    row_scratch.clear();
2198                                    for (col, _) in bind.iter() {
2199                                        let val = if col.index() < group_key_len {
2200                                            group_key[col.index()]
2201                                        } else {
2202                                            non_keys[col.index() - group_key_len]
2203                                        };
2204                                        row_scratch.push(val);
2205                                    }
2206                                    buf.add_row(RowId::new(0), &row_scratch);
2207                                }
2208                            }
2209                        }
2210                        MatScanMode::KeyOnly => {
2211                            for group in cover_mat.iter() {
2212                                let group_key = group.0;
2213                                row_scratch.clear();
2214                                for (col, _) in bind.iter() {
2215                                    debug_assert!(col.index() < group_key.len());
2216                                    row_scratch.push(group_key[col.index()]);
2217                                }
2218                                buf.add_row(RowId::new(0), &row_scratch);
2219                            }
2220                        }
2221                        MatScanMode::Value(index_vars) => {
2222                            let keys: Vec<Value> = index_vars
2223                                .iter()
2224                                .map(|var| binding_info.bindings[*var])
2225                                .collect();
2226                            if let Some(group) = cover_mat.get(&keys) {
2227                                for vals in group.iter() {
2228                                    debug_assert!(vals.len() == bind.len());
2229                                    row_scratch.clear();
2230                                    for (col, _) in bind.iter() {
2231                                        row_scratch.push(vals[col.index()]);
2232                                    }
2233                                    buf.add_row(RowId::new(0), &row_scratch);
2234                                }
2235                            }
2236                        }
2237                        MatScanMode::Lookup(_) => unreachable!("guarded above"),
2238                    }
2239                    if buf.is_empty() {
2240                        return;
2241                    }
2242                    bind_leaf_rows!(buf, bind);
2243                })();
2244                if restore_materialization {
2245                    let previous = binding_info.materializations.insert(*cover, cover_mat);
2246                    debug_assert!(previous.is_none());
2247                }
2248            }
2249            JoinStage::FusedIntersectMat {
2250                cover,
2251                mode,
2252                bind,
2253                to_intersect,
2254            } => {
2255                let keep_for_tail =
2256                    materialization_is_live_in_tail(&stages.instrs, instr_order, cur + 1, *cover);
2257                let restore_materialization = !keep_for_tail;
2258                let cover_mat = if keep_for_tail {
2259                    Arc::clone(&binding_info.materializations[*cover])
2260                } else {
2261                    binding_info.materializations.unwrap_val(*cover)
2262                };
2263                (|| {
2264                    let mut updates: FrameUpdates<'rows, 'exec> =
2265                        FrameUpdates::with_capacity(cmp::min(chunk_size, cur_size));
2266                    let probers: SmallVec<[Prober<'_, 'rows, 'exec>; 4]> = to_intersect
2267                        .iter()
2268                        .zip(prepared_indexes)
2269                        .map(|((spec, _), prepared_slot)| {
2270                            let tail = atom_tail_use(
2271                                spec.to_index.atom,
2272                                &stages.instrs,
2273                                prepared,
2274                                remaining_after_current,
2275                                instr_order,
2276                                cur + 1,
2277                            );
2278                            self.get_index(
2279                                atoms,
2280                                binding_info,
2281                                ProbeRequest::tuple(
2282                                    spec,
2283                                    tail.keep_rows,
2284                                    tail.child_shape,
2285                                    prepared.resolve(prepared_slot),
2286                                ),
2287                            )
2288                        })
2289                        .collect();
2290                    debug_assert!(to_intersect.iter().enumerate().all(|(i, (spec, _))| {
2291                        to_intersect[..i]
2292                            .iter()
2293                            .all(|(prior, _)| prior.to_index.atom != spec.to_index.atom)
2294                    }));
2295                    let mut key = Vec::with_capacity(4);
2296                    let mut prune_probers = |updates: &mut FrameUpdates<'rows, 'exec>,
2297                                             mat_key: Option<&[Value]>,
2298                                             mat_non_key: Option<&[Value]>|
2299                     -> bool {
2300                        for ((spec, cols), prober) in to_intersect.iter().zip(probers.iter()) {
2301                            key.clear();
2302                            for col in cols.iter() {
2303                                let val = match mat_key {
2304                                    Some(mat_key) => {
2305                                        if col.index() < mat_key.len() {
2306                                            mat_key[col.index()]
2307                                        } else {
2308                                            mat_non_key.unwrap()[col.index() - mat_key.len()]
2309                                        }
2310                                    }
2311                                    None => mat_non_key.unwrap()[col.index()],
2312                                };
2313                                key.push(val);
2314                            }
2315                            if let Some(subset) = prober.get_subset(&key) {
2316                                subset.refine(spec.to_index.atom, updates);
2317                            } else {
2318                                return false;
2319                            }
2320                        }
2321                        true
2322                    };
2323
2324                    match mode {
2325                        MatScanMode::Full | MatScanMode::KeyOnly => {
2326                            // enumerate keys
2327                            for group in cover_mat.iter() {
2328                                let group_key = group.0;
2329                                let group_val = group.1;
2330                                let group_key_len = group_key.len();
2331                                if mode == &MatScanMode::Full {
2332                                    // enumerate non-keys
2333                                    for non_keys in group_val.iter() {
2334                                        for (col, var) in bind.iter() {
2335                                            if col.index() < group_key_len {
2336                                                updates.push_binding(*var, group_key[col.index()]);
2337                                            }
2338                                        }
2339
2340                                        // TODO: optimization that guaratees all keys come before non-keys
2341                                        for (col, var) in bind.iter() {
2342                                            if col.index() >= group_key_len {
2343                                                updates.push_binding(
2344                                                    *var,
2345                                                    non_keys[col.index() - group_key_len],
2346                                                );
2347                                            }
2348                                        }
2349                                        if prune_probers(
2350                                            &mut updates,
2351                                            Some(group_key),
2352                                            Some(non_keys),
2353                                        ) {
2354                                            updates.finish_frame();
2355                                        } else {
2356                                            updates.rollback();
2357                                        }
2358                                        if updates.frames() >= chunk_size {
2359                                            drain_updates!(updates);
2360                                        }
2361                                    }
2362                                } else if mode == &MatScanMode::KeyOnly {
2363                                    for (col, var) in bind.iter() {
2364                                        debug_assert!(col.index() < group_key_len);
2365                                        updates.push_binding(*var, group_key[col.index()]);
2366                                    }
2367                                    if prune_probers(&mut updates, Some(group_key), None) {
2368                                        updates.finish_frame();
2369                                    } else {
2370                                        updates.rollback();
2371                                    }
2372                                    if updates.frames() >= chunk_size {
2373                                        drain_updates!(updates);
2374                                    }
2375                                }
2376                            }
2377                        }
2378                        MatScanMode::Value(index_vars) | MatScanMode::Lookup(index_vars) => {
2379                            let keys = index_vars
2380                                .iter()
2381                                .map(|var| binding_info.bindings[*var])
2382                                .collect::<Vec<Value>>();
2383                            // lookup keys
2384                            if let Some(group) = cover_mat.get(&keys) {
2385                                if matches!(mode, MatScanMode::Lookup(_)) {
2386                                    debug_assert_eq!(to_intersect.len(), 0);
2387                                    debug_assert_eq!(bind.len(), 0);
2388                                    if group.len() > 0 {
2389                                        updates.finish_frame();
2390                                    }
2391                                    drain_updates!(updates);
2392                                } else {
2393                                    // enumerate non-keys
2394                                    // for vals in group.value().iter() {
2395                                    for vals in group.iter() {
2396                                        debug_assert!(vals.len() == bind.len()); // TODO: not true for non-full query
2397                                        for (col, var) in bind.iter() {
2398                                            updates.push_binding(*var, vals[col.index()]);
2399                                        }
2400                                        if prune_probers(&mut updates, None, Some(vals)) {
2401                                            updates.finish_frame();
2402                                        } else {
2403                                            updates.rollback();
2404                                        }
2405                                        if updates.frames() >= chunk_size {
2406                                            drain_updates!(updates);
2407                                        }
2408                                    }
2409                                }
2410                            }
2411                        }
2412                    }
2413
2414                    drain_updates!(updates);
2415                    for (spec, prober) in to_intersect.iter().zip(probers) {
2416                        binding_info.move_back(spec.0.to_index.atom, prober);
2417                    }
2418                })();
2419                if restore_materialization {
2420                    let previous = binding_info.materializations.insert(*cover, cover_mat);
2421                    debug_assert!(previous.is_none());
2422                }
2423            }
2424        }
2425    }
2426}
2427
2428const LOCAL_ACTION_BATCH_SIZE: usize = 128;
2429
2430/// A trait used to abstract over different ways of buffering actions together
2431/// before running them.
2432///
2433/// This trait exists as a fairly ad-hoc wrapper over its two implementations.
2434/// It allows us to avoid duplicating the (somewhat monstrous) `run_plan` method
2435/// for serial and parallel modes.
2436trait ActionBuffer<'scope, 'exec, A: NumericId>: Send
2437where
2438    'exec: 'scope,
2439{
2440    type AsLocal<'a>: ActionBuffer<'scope, 'exec, A>
2441    where
2442        'scope: 'a;
2443    type AsGlobalSerial<'a>: ActionBuffer<'scope, 'exec, A>
2444    where
2445        'scope: 'a;
2446
2447    /// Expand the binding sets to individual bindings and
2448    /// call push_bindings
2449    fn push_bindings_factorized(
2450        &mut self,
2451        action: A,
2452        bindings: &mut DenseIdMap<Variable, Value>,
2453        binding_sets: &BindingSet,
2454        exec_state: &ExecutionStateSeed<'scope, '_>,
2455    ) {
2456        expand_binding_sets(self, action, bindings, binding_sets, 0, exec_state);
2457    }
2458
2459    /// Push the given bindings to be executed for the specified action. If this
2460    /// buffer has built up a sufficient batch size, it may execute
2461    /// `to_exec_state` and then execute the action.
2462    ///
2463    /// NB: `push_bindings` makes module-specific assumptions on what values are passed to
2464    /// `bindings` for a common `action`. This is not a general-purpose trait for that reason and
2465    /// it should not, in general, be used outside of this module.
2466    fn push_bindings(
2467        &mut self,
2468        action: A,
2469        bindings: &DenseIdMap<Variable, Value>,
2470        to_exec_state: impl FnMut() -> ExecutionState<'scope>,
2471    );
2472
2473    /// Execute any remaining actions associated with this buffer.
2474    fn flush(&mut self, exec_state: &mut ExecutionState);
2475
2476    /// Execute `work`, potentially asynchronously, with a mutable reference to
2477    /// an action buffer, potentially handed off to a different thread.
2478    ///
2479    /// Callers [`BorrowedLocalState`] values that may be modified by work, or
2480    /// cloned first and then have a separate copy modified by `work`. Callers
2481    /// should assume that `local` _is_ modified synchronously.
2482    // NB: Earlier versions of this method had BorrowedLocalState be a generic instead, but this
2483    // ran into difficulties when we needed to pass multiple mutable references.
2484    fn recur<'local, 'rows>(
2485        &mut self,
2486        local: BorrowedLocalState<'local, 'rows, 'exec>,
2487        subset_clone_plan: SubsetClonePlan<'_>,
2488        to_exec_state: impl FnMut() -> ExecutionState<'scope> + Send + 'scope,
2489        work: impl for<'a> FnOnce(BorrowedLocalState<'a, 'scope, 'exec>, &mut Self::AsLocal<'a>)
2490        + Send
2491        + 'scope,
2492    ) where
2493        'rows: 'scope;
2494
2495    /// Run one coarse partition as a global pool job, using a buffer whose
2496    /// recursive work and action execution are both serial. Implementations
2497    /// that return `false` from [`Self::supports_global_partition`] execute the
2498    /// callback inline; the scoped implementations enqueue exactly one job.
2499    fn recur_global_serial<'local, 'rows>(
2500        &mut self,
2501        local: BorrowedLocalState<'local, 'rows, 'exec>,
2502        subset_clone_plan: SubsetClonePlan<'_>,
2503        to_exec_state: impl FnMut() -> ExecutionState<'scope> + Send + 'scope,
2504        work: impl for<'a> FnOnce(BorrowedLocalState<'a, 'scope, 'exec>, &mut Self::AsGlobalSerial<'a>)
2505        + Send
2506        + 'scope,
2507    ) where
2508        'rows: 'scope;
2509
2510    /// The unit at which you should batch updates passed to calls to `recur`,
2511    /// potentially depending on the current level of recursion.
2512    ///
2513    /// As of right now this is just a hard-coded value. We may change it in the
2514    /// future to fan out more at higher levels though.
2515    fn morsel_size(&mut self, _level: usize, _total: usize) -> usize {
2516        256
2517    }
2518
2519    /// Whether this buffer supports parallel drain operations.
2520    ///
2521    /// When `false`, `drain_updates` uses the serial path at every depth,
2522    /// avoiding scheduling-policy checks and live-state cloning.
2523    fn supports_parallel_drain(&self) -> bool {
2524        true
2525    }
2526
2527    /// Advisory pool pressure used only after a batch has enough join work to
2528    /// amortize cloning its live state.
2529    fn has_available_parallelism(&self) -> bool {
2530        false
2531    }
2532
2533    /// Whether this buffer can enqueue independent top-level partitions.
2534    fn supports_global_partition(&self) -> bool {
2535        false
2536    }
2537}
2538
2539/// The action buffer we use if we are executing in a single-threaded
2540/// environment. It builds up local batches and then flushes them inline.
2541struct InPlaceActionBuffer<'a> {
2542    rule_set: &'a RuleSet,
2543    match_counter: &'a MatchCounter,
2544    batches: DenseIdMap<ActionId, ActionState>,
2545}
2546
2547impl<'scope, 'exec, 'outer: 'scope> ActionBuffer<'scope, 'exec, ActionId>
2548    for InPlaceActionBuffer<'outer>
2549where
2550    'exec: 'scope,
2551{
2552    type AsLocal<'b>
2553        = Self
2554    where
2555        'scope: 'b;
2556    type AsGlobalSerial<'b>
2557        = Self
2558    where
2559        'scope: 'b;
2560
2561    fn push_bindings(
2562        &mut self,
2563        action: ActionId,
2564        bindings: &DenseIdMap<Variable, Value>,
2565        mut to_exec_state: impl FnMut() -> ExecutionState<'scope>,
2566    ) {
2567        let action_state = self
2568            .batches
2569            .get_or_insert(action, || ActionState::new(LOCAL_ACTION_BATCH_SIZE));
2570        action_state.n_runs += 1;
2571        action_state.len += 1;
2572        let action_info = &self.rule_set.actions[action];
2573        // SAFETY: `used_vars` is a constant per-rule. This module only ever calls it with
2574        // `bindings` produced by the same join.
2575        unsafe {
2576            action_state.bindings.push(bindings, &action_info.used_vars);
2577        }
2578        if action_state.len >= LOCAL_ACTION_BATCH_SIZE {
2579            let mut state = to_exec_state();
2580            let succeeded = state.run_instrs(&action_info.instrs, &mut action_state.bindings);
2581            action_state.bindings.clear();
2582            self.match_counter.inc_matches(action, succeeded);
2583            action_state.len = 0;
2584        }
2585    }
2586
2587    fn flush(&mut self, exec_state: &mut ExecutionState) {
2588        flush_action_states(
2589            exec_state,
2590            &mut self.batches,
2591            self.rule_set,
2592            self.match_counter,
2593        );
2594    }
2595
2596    fn recur<'local, 'rows>(
2597        &mut self,
2598        mut local: BorrowedLocalState<'local, 'rows, 'exec>,
2599        subset_clone_plan: SubsetClonePlan<'_>,
2600        _to_exec_state: impl FnMut() -> ExecutionState<'scope> + Send + 'scope,
2601        work: impl for<'b> FnOnce(BorrowedLocalState<'b, 'scope, 'exec>, &mut Self) + Send + 'scope,
2602    ) where
2603        'rows: 'scope,
2604    {
2605        let mut inner: LocalState<'scope, 'exec> = local.clone_state(subset_clone_plan);
2606        work(inner.borrow_mut(), self)
2607    }
2608
2609    fn recur_global_serial<'local, 'rows>(
2610        &mut self,
2611        mut local: BorrowedLocalState<'local, 'rows, 'exec>,
2612        subset_clone_plan: SubsetClonePlan<'_>,
2613        _to_exec_state: impl FnMut() -> ExecutionState<'scope> + Send + 'scope,
2614        work: impl for<'b> FnOnce(BorrowedLocalState<'b, 'scope, 'exec>, &mut Self) + Send + 'scope,
2615    ) where
2616        'rows: 'scope,
2617    {
2618        let mut inner: LocalState<'scope, 'exec> = local.clone_state(subset_clone_plan);
2619        work(inner.borrow_mut(), self)
2620    }
2621
2622    fn supports_parallel_drain(&self) -> bool {
2623        false
2624    }
2625}
2626
2627/// Strictly serial action buffer used inside one globally scheduled top-index
2628/// shard. It shares the rule-set match counter with sibling shards, but executes
2629/// all recursive join and action work inline. It deliberately has no
2630/// `needs_flush` flag: its owner unconditionally flushes it once after the shard
2631/// callback returns, and recursive calls reuse the same buffer synchronously.
2632struct SerialScopedActionBuffer<'scope> {
2633    rule_set: &'scope RuleSet,
2634    match_counter: Arc<MatchCounter>,
2635    batches: DenseIdMap<ActionId, ActionState>,
2636}
2637
2638impl<'scope> SerialScopedActionBuffer<'scope> {
2639    fn new(rule_set: &'scope RuleSet, match_counter: Arc<MatchCounter>) -> Self {
2640        Self {
2641            rule_set,
2642            match_counter,
2643            batches: Default::default(),
2644        }
2645    }
2646}
2647
2648impl<'scope, 'exec> ActionBuffer<'scope, 'exec, ActionId> for SerialScopedActionBuffer<'scope>
2649where
2650    'exec: 'scope,
2651{
2652    type AsLocal<'a>
2653        = Self
2654    where
2655        'scope: 'a;
2656    type AsGlobalSerial<'a>
2657        = Self
2658    where
2659        'scope: 'a;
2660
2661    fn push_bindings(
2662        &mut self,
2663        action: ActionId,
2664        bindings: &DenseIdMap<Variable, Value>,
2665        mut to_exec_state: impl FnMut() -> ExecutionState<'scope>,
2666    ) {
2667        let batch_size = action_batch_size();
2668        let action_state = self
2669            .batches
2670            .get_or_insert(action, || ActionState::new(batch_size));
2671        action_state.n_runs += 1;
2672        action_state.len += 1;
2673        let action_info = &self.rule_set.actions[action];
2674        // SAFETY: `used_vars` is constant for the rule and the bindings come
2675        // from this rule's join plan.
2676        unsafe {
2677            action_state.bindings.push(bindings, &action_info.used_vars);
2678        }
2679        if action_state.len >= batch_size {
2680            let succeeded =
2681                to_exec_state().run_instrs(&action_info.instrs, &mut action_state.bindings);
2682            action_state.bindings.clear();
2683            self.match_counter.inc_matches(action, succeeded);
2684            action_state.len = 0;
2685        }
2686    }
2687
2688    fn flush(&mut self, exec_state: &mut ExecutionState) {
2689        flush_action_states(
2690            exec_state,
2691            &mut self.batches,
2692            self.rule_set,
2693            self.match_counter.as_ref(),
2694        );
2695    }
2696
2697    fn recur<'local, 'rows>(
2698        &mut self,
2699        mut local: BorrowedLocalState<'local, 'rows, 'exec>,
2700        subset_clone_plan: SubsetClonePlan<'_>,
2701        _to_exec_state: impl FnMut() -> ExecutionState<'scope> + Send + 'scope,
2702        work: impl for<'a> FnOnce(BorrowedLocalState<'a, 'scope, 'exec>, &mut Self) + Send + 'scope,
2703    ) where
2704        'rows: 'scope,
2705    {
2706        let mut inner: LocalState<'scope, 'exec> = local.clone_state(subset_clone_plan);
2707        work(inner.borrow_mut(), self);
2708    }
2709
2710    fn recur_global_serial<'local, 'rows>(
2711        &mut self,
2712        mut local: BorrowedLocalState<'local, 'rows, 'exec>,
2713        subset_clone_plan: SubsetClonePlan<'_>,
2714        _to_exec_state: impl FnMut() -> ExecutionState<'scope> + Send + 'scope,
2715        work: impl for<'a> FnOnce(BorrowedLocalState<'a, 'scope, 'exec>, &mut Self) + Send + 'scope,
2716    ) where
2717        'rows: 'scope,
2718    {
2719        let mut inner: LocalState<'scope, 'exec> = local.clone_state(subset_clone_plan);
2720        work(inner.borrow_mut(), self);
2721    }
2722
2723    fn supports_parallel_drain(&self) -> bool {
2724        false
2725    }
2726}
2727
2728/// An action buffer that hands off batches of actions to scoped worker tasks.
2729struct ScopedActionBuffer<'inner, 'scope> {
2730    scope: &'inner Scope<'scope>,
2731    rule_set: &'scope RuleSet,
2732    match_counter: Arc<MatchCounter>,
2733    batches: DenseIdMap<ActionId, ActionState>,
2734    needs_flush: bool,
2735}
2736
2737impl<'inner, 'scope> ScopedActionBuffer<'inner, 'scope> {
2738    fn new(
2739        scope: &'inner Scope<'scope>,
2740        rule_set: &'scope RuleSet,
2741        match_counter: Arc<MatchCounter>,
2742    ) -> Self {
2743        Self {
2744            scope,
2745            rule_set,
2746            batches: Default::default(),
2747            match_counter,
2748            needs_flush: false,
2749        }
2750    }
2751}
2752
2753impl<'scope, 'exec> ActionBuffer<'scope, 'exec, ActionId> for ScopedActionBuffer<'_, 'scope>
2754where
2755    'exec: 'scope,
2756{
2757    type AsLocal<'a>
2758        = ScopedActionBuffer<'a, 'scope>
2759    where
2760        'scope: 'a;
2761    type AsGlobalSerial<'a>
2762        = SerialScopedActionBuffer<'scope>
2763    where
2764        'scope: 'a;
2765    fn push_bindings(
2766        &mut self,
2767        action: ActionId,
2768        bindings: &DenseIdMap<Variable, Value>,
2769        mut to_exec_state: impl FnMut() -> ExecutionState<'scope>,
2770    ) {
2771        self.needs_flush = true;
2772        let batch_size = action_batch_size();
2773        let action_state = self
2774            .batches
2775            .get_or_insert(action, || ActionState::new(batch_size));
2776        action_state.n_runs += 1;
2777        action_state.len += 1;
2778        let action_info = &self.rule_set.actions[action];
2779        // SAFETY: `used_vars` is a constant per-rule. This module only ever calls it with
2780        // `bindings` produced by the same join.
2781        unsafe {
2782            action_state.bindings.push(bindings, &action_info.used_vars);
2783        }
2784        if action_state.len >= batch_size {
2785            let mut state = to_exec_state();
2786            let mut bindings = mem::replace(&mut action_state.bindings, Bindings::new(batch_size));
2787            action_state.len = 0;
2788            let match_counter = self.match_counter.clone();
2789            self.scope.spawn(move |_| {
2790                let succeeded = state.run_instrs(&action_info.instrs, &mut bindings);
2791                match_counter.inc_matches(action, succeeded);
2792            });
2793        }
2794    }
2795
2796    fn flush(&mut self, exec_state: &mut ExecutionState) {
2797        flush_action_states(
2798            exec_state,
2799            &mut self.batches,
2800            self.rule_set,
2801            self.match_counter.as_ref(),
2802        );
2803        self.needs_flush = false;
2804    }
2805    fn recur<'local, 'rows>(
2806        &mut self,
2807        mut local: BorrowedLocalState<'local, 'rows, 'exec>,
2808        subset_clone_plan: SubsetClonePlan<'_>,
2809        mut to_exec_state: impl FnMut() -> ExecutionState<'scope> + Send + 'scope,
2810        work: impl for<'a> FnOnce(
2811            BorrowedLocalState<'a, 'scope, 'exec>,
2812            &mut ScopedActionBuffer<'a, 'scope>,
2813        ) + Send
2814        + 'scope,
2815    ) where
2816        'rows: 'scope,
2817    {
2818        let rule_set = self.rule_set;
2819        let match_counter = self.match_counter.clone();
2820        let mut inner = local.clone_state(subset_clone_plan);
2821        // Keep recursive join work on the current worker when possible. If
2822        // coarse top-index partitioning was unavailable, stalled workers cause
2823        // the private deque to donate older siblings to the global queue.
2824        self.scope.spawn_local(move |scope| {
2825            let mut buf: ScopedActionBuffer<'_, 'scope> = ScopedActionBuffer {
2826                scope,
2827                rule_set,
2828                match_counter,
2829                needs_flush: false,
2830                batches: Default::default(),
2831            };
2832            work(inner.borrow_mut(), &mut buf);
2833            if buf.needs_flush {
2834                flush_action_states(
2835                    &mut to_exec_state(),
2836                    &mut buf.batches,
2837                    buf.rule_set,
2838                    buf.match_counter.as_ref(),
2839                );
2840            }
2841        });
2842    }
2843
2844    fn recur_global_serial<'local, 'rows>(
2845        &mut self,
2846        mut local: BorrowedLocalState<'local, 'rows, 'exec>,
2847        subset_clone_plan: SubsetClonePlan<'_>,
2848        mut to_exec_state: impl FnMut() -> ExecutionState<'scope> + Send + 'scope,
2849        work: impl for<'a> FnOnce(
2850            BorrowedLocalState<'a, 'scope, 'exec>,
2851            &mut SerialScopedActionBuffer<'scope>,
2852        ) + Send
2853        + 'scope,
2854    ) where
2855        'rows: 'scope,
2856    {
2857        let rule_set = self.rule_set;
2858        let match_counter = self.match_counter.clone();
2859        let mut inner = local.clone_state(subset_clone_plan);
2860        self.scope.spawn_global(move |_| {
2861            let mut buf = SerialScopedActionBuffer::new(rule_set, match_counter);
2862            work(inner.borrow_mut(), &mut buf);
2863            // Unlike a nested `ScopedActionBuffer`, this buffer is owned by the
2864            // one shard job and is always flushed exactly once before it exits.
2865            buf.flush(&mut to_exec_state());
2866        });
2867    }
2868
2869    fn morsel_size(&mut self, _level: usize, _total: usize) -> usize {
2870        // Lower morsel size to increase parallelism.
2871        match _level {
2872            0 if _total > 2 => 32,
2873            _ => 256,
2874        }
2875    }
2876
2877    fn supports_global_partition(&self) -> bool {
2878        true
2879    }
2880
2881    fn has_available_parallelism(&self) -> bool {
2882        self.scope.has_available_parallelism()
2883    }
2884}
2885
2886fn expand_binding_sets<'scope, 'exec, A: NumericId, BUF: ActionBuffer<'scope, 'exec, A> + ?Sized>(
2887    action_buf: &mut BUF,
2888    action: A,
2889    bindings: &mut DenseIdMap<Variable, Value>,
2890    binding_sets: &BindingSet,
2891    idx: usize,
2892    exec_state: &ExecutionStateSeed<'scope, '_>,
2893) where
2894    'exec: 'scope,
2895{
2896    if exec_state.should_stop() {
2897        return;
2898    }
2899    if idx >= binding_sets.len() {
2900        action_buf.push_bindings(action, bindings, || exec_state.to_execution_state());
2901        return;
2902    }
2903    if idx + 1 == binding_sets.len() {
2904        let (vars, buf) = &binding_sets[idx];
2905        for (_, row) in buf.iter() {
2906            if exec_state.should_stop() {
2907                return;
2908            }
2909            for (var, val) in vars.iter().zip(row.iter()) {
2910                bindings.insert(*var, *val);
2911            }
2912            action_buf.push_bindings(action, bindings, || exec_state.to_execution_state());
2913        }
2914        return;
2915    }
2916    let (vars, buf) = &binding_sets[idx];
2917    for (_, row) in buf.iter() {
2918        for (var, val) in vars.iter().zip(row.iter()) {
2919            bindings.insert(*var, *val);
2920        }
2921        expand_binding_sets(
2922            action_buf,
2923            action,
2924            bindings,
2925            binding_sets,
2926            idx + 1,
2927            exec_state,
2928        );
2929    }
2930}
2931
2932fn flush_action_states(
2933    exec_state: &mut ExecutionState,
2934    actions: &mut DenseIdMap<ActionId, ActionState>,
2935    rule_set: &RuleSet,
2936    match_counter: &MatchCounter,
2937) {
2938    for (action, ActionState { bindings, len, .. }) in actions.iter_mut() {
2939        if *len > 0 {
2940            let succeeded = exec_state.run_instrs(&rule_set.actions[action].instrs, bindings);
2941            bindings.clear();
2942            match_counter.inc_matches(action, succeeded);
2943            *len = 0;
2944        }
2945    }
2946}
2947
2948struct InPlaceMaterializer<'a> {
2949    specs: &'a DenseIdMap<MatId, MatSpec>,
2950    materializations: DenseIdMap<MatId, IndexMap<Vec<Value>, RowBuffer>>,
2951    scratch_key: Vec<Value>,
2952    scratch_val: Vec<Value>,
2953}
2954
2955impl<'scope, 'exec, 'outer: 'scope> ActionBuffer<'scope, 'exec, MatId>
2956    for InPlaceMaterializer<'outer>
2957where
2958    'exec: 'scope,
2959{
2960    type AsLocal<'b>
2961        = Self
2962    where
2963        'scope: 'b;
2964    type AsGlobalSerial<'b>
2965        = Self
2966    where
2967        'scope: 'b;
2968
2969    fn push_bindings(
2970        &mut self,
2971        mat_id: MatId,
2972        bindings: &DenseIdMap<Variable, Value>,
2973        _to_exec_state: impl FnMut() -> ExecutionState<'scope>,
2974    ) {
2975        let mat = self
2976            .materializations
2977            .get_mut(mat_id)
2978            .expect("invalid mat id");
2979        let spec = self.specs.get(mat_id).expect("invalid mat id");
2980        self.scratch_key.clear();
2981        for key in spec.msg_vars.iter().map(|var| bindings[*var]) {
2982            self.scratch_key.push(key);
2983        }
2984        self.scratch_val.clear();
2985        for val in spec.val_vars.iter().map(|var| bindings[*var]) {
2986            self.scratch_val.push(val);
2987        }
2988        if self.scratch_val.is_empty() {
2989            self.scratch_val.push(Value::stale());
2990        }
2991        if let Some(buffer) = mat.get_mut(&self.scratch_key) {
2992            buffer.add_row(&self.scratch_val);
2993        } else {
2994            let mut buffer = RowBuffer::new(usize::max(spec.val_vars.len(), 1));
2995            buffer.add_row(&self.scratch_val);
2996            mat.insert(self.scratch_key.clone(), buffer);
2997        }
2998    }
2999
3000    fn flush(&mut self, _exec_state: &mut ExecutionState) {
3001        // No-op for in-place materializer.
3002    }
3003
3004    fn recur<'local, 'rows>(
3005        &mut self,
3006        mut local: BorrowedLocalState<'local, 'rows, 'exec>,
3007        subset_clone_plan: SubsetClonePlan<'_>,
3008        _to_exec_state: impl FnMut() -> ExecutionState<'scope> + Send + 'scope,
3009        work: impl for<'b> FnOnce(BorrowedLocalState<'b, 'scope, 'exec>, &mut Self) + Send + 'scope,
3010    ) where
3011        'rows: 'scope,
3012    {
3013        let mut inner: LocalState<'scope, 'exec> = local.clone_state(subset_clone_plan);
3014        work(inner.borrow_mut(), self)
3015    }
3016
3017    fn recur_global_serial<'local, 'rows>(
3018        &mut self,
3019        mut local: BorrowedLocalState<'local, 'rows, 'exec>,
3020        subset_clone_plan: SubsetClonePlan<'_>,
3021        _to_exec_state: impl FnMut() -> ExecutionState<'scope> + Send + 'scope,
3022        work: impl for<'b> FnOnce(BorrowedLocalState<'b, 'scope, 'exec>, &mut Self) + Send + 'scope,
3023    ) where
3024        'rows: 'scope,
3025    {
3026        let mut inner: LocalState<'scope, 'exec> = local.clone_state(subset_clone_plan);
3027        work(inner.borrow_mut(), self)
3028    }
3029
3030    fn supports_parallel_drain(&self) -> bool {
3031        false
3032    }
3033}
3034
3035/// Serial recursive view of a scoped materializer.  Sibling top-level shards
3036/// still share the concurrent output maps, but this buffer never schedules
3037/// deeper work itself.
3038struct SerialScopedMaterializer {
3039    specs: Arc<DenseIdMap<MatId, MatSpec>>,
3040    materializations: Arc<DenseIdMap<MatId, Arc<DashMap<Vec<Value>, RowBuffer>>>>,
3041    scratch_key: Vec<Value>,
3042    scratch_val: Vec<Value>,
3043}
3044
3045impl SerialScopedMaterializer {
3046    fn new(
3047        specs: Arc<DenseIdMap<MatId, MatSpec>>,
3048        materializations: Arc<DenseIdMap<MatId, Arc<DashMap<Vec<Value>, RowBuffer>>>>,
3049    ) -> Self {
3050        Self {
3051            specs,
3052            materializations,
3053            scratch_key: Vec::new(),
3054            scratch_val: Vec::new(),
3055        }
3056    }
3057}
3058
3059impl<'scope, 'exec> ActionBuffer<'scope, 'exec, MatId> for SerialScopedMaterializer
3060where
3061    'exec: 'scope,
3062{
3063    type AsLocal<'a>
3064        = Self
3065    where
3066        'scope: 'a;
3067    type AsGlobalSerial<'a>
3068        = Self
3069    where
3070        'scope: 'a;
3071
3072    fn push_bindings(
3073        &mut self,
3074        mat_id: MatId,
3075        bindings: &DenseIdMap<Variable, Value>,
3076        _to_exec_state: impl FnMut() -> ExecutionState<'scope>,
3077    ) {
3078        let mat = self.materializations.get(mat_id).expect("invalid mat id");
3079        let spec = self.specs.get(mat_id).expect("invalid mat id");
3080        self.scratch_key.clear();
3081        self.scratch_key
3082            .extend(spec.msg_vars.iter().map(|var| bindings[*var]));
3083        self.scratch_val.clear();
3084        self.scratch_val
3085            .extend(spec.val_vars.iter().map(|var| bindings[*var]));
3086        if self.scratch_val.is_empty() {
3087            self.scratch_val.push(Value::stale());
3088        }
3089        match mat.entry(self.scratch_key.clone()) {
3090            Entry::Occupied(mut occupied) => {
3091                occupied.get_mut().add_row(&self.scratch_val);
3092            }
3093            Entry::Vacant(vacant) => {
3094                let mut buffer = RowBuffer::new(usize::max(spec.val_vars.len(), 1));
3095                buffer.add_row(&self.scratch_val);
3096                vacant.insert(buffer);
3097            }
3098        }
3099    }
3100
3101    fn flush(&mut self, _exec_state: &mut ExecutionState) {}
3102
3103    fn recur<'local, 'rows>(
3104        &mut self,
3105        mut local: BorrowedLocalState<'local, 'rows, 'exec>,
3106        subset_clone_plan: SubsetClonePlan<'_>,
3107        _to_exec_state: impl FnMut() -> ExecutionState<'scope> + Send + 'scope,
3108        work: impl for<'a> FnOnce(BorrowedLocalState<'a, 'scope, 'exec>, &mut Self) + Send + 'scope,
3109    ) where
3110        'rows: 'scope,
3111    {
3112        let mut inner: LocalState<'scope, 'exec> = local.clone_state(subset_clone_plan);
3113        work(inner.borrow_mut(), self);
3114    }
3115
3116    fn recur_global_serial<'local, 'rows>(
3117        &mut self,
3118        mut local: BorrowedLocalState<'local, 'rows, 'exec>,
3119        subset_clone_plan: SubsetClonePlan<'_>,
3120        _to_exec_state: impl FnMut() -> ExecutionState<'scope> + Send + 'scope,
3121        work: impl for<'a> FnOnce(BorrowedLocalState<'a, 'scope, 'exec>, &mut Self) + Send + 'scope,
3122    ) where
3123        'rows: 'scope,
3124    {
3125        let mut inner: LocalState<'scope, 'exec> = local.clone_state(subset_clone_plan);
3126        work(inner.borrow_mut(), self);
3127    }
3128
3129    fn supports_parallel_drain(&self) -> bool {
3130        false
3131    }
3132}
3133
3134struct ScopedMaterializer<'inner, 'scope, 'exec> {
3135    scope: &'inner Scope<'scope>,
3136    retired_states: &'scope RetiredLocalStates<'scope, 'exec>,
3137    specs: Arc<DenseIdMap<MatId, MatSpec>>,
3138    materializations: Arc<DenseIdMap<MatId, Arc<DashMap<Vec<Value>, RowBuffer>>>>,
3139    scratch_key: Vec<Value>,
3140    scratch_val: Vec<Value>,
3141}
3142impl<'scope, 'exec> ActionBuffer<'scope, 'exec, MatId> for ScopedMaterializer<'_, 'scope, 'exec>
3143where
3144    'exec: 'scope,
3145{
3146    type AsLocal<'a>
3147        = ScopedMaterializer<'a, 'scope, 'exec>
3148    where
3149        'scope: 'a;
3150    type AsGlobalSerial<'a>
3151        = SerialScopedMaterializer
3152    where
3153        'scope: 'a;
3154
3155    fn push_bindings(
3156        &mut self,
3157        mat_id: MatId,
3158        bindings: &DenseIdMap<Variable, Value>,
3159        _to_exec_state: impl FnMut() -> ExecutionState<'scope>,
3160    ) {
3161        let mat = self.materializations.get(mat_id).expect("invalid mat id");
3162        let spec = self.specs.get(mat_id).expect("invalid mat id");
3163        self.scratch_key.clear();
3164        for key in spec.msg_vars.iter().map(|var| bindings[*var]) {
3165            self.scratch_key.push(key);
3166        }
3167        self.scratch_val.clear();
3168        for val in spec.val_vars.iter().map(|var| bindings[*var]) {
3169            self.scratch_val.push(val);
3170        }
3171        if self.scratch_val.is_empty() {
3172            self.scratch_val.push(Value::stale());
3173        }
3174        let key = self.scratch_key.clone();
3175        match mat.entry(key) {
3176            Entry::Occupied(mut occ) => {
3177                occ.get_mut().add_row(&self.scratch_val);
3178            }
3179            Entry::Vacant(vac) => {
3180                let mut buffer = RowBuffer::new(usize::max(spec.val_vars.len(), 1));
3181                buffer.add_row(&self.scratch_val);
3182                vac.insert(buffer);
3183            }
3184        }
3185    }
3186
3187    fn flush(&mut self, _exec_state: &mut ExecutionState) {
3188        // No-op for scoped materializer since we always write to the materialization in-place.
3189    }
3190
3191    fn recur<'local, 'rows>(
3192        &mut self,
3193        mut local: BorrowedLocalState<'local, 'rows, 'exec>,
3194        subset_clone_plan: SubsetClonePlan<'_>,
3195        _to_exec_state: impl FnMut() -> ExecutionState<'scope> + Send + 'scope,
3196        work: impl for<'a> FnOnce(
3197            BorrowedLocalState<'a, 'scope, 'exec>,
3198            &mut ScopedMaterializer<'a, 'scope, 'exec>,
3199        ) + Send
3200        + 'scope,
3201    ) where
3202        'rows: 'scope,
3203    {
3204        let scope = self.scope;
3205        let retired_states = self.retired_states;
3206        let specs = self.specs.clone();
3207        let materializations = self.materializations.clone();
3208        let mut inner = local.clone_state(subset_clone_plan);
3209        // Match the action path: preserve locality by default and rely on
3210        // private-deque donation when other workers need fallback work.
3211        scope.spawn_local(move |scope| {
3212            let mut buf: ScopedMaterializer<'_, 'scope, 'exec> = ScopedMaterializer {
3213                scope,
3214                retired_states,
3215                specs,
3216                materializations: materializations.clone(),
3217                scratch_key: Vec::new(),
3218                scratch_val: Vec::new(),
3219            };
3220            work(inner.borrow_mut(), &mut buf);
3221            retired_states.retire(inner);
3222        });
3223    }
3224
3225    fn recur_global_serial<'local, 'rows>(
3226        &mut self,
3227        mut local: BorrowedLocalState<'local, 'rows, 'exec>,
3228        subset_clone_plan: SubsetClonePlan<'_>,
3229        _to_exec_state: impl FnMut() -> ExecutionState<'scope> + Send + 'scope,
3230        work: impl for<'a> FnOnce(BorrowedLocalState<'a, 'scope, 'exec>, &mut SerialScopedMaterializer)
3231        + Send
3232        + 'scope,
3233    ) where
3234        'rows: 'scope,
3235    {
3236        let specs = self.specs.clone();
3237        let materializations = self.materializations.clone();
3238        let retired_states = self.retired_states;
3239        let mut inner = local.clone_state(subset_clone_plan);
3240        self.scope.spawn_global(move |_| {
3241            let mut buf = SerialScopedMaterializer::new(specs, materializations);
3242            work(inner.borrow_mut(), &mut buf);
3243            retired_states.retire(inner);
3244        });
3245    }
3246
3247    fn supports_global_partition(&self) -> bool {
3248        true
3249    }
3250
3251    fn has_available_parallelism(&self) -> bool {
3252        self.scope.has_available_parallelism()
3253    }
3254}
3255
3256#[cfg(test)]
3257#[path = "execute_tests.rs"]
3258mod top_index_tests;