egglog_core_relations/hash_index/
mod.rs

1//! Hash-based secondary indexes.
2#[cfg(test)]
3use std::sync::atomic::{AtomicUsize, Ordering};
4use std::{
5    cmp,
6    hash::{Hash, Hasher},
7    mem,
8    sync::{Mutex, OnceLock},
9};
10
11use crate::{
12    common::IndexMap,
13    numeric_id::{IdVec, NumericId, define_id},
14};
15use egglog_concurrency::{ReadOptimizedLock, ThreadPool};
16use hashbrown::HashTable;
17use indexmap::map::Entry;
18use once_cell::sync::Lazy;
19use rustc_hash::FxHasher;
20use smallvec::SmallVec;
21
22use crate::{
23    OffsetRange, Subset,
24    common::{ShardData, ShardId, Value},
25    offsets::{RowId, SortedOffsetSlice, SubsetRef},
26    parallel,
27    parallel_heuristics::parallelize_index_construction,
28    pool::{Pooled, with_pool_set},
29    row_buffer::{RowBuffer, RowSink, TaggedRowBuffer},
30    table_spec::{ColumnId, Generation, Offset, TableVersion, WrappedTableRef},
31};
32
33#[cfg(test)]
34mod tests;
35
36mod radix_sort;
37
38#[doc(hidden)]
39pub mod bench_support;
40
41#[derive(Clone)]
42pub(crate) struct TableEntry<T> {
43    hash: u64,
44    /// Points into `keys`
45    key: RowId,
46    vals: T,
47}
48
49#[derive(Clone)]
50pub(crate) struct Index<TI> {
51    key: Vec<ColumnId>,
52    updated_to: TableVersion,
53    table: TI,
54}
55
56/// A stable position for one key within a frozen index.
57///
58/// Positions are scoped to the exact index that produced them. They may be
59/// retained while that index is only read. Existing positions also survive an
60/// append-only incremental refresh, but a clear/full rebuild invalidates every
61/// position. The two components are deliberately private so callers cannot
62/// manufacture positions belonging to another index.
63#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
64pub(crate) struct IndexPosition {
65    shard: u32,
66    slot: u32,
67}
68
69impl IndexPosition {
70    fn new(shard: ShardId, slot: usize) -> Self {
71        Self {
72            shard: u32::try_from(shard.index()).expect("index shard exceeds u32::MAX"),
73            slot: u32::try_from(slot).expect("index shard contains more than u32::MAX keys"),
74        }
75    }
76
77    pub(crate) fn shard(self) -> usize {
78        self.shard as usize
79    }
80
81    pub(crate) fn slot(self) -> usize {
82        self.slot as usize
83    }
84}
85
86impl<TI: IndexBase> Index<TI> {
87    pub(crate) fn new(key: Vec<ColumnId>, table: TI) -> Self {
88        Index {
89            key,
90            updated_to: TableVersion {
91                major: Generation::new(0),
92                minor: Offset::new(0),
93            },
94            table,
95        }
96    }
97
98    /// Get the nonempty subset of rows associated with this key, if there is
99    /// one.
100    pub(crate) fn get_subset<'a>(&'a self, key: &TI::Key) -> Option<SubsetRef<'a>> {
101        self.table.get_subset(key)
102    }
103
104    pub(crate) fn needs_refresh(&self, table: WrappedTableRef) -> bool {
105        table.version() != self.updated_to
106    }
107
108    /// Physical rows that [`Index::refresh`] would scan for a table at `current`.
109    pub(crate) fn stale_rows(&self, current: TableVersion) -> usize {
110        if current.major == self.updated_to.major {
111            current
112                .minor
113                .index()
114                .saturating_sub(self.updated_to.minor.index())
115        } else {
116            current.minor.index()
117        }
118    }
119
120    pub(crate) fn refresh(&mut self, table: WrappedTableRef) {
121        let cur_version = table.version();
122        if cur_version == self.updated_to {
123            return;
124        }
125        let is_full = cur_version.major != self.updated_to.major;
126        let subset = if is_full {
127            self.table.clear();
128            table.all()
129        } else {
130            table.updates_since(self.updated_to.minor)
131        };
132        // Three ways to fold `subset` into the index; all produce the same result (each value's
133        // rows sorted ascending and de-duplicated) but trade fixed overhead against throughput:
134        //
135        // * `merge_parallel` shards the rows across worker threads. It handles both full and
136        //   incremental refreshes (it appends to whatever is already indexed), but the thread
137        //   coordination only pays off once `subset` clears the size cutoff.
138        // * `rebuild_full` is the serial bulk path for a full rebuild: it sorts all (value, row)
139        //   pairs and sizes each key's subset in a single allocation, avoiding the repeated
140        //   regrowth of the row-at-a-time path. It assumes an empty index, so it is only valid
141        //   right after the major-version `clear()` above.
142        // * `refresh_serial` scans in batches and inserts one row at a time into the existing
143        //   index. Lowest fixed cost, and the only path suited to merging a small incremental
144        //   delta into the index's prior contents.
145        if parallelize_index_construction(subset.size()) {
146            self.table.merge_parallel(&self.key, table, subset.as_ref());
147        } else if is_full {
148            self.table.rebuild_full(&self.key, table, subset.as_ref());
149        } else {
150            self.refresh_serial(table, subset);
151        }
152
153        self.updated_to = cur_version;
154    }
155
156    /// Update the contents of the index to the current version of the table.
157    ///
158    /// The index is guaranteed to be up to date until `merge` is called on the
159    /// table again.
160    pub(crate) fn refresh_serial(&mut self, table: WrappedTableRef, subset: Subset) {
161        let mut buf = TaggedRowBuffer::new(self.key.len());
162        let mut cur = Offset::new(0);
163        loop {
164            buf.clear();
165            if let Some(next) =
166                table.scan_project(subset.as_ref(), &self.key, cur, 1024, &[], &mut buf)
167            {
168                cur = next;
169                self.table.merge_rows(&buf);
170            } else {
171                self.table.merge_rows(&buf);
172                break;
173            }
174        }
175    }
176
177    /// Return the number of physical shards in this index.
178    pub(crate) fn shard_count(&self) -> usize {
179        self.table.shard_count()
180    }
181
182    /// Return the number of distinct keys stored in one physical shard.
183    pub(crate) fn shard_len(&self, shard: usize) -> usize {
184        self.table.shard_len(shard)
185    }
186
187    pub(crate) fn len(&self) -> usize {
188        self.table.len()
189    }
190}
191
192impl<TI: PositionedIndexBase> Index<TI> {
193    /// Get a key's execution-stable position along with its nonempty subset.
194    pub(crate) fn get_subset_positioned<'a>(
195        &'a self,
196        key: &TI::Key,
197    ) -> Option<(IndexPosition, SubsetRef<'a>)> {
198        self.table.get_subset_positioned(key)
199    }
200
201    /// Visit every key together with its execution-stable position.
202    pub(crate) fn for_each_positioned<'a>(
203        &'a self,
204        f: impl FnMut(IndexPosition, &'a TI::Key, SubsetRef<'a>),
205    ) {
206        self.table.for_each_positioned(f);
207    }
208
209    /// Visit one physical shard together with each key's stable position.
210    pub(crate) fn for_each_shard_positioned<'a>(
211        &'a self,
212        shard: usize,
213        f: impl FnMut(IndexPosition, &'a TI::Key, SubsetRef<'a>),
214    ) {
215        self.table.for_each_shard_positioned(shard, f);
216    }
217}
218
219pub(crate) struct SubsetTable {
220    keys: RowBuffer,
221    hash: Pooled<HashTable<TableEntry<BufferedSubset>>>,
222}
223
224impl Clone for SubsetTable {
225    fn clone(&self) -> Self {
226        SubsetTable {
227            keys: self.keys.clone(),
228            hash: Pooled::cloned(&self.hash),
229        }
230    }
231}
232
233impl SubsetTable {
234    fn new(key_arity: usize) -> SubsetTable {
235        SubsetTable {
236            keys: RowBuffer::new(key_arity),
237            hash: with_pool_set(|ps| ps.get()),
238        }
239    }
240}
241
242pub(crate) trait IndexBase {
243    /// The type of keys for this index.  Keys can have validity constraints
244    /// (e.g. the arity of a slice for `Key = [Value]`). If keys are invalid,
245    /// these methods can panic.
246    type Key: ?Sized;
247
248    /// The write-side keys for an index. This is generally the same as `Key`, but Column-level
249    /// indexes allow for multiple values (e.g. a subset of a row) to be provided, allowing the
250    /// index to effectively cover multiple columns. This is useful for rebuilding.
251    type WriteKey: ?Sized;
252
253    /// Remove any existing entries in the index.
254    fn clear(&mut self);
255    /// Get the subset corresponding to this key, if there is one.
256    fn get_subset(&self, key: &Self::Key) -> Option<SubsetRef<'_>>;
257    /// Add the given key and row id to the table.
258    fn add_row(&mut self, key: &Self::WriteKey, row: RowId);
259    /// Merge the contents of the [`TaggedRowBuffer`] into the table.
260    fn merge_rows(&mut self, buf: &TaggedRowBuffer);
261    /// The number of physical shards in the index.
262    fn shard_count(&self) -> usize;
263    /// The number of distinct keys in one physical shard.
264    fn shard_len(&self, shard: usize) -> usize;
265    /// The number of keys in the index.
266    fn len(&self) -> usize;
267
268    fn merge_parallel(&mut self, cols: &[ColumnId], table: WrappedTableRef, subset: SubsetRef);
269
270    /// Bulk-rebuild this index from scratch (called on major version change after clear()).
271    /// The default implementation batches via `scan_project`+`merge_rows`. Implementations
272    /// can override this for more efficient bulk construction.
273    fn rebuild_full(&mut self, cols: &[ColumnId], table: WrappedTableRef, subset: SubsetRef) {
274        let mut buf = TaggedRowBuffer::new(cols.len());
275        let mut cur = Offset::new(0);
276        loop {
277            buf.clear();
278            if let Some(next) = table.scan_project(subset, cols, cur, 1024, &[], &mut buf) {
279                cur = next;
280                self.merge_rows(&buf);
281            } else {
282                self.merge_rows(&buf);
283                break;
284            }
285        }
286    }
287}
288
289/// Read-only index operations that also expose a stable per-index key position.
290///
291/// Implementations may choose different physical slot schemes. Positions only
292/// need to remain stable while the index is frozen; callers must treat them as
293/// opaque tokens belonging to the exact index that returned them.
294pub(crate) trait PositionedIndexBase: IndexBase {
295    fn get_subset_positioned<'a>(
296        &'a self,
297        key: &Self::Key,
298    ) -> Option<(IndexPosition, SubsetRef<'a>)>;
299
300    fn for_each_positioned<'a>(
301        &'a self,
302        f: impl FnMut(IndexPosition, &'a Self::Key, SubsetRef<'a>),
303    );
304
305    fn for_each_shard_positioned<'a>(
306        &'a self,
307        shard: usize,
308        f: impl FnMut(IndexPosition, &'a Self::Key, SubsetRef<'a>),
309    );
310}
311
312struct ColumnIndexShard {
313    /// It's important that table is implemented using IndexMap instead of the more efficient
314    /// HashMap because we want stable enumeration order.
315    table: Pooled<IndexMap<Value, BufferedSubset>>,
316    subsets: SubsetBuffer,
317}
318
319struct ColumnIndexPairSink {
320    pairs: Vec<(Value, RowId)>,
321}
322
323impl ColumnIndexPairSink {
324    fn with_capacity(capacity: usize) -> Self {
325        Self {
326            pairs: Vec::with_capacity(capacity),
327        }
328    }
329}
330
331impl RowSink for ColumnIndexPairSink {
332    fn add_row(&mut self, row_id: RowId, keys: &[Value]) {
333        for (i, key) in keys.iter().enumerate() {
334            // A value repeated across covered columns maps the row only once.
335            if !keys[..i].contains(key) {
336                self.pairs.push((*key, row_id));
337            }
338        }
339    }
340}
341
342struct SortedIndexChunk {
343    /// Ordered by (physical shard, value, row id) and de-duplicated.
344    pairs: Vec<(Value, RowId)>,
345    /// Each physical shard owns one contiguous range in `pairs`.
346    shard_ranges: IdVec<ShardId, std::ops::Range<usize>>,
347}
348
349fn value_shard_id(shard_data: ShardData, value: Value) -> ShardId {
350    let mut hasher = FxHasher::default();
351    value.hash(&mut hasher);
352    shard_data.shard_id(hasher.finish())
353}
354
355fn sort_index_chunk(mut pairs: Vec<(Value, RowId)>, shard_data: ShardData) -> SortedIndexChunk {
356    if pairs.is_empty() {
357        let mut shard_ranges = IdVec::with_capacity(shard_data.n_shards());
358        shard_ranges.resize_with(shard_data.n_shards(), || 0..0);
359        return SortedIndexChunk {
360            pairs,
361            shard_ranges,
362        };
363    }
364
365    // The scan emits rows in RowId order. The stable value radix sort therefore
366    // produces (Value, RowId) order without a RowId pass.
367    let original_len = pairs.len();
368    let mut scratch = vec![(Value::new_const(0), RowId::new_const(0)); original_len];
369    radix_sort_slice_by_value(&mut pairs, &mut scratch);
370    pairs.dedup();
371
372    // A final stable counting pass by physical shard turns each shard's values
373    // into one contiguous run while preserving (Value, RowId) order within it.
374    let mut counts = vec![0usize; shard_data.n_shards()];
375    for &(value, _) in &pairs {
376        counts[value_shard_id(shard_data, value).index()] += 1;
377    }
378    let mut starts = counts;
379    let mut prefix = 0;
380    for count in &mut starts {
381        let size = *count;
382        *count = prefix;
383        prefix += size;
384    }
385    let mut next = starts.clone();
386    for &pair in &pairs {
387        let shard = value_shard_id(shard_data, pair.0).index();
388        scratch[next[shard]] = pair;
389        next[shard] += 1;
390    }
391    scratch.truncate(pairs.len());
392    mem::swap(&mut pairs, &mut scratch);
393
394    let mut shard_ranges = IdVec::with_capacity(shard_data.n_shards());
395    for (start, end) in starts.into_iter().zip(next) {
396        shard_ranges.push(start..end);
397    }
398    SortedIndexChunk {
399        pairs,
400        shard_ranges,
401    }
402}
403
404const MIN_COARSE_INDEX_SCAN_ROWS: usize = 256;
405// Below this worker count, the radix-sort setup costs more than it saves over
406// the existing fine-grained scan-and-split path.
407const MIN_COARSE_INDEX_SCAN_THREADS: usize = 8;
408
409fn coarse_index_scan_partition_size(scan_size: usize, workers: usize) -> usize {
410    scan_size
411        .div_ceil(workers.max(1))
412        .max(MIN_COARSE_INDEX_SCAN_ROWS)
413}
414
415fn subset_partition<'a>(subset: SubsetRef<'a>, start: usize, end: usize) -> SubsetRef<'a> {
416    debug_assert!(start <= end);
417    debug_assert!(end <= subset.size());
418    match subset {
419        SubsetRef::Dense(range) => SubsetRef::Dense(OffsetRange::new(
420            RowId::from_usize(range.start.index() + start),
421            RowId::from_usize(range.start.index() + end),
422        )),
423        SubsetRef::Sparse(rows) => SubsetRef::Sparse(rows.subslice(start, end)),
424    }
425}
426
427impl Clone for ColumnIndexShard {
428    fn clone(&self) -> Self {
429        ColumnIndexShard {
430            table: Pooled::cloned(&self.table),
431            subsets: self.subsets.clone(),
432        }
433    }
434}
435
436impl ColumnIndexShard {
437    fn merge_sorted_pairs(&mut self, pairs: &[(Value, RowId)]) {
438        let mut start = 0;
439        while start < pairs.len() {
440            let key = pairs[start].0;
441            let mut end = start + 1;
442            while end < pairs.len() && pairs[end].0 == key {
443                end += 1;
444            }
445            let run = &pairs[start..end];
446            match self.table.entry(key) {
447                Entry::Occupied(mut occupied) => {
448                    // SAFETY: every sparse subset in this table comes from
449                    // `self.subsets`, and source partitions are consumed in
450                    // ascending RowId order.
451                    unsafe {
452                        occupied
453                            .get_mut()
454                            .merge_sorted_pairs(run, &mut self.subsets);
455                    }
456                }
457                Entry::Vacant(vacant) => {
458                    vacant.insert(buffered_subset_from_sorted_pairs(run, &mut self.subsets));
459                }
460            }
461            start = end;
462        }
463    }
464}
465
466#[derive(Clone)]
467pub struct ColumnIndex {
468    // A specialized index used when we are indexing on a single column.
469    shard_data: ShardData,
470    shards: IdVec<ShardId, ColumnIndexShard>,
471}
472
473impl IndexBase for ColumnIndex {
474    type Key = Value;
475    type WriteKey = [Value];
476    fn clear(&mut self) {
477        for (_, shard) in self.shards.iter_mut() {
478            for (_, subset) in shard.table.drain(..) {
479                match subset {
480                    BufferedSubset::Dense(_) => {}
481                    BufferedSubset::Sparse(buffered_vec) => {
482                        shard.subsets.return_vec(buffered_vec);
483                    }
484                }
485            }
486        }
487    }
488
489    fn get_subset<'a>(&'a self, key: &Value) -> Option<SubsetRef<'a>> {
490        let shard = self.shard_data.get_shard(key, &self.shards);
491        shard.table.get(key).map(|x| x.as_ref(&shard.subsets))
492    }
493    fn add_row(&mut self, vals: &[Value], row: RowId) {
494        for (i, key) in vals.iter().enumerate() {
495            // A value repeated across this row's covered columns maps the row in only once.
496            if vals[..i].contains(key) {
497                continue;
498            }
499            let shard = self.shard_data.get_shard_mut(key, &mut self.shards);
500            // SAFETY: everything in `table` comes from `subsets`.
501            unsafe {
502                shard
503                    .table
504                    .entry(*key)
505                    .or_insert_with(BufferedSubset::empty)
506                    .add_row_sorted(row, &mut shard.subsets);
507            }
508        }
509    }
510    fn merge_rows(&mut self, buf: &TaggedRowBuffer) {
511        for (src_id, key) in buf.iter() {
512            self.add_row(key, src_id);
513        }
514    }
515
516    fn shard_count(&self) -> usize {
517        self.shards.len()
518    }
519
520    fn shard_len(&self, shard: usize) -> usize {
521        self.shards[ShardId::from_usize(shard)].table.len()
522    }
523
524    fn len(&self) -> usize {
525        self.shards.iter().map(|(_, shard)| shard.table.len()).sum()
526    }
527
528    fn merge_parallel(&mut self, cols: &[ColumnId], table: WrappedTableRef, subset: SubsetRef) {
529        let shard_data = self.shard_data;
530        let workers = parallel::current_num_threads();
531        let use_coarse_scan = workers >= MIN_COARSE_INDEX_SCAN_THREADS;
532        let partition_size = coarse_index_scan_partition_size(subset.size(), workers);
533        let n_partitions = subset.size().div_ceil(partition_size);
534
535        run_in_index_thread_pool(|| {
536            if use_coarse_scan {
537                // A fixed slot per logical partition transfers ownership of
538                // each sorted backing vector out of its producer task. After
539                // the scope joins, shard workers can borrow their contiguous
540                // ranges directly without Arc ownership or another copy.
541                let chunks = (0..n_partitions)
542                    .map(|_| OnceLock::new())
543                    .collect::<Vec<OnceLock<SortedIndexChunk>>>();
544                egglog_concurrency::scope(|inner| {
545                    for (partition_id, start) in
546                        (0..subset.size()).step_by(partition_size).enumerate()
547                    {
548                        let end = cmp::min(start + partition_size, subset.size());
549                        let partition = subset_partition(subset, start, end);
550                        let slot = &chunks[partition_id];
551                        inner.spawn(move |_| {
552                            let capacity = partition.size().saturating_mul(cols.len());
553                            let mut sink = ColumnIndexPairSink::with_capacity(capacity);
554                            let next = table.scan_project(
555                                partition,
556                                cols,
557                                Offset::new(0),
558                                usize::MAX,
559                                &[],
560                                &mut sink,
561                            );
562                            debug_assert!(next.is_none());
563                            slot.set(sort_index_chunk(sink.pairs, shard_data))
564                                .unwrap_or_else(|_| unreachable!("partition slot set twice"));
565                        });
566                    }
567                });
568                parallel::for_each_id_vec_mut(&mut self.shards, |shard_id, shard| {
569                    for slot in &chunks {
570                        let chunk = slot
571                            .get()
572                            .expect("all index scan partitions completed before population");
573                        let range = chunk.shard_ranges[shard_id].clone();
574                        shard.merge_sorted_pairs(&chunk.pairs[range]);
575                    }
576                });
577                return;
578            }
579
580            const BATCH_SIZE: usize = 1024;
581            let mut queues = IdVec::<ShardId, Mutex<Vec<(RowId, TaggedRowBuffer)>>>::with_capacity(
582                shard_data.n_shards(),
583            );
584            queues.resize_with(shard_data.n_shards(), || {
585                Mutex::new(Vec::with_capacity((subset.size() / BATCH_SIZE) + 1))
586            });
587            let split_buf = |buf: TaggedRowBuffer| {
588                let mut split = IdVec::<ShardId, TaggedRowBuffer>::default();
589                split.resize_with(shard_data.n_shards(), || TaggedRowBuffer::new(1));
590                for (row_id, keys) in buf.iter() {
591                    for (i, key) in keys.iter().enumerate() {
592                        // Match `add_row`: a value repeated across this row's covered columns is
593                        // recorded once, so a value's subset never holds a duplicate row id.
594                        if keys[..i].contains(key) {
595                            continue;
596                        }
597                        shard_data
598                            .get_shard_mut(*key, &mut split)
599                            .add_row(row_id, &[*key]);
600                    }
601                }
602                for (shard_id, buf) in split.drain() {
603                    if buf.is_empty() {
604                        continue;
605                    }
606                    let first = buf.get_row(RowId::new(0)).0;
607                    queues[shard_id].lock().unwrap().push((first, buf));
608                }
609            };
610            egglog_concurrency::scope(|inner| {
611                let mut cur = Offset::new(0);
612                loop {
613                    let mut buf = TaggedRowBuffer::new(cols.len());
614                    if let Some(next) =
615                        table.scan_project(subset, cols, cur, BATCH_SIZE, &[], &mut buf)
616                    {
617                        cur = next;
618                        inner.spawn(move |_| split_buf(buf));
619                    } else {
620                        inner.spawn(move |_| split_buf(buf));
621                        break;
622                    }
623                }
624            });
625            parallel::for_each_id_vec_mut(&mut self.shards, |shard_id, shard| {
626                // Sort the vector by start row id to ensure we populate subsets in sorted order.
627                let mut vec = queues[shard_id].lock().unwrap();
628                vec.sort_by_key(|(start, _)| *start);
629                for (_, buf) in vec.drain(..) {
630                    for (row_id, key) in buf.iter() {
631                        debug_assert_eq!(key.len(), 1);
632                        match shard.table.entry(key[0]) {
633                            Entry::Occupied(mut occ) => {
634                                // SAFETY: all of the buffered vectors in this map come from `subsets`.
635                                unsafe {
636                                    occ.get_mut().add_row_sorted(row_id, &mut shard.subsets);
637                                }
638                            }
639                            Entry::Vacant(v) => {
640                                v.insert(BufferedSubset::singleton(row_id));
641                            }
642                        }
643                    }
644                }
645            });
646        });
647    }
648
649    /// Sort-based full rebuild: collect all (value, row_id) pairs, sort by (value, row_id),
650    /// then build each key's subset with a single pre-sized allocation. Compared to `merge_rows`,
651    /// this eliminates the doubling memmoves from `push_vec` that occur in the row-at-a-time `add_row` path.
652    ///
653    /// Supports multiple columns (e.g. rebuild_index covering all value columns): each value
654    /// maps to the union of rows containing it in any of the covered columns.
655    fn rebuild_full(&mut self, cols: &[ColumnId], table: WrappedTableRef, subset: SubsetRef) {
656        // Collect each column into its own contiguous block, still in RowId-ascending scan
657        // order. `bounds[b]..bounds[b + 1]` delimits column `b`'s block; the number of columns
658        // is tiny, so it stays inline.
659        let rows = subset.size();
660        let mut pairs: Pooled<Vec<(Value, RowId)>> = with_pool_set(|ps| ps.get());
661        pairs.reserve(rows * cols.len());
662        let mut bounds: SmallVec<[usize; 8]> = SmallVec::new();
663        bounds.push(0);
664        for &col in cols {
665            table.collect_col_pairs(subset, col, &mut pairs);
666            bounds.push(pairs.len());
667        }
668
669        // Value-only sort each block. Since each block arrives RowId-ascending and the sort is
670        // stable, the block ends up ordered by (Value, RowId) without any RowId pass.
671        let mut scratch: Pooled<Vec<(Value, RowId)>> = with_pool_set(|ps| ps.get());
672        scratch.resize(rows, (Value::new_const(0), RowId::new_const(0)));
673        for b in 0..cols.len() {
674            radix_sort_slice_by_value(&mut pairs[bounds[b]..bounds[b + 1]], &mut scratch);
675        }
676
677        if cols.len() == 1 {
678            // A single column needs no merge: its block is already (Value, RowId)-sorted, and a
679            // row has one value per column so there are no duplicates.
680            self.build_subsets_from_sorted(&pairs);
681            return;
682        }
683
684        // Multiple columns: merge the sorted blocks with a balanced (tournament) two-way merge.
685        // Each merge drops duplicate (Value, RowId) pairs -- a value appearing in several of a
686        // row's columns -- and dedup composes through the tree, so the result is
687        // (Value, RowId)-sorted and unique without ever sorting by RowId. Halving the number of
688        // runs each round makes this O(n log k) rather than the O(n*k) of a left fold (whose
689        // growing accumulator is re-copied every step), which matters for wide tables.
690        let merged = merge_sorted_blocks_dedup(pairs, &bounds);
691        self.build_subsets_from_sorted(&merged);
692    }
693}
694
695impl PositionedIndexBase for ColumnIndex {
696    fn get_subset_positioned<'a>(&'a self, key: &Value) -> Option<(IndexPosition, SubsetRef<'a>)> {
697        let mut hasher = FxHasher::default();
698        key.hash(&mut hasher);
699        let shard_id = self.shard_data.shard_id(hasher.finish());
700        let shard = &self.shards[shard_id];
701        let (slot, _, subset) = shard.table.get_full(key)?;
702        Some((
703            IndexPosition::new(shard_id, slot),
704            subset.as_ref(&shard.subsets),
705        ))
706    }
707
708    fn for_each_positioned<'a>(
709        &'a self,
710        mut f: impl FnMut(IndexPosition, &'a Value, SubsetRef<'a>),
711    ) {
712        for (shard_id, shard) in self.shards.iter() {
713            for (slot, (key, subset)) in shard.table.iter().enumerate() {
714                f(
715                    IndexPosition::new(shard_id, slot),
716                    key,
717                    subset.as_ref(&shard.subsets),
718                );
719            }
720        }
721    }
722
723    fn for_each_shard_positioned<'a>(
724        &'a self,
725        shard: usize,
726        mut f: impl FnMut(IndexPosition, &'a Value, SubsetRef<'a>),
727    ) {
728        let shard_id = ShardId::from_usize(shard);
729        let shard = &self.shards[shard_id];
730        for (slot, (key, subset)) in shard.table.iter().enumerate() {
731            f(
732                IndexPosition::new(shard_id, slot),
733                key,
734                subset.as_ref(&shard.subsets),
735            );
736        }
737    }
738}
739
740/// Stable value sorting for a block projected in RowId order.
741///
742/// `scratch` must hold at least `data.len()` pairs. Stability preserves RowId
743/// order within each key, including the per-column blocks used by rebuilds.
744pub(crate) fn radix_sort_slice_by_value(
745    data: &mut [(Value, RowId)],
746    scratch: &mut [(Value, RowId)],
747) {
748    radix_sort::sort(data, scratch);
749}
750
751/// Merge two (Value, RowId)-sorted slices, *appending* the result to `out` and dropping pairs
752/// equal to the previous one emitted *by this call*.
753///
754/// Inputs `a` and `b` must each be sorted by (Value, RowId). Duplicates arise when one value
755/// appears in several of a row's columns; the dedup check is scoped to this call's output (via
756/// `start`) so back-to-back runs packed into the same buffer are not merged into each other.
757fn merge2_into(a: &[(Value, RowId)], b: &[(Value, RowId)], out: &mut Vec<(Value, RowId)>) {
758    let start = out.len();
759    let push = |out: &mut Vec<(Value, RowId)>, next: (Value, RowId)| {
760        if out.len() == start || *out.last().unwrap() != next {
761            out.push(next);
762        }
763    };
764    let (mut i, mut j) = (0, 0);
765    while i < a.len() && j < b.len() {
766        if a[i] <= b[j] {
767            push(out, a[i]);
768            i += 1;
769        } else {
770            push(out, b[j]);
771            j += 1;
772        }
773    }
774    for &next in &a[i..] {
775        push(out, next);
776    }
777    for &next in &b[j..] {
778        push(out, next);
779    }
780}
781
782/// Merge the `(Value, RowId)`-sorted column blocks of `src` (block `b` is
783/// `src[bounds[b]..bounds[b + 1]]`) into one sorted, de-duplicated vector.
784///
785/// Uses a balanced (tournament) two-way merge: adjacent runs are merged pairwise, then the
786/// results are merged pairwise, halving the run count each round. This is O(n log k) in the
787/// number of blocks `k`, versus the O(n*k) of merging a single growing accumulator against
788/// each block in turn -- the difference matters when a table has many covered columns.
789///
790/// Each round packs its merged runs contiguously into a second buffer of the same size and the
791/// two buffers ping-pong, so the whole tournament uses just one extra allocation (`src` is
792/// reused as the other buffer) rather than a fresh `Vec` per merge. Because merging two
793/// de-duplicated sorted runs leaves any shared pair adjacent, dedup composes across rounds.
794fn merge_sorted_blocks_dedup(
795    mut src: Pooled<Vec<(Value, RowId)>>,
796    bounds: &[usize],
797) -> Pooled<Vec<(Value, RowId)>> {
798    let n = src.len();
799    debug_assert!(bounds.len() >= 2);
800
801    // `src` holds the current rounds's runs, delimited by `cur`; `dst` receives the merged runs.
802    let mut dst: Pooled<Vec<(Value, RowId)>> = with_pool_set(|ps| ps.get());
803    dst.reserve(n);
804    let mut cur: SmallVec<[usize; 8]> = bounds.iter().copied().collect();
805
806    // Each round more than halves the run count (`cur.len() - 1`); stop at a single run.
807    while cur.len() > 2 {
808        dst.clear();
809        let mut next: SmallVec<[usize; 8]> = SmallVec::new();
810        next.push(0);
811        let runs = cur.len() - 1;
812        let mut r = 0;
813        while r < runs {
814            if r + 1 < runs {
815                merge2_into(
816                    &src[cur[r]..cur[r + 1]],
817                    &src[cur[r + 1]..cur[r + 2]],
818                    &mut dst,
819                );
820                r += 2;
821            } else {
822                // Odd trailing run: already sorted and de-duplicated, so copy it forward.
823                dst.extend_from_slice(&src[cur[r]..cur[r + 1]]);
824                r += 1;
825            }
826            next.push(dst.len());
827        }
828        mem::swap(&mut src, &mut dst);
829        cur = next;
830    }
831
832    // One run remains, packed at the front of `src`.
833    src.truncate(cur[1]);
834    src
835}
836
837impl ColumnIndex {
838    pub(crate) fn new() -> ColumnIndex {
839        with_pool_set(|ps| {
840            let shard_data = ShardData::new(num_shards());
841            let mut shards = IdVec::with_capacity(shard_data.n_shards());
842            shards.resize_with(shard_data.n_shards(), || ColumnIndexShard {
843                table: ps.get(),
844                subsets: SubsetBuffer::default(),
845            });
846            ColumnIndex { shard_data, shards }
847        })
848    }
849
850    /// Build each key's subset from `pairs`, which must be sorted by (Value, RowId) and
851    /// free of duplicate (Value, RowId) entries. Each contiguous run of equal values
852    /// becomes one subset, pre-sized from the run length.
853    fn build_subsets_from_sorted(&mut self, pairs: &[(Value, RowId)]) {
854        let mut i = 0;
855        while i < pairs.len() {
856            let key = pairs[i].0;
857            let start = i;
858            while i < pairs.len() && pairs[i].0 == key {
859                i += 1;
860            }
861            let shard = self.shard_data.get_shard_mut(key, &mut self.shards);
862            let buffered = buffered_subset_from_sorted_pairs(&pairs[start..i], &mut shard.subsets);
863            shard.table.insert(key, buffered);
864        }
865    }
866}
867
868#[derive(Clone)]
869struct TupleIndexShard {
870    table: SubsetTable,
871    subsets: SubsetBuffer,
872}
873
874/// A mapping from keys to subsets of rows.
875#[derive(Clone)]
876pub struct TupleIndex {
877    // NB: we could store RowBuffers inline and then have indexes reference
878    // (u32, RowId) instead of RowId. Trades copying off for indirections.
879    shard_data: ShardData,
880    shards: IdVec<ShardId, TupleIndexShard>,
881}
882
883impl TupleIndex {
884    pub(crate) fn new(key_arity: usize) -> TupleIndex {
885        let shard_data = ShardData::new(num_shards());
886        let mut shards = IdVec::with_capacity(shard_data.n_shards());
887        shards.resize_with(shard_data.n_shards(), || TupleIndexShard {
888            table: SubsetTable::new(key_arity),
889            subsets: SubsetBuffer::default(),
890        });
891        TupleIndex { shard_data, shards }
892    }
893}
894
895impl IndexBase for TupleIndex {
896    type Key = [Value];
897    type WriteKey = Self::Key;
898
899    fn clear(&mut self) {
900        for (_, shard) in self.shards.iter_mut() {
901            shard.table.keys.clear();
902            for entry in shard.table.hash.drain() {
903                match entry.vals {
904                    BufferedSubset::Dense(_) => {}
905                    BufferedSubset::Sparse(v) => {
906                        shard.subsets.return_vec(v);
907                    }
908                }
909            }
910        }
911    }
912
913    fn get_subset<'a>(&'a self, key: &[Value]) -> Option<SubsetRef<'a>> {
914        let hash = hash_key(key);
915        let shard = &self.shards[self.shard_data.shard_id(hash)];
916        let entry = shard.table.hash.find(hash, |entry| {
917            // SAFETY: entry.key was stored by add_row, which returns a valid RowId.
918            entry.hash == hash && unsafe { shard.table.keys.get_row_unchecked(entry.key) } == key
919        })?;
920        Some(entry.vals.as_ref(&shard.subsets))
921    }
922
923    fn add_row(&mut self, key: &[Value], row: RowId) {
924        use hashbrown::hash_table::Entry;
925        let hash = hash_key(key);
926        let shard = &mut self.shards[self.shard_data.shard_id(hash)];
927        let table_entry = shard.table.hash.entry(
928            hash,
929            // SAFETY: entry.key was stored by add_row, which returns a valid RowId.
930            |entry| {
931                entry.hash == hash
932                    && unsafe { shard.table.keys.get_row_unchecked(entry.key) } == key
933            },
934            |ent| ent.hash,
935        );
936        match table_entry {
937            Entry::Occupied(mut occ) => {
938                // SAFETY: everything in `table_entry` comes from `vals`.
939                unsafe {
940                    occ.get_mut().vals.add_row_sorted(row, &mut shard.subsets);
941                }
942            }
943            Entry::Vacant(v) => {
944                let key_id = shard.table.keys.add_row(key);
945                let subset = BufferedSubset::singleton(row);
946                v.insert(TableEntry {
947                    hash,
948                    key: key_id,
949                    vals: subset,
950                });
951            }
952        }
953    }
954
955    fn merge_rows(&mut self, buf: &TaggedRowBuffer) {
956        for (src_id, key) in buf.iter() {
957            self.add_row(key, src_id);
958        }
959    }
960    fn shard_count(&self) -> usize {
961        self.shards.len()
962    }
963
964    fn shard_len(&self, shard: usize) -> usize {
965        self.shards[ShardId::from_usize(shard)].table.hash.len()
966    }
967
968    fn len(&self) -> usize {
969        self.shards
970            .iter()
971            .map(|(_, shard)| shard.table.hash.len())
972            .sum()
973    }
974
975    fn merge_parallel(&mut self, cols: &[ColumnId], table: WrappedTableRef, subset: SubsetRef) {
976        // The structure here is similar to the implementation for ColumnIndex, with
977        // slightly more bookkeeping needed to handle arbitrary-arity keys.
978
979        const BATCH_SIZE: usize = 1024;
980        let shard_data = self.shard_data;
981        let mut queues = IdVec::<ShardId, Mutex<Vec<(RowId, TaggedRowBuffer)>>>::with_capacity(
982            shard_data.n_shards(),
983        );
984        queues.resize_with(shard_data.n_shards(), || {
985            Mutex::new(Vec::with_capacity((subset.size() / BATCH_SIZE) + 1))
986        });
987        let split_buf = |buf: TaggedRowBuffer| {
988            let mut split = IdVec::<ShardId, TaggedRowBuffer>::default();
989            split.resize_with(shard_data.n_shards(), || TaggedRowBuffer::new(cols.len()));
990            for (row_id, key) in buf.iter() {
991                shard_data
992                    .get_shard_mut(key, &mut split)
993                    .add_row(row_id, key);
994            }
995            for (shard_id, buf) in split.drain() {
996                if buf.is_empty() {
997                    continue;
998                }
999                let first = buf.get_row(RowId::new(0)).0;
1000                queues[shard_id].lock().unwrap().push((first, buf));
1001            }
1002        };
1003        run_in_index_thread_pool(|| {
1004            egglog_concurrency::scope(|scope| {
1005                let mut cur = Offset::new(0);
1006                loop {
1007                    let mut buf = TaggedRowBuffer::new(cols.len());
1008                    if let Some(next) =
1009                        table.scan_project(subset, cols, cur, BATCH_SIZE, &[], &mut buf)
1010                    {
1011                        cur = next;
1012                        scope.spawn(move |_| split_buf(buf));
1013                    } else {
1014                        scope.spawn(move |_| split_buf(buf));
1015                        break;
1016                    }
1017                }
1018            });
1019            parallel::for_each_id_vec_mut(&mut self.shards, |shard_id, shard| {
1020                use hashbrown::hash_table::Entry;
1021                // Sort the vector by start row id to ensure we populate subsets in sorted order.
1022                let mut vec = queues[shard_id].lock().unwrap();
1023                vec.sort_by_key(|(start, _)| *start);
1024                for (_, buf) in vec.drain(..) {
1025                    for (row_id, key) in buf.iter() {
1026                        let hash = hash_key(key);
1027                        let table_entry = shard.table.hash.entry(
1028                            hash,
1029                            // SAFETY: entry.key was stored by add_row, which returns a valid RowId.
1030                            |entry| {
1031                                entry.hash == hash
1032                                    && unsafe { shard.table.keys.get_row_unchecked(entry.key) }
1033                                        == key
1034                            },
1035                            |ent| ent.hash,
1036                        );
1037                        match table_entry {
1038                            Entry::Occupied(mut occ) => {
1039                                // SAFETY: everything in `table_entry` comes from `vals`.
1040                                unsafe {
1041                                    occ.get_mut()
1042                                        .vals
1043                                        .add_row_sorted(row_id, &mut shard.subsets);
1044                                }
1045                            }
1046                            Entry::Vacant(v) => {
1047                                let key_id = shard.table.keys.add_row(key);
1048                                let subset = BufferedSubset::singleton(row_id);
1049                                v.insert(TableEntry {
1050                                    hash,
1051                                    key: key_id,
1052                                    vals: subset,
1053                                });
1054                            }
1055                        }
1056                    }
1057                }
1058            });
1059        });
1060    }
1061}
1062
1063impl PositionedIndexBase for TupleIndex {
1064    fn get_subset_positioned<'a>(
1065        &'a self,
1066        key: &[Value],
1067    ) -> Option<(IndexPosition, SubsetRef<'a>)> {
1068        let hash = hash_key(key);
1069        let shard_id = self.shard_data.shard_id(hash);
1070        let shard = &self.shards[shard_id];
1071        let entry = shard.table.hash.find(hash, |entry| {
1072            // SAFETY: entry.key was stored by add_row, which returns a valid RowId.
1073            entry.hash == hash && unsafe { shard.table.keys.get_row_unchecked(entry.key) } == key
1074        })?;
1075        Some((
1076            IndexPosition::new(shard_id, entry.key.index()),
1077            entry.vals.as_ref(&shard.subsets),
1078        ))
1079    }
1080
1081    fn for_each_positioned<'a>(
1082        &'a self,
1083        mut f: impl FnMut(IndexPosition, &'a [Value], SubsetRef<'a>),
1084    ) {
1085        for (shard_id, shard) in self.shards.iter() {
1086            for entry in shard.table.hash.iter() {
1087                // SAFETY: entry.key was stored by add_row, so it is always in-bounds.
1088                let key = unsafe { shard.table.keys.get_row_unchecked(entry.key) };
1089                f(
1090                    IndexPosition::new(shard_id, entry.key.index()),
1091                    key,
1092                    entry.vals.as_ref(&shard.subsets),
1093                );
1094            }
1095        }
1096    }
1097
1098    fn for_each_shard_positioned<'a>(
1099        &'a self,
1100        shard: usize,
1101        mut f: impl FnMut(IndexPosition, &'a [Value], SubsetRef<'a>),
1102    ) {
1103        let shard_id = ShardId::from_usize(shard);
1104        let shard = &self.shards[shard_id];
1105        for entry in shard.table.hash.iter() {
1106            // SAFETY: entry.key was stored by add_row, so it is always in-bounds.
1107            let key = unsafe { shard.table.keys.get_row_unchecked(entry.key) };
1108            f(
1109                IndexPosition::new(shard_id, entry.key.index()),
1110                key,
1111                entry.vals.as_ref(&shard.subsets),
1112            );
1113        }
1114    }
1115}
1116
1117fn hash_key(key: &[Value]) -> u64 {
1118    let mut hasher = FxHasher::default();
1119    key.hash(&mut hasher);
1120    hasher.finish()
1121}
1122
1123/// A map from access patterns to indices.
1124///
1125/// Implemented as an read-optimized key-value arrays, which should be faster
1126/// than concurrent hashmaps as long as # indices is smaller than say 64.
1127///
1128/// For simplicity we assume the index can be cloned cheaply, e.g., it's behind an [`Arc`].
1129#[derive(Default)]
1130pub struct IndexCatalog<K: Clone + std::hash::Hash + Eq, I: Clone> {
1131    data: ReadOptimizedLock<Vec<(K, I)>>,
1132    #[cfg(test)]
1133    get_or_insert_calls: AtomicUsize,
1134}
1135
1136impl<K, I: Clone> IndexCatalog<K, I>
1137where
1138    K: Clone + std::hash::Hash + Eq,
1139{
1140    pub fn new() -> Self {
1141        IndexCatalog {
1142            data: ReadOptimizedLock::new(Vec::new()),
1143            #[cfg(test)]
1144            get_or_insert_calls: AtomicUsize::new(0),
1145        }
1146    }
1147
1148    pub fn map(&self, f: impl Fn(&(K, I)) -> (K, I)) -> Self {
1149        let vec = self.data.read().iter().map(f).collect();
1150        IndexCatalog {
1151            data: ReadOptimizedLock::new(vec),
1152            #[cfg(test)]
1153            get_or_insert_calls: AtomicUsize::new(0),
1154        }
1155    }
1156
1157    pub fn update(&mut self, f: impl Fn(&K, &mut I)) {
1158        for (k, i) in self.data.as_mut_ref() {
1159            f(k, i)
1160        }
1161    }
1162
1163    pub fn get_or_insert(&self, k: K, init: impl FnOnce() -> I) -> I {
1164        #[cfg(test)]
1165        self.get_or_insert_calls.fetch_add(1, Ordering::Relaxed);
1166        let data = self.data.read();
1167        let entry = data.iter().find(|(k1, _)| k1 == &k);
1168        if let Some(entry) = entry {
1169            entry.1.clone()
1170        } else {
1171            drop(data);
1172            let mut data = self.data.lock();
1173            if let Some(entry) = data.iter().find(|(k1, _)| k1 == &k) {
1174                entry.1.clone()
1175            } else {
1176                let index = init();
1177                data.push((k, index.clone()));
1178                index
1179            }
1180        }
1181    }
1182
1183    #[cfg(test)]
1184    pub(crate) fn get_or_insert_calls(&self) -> usize {
1185        self.get_or_insert_calls.load(Ordering::Relaxed)
1186    }
1187}
1188
1189define_id!(BufferIndex, u32, "an index into a subset buffer");
1190
1191/// A shared pool of row ids used to store sorted offset vectors with a common
1192/// lifetime.
1193///
1194/// This is used as the backing store for subsets stored in indexes. While
1195/// definitely saves some allocations, the primary use for SubsetBuffer is to
1196/// make deallocation faster: with a standard [`crate::offsets::Subset`]
1197/// structure stored in the index, dropping requires an O(n) traversal of the
1198/// index. SubsetBuffer allows deallocation to happen in constant time (given
1199/// our use of memory pools).
1200struct SubsetBuffer {
1201    buf: Pooled<Vec<RowId>>,
1202    free_list: FreeList,
1203}
1204
1205impl Clone for SubsetBuffer {
1206    fn clone(&self) -> Self {
1207        SubsetBuffer {
1208            buf: Pooled::cloned(&self.buf),
1209            free_list: self.free_list.clone(),
1210        }
1211    }
1212}
1213
1214impl Default for SubsetBuffer {
1215    fn default() -> SubsetBuffer {
1216        with_pool_set(|ps| SubsetBuffer {
1217            buf: ps.get(),
1218            free_list: Default::default(),
1219        })
1220    }
1221}
1222
1223impl SubsetBuffer {
1224    fn new_vec(&mut self, rows: impl ExactSizeIterator<Item = RowId>) -> BufferedVec {
1225        let len = rows.len();
1226        if let Some(v) = self.free_list.get_size_class(len).pop() {
1227            return self.fill_at(v, rows);
1228        }
1229        let start = BufferIndex::from_usize(self.buf.len());
1230        self.buf.resize(
1231            start.index() + len.next_power_of_two(),
1232            RowId::new(u32::MAX),
1233        );
1234        self.fill_at(start, rows)
1235    }
1236
1237    fn fill_at(
1238        &mut self,
1239        start: BufferIndex,
1240        rows: impl ExactSizeIterator<Item = RowId>,
1241    ) -> BufferedVec {
1242        let mut cur = start;
1243        for i in rows {
1244            self.buf[cur.index()] = i;
1245            cur = cur.inc();
1246        }
1247        BufferedVec(start, cur)
1248    }
1249
1250    fn return_vec(&mut self, vec: BufferedVec) {
1251        self.free_list.get_size_class(vec.len()).push(vec.0);
1252    }
1253
1254    fn push_vec(&mut self, vec: BufferedVec, row: RowId) -> BufferedVec {
1255        debug_assert!(
1256            vec.is_empty() || self.buf[vec.1.index() - 1] <= row,
1257            "vec={vec:?}, row={row:?}, last_elt={:?}",
1258            self.buf[vec.1.index() - 1]
1259        );
1260        if !vec.len().is_power_of_two() {
1261            self.buf[vec.1.index()] = row;
1262            return BufferedVec(vec.0, vec.1.inc());
1263        }
1264
1265        let res = if let Some(v) = self.free_list.get_size_class(vec.len() + 1).pop() {
1266            self.buf
1267                .copy_within(vec.0.index()..vec.1.index(), v.index());
1268            self.buf[v.index() + vec.len()] = row;
1269            BufferedVec(v, BufferIndex::from_usize(v.index() + vec.len() + 1))
1270        } else {
1271            let start = self.buf.len();
1272            self.buf.resize(
1273                start + (vec.len() + 1).next_power_of_two(),
1274                RowId::new(u32::MAX),
1275            );
1276            self.buf.copy_within(vec.0.index()..vec.1.index(), start);
1277            self.buf[start + vec.len()] = row;
1278            let end = start + vec.len() + 1;
1279            BufferedVec(BufferIndex::from_usize(start), BufferIndex::from_usize(end))
1280        };
1281        self.return_vec(vec);
1282        res
1283    }
1284
1285    fn extend_vec(
1286        &mut self,
1287        vec: BufferedVec,
1288        rows: impl ExactSizeIterator<Item = RowId>,
1289    ) -> BufferedVec {
1290        let old_len = vec.len();
1291        let added = rows.len();
1292        if added == 0 {
1293            return vec;
1294        }
1295        let new_len = old_len + added;
1296        let old_capacity = old_len.next_power_of_two();
1297        if new_len <= old_capacity {
1298            let mut end = vec.1;
1299            for row in rows {
1300                self.buf[end.index()] = row;
1301                end = end.inc();
1302            }
1303            return BufferedVec(vec.0, end);
1304        }
1305
1306        let start = if let Some(start) = self.free_list.get_size_class(new_len).pop() {
1307            start
1308        } else {
1309            let start = BufferIndex::from_usize(self.buf.len());
1310            self.buf.resize(
1311                start.index() + new_len.next_power_of_two(),
1312                RowId::new(u32::MAX),
1313            );
1314            start
1315        };
1316        self.buf
1317            .copy_within(vec.0.index()..vec.1.index(), start.index());
1318        let mut end = BufferIndex::from_usize(start.index() + old_len);
1319        for row in rows {
1320            self.buf[end.index()] = row;
1321            end = end.inc();
1322        }
1323        self.return_vec(vec);
1324        BufferedVec(start, end)
1325    }
1326
1327    fn make_ref<'a>(&'a self, vec: &BufferedVec) -> SubsetRef<'a> {
1328        // SAFETY: if `vec` is a valid index into self.buf, it will be sorted.
1329        //
1330        // NB: we do not guarantee this in the type signature of BufferedVec,
1331        // etc. But this is indeed safe given the usage within this module.
1332        let res = SubsetRef::Sparse(unsafe {
1333            SortedOffsetSlice::new_unchecked(&self.buf[vec.0.index()..vec.1.index()])
1334        });
1335        #[cfg(debug_assertions)]
1336        {
1337            use crate::offsets::Offsets;
1338            res.offsets(|x| assert_ne!(x.rep(), u32::MAX))
1339        }
1340        res
1341    }
1342}
1343
1344/// A sorted vector of offsets stored in a [`SubsetBuffer`].
1345///
1346/// Note: this implements `Clone` to facilitate cloning entire indexes, but this is a _shallow_
1347/// clone, making the clone operation work akin to slices in Golang. In particular: code that
1348/// pushes to a clone of a `BufferedVec` can affect the original, and vice versa.
1349///
1350/// Business logic in this module probably shouldn't call clone explicitly. The implicit uses of
1351/// clone (by other generated `Clone` implementations) are fine because they clone the
1352/// `SubsetBuffer` that the `BufferedVec` points to at the same time that the vector is cloned.
1353#[derive(Debug, Clone)]
1354pub(crate) struct BufferedVec(BufferIndex, BufferIndex);
1355
1356impl Default for BufferedVec {
1357    fn default() -> Self {
1358        BufferedVec(BufferIndex::new(0), BufferIndex::new(0))
1359    }
1360}
1361
1362impl BufferedVec {
1363    fn is_empty(&self) -> bool {
1364        self.0 == self.1
1365    }
1366    fn len(&self) -> usize {
1367        self.1.index() - self.0.index()
1368    }
1369}
1370
1371#[derive(Clone)]
1372pub(crate) enum BufferedSubset {
1373    Dense(OffsetRange),
1374    Sparse(BufferedVec),
1375}
1376
1377impl BufferedSubset {
1378    /// *Safety:*  callers must ensure that `self` is either dense, or comes from `buf`.
1379    unsafe fn add_row_sorted(&mut self, row: RowId, buf: &mut SubsetBuffer) {
1380        match self {
1381            BufferedSubset::Dense(range) => {
1382                if range.end == range.start {
1383                    range.start = row;
1384                    range.end = row.inc();
1385                    return;
1386                }
1387                if range.end == row {
1388                    range.end = row.inc();
1389                    return;
1390                }
1391                let mut v = buf.new_vec((range.start.rep()..range.end.rep()).map(RowId::new));
1392                v = buf.push_vec(v, row);
1393                *self = BufferedSubset::Sparse(v);
1394            }
1395            BufferedSubset::Sparse(vec) => *vec = buf.push_vec(mem::take(vec), row),
1396        }
1397    }
1398
1399    /// Merge one nonempty `(Value, RowId)` run whose rows are strictly sorted
1400    /// and newer than every row already in this subset.
1401    ///
1402    /// *Safety:* callers must ensure that `self` is either dense or comes from
1403    /// `buf`, and that the ordering preconditions above hold.
1404    unsafe fn merge_sorted_pairs(&mut self, pairs: &[(Value, RowId)], buf: &mut SubsetBuffer) {
1405        debug_assert!(!pairs.is_empty());
1406        debug_assert!(
1407            pairs
1408                .windows(2)
1409                .all(|pair| { pair[0].0 == pair[1].0 && pair[0].1 < pair[1].1 })
1410        );
1411        let first = pairs[0].1;
1412        let last = pairs[pairs.len() - 1].1;
1413        let incoming_is_dense = last.rep() - first.rep() == u32::try_from(pairs.len() - 1).unwrap();
1414
1415        match self {
1416            BufferedSubset::Dense(range) if range.start == range.end => {
1417                *self = buffered_subset_from_sorted_pairs(pairs, buf);
1418            }
1419            BufferedSubset::Dense(range) => {
1420                debug_assert!(range.end <= first);
1421                if range.end == first && incoming_is_dense {
1422                    range.end = last.inc();
1423                } else {
1424                    let old_start = range.start.rep();
1425                    let old_len = range.end.index() - range.start.index();
1426                    let rows = (0..old_len + pairs.len()).map(|i| {
1427                        if i < old_len {
1428                            RowId::new(old_start + u32::try_from(i).unwrap())
1429                        } else {
1430                            pairs[i - old_len].1
1431                        }
1432                    });
1433                    *self = BufferedSubset::Sparse(buf.new_vec(rows));
1434                }
1435            }
1436            BufferedSubset::Sparse(vec) => {
1437                debug_assert!(buf.buf[vec.1.index() - 1] < first);
1438                *vec = buf.extend_vec(mem::take(vec), pairs.iter().map(|&(_, row)| row));
1439            }
1440        }
1441    }
1442
1443    fn empty() -> Self {
1444        BufferedSubset::Dense(OffsetRange::new(RowId::new(0), RowId::new(0)))
1445    }
1446
1447    fn singleton(row: RowId) -> Self {
1448        BufferedSubset::Dense(OffsetRange::new(row, row.inc()))
1449    }
1450
1451    fn as_ref<'a>(&self, buf: &'a SubsetBuffer) -> SubsetRef<'a> {
1452        match self {
1453            BufferedSubset::Dense(range) => SubsetRef::Dense(*range),
1454            BufferedSubset::Sparse(vec) => buf.make_ref(vec),
1455        }
1456    }
1457}
1458
1459fn buffered_subset_from_sorted_pairs(
1460    pairs: &[(Value, RowId)],
1461    buf: &mut SubsetBuffer,
1462) -> BufferedSubset {
1463    debug_assert!(!pairs.is_empty());
1464    debug_assert!(
1465        pairs
1466            .windows(2)
1467            .all(|pair| { pair[0].0 == pair[1].0 && pair[0].1 < pair[1].1 })
1468    );
1469    let first = pairs[0].1;
1470    let last = pairs[pairs.len() - 1].1;
1471    if last.rep() - first.rep() == u32::try_from(pairs.len() - 1).unwrap() {
1472        BufferedSubset::Dense(OffsetRange::new(first, last.inc()))
1473    } else {
1474        BufferedSubset::Sparse(buf.new_vec(pairs.iter().map(|&(_, row)| row)))
1475    }
1476}
1477
1478fn num_shards() -> usize {
1479    let n_threads = parallel::current_num_threads();
1480    if n_threads == 1 { 1 } else { n_threads * 2 }
1481}
1482
1483/// A thread pool specifically for parallel hash index construction.
1484///
1485/// Callers can construct indexes while holding database-level index locks. The
1486/// separate pool preserves parallelism without tying up the caller's installed
1487/// pool behind those locks.
1488static INDEX_THREAD_POOL: Lazy<ThreadPool> =
1489    Lazy::new(|| ThreadPool::new(parallel::current_num_threads().max(1)));
1490
1491fn run_in_index_thread_pool<R>(f: impl FnOnce() -> R) -> R {
1492    INDEX_THREAD_POOL.install(f)
1493}
1494
1495/// A simple free list used to reuse slots in a [`SubsetBuffer`].
1496///
1497/// This free list works as a map from power-of-two size classes to a vector of offsets that point
1498/// to the beginning of an unused vector.
1499///
1500/// Size classes are indexed by their log2 value (i.e., size_class = 2^idx), so a 32-entry
1501/// array covers all power-of-two sizes from 1 (idx=0) up to 2^31. This replaces the
1502/// previous HashMap with an O(1) array index + trailing_zeros().
1503#[derive(Clone, Default)]
1504pub(super) struct FreeList {
1505    data: [Vec<BufferIndex>; 32],
1506}
1507
1508impl FreeList {
1509    fn get_size_class(&mut self, size: usize) -> &mut Vec<BufferIndex> {
1510        let size_class = size.next_power_of_two();
1511        let idx = size_class.trailing_zeros() as usize;
1512        &mut self.data[idx]
1513    }
1514}