1use std::borrow::Cow;
41#[cfg(test)]
42use std::cell::Cell;
43use std::cell::RefCell;
44use std::collections::VecDeque;
45use std::marker::PhantomData;
46use std::rc::Rc;
47use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
48use std::sync::{Arc, OnceLock};
49
50use columnar::bytes::indexed;
51use columnar::{Borrow, BorrowedOf, Columnar, Container as _, Index, Len, Push as _};
52use differential_dataflow::difference::Semigroup;
53use differential_dataflow::lattice::Lattice;
54use differential_dataflow::trace::chunk::Chunk;
55use mz_ore::cast::CastFrom;
56use mz_ore::pool::{ChunkHandle, ChunkHints, ExtentCodec, IDENTITY_CODEC, Pool, TypedBody};
57use smallvec::SmallVec;
58use timely::Accountable;
59use timely::PartialOrder;
60use timely::container::{ContainerBuilder, PushInto};
61use timely::progress::Timestamp;
62use timely::progress::frontier::{Antichain, AntichainRef};
63
64use crate::columnar::batcher::{ColumnChunker, gallop};
65use crate::columnar::body::{ColumnBody, borrow_words};
66use crate::columnar::unload::UnloadChunk;
67use crate::columnar::{Column, at_serialized_capacity};
68
69pub mod metrics;
70
71static COMPUTE_SPILL_ENABLED: AtomicBool = AtomicBool::new(false);
73
74static STORAGE_SPILL_ENABLED: AtomicBool = AtomicBool::new(false);
76
77static SINK_SPILL_ENABLED: AtomicBool = AtomicBool::new(false);
80
81thread_local! {
82 static SPILL_OVERRIDE: RefCell<Option<Pool>> = const { RefCell::new(None) };
86
87 #[cfg(test)]
91 static COMPRESS_MIN_DEPTH_OVERRIDE: Cell<Option<u8>> = const { Cell::new(None) };
92
93 #[cfg(test)]
95 static SINK_COMPRESS_MIN_DEPTH_OVERRIDE: Cell<Option<u8>> = const { Cell::new(None) };
96
97 static READ_SCRATCH: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
99}
100
101pub trait SpillGate: 'static {
110 fn enabled() -> bool;
112}
113
114pub enum ComputeSpill {}
116
117impl SpillGate for ComputeSpill {
118 fn enabled() -> bool {
119 COMPUTE_SPILL_ENABLED.load(Ordering::Relaxed)
120 }
121}
122
123pub enum StorageSpill {}
126
127impl SpillGate for StorageSpill {
128 fn enabled() -> bool {
129 STORAGE_SPILL_ENABLED.load(Ordering::Relaxed)
130 }
131}
132
133pub fn set_compute_spill_enabled(enabled: bool) {
136 COMPUTE_SPILL_ENABLED.store(enabled, Ordering::Relaxed);
137}
138
139pub fn set_storage_spill_enabled(enabled: bool) {
142 STORAGE_SPILL_ENABLED.store(enabled, Ordering::Relaxed);
143}
144
145pub fn set_sink_spill_enabled(enabled: bool) {
150 SINK_SPILL_ENABLED.store(enabled, Ordering::Relaxed);
151}
152
153pub fn set_spill_override(pool: Option<Pool>) {
157 SPILL_OVERRIDE.with(|cell| *cell.borrow_mut() = pool);
158}
159
160static COMPRESS_MIN_DEPTH: AtomicU8 = AtomicU8::new(DEFAULT_COMPRESS_MIN_DEPTH);
163
164pub fn set_compress_min_depth(depth: u8) {
183 COMPRESS_MIN_DEPTH.store(depth, Ordering::Relaxed);
184}
185
186#[cfg(test)]
190pub fn set_compress_min_depth_override(depth: Option<u8>) {
191 COMPRESS_MIN_DEPTH_OVERRIDE.with(|cell| cell.set(depth));
192}
193
194fn compress_min_depth() -> u8 {
196 #[cfg(test)]
197 if let Some(depth) = COMPRESS_MIN_DEPTH_OVERRIDE.with(|cell| cell.get()) {
198 return depth;
199 }
200 COMPRESS_MIN_DEPTH.load(Ordering::Relaxed)
201}
202
203static SINK_COMPRESS_MIN_DEPTH: AtomicU8 = AtomicU8::new(DEFAULT_COMPRESS_MIN_DEPTH);
206
207pub fn set_sink_compress_min_depth(depth: u8) {
214 SINK_COMPRESS_MIN_DEPTH.store(depth, Ordering::Relaxed);
215}
216
217#[cfg(test)]
219pub fn set_sink_compress_min_depth_override(depth: Option<u8>) {
220 SINK_COMPRESS_MIN_DEPTH_OVERRIDE.with(|cell| cell.set(depth));
221}
222
223fn sink_compress_min_depth() -> u8 {
225 #[cfg(test)]
226 if let Some(depth) = SINK_COMPRESS_MIN_DEPTH_OVERRIDE.with(|cell| cell.get()) {
227 return depth;
228 }
229 SINK_COMPRESS_MIN_DEPTH.load(Ordering::Relaxed)
230}
231
232fn codec_for_depth(depth: u8, floor: u8) -> (&'static dyn ExtentCodec, bool) {
237 if depth < floor {
238 (&IDENTITY_CODEC, false)
239 } else {
240 (&LZ4_CODEC, true)
241 }
242}
243
244fn spill_target(enabled: bool, len_bytes: usize) -> Option<Pool> {
250 resolve_pool(enabled).filter(|_| len_bytes >= SPILL_MIN_BYTES)
251}
252
253fn resolve_pool(enabled: bool) -> Option<Pool> {
255 if let Some(pool) = SPILL_OVERRIDE.with(|cell| cell.borrow().clone()) {
256 return Some(pool);
257 }
258 if enabled {
259 crate::pool_config::active_pool()
260 } else {
261 None
262 }
263}
264
265const SCRATCH_RETAIN_WORDS: usize = 1 << 18;
269
270fn with_scratch<Out>(f: impl FnOnce(&mut Vec<u64>) -> Out) -> Out {
272 READ_SCRATCH.with(|cell| {
273 let mut scratch = cell.take();
274 scratch.clear();
275 let out = f(&mut scratch);
276 if scratch.capacity() > SCRATCH_RETAIN_WORDS {
277 scratch.clear();
278 scratch.shrink_to_fit();
279 }
280 cell.replace(scratch);
281 out
282 })
283}
284
285const COMMIT_BYTES: usize = 2 << 20;
288
289const SPILL_MIN_BYTES: usize = 64 << 10;
298
299const DEFAULT_COMPRESS_MIN_DEPTH: u8 = 1;
308
309fn cut_records(len: usize, bytes: usize, space: usize) -> usize {
315 let space = space.saturating_sub(COMMIT_BYTES / 20);
316 (len.saturating_mul(space) / bytes.max(1)).min(len)
317}
318
319fn at_commit_size<C: Columnar>(body: &ColumnBody<C>) -> bool {
321 body.length_in_bytes() >= COMMIT_BYTES - COMMIT_BYTES / 10
322}
323
324#[inline(always)]
328fn rr<'b, 'a: 'b, C: Columnar>(item: columnar::Ref<'a, C>) -> columnar::Ref<'b, C> {
329 columnar::ContainerOf::<C>::reborrow_ref(item)
330}
331
332pub struct SpilledBody<D: Columnar, T, G> {
338 records: usize,
340 fences: D::Container,
344 time_bounds: Arc<OnceLock<TimeBounds<T>>>,
350 compressed: bool,
357 len_bytes: usize,
362 handle: ChunkHandle,
364 gate: PhantomData<G>,
367}
368
369pub enum ColumnChunk<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> {
388 Resident(Rc<ColumnBody<(D, T, R)>>, u8),
390 Spilled(Rc<SpilledBody<D, T, G>>, u8),
392}
393
394impl<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> Clone for ColumnChunk<D, T, R, G> {
395 fn clone(&self) -> Self {
396 match self {
397 ColumnChunk::Resident(col, depth) => ColumnChunk::Resident(Rc::clone(col), *depth),
398 ColumnChunk::Spilled(body, depth) => ColumnChunk::Spilled(Rc::clone(body), *depth),
399 }
400 }
401}
402
403impl<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> Default for ColumnChunk<D, T, R, G> {
404 fn default() -> Self {
405 ColumnChunk::Resident(Rc::new(ColumnBody::default()), 0)
406 }
407}
408
409impl<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> Accountable for ColumnChunk<D, T, R, G> {
410 fn record_count(&self) -> i64 {
411 i64::try_from(self.records()).expect("record count fits i64")
412 }
413}
414
415impl<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> ColumnChunk<D, T, R, G> {
416 pub fn from_body(body: ColumnBody<(D, T, R)>) -> Self {
419 mz_ore::soft_assert_no_log!(!body.is_empty(), "chunks must be non-empty");
420 ColumnChunk::Resident(Rc::new(body), 0)
421 }
422
423 fn push_bounded(body: ColumnBody<(D, T, R)>, depth: u8, out: &mut VecDeque<Self>) {
427 let len = body.len();
428 let bytes = body.length_in_bytes();
429 if len <= 1 || bytes <= COMMIT_BYTES {
430 if len > 0 {
431 out.push_back(Self::Resident(Rc::new(body), depth));
432 }
433 return;
434 }
435 Self::push_cuts(
436 &body,
437 cut_records(len, bytes, COMMIT_BYTES).max(1),
438 depth,
439 out,
440 );
441 }
442
443 fn push_cuts(
450 body: &ColumnBody<(D, T, R)>,
451 records: usize,
452 depth: u8,
453 out: &mut VecDeque<Self>,
454 ) {
455 let view = body.borrow();
456 Self::push_range(view, 0..view.len(), records, depth, out);
457 }
458
459 fn push_range(
464 view: BorrowedOf<'_, (D, T, R)>,
465 range: std::ops::Range<usize>,
466 records: usize,
467 depth: u8,
468 out: &mut VecDeque<Self>,
469 ) {
470 let mut start = range.start;
471 while start < range.end {
472 let end = range.end.min(start + records);
473 let mut part = <(D, T, R) as Columnar>::Container::default();
474 part.extend_from_self(view, start..end);
475 let part = ColumnBody::Typed(part);
476 if end - start > 1 && part.length_in_bytes() > COMMIT_BYTES {
477 drop(part);
478 Self::push_range(view, start..end, (end - start).div_ceil(2), depth, out);
479 } else {
480 out.push_back(Self::Resident(Rc::new(part), depth));
481 }
482 start = end;
483 }
484 }
485
486 pub fn into_body(self) -> ColumnBody<(D, T, R)> {
489 match self {
490 ColumnChunk::Resident(col, _) => {
491 Rc::try_unwrap(col).unwrap_or_else(|shared| shared.duplicate())
492 }
493 ColumnChunk::Spilled(body, _) => match Rc::try_unwrap(body) {
494 Ok(spilled) => match spilled.handle.take_typed() {
495 Ok(typed) => {
496 typed
497 .into_any()
498 .downcast::<PooledBody<D, T, R>>()
499 .expect("chunk bodies are pooled as `PooledBody`")
500 .body
501 }
502 Err(handle) => read_words(&handle),
503 },
504 Err(shared) => shared.handle.with_typed(|typed| match typed {
507 Some(typed) => pooled::<D, T, R>(typed).body.duplicate(),
508 None => read_words(&shared.handle),
509 }),
510 },
511 }
512 }
513
514 pub fn with_body<F, X>(&self, f: F) -> X
517 where
518 F: FnOnce(&ColumnBody<(D, T, R)>) -> X,
519 {
520 match self {
521 ColumnChunk::Resident(col, _) => f(col),
522 ColumnChunk::Spilled(body, _) => {
523 let mut f = Some(f);
524 let borrowed = body.handle.with_typed(|typed| {
525 typed.map(|typed| f.take().expect("unused")(&pooled::<D, T, R>(typed).body))
526 });
527 match borrowed {
528 Some(out) => out,
529 None => f.take().expect("unused")(&read_words(&body.handle)),
530 }
531 }
532 }
533 }
534
535 pub fn is_spilled(&self) -> bool {
537 matches!(self, ColumnChunk::Spilled(_, _))
538 }
539
540 fn records(&self) -> usize {
542 match self {
543 ColumnChunk::Resident(col, _) => col.len(),
544 ColumnChunk::Spilled(body, _) => body.records,
545 }
546 }
547
548 fn depth(&self) -> u8 {
550 match self {
551 ColumnChunk::Resident(_, depth) | ColumnChunk::Spilled(_, depth) => *depth,
552 }
553 }
554
555 fn data_span(&self) -> (columnar::Ref<'_, D>, columnar::Ref<'_, D>) {
557 match self {
558 ColumnChunk::Resident(col, _) => {
559 let data = col.borrow().0;
560 (data.get(0), data.get(data.len() - 1))
561 }
562 ColumnChunk::Spilled(body, _) => {
563 let fences = body.fences.borrow();
564 (fences.get(0), fences.get(1))
565 }
566 }
567 }
568
569 fn commit(body: ColumnBody<(D, T, R)>, depth: u8) -> Self
573 where
574 D: PoolColumnar,
575 T: Timestamp + PoolColumnar,
576 R: PoolColumnar,
577 {
578 let len_bytes = body.length_in_bytes();
579 metrics::record(metrics::Stage::Commit, body.len(), len_bytes);
580 mz_ore::soft_assert_no_log!(!body.is_empty(), "chunks must be non-empty");
581 match spill_target(G::enabled(), len_bytes) {
582 Some(pool) => Self::spill_body(body, &pool, depth),
583 None => ColumnChunk::Resident(Rc::new(body), depth),
584 }
585 }
586
587 fn spill_body(body: ColumnBody<(D, T, R)>, pool: &Pool, depth: u8) -> Self
595 where
596 D: PoolColumnar,
597 T: Timestamp + PoolColumnar,
598 R: PoolColumnar,
599 {
600 let (codec, compressed) = codec_for_depth(depth, compress_min_depth());
601 let len_bytes = body.length_in_bytes();
602 let view = body.borrow();
603 let records = view.len();
604 let mut fences = D::Container::default();
605 fences.push(view.0.get(0));
606 fences.push(view.0.get(records - 1));
607 let time_bounds = Arc::new(OnceLock::new());
608 let pooled = PooledBody {
609 body,
610 bounds: Arc::clone(&time_bounds),
611 compute: |body| {
612 let (lower, upper) = Self::time_bounds(body);
613 (lower, upper.into())
614 },
615 };
616 let handle = pool.insert_typed(Box::new(pooled), ChunkHints { depth }, codec);
617 ColumnChunk::Spilled(
618 Rc::new(SpilledBody {
619 records,
620 fences,
621 time_bounds,
622 compressed,
623 len_bytes,
624 handle,
625 gate: PhantomData,
626 }),
627 depth,
628 )
629 }
630
631 fn survive_merge(self) -> Self
647 where
648 D: PoolColumnar,
649 T: Timestamp + PoolColumnar,
650 R: PoolColumnar,
651 {
652 let depth = self.depth().saturating_add(1);
653 match self {
654 ColumnChunk::Resident(col, _) => ColumnChunk::Resident(col, depth),
655 ColumnChunk::Spilled(body, was) => {
656 let migrate = !body.compressed && depth >= compress_min_depth();
657 if !migrate || Rc::strong_count(&body) > 1 {
658 return ColumnChunk::Spilled(body, depth);
659 }
660 match resolve_pool(G::enabled()) {
661 Some(pool) => {
662 let body = ColumnChunk::Spilled(body, was).into_body();
663 Self::spill_body(body, &pool, depth)
664 }
665 None => ColumnChunk::Spilled(body, depth),
666 }
667 }
668 }
669 }
670
671 fn chunk_time_bounds(&self) -> (Cow<'_, Antichain<T>>, Cow<'_, [T]>)
676 where
677 T: Timestamp,
678 {
679 match self {
680 ColumnChunk::Resident(col, _) => {
681 let (lower, upper) = Self::time_bounds(col);
682 (Cow::Owned(lower), Cow::Owned(upper))
683 }
684 ColumnChunk::Spilled(body, _) => {
685 if body.time_bounds.get().is_none() {
690 let filled = body.handle.with_typed(|typed| {
691 typed
692 .map(|typed| pooled::<D, T, R>(typed).bounds())
693 .is_some()
694 });
695 if !filled {
698 let (lower, upper) = Self::time_bounds(&read_words(&body.handle));
699 let _ = body.time_bounds.set((lower, upper.into()));
700 }
701 }
702 let (lower, upper) = body.time_bounds.get().expect("time bounds filled above");
703 (Cow::Borrowed(lower), Cow::Borrowed(&upper[..]))
704 }
705 }
706 }
707
708 fn time_bounds(body: &ColumnBody<(D, T, R)>) -> (Antichain<T>, Vec<T>)
713 where
714 T: Timestamp,
715 {
716 let (_, times, _) = body.borrow();
717 let mut lower = Antichain::new();
718 let mut upper: Vec<T> = Vec::new();
719 let mut time = T::minimum();
723 for i in 0..times.len() {
724 time.copy_from(rr::<T>(times.get(i)));
725 if !upper.iter().any(|u| PartialOrder::less_equal(&time, u)) {
726 upper.retain(|u| !PartialOrder::less_equal(u, &time));
727 upper.push(time.clone());
728 }
729 lower.insert_ref(&time);
730 }
731 (lower, upper)
732 }
733}
734
735#[derive(Debug)]
740pub struct Lz4Codec;
741
742pub static LZ4_CODEC: Lz4Codec = Lz4Codec;
745
746impl ExtentCodec for Lz4Codec {
747 fn encode(&self, body: &[u8], out: &mut Vec<u8>) {
748 let max_out = lz4_flex::block::get_maximum_output_size(body.len());
749 out.resize(4 + max_out, 0);
750 let len = u32::try_from(body.len()).expect("chunk bodies are bounded by the size classes");
751 out[..4].copy_from_slice(&len.to_le_bytes());
752 let compressed = lz4_flex::block::compress_into(body, &mut out[4..])
753 .expect("output sized to the maximum");
754 out.truncate(4 + compressed);
755 }
756
757 fn decode(&self, stored: &[u8], body: &mut [u8]) {
758 let prefix: [u8; 4] = stored[..4].try_into().expect("prefix length");
759 let len = usize::try_from(u32::from_le_bytes(prefix)).expect("length fits usize");
760 assert_eq!(
761 len,
762 body.len(),
763 "destination must match the encoded body length"
764 );
765 let written = lz4_flex::block::decompress_into(&stored[4..], body)
766 .expect("stored bytes hold a valid lz4 block");
767 assert_eq!(written, body.len(), "decoded length mismatch");
768 }
769}
770
771type TimeBounds<T> = (Antichain<T>, SmallVec<[T; 1]>);
774
775pub trait PoolColumnar: Columnar<Container: Send> + Send + Sync {}
779
780impl<C: Columnar<Container: Send> + Send + Sync> PoolColumnar for C {}
781
782struct PooledBody<D: Columnar, T: Columnar, R: Columnar> {
790 body: ColumnBody<(D, T, R)>,
791 bounds: Arc<OnceLock<TimeBounds<T>>>,
792 compute: fn(&ColumnBody<(D, T, R)>) -> TimeBounds<T>,
793}
794
795impl<D: Columnar, T: Columnar, R: Columnar> PooledBody<D, T, R> {
796 fn bounds(&self) -> &TimeBounds<T> {
797 self.bounds.get_or_init(|| (self.compute)(&self.body))
798 }
799}
800
801impl<D: Columnar, T: Columnar, R: Columnar> std::fmt::Debug for PooledBody<D, T, R> {
802 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
803 f.debug_struct("PooledBody")
804 .field("len_bytes", &self.body.length_in_bytes())
805 .finish()
806 }
807}
808
809impl<D: PoolColumnar + 'static, T: PoolColumnar + 'static, R: PoolColumnar + 'static> TypedBody
810 for PooledBody<D, T, R>
811{
812 fn words(&self) -> usize {
813 self.body.length_in_bytes() / 8
814 }
815
816 fn serialize_into(&self, dst: &mut [u64]) {
817 self.bounds();
818 let len_bytes = self.body.length_in_bytes();
819 let bytes: &mut [u8] = bytemuck::cast_slice_mut(dst);
820 let mut cursor = std::io::Cursor::new(bytes);
821 self.body
822 .write_into(&mut cursor)
823 .expect("the destination is sized to the serialized body");
824 assert_eq!(
825 usize::try_from(cursor.position()).expect("usize position"),
826 len_bytes,
827 "serialized body must fill the destination exactly",
828 );
829 }
830
831 fn as_any(&self) -> &dyn std::any::Any {
832 self
833 }
834
835 fn into_any(self: Box<Self>) -> Box<dyn std::any::Any> {
836 self
837 }
838}
839
840fn read_words<C: Columnar>(handle: &ChunkHandle) -> ColumnBody<C> {
842 let mut words = Vec::new();
843 handle.read_into(&mut words);
844 ColumnBody::Words(words)
845}
846
847fn pooled<D: Columnar + 'static, T: Columnar + 'static, R: Columnar + 'static>(
849 typed: &dyn TypedBody,
850) -> &PooledBody<D, T, R> {
851 typed
852 .as_any()
853 .downcast_ref::<PooledBody<D, T, R>>()
854 .expect("chunk bodies are pooled as `PooledBody`")
855}
856
857fn spill_serialized<C: Columnar>(
861 body: &ColumnBody<C>,
862 pool: &Pool,
863 len_bytes: usize,
864 hints: ChunkHints,
865 codec: &'static dyn ExtentCodec,
866) -> ChunkHandle {
867 mz_ore::soft_assert_eq_no_log!(len_bytes % 8, 0);
868 pool.insert_with(len_bytes / 8, hints, codec, |dst| {
869 let bytes: &mut [u8] = bytemuck::cast_slice_mut(dst);
870 let mut cursor = std::io::Cursor::new(bytes);
871 body.write_into(&mut cursor)
872 .expect("the slot is sized to the serialized body");
873 assert_eq!(
874 usize::try_from(cursor.position()).expect("usize position"),
875 len_bytes,
876 "serialized body must fill the chunk exactly",
877 );
878 })
879}
880
881pub fn try_spill_ref<C: Columnar>(body: &ColumnBody<C>, depth: u8) -> Option<ChunkHandle> {
895 let len_bytes = body.length_in_bytes();
896 let pool = spill_target(SINK_SPILL_ENABLED.load(Ordering::Relaxed), len_bytes)?;
897 let (codec, _) = codec_for_depth(depth, sink_compress_min_depth());
898 Some(spill_serialized(
899 body,
900 &pool,
901 len_bytes,
902 ChunkHints { depth },
903 codec,
904 ))
905}
906
907impl<D, T, R, G> Chunk for ColumnChunk<D, T, R, G>
908where
909 G: SpillGate,
910 D: PoolColumnar,
911 for<'a> columnar::Ref<'a, D>: Copy + Ord,
912 T: PoolColumnar + Default + Timestamp + Lattice + Ord,
913 for<'a> columnar::Ref<'a, T>: Copy + Ord,
914 R: PoolColumnar + Default + Semigroup + for<'a> Semigroup<columnar::Ref<'a, R>>,
915{
916 type Time = T;
917
918 const TARGET: usize = 65536;
924
925 fn len(&self) -> usize {
926 self.records()
927 }
928
929 fn merge(in1: &mut VecDeque<Self>, in2: &mut VecDeque<Self>, out: &mut VecDeque<Self>) {
936 let (a_first, a_last) = in1
941 .front()
942 .expect("caller guarantees non-empty input")
943 .data_span();
944 let (b_first, b_last) = in2
945 .front()
946 .expect("caller guarantees non-empty input")
947 .data_span();
948 let a_low = rr::<D>(a_last) < rr::<D>(b_first);
949 let b_low = rr::<D>(b_last) < rr::<D>(a_first);
950 if a_low {
951 let chunk = in1.pop_front().expect("front observed above");
952 out.push_back(chunk.survive_merge());
953 return;
954 }
955 if b_low {
956 let chunk = in2.pop_front().expect("front observed above");
957 out.push_back(chunk.survive_merge());
958 return;
959 }
960
961 let a = in1.pop_front().expect("caller guarantees non-empty input");
962 let b = in2.pop_front().expect("caller guarantees non-empty input");
963 let depths = [a.depth(), b.depth()];
966 let out_depth = depths[0].max(depths[1]).saturating_add(1);
967 let keep = |chunk: &Self| match chunk {
972 ColumnChunk::Spilled(body, _) if !body.handle.is_typed() => Some(Rc::clone(body)),
973 _ => None,
974 };
975 let respill = [a.is_spilled(), b.is_spilled()];
976 let mut spill_a = keep(&a);
977 let mut spill_b = keep(&b);
978 let mut cols = [a.into_body(), b.into_body()];
979 let mut positions = [0usize, 0usize];
980 loop {
981 let mut result: ColumnBody<(D, T, R)> = ColumnBody::default();
982 let yielded = result.merge_from(&mut cols, &mut positions);
983 if !result.is_empty() {
984 out.push_back(ColumnChunk::Resident(Rc::new(result), out_depth));
985 }
986 if !yielded {
987 break;
988 }
989 }
990 metrics::record(metrics::Stage::Merge, positions[0] + positions[1], 0);
993 let [col_a, col_b] = &mut cols;
994 for (col, pos, depth, spilled, respill, queue) in [
998 (
999 col_a,
1000 positions[0],
1001 depths[0],
1002 &mut spill_a,
1003 respill[0],
1004 in1,
1005 ),
1006 (
1007 col_b,
1008 positions[1],
1009 depths[1],
1010 &mut spill_b,
1011 respill[1],
1012 in2,
1013 ),
1014 ] {
1015 let len = col.len();
1016 if pos == 0 && len > 0 {
1017 let chunk = match spilled.take() {
1020 Some(body) => ColumnChunk::Spilled(body, depth).survive_merge(),
1021 None if respill => Self::commit(std::mem::take(col), depth.saturating_add(1)),
1023 None => {
1024 ColumnChunk::Resident(Rc::new(std::mem::take(col)), depth).survive_merge()
1025 }
1026 };
1027 queue.push_front(chunk);
1028 } else if pos < len {
1029 let view = col.borrow();
1030 let mut rest = <(D, T, R) as Columnar>::Container::default();
1031 rest.extend_from_self(view, pos..len);
1032 queue.push_front(ColumnChunk::Resident(
1033 Rc::new(ColumnBody::Typed(rest)),
1034 depth,
1035 ));
1036 }
1037 }
1038 }
1039
1040 fn extract(
1044 input: &mut VecDeque<Self>,
1045 frontier: AntichainRef<T>,
1046 residual: &mut timely::progress::Antichain<T>,
1047 keep: &mut VecDeque<Self>,
1048 ship: &mut VecDeque<Self>,
1049 ) {
1050 let Some(chunk) = input.pop_front() else {
1051 return;
1052 };
1053 let (time_lower, time_upper) = chunk.chunk_time_bounds();
1059 if time_upper.iter().all(|t| !frontier.less_equal(t)) {
1060 ship.push_back(chunk);
1061 return;
1062 }
1063 if time_lower.elements().iter().all(|m| frontier.less_equal(m)) {
1064 for m in time_lower.elements() {
1067 residual.insert_ref(m);
1068 }
1069 keep.push_back(chunk);
1070 return;
1071 }
1072 let depth = chunk.depth();
1075 let mut col = chunk.into_body();
1076 let len = col.len();
1077 let mut pos = 0;
1078 let mut keep_col: ColumnBody<(D, T, R)> = ColumnBody::default();
1079 let mut ship_col: ColumnBody<(D, T, R)> = ColumnBody::default();
1080 let cut = |col: &mut ColumnBody<(D, T, R)>, queue: &mut VecDeque<Self>, force: bool| {
1086 if !col.is_empty() && (force || at_serialized_capacity(&col.borrow())) {
1087 queue.push_back(ColumnChunk::Resident(Rc::new(std::mem::take(col)), depth));
1088 }
1089 };
1090 while pos < len {
1091 col.extract(&mut pos, frontier, residual, &mut keep_col, &mut ship_col);
1092 if pos < len {
1093 cut(&mut keep_col, keep, false);
1094 cut(&mut ship_col, ship, false);
1095 }
1096 }
1097 cut(&mut keep_col, keep, true);
1098 cut(&mut ship_col, ship, true);
1099 }
1100
1101 fn advance(
1111 input: &mut VecDeque<Self>,
1112 frontier: AntichainRef<T>,
1113 done: bool,
1114 out: &mut VecDeque<Self>,
1115 ) {
1116 let Some(front) = input.pop_front() else {
1117 return;
1118 };
1119 let mut depth = front.depth();
1122 let mut base = front.into_body();
1126 {
1127 let base_c = base.typed_mut();
1128 for chunk in input.drain(..) {
1129 depth = depth.max(chunk.depth());
1130 let col = chunk.into_body();
1131 let view = col.borrow();
1132 base_c.extend_from_self(view, 0..view.len());
1133 }
1134 }
1135 let view = base.borrow();
1136 let total = view.len();
1137 if total == 0 {
1138 return;
1139 }
1140 let data = view.0;
1141
1142 if !done && data.get(0) == data.get(total - 1) {
1145 input.push_front(ColumnChunk::Resident(Rc::new(base), depth));
1146 return;
1147 }
1148
1149 let end = if done {
1152 total
1153 } else {
1154 let last = data.get(total - 1);
1155 let mut end = total - 1;
1156 while end > 0 && data.get(end - 1) == last {
1157 end -= 1;
1158 }
1159 end
1160 };
1161 metrics::record(metrics::Stage::Advance, end, 0);
1165
1166 let mut result = <(D, T, R) as Columnar>::Container::default();
1167 let mut scratch: Vec<(T, R)> = Vec::new();
1169 let mut index = 0;
1170 const CUT_CHECK_RECORDS: usize = 1024;
1179 let mut records_since_check = 0usize;
1180 while index < end {
1187 let group_d = data.get(index);
1188 scratch.clear();
1189 while index < end && data.get(index) == group_d {
1190 let (_, t, r) = view.get(index);
1191 let mut owned_t = T::into_owned(t);
1192 owned_t.advance_by(frontier);
1193 scratch.push((owned_t, R::into_owned(r)));
1194 index += 1;
1195 }
1196 scratch.sort_by(|a, b| a.0.cmp(&b.0));
1197 let mut run = scratch.drain(..).peekable();
1198 while let Some((t, mut r)) = run.next() {
1199 while run.peek().is_some_and(|(t2, _)| *t2 == t) {
1200 let (_, r2) = run.next().expect("peeked");
1201 r.plus_equals(&r2);
1202 }
1203 if !r.is_zero() {
1204 result.0.push(group_d);
1205 result.1.push(&t);
1206 result.2.push(&r);
1207 records_since_check += 1;
1208 if records_since_check >= CUT_CHECK_RECORDS {
1209 records_since_check = 0;
1210 if u64::cast_from(indexed::length_in_words(&result.borrow()))
1211 >= u64::cast_from(COMMIT_BYTES / 8)
1212 {
1213 out.push_back(ColumnChunk::Resident(
1214 Rc::new(ColumnBody::Typed(std::mem::take(&mut result))),
1215 depth,
1216 ));
1217 }
1218 }
1219 }
1220 }
1221 }
1222 if !result.is_empty() {
1223 out.push_back(ColumnChunk::Resident(
1224 Rc::new(ColumnBody::Typed(result)),
1225 depth,
1226 ));
1227 }
1228
1229 if end < total {
1231 let mut carry = <(D, T, R) as Columnar>::Container::default();
1232 carry.extend_from_self(view, end..total);
1233 input.push_front(ColumnChunk::Resident(
1234 Rc::new(ColumnBody::Typed(carry)),
1235 depth,
1236 ));
1237 }
1238 }
1239
1240 fn settle(input: &mut VecDeque<Self>, done: bool, out: &mut VecDeque<Self>) {
1246 Self::settle_graded(input, done, out, true)
1247 }
1248}
1249
1250impl<D, T, R, G> ColumnChunk<D, T, R, G>
1251where
1252 G: SpillGate,
1253 D: PoolColumnar,
1254 T: PoolColumnar + Timestamp,
1255 R: PoolColumnar,
1256 for<'a> columnar::Ref<'a, D>: Ord,
1257 for<'a> columnar::Ref<'a, T>: Ord,
1258{
1259 fn settle_graded(
1266 input: &mut VecDeque<Self>,
1267 done: bool,
1268 out: &mut VecDeque<Self>,
1269 commit: bool,
1270 ) {
1271 let mut acc: Option<(ColumnBody<(D, T, R)>, u8)> = None;
1275 while let Some(chunk) = input.pop_front() {
1276 let (rc, depth) = match chunk {
1277 spilled @ ColumnChunk::Spilled(_, _) => {
1278 if let Some((body, depth)) = acc.take() {
1279 out.push_back(Self::grade(body, depth, commit));
1280 }
1281 out.push_back(spilled);
1282 continue;
1283 }
1284 ColumnChunk::Resident(rc, depth) => (rc, depth),
1285 };
1286 if rc.length_in_bytes() > COMMIT_BYTES && rc.len() > 1 {
1287 let records = cut_records(rc.len(), rc.length_in_bytes(), COMMIT_BYTES).max(1);
1290 let mut pieces = VecDeque::new();
1291 Self::push_cuts(&rc, records, depth, &mut pieces);
1292 for piece in pieces.into_iter().rev() {
1293 input.push_front(piece);
1294 }
1295 continue;
1296 }
1297 let full = at_commit_size(&rc);
1298 let fits = acc.as_ref().is_some_and(|(body, _)| {
1301 body.length_in_bytes().saturating_add(rc.length_in_bytes()) <= COMMIT_BYTES
1302 });
1303 if !full
1304 && fits
1305 && let Some((mut body, acc_depth)) = acc.take()
1306 {
1307 let view = rc.borrow();
1308 body.typed_mut().extend_from_self(view, 0..view.len());
1309 let acc_depth = acc_depth.max(depth);
1310 if at_commit_size(&body) {
1311 out.push_back(Self::grade(body, acc_depth, commit));
1312 } else {
1313 acc = Some((body, acc_depth));
1314 }
1315 continue;
1316 }
1317 if let Some((mut body, acc_depth)) = acc.take() {
1323 let len = rc.len();
1324 let prefix = if full {
1325 0
1326 } else {
1327 let space = COMMIT_BYTES.saturating_sub(body.length_in_bytes());
1328 cut_records(len, rc.length_in_bytes(), space)
1329 };
1330 if prefix == 0 || prefix >= len {
1331 out.push_back(Self::grade(body, acc_depth, commit));
1332 } else {
1333 let view = rc.borrow();
1334 body.typed_mut().extend_from_self(view, 0..prefix);
1335 let mut rest = <(D, T, R) as Columnar>::Container::default();
1336 rest.extend_from_self(view, prefix..len);
1337 input.push_front(ColumnChunk::Resident(
1338 Rc::new(ColumnBody::Typed(rest)),
1339 depth,
1340 ));
1341 let acc_depth = acc_depth.max(depth);
1342 if body.length_in_bytes() > COMMIT_BYTES {
1343 let mut pieces = VecDeque::new();
1345 Self::push_bounded(body, acc_depth, &mut pieces);
1346 for piece in pieces {
1347 let ColumnChunk::Resident(piece, piece_depth) = piece else {
1348 unreachable!("push_bounded emits resident pieces");
1349 };
1350 let piece =
1351 Rc::try_unwrap(piece).unwrap_or_else(|piece| piece.duplicate());
1352 out.push_back(Self::grade(piece, piece_depth, commit));
1353 }
1354 } else {
1355 out.push_back(Self::grade(body, acc_depth, commit));
1356 }
1357 continue;
1358 }
1359 }
1360 let body = Rc::try_unwrap(rc).unwrap_or_else(|rc| rc.duplicate());
1361 if full {
1362 out.push_back(Self::grade(body, depth, commit));
1363 } else {
1364 acc = Some((body, depth));
1365 }
1366 }
1367 if let Some((body, depth)) = acc {
1368 if done {
1369 out.push_back(Self::grade(body, depth, commit));
1370 } else {
1371 input.push_front(ColumnChunk::Resident(Rc::new(body), depth));
1372 }
1373 }
1374 }
1375
1376 fn grade(body: ColumnBody<(D, T, R)>, depth: u8, commit: bool) -> Self {
1379 if commit {
1380 Self::commit(body, depth)
1381 } else {
1382 ColumnChunk::Resident(Rc::new(body), depth)
1383 }
1384 }
1385}
1386
1387fn extract_view_into<'v, 'p, K, V, T, R>(
1392 view: BorrowedOf<'v, ((K, V), T, R)>,
1393 probes: BorrowedOf<'p, K>,
1394 probe_index: &mut usize,
1395 staging: &mut <((K, V), T, R) as Columnar>::Container,
1396) where
1397 K: Columnar,
1398 V: Columnar,
1399 T: Columnar,
1400 R: Columnar,
1401 for<'b> columnar::Ref<'b, K>: Copy + Ord,
1402{
1403 let keys = view.0.0;
1404 let len = keys.len();
1405 let last = keys.get(len - 1);
1406 let count = probes.len();
1407 let mut pos = 0;
1408 while *probe_index < count {
1409 let probe = probes.get(*probe_index);
1410 mz_ore::soft_assert_no_log!(
1411 *probe_index == 0 || rr::<K>(probes.get(*probe_index - 1)) < rr::<K>(probe),
1412 "probe keys must be sorted and deduplicated"
1413 );
1414 if rr::<K>(probe) > rr::<K>(last) {
1415 return;
1416 }
1417 gallop(len, &mut pos, |i| rr::<K>(keys.get(i)) < rr::<K>(probe));
1418 let start = pos;
1419 while pos < len && rr::<K>(keys.get(pos)) == rr::<K>(probe) {
1420 pos += 1;
1421 }
1422 staging.extend_from_self(view, start..pos);
1423 if rr::<K>(probe) == rr::<K>(last) {
1424 return;
1425 }
1426 *probe_index += 1;
1427 }
1428}
1429
1430impl<K, V, T, R, G> UnloadChunk for ColumnChunk<(K, V), T, R, G>
1431where
1432 G: SpillGate,
1433 K: PoolColumnar,
1434 for<'a> columnar::Ref<'a, K>: Copy + Ord,
1435 V: PoolColumnar,
1436 for<'a> columnar::Ref<'a, V>: Copy + Ord,
1437 T: PoolColumnar + Default + Timestamp + Lattice + Ord,
1438 for<'a> columnar::Ref<'a, T>: Copy + Ord,
1439 R: PoolColumnar + Default + Semigroup + for<'a> Semigroup<columnar::Ref<'a, R>>,
1440{
1441 type Staging = <((K, V), T, R) as Columnar>::Container;
1444
1445 type Probes<'a> = BorrowedOf<'a, K>;
1448
1449 fn probe_count(probes: Self::Probes<'_>) -> usize {
1450 probes.len()
1451 }
1452
1453 fn locate(&self, probes: Self::Probes<'_>, probe_index: usize) -> std::cmp::Ordering {
1454 let probe = probes.get(probe_index);
1455 let (first, last) = self.data_span();
1458 let (first, last) = (first.0, last.0);
1459 if rr::<K>(probe) < rr::<K>(first) {
1460 std::cmp::Ordering::Less
1461 } else if rr::<K>(probe) > rr::<K>(last) {
1462 std::cmp::Ordering::Greater
1463 } else {
1464 std::cmp::Ordering::Equal
1465 }
1466 }
1467
1468 fn extract_into(
1469 &self,
1470 probes: Self::Probes<'_>,
1471 probe_index: &mut usize,
1472 staging: &mut Self::Staging,
1473 ) {
1474 match self {
1475 ColumnChunk::Resident(col, _) => {
1476 extract_view_into::<K, V, T, R>(col.borrow(), probes, probe_index, staging);
1477 }
1478 ColumnChunk::Spilled(body, _) => body.handle.with_typed(|typed| match typed {
1479 Some(typed) => {
1480 let view = pooled::<(K, V), T, R>(typed).body.borrow();
1481 extract_view_into::<K, V, T, R>(view, probes, probe_index, staging);
1482 }
1483 None => with_scratch(|scratch| {
1484 body.handle.read_into(scratch);
1490 let view = borrow_words::<((K, V), T, R)>(scratch);
1491 extract_view_into::<K, V, T, R>(view, probes, probe_index, staging);
1492 }),
1493 }),
1494 }
1495 }
1496
1497 fn fetch_into(&self, staging: &mut Self::Staging) {
1498 match self {
1499 ColumnChunk::Resident(col, _) => {
1500 let view = col.borrow();
1501 staging.extend_from_self(view, 0..view.len());
1502 }
1503 ColumnChunk::Spilled(body, _) => body.handle.with_typed(|typed| match typed {
1504 Some(typed) => {
1505 let view = pooled::<(K, V), T, R>(typed).body.borrow();
1506 staging.extend_from_self(view, 0..view.len());
1507 }
1508 None => with_scratch(|scratch| {
1509 body.handle.read_into(scratch);
1510 let view = borrow_words::<((K, V), T, R)>(scratch);
1511 staging.extend_from_self(view, 0..view.len());
1512 }),
1513 }),
1514 }
1515 }
1516}
1517
1518pub struct UnchunkBuilder<Bu, D: Columnar, T: Columnar, R: Columnar, G: SpillGate> {
1528 inner: Bu,
1529 _marker: std::marker::PhantomData<(D, T, R, G)>,
1530}
1531
1532impl<Bu: Default, D: Columnar, T: Columnar, R: Columnar, G: SpillGate> Default
1533 for UnchunkBuilder<Bu, D, T, R, G>
1534{
1535 fn default() -> Self {
1536 Self {
1537 inner: Bu::default(),
1538 _marker: std::marker::PhantomData,
1539 }
1540 }
1541}
1542
1543impl<Bu, D, T, R, G> differential_dataflow::trace::Builder for UnchunkBuilder<Bu, D, T, R, G>
1544where
1545 Bu: differential_dataflow::trace::Builder<Input = ColumnBody<(D, T, R)>> + ChainState,
1546 D: Columnar + 'static,
1547 T: Columnar + 'static,
1548 R: Columnar + 'static,
1549 G: SpillGate,
1550{
1551 type Input = ColumnChunk<D, T, R, G>;
1552 type Time = Bu::Time;
1553 type Output = Bu::Output;
1554
1555 fn push(&mut self, chunk: &mut Self::Input) {
1556 let mut body = std::mem::take(chunk).into_body();
1557 self.inner.push(&mut body);
1558 }
1559
1560 fn done(self) -> Option<Self::Output> {
1561 self.inner.done()
1562 }
1563}
1564
1565impl<Bu, D, T, R, G>
1566 differential_dataflow::trace::implementations::merge_batcher::Sealer<ColumnChunk<D, T, R, G>>
1567 for UnchunkBuilder<Bu, D, T, R, G>
1568where
1569 Bu: differential_dataflow::trace::Builder<Input = ColumnBody<(D, T, R)>> + ChainState,
1570 D: Columnar + 'static,
1571 T: Columnar + 'static,
1572 R: Columnar + 'static,
1573 G: SpillGate,
1574{
1575 type Output = Bu::Output;
1576
1577 fn seal(chain: &mut Vec<ColumnChunk<D, T, R, G>>) -> Option<Self::Output> {
1578 use differential_dataflow::trace::Builder;
1579
1580 let mut state = Bu::State::default();
1581 for chunk in chain.iter() {
1582 if !chunk.is_spilled() || Bu::wants_bodies() {
1587 chunk.with_body(|body| Bu::observe(&mut state, body));
1588 } else {
1589 Bu::observe_records(&mut state, chunk.records());
1590 }
1591 }
1592 let mut builder = Self {
1593 inner: Bu::from_state(state),
1594 _marker: std::marker::PhantomData,
1595 };
1596 for chunk in chain.iter_mut() {
1599 builder.push(chunk);
1600 }
1601 chain.clear();
1602 builder.done()
1603 }
1604}
1605
1606pub trait ChainState: differential_dataflow::trace::Builder {
1623 type State: Default;
1625
1626 fn wants_bodies() -> bool;
1630
1631 fn observe(state: &mut Self::State, input: &Self::Input);
1633
1634 fn observe_records(state: &mut Self::State, records: usize);
1637
1638 fn from_state(state: Self::State) -> Self;
1640}
1641
1642pub struct ChunkChunker<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> {
1645 inner: ColumnChunker<(D, T, R)>,
1646 ready: VecDeque<ColumnChunk<D, T, R, G>>,
1647 staged: ColumnChunk<D, T, R, G>,
1648}
1649
1650impl<D, T, R, G> Default for ChunkChunker<D, T, R, G>
1651where
1652 D: Columnar,
1653 T: Columnar,
1654 R: Columnar,
1655 G: SpillGate,
1656 ColumnChunker<(D, T, R)>: Default,
1657{
1658 fn default() -> Self {
1659 Self {
1660 inner: Default::default(),
1661 ready: VecDeque::new(),
1662 staged: Default::default(),
1663 }
1664 }
1665}
1666
1667impl<'a, D, T, R, G> PushInto<&'a mut Column<(D, T, R)>> for ChunkChunker<D, T, R, G>
1668where
1669 D: Columnar,
1670 T: Columnar,
1671 R: Columnar,
1672 G: SpillGate,
1673 ColumnChunker<(D, T, R)>: PushInto<&'a mut Column<(D, T, R)>>,
1674{
1675 fn push_into(&mut self, item: &'a mut Column<(D, T, R)>) {
1676 self.inner.push_into(item);
1677 }
1678}
1679
1680impl<D, T, R, G> ContainerBuilder for ChunkChunker<D, T, R, G>
1681where
1682 D: Columnar + 'static,
1683 T: Columnar + 'static,
1684 R: Columnar + 'static,
1685 G: SpillGate,
1686 ColumnChunker<(D, T, R)>: ContainerBuilder<Container = ColumnBody<(D, T, R)>>,
1687{
1688 type Container = ColumnChunk<D, T, R, G>;
1689
1690 fn extract(&mut self) -> Option<&mut Self::Container> {
1691 if self.ready.is_empty() {
1692 let body = self.inner.extract()?;
1693 ColumnChunk::push_bounded(std::mem::take(body), 0, &mut self.ready);
1694 }
1695 self.staged = self.ready.pop_front()?;
1696 Some(&mut self.staged)
1697 }
1698
1699 fn finish(&mut self) -> Option<&mut Self::Container> {
1700 if self.ready.is_empty() {
1701 let body = self.inner.finish()?;
1702 ColumnChunk::push_bounded(std::mem::take(body), 0, &mut self.ready);
1703 }
1704 self.staged = self.ready.pop_front()?;
1705 Some(&mut self.staged)
1706 }
1707}
1708
1709pub type AccountedChunkBatcher<D, T, R, G, S> =
1717 differential_dataflow::trace::implementations::merge_batcher::MergeBatcher<
1718 ChunkChunker<D, T, R, G>,
1719 AccountedChunkMerger<D, T, R, G>,
1720 S,
1721 >;
1722
1723pub type AccountedChunkChainBatcher<D, T, R, G> = crate::operator::ConsolidatingBatcher<
1726 ChunkChunker<D, T, R, G>,
1727 AccountedChunkMerger<D, T, R, G>,
1728>;
1729
1730pub struct AccountedChunkMerger<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> {
1743 inner: differential_dataflow::trace::chunk::ChunkMerger<ColumnChunk<D, T, R, G>>,
1744}
1745
1746impl<D: Columnar, T: Columnar, R: Columnar, G: SpillGate> Default
1747 for AccountedChunkMerger<D, T, R, G>
1748{
1749 fn default() -> Self {
1750 Self {
1751 inner: Default::default(),
1752 }
1753 }
1754}
1755
1756impl<D, T, R, G> differential_dataflow::trace::implementations::merge_batcher::Merger
1757 for AccountedChunkMerger<D, T, R, G>
1758where
1759 D: PoolColumnar + 'static,
1760 T: PoolColumnar + Timestamp + 'static,
1761 R: PoolColumnar + 'static,
1762 G: SpillGate,
1763 for<'a> columnar::Ref<'a, D>: Ord,
1764 for<'a> columnar::Ref<'a, T>: Ord,
1765 ColumnChunk<D, T, R, G>: Chunk,
1766 <ColumnChunk<D, T, R, G> as Chunk>::Time: Clone + PartialOrder + 'static,
1767{
1768 type Chunk = ColumnChunk<D, T, R, G>;
1769
1770 fn merge(
1771 &mut self,
1772 list1: Vec<Self::Chunk>,
1773 list2: Vec<Self::Chunk>,
1774 output: &mut Vec<Self::Chunk>,
1775 stash: &mut Vec<Self::Chunk>,
1776 ) {
1777 self.inner.merge(list1, list2, output, stash)
1778 }
1779
1780 fn len(chunk: &Self::Chunk) -> usize {
1781 Chunk::len(chunk)
1782 }
1783
1784 fn allocation(chunk: &Self::Chunk) -> (usize, usize, usize) {
1785 let bytes = match chunk {
1786 ColumnChunk::Resident(col, _) => col.length_in_bytes(),
1787 ColumnChunk::Spilled(body, _) => body.len_bytes,
1788 };
1789 (bytes, bytes, 1)
1790 }
1791}
1792
1793impl<D, T, R, G> differential_dataflow::trace::implementations::merge_batcher::Extractor
1794 for AccountedChunkMerger<D, T, R, G>
1795where
1796 D: PoolColumnar + 'static,
1797 T: PoolColumnar + Timestamp + 'static,
1798 R: PoolColumnar + 'static,
1799 G: SpillGate,
1800 for<'a> columnar::Ref<'a, D>: Ord,
1801 for<'a> columnar::Ref<'a, T>: Ord,
1802 ColumnChunk<D, T, R, G>: Chunk,
1803 <ColumnChunk<D, T, R, G> as Chunk>::Time: Clone + PartialOrder + 'static,
1804{
1805 type Time = <ColumnChunk<D, T, R, G> as Chunk>::Time;
1806
1807 fn extract(
1808 &mut self,
1809 merged: Vec<Self::Chunk>,
1810 upper: AntichainRef<Self::Time>,
1811 frontier: &mut Antichain<Self::Time>,
1812 readied: &mut Vec<Self::Chunk>,
1813 kept: &mut Vec<Self::Chunk>,
1814 _stash: &mut Vec<Self::Chunk>,
1815 ) {
1816 let mut input: VecDeque<Self::Chunk> = merged.into();
1824 let (mut keep, mut shipped) = (VecDeque::new(), VecDeque::new());
1825 let (mut kept_q, mut shipped_q) = (VecDeque::new(), VecDeque::new());
1826 while !input.is_empty() {
1827 Chunk::extract(&mut input, upper, frontier, &mut keep, &mut shipped);
1828 Chunk::settle(&mut keep, false, &mut kept_q);
1829 ColumnChunk::settle_graded(&mut shipped, false, &mut shipped_q, false);
1830 }
1831 Chunk::settle(&mut keep, true, &mut kept_q);
1832 ColumnChunk::settle_graded(&mut shipped, true, &mut shipped_q, false);
1833 Extend::extend(kept, kept_q);
1834 Extend::extend(readied, shipped_q);
1835 }
1836}
1837
1838#[cfg(test)]
1839mod tests {
1840 use differential_dataflow::batcher::Extract;
1850 use differential_dataflow::trace::chunk::ChunkBatch;
1851 use mz_ore::pool::Pool;
1852 use proptest::prelude::*;
1853 use timely::container::PushInto;
1854 use timely::progress::Antichain;
1855
1856 use crate::columnar::unload::UnloadBatch;
1857
1858 use super::*;
1859
1860 type Tuple = ((u64, u64), u64, i64);
1861 type TestChunk = ColumnChunk<(u64, u64), u64, i64, ComputeSpill>;
1862 type TestChunkBatcher = crate::operator::ConsolidatingBatcher<
1864 ChunkChunker<(u64, u64), u64, i64, ComputeSpill>,
1865 differential_dataflow::trace::chunk::ChunkMerger<TestChunk>,
1866 >;
1867
1868 #[mz_ore::test]
1873 fn lz4_codec_matches_the_previous_extent_framing() {
1874 let body: Vec<u8> = (0..100_000u32).flat_map(|i| i.to_le_bytes()).collect();
1875 let mut stored = Vec::new();
1876 LZ4_CODEC.encode(&body, &mut stored);
1877 assert_eq!(stored, lz4_flex::block::compress_prepend_size(&body));
1878 let mut round = vec![0u8; body.len()];
1879 LZ4_CODEC.decode(&stored, &mut round);
1880 assert_eq!(round, body);
1881 }
1882
1883 #[mz_ore::test]
1884 #[should_panic(expected = "destination must match")]
1885 fn lz4_codec_decode_length_mismatch_panics() {
1886 let mut stored = Vec::new();
1887 LZ4_CODEC.encode(&[7u8; 64], &mut stored);
1888 let mut short = vec![0u8; 32];
1889 LZ4_CODEC.decode(&stored, &mut short);
1890 }
1891
1892 fn consolidate(mut v: Vec<Tuple>) -> Vec<Tuple> {
1895 v.sort();
1896 let mut out: Vec<Tuple> = Vec::new();
1897 for (d, t, r) in v {
1898 if let Some(last) = out.last_mut() {
1899 if last.0 == d && last.1 == t {
1900 last.2 += r;
1901 continue;
1902 }
1903 }
1904 out.push((d, t, r));
1905 }
1906 out.retain(|x| x.2 != 0);
1907 out
1908 }
1909
1910 fn arb_consolidated() -> impl Strategy<Value = Vec<Tuple>> {
1911 prop::collection::vec(((0u64..5, 0u64..5), 0u64..4, -3i64..=3i64), 0..40)
1912 .prop_map(consolidate)
1913 }
1914
1915 fn build_column(v: &[Tuple]) -> ColumnBody<Tuple> {
1916 let mut col: ColumnBody<Tuple> = Default::default();
1917 for tup in v {
1918 col.push_into(*tup);
1919 }
1920 col
1921 }
1922
1923 fn collect_column(col: &ColumnBody<Tuple>) -> Vec<Tuple> {
1924 col.borrow()
1925 .into_index_iter()
1926 .map(|((k, v), t, r)| {
1927 (
1928 (u64::into_owned(k), u64::into_owned(v)),
1929 u64::into_owned(t),
1930 i64::into_owned(r),
1931 )
1932 })
1933 .collect()
1934 }
1935
1936 fn collect_chunks(chunks: impl IntoIterator<Item = TestChunk>) -> Vec<Tuple> {
1937 chunks
1938 .into_iter()
1939 .flat_map(|chunk| collect_column(&chunk.into_body()))
1940 .collect()
1941 }
1942
1943 fn collect_staging(staging: &<Tuple as Columnar>::Container) -> Vec<Tuple> {
1944 staging
1945 .borrow()
1946 .into_index_iter()
1947 .map(|((k, v), t, r)| {
1948 (
1949 (u64::into_owned(k), u64::into_owned(v)),
1950 u64::into_owned(t),
1951 i64::into_owned(r),
1952 )
1953 })
1954 .collect()
1955 }
1956
1957 fn chunked(data: &[Tuple], cuts: &[usize]) -> VecDeque<TestChunk> {
1959 let mut chunks = VecDeque::new();
1960 let mut start = 0;
1961 for cut in cuts {
1962 let end = (start + 1 + cut % 7).min(data.len());
1963 if end > start {
1964 chunks.push_back(ColumnChunk::from_body(build_column(&data[start..end])));
1965 start = end;
1966 }
1967 }
1968 if start < data.len() {
1969 chunks.push_back(ColumnChunk::from_body(build_column(&data[start..])));
1970 }
1971 chunks
1972 }
1973
1974 fn chunked_spilled(data: &[Tuple], cuts: &[usize], pool: &Pool) -> VecDeque<TestChunk> {
1977 chunked(data, cuts)
1978 .into_iter()
1979 .map(|chunk| force_spill(chunk, pool))
1980 .collect()
1981 }
1982
1983 fn body_compressed(chunk: &TestChunk) -> bool {
1987 match chunk {
1988 ColumnChunk::Spilled(body, _) => body.compressed,
1989 ColumnChunk::Resident(_, _) => panic!("chunk must be spilled"),
1990 }
1991 }
1992
1993 fn force_spill(chunk: TestChunk, pool: &Pool) -> TestChunk {
1996 let depth = chunk.depth();
1997 TestChunk::spill_body(chunk.into_body(), pool, depth)
1998 }
1999
2000 #[mz_ore::test]
2003 #[cfg_attr(miri, ignore)]
2004 fn allocation_reports_a_body_wherever_it_lives() {
2005 use differential_dataflow::trace::implementations::merge_batcher::Merger;
2006
2007 let data: Vec<Tuple> = (0..64u64).map(|i| ((i, i), 0, 1)).collect();
2008 let resident = TestChunk::from_body(build_column(&data));
2009 let (size, capacity, allocations) =
2010 AccountedChunkMerger::<(u64, u64), u64, i64, ComputeSpill>::allocation(&resident);
2011 assert!(size > 0, "a resident body reports its bytes");
2012 assert_eq!((capacity, allocations), (size, 1));
2013
2014 let spilled = force_spill(resident, &test_pool());
2015 assert_eq!(
2016 AccountedChunkMerger::<(u64, u64), u64, i64, ComputeSpill>::allocation(&spilled),
2017 (size, capacity, allocations),
2018 "spilling a body does not change what its owner holds"
2019 );
2020 }
2021
2022 #[mz_ore::test]
2031 #[cfg_attr(miri, ignore)]
2032 fn seal_readies_resident_chunks() {
2033 let data: Vec<Tuple> = (0..20_000u64).map(|i| ((i, i), 0, 1)).collect();
2037
2038 set_spill_override(Some(test_pool()));
2039 let mut batcher =
2040 AccountedChunkChainBatcher::<(u64, u64), u64, i64, ComputeSpill>::new(None, 0);
2041 batcher.push_chunk(TestChunk::from_body(build_column(&data)));
2042 let (chain, _frontier) = batcher.extract(Antichain::new().borrow());
2043 let chain = chain.unwrap_or_default();
2044 set_spill_override(None);
2045
2046 assert!(!chain.is_empty(), "the seal ships what was pushed");
2047 assert!(
2048 chain.iter().all(|chunk| !chunk.is_spilled()),
2049 "a chunk that arrived resident is readied resident"
2050 );
2051 }
2052
2053 fn test_pool() -> Pool {
2057 static POOL: std::sync::OnceLock<Pool> = std::sync::OnceLock::new();
2058 POOL.get_or_init(|| Pool::new().expect("pool creation"))
2059 .clone()
2060 }
2061
2062 proptest! {
2063 #[mz_ore::test]
2066 #[cfg_attr(miri, ignore)]
2067 fn batcher_round_trip(
2068 inputs in prop::collection::vec(arb_consolidated(), 1..6),
2069 cuts in prop::collection::vec(0usize..7, 0..8),
2070 ) {
2071 let mut batcher = TestChunkBatcher::new(None, 0);
2072 let mut union = Vec::new();
2073 for input in &inputs {
2074 Extend::extend(&mut union, input.iter().copied());
2075 for chunk in chunked(input, &cuts) {
2076 batcher.push_chunk(chunk);
2077 }
2078 }
2079 let (sealed, _frontier) = batcher.extract(Antichain::new().borrow());
2081 let sealed = sealed.unwrap_or_default();
2082 prop_assert_eq!(collect_chunks(sealed), consolidate(union));
2083 }
2084
2085 #[mz_ore::test]
2088 #[cfg_attr(miri, ignore)]
2089 fn batcher_round_trip_spilled(
2090 inputs in prop::collection::vec(arb_consolidated(), 1..4),
2091 cuts in prop::collection::vec(0usize..7, 0..6),
2092 ) {
2093 let pool = test_pool();
2094 let mut batcher = TestChunkBatcher::new(None, 0);
2095 let mut union = Vec::new();
2096 for input in &inputs {
2097 Extend::extend(&mut union, input.iter().copied());
2098 for chunk in chunked_spilled(input, &cuts, &pool) {
2099 batcher.push_chunk(chunk);
2100 }
2101 }
2102 let (sealed, _frontier) = batcher.extract(Antichain::new().borrow());
2103 let sealed = sealed.unwrap_or_default();
2104 prop_assert_eq!(collect_chunks(sealed), consolidate(union));
2105 }
2106
2107 #[mz_ore::test]
2110 #[cfg_attr(miri, ignore)]
2111 fn seal_partitions_by_time(
2112 input in arb_consolidated(),
2113 cuts in prop::collection::vec(0usize..7, 0..8),
2114 upper in 0u64..5,
2115 ) {
2116 let mut batcher = TestChunkBatcher::new(None, 0);
2117 for chunk in chunked(&input, &cuts) {
2118 batcher.push_chunk(chunk);
2119 }
2120 let (shipped, frontier) = batcher.extract(Antichain::from_elem(upper).borrow());
2121 let shipped = shipped.unwrap_or_default();
2122 let frontier = frontier.to_owned();
2123 let expected_shipped: Vec<Tuple> =
2124 input.iter().copied().filter(|(_, t, _)| *t < upper).collect();
2125 prop_assert_eq!(collect_chunks(shipped), consolidate(expected_shipped));
2126
2127 let kept_min = input.iter().filter(|(_, t, _)| *t >= upper).map(|(_, t, _)| *t).min();
2128 prop_assert_eq!(frontier.elements().first().copied(), kept_min);
2129
2130 let (rest, _frontier) = batcher.extract(Antichain::new().borrow());
2131 let rest = rest.unwrap_or_default();
2132 let expected_rest: Vec<Tuple> =
2133 input.iter().copied().filter(|(_, t, _)| *t >= upper).collect();
2134 prop_assert_eq!(collect_chunks(rest), consolidate(expected_rest));
2135 }
2136
2137 #[mz_ore::test]
2141 #[cfg_attr(miri, ignore)]
2142 fn seal_partitions_by_time_spilled(
2143 input in arb_consolidated(),
2144 cuts in prop::collection::vec(0usize..7, 0..8),
2145 upper in 0u64..5,
2146 ) {
2147 let pool = test_pool();
2148 let mut batcher = TestChunkBatcher::new(None, 0);
2149 for chunk in chunked_spilled(&input, &cuts, &pool) {
2150 batcher.push_chunk(chunk);
2151 }
2152 let (shipped, frontier) = batcher.extract(Antichain::from_elem(upper).borrow());
2153 let shipped = shipped.unwrap_or_default();
2154 let frontier = frontier.to_owned();
2155 let expected_shipped: Vec<Tuple> =
2156 input.iter().copied().filter(|(_, t, _)| *t < upper).collect();
2157 prop_assert_eq!(collect_chunks(shipped), consolidate(expected_shipped));
2158
2159 let kept_min = input.iter().filter(|(_, t, _)| *t >= upper).map(|(_, t, _)| *t).min();
2160 prop_assert_eq!(frontier.elements().first().copied(), kept_min);
2161
2162 let (rest, _frontier) = batcher.extract(Antichain::new().borrow());
2163 let rest = rest.unwrap_or_default();
2164 let expected_rest: Vec<Tuple> =
2165 input.iter().copied().filter(|(_, t, _)| *t >= upper).collect();
2166 prop_assert_eq!(collect_chunks(rest), consolidate(expected_rest));
2167 }
2168
2169 #[mz_ore::test]
2172 #[cfg_attr(miri, ignore)]
2173 fn advance_matches_reference(
2174 input in arb_consolidated(),
2175 cuts in prop::collection::vec(0usize..7, 0..8),
2176 frontier_elem in 0u64..5,
2177 ) {
2178 let frontier = Antichain::from_elem(frontier_elem);
2179 let mut chunks = chunked(&input, &cuts);
2180 let mut out = VecDeque::new();
2181 TestChunk::advance(&mut chunks, frontier.borrow(), false, &mut out);
2182 TestChunk::advance(&mut chunks, frontier.borrow(), true, &mut out);
2183 prop_assert!(chunks.is_empty());
2184
2185 let expected = consolidate(
2186 input
2187 .iter()
2188 .map(|&(d, mut t, r)| {
2189 t.advance_by(frontier.borrow());
2190 (d, t, r)
2191 })
2192 .collect(),
2193 );
2194 prop_assert_eq!(collect_chunks(out), expected);
2195 }
2196
2197 #[mz_ore::test]
2200 #[cfg_attr(miri, ignore)]
2201 fn settle_preserves_and_packs(
2202 input in arb_consolidated(),
2203 cuts in prop::collection::vec(0usize..7, 1..8),
2204 ) {
2205 let mut chunks = chunked(&input, &cuts);
2206 let mut out = VecDeque::new();
2207 TestChunk::settle(&mut chunks, true, &mut out);
2208 prop_assert!(chunks.is_empty());
2209 prop_assert!(out.len() <= 1);
2212 prop_assert_eq!(collect_chunks(out), input);
2213 }
2214
2215 #[mz_ore::test]
2219 #[cfg_attr(miri, ignore)]
2220 fn unload_extract_matches_filter(
2221 input in arb_consolidated(),
2222 cuts in prop::collection::vec(0usize..7, 0..8),
2223 probe_keys in prop::collection::btree_set(0u64..6, 0..6),
2224 spill in any::<bool>(),
2225 ) {
2226 prop_assume!(!input.is_empty());
2227 let pool = test_pool();
2228 let chunks: Vec<TestChunk> = if spill {
2229 chunked_spilled(&input, &cuts, &pool).into()
2230 } else {
2231 chunked(&input, &cuts).into()
2232 };
2233 let batch = ChunkBatch::new(chunks);
2234
2235 let mut probe_col = <u64 as Columnar>::Container::default();
2236 for key in &probe_keys {
2237 probe_col.push(*key);
2238 }
2239 let mut staging = <Tuple as Columnar>::Container::default();
2240 batch.extract_into(probe_col.borrow(), &mut staging);
2241
2242 let expected: Vec<Tuple> = input
2243 .iter()
2244 .copied()
2245 .filter(|((k, _), _, _)| probe_keys.contains(k))
2246 .collect();
2247 prop_assert_eq!(collect_staging(&staging), expected);
2248
2249 let mut staging = <Tuple as Columnar>::Container::default();
2252 batch.fetch_into(&mut staging);
2253 prop_assert_eq!(collect_staging(&staging), input);
2254 }
2255 }
2256
2257 #[mz_ore::test]
2260 fn locate_spans_keys() {
2261 let chunk = TestChunk::from_body(build_column(&[
2262 ((2, 0), 0, 1),
2263 ((4, 0), 0, 1),
2264 ((6, 0), 0, 1),
2265 ]));
2266 let mut probe_col = <u64 as Columnar>::Container::default();
2267 for key in [0u64, 2, 3, 6, 9] {
2268 probe_col.push(key);
2269 }
2270 let probes = probe_col.borrow();
2271 use std::cmp::Ordering::*;
2272 let expected = [Less, Equal, Equal, Equal, Greater];
2273 for (index, expected) in expected.iter().enumerate() {
2274 assert_eq!(chunk.locate(probes, index), *expected, "probe {index}");
2275 }
2276 }
2277
2278 fn collect_bounded(chunks: impl IntoIterator<Item = TestChunk>, bound: usize) -> Vec<Tuple> {
2281 let mut collected = Vec::new();
2282 for chunk in chunks {
2283 let col = chunk.into_body();
2284 let bytes = col.length_in_bytes();
2285 assert!(bytes <= bound, "chunk of {bytes} bytes exceeds {bound}");
2286 Extend::extend(&mut collected, collect_column(&col));
2287 }
2288 collected
2289 }
2290
2291 type WideUpdate = ((u64, String), u64, i64);
2292 type WideChunk = ColumnChunk<(u64, String), u64, i64, ComputeSpill>;
2293
2294 fn wide_column(keys: impl Iterator<Item = u64>, bytes: usize) -> ColumnBody<WideUpdate> {
2295 let mut column = ColumnBody::default();
2296 for key in keys {
2297 column.push_into(&((key, "x".repeat(bytes)), 0, 1));
2298 }
2299 column
2300 }
2301
2302 fn assert_wide_byte_bound(chunks: VecDeque<WideChunk>, expected: usize, payload_bytes: usize) {
2303 let mut keys = Vec::new();
2304 for chunk in chunks {
2305 let column = chunk.into_body();
2306 assert!(
2307 column.length_in_bytes() <= COMMIT_BYTES || column.len() == 1,
2308 "{} bytes in a {}-record chunk",
2309 column.length_in_bytes(),
2310 column.len(),
2311 );
2312 let view = column.borrow();
2313 for index in 0..view.len() {
2314 let ((key, payload), time, diff) = view.get(index);
2315 assert_eq!(payload.len(), payload_bytes);
2316 assert!(payload.iter().all(|byte| *byte == b'x'));
2317 assert_eq!((*time, *diff), (0, 1));
2318 keys.push(*key);
2319 }
2320 }
2321 assert_eq!(keys, (0..u64::cast_from(expected)).collect::<Vec<_>>());
2322 }
2323
2324 #[mz_ore::test]
2325 fn chunker_enforces_byte_bound() {
2326 let mut chunker = ChunkChunker::default();
2327 let mut input: Column<WideUpdate> = wide_column((0..4000).rev(), 3000).into();
2328 chunker.push_into(&mut input);
2329 let mut chunks = VecDeque::new();
2330 if let Some(chunk) = chunker.extract() {
2331 chunks.push_back(std::mem::take(chunk));
2332 }
2333 while let Some(chunk) = chunker.finish() {
2334 chunks.push_back(std::mem::take(chunk));
2335 }
2336 assert_wide_byte_bound(chunks, 4000, 3000);
2337 }
2338
2339 #[mz_ore::test]
2340 fn merge_settle_enforces_byte_bound() {
2341 let mut left = VecDeque::from([WideChunk::from_body(wide_column(
2342 (0..2000).step_by(2),
2343 2100,
2344 ))]);
2345 let mut right = VecDeque::from([WideChunk::from_body(wide_column(
2346 (1..2000).step_by(2),
2347 2100,
2348 ))]);
2349 let mut merged = VecDeque::new();
2350 while !left.is_empty() && !right.is_empty() {
2351 WideChunk::merge(&mut left, &mut right, &mut merged);
2352 }
2353 merged.append(&mut left);
2354 merged.append(&mut right);
2355 let mut settled = VecDeque::new();
2356 WideChunk::settle(&mut merged, true, &mut settled);
2357 assert_wide_byte_bound(settled, 2000, 2100);
2358 }
2359
2360 #[mz_ore::test]
2361 fn settle_enforces_byte_bound_after_coalescing() {
2362 let mut input = VecDeque::from([
2363 WideChunk::from_body(wide_column(0..400, 3000)),
2364 WideChunk::from_body(wide_column(400..800, 3000)),
2365 ]);
2366 let mut settled = VecDeque::new();
2367 WideChunk::settle(&mut input, true, &mut settled);
2368 assert_wide_byte_bound(settled, 800, 3000);
2369 }
2370
2371 #[mz_ore::test]
2372 fn settle_byte_bound_allows_indivisible_update() {
2373 let mut input = VecDeque::from([WideChunk::from_body(wide_column(0..1, 2 * COMMIT_BYTES))]);
2374 let mut settled = VecDeque::new();
2375 WideChunk::settle(&mut input, true, &mut settled);
2376 assert_wide_byte_bound(settled, 1, 2 * COMMIT_BYTES);
2377 }
2378
2379 #[mz_ore::test]
2383 fn push_bounded_splits_uneven_widths() {
2384 let mut column: ColumnBody<WideUpdate> = ColumnBody::default();
2385 column.push_into(&((0, "x".repeat(COMMIT_BYTES - 4096)), 0, 1));
2386 for key in 1..20_000u64 {
2387 column.push_into(&((key, "x".to_string()), 0, 1));
2388 }
2389 assert!(column.length_in_bytes() > COMMIT_BYTES);
2390 let mut out = VecDeque::new();
2391 WideChunk::push_bounded(column, 3, &mut out);
2392 let mut keys = Vec::new();
2393 for chunk in out {
2394 let ColumnChunk::Resident(_, depth) = &chunk else {
2395 panic!("pieces are resident");
2396 };
2397 assert_eq!(*depth, 3, "pieces keep the input's depth");
2398 let column = chunk.into_body();
2399 assert!(
2400 column.length_in_bytes() <= COMMIT_BYTES || column.len() == 1,
2401 "{} bytes in a {}-record piece",
2402 column.length_in_bytes(),
2403 column.len(),
2404 );
2405 let view = column.borrow();
2406 for index in 0..view.len() {
2407 let ((key, _), _, _) = view.get(index);
2408 keys.push(*key);
2409 }
2410 }
2411 assert_eq!(keys, (0..20_000u64).collect::<Vec<_>>());
2412 }
2413
2414 #[mz_ore::test]
2418 fn merge_output_within_byte_bound_before_settle() {
2419 let interleaved = (
2420 wide_column((0..1600).step_by(2), 2100),
2421 wide_column((1..1600).step_by(2), 2100),
2422 );
2423 let runs = (
2424 wide_column((0..500).chain(1000..1100), 2100),
2425 wide_column(500..1000, 2100),
2426 );
2427 for (left, right) in [interleaved, runs] {
2428 let expected = left.len() + right.len();
2429 let mut left = VecDeque::from([WideChunk::from_body(left)]);
2430 let mut right = VecDeque::from([WideChunk::from_body(right)]);
2431 let mut merged = VecDeque::new();
2432 while !left.is_empty() && !right.is_empty() {
2433 WideChunk::merge(&mut left, &mut right, &mut merged);
2434 }
2435 assert!(merged.len() > 1, "merge never cut its output");
2436 merged.append(&mut left);
2437 merged.append(&mut right);
2438 assert_wide_byte_bound(merged, expected, 2100);
2439 }
2440 }
2441
2442 #[mz_ore::test]
2443 fn settle_split_preserves_depth() {
2444 let column = Rc::new(wide_column(0..2000, 2100));
2445 let shared = Rc::clone(&column);
2446 let mut input = VecDeque::from([WideChunk::Resident(column, 3)]);
2447 let mut settled = VecDeque::new();
2448 WideChunk::settle(&mut input, true, &mut settled);
2449 assert!(settled.len() > 1, "oversized chunk was not split");
2450 for chunk in &settled {
2451 assert_eq!(chunk.depth(), 3, "split piece changed generation");
2452 }
2453 assert_eq!(shared.len(), 2000, "shared body was mutated");
2454 assert_wide_byte_bound(settled, 2000, 2100);
2455 }
2456
2457 #[mz_ore::test]
2460 fn settle_split_then_coalesce_keeps_depth() {
2461 let mut input = VecDeque::from([
2462 WideChunk::Resident(Rc::new(wide_column(0..800, 3000)), 2),
2463 WideChunk::Resident(Rc::new(wide_column(800..810, 3000)), 0),
2464 ]);
2465 let mut settled = VecDeque::new();
2466 WideChunk::settle(&mut input, true, &mut settled);
2467 assert!(settled.len() > 1, "oversized chunk was not split");
2468 for chunk in &settled {
2469 assert_eq!(chunk.depth(), 2, "coalescing lost the deeper generation");
2470 }
2471 assert_wide_byte_bound(settled, 810, 3000);
2472 }
2473
2474 #[mz_ore::test]
2478 fn settle_fills_accumulated_column_from_next_chunk() {
2479 let per_chunk = 370;
2480 let mut input: VecDeque<WideChunk> = (0..8u64)
2481 .map(|i| {
2482 let start = i * per_chunk;
2483 WideChunk::from_body(wide_column(start..start + per_chunk, 3000))
2484 })
2485 .collect();
2486 let chunk_bytes = input[0].clone().into_body().length_in_bytes();
2487 assert!(2 * chunk_bytes > COMMIT_BYTES && chunk_bytes < COMMIT_BYTES);
2488 let mut settled = VecDeque::new();
2489 WideChunk::settle(&mut input, true, &mut settled);
2490 let sizes: Vec<usize> = settled
2491 .iter()
2492 .map(|chunk| chunk.clone().into_body().length_in_bytes())
2493 .collect();
2494 let (last, rest) = sizes.split_last().expect("settled output");
2495 assert!(*last <= COMMIT_BYTES);
2496 for size in rest {
2497 assert!(
2498 *size >= COMMIT_BYTES - COMMIT_BYTES / 10 && *size <= COMMIT_BYTES,
2499 "committed {size} bytes, sizes {sizes:?}",
2500 );
2501 }
2502 assert_wide_byte_bound(settled, 8 * 370, 3000);
2503 }
2504
2505 #[mz_ore::test]
2508 #[cfg_attr(miri, ignore)]
2509 fn advance_cuts_large_output() {
2510 let records: Vec<Tuple> = (0..300_000u64).map(|k| ((k, 0), 0, 1)).collect();
2511 let mut input = VecDeque::from([ColumnChunk::from_body(build_column(&records))]);
2512 let frontier = Antichain::from_elem(0u64);
2513 let mut out = VecDeque::new();
2514 TestChunk::advance(&mut input, frontier.borrow(), true, &mut out);
2515 assert!(input.is_empty());
2516 assert!(
2517 out.len() >= 2,
2518 "expected a cut output, got {} chunk(s)",
2519 out.len()
2520 );
2521 assert_eq!(collect_bounded(out, 2 * COMMIT_BYTES), records);
2522 }
2523
2524 #[mz_ore::test]
2527 #[cfg_attr(miri, ignore)]
2528 fn advance_withholds_giant_group() {
2529 let records: Vec<Tuple> = (0..100u64).map(|t| ((7, 7), t, 1)).collect();
2530 let mut input: VecDeque<TestChunk> = VecDeque::new();
2531 for piece in records.chunks(30) {
2532 input.push_back(ColumnChunk::from_body(build_column(piece)));
2533 }
2534 let frontier = Antichain::from_elem(50u64);
2535 let mut out = VecDeque::new();
2536 TestChunk::advance(&mut input, frontier.borrow(), false, &mut out);
2537 assert!(out.is_empty(), "nothing may ship from a single open group");
2538 assert_eq!(input.len(), 1, "the whole input becomes one carry chunk");
2539 TestChunk::advance(&mut input, frontier.borrow(), true, &mut out);
2541 assert!(input.is_empty());
2542 let advanced = records.iter().map(|&(d, t, r)| (d, t.max(50), r)).collect();
2543 assert_eq!(collect_chunks(out), consolidate(advanced));
2544 }
2545
2546 #[mz_ore::test]
2551 #[cfg_attr(miri, ignore)]
2552 fn extract_passes_frontier_disjoint_chunks_through() {
2553 set_spill_override(Some(test_pool()));
2554 let low: Vec<Tuple> = (0..20_000u64).map(|i| ((i, 0), i % 4, 1)).collect();
2555 let high: Vec<Tuple> = (0..20_000u64).map(|i| ((i, 0), 6 + i % 4, 1)).collect();
2556 let spilled_chunk = |data: &[Tuple]| {
2557 let chunk = TestChunk::commit(build_column(&consolidate(data.to_vec())), 1);
2558 assert!(chunk.is_spilled());
2559 chunk
2560 };
2561
2562 let mut input = VecDeque::from([spilled_chunk(&low), spilled_chunk(&high)]);
2567 let frontier = Antichain::from_elem(5u64);
2568 let mut residual = Antichain::new();
2569 let (mut keep, mut ship) = (VecDeque::new(), VecDeque::new());
2570 while !input.is_empty() {
2571 TestChunk::extract(
2572 &mut input,
2573 frontier.borrow(),
2574 &mut residual,
2575 &mut keep,
2576 &mut ship,
2577 );
2578 }
2579 assert_eq!(ship.len(), 1);
2580 assert!(ship[0].is_spilled(), "shipped whole: body untouched");
2581 assert_eq!(keep.len(), 1);
2582 assert!(keep[0].is_spilled(), "kept whole: body untouched");
2583 assert_eq!(residual, Antichain::from_elem(6));
2584 let shipped = ship.pop_front().unwrap().into_body();
2585 assert_eq!(collect_column(&shipped), consolidate(low));
2586 let kept = keep.pop_front().unwrap().into_body();
2587 assert_eq!(collect_column(&kept), consolidate(high));
2588 set_spill_override(None);
2589 }
2590
2591 #[mz_ore::test]
2594 #[cfg_attr(miri, ignore)]
2595 fn extract_cuts_large_output() {
2596 let records: Vec<Tuple> = (0..300_000u64).map(|k| ((k, 0), k % 2, 1)).collect();
2597 let mut input = VecDeque::from([ColumnChunk::from_body(build_column(&records))]);
2598 let frontier = Antichain::from_elem(1u64);
2599 let mut residual = Antichain::new();
2600 let (mut keep, mut ship) = (VecDeque::new(), VecDeque::new());
2601 while !input.is_empty() {
2602 TestChunk::extract(
2603 &mut input,
2604 frontier.borrow(),
2605 &mut residual,
2606 &mut keep,
2607 &mut ship,
2608 );
2609 }
2610 assert!(
2611 keep.len() >= 2,
2612 "expected a cut keep side, got {} chunk(s)",
2613 keep.len()
2614 );
2615 assert!(
2616 ship.len() >= 2,
2617 "expected a cut ship side, got {} chunk(s)",
2618 ship.len()
2619 );
2620 let kept: Vec<Tuple> = records.iter().copied().filter(|r| r.1 >= 1).collect();
2621 let shipped: Vec<Tuple> = records.iter().copied().filter(|r| r.1 < 1).collect();
2622 assert_eq!(collect_bounded(keep, 2 * COMMIT_BYTES), kept);
2623 assert_eq!(collect_bounded(ship, 2 * COMMIT_BYTES), shipped);
2624 assert_eq!(residual, Antichain::from_elem(1));
2625 }
2626
2627 #[mz_ore::test]
2630 fn locate_uses_resident_bounds() {
2631 let pool = test_pool();
2632 let data: Vec<Tuple> = vec![((2, 0), 0, 1), ((4, 0), 0, 1)];
2633 let chunk = force_spill(ColumnChunk::from_body(build_column(&data)), &pool);
2634
2635 let mut probe_col = <u64 as Columnar>::Container::default();
2636 for key in [1u64, 3, 5] {
2637 probe_col.push(key);
2638 }
2639 let probes = probe_col.borrow();
2640 assert_eq!(chunk.locate(probes, 0), std::cmp::Ordering::Less);
2641 assert_eq!(chunk.locate(probes, 1), std::cmp::Ordering::Equal);
2642 assert_eq!(chunk.locate(probes, 2), std::cmp::Ordering::Greater);
2643 }
2644
2645 #[mz_ore::test]
2648 #[cfg_attr(miri, ignore)] fn spill_round_trip() {
2650 set_spill_override(Some(test_pool()));
2651
2652 let data: Vec<Tuple> = (0..40_000u64)
2653 .map(|i| ((i / 4, i % 4), i % 8, 1i64))
2654 .collect();
2655 let data = consolidate(data);
2656
2657 let column = build_column(&data);
2658 let committed = TestChunk::commit(column, 0);
2659 assert!(committed.is_spilled(), "large body must spill");
2660 assert_eq!(committed.len(), data.len());
2661 assert_eq!(collect_column(&committed.clone().into_body()), data);
2662
2663 let mut batcher = TestChunkBatcher::new(None, 0);
2664 for piece in data.chunks(10_000) {
2665 batcher.push_chunk(ColumnChunk::from_body(build_column(piece)));
2666 }
2667 let (sealed, _frontier) = batcher.extract(Antichain::new().borrow());
2668 let sealed = sealed.unwrap_or_default();
2669 assert!(
2670 sealed.iter().any(ColumnChunk::is_spilled),
2671 "sealed output should contain spilled chunks",
2672 );
2673 assert_eq!(collect_chunks(sealed), data);
2674
2675 set_spill_override(None);
2676 }
2677
2678 #[mz_ore::test]
2681 #[cfg_attr(miri, ignore)] fn merge_spilled_chains() {
2683 set_spill_override(Some(test_pool()));
2684
2685 let a: Vec<Tuple> = (0..20_000u64).map(|i| ((i, 0), 0, 1i64)).collect();
2686 let b: Vec<Tuple> = (0..20_000u64).map(|i| ((i, 0), 0, 2i64)).collect();
2687
2688 let mut in1 = VecDeque::from([TestChunk::commit(build_column(&a), 0)]);
2689 let mut in2 = VecDeque::from([TestChunk::commit(build_column(&b), 0)]);
2690 assert!(in1[0].is_spilled() && in2[0].is_spilled());
2691
2692 let mut out = VecDeque::new();
2693 while !in1.is_empty() && !in2.is_empty() {
2694 TestChunk::merge(&mut in1, &mut in2, &mut out);
2695 }
2696 for tail in in1.drain(..).chain(in2.drain(..)) {
2697 out.push_back(tail);
2698 }
2699
2700 let expected: Vec<Tuple> = (0..20_000u64).map(|i| ((i, 0), 0, 3i64)).collect();
2701 assert_eq!(collect_chunks(out), expected);
2702
2703 set_spill_override(None);
2704 }
2705
2706 #[mz_ore::test]
2709 fn merge_untouched_survivor_stays_spilled() {
2710 let pool = test_pool();
2711 let low: Vec<Tuple> = (0..100u64).map(|i| ((i, 0), 0, 1i64)).collect();
2712 let high: Vec<Tuple> = (1000..1100u64).map(|i| ((i, 0), 0, 1i64)).collect();
2713
2714 let mut in1 = VecDeque::from([force_spill(
2715 ColumnChunk::from_body(build_column(&low)),
2716 &pool,
2717 )]);
2718 let mut in2 = VecDeque::from([force_spill(
2719 ColumnChunk::from_body(build_column(&high)),
2720 &pool,
2721 )]);
2722 let mut out = VecDeque::new();
2723 TestChunk::merge(&mut in1, &mut in2, &mut out);
2724
2725 assert!(in1.is_empty());
2728 assert_eq!(in2.len(), 1);
2729 assert!(in2[0].is_spilled(), "untouched survivor must stay spilled");
2730 let mut all = collect_chunks(out);
2731 Extend::extend(&mut all, collect_chunks(in2.drain(..)));
2732 let mut expected = low;
2733 Extend::extend(&mut expected, high);
2734 assert_eq!(all, expected);
2735 }
2736
2737 #[mz_ore::test]
2741 fn merge_derives_generational_depth() {
2742 let low: Vec<Tuple> = (0..100u64).map(|i| ((i, 0), 0, 1i64)).collect();
2743 let high: Vec<Tuple> = (50..150u64).map(|i| ((i, 0), 0, 1i64)).collect();
2744 let mut in1 = VecDeque::from([ColumnChunk::from_body(build_column(&low))]);
2745 let mut in2 = VecDeque::from([ColumnChunk::from_body(build_column(&high))]);
2746 assert_eq!(in1[0].depth(), 0, "fresh chunks start at depth 0");
2747 let mut out = VecDeque::new();
2748 TestChunk::merge(&mut in1, &mut in2, &mut out);
2749 assert!(!out.is_empty());
2750 for chunk in &out {
2751 assert_eq!(chunk.depth(), 1, "merge output is one past its inputs");
2752 }
2753 assert!(in1.is_empty());
2756 assert_eq!(in2.len(), 1);
2757 assert_eq!(in2[0].depth(), 0, "rewritten survivor keeps its depth");
2758
2759 let mut in1 = VecDeque::from([ColumnChunk::Resident(Rc::new(build_column(&low)), 3)]);
2762 let far: Vec<Tuple> = (1000..1100u64).map(|i| ((i, 0), 0, 1i64)).collect();
2763 let mut in2 = VecDeque::from([ColumnChunk::from_body(build_column(&far))]);
2764 let mut out = VecDeque::new();
2765 TestChunk::merge(&mut in1, &mut in2, &mut out);
2766 assert_eq!(out.len(), 1);
2767 assert_eq!(out[0].depth(), 4, "pass-through ages a generation");
2768 assert_eq!(collect_chunks(out), low);
2769 }
2770
2771 #[mz_ore::test]
2774 fn advance_preserves_depth() {
2775 let data: Vec<Tuple> = (0..100u64).map(|i| ((i, 0), 1, 1i64)).collect();
2776 let mut input = VecDeque::from([
2777 ColumnChunk::Resident(Rc::new(build_column(&data[..50])), 2),
2778 ColumnChunk::Resident(Rc::new(build_column(&data[50..])), 1),
2779 ]);
2780 let frontier = Antichain::from_elem(5u64);
2781 let mut out = VecDeque::new();
2782 TestChunk::advance(&mut input, frontier.borrow(), false, &mut out);
2783 for chunk in out.iter().chain(input.iter()) {
2784 assert_eq!(chunk.depth(), 2);
2785 }
2786 TestChunk::advance(&mut input, frontier.borrow(), true, &mut out);
2787 assert!(input.is_empty());
2788 assert!(!out.is_empty());
2789 for chunk in &out {
2790 assert_eq!(chunk.depth(), 2);
2791 }
2792 }
2793
2794 #[mz_ore::test]
2798 #[cfg_attr(miri, ignore)] fn settle_commits_at_accumulated_depth() {
2800 set_spill_override(Some(test_pool()));
2801 let big: Vec<Tuple> = (0..60_000u64).map(|i| ((i, 0), 0, 1i64)).collect();
2802 let mut input = VecDeque::from([
2803 ColumnChunk::Resident(Rc::new(build_column(&big)), 1),
2804 ColumnChunk::Resident(Rc::new(build_column(&[((0, 0), 0, 1)])), 0),
2805 ColumnChunk::Resident(Rc::new(build_column(&[((1, 0), 0, 1)])), 2),
2806 ]);
2807 let mut out = VecDeque::new();
2808 TestChunk::settle(&mut input, true, &mut out);
2809 assert!(input.is_empty());
2810 assert_eq!(out.len(), 2);
2811 assert!(out[0].is_spilled(), "large commit must spill");
2812 assert_eq!(out[0].depth(), 1, "sole commit keeps its depth");
2813 assert!(!out[1].is_spilled(), "small commit stays resident");
2814 assert_eq!(out[1].depth(), 2, "coalesced commit takes the max depth");
2815 set_spill_override(None);
2816 }
2817
2818 #[mz_ore::test]
2822 #[cfg_attr(miri, ignore)] fn settle_carry_commits_at_target() {
2824 let chunk_rows = u64::cast_from(800_000usize / 32);
2826 let mut input: VecDeque<TestChunk> = (0..4u64)
2827 .map(|c| {
2828 let data: Vec<Tuple> = (0..chunk_rows)
2829 .map(|i| ((c * chunk_rows + i, 0), 0, 1i64))
2830 .collect();
2831 ColumnChunk::from_body(build_column(&data))
2832 })
2833 .collect();
2834 let mut out = VecDeque::new();
2835 TestChunk::settle(&mut input, true, &mut out);
2836 assert!(out.len() < 4, "nothing coalesced");
2839 for chunk in &out {
2840 let col = chunk.clone().into_body();
2841 assert!(
2842 col.length_in_bytes() <= COMMIT_BYTES,
2843 "settled chunk of {} bytes exceeds the commit target",
2844 col.length_in_bytes(),
2845 );
2846 }
2847 assert_eq!(
2848 collect_chunks(out).len(),
2849 usize::try_from(4 * chunk_rows).unwrap(),
2850 );
2851 }
2852
2853 #[mz_ore::test]
2854 fn small_chunks_stay_resident() {
2855 set_spill_override(Some(test_pool()));
2856 let committed = TestChunk::commit(build_column(&[((1, 1), 0, 1)]), 0);
2857 assert!(!committed.is_spilled());
2858 set_spill_override(None);
2859 }
2860
2861 fn column_at_spill_floor() -> (ColumnBody<Tuple>, u64) {
2864 let mut col: ColumnBody<Tuple> = ColumnBody::default();
2865 let mut n = 0u64;
2866 while col.length_in_bytes() < SPILL_MIN_BYTES {
2867 col.push_into(((n, n), 0, 1));
2868 n += 1;
2869 }
2870 (col, n)
2871 }
2872
2873 #[mz_ore::test]
2876 fn spill_floor_boundary() {
2877 set_spill_override(Some(test_pool()));
2878 let (col, n) = column_at_spill_floor();
2879 let mut under: ColumnBody<Tuple> = ColumnBody::default();
2880 for m in 0..n - 1 {
2881 under.push_into(((m, m), 0, 1));
2882 }
2883 assert!(under.length_in_bytes() < SPILL_MIN_BYTES);
2884 assert!(!TestChunk::commit(under, 0).is_spilled());
2885 assert!(TestChunk::commit(col, 0).is_spilled());
2886 set_spill_override(None);
2887 }
2888
2889 #[mz_ore::test]
2893 fn spill_codec_depth_floor() {
2894 set_spill_override(Some(test_pool()));
2895 set_compress_min_depth_override(Some(2));
2896 let codec_name = |depth: u8| {
2900 let (codec, compressed) = codec_for_depth(depth, compress_min_depth());
2901 let name = format!("{:?}", codec);
2902 assert_eq!(compressed, name == "Lz4Codec", "flag tracks the codec");
2903 name
2904 };
2905 assert_eq!(codec_name(0), "IdentityCodec");
2906 assert_eq!(codec_name(1), "IdentityCodec");
2907 assert_eq!(codec_name(2), "Lz4Codec");
2908 assert_eq!(codec_name(u8::MAX), "Lz4Codec");
2909
2910 let data: Vec<Tuple> = (0..20_000u64).map(|i| ((i, 0), 0, 1i64)).collect();
2911 let data = consolidate(data);
2912 let column = build_column(&data);
2913 for depth in [0u8, 1, 2, 3] {
2914 let chunk = TestChunk::commit(column.clone(), depth);
2915 assert!(chunk.is_spilled(), "depth {depth} must spill");
2916 assert_eq!(collect_column(&chunk.into_body()), data);
2917 }
2918 set_spill_override(None);
2919 set_compress_min_depth_override(None);
2920
2921 set_compress_min_depth_override(Some(DEFAULT_COMPRESS_MIN_DEPTH));
2923 assert_eq!(codec_name(0), "IdentityCodec");
2924 assert_eq!(codec_name(1), "Lz4Codec");
2925 set_compress_min_depth_override(None);
2926 }
2927
2928 #[mz_ore::test]
2932 #[cfg_attr(miri, ignore)]
2933 fn sink_spill_codec_follows_sink_floor() {
2934 static POOL: std::sync::OnceLock<Pool> = std::sync::OnceLock::new();
2935 let pool = POOL
2936 .get_or_init(|| {
2937 let pool = Pool::new().expect("pool creation");
2938 pool.set_budget(0);
2939 pool
2940 })
2941 .clone();
2942 set_spill_override(Some(pool.clone()));
2943 let mut col: ColumnBody<Tuple> = ColumnBody::default();
2945 while col.length_in_bytes() < SPILL_MIN_BYTES {
2946 col.push_into(((0, 0), 0, 1));
2947 }
2948 let len = u64::cast_from(col.length_in_bytes());
2949 let written = |chunk_floor: u8, sink_floor: u8| {
2950 set_compress_min_depth_override(Some(chunk_floor));
2951 set_sink_compress_min_depth_override(Some(sink_floor));
2952 let before = pool.stats().extent_bytes_written;
2953 let handle = try_spill_ref(&col, 1).expect("the override pool takes the body");
2954 let written = pool.stats().extent_bytes_written - before;
2955 drop(handle);
2956 written
2957 };
2958 assert_eq!(
2959 written(0, u8::MAX),
2960 len,
2961 "below the sink floor, the body stores uncompressed"
2962 );
2963 assert!(
2964 written(u8::MAX, 0) < len / 2,
2965 "at the sink floor, the body stores compressed"
2966 );
2967 set_spill_override(None);
2968 set_compress_min_depth_override(None);
2969 set_sink_compress_min_depth_override(None);
2970 }
2971
2972 #[mz_ore::test]
2978 #[cfg_attr(miri, ignore)] fn merge_survivor_crosses_compression_floor() {
2980 set_spill_override(Some(test_pool()));
2981 set_compress_min_depth_override(Some(1));
2982
2983 let low = consolidate((0..20_000u64).map(|i| ((i, 0), 0, 1i64)).collect());
2984 let far = consolidate((100_000..120_000u64).map(|i| ((i, 0), 0, 1i64)).collect());
2985 let fresh_far = || VecDeque::from([TestChunk::commit(build_column(&far), 0)]);
2986
2987 let mut in1 = VecDeque::from([TestChunk::commit(build_column(&low), 0)]);
2990 let mut in2 = fresh_far();
2991 assert!(in1[0].is_spilled() && in2[0].is_spilled());
2992 assert!(
2993 !body_compressed(&in1[0]),
2994 "a fresh body below the floor is identity coded"
2995 );
2996
2997 let mut out = VecDeque::new();
2998 TestChunk::merge(&mut in1, &mut in2, &mut out);
2999 assert_eq!(out.len(), 1);
3000 let survived = out.pop_front().expect("the lower front passes through");
3001 assert_eq!(survived.depth(), 1, "survival ages across the floor");
3002 assert!(
3003 survived.is_spilled(),
3004 "the crossing re-spills, it does not evict"
3005 );
3006 assert!(
3007 body_compressed(&survived),
3008 "the survivor is re-spilled under the compressing codec"
3009 );
3010
3011 let mut in1 = VecDeque::from([survived]);
3014 let mut in2 = fresh_far();
3015 let mut out = VecDeque::new();
3016 TestChunk::merge(&mut in1, &mut in2, &mut out);
3017 assert_eq!(out.len(), 1);
3018 assert_eq!(out[0].depth(), 2, "an aged survivor keeps aging");
3019 assert!(out[0].is_spilled());
3020 assert_eq!(
3021 collect_chunks(out),
3022 low,
3023 "the body reads back intact across both survivals"
3024 );
3025
3026 set_spill_override(None);
3027 set_compress_min_depth_override(None);
3028 }
3029
3030 #[mz_ore::test]
3037 #[cfg_attr(miri, ignore)] fn merge_survivor_ages_while_shared() {
3039 set_spill_override(Some(test_pool()));
3040 set_compress_min_depth_override(Some(1));
3041
3042 let low = consolidate((0..20_000u64).map(|i| ((i, 0), 0, 1i64)).collect());
3043 let far = consolidate((100_000..120_000u64).map(|i| ((i, 0), 0, 1i64)).collect());
3044
3045 let source = TestChunk::commit(build_column(&low), 0);
3048 let ColumnChunk::Spilled(source_body, 0) = &source else {
3049 panic!("a fresh commit above the spill floor is spilled at depth 0");
3050 };
3051 let source_body = Rc::clone(source_body);
3052
3053 let mut in1 = VecDeque::from([source.clone()]);
3054 let mut in2 = VecDeque::from([TestChunk::commit(build_column(&far), 0)]);
3055 let mut out = VecDeque::new();
3056 TestChunk::merge(&mut in1, &mut in2, &mut out);
3057
3058 assert_eq!(out.len(), 1);
3059 assert_eq!(out[0].depth(), 1, "a shared body ages all the same");
3060 let ColumnChunk::Spilled(survived_body, _) = &out[0] else {
3061 panic!("the survivor stays spilled");
3062 };
3063 assert!(
3064 Rc::ptr_eq(&source_body, survived_body),
3065 "a shared body is aged in place, not re-spilled"
3066 );
3067 assert_eq!(source.depth(), 0, "the other holder is left as it was");
3068
3069 let mut in1 = VecDeque::from([out.pop_front().expect("survivor observed above")]);
3072 let mut in2 = VecDeque::from([TestChunk::commit(build_column(&far), 0)]);
3073 let mut out = VecDeque::new();
3074 TestChunk::merge(&mut in1, &mut in2, &mut out);
3075 assert_eq!(out.len(), 1);
3076 assert_eq!(out[0].depth(), 2, "aging past the floor is not pinned");
3077 assert_eq!(collect_chunks(out), low);
3078
3079 set_spill_override(None);
3080 set_compress_min_depth_override(None);
3081 }
3082
3083 #[mz_ore::test]
3089 #[cfg_attr(miri, ignore)] fn survive_merge_retries_missed_migrations() {
3091 let low = consolidate((0..20_000u64).map(|i| ((i, 0), 0, 1i64)).collect());
3092 let far = consolidate((100_000..120_000u64).map(|i| ((i, 0), 0, 1i64)).collect());
3093
3094 let survive = |chunk: TestChunk| {
3097 let mut in1 = VecDeque::from([chunk]);
3098 let mut in2 = VecDeque::from([TestChunk::commit(build_column(&far), 0)]);
3099 let mut out = VecDeque::new();
3100 TestChunk::merge(&mut in1, &mut in2, &mut out);
3101 out.pop_front().expect("the lower front passes through")
3102 };
3103
3104 set_spill_override(Some(test_pool()));
3107 set_compress_min_depth_override(Some(1));
3108 let chunk = TestChunk::commit(build_column(&low), 0);
3109 assert!(!body_compressed(&chunk));
3110 set_spill_override(None);
3111 let chunk = survive(chunk);
3112 assert_eq!(chunk.depth(), 1, "aging does not need a pool");
3113 assert!(!body_compressed(&chunk), "no pool, no migration");
3114 set_spill_override(Some(test_pool()));
3115 let chunk = survive(chunk);
3116 assert!(
3117 body_compressed(&chunk),
3118 "the migration retries once a pool is back"
3119 );
3120
3121 let chunk = TestChunk::commit(build_column(&low), 0);
3124 let held = chunk.clone();
3125 let chunk = survive(chunk);
3126 assert!(!body_compressed(&chunk), "shared, so not migrated");
3127 drop(held);
3128 let chunk = survive(chunk);
3129 assert!(
3130 body_compressed(&chunk),
3131 "the migration retries once the body is unshared"
3132 );
3133
3134 set_compress_min_depth_override(Some(8));
3139 let chunk = TestChunk::commit(build_column(&low), 3);
3140 assert!(!body_compressed(&chunk));
3141 set_compress_min_depth_override(Some(1));
3142 let chunk = survive(chunk);
3143 assert_eq!(chunk.depth(), 4);
3144 assert!(
3145 body_compressed(&chunk),
3146 "lowering the floor migrates bodies already past it"
3147 );
3148
3149 set_spill_override(None);
3150 set_compress_min_depth_override(None);
3151 }
3152
3153 #[mz_ore::test]
3155 #[cfg_attr(miri, ignore)]
3156 fn spill_gates_are_independent() {
3157 let installed = crate::pool_config::apply_pool_config(
3158 crate::pool_config::PoolPagerConfig {
3159 budget_bytes: 32 << 20,
3160 spill_threads: 1,
3161 eager_backing: false,
3162 rss_target_bytes: 16 << 20,
3163 file_release_interval: std::time::Duration::ZERO,
3164 file_release_bytes: 0,
3165 },
3166 crate::pool_config::ExtentBackend::Swap,
3167 );
3168 assert!(installed, "pool reservation failed");
3169 let (col, _) = column_at_spill_floor();
3171 let compute = |col: &ColumnBody<Tuple>| TestChunk::commit(col.clone(), 0).is_spilled();
3172 let storage = |col: &ColumnBody<Tuple>| {
3173 ColumnChunk::<(u64, u64), u64, i64, StorageSpill>::commit(col.clone(), 0).is_spilled()
3174 };
3175 let sink = |col: &ColumnBody<Tuple>| try_spill_ref(col, 0).is_some();
3176
3177 assert!(!compute(&col), "all gates off");
3178 assert!(!storage(&col), "all gates off");
3179 assert!(!sink(&col), "all gates off");
3180
3181 set_storage_spill_enabled(true);
3182 assert!(storage(&col), "the storage gate spills storage chunks");
3183 assert!(
3184 !compute(&col),
3185 "the storage gate must not spill compute chunks"
3186 );
3187 assert!(!sink(&col), "the storage gate must not spill sink bodies");
3188 set_storage_spill_enabled(false);
3189
3190 set_compute_spill_enabled(true);
3191 assert!(compute(&col), "the compute gate spills compute chunks");
3192 assert!(
3193 !storage(&col),
3194 "the compute gate must not spill storage chunks"
3195 );
3196 assert!(!sink(&col), "the compute gate must not spill sink bodies");
3197 set_compute_spill_enabled(false);
3198
3199 set_sink_spill_enabled(true);
3200 assert!(sink(&col), "the sink gate spills sink bodies");
3201 assert!(
3202 !compute(&col),
3203 "the sink gate must not spill compute chunks"
3204 );
3205 assert!(
3206 !storage(&col),
3207 "the sink gate must not spill storage chunks"
3208 );
3209 set_sink_spill_enabled(false);
3210 set_compress_min_depth_override(None);
3211 }
3212
3213 #[mz_ore::test]
3218 #[cfg_attr(miri, ignore)] fn spill_align_round_trip() {
3220 let pool = Pool::new().expect("pool reservation");
3221 pool.set_budget(0);
3222 let data: Vec<Tuple> = (0..64u64).map(|k| ((k, k), 0, 1)).collect();
3223 let spilled = force_spill(ColumnChunk::from_body(build_column(&data)), &pool);
3224 let column = spilled.into_body();
3225 let ColumnBody::Words(words) = &column else {
3226 panic!("an evicted body reads back as ColumnBody::Words");
3227 };
3228 let words = words.clone();
3229 let respilled = force_spill(ColumnChunk::from_body(column), &pool);
3230 let reread = respilled.into_body();
3231 let ColumnBody::Words(words2) = &reread else {
3232 panic!("an evicted body reads back as ColumnBody::Words");
3233 };
3234 assert_eq!(&words, words2, "byte-identical round trip");
3235 assert_eq!(collect_column(&reread), data);
3236 }
3237
3238 #[mz_ore::test]
3242 #[cfg_attr(miri, ignore)] fn time_bounds_race_spill_thread_eviction() {
3244 let (done_tx, done_rx) = std::sync::mpsc::channel();
3245 std::thread::spawn(move || {
3246 let pool = Pool::new().expect("pool reservation");
3247 pool.set_budget(0);
3248 pool.set_spill_threads(4);
3249 let data: Vec<Tuple> = (0..2048u64).map(|k| ((k, k), k % 7, 1)).collect();
3250 for _ in 0..2000 {
3251 let chunk = force_spill(ColumnChunk::from_body(build_column(&data)), &pool);
3252 let (lower, upper) = chunk.chunk_time_bounds();
3253 assert_eq!(lower.elements(), &[0]);
3254 assert_eq!(&upper[..], &[6]);
3255 }
3256 pool.set_spill_threads(0);
3257 done_tx.send(()).expect("receiver alive");
3258 });
3259 done_rx
3260 .recv_timeout(std::time::Duration::from_secs(120))
3261 .expect("time bounds reads deadlocked against spill-thread eviction");
3262 }
3263
3264 #[mz_ore::test]
3265 fn merge_depth_saturates() {
3266 let a = ColumnChunk::Resident(
3267 Rc::new(build_column(&[((1, 0), 0, 1), ((3, 0), 0, 1)])),
3268 u8::MAX,
3269 );
3270 let b = ColumnChunk::Resident(
3271 Rc::new(build_column(&[((2, 0), 0, 1), ((4, 0), 0, 1)])),
3272 u8::MAX,
3273 );
3274 let mut in1 = VecDeque::from([a]);
3275 let mut in2 = VecDeque::from([b]);
3276 let mut out = VecDeque::new();
3277 TestChunk::merge(&mut in1, &mut in2, &mut out);
3278 for chunk in out.iter().chain(in1.iter()).chain(in2.iter()) {
3279 assert_eq!(chunk.depth(), u8::MAX, "depth saturates");
3280 }
3281 }
3282
3283 #[mz_ore::test]
3284 fn into_body_copies_shared_resident() {
3285 let data: Vec<Tuple> = vec![((1, 1), 0, 1), ((2, 2), 0, 1)];
3286 let a = TestChunk::from_body(build_column(&data));
3287 let b = a.clone();
3288 assert_eq!(collect_column(&a.into_body()), data);
3289 assert_eq!(collect_column(&b.into_body()), data);
3290 }
3291}