1#![deny(missing_docs)]
19
20pub mod batcher;
21pub mod body;
22pub mod builder;
23pub mod builder_input;
24pub mod chunk;
25pub mod consolidate;
26pub mod unload;
27
28use std::hash::{BuildHasher, Hash, Hasher};
29use std::sync::LazyLock;
30
31use columnar::Borrow;
32use columnar::bytes::indexed;
33use columnar::common::IterOwn;
34use columnar::{Clear, FromBytes, Index, Len};
35use columnar::{Columnar, Ref};
36use differential_dataflow::Hashable;
37use differential_dataflow::collection::containers::{Enter, ResultsIn};
38use differential_dataflow::trace::implementations::merge_batcher::MergeBatcher;
39use itertools::Itertools;
40use timely::Accountable;
41use timely::bytes::arc::Bytes;
42use timely::container::{DrainContainer, PushInto, SizableContainer};
43use timely::dataflow::channels::ContainerBytes;
44use timely::progress::Timestamp;
45use timely::progress::timestamp::Refines;
46
47use crate::columnation::ColInternalMerger;
48
49pub type Col2ValBatcher<K, V, T, R, Chu, Se> =
58 MergeBatcher<Chu, ColInternalMerger<(K, V), T, R>, Se>;
59pub type Col2KeyBatcher<K, T, R, Chu, Se> = Col2ValBatcher<K, (), T, R, Chu, Se>;
61
62pub type Col2ValColBatcher<K, V, T, R, Chu, Se> =
69 MergeBatcher<Chu, batcher::ColumnMerger<(K, V), T, R>, Se>;
70
71pub enum Column<C: Columnar> {
81 Typed(C::Container),
83 Bytes(Bytes),
85 Align(Vec<u64>),
92}
93
94impl<C: Columnar> Column<C> {
95 #[inline]
102 pub fn clear(&mut self) {
103 match self {
104 Column::Typed(t) => t.clear(),
105 Column::Bytes(_) | Column::Align(_) => *self = Default::default(),
106 }
107 }
108
109 #[inline]
115 pub fn is_empty(&self) -> bool {
116 match self {
117 Column::Typed(t) => t.is_empty(),
118 Column::Bytes(_) | Column::Align(_) => self.borrow().is_empty(),
119 }
120 }
121
122 #[inline(always)]
126 pub fn borrow(&self) -> <C::Container as Borrow>::Borrowed<'_> {
127 match self {
128 Column::Typed(t) => t.borrow(),
129 Column::Bytes(b) => <<C::Container as Borrow>::Borrowed<'_>>::from_bytes(
130 &mut indexed::decode(bytemuck::cast_slice(b)),
131 ),
132 Column::Align(a) => {
133 <<C::Container as Borrow>::Borrowed<'_>>::from_bytes(&mut indexed::decode(a))
134 }
135 }
136 }
137}
138
139impl<C: Columnar> Default for Column<C> {
140 fn default() -> Self {
141 Self::Typed(Default::default())
142 }
143}
144
145impl<C: Columnar> Clone for Column<C>
146where
147 C::Container: Clone,
148{
149 fn clone(&self) -> Self {
150 match self {
151 Column::Typed(t) => Column::Typed(t.clone()),
154 Column::Bytes(b) => {
155 assert_eq!(b.len() % 8, 0);
156 Self::Align(bytemuck::allocation::pod_collect_to_vec(b))
157 }
158 Column::Align(a) => Column::Align(a.clone()),
159 }
160 }
161}
162
163impl<C: Columnar> Accountable for Column<C> {
164 #[inline]
165 fn record_count(&self) -> i64 {
166 self.borrow().len().try_into().expect("Must fit")
167 }
168}
169impl<C: Columnar> DrainContainer for Column<C> {
170 type Item<'a> = Ref<'a, C>;
171 type DrainIter<'a> = IterOwn<<C::Container as Borrow>::Borrowed<'a>>;
172 #[inline]
173 fn drain(&mut self) -> Self::DrainIter<'_> {
174 self.borrow().into_index_iter()
175 }
176}
177
178impl<C: Columnar, T> PushInto<T> for Column<C>
179where
180 C::Container: columnar::Push<T>,
181{
182 #[inline]
183 fn push_into(&mut self, item: T) {
184 use columnar::Push;
185 match self {
186 Column::Typed(t) => t.push(item),
187 Column::Align(_) | Column::Bytes(_) => {
188 unimplemented!("Pushing into Column::Bytes without first clearing");
191 }
192 }
193 }
194}
195
196impl<D, T1, T2, R> Enter<T1, T2> for Column<(D, T1, R)>
199where
200 D: Columnar,
201 T1: Columnar + Timestamp,
202 T2: Columnar + Refines<T1>,
203 R: Columnar,
204 (D, T1, R): Columnar<Container = (D::Container, T1::Container, R::Container)>,
205 (D, T2, R): Columnar<Container = (D::Container, T2::Container, R::Container)>,
206 for<'a> D::Container: columnar::Push<Ref<'a, D>>,
207 for<'a> T2::Container: columnar::Push<&'a T2>,
208 for<'a> R::Container: columnar::Push<Ref<'a, R>>,
209{
210 type InnerContainer = Column<(D, T2, R)>;
211
212 fn enter(self) -> Self::InnerContainer {
213 use columnar::Push;
214 match self {
215 Column::Typed((data, times, diffs)) => {
217 let mut inner = T2::Container::default();
218 for time in times.borrow().into_index_iter() {
219 inner.push(&T2::to_inner(T1::into_owned(time)));
220 }
221 Column::Typed((data, inner, diffs))
222 }
223 serialized => {
228 let (borrowed_data, borrowed_times, borrowed_diffs) = serialized.borrow();
229 let mut times = T2::Container::default();
230 for time in borrowed_times.into_index_iter() {
231 times.push(&T2::to_inner(T1::into_owned(time)));
232 }
233 let view = (borrowed_data, times.borrow(), borrowed_diffs);
234 let words = indexed::length_in_words(&view);
235 let mut alloc: Vec<u64> = Vec::with_capacity(words);
236 indexed::encode(&mut alloc, &view);
237 Column::Align(alloc)
238 }
239 }
240 }
241}
242
243impl<D, T, R> ResultsIn<T::Summary> for Column<(D, T, R)>
250where
251 D: Columnar,
252 T: Columnar + Timestamp,
253 R: Columnar,
254 (D, T, R): Columnar<Container = (D::Container, T::Container, R::Container)>,
255 for<'a> D::Container: columnar::Push<Ref<'a, D>>,
256 for<'a> T::Container: columnar::Push<&'a T>,
257 for<'a> R::Container: columnar::Push<Ref<'a, R>>,
258{
259 fn results_in(self, step: &T::Summary) -> Self {
260 use columnar::Push;
261 use timely::progress::PathSummary;
262
263 let (times, kept) = {
267 let (_, borrowed_times, _) = self.borrow();
268 let mut times = T::Container::default();
269 let mut time = T::minimum();
270 let kept: Vec<bool> = borrowed_times
271 .into_index_iter()
272 .map(|reference| {
273 time.copy_from(reference);
274 match step.results_in(&time) {
275 Some(time) => {
276 times.push(&time);
277 true
278 }
279 None => false,
280 }
281 })
282 .collect();
283 (times, kept)
284 };
285
286 if kept.iter().all(|kept| *kept) {
287 match self {
288 Column::Typed((data, _, diffs)) => Column::Typed((data, times, diffs)),
290 serialized => {
293 let (borrowed_data, _, borrowed_diffs) = serialized.borrow();
294 let view = (borrowed_data, times.borrow(), borrowed_diffs);
295 let words = indexed::length_in_words(&view);
296 let mut alloc: Vec<u64> = Vec::with_capacity(words);
297 indexed::encode(&mut alloc, &view);
298 Column::Align(alloc)
299 }
300 }
301 } else {
302 let (borrowed_data, _, borrowed_diffs) = self.borrow();
303 let mut data = D::Container::default();
304 let mut diffs = R::Container::default();
305 let records = borrowed_data
306 .into_index_iter()
307 .zip_eq(borrowed_diffs.into_index_iter())
308 .zip_eq(kept.iter());
309 for ((datum, diff), _) in records.filter(|(_, kept)| **kept) {
310 data.push(datum);
311 diffs.push(diff);
312 }
313 Column::Typed((data, times, diffs))
314 }
315 }
316}
317
318const SHIP_WORDS: usize = 1 << 18;
323
324#[inline]
335pub(crate) fn at_serialized_capacity<'a, A>(borrow: &A) -> bool
336where
337 A: columnar::AsBytes<'a>,
338{
339 indexed::length_in_words(borrow) >= SHIP_WORDS - SHIP_WORDS / 10
340}
341
342impl<C: Columnar> SizableContainer for Column<C> {
343 fn at_capacity(&self) -> bool {
344 match self {
352 Column::Typed(c) => at_serialized_capacity(&c.borrow()),
353 Column::Bytes(_) | Column::Align(_) => true,
354 }
355 }
356
357 fn ensure_capacity(&mut self, _stash: &mut Option<Self>) {
358 }
365}
366
367impl<C: Columnar> ContainerBytes for Column<C> {
368 #[inline]
369 fn from_bytes(bytes: Bytes) -> Self {
370 assert_eq!(bytes.len() % 8, 0);
376 if let Ok(_) = bytemuck::try_cast_slice::<_, u64>(&bytes) {
377 Self::Bytes(bytes)
378 } else {
379 Self::Align(bytemuck::allocation::pod_collect_to_vec(&bytes[..]))
382 }
383 }
384
385 #[inline]
386 fn length_in_bytes(&self) -> usize {
387 match self {
388 Column::Typed(t) => indexed::length_in_bytes(&t.borrow()),
389 Column::Bytes(b) => b.len(),
390 Column::Align(a) => 8 * a.len(),
391 }
392 }
393
394 #[inline]
395 fn into_bytes<W: ::std::io::Write>(&self, writer: &mut W) {
396 match self {
397 Column::Typed(t) => indexed::write(writer, &t.borrow()).unwrap(),
398 Column::Bytes(b) => writer.write_all(b).unwrap(),
399 Column::Align(a) => writer.write_all(bytemuck::cast_slice(a)).unwrap(),
400 }
401 }
402}
403
404#[inline(always)]
408pub fn columnar_exchange<K, V, T, D>(((k, _), _, _): &Ref<'_, ((K, V), T, D)>) -> u64
409where
410 K: Columnar,
411 for<'a> Ref<'a, K>: Hash,
412 V: Columnar,
413 D: Columnar,
414 T: Columnar,
415{
416 k.hashed()
417}
418
419pub fn columnar_exchange_data<D, T, R>((d, _, _): &Ref<'_, (D, T, R)>) -> u64
425where
426 D: Columnar,
427 for<'a> Ref<'a, D>: Hash,
428 T: Columnar,
429 R: Columnar,
430{
431 d.hashed()
432}
433
434pub fn columnar_consolidate_exchange<D, T, R>((d, _, _): &Ref<'_, (D, T, R)>) -> u64
443where
444 D: Columnar,
445 for<'a> Ref<'a, D>: Hash,
446 T: Columnar,
447 R: Columnar,
448{
449 static STATE: LazyLock<ahash::RandomState> = LazyLock::new(crate::hash::fixed_state);
450 let mut hasher = STATE.build_hasher();
451 d.hash(&mut hasher);
452 hasher.finish()
453}
454
455#[cfg(test)]
456mod tests {
457 use timely::bytes::arc::BytesMut;
458 use timely::container::PushInto;
459 use timely::dataflow::channels::ContainerBytes;
460
461 use super::*;
462
463 fn raw_columnar_bytes() -> Vec<u8> {
465 let mut raw = Vec::new();
466 raw.extend(16_u64.to_le_bytes()); raw.extend(28_u64.to_le_bytes()); raw.extend(1_i32.to_le_bytes());
469 raw.extend(2_i32.to_le_bytes());
470 raw.extend(3_i32.to_le_bytes());
471 raw.extend([0, 0, 0, 0]); raw
473 }
474
475 #[mz_ore::test]
476 fn test_column_clone() {
477 let columns = Columnar::as_columns([1, 2, 3].iter());
478 let column_typed: Column<i32> = Column::Typed(columns);
479 let column_typed2 = column_typed.clone();
480
481 assert_eq!(
482 column_typed2.borrow().into_index_iter().collect::<Vec<_>>(),
483 vec![&1, &2, &3]
484 );
485
486 let bytes = BytesMut::from(raw_columnar_bytes()).freeze();
487 let column_bytes: Column<i32> = Column::Bytes(bytes);
488 let column_bytes2 = column_bytes.clone();
489
490 assert_eq!(
491 column_bytes2.borrow().into_index_iter().collect::<Vec<_>>(),
492 vec![&1, &2, &3]
493 );
494
495 let raw = raw_columnar_bytes();
496 let mut region: Vec<u64> = vec![0; raw.len() / 8];
497 let region_bytes = bytemuck::cast_slice_mut(&mut region[..]);
498 region_bytes[..raw.len()].copy_from_slice(&raw);
499 let column_align: Column<i32> = Column::Align(region);
500 let column_align2 = column_align.clone();
501
502 assert_eq!(
503 column_align2.borrow().into_index_iter().collect::<Vec<_>>(),
504 vec![&1, &2, &3]
505 );
506 }
507
508 #[mz_ore::test]
511 fn test_column_known_bytes() {
512 let mut column: Column<i32> = Default::default();
513 column.push_into(1);
514 column.push_into(2);
515 column.push_into(3);
516 let mut data = Vec::new();
517 column.into_bytes(&mut std::io::Cursor::new(&mut data));
518 assert_eq!(data, raw_columnar_bytes());
519 }
520
521 #[mz_ore::test]
522 fn test_column_from_bytes() {
523 let raw = raw_columnar_bytes();
524
525 let buf = vec![0; raw.len() + 8];
526 let align = buf.as_ptr().align_offset(std::mem::size_of::<u64>());
527 let mut bytes_mut = BytesMut::from(buf);
528 let _ = bytes_mut.extract_to(align);
529 bytes_mut[..raw.len()].copy_from_slice(&raw);
530 let aligned_bytes = bytes_mut.extract_to(raw.len());
531
532 let column: Column<i32> = Column::from_bytes(aligned_bytes);
533 assert!(matches!(column, Column::Bytes(_)));
534 assert_eq!(
535 column.borrow().into_index_iter().collect::<Vec<_>>(),
536 vec![&1, &2, &3]
537 );
538
539 let buf = vec![0; raw.len() + 8];
540 let align = buf.as_ptr().align_offset(std::mem::size_of::<u64>());
541 let mut bytes_mut = BytesMut::from(buf);
542 let _ = bytes_mut.extract_to(align + 1);
543 bytes_mut[..raw.len()].copy_from_slice(&raw);
544 let unaligned_bytes = bytes_mut.extract_to(raw.len());
545
546 let column: Column<i32> = Column::from_bytes(unaligned_bytes);
547 assert!(matches!(column, Column::Align(_)));
548 assert_eq!(
549 column.borrow().into_index_iter().collect::<Vec<_>>(),
550 vec![&1, &2, &3]
551 );
552 }
553
554 #[mz_ore::test]
557 #[cfg_attr(miri, ignore)] fn ship_threshold_monotone() {
559 use columnar::Push;
560 let mut container = <Vec<u64> as Columnar>::Container::default();
561 let wide: Vec<u64> = vec![0u64; 50_000];
563 let mut fired = false;
564 for pushes in 1..=64 {
565 container.push(&wide);
566 let now = at_serialized_capacity(&container.borrow());
567 if fired {
568 assert!(now, "ship signal un-fired at {pushes} records");
569 }
570 fired = fired || now;
571 }
572 assert!(fired, "ship signal never fired");
573 }
574}