egglog_core_relations/table/
mod.rs

1//! A generic table implementation supporting sorted writes.
2//!
3//! The primary difference between this table and the `Function` implementation
4//! in egglog is that high level concepts like "timestamp" and "merge function"
5//! are abstracted away from the core functionality of the table.
6
7use std::{
8    any::Any,
9    cmp,
10    hash::Hasher,
11    mem,
12    sync::{
13        Arc, Weak,
14        atomic::{AtomicUsize, Ordering},
15    },
16};
17
18use crate::numeric_id::{DenseIdMap, NumericId};
19use crossbeam_queue::SegQueue;
20use hashbrown::HashTable;
21use rustc_hash::FxHasher;
22use sharded_hash_table::ShardedHashTable;
23
24use crate::{
25    Pooled, TableChange, TableId,
26    action::ExecutionState,
27    common::{ShardData, ShardId, SubsetTracker, Value},
28    hash_index::{ColumnIndex, Index},
29    offsets::{OffsetRange, Offsets, RowId, SortedOffsetVector, Subset, SubsetRef},
30    parallel,
31    parallel_heuristics::parallelize_table_op,
32    pool::with_pool_set,
33    row_buffer::{ParallelRowBufWriter, RowBuffer},
34    table_spec::{
35        ColumnId, Constraint, Generation, MutationBuffer, Offset, Row, Table, TableSpec,
36        TableVersion,
37    },
38};
39
40mod rebuild;
41mod sharded_hash_table;
42#[cfg(test)]
43mod tests;
44
45const PARALLEL_INSERT_BATCH_SIZE: usize = 1 << 12;
46
47/// The complete hash used to choose a physical shard.
48///
49/// Only this representation may be passed to [`ShardData::shard_id`]. The
50/// compact hash deliberately omits the shard-selection bits.
51#[derive(Clone, Copy, Debug, Eq, PartialEq)]
52#[repr(transparent)]
53struct FullHash(u64);
54
55/// The 32-bit hash fingerprint cached beside rows and table entries.
56///
57/// Bits 0..25 preserve the full hash's low bucket-index bits, while bits
58/// 25..32 preserve hashbrown's exact seven-bit H2 tag from the top of the
59/// target's effective hash word.
60#[derive(Clone, Copy, Debug, Eq, PartialEq)]
61#[repr(transparent)]
62struct CompactHash(u32);
63
64impl CompactHash {
65    const LOW_BITS: u32 = 25;
66    const LOW_MASK: u64 = (1 << Self::LOW_BITS) - 1;
67    const H2_BITS: u32 = 7;
68    const H2_MASK: u64 = (1 << Self::H2_BITS) - 1;
69    const H2_SHIFT: u32 = if usize::BITS < u64::BITS {
70        usize::BITS - Self::H2_BITS
71    } else {
72        u64::BITS - Self::H2_BITS
73    };
74
75    #[inline]
76    fn from_full(full: FullHash) -> Self {
77        let low = full.0 & Self::LOW_MASK;
78        let h2 = (full.0 >> Self::H2_SHIFT) & Self::H2_MASK;
79        Self((low | (h2 << Self::LOW_BITS)) as u32)
80    }
81
82    #[inline]
83    fn from_value(value: Value) -> Self {
84        Self(value.rep())
85    }
86
87    #[inline]
88    fn as_value(self) -> Value {
89        Value::new(self.0)
90    }
91
92    #[inline]
93    fn probe(self) -> ProbeHash {
94        let low = self.0 as u64;
95        let h2 = low >> Self::LOW_BITS;
96        ProbeHash(low | (h2 << Self::H2_SHIFT))
97    }
98}
99
100/// A reconstructed 64-bit hash used only at hashbrown's raw API boundary.
101///
102/// This has the cached low bucket bits and exact H2 tag, but it does not
103/// contain the bits needed to recover a physical shard.
104#[derive(Clone, Copy, Debug, Eq, PartialEq)]
105#[repr(transparent)]
106struct ProbeHash(u64);
107
108impl ProbeHash {
109    #[inline]
110    fn raw(self) -> u64 {
111        self.0
112    }
113}
114
115/// The two independent products of hashing a row.
116///
117/// `shard` is computed from the full hash before compaction. `compact` is the
118/// fingerprint cached after the row has already been routed to that shard.
119#[derive(Clone, Copy, Debug, Eq, PartialEq)]
120struct ShardHash {
121    shard: ShardId,
122    compact: CompactHash,
123}
124
125impl ShardHash {
126    #[inline]
127    fn from_full(shard_data: ShardData, full: FullHash) -> Self {
128        Self {
129            shard: shard_data.shard_id(full.0),
130            compact: CompactHash::from_full(full),
131        }
132    }
133}
134
135/// A pointer to a row in the table.
136#[derive(Clone, Debug)]
137#[repr(C)]
138pub(crate) struct TableEntry {
139    hash: CompactHash,
140    row: RowId,
141}
142
143impl TableEntry {
144    /// Adapter for hashbrown callbacks, which require the raw `u64`.
145    fn raw_probe_hash(&self) -> u64 {
146        self.hash.probe().raw()
147    }
148}
149
150/// Producer-local rows for one physical hash-table shard.
151///
152/// This preserves producer order and performs no seal/scatter step. A compact
153/// hash is stored as a trailing `Value` in each physical row, matching
154/// `TaggedRowBuffer`'s one-allocation layout.
155#[derive(Clone)]
156struct HashedRowBuffer {
157    arity: usize,
158    values: Vec<Value>,
159}
160
161impl HashedRowBuffer {
162    fn new(arity: usize) -> Self {
163        Self {
164            arity,
165            values: Vec::new(),
166        }
167    }
168
169    fn add_row(&mut self, hash: CompactHash, row: &[Value]) {
170        assert_eq!(row.len(), self.arity);
171        self.values.extend_from_slice(row);
172        self.values.push(hash.as_value());
173    }
174
175    fn len(&self) -> usize {
176        self.values.len() / (self.arity + 1)
177    }
178
179    fn rows_hashed(&self) -> impl Iterator<Item = (CompactHash, &[Value])> {
180        debug_assert_eq!(self.values.len() % (self.arity + 1), 0);
181        self.values.chunks_exact(self.arity + 1).map(|tagged| {
182            let hash = CompactHash::from_value(tagged[self.arity]);
183            (hash, &tagged[..self.arity])
184        })
185    }
186}
187
188#[derive(Clone, Copy, Debug)]
189#[repr(C)]
190struct KnownRemoval {
191    hash: CompactHash,
192    row: RowId,
193}
194
195/// The core data for a table.
196///
197/// This type is a thin wrapper around `RowBuffer`. The big difference is that
198/// it keeps track of how many stale rows are present.
199#[derive(Clone)]
200struct Rows {
201    data: RowBuffer,
202    scratch: RowBuffer,
203    stale_rows: usize,
204}
205
206impl Rows {
207    fn new(data: RowBuffer) -> Rows {
208        let arity = data.arity();
209        Rows {
210            data,
211            scratch: RowBuffer::new(arity),
212            stale_rows: 0,
213        }
214    }
215    fn clear(&mut self) {
216        self.data.clear();
217        self.stale_rows = 0;
218    }
219    fn next_row(&self) -> RowId {
220        RowId::from_usize(self.data.len())
221    }
222    fn set_stale(&mut self, row: RowId) {
223        if !self.data.set_stale(row) {
224            self.stale_rows += 1;
225        }
226    }
227
228    fn get_row(&self, row: RowId) -> Option<&[Value]> {
229        let row = self.data.get_row(row);
230        if row[0].is_stale() { None } else { Some(row) }
231    }
232
233    /// A variant of `get_row` without bounds-checking on `row`.
234    unsafe fn get_row_unchecked(&self, row: RowId) -> Option<&[Value]> {
235        let row = unsafe { self.data.get_row_unchecked(row) };
236        if row[0].is_stale() { None } else { Some(row) }
237    }
238
239    fn add_row(&mut self, row: &[Value]) -> RowId {
240        if row[0].is_stale() {
241            self.stale_rows += 1;
242        }
243        self.data.add_row(row)
244    }
245
246    fn remove_stale(&mut self, remap: impl FnMut(&[Value], RowId, RowId)) {
247        self.data.remove_stale(remap);
248        self.stale_rows = 0;
249    }
250}
251
252/// The type of closures that are used to merge values in a [`SortedWritesTable`].
253///
254/// The first argument grants access to database using an [`ExecutionState`], the second argument
255/// is the current value of the tuple. The third argument is the new, or "incoming" value of the
256/// tuple. The fourth argument is a mutable reference to a vector that will be used to store the
257/// output of the merge function _if_ it changes the value of the tuple. If it does not, then the
258/// merge function should return `false`.
259pub type MergeFn =
260    dyn Fn(&mut ExecutionState, &[Value], &[Value], &mut Vec<Value>) -> bool + Send + Sync;
261
262pub struct SortedWritesTable {
263    generation: Generation,
264    data: Rows,
265    hash: ShardedHashTable<TableEntry>,
266
267    n_keys: usize,
268    n_columns: usize,
269    sort_by: ColumnId,
270    offsets: Vec<(Value, RowId)>,
271
272    pending_state: Arc<PendingState>,
273    merge: Arc<MergeFn>,
274    to_rebuild: Vec<ColumnId>,
275    rebuild_index: Index<ColumnIndex>,
276    // Used to manage incremental rebuilds.
277    subset_tracker: SubsetTracker,
278    // Full-scan work spent on sparse updates while `rebuild_index` was stale.
279    full_scan_credit: usize,
280}
281
282impl Clone for SortedWritesTable {
283    fn clone(&self) -> SortedWritesTable {
284        SortedWritesTable {
285            generation: self.generation,
286            data: self.data.clone(),
287            hash: self.hash.clone(),
288            n_keys: self.n_keys,
289            n_columns: self.n_columns,
290            sort_by: self.sort_by,
291            offsets: self.offsets.clone(),
292            pending_state: Arc::new(self.pending_state.deep_copy()),
293            merge: self.merge.clone(),
294            to_rebuild: self.to_rebuild.clone(),
295            rebuild_index: Index::new(self.to_rebuild.clone(), ColumnIndex::new()),
296            subset_tracker: Default::default(),
297            full_scan_credit: 0,
298        }
299    }
300}
301
302struct Buffer {
303    pending_rows: DenseIdMap<ShardId, HashedRowBuffer>,
304    pending_removals: DenseIdMap<ShardId, HashedRowBuffer>,
305    /// Removals whose row ID was already found during rebuilding, grouped by
306    /// physical shard. Carrying the compact hash and row ID avoids a second
307    /// key lookup; deletion still checks the row ID so a newer row survives.
308    pending_known_removals: DenseIdMap<ShardId, Vec<KnownRemoval>>,
309    state: Weak<PendingState>,
310    n_cols: u32,
311    n_keys: u32,
312    shard_data: ShardData,
313}
314
315impl MutationBuffer for Buffer {
316    fn stage_insert(&mut self, row: &[Value]) {
317        let hash = shard_hash(self.shard_data, row, self.n_keys as _);
318        self.pending_rows
319            .get_or_insert(hash.shard, || HashedRowBuffer::new(self.n_cols as _))
320            .add_row(hash.compact, row);
321    }
322    fn stage_remove(&mut self, key: &[Value]) {
323        let hash = shard_hash(self.shard_data, key, self.n_keys as _);
324        self.pending_removals
325            .get_or_insert(hash.shard, || HashedRowBuffer::new(self.n_keys as _))
326            .add_row(hash.compact, key);
327    }
328    fn fresh_handle(&self) -> Box<dyn MutationBuffer> {
329        Box::new(Buffer {
330            pending_rows: DenseIdMap::with_capacity(self.shard_data.n_shards()),
331            pending_removals: DenseIdMap::with_capacity(self.shard_data.n_shards()),
332            pending_known_removals: DenseIdMap::with_capacity(self.shard_data.n_shards()),
333            state: self.state.clone(),
334            n_cols: self.n_cols,
335            n_keys: self.n_keys,
336            shard_data: self.shard_data,
337        })
338    }
339}
340
341impl Buffer {
342    fn stage_remove_row(&mut self, row: RowId, key: &[Value]) {
343        let hash = shard_hash(self.shard_data, key, self.n_keys as _);
344        self.pending_known_removals
345            .get_or_insert(hash.shard, Vec::new)
346            .push(KnownRemoval {
347                hash: hash.compact,
348                row,
349            });
350    }
351}
352
353impl Drop for Buffer {
354    fn drop(&mut self) {
355        if let Some(state) = self.state.upgrade() {
356            let mut rows = 0;
357            for shard_index in 0..self.pending_rows.n_ids() {
358                let shard = ShardId::from_usize(shard_index);
359                if let Some(buffer) = self.pending_rows.take(shard) {
360                    rows += buffer.len();
361                    state.pending_rows[shard].push(buffer);
362                }
363            }
364            state.total_rows.fetch_add(rows, Ordering::Relaxed);
365
366            let mut removals = 0;
367            for shard_index in 0..self.pending_removals.n_ids() {
368                let shard = ShardId::from_usize(shard_index);
369                if let Some(buffer) = self.pending_removals.take(shard) {
370                    removals += buffer.len();
371                    state.pending_removals[shard].push(buffer);
372                }
373            }
374            for shard_index in 0..self.pending_known_removals.n_ids() {
375                let shard = ShardId::from_usize(shard_index);
376                if let Some(buffer) = self.pending_known_removals.take(shard) {
377                    removals += buffer.len();
378                    state.pending_known_removals[shard].push(buffer);
379                }
380            }
381            state.total_removals.fetch_add(removals, Ordering::Relaxed);
382        }
383    }
384}
385
386impl Table for SortedWritesTable {
387    fn dyn_clone(&self) -> Box<dyn Table> {
388        Box::new(self.clone())
389    }
390    fn as_any(&self) -> &dyn Any {
391        self
392    }
393    fn clear(&mut self) {
394        self.pending_state.clear();
395        self.full_scan_credit = 0;
396        if self.data.data.len() == 0 {
397            return;
398        }
399        self.offsets.clear();
400        self.data.clear();
401        self.hash.clear();
402        self.generation = Generation::from_usize(self.version().major.index() + 1);
403    }
404
405    fn spec(&self) -> TableSpec {
406        TableSpec {
407            n_keys: self.n_keys,
408            n_vals: self.n_columns - self.n_keys,
409            uncacheable_columns: Default::default(),
410        }
411    }
412
413    fn apply_rebuild(
414        &mut self,
415        table_id: TableId,
416        table: &crate::WrappedTable,
417        next_ts: Value,
418        exec_state: &mut ExecutionState,
419    ) -> bool {
420        self.do_rebuild(table_id, table, next_ts, exec_state)
421    }
422
423    fn refresh_rows_for_values(&mut self, dirty_ids: &[Value], next_ts: Value) -> bool {
424        SortedWritesTable::refresh_rows_for_values(self, dirty_ids, next_ts)
425    }
426
427    fn version(&self) -> TableVersion {
428        TableVersion {
429            major: self.generation,
430            minor: Offset::from_usize(self.data.next_row().index()),
431        }
432    }
433
434    fn updates_since(&self, offset: Offset) -> Subset {
435        Subset::Dense(OffsetRange::new(
436            RowId::from_usize(offset.index()),
437            self.data.next_row(),
438        ))
439    }
440
441    fn all(&self) -> Subset {
442        Subset::Dense(OffsetRange::new(RowId::new(0), self.data.next_row()))
443    }
444
445    fn has_stale_rows(&self) -> bool {
446        self.data.stale_rows > 0
447    }
448
449    fn len(&self) -> usize {
450        self.data.data.len() - self.data.stale_rows
451    }
452
453    fn scan_generic(&self, subset: SubsetRef, mut f: impl FnMut(RowId, &[Value]))
454    where
455        Self: Sized,
456    {
457        let Some((_low, hi)) = subset.bounds() else {
458            // Empty subset
459            return;
460        };
461        assert!(
462            hi.index() <= self.data.data.len(),
463            "{} vs. {}",
464            hi.index(),
465            self.data.data.len()
466        );
467        if self.data.stale_rows == 0 {
468            // Fast path: no stale rows, skip is_stale check per row.
469            // SAFETY: subsets are sorted, low must be at most hi, and hi is less
470            // than the length of the table.
471            // TODO: provide a safe API for this `get_row_unchecked` usage since we have
472            // checked the full bounds above.
473            subset.offsets(|row| unsafe { f(row, self.data.data.get_row_unchecked(row)) })
474        } else {
475            // SAFETY: same as above.
476            subset.offsets(|row| unsafe {
477                if let Some(vals) = self.data.get_row_unchecked(row) {
478                    f(row, vals)
479                }
480            })
481        }
482    }
483
484    /// Stale rows are skipped, constrained or not, so a caller need not filter
485    /// them back out of the rows it receives. `tests/repro-stale-rows.egg`
486    /// guards the constrained path.
487    fn scan_generic_bounded(
488        &self,
489        subset: SubsetRef,
490        start: Offset,
491        n: usize,
492        cs: &[Constraint],
493        mut f: impl FnMut(RowId, &[Value]),
494    ) -> Option<Offset>
495    where
496        Self: Sized,
497    {
498        let Some((_low, hi)) = subset.bounds() else {
499            // Empty subset
500            return None;
501        };
502        assert!(
503            hi.index() <= self.data.data.len(),
504            "{} vs. {}",
505            hi.index(),
506            self.data.data.len()
507        );
508        if cs.is_empty() {
509            if self.data.stale_rows == 0 {
510                // Fast path: no stale rows, skip bounds check and is_stale check.
511                // SAFETY: all row IDs are in-bounds.
512                subset
513                    .iter_bounded(start.index(), start.index() + n, |row| {
514                        let entry = unsafe { self.data.data.get_row_unchecked(row) };
515                        f(row, entry);
516                    })
517                    .map(Offset::from_usize)
518            } else {
519                subset
520                    .iter_bounded(start.index(), start.index() + n, |row| {
521                        // SAFETY: all row IDs are in-bounds.
522                        let Some(entry) = (unsafe { self.data.get_row_unchecked(row) }) else {
523                            return;
524                        };
525                        f(row, entry);
526                    })
527                    .map(Offset::from_usize)
528            }
529        } else {
530            subset
531                .iter_bounded(start.index(), start.index() + n, |row| {
532                    // SAFETY: all row IDs are in-bounds.
533                    let Some(entry) = (unsafe { self.get_if_unchecked(cs, row) }) else {
534                        return;
535                    };
536                    f(row, entry);
537                })
538                .map(Offset::from_usize)
539        }
540    }
541
542    fn fast_subset(&self, constraint: &Constraint) -> Option<Subset> {
543        let sort_by = self.sort_by;
544        match constraint {
545            Constraint::Eq { .. } => None,
546            Constraint::EqConst { col, val } => {
547                if col == &sort_by {
548                    match self.binary_search_sort_val(*val) {
549                        Ok((found, bound)) => Some(Subset::Dense(OffsetRange::new(found, bound))),
550                        Err(_) => Some(Subset::empty()),
551                    }
552                } else {
553                    None
554                }
555            }
556            Constraint::LtConst { col, val } => {
557                if col == &sort_by {
558                    match self.binary_search_sort_val(*val) {
559                        Ok((found, _)) => {
560                            Some(Subset::Dense(OffsetRange::new(RowId::new(0), found)))
561                        }
562                        Err(next) => Some(Subset::Dense(OffsetRange::new(RowId::new(0), next))),
563                    }
564                } else {
565                    None
566                }
567            }
568            Constraint::GtConst { col, val } => {
569                if col == &sort_by {
570                    match self.binary_search_sort_val(*val) {
571                        Ok((_, bound)) => {
572                            Some(Subset::Dense(OffsetRange::new(bound, self.data.next_row())))
573                        }
574                        Err(next) => {
575                            Some(Subset::Dense(OffsetRange::new(next, self.data.next_row())))
576                        }
577                    }
578                } else {
579                    None
580                }
581            }
582            Constraint::LeConst { col, val } => {
583                if col == &sort_by {
584                    match self.binary_search_sort_val(*val) {
585                        Ok((_, bound)) => {
586                            Some(Subset::Dense(OffsetRange::new(RowId::new(0), bound)))
587                        }
588                        Err(next) => Some(Subset::Dense(OffsetRange::new(RowId::new(0), next))),
589                    }
590                } else {
591                    None
592                }
593            }
594            Constraint::GeConst { col, val } => {
595                if col == &sort_by {
596                    match self.binary_search_sort_val(*val) {
597                        Ok((found, _)) => {
598                            Some(Subset::Dense(OffsetRange::new(found, self.data.next_row())))
599                        }
600                        Err(next) => {
601                            Some(Subset::Dense(OffsetRange::new(next, self.data.next_row())))
602                        }
603                    }
604                } else {
605                    None
606                }
607            }
608        }
609    }
610
611    fn refine_one(&self, mut subset: Subset, c: &Constraint) -> Subset {
612        // NB: we aren't using any of the `fast_subset` tricks here. We may want
613        // to if the higher-level implementations end up using it directly.
614        subset.retain(|row| self.eval(std::slice::from_ref(c), row));
615        subset
616    }
617
618    fn refine_ref(&self, subset: SubsetRef, cs: &[Constraint], _check_live: bool) -> Subset {
619        // Single fused pass: `eval` reads each row once, checking liveness
620        // (`get_row` skips stale rows) and all constraints together. A dense
621        // input whose rows all survive stays dense.
622        let n = subset.size();
623        let mut vec: Pooled<SortedOffsetVector> = with_pool_set(|ps| ps.get());
624        subset.offsets(|row| {
625            if self.eval(cs, row) {
626                // SAFETY: `offsets` visits rows in ascending order.
627                unsafe { vec.push_unchecked(row) }
628            }
629        });
630        if let SubsetRef::Dense(range) = subset
631            && vec.slice().inner().len() == n
632        {
633            return Subset::Dense(range);
634        }
635        Subset::Sparse(vec)
636    }
637
638    fn contains_match(&self, subset: SubsetRef, cs: &[Constraint]) -> bool {
639        // `eval` rejects stale rows, so this is a short-circuiting
640        // `refine_ref(subset, cs, true).is_empty()`.
641        match subset {
642            SubsetRef::Dense(range) => (range.start.index()..range.end.index())
643                .any(|row| self.eval(cs, RowId::from_usize(row))),
644            SubsetRef::Sparse(rows) => rows.iter().any(|row| self.eval(cs, row)),
645        }
646    }
647
648    fn new_buffer(&self) -> Box<dyn MutationBuffer> {
649        Box::new(self.new_table_buffer())
650    }
651
652    fn merge(&mut self, exec_state: &mut ExecutionState) -> TableChange {
653        self.do_delete();
654        let added = self.do_insert(exec_state);
655        self.maybe_rehash();
656        TableChange { added }
657    }
658
659    fn get_row(&self, key: &[Value]) -> Option<Row> {
660        let id = get_entry(key, self.n_keys, &self.hash, |row| {
661            &self.data.get_row(row).unwrap()[0..self.n_keys] == key
662        })?;
663        let mut vals = with_pool_set(|ps| ps.get::<Vec<Value>>());
664        vals.extend_from_slice(self.data.get_row(id).unwrap());
665        Some(Row { id, vals })
666    }
667
668    fn get_row_column(&self, key: &[Value], col: ColumnId) -> Option<Value> {
669        let id = get_entry(key, self.n_keys, &self.hash, |row| {
670            &self.data.get_row(row).unwrap()[0..self.n_keys] == key
671        })?;
672        Some(self.data.get_row(id).unwrap()[col.index()])
673    }
674}
675
676impl SortedWritesTable {
677    fn new_table_buffer(&self) -> Buffer {
678        let n_shards = self.hash.shard_data().n_shards();
679        Buffer {
680            pending_rows: DenseIdMap::with_capacity(n_shards),
681            pending_removals: DenseIdMap::with_capacity(n_shards),
682            pending_known_removals: DenseIdMap::with_capacity(n_shards),
683            state: Arc::downgrade(&self.pending_state),
684            n_keys: u32::try_from(self.n_keys).expect("n_keys should fit in u32"),
685            n_cols: u32::try_from(self.n_columns).expect("n_columns should fit in u32"),
686            shard_data: self.hash.shard_data(),
687        }
688    }
689
690    /// Create a new [`SortedWritesTable`] with the given number of keys,
691    /// columns, and a sort column (normally the timestamp).
692    ///
693    /// The `merge_fn` is used to evaluate conflicts when more than one row is
694    /// inserted with the same primary key. The old and new proposed values are
695    /// passed as the second and third arguments, respectively, with the
696    /// function filling the final argument with the contents of the new row.
697    /// The return value indicates whether or not the contents of the vector
698    /// should be used.
699    ///
700    /// Merge functions can access the database via [`ExecutionState`].
701    pub fn new(
702        n_keys: usize,
703        n_columns: usize,
704        sort_by: ColumnId,
705        to_rebuild: Vec<ColumnId>,
706        merge_fn: Box<MergeFn>,
707    ) -> Self {
708        let hash = ShardedHashTable::<TableEntry>::default();
709        let shard_data = hash.shard_data();
710        let rebuild_index = Index::new(to_rebuild.clone(), ColumnIndex::new());
711        SortedWritesTable {
712            generation: Generation::new(0),
713            data: Rows::new(RowBuffer::new(n_columns)),
714            hash,
715            n_keys,
716            n_columns,
717            sort_by,
718            offsets: Default::default(),
719            pending_state: Arc::new(PendingState::new(shard_data)),
720            merge: merge_fn.into(),
721            to_rebuild,
722            rebuild_index,
723            subset_tracker: Default::default(),
724            full_scan_credit: 0,
725        }
726    }
727
728    /// Flush pending removals in coarse shard partitions. Each worker first
729    /// probes and erases all entries in its partition, then marks the removed
730    /// rows stale as a separate write-only pass.
731    fn parallel_delete(&mut self) -> bool {
732        let pending_removals = &self.pending_state.pending_removals;
733        let pending_known_removals = &self.pending_state.pending_known_removals;
734        let data = &self.data.data;
735        let n_keys = self.n_keys;
736        let stale_delta: usize =
737            parallel::map_chunks_mut(self.hash.mut_shards(), |base_shard, shards| {
738                let mut removed_rows = with_pool_set(|ps| ps.get::<Vec<RowId>>());
739                for (shard_offset, shard) in shards.iter_mut().enumerate() {
740                    let shard_id = ShardId::from_usize(base_shard + shard_offset);
741                    let removal_buffers = drain_queue(&pending_removals[shard_id]);
742                    for buf in &removal_buffers {
743                        debug_assert_eq!(buf.arity, n_keys);
744                        for (hash, to_remove) in buf.rows_hashed() {
745                            if let Ok(entry) = shard.find_entry(hash.probe().raw(), |entry| {
746                                entry.hash == hash
747                                    && &data.get_row(entry.row)[0..n_keys] == to_remove
748                            }) {
749                                let (ent, _) = entry.remove();
750                                removed_rows.push(ent.row);
751                            }
752                        }
753                    }
754                    let known_buffers = drain_queue(&pending_known_removals[shard_id]);
755                    for buf in &known_buffers {
756                        for removal in buf {
757                            if let Ok(entry) = shard
758                                .find_entry(removal.hash.probe().raw(), |entry| {
759                                    entry.hash == removal.hash && entry.row == removal.row
760                                })
761                            {
762                                let (ent, _) = entry.remove();
763                                removed_rows.push(ent.row);
764                            }
765                        }
766                    }
767                }
768                // SAFETY: A worker exclusively owns every shard in this
769                // partition. Live rows have exactly one primary-key entry,
770                // so successful removals yield disjoint rows across tasks.
771                unsafe { mark_rows_stale(data, &removed_rows) };
772                removed_rows.len()
773            })
774            .into_iter()
775            .sum();
776        self.data.stale_rows += stale_delta;
777        stale_delta > 0
778    }
779    fn serial_delete(&mut self) -> bool {
780        let mut changed = false;
781        self.hash
782            .mut_shards()
783            .iter_mut()
784            .enumerate()
785            .for_each(|(shard_id, shard)| {
786                let shard_id = ShardId::from_usize(shard_id);
787                let removal_buffers = drain_queue(&self.pending_state.pending_removals[shard_id]);
788                for buf in &removal_buffers {
789                    debug_assert_eq!(buf.arity, self.n_keys);
790                    for (hash, to_remove) in buf.rows_hashed() {
791                        if let Ok(entry) = shard.find_entry(hash.probe().raw(), |entry| {
792                            entry.hash == hash
793                                && &self.data.get_row(entry.row).unwrap()[0..self.n_keys]
794                                    == to_remove
795                        }) {
796                            let (ent, _) = entry.remove();
797                            self.data.set_stale(ent.row);
798                            changed = true;
799                        }
800                    }
801                }
802                let known_buffers =
803                    drain_queue(&self.pending_state.pending_known_removals[shard_id]);
804                for buf in &known_buffers {
805                    for removal in buf {
806                        if let Ok(entry) = shard.find_entry(removal.hash.probe().raw(), |entry| {
807                            entry.hash == removal.hash && entry.row == removal.row
808                        }) {
809                            let (ent, _) = entry.remove();
810                            self.data.set_stale(ent.row);
811                            changed = true;
812                        }
813                    }
814                }
815            });
816        changed
817    }
818
819    fn do_delete(&mut self) {
820        let total = self.pending_state.total_removals.swap(0, Ordering::Relaxed);
821
822        if parallelize_table_op(total) {
823            self.parallel_delete()
824        } else {
825            self.serial_delete()
826        };
827    }
828
829    fn do_insert(&mut self, exec_state: &mut ExecutionState) -> bool {
830        let total = self.pending_state.total_rows.swap(0, Ordering::Relaxed);
831        self.data.data.reserve(total);
832        if parallelize_table_op(total) {
833            self.parallel_insert(
834                exec_state,
835                SortChecker {
836                    col: self.sort_by,
837                    current: None,
838                    baseline: self.offsets.last().map(|(v, _)| *v),
839                },
840            )
841        } else {
842            self.serial_insert(exec_state)
843        }
844    }
845
846    fn serial_insert(&mut self, exec_state: &mut ExecutionState) -> bool {
847        let mut changed = false;
848        let n_keys = self.n_keys;
849        let mut scratch = with_pool_set(|ps| ps.get::<Vec<Value>>());
850        for (outer_shard, queue) in self.pending_state.pending_rows.iter() {
851            let buffers = drain_queue(queue);
852            let incoming = buffers.iter().map(HashedRowBuffer::len).sum();
853            self.hash.mut_shards()[outer_shard.index()]
854                .reserve(incoming, TableEntry::raw_probe_hash);
855            for buf in &buffers {
856                for (hash, query) in buf.rows_hashed() {
857                    if query.first().is_some_and(Value::is_stale) {
858                        continue;
859                    }
860                    let key = &query[0..n_keys];
861                    use hashbrown::hash_table::Entry;
862                    match self.hash.mut_shards()[outer_shard.index()].entry(
863                        hash.probe().raw(),
864                        |entry| {
865                            entry.hash == hash
866                                && self
867                                    .data
868                                    .get_row(entry.row)
869                                    .is_some_and(|row| &row[0..n_keys] == key)
870                        },
871                        TableEntry::raw_probe_hash,
872                    ) {
873                        Entry::Occupied(mut entry) => {
874                            let old_row = entry.get().row;
875                            let cur = self
876                                .data
877                                .get_row(old_row)
878                                .expect("table should not point to stale entry");
879                            if (self.merge)(exec_state, cur, query, &mut scratch) {
880                                debug_assert_eq!(&scratch[0..n_keys], key);
881                                let new = self.data.add_row(&scratch);
882                                update_sort_offsets(self.sort_by, &scratch, new, &mut self.offsets);
883                                self.data.set_stale(old_row);
884                                entry.get_mut().row = new;
885                                changed = true;
886                            }
887                            scratch.clear();
888                        }
889                        Entry::Vacant(entry) => {
890                            let new = self.data.add_row(query);
891                            update_sort_offsets(self.sort_by, query, new, &mut self.offsets);
892                            entry.insert(TableEntry { hash, row: new });
893                            changed = true;
894                        }
895                    }
896                }
897            }
898        }
899        changed
900    }
901
902    fn parallel_insert(&mut self, exec_state: &ExecutionState, checker: SortChecker) -> bool {
903        // Parallel insert uses one giant parallel foreach. We have updates
904        // pre-sharded, and one logical thread can process updates for each
905        // shard independently. Updates happen in three phases, which comments
906        // describe below.
907        let n_keys = self.n_keys;
908        let n_cols = self.n_columns;
909        let next_offset = RowId::from_usize(self.data.data.len());
910        let row_writer = self.data.data.parallel_writer();
911        let pending_rows = &self.pending_state.pending_rows;
912        let merge = self.merge.clone();
913        let pending_adds = parallel::map_mut(self.hash.mut_shards(), |shard_id, shard| {
914            let shard_id = ShardId::from_usize(shard_id);
915            let mut checker = checker;
916            let mut exec_state = exec_state.clone();
917            let mut scratch = with_pool_set(|ps| ps.get::<Vec<Value>>());
918            let queue = &pending_rows[shard_id];
919            let buffers = drain_queue(queue);
920            let incoming = buffers.iter().map(HashedRowBuffer::len).sum();
921            shard.reserve(incoming, TableEntry::raw_probe_hash);
922            let mut marked_stale = 0usize;
923            let mut staged = CoalescedInsertBatch::new(n_keys, n_cols, PARALLEL_INSERT_BATCH_SIZE);
924            let mut changed = false;
925            // Flush after a bounded number of staged physical rows.
926            macro_rules! flush_insert_batch {
927                () => {{
928                    if !staged.is_empty() {
929                        // Phase 2: Write the staged rows to the row writer. This only
930                        // works due to the `ParallelRowBufWriter` machinery.
931                        let (start_row, stale) = staged.write_output(&row_writer);
932                        marked_stale += stale;
933                        // Phase 3: With the values buffered in the row buffer, we can
934                        // write them back to the shard, pointed to the correct rows.
935
936                        // In the serial implementation, we do phases 2 and 3 inline with
937                        // processing the incoming mutation, but separating them out
938                        // this way allows us to do a single write to the shared row
939                        // buffer, rather than one per row, which would cause
940                        // contention.
941                        let mut cur_row = start_row;
942                        let read_handle = row_writer.read_handle();
943                        for (hash, row) in staged.rows_hashed() {
944                            if row.first().is_some_and(Value::is_stale) {
945                                cur_row = cur_row.inc();
946                                continue;
947                            }
948                            use hashbrown::hash_table::Entry;
949                            let key = &row[0..n_keys];
950                            #[cfg(any(debug_assertions, test))]
951                            {
952                                unsafe {
953                                    // read the value we wrote at this row and
954                                    // check that it matches.
955                                    assert_eq!(read_handle.get_row_unchecked(cur_row), row);
956                                }
957                            }
958                            match shard.entry(
959                                hash.probe().raw(),
960                                // SAFETY: `ent` must point to a valid row
961                                |ent| unsafe {
962                                    ent.hash == hash
963                                        && &read_handle.get_row_unchecked(ent.row)[0..n_keys] == key
964                                },
965                                TableEntry::raw_probe_hash,
966                            ) {
967                                Entry::Occupied(mut occ) => {
968                                    // SAFETY: `occ` must point to a valid row: we only insert valid rows
969                                    // into the map.
970                                    let old_row = occ.get().row;
971                                    let merged = {
972                                        let cur =
973                                            unsafe { read_handle.get_row_unchecked(old_row) };
974                                        (merge)(&mut exec_state, cur, row, &mut scratch)
975                                    };
976
977                                    // SAFETY: The safety requirements of
978                                    // `replace_row_shared` and `set_stale_shared`
979                                    // are that there are no concurrent accesses
980                                    // to either row. `cur_row` is a completed,
981                                    // uniquely reserved write that has not yet
982                                    // been published, and we have exclusive
983                                    // access to every existing row whose hash
984                                    // maps to this shard.
985                                    if merged {
986                                        debug_assert_eq!(
987                                            &scratch[0..n_keys],
988                                            key,
989                                            "merge functions must preserve table keys"
990                                        );
991                                        checker.check_local(&scratch);
992                                        unsafe {
993                                            read_handle.replace_row_shared(cur_row, &scratch);
994                                        }
995                                        occ.get_mut().row = cur_row;
996                                        unsafe {
997                                            let _was_stale =
998                                                read_handle.set_stale_shared(old_row);
999                                            debug_assert!(!_was_stale);
1000                                        }
1001                                        changed = true;
1002                                    } else {
1003                                        // Mark the new row as stale: we didn't end up needing it.
1004                                        unsafe {
1005                                            let _was_stale = read_handle.set_stale_shared(cur_row);
1006                                            debug_assert!(!_was_stale);
1007                                        }
1008                                    }
1009                                    marked_stale += 1;
1010                                    scratch.clear();
1011                                }
1012                                Entry::Vacant(v) => {
1013                                    checker.check_local(row);
1014                                    changed = true;
1015                                    v.insert(TableEntry {
1016                                        hash,
1017                                        row: cur_row,
1018                                    });
1019                                }
1020                            }
1021
1022                            cur_row = cur_row.inc();
1023                        }
1024                        staged.clear();
1025                    }
1026                }};
1027            }
1028            // Phase 1: process all incoming updates:
1029            // * Coalesce rows with the same key in a bounded temporary table.
1030            // * Copy the staged rows to the shared row buffer in one
1031            //   reservation.
1032            // * Apply each live row to the exclusively owned destination
1033            //   shard in `flush_insert_batch`.
1034            for buf in &buffers {
1035                for (hash, row) in buf.rows_hashed() {
1036                    staged.insert_hashed(hash, row, |cur, new, out| {
1037                        (merge)(&mut exec_state, cur, new, out)
1038                    });
1039                    if staged.physical_len() >= PARALLEL_INSERT_BATCH_SIZE {
1040                        flush_insert_batch!();
1041                    }
1042                }
1043            }
1044            flush_insert_batch!();
1045            (checker, marked_stale, changed)
1046        });
1047        self.data.data = row_writer.finish();
1048        // Now we just need to reset our invariants.
1049
1050        // Confirm none of the writes violated sort order and update the
1051        // `offsets` vector.
1052        let checker = SortChecker::check_global(pending_adds.iter().map(|(checker, _, _)| checker));
1053        checker.update_offsets(next_offset, &mut self.offsets);
1054
1055        // Update the staleness counters.
1056        self.data.stale_rows += pending_adds
1057            .iter()
1058            .map(|(_, stale, _)| *stale)
1059            .sum::<usize>();
1060
1061        // Register any changes.
1062        pending_adds.iter().any(|(_, _, changed)| *changed)
1063    }
1064
1065    fn binary_search_sort_val(&self, val: Value) -> Result<(RowId, RowId), RowId> {
1066        debug_assert!(
1067            self.offsets.windows(2).all(|x| x[0].1 < x[1].1),
1068            "{:?}",
1069            self.offsets
1070        );
1071
1072        debug_assert!(
1073            self.offsets.windows(2).all(|x| x[0].0 < x[1].0),
1074            "{:?}",
1075            self.offsets
1076        );
1077        match self.offsets.binary_search_by_key(&val, |(v, _)| *v) {
1078            Ok(got) => Ok((
1079                self.offsets[got].1,
1080                self.offsets
1081                    .get(got + 1)
1082                    .map(|(_, r)| *r)
1083                    .unwrap_or(self.data.next_row()),
1084            )),
1085            Err(next) => Err(self
1086                .offsets
1087                .get(next)
1088                .map(|(_, id)| *id)
1089                .unwrap_or(self.data.next_row())),
1090        }
1091    }
1092    fn eval(&self, cs: &[Constraint], row: RowId) -> bool {
1093        self.get_if(cs, row).is_some()
1094    }
1095
1096    fn eval_constraints(cs: &[Constraint], row: &[Value]) -> bool {
1097        cs.iter().all(|constraint| match constraint {
1098            Constraint::Eq { l_col, r_col } => row[l_col.index()] == row[r_col.index()],
1099            Constraint::EqConst { col, val } => row[col.index()] == *val,
1100            Constraint::LtConst { col, val } => row[col.index()] < *val,
1101            Constraint::GtConst { col, val } => row[col.index()] > *val,
1102            Constraint::LeConst { col, val } => row[col.index()] <= *val,
1103            Constraint::GeConst { col, val } => row[col.index()] >= *val,
1104        })
1105    }
1106
1107    unsafe fn get_if_unchecked(&self, cs: &[Constraint], row: RowId) -> Option<&[Value]> {
1108        let row = unsafe { self.data.get_row_unchecked(row) }?;
1109        if Self::eval_constraints(cs, row) {
1110            Some(row)
1111        } else {
1112            None
1113        }
1114    }
1115
1116    fn get_if(&self, cs: &[Constraint], row: RowId) -> Option<&[Value]> {
1117        let row = self.data.get_row(row)?;
1118        if Self::eval_constraints(cs, row) {
1119            Some(row)
1120        } else {
1121            None
1122        }
1123    }
1124
1125    fn maybe_rehash(&mut self) {
1126        if self.data.stale_rows <= cmp::max(16, self.data.data.len() / 2) {
1127            return;
1128        }
1129
1130        if parallelize_table_op(self.data.data.len()) {
1131            self.parallel_rehash();
1132        } else {
1133            self.rehash();
1134        }
1135    }
1136    /// Remove stale rows while preserving the order of the live rows.
1137    ///
1138    /// A live row's new ID is its rank: the number of live rows strictly before
1139    /// it in the old buffer. We compute this mapping in 64-row blocks, storing
1140    /// `(live, base)` in `ranks[block]`. Bit `i` of `live` is set exactly when old
1141    /// row `block * 64 + i` is live; `base` is the total number of live rows in
1142    /// earlier blocks. Thus a row's rank is `base` plus the population count of
1143    /// the bits below its bit. The same formula maps old timestamp boundaries
1144    /// to new boundaries, even when the row at a boundary is stale.
1145    ///
1146    /// The passes below first build the bitmaps in parallel, then compute block
1147    /// bases and remap timestamp boundaries serially. Next, workers copy live
1148    /// rows into scratch in order within each block. A block owns the output
1149    /// range `[base, base + live.count_ones())`, so writes cannot overlap and
1150    /// global row order is preserved regardless of which worker finishes first.
1151    /// Finally, workers remap hash-entry row IDs by shard using the same ranks;
1152    /// keys, hashes, and bucket positions stay unchanged. Each parallel pass
1153    /// joins its workers before the next pass begins. We then swap in scratch
1154    /// as the new row buffer and reset the stale-row count.
1155    fn parallel_rehash(&mut self) {
1156        self.generation = self.generation.inc();
1157        // 1. Scan the old rows in parallel. Unused bits in the final, partial
1158        // block stay zero so they contribute neither ranks nor output rows.
1159        let data = &self.data.data;
1160        let mut ranks = vec![(0u64, RowId::new(0)); data.len().div_ceil(64)];
1161        parallel::for_each_mut(&mut ranks, |block, (live, _)| {
1162            let start = block * 64;
1163            let mut bitmap = 0u64;
1164            for old in start..(start + 64).min(data.len()) {
1165                let is_live = !data.get_row(RowId::from_usize(old))[0].is_stale();
1166                bitmap |= u64::from(is_live) << (old - start);
1167            }
1168            *live = bitmap;
1169        });
1170
1171        // 2. Take an exclusive prefix sum of the block populations. This gives
1172        // each block its output base and computes the total output size.
1173        let mut live_rows = 0;
1174        for (live, base) in &mut ranks {
1175            *base = RowId::from_usize(live_rows);
1176            live_rows += live.count_ones() as usize;
1177        }
1178        debug_assert_eq!(live_rows, data.len() - self.data.stale_rows);
1179
1180        // 3. Map each old timestamp range [start, end) to
1181        // [rank_before(start), rank_before(end)). Equal ranks mean the range
1182        // contains no live rows, so omit it. This work is linear in the number
1183        // of distinct timestamps, independent of the number of shards and of
1184        // the numeric timestamp range.
1185        let rank_before = |old: usize| {
1186            if old == data.len() {
1187                return live_rows;
1188            }
1189            let (live, base) = ranks[old / 64];
1190            let preceding = (1u64 << (old % 64)) - 1;
1191            base.index() + (live & preceding).count_ones() as usize
1192        };
1193        let mut write = 0;
1194        for read in 0..self.offsets.len() {
1195            let (timestamp, old_start) = self.offsets[read];
1196            let old_end = self
1197                .offsets
1198                .get(read + 1)
1199                .map_or(data.len(), |(_, row)| row.index());
1200            let new_start = rank_before(old_start.index());
1201            if rank_before(old_end) > new_start {
1202                self.offsets[write] = (timestamp, RowId::from_usize(new_start));
1203                write += 1;
1204            }
1205        }
1206        self.offsets.truncate(write);
1207
1208        // 4. Copy from the unchanged source into the disjoint output ranges.
1209        // Visiting the lowest remaining set bit emits live rows in old order
1210        // without testing stale rows again.
1211        self.data.scratch.clear();
1212        self.data.scratch.reserve(live_rows);
1213        let scratch_ptr = self.data.scratch.raw_rows() as usize;
1214        let n_columns = self.n_columns;
1215        parallel::for_each_mut(&mut ranks, |block, (live, base)| {
1216            let mut remaining = *live;
1217            let mut next = base.index();
1218            while remaining != 0 {
1219                let offset = remaining.trailing_zeros() as usize;
1220                remaining &= remaining - 1;
1221                let row = data.get_row(RowId::from_usize(block * 64 + offset));
1222                // SAFETY: the prefix sum assigns each block a disjoint output
1223                // range with exactly as many rows as its bitmap has set bits.
1224                // scratch is reserved for the sum of these counts, does not
1225                // overlap data, and is not borrowed until all workers finish.
1226                unsafe {
1227                    std::ptr::copy_nonoverlapping(
1228                        row.as_ptr(),
1229                        (scratch_ptr as *mut Value).add(next * n_columns),
1230                        n_columns,
1231                    );
1232                }
1233                next += 1;
1234            }
1235        });
1236        // SAFETY: all live_rows rows were initialized by the joined workers.
1237        unsafe { self.data.scratch.set_len(live_rows) };
1238
1239        // 5. Remap each hash entry to the position where its row was copied.
1240        // Shards can be updated independently; keys, hashes, and buckets are
1241        // unchanged, so this needs no hashing or probing.
1242        parallel::for_each_mut(self.hash.mut_shards(), |_, shard| {
1243            for entry in shard.iter_mut() {
1244                let old = entry.row.index();
1245                let (live, base) = ranks[old / 64];
1246                let bit = 1u64 << (old % 64);
1247                debug_assert_ne!(live & bit, 0, "hash entry mapped to a stale row");
1248                entry.row =
1249                    RowId::from_usize(base.index() + (live & (bit - 1)).count_ones() as usize);
1250            }
1251        });
1252        mem::swap(&mut self.data.data, &mut self.data.scratch);
1253        self.data.stale_rows = 0;
1254    }
1255
1256    fn rehash_impl(
1257        sort_by: ColumnId,
1258        rows: &mut Rows,
1259        offsets: &mut Vec<(Value, RowId)>,
1260        hash: &mut ShardedHashTable<TableEntry>,
1261    ) {
1262        // Stable compaction maps an old row id to the number of live rows
1263        // preceding it. Keep that rank in 64-row blocks instead of probing the
1264        // key hash table again for every retained row. A block takes 16 bytes,
1265        // versus 256 bytes for a dense old-to-new RowId map.
1266        let mut ranks = vec![(0u64, RowId::new(0)); rows.data.len().div_ceil(64)];
1267        offsets.clear();
1268        rows.remove_stale(|row, old, new| {
1269            let (live, base) = &mut ranks[old.index() / 64];
1270            if *live == 0 {
1271                *base = new;
1272            }
1273            *live |= 1u64 << (old.index() % 64);
1274            let sort_col = row[sort_by.index()];
1275            if offsets.last().is_none_or(|(max, _)| sort_col > *max) {
1276                offsets.push((sort_col, new));
1277            }
1278        });
1279        // Keys and hashes are unchanged, so the existing buckets remain valid.
1280        // Visiting them directly avoids recomputing key hashes and random probes.
1281        for shard in hash.mut_shards() {
1282            for entry in shard.iter_mut() {
1283                let old = entry.row.index();
1284                let (live, base) = ranks[old / 64];
1285                let bit = 1u64 << (old % 64);
1286                debug_assert_ne!(live & bit, 0, "hash entry mapped to a stale row");
1287                entry.row =
1288                    RowId::from_usize(base.index() + (live & (bit - 1)).count_ones() as usize);
1289            }
1290        }
1291    }
1292
1293    fn rehash(&mut self) {
1294        self.generation = self.generation.inc();
1295        Self::rehash_impl(
1296            self.sort_by,
1297            &mut self.data,
1298            &mut self.offsets,
1299            &mut self.hash,
1300        )
1301    }
1302}
1303
1304fn get_entry(
1305    row: &[Value],
1306    n_keys: usize,
1307    table: &ShardedHashTable<TableEntry>,
1308    test: impl Fn(RowId) -> bool,
1309) -> Option<RowId> {
1310    let hash = shard_hash(table.shard_data(), row, n_keys);
1311    table
1312        .get_shard(hash.shard)
1313        .find(hash.compact.probe().raw(), |ent| {
1314            ent.hash == hash.compact && test(ent.row)
1315        })
1316        .map(|ent| ent.row)
1317}
1318
1319fn shard_hash(shard_data: ShardData, row: &[Value], n_keys: usize) -> ShardHash {
1320    let mut hasher = FxHasher::default();
1321    for val in &row[0..n_keys] {
1322        hasher.write_usize(val.index());
1323    }
1324    ShardHash::from_full(shard_data, FullHash(hasher.finish()))
1325}
1326
1327fn update_sort_offsets(
1328    sort_by: ColumnId,
1329    row: &[Value],
1330    row_id: RowId,
1331    offsets: &mut Vec<(Value, RowId)>,
1332) {
1333    let sort_val = row[sort_by.index()];
1334    if let Some(largest) = offsets.last().map(|(value, _)| *value) {
1335        assert!(
1336            sort_val >= largest,
1337            "inserting row that violates sort order ({sort_val:?} vs. {largest:?})"
1338        );
1339        if sort_val > largest {
1340            offsets.push((sort_val, row_id));
1341        }
1342    } else {
1343        offsets.push((sort_val, row_id));
1344    }
1345}
1346
1347fn drain_queue<T>(queue: &SegQueue<T>) -> Vec<T> {
1348    let mut drained = Vec::new();
1349    while let Some(item) = queue.pop() {
1350        drained.push(item);
1351    }
1352    drained
1353}
1354
1355/// # Safety
1356/// The caller must ensure exclusive access to every row in `rows`.
1357unsafe fn mark_rows_stale(data: &RowBuffer, rows: &[RowId]) {
1358    for row in rows {
1359        let was_stale = unsafe { data.set_stale_shared(*row) };
1360        debug_assert!(!was_stale);
1361    }
1362}
1363
1364/// A simple struct for packaging up pending mutations to a `SortedWritesTable`.
1365struct PendingState {
1366    pending_rows: DenseIdMap<ShardId, SegQueue<HashedRowBuffer>>,
1367    pending_removals: DenseIdMap<ShardId, SegQueue<HashedRowBuffer>>,
1368    pending_known_removals: DenseIdMap<ShardId, SegQueue<Vec<KnownRemoval>>>,
1369    total_removals: AtomicUsize,
1370    total_rows: AtomicUsize,
1371}
1372
1373impl PendingState {
1374    fn new(shard_data: ShardData) -> PendingState {
1375        let n_shards = shard_data.n_shards();
1376        let mut pending_rows = DenseIdMap::with_capacity(n_shards);
1377        let mut pending_removals = DenseIdMap::with_capacity(n_shards);
1378        let mut pending_known_removals = DenseIdMap::with_capacity(n_shards);
1379        for i in 0..n_shards {
1380            pending_rows.insert(ShardId::from_usize(i), SegQueue::default());
1381            pending_removals.insert(ShardId::from_usize(i), SegQueue::default());
1382            pending_known_removals.insert(ShardId::from_usize(i), SegQueue::default());
1383        }
1384
1385        PendingState {
1386            pending_rows,
1387            pending_removals,
1388            pending_known_removals,
1389            total_removals: AtomicUsize::new(0),
1390            total_rows: AtomicUsize::new(0),
1391        }
1392    }
1393    fn clear(&self) {
1394        for (_, queue) in self.pending_rows.iter() {
1395            while queue.pop().is_some() {}
1396        }
1397
1398        for (_, queue) in self.pending_removals.iter() {
1399            while queue.pop().is_some() {}
1400        }
1401
1402        for (_, queue) in self.pending_known_removals.iter() {
1403            while queue.pop().is_some() {}
1404        }
1405        self.total_rows.store(0, Ordering::Relaxed);
1406        self.total_removals.store(0, Ordering::Relaxed);
1407    }
1408
1409    /// This is only really used in debugging, but it's annoying enough to write
1410    /// that it may help to have around.
1411    ///
1412    /// We also, however, use it in the clone impl (which should only be called when pending state
1413    /// is empty).
1414    fn deep_copy(&self) -> PendingState {
1415        let mut pending_rows = DenseIdMap::new();
1416        let mut pending_removals = DenseIdMap::new();
1417        let mut pending_known_removals = DenseIdMap::new();
1418        fn drain_queue<T>(queue: &SegQueue<T>) -> Vec<T> {
1419            let mut res = Vec::new();
1420            while let Some(x) = queue.pop() {
1421                res.push(x);
1422            }
1423            res
1424        }
1425        for (shard, queue) in self.pending_rows.iter() {
1426            let contents = drain_queue(queue);
1427            let new_queue = SegQueue::default();
1428            for x in contents {
1429                new_queue.push(x.clone());
1430                queue.push(x);
1431            }
1432            pending_rows.insert(shard, new_queue);
1433        }
1434
1435        for (shard, queue) in self.pending_removals.iter() {
1436            let contents = drain_queue(queue);
1437            let new_queue = SegQueue::default();
1438            for x in contents {
1439                new_queue.push(x.clone());
1440                queue.push(x);
1441            }
1442            pending_removals.insert(shard, new_queue);
1443        }
1444
1445        for (shard, queue) in self.pending_known_removals.iter() {
1446            let contents = drain_queue(queue);
1447            let new_queue = SegQueue::default();
1448            for x in contents {
1449                new_queue.push(x.clone());
1450                queue.push(x);
1451            }
1452            pending_known_removals.insert(shard, new_queue);
1453        }
1454
1455        PendingState {
1456            pending_rows,
1457            pending_removals,
1458            pending_known_removals,
1459            total_removals: AtomicUsize::new(self.total_removals.load(Ordering::Acquire)),
1460            total_rows: AtomicUsize::new(self.total_rows.load(Ordering::Acquire)),
1461        }
1462    }
1463}
1464
1465#[derive(Copy, Clone)]
1466struct SortChecker {
1467    col: ColumnId,
1468    baseline: Option<Value>,
1469    current: Option<Value>,
1470}
1471
1472impl SortChecker {
1473    fn check_local(&mut self, row: &[Value]) {
1474        let val = row[self.col.index()];
1475        if let Some(cur) = self.current {
1476            assert_eq!(
1477                cur, val,
1478                "concurrently inserting rows with different sort keys"
1479            );
1480        } else {
1481            self.current = Some(val);
1482            if let Some(baseline) = self.baseline {
1483                assert!(val >= baseline, "inserted row violates sort order");
1484            }
1485        }
1486    }
1487
1488    fn check_global<'a>(mut checkers: impl Iterator<Item = &'a Self>) -> Self {
1489        let start = checkers
1490            .next()
1491            .expect("a table must have at least one shard");
1492        let mut expected = start.current;
1493        for checker in checkers {
1494            assert_eq!(checker.baseline, start.baseline);
1495            match (&mut expected, checker.current) {
1496                (None, None) => {}
1497                (cur @ None, Some(x)) => {
1498                    *cur = Some(x);
1499                }
1500                (Some(_), None) => {}
1501                (Some(x), Some(y)) => {
1502                    assert_eq!(
1503                        *x, y,
1504                        "concurrently inserting rows with different sort keys"
1505                    );
1506                }
1507            }
1508        }
1509        SortChecker {
1510            col: start.col,
1511            baseline: start.baseline,
1512            current: expected,
1513        }
1514    }
1515
1516    fn update_offsets(&self, start: RowId, offsets: &mut Vec<(Value, RowId)>) {
1517        if let Some(cur) = self.current {
1518            if let Some((max, _)) = offsets.last() {
1519                if cur > *max {
1520                    offsets.push((cur, start));
1521                }
1522            } else {
1523                offsets.push((cur, start));
1524            }
1525        }
1526    }
1527}
1528
1529/// A bounded, cached-hash coalescer for pending insertion rows.
1530///
1531/// Multiple rows with the same key are merged before the surviving value is
1532/// combined with the destination table's current value. Physical rows and
1533/// their compact hash fingerprints stay aligned, including stale intermediate
1534/// merge outputs.
1535struct CoalescedInsertBatch {
1536    n_keys: usize,
1537    by_key: Pooled<HashTable<TableEntry>>,
1538    rows: RowBuffer,
1539    row_hashes: Vec<CompactHash>,
1540    n_stale: usize,
1541    scratch: Pooled<Vec<Value>>,
1542}
1543
1544impl CoalescedInsertBatch {
1545    fn rows_hashed(&self) -> impl Iterator<Item = (CompactHash, &[Value])> {
1546        debug_assert_eq!(self.row_hashes.len(), self.rows.len());
1547        self.row_hashes.iter().copied().zip(self.rows.iter())
1548    }
1549
1550    fn new(n_keys: usize, n_cols: usize, capacity: usize) -> Self {
1551        let mut res = with_pool_set(|ps| CoalescedInsertBatch {
1552            n_keys,
1553            by_key: ps.get(),
1554            rows: RowBuffer::new(n_cols),
1555            row_hashes: Vec::with_capacity(capacity),
1556            n_stale: 0,
1557            scratch: ps.get(),
1558        });
1559        res.by_key
1560            .reserve(capacity, |entry| coalesced_hash(entry.hash));
1561        res.rows.reserve(capacity);
1562        res
1563    }
1564
1565    fn clear(&mut self) {
1566        self.by_key.clear();
1567        self.rows.clear();
1568        self.row_hashes.clear();
1569        self.n_stale = 0;
1570    }
1571
1572    fn is_empty(&self) -> bool {
1573        self.rows.len() == 0
1574    }
1575
1576    fn physical_len(&self) -> usize {
1577        self.rows.len()
1578    }
1579
1580    fn insert_hashed(
1581        &mut self,
1582        hash: CompactHash,
1583        row: &[Value],
1584        mut merge_fn: impl FnMut(&[Value], &[Value], &mut Vec<Value>) -> bool,
1585    ) {
1586        if row.first().is_some_and(Value::is_stale) {
1587            return;
1588        }
1589
1590        debug_assert_eq!(self.row_hashes.len(), self.rows.len());
1591        use hashbrown::hash_table::Entry;
1592        let entry = self.by_key.entry(
1593            coalesced_hash(hash),
1594            |entry| {
1595                entry.hash == hash
1596                    && self.rows.get_row(entry.row)[0..self.n_keys] == row[0..self.n_keys]
1597            },
1598            |entry| coalesced_hash(entry.hash),
1599        );
1600        match entry {
1601            Entry::Occupied(mut occupied) => {
1602                let cur = self.rows.get_row(occupied.get().row);
1603                if merge_fn(cur, row, &mut self.scratch) {
1604                    debug_assert_eq!(
1605                        &self.scratch[0..self.n_keys],
1606                        &row[0..self.n_keys],
1607                        "merge functions must preserve table keys"
1608                    );
1609                    let new = self.rows.add_row(&self.scratch);
1610                    self.row_hashes.push(hash);
1611                    self.rows.set_stale(occupied.get().row);
1612                    self.n_stale += 1;
1613                    occupied.get_mut().row = new;
1614                }
1615                self.scratch.clear();
1616            }
1617            Entry::Vacant(vacant) => {
1618                let next = self.rows.add_row(row);
1619                self.row_hashes.push(hash);
1620                vacant.insert(TableEntry { hash, row: next });
1621            }
1622        }
1623        debug_assert_eq!(self.row_hashes.len(), self.rows.len());
1624    }
1625
1626    /// Append all physical rows, returning the first RowId and stale count.
1627    fn write_output(&self, output: &ParallelRowBufWriter) -> (RowId, usize) {
1628        debug_assert_eq!(self.row_hashes.len(), self.rows.len());
1629        (output.append_contents(&self.rows), self.n_stale)
1630    }
1631}
1632
1633/// Mix a row's cached fingerprint for the temporary coalescing table.
1634///
1635/// `CoalescedInsertBatch::by_key` merges repeated keys within a batch before
1636/// they reach the destination table. Reusing the cached fingerprint avoids
1637/// hashing each row's key columns again, but both tables select their initial
1638/// buckets from the hash's low bits. If batching groups rows by those bits,
1639/// distinct keys can crowd the same temporary buckets and lengthen probes.
1640///
1641/// This was the motivation in the former cache-partitioned mutation buffers:
1642/// bits 0..11 selected a bucket within a destination cache window, and bits
1643/// 11..17 selected a partition of windows to process together for locality.
1644/// Every row in a partition therefore shared bits 11..17. Using those hashes
1645/// directly in the smaller coalescing table restricted its initial buckets
1646/// wherever its bucket mask overlapped the fixed bits. Shifting by 17 and
1647/// XORing folds bits above that partition selector into the low bucket bits,
1648/// allowing the temporary table to spread those keys across more buckets.
1649/// For example, fingerprints `0` and `1 << 17` have identical low 17 bits;
1650/// after mixing, the latter is `(1 << 17) | 1`, so their lowest bit differs.
1651///
1652/// Current mutation buffers group rows by physical shard, without that cache
1653/// partitioning. The mixer remains as a cheap bucket-distribution heuristic;
1654/// whether it helps with the current buffers needs separate measurement.
1655/// The shift is consequently not a buffer-layout requirement. Only the
1656/// temporary lookup hash changes: the cached fingerprint stays unchanged for
1657/// destination-table probes, and actual key comparisons establish equality.
1658#[inline]
1659fn coalesced_hash(hash: CompactHash) -> u64 {
1660    const MIX_SHIFT: u32 = 17;
1661    let probe_hash = hash.probe().raw();
1662    probe_hash ^ probe_hash.wrapping_shr(MIX_SHIFT)
1663}