1use std::{
4 any::Any,
5 mem::{self, ManuallyDrop},
6 sync::{Arc, Weak},
7};
8
9use crate::numeric_id::{DenseIdMap, NumericId};
10use crossbeam_queue::SegQueue;
11use smallvec::SmallVec;
12
13use crate::{
14 TableChange, TaggedRowBuffer,
15 action::ExecutionState,
16 common::{HashMap, Value},
17 offsets::{OffsetRange, RowId, Subset, SubsetRef},
18 parallel,
19 pool::with_pool_set,
20 row_buffer::RowBuffer,
21 table_spec::{
22 ColumnId, Constraint, Generation, MutationBuffer, Offset, Rebuilder, Row, Table, TableSpec,
23 TableVersion, ValueRebuilder, WrappedTableRef,
24 },
25};
26
27#[cfg(test)]
28mod tests;
29
30type UnionFind = crate::union_find::UnionFind<Value>;
31
32const PARALLEL_UNION_THRESHOLD_ROWS: usize = 16 * 1024;
34const PARALLEL_UNION_CHUNK_ROWS: usize = 16 * 1024;
36const SMALL_PARALLEL_UNION_CHUNK_ROWS: usize = 2 * 1024;
38
39#[derive(Clone, Copy)]
40struct UnionChunk {
41 buffer: usize,
42 start: usize,
43 end: usize,
44}
45
46struct TimestampGroup {
47 timestamp: Value,
48 chunks: std::ops::Range<usize>,
49 rows: usize,
50 max_value: Value,
51}
52
53pub struct DisplacedTable {
78 uf: UnionFind,
79 displaced: Vec<(Value, Value)>,
80 changed: bool,
81 lookup_table: HashMap<Value, RowId>,
82 buffered_writes: Arc<SegQueue<RowBuffer>>,
83}
84
85struct Canonicalizer<'a> {
86 cols: Vec<ColumnId>,
87 table: &'a DisplacedTable,
88}
89
90impl ValueRebuilder for Canonicalizer<'_> {
91 fn rebuild_val(&self, val: Value) -> Value {
92 self.table.uf.find_naive(val)
93 }
94 }
96
97impl Rebuilder for Canonicalizer<'_> {
98 fn hint_col(&self) -> Option<ColumnId> {
99 Some(ColumnId::new(0))
100 }
101 fn rebuild_buf(
102 &self,
103 buf: &RowBuffer,
104 start: RowId,
105 end: RowId,
106 out: &mut TaggedRowBuffer,
107 _exec_state: &mut ExecutionState,
108 ) {
109 if start >= end {
110 return;
111 }
112 assert!(end.index() <= buf.len());
113 let mut cur = start;
114 match self.cols.as_slice() {
118 [c] => {
119 while cur < end {
120 let row = unsafe { buf.get_row_unchecked(cur) };
121 let to_canon = row[c.index()];
122 let canon = self.table.uf.find_naive(to_canon);
123 if canon != to_canon {
124 out.add_row_with(cur, row, |dst| dst[c.index()] = canon);
125 }
126 cur = cur.inc();
127 }
128 }
129 [c1, c2] => {
130 while cur < end {
131 let row = unsafe { buf.get_row_unchecked(cur) };
132 let v1 = row[c1.index()];
133 let v2 = row[c2.index()];
134 let ca1 = self.table.uf.find_naive(v1);
135 let ca2 = self.table.uf.find_naive(v2);
136 if ca1 != v1 || ca2 != v2 {
137 out.add_row_with(cur, row, |dst| {
138 dst[c1.index()] = ca1;
139 dst[c2.index()] = ca2;
140 });
141 }
142 cur = cur.inc();
143 }
144 }
145 [c1, c2, c3] => {
146 while cur < end {
147 let row = unsafe { buf.get_row_unchecked(cur) };
148 let v1 = row[c1.index()];
149 let v2 = row[c2.index()];
150 let v3 = row[c3.index()];
151 let ca1 = self.table.uf.find_naive(v1);
152 let ca2 = self.table.uf.find_naive(v2);
153 let ca3 = self.table.uf.find_naive(v3);
154 if ca1 != v1 || ca2 != v2 || ca3 != v3 {
155 out.add_row_with(cur, row, |dst| {
156 dst[c1.index()] = ca1;
157 dst[c2.index()] = ca2;
158 dst[c3.index()] = ca3;
159 });
160 }
161 cur = cur.inc();
162 }
163 }
164 cs => {
165 let mut canons: SmallVec<[Value; 8]> = SmallVec::with_capacity(cs.len());
166 while cur < end {
167 let row = unsafe { buf.get_row_unchecked(cur) };
168 canons.clear();
169 let mut changed = false;
170 for c in cs {
171 let to_canon = row[c.index()];
172 let canon = self.table.uf.find_naive(to_canon);
173 changed |= canon != to_canon;
174 canons.push(canon);
175 }
176 if changed {
177 out.add_row_with(cur, row, |dst| {
178 for (c, canon) in cs.iter().zip(canons.iter()) {
179 dst[c.index()] = *canon;
180 }
181 });
182 }
183 cur = cur.inc();
184 }
185 }
186 }
187 }
188 fn rebuild_subset(
189 &self,
190 other: WrappedTableRef,
191 subset: SubsetRef,
192 out: &mut TaggedRowBuffer,
193 _exec_state: &mut ExecutionState,
194 ) {
195 let old_len = u32::try_from(out.len()).expect("row buffer sizes should fit in a u32");
196 let _next = other.scan_bounded(subset, Offset::new(0), usize::MAX, out);
197 debug_assert!(_next.is_none());
198 for i in old_len..u32::try_from(out.len()).expect("row buffer sizes should fit in a u32") {
199 let i = RowId::new(i);
200 let (_id, row) = out.get_row_mut(i);
201 let mut changed = false;
202 for col in &self.cols {
203 let to_canon = row[col.index()];
204 let canon = self.table.uf.find_naive(to_canon);
205 changed |= canon != to_canon;
206 row[col.index()] = canon;
207 }
208 if !changed {
209 out.set_stale(i);
210 }
211 }
212 }
213}
214
215impl Default for DisplacedTable {
216 fn default() -> Self {
217 Self {
218 uf: UnionFind::default(),
219 displaced: Vec::new(),
220 changed: false,
221 lookup_table: HashMap::default(),
222 buffered_writes: Arc::new(SegQueue::new()),
223 }
224 }
225}
226
227impl Clone for DisplacedTable {
228 fn clone(&self) -> Self {
229 DisplacedTable {
230 uf: self.uf.clone(),
231 displaced: self.displaced.clone(),
232 changed: self.changed,
233 lookup_table: self.lookup_table.clone(),
234 buffered_writes: Default::default(),
235 }
236 }
237}
238
239struct UfBuffer {
240 to_insert: ManuallyDrop<RowBuffer>,
241 buffered_writes: Weak<SegQueue<RowBuffer>>,
242}
243
244impl Drop for UfBuffer {
245 fn drop(&mut self) {
246 let Some(buffered_writes) = self.buffered_writes.upgrade() else {
247 unsafe {
249 ManuallyDrop::drop(&mut self.to_insert);
250 }
251 return;
252 };
253 let to_insert = unsafe { ManuallyDrop::take(&mut self.to_insert) };
258 buffered_writes.push(to_insert);
259 }
260}
261
262impl MutationBuffer for UfBuffer {
263 fn stage_insert(&mut self, row: &[Value]) {
264 self.to_insert.add_row(row);
265 }
266 fn stage_remove(&mut self, _: &[Value]) {
267 panic!("attempting to remove data from a DisplacedTable")
268 }
269 fn fresh_handle(&self) -> Box<dyn MutationBuffer> {
270 Box::new(UfBuffer {
271 to_insert: ManuallyDrop::new(RowBuffer::new(self.to_insert.arity())),
272 buffered_writes: self.buffered_writes.clone(),
273 })
274 }
275}
276
277impl Table for DisplacedTable {
278 fn dyn_clone(&self) -> Box<dyn Table> {
279 Box::new(self.clone())
280 }
281 fn as_any(&self) -> &dyn Any {
282 self
283 }
284 fn spec(&self) -> TableSpec {
285 let mut uncacheable_columns = DenseIdMap::default();
286 uncacheable_columns.insert(ColumnId::new(1), true);
288 TableSpec {
289 n_keys: 1,
290 n_vals: 2,
291 uncacheable_columns,
292 }
293 }
294
295 fn rebuilder<'a>(&'a self, cols: &[ColumnId]) -> Option<Box<dyn Rebuilder + 'a>> {
296 Some(Box::new(Canonicalizer {
297 cols: cols.to_vec(),
298 table: self,
299 }))
300 }
301
302 fn clear(&mut self) {
303 self.uf.reset();
304 self.displaced.clear();
305 }
306
307 fn all(&self) -> Subset {
308 Subset::Dense(OffsetRange::new(
309 RowId::new(0),
310 RowId::from_usize(self.displaced.len()),
311 ))
312 }
313
314 fn len(&self) -> usize {
315 self.displaced.len()
316 }
317
318 fn version(&self) -> TableVersion {
319 TableVersion {
320 major: Generation::new(0),
321 minor: Offset::from_usize(self.displaced.len()),
322 }
323 }
324
325 fn updates_since(&self, offset: Offset) -> Subset {
326 Subset::Dense(OffsetRange::new(
327 RowId::from_usize(offset.index()),
328 RowId::from_usize(self.displaced.len()),
329 ))
330 }
331
332 fn scan_generic_bounded(
333 &self,
334 subset: SubsetRef,
335 start: Offset,
336 n: usize,
337 cs: &[Constraint],
338 mut f: impl FnMut(RowId, &[Value]),
339 ) -> Option<Offset>
340 where
341 Self: Sized,
342 {
343 if cs.is_empty() {
344 let start = start.index();
345 subset
346 .iter_bounded(start, start + n, |row| {
347 f(row, self.expand(row).as_slice());
348 })
349 .map(Offset::from_usize)
350 } else {
351 let start = start.index();
352 subset
353 .iter_bounded(start, start + n, |row| {
354 if cs.iter().all(|c| self.eval(c, row)) {
355 f(row, self.expand(row).as_slice());
356 }
357 })
358 .map(Offset::from_usize)
359 }
360 }
361
362 fn refine_one(&self, mut subset: Subset, c: &Constraint) -> Subset {
363 subset.retain(|row| self.eval(c, row));
364 subset
365 }
366
367 fn fast_subset(&self, constraint: &Constraint) -> Option<Subset> {
368 let ts = ColumnId::new(2);
369 match constraint {
370 Constraint::Eq { .. } => None,
371 Constraint::EqConst { col, val } => {
372 if *col == ColumnId::new(1) {
373 return None;
374 }
375 if *col == ColumnId::new(0) {
376 return Some(match self.lookup_table.get(val) {
377 Some(row) => Subset::Dense(OffsetRange::new(
378 *row,
379 RowId::from_usize(row.index() + 1),
380 )),
381 None => Subset::empty(),
382 });
383 }
384 match self.timestamp_bounds(*val) {
385 Ok((start, end)) => Some(Subset::Dense(OffsetRange::new(start, end))),
386 Err(_) => None,
387 }
388 }
389 Constraint::LtConst { col, val } => {
390 if *col != ts {
391 return None;
392 }
393 match self.timestamp_bounds(*val) {
394 Err(bound) | Ok((bound, _)) => {
395 Some(Subset::Dense(OffsetRange::new(RowId::new(0), bound)))
396 }
397 }
398 }
399 Constraint::GtConst { col, val } => {
400 if *col != ts {
401 return None;
402 }
403
404 match self.timestamp_bounds(*val) {
405 Err(bound) | Ok((_, bound)) => Some(Subset::Dense(OffsetRange::new(
406 bound,
407 RowId::from_usize(self.displaced.len()),
408 ))),
409 }
410 }
411 Constraint::LeConst { col, val } => {
412 if *col != ts {
413 return None;
414 }
415
416 match self.timestamp_bounds(*val) {
417 Err(bound) | Ok((_, bound)) => {
418 Some(Subset::Dense(OffsetRange::new(RowId::new(0), bound)))
419 }
420 }
421 }
422 Constraint::GeConst { col, val } => {
423 if *col != ts {
424 return None;
425 }
426
427 match self.timestamp_bounds(*val) {
428 Err(bound) | Ok((bound, _)) => Some(Subset::Dense(OffsetRange::new(
429 bound,
430 RowId::from_usize(self.displaced.len()),
431 ))),
432 }
433 }
434 }
435 }
436
437 fn get_row(&self, key: &[Value]) -> Option<Row> {
438 assert_eq!(key.len(), 1, "attempt to lookup a row with the wrong key");
439 let row_id = *self.lookup_table.get(&key[0])?;
440 let mut vals = with_pool_set(|ps| ps.get::<Vec<Value>>());
441 vals.extend_from_slice(self.expand(row_id).as_slice());
442 Some(Row { id: row_id, vals })
443 }
444
445 fn get_row_column(&self, key: &[Value], col: ColumnId) -> Option<Value> {
446 assert_eq!(key.len(), 1, "attempt to lookup a row with the wrong key");
447 if col == ColumnId::new(1) {
448 Some(self.uf.find_naive(key[0]))
449 } else {
450 let row_id = *self.lookup_table.get(&key[0])?;
451 Some(self.expand(row_id)[col.index()])
452 }
453 }
454
455 fn new_buffer(&self) -> Box<dyn MutationBuffer> {
456 Box::new(UfBuffer {
457 to_insert: ManuallyDrop::new(RowBuffer::new(3)),
458 buffered_writes: Arc::downgrade(&self.buffered_writes),
459 })
460 }
461
462 fn merge(&mut self, _: &mut ExecutionState) -> TableChange {
463 if parallel::current_num_threads() < 2 {
464 while let Some(rowbuf) = self.buffered_writes.pop() {
465 for row in rowbuf.iter() {
466 self.changed |= self.insert_impl(row).is_some();
467 }
468 }
469 return self.take_change();
470 }
471
472 let mut buffers = Vec::new();
473 let mut total_rows = 0;
474 while let Some(buffer) = self.buffered_writes.pop() {
475 total_rows += buffer.len();
476 buffers.push(buffer);
477 }
478 if total_rows <= PARALLEL_UNION_THRESHOLD_ROWS {
479 for buffer in &buffers {
480 for row in buffer.iter() {
481 self.changed |= self.insert_impl(row).is_some();
482 }
483 }
484 return self.take_change();
485 }
486
487 let (chunks, groups) = Self::union_work(&buffers);
488 for group in groups {
493 if group.rows <= PARALLEL_UNION_THRESHOLD_ROWS {
494 for chunk in &chunks[group.chunks] {
495 for row_index in chunk.start..chunk.end {
496 let row = buffers[chunk.buffer].get_row(RowId::from_usize(row_index));
497 self.changed |= self.insert_impl(row).is_some();
498 }
499 }
500 continue;
501 }
502
503 let successes = self.uf.with_atomic_access(group.max_value, |uf| {
504 if !parallel::enabled_for_len(group.chunks.len()) {
505 let mut children = Vec::with_capacity(group.rows);
506 for chunk in &chunks[group.chunks.clone()] {
507 for row_index in chunk.start..chunk.end {
508 let row = buffers[chunk.buffer].get_row(RowId::from_usize(row_index));
509 let (parent, child) = uf.union(row[0], row[1]);
510 if parent != child {
511 children.push(child);
512 }
513 }
514 }
515 vec![children]
516 } else {
517 parallel::map(&chunks[group.chunks.clone()], |_, chunk| {
518 let mut children = Vec::with_capacity(chunk.end - chunk.start);
519 for row_index in chunk.start..chunk.end {
520 let row = buffers[chunk.buffer].get_row(RowId::from_usize(row_index));
521 let (parent, child) = uf.union(row[0], row[1]);
522 if parent != child {
523 children.push(child);
524 }
525 }
526 children
527 })
528 }
529 });
530
531 let added = successes.iter().map(Vec::len).sum();
532 self.displaced.reserve(added);
533 self.lookup_table.reserve(added);
534 for child in successes.into_iter().flatten() {
539 self.publish_displaced(child, group.timestamp);
540 self.changed = true;
541 }
542 }
543 self.take_change()
544 }
545}
546
547impl DisplacedTable {
548 fn take_change(&mut self) -> TableChange {
549 let changed = mem::take(&mut self.changed);
550 TableChange { added: changed }
551 }
552
553 pub fn underlying_uf(&self) -> &UnionFind {
554 &self.uf
555 }
556 fn expand(&self, row: RowId) -> [Value; 3] {
557 let (child, ts) = self.displaced[row.index()];
558 [child, self.uf.find_naive(child), ts]
559 }
560 fn timestamp_bounds(&self, val: Value) -> Result<(RowId, RowId), RowId> {
561 match self.displaced.binary_search_by_key(&val, |(_, ts)| *ts) {
562 Ok(mut off) => {
563 let mut next = off;
564 while off > 0 && self.displaced[off - 1].1 == val {
565 off -= 1;
566 }
567 while next < self.displaced.len() && self.displaced[next].1 == val {
568 next += 1;
569 }
570 Ok((RowId::from_usize(off), RowId::from_usize(next)))
571 }
572 Err(off) => Err(RowId::from_usize(off)),
573 }
574 }
575 fn eval(&self, constraint: &Constraint, row: RowId) -> bool {
576 let vals = self.expand(row);
577 eval_constraint(&vals, constraint)
578 }
579 fn insert_impl(&mut self, row: &[Value]) -> Option<(Value, Value)> {
580 assert_eq!(row.len(), 3, "attempt to insert a row with the wrong arity");
581 if self.uf.find(row[0]) == self.uf.find(row[1]) {
582 return None;
583 }
584 let (parent, child) = self.uf.union(row[0], row[1]);
585
586 let _ = self.uf.find(parent);
588 let _ = self.uf.find(child);
589 self.publish_displaced(child, row[2]);
590 Some((parent, child))
591 }
592
593 fn publish_displaced(&mut self, child: Value, ts: Value) {
594 if let Some((_, highest)) = self.displaced.last() {
595 assert!(
596 *highest <= ts,
597 "must insert rows with increasing timestamps"
598 );
599 }
600 let next = RowId::from_usize(self.displaced.len());
601 self.displaced.push((child, ts));
602 self.lookup_table.insert(child, next);
603 }
604
605 fn union_work(buffers: &[RowBuffer]) -> (Vec<UnionChunk>, Vec<TimestampGroup>) {
606 let mut chunks = Vec::new();
607 let mut groups = Vec::<TimestampGroup>::new();
608
609 for (buffer_index, buffer) in buffers.iter().enumerate() {
610 assert_eq!(
611 buffer.arity(),
612 3,
613 "attempt to insert a row with the wrong arity"
614 );
615 let mut run_start = 0;
616 let mut run_timestamp = None;
617 let mut run_max = None;
618 for (row_index, row) in buffer.iter().enumerate() {
619 let timestamp = row[2];
620 if run_timestamp.is_some_and(|current| current != timestamp) {
621 Self::push_union_run(
622 &mut chunks,
623 &mut groups,
624 buffer_index,
625 run_start,
626 row_index,
627 run_timestamp.unwrap(),
628 run_max.unwrap(),
629 );
630 run_start = row_index;
631 run_max = None;
632 }
633 run_timestamp = Some(timestamp);
634 let row_max = row[0].max(row[1]);
635 run_max = Some(run_max.map_or(row_max, |current: Value| current.max(row_max)));
636 }
637 if let Some(timestamp) = run_timestamp {
638 Self::push_union_run(
639 &mut chunks,
640 &mut groups,
641 buffer_index,
642 run_start,
643 buffer.len(),
644 timestamp,
645 run_max.unwrap(),
646 );
647 }
648 }
649 (chunks, groups)
650 }
651
652 fn push_union_run(
653 chunks: &mut Vec<UnionChunk>,
654 groups: &mut Vec<TimestampGroup>,
655 buffer: usize,
656 start: usize,
657 end: usize,
658 timestamp: Value,
659 max_value: Value,
660 ) {
661 let group = match groups.last_mut() {
662 Some(group) if group.timestamp == timestamp => group,
663 _ => {
664 let start = chunks.len();
665 groups.push(TimestampGroup {
666 timestamp,
667 chunks: start..start,
668 rows: 0,
669 max_value,
670 });
671 groups.last_mut().unwrap()
672 }
673 };
674 let chunk_rows =
678 if end - start < PARALLEL_UNION_CHUNK_ROWS * parallel::current_num_threads() {
679 SMALL_PARALLEL_UNION_CHUNK_ROWS
680 } else {
681 PARALLEL_UNION_CHUNK_ROWS
682 };
683 for start in (start..end).step_by(chunk_rows) {
684 chunks.push(UnionChunk {
685 buffer,
686 start,
687 end: (start + chunk_rows).min(end),
688 });
689 }
690 group.chunks.end = chunks.len();
691 group.rows += end - start;
692 group.max_value = group.max_value.max(max_value);
693 }
694}
695
696fn eval_constraint<const N: usize>(vals: &[Value; N], constraint: &Constraint) -> bool {
697 match constraint {
698 Constraint::Eq { l_col, r_col } => vals[l_col.index()] == vals[r_col.index()],
699 Constraint::EqConst { col, val } => vals[col.index()] == *val,
700 Constraint::LtConst { col, val } => vals[col.index()] < *val,
701 Constraint::GtConst { col, val } => vals[col.index()] > *val,
702 Constraint::LeConst { col, val } => vals[col.index()] <= *val,
703 Constraint::GeConst { col, val } => vals[col.index()] >= *val,
704 }
705}