1#![deny(missing_docs)]
19
20pub mod batcher;
21pub mod builder;
22pub mod builder_input;
23pub mod chunk;
24pub mod consolidate;
25pub mod merge_batcher;
26pub mod unload;
27
28use std::hash::Hash;
29
30use columnar::Borrow;
31use columnar::bytes::indexed;
32use columnar::common::IterOwn;
33use columnar::{Clear, FromBytes, Index, Len};
34use columnar::{Columnar, Ref};
35use differential_dataflow::Hashable;
36use differential_dataflow::trace::implementations::merge_batcher::MergeBatcher;
37use timely::Accountable;
38use timely::bytes::arc::Bytes;
39use timely::container::{DrainContainer, PushInto, SizableContainer};
40use timely::dataflow::channels::ContainerBytes;
41
42use crate::columnation::ColInternalMerger;
43
44pub type Col2ValBatcher<K, V, T, R> = MergeBatcher<ColInternalMerger<(K, V), T, R>>;
51pub type Col2KeyBatcher<K, T, R> = Col2ValBatcher<K, (), T, R>;
53
54pub type Col2ValPagedBatcher<K, V, T, R> = merge_batcher::ColumnMergeBatcher<(K, V), T, R>;
66
67pub enum Column<C: Columnar> {
73 Typed(C::Container),
75 Bytes(Bytes),
77 Align(Vec<u64>),
84}
85
86impl<C: Columnar> Column<C> {
87 #[inline]
94 pub fn clear(&mut self) {
95 match self {
96 Column::Typed(t) => t.clear(),
97 Column::Bytes(_) | Column::Align(_) => *self = Default::default(),
98 }
99 }
100
101 #[inline]
107 pub fn is_empty(&self) -> bool {
108 match self {
109 Column::Typed(t) => t.is_empty(),
110 Column::Bytes(_) | Column::Align(_) => self.borrow().is_empty(),
111 }
112 }
113
114 #[inline]
116 pub fn borrow(&self) -> <C::Container as Borrow>::Borrowed<'_> {
117 match self {
118 Column::Typed(t) => t.borrow(),
119 Column::Bytes(b) => <<C::Container as Borrow>::Borrowed<'_>>::from_bytes(
120 &mut indexed::decode(bytemuck::cast_slice(b)),
121 ),
122 Column::Align(a) => {
123 <<C::Container as Borrow>::Borrowed<'_>>::from_bytes(&mut indexed::decode(a))
124 }
125 }
126 }
127}
128
129impl<C: Columnar> Default for Column<C> {
130 fn default() -> Self {
131 Self::Typed(Default::default())
132 }
133}
134
135impl<C: Columnar> Clone for Column<C>
136where
137 C::Container: Clone,
138{
139 fn clone(&self) -> Self {
140 match self {
141 Column::Typed(t) => Column::Typed(t.clone()),
144 Column::Bytes(b) => {
145 assert_eq!(b.len() % 8, 0);
146 Self::Align(bytemuck::allocation::pod_collect_to_vec(b))
147 }
148 Column::Align(a) => Column::Align(a.clone()),
149 }
150 }
151}
152
153impl<C: Columnar> Accountable for Column<C> {
154 #[inline]
155 fn record_count(&self) -> i64 {
156 self.borrow().len().try_into().expect("Must fit")
157 }
158}
159impl<C: Columnar> DrainContainer for Column<C> {
160 type Item<'a> = Ref<'a, C>;
161 type DrainIter<'a> = IterOwn<<C::Container as Borrow>::Borrowed<'a>>;
162 #[inline]
163 fn drain(&mut self) -> Self::DrainIter<'_> {
164 self.borrow().into_index_iter()
165 }
166}
167
168impl<C: Columnar, T> PushInto<T> for Column<C>
169where
170 C::Container: columnar::Push<T>,
171{
172 #[inline]
173 fn push_into(&mut self, item: T) {
174 use columnar::Push;
175 match self {
176 Column::Typed(t) => t.push(item),
177 Column::Align(_) | Column::Bytes(_) => {
178 unimplemented!("Pushing into Column::Bytes without first clearing");
181 }
182 }
183 }
184}
185
186const SHIP_WORDS: usize = 1 << 18;
191
192#[inline]
203pub(crate) fn at_serialized_capacity<'a, A>(borrow: &A) -> bool
204where
205 A: columnar::AsBytes<'a>,
206{
207 indexed::length_in_words(borrow) >= SHIP_WORDS - SHIP_WORDS / 10
208}
209
210impl<C: Columnar> SizableContainer for Column<C> {
211 fn at_capacity(&self) -> bool {
212 match self {
220 Column::Typed(c) => at_serialized_capacity(&c.borrow()),
221 Column::Bytes(_) | Column::Align(_) => true,
222 }
223 }
224
225 fn ensure_capacity(&mut self, _stash: &mut Option<Self>) {
226 }
233}
234
235impl<C: Columnar> ContainerBytes for Column<C> {
236 #[inline]
237 fn from_bytes(bytes: Bytes) -> Self {
238 assert_eq!(bytes.len() % 8, 0);
244 if let Ok(_) = bytemuck::try_cast_slice::<_, u64>(&bytes) {
245 Self::Bytes(bytes)
246 } else {
247 Self::Align(bytemuck::allocation::pod_collect_to_vec(&bytes[..]))
250 }
251 }
252
253 #[inline]
254 fn length_in_bytes(&self) -> usize {
255 match self {
256 Column::Typed(t) => indexed::length_in_bytes(&t.borrow()),
257 Column::Bytes(b) => b.len(),
258 Column::Align(a) => 8 * a.len(),
259 }
260 }
261
262 #[inline]
263 fn into_bytes<W: ::std::io::Write>(&self, writer: &mut W) {
264 match self {
265 Column::Typed(t) => indexed::write(writer, &t.borrow()).unwrap(),
266 Column::Bytes(b) => writer.write_all(b).unwrap(),
267 Column::Align(a) => writer.write_all(bytemuck::cast_slice(a)).unwrap(),
268 }
269 }
270}
271
272#[inline(always)]
276pub fn columnar_exchange<K, V, T, D>(((k, _), _, _): &Ref<'_, ((K, V), T, D)>) -> u64
277where
278 K: Columnar,
279 for<'a> Ref<'a, K>: Hash,
280 V: Columnar,
281 D: Columnar,
282 T: Columnar,
283{
284 k.hashed()
285}
286
287#[cfg(test)]
288mod tests {
289 use timely::bytes::arc::BytesMut;
290 use timely::container::PushInto;
291 use timely::dataflow::channels::ContainerBytes;
292
293 use super::*;
294
295 fn raw_columnar_bytes() -> Vec<u8> {
297 let mut raw = Vec::new();
298 raw.extend(16_u64.to_le_bytes()); raw.extend(28_u64.to_le_bytes()); raw.extend(1_i32.to_le_bytes());
301 raw.extend(2_i32.to_le_bytes());
302 raw.extend(3_i32.to_le_bytes());
303 raw.extend([0, 0, 0, 0]); raw
305 }
306
307 #[mz_ore::test]
308 fn test_column_clone() {
309 let columns = Columnar::as_columns([1, 2, 3].iter());
310 let column_typed: Column<i32> = Column::Typed(columns);
311 let column_typed2 = column_typed.clone();
312
313 assert_eq!(
314 column_typed2.borrow().into_index_iter().collect::<Vec<_>>(),
315 vec![&1, &2, &3]
316 );
317
318 let bytes = BytesMut::from(raw_columnar_bytes()).freeze();
319 let column_bytes: Column<i32> = Column::Bytes(bytes);
320 let column_bytes2 = column_bytes.clone();
321
322 assert_eq!(
323 column_bytes2.borrow().into_index_iter().collect::<Vec<_>>(),
324 vec![&1, &2, &3]
325 );
326
327 let raw = raw_columnar_bytes();
328 let mut region: Vec<u64> = vec![0; raw.len() / 8];
329 let region_bytes = bytemuck::cast_slice_mut(&mut region[..]);
330 region_bytes[..raw.len()].copy_from_slice(&raw);
331 let column_align: Column<i32> = Column::Align(region);
332 let column_align2 = column_align.clone();
333
334 assert_eq!(
335 column_align2.borrow().into_index_iter().collect::<Vec<_>>(),
336 vec![&1, &2, &3]
337 );
338 }
339
340 #[mz_ore::test]
343 fn test_column_known_bytes() {
344 let mut column: Column<i32> = Default::default();
345 column.push_into(1);
346 column.push_into(2);
347 column.push_into(3);
348 let mut data = Vec::new();
349 column.into_bytes(&mut std::io::Cursor::new(&mut data));
350 assert_eq!(data, raw_columnar_bytes());
351 }
352
353 #[mz_ore::test]
354 fn test_column_from_bytes() {
355 let raw = raw_columnar_bytes();
356
357 let buf = vec![0; raw.len() + 8];
358 let align = buf.as_ptr().align_offset(std::mem::size_of::<u64>());
359 let mut bytes_mut = BytesMut::from(buf);
360 let _ = bytes_mut.extract_to(align);
361 bytes_mut[..raw.len()].copy_from_slice(&raw);
362 let aligned_bytes = bytes_mut.extract_to(raw.len());
363
364 let column: Column<i32> = Column::from_bytes(aligned_bytes);
365 assert!(matches!(column, Column::Bytes(_)));
366 assert_eq!(
367 column.borrow().into_index_iter().collect::<Vec<_>>(),
368 vec![&1, &2, &3]
369 );
370
371 let buf = vec![0; raw.len() + 8];
372 let align = buf.as_ptr().align_offset(std::mem::size_of::<u64>());
373 let mut bytes_mut = BytesMut::from(buf);
374 let _ = bytes_mut.extract_to(align + 1);
375 bytes_mut[..raw.len()].copy_from_slice(&raw);
376 let unaligned_bytes = bytes_mut.extract_to(raw.len());
377
378 let column: Column<i32> = Column::from_bytes(unaligned_bytes);
379 assert!(matches!(column, Column::Align(_)));
380 assert_eq!(
381 column.borrow().into_index_iter().collect::<Vec<_>>(),
382 vec![&1, &2, &3]
383 );
384 }
385
386 #[mz_ore::test]
389 #[cfg_attr(miri, ignore)] fn ship_threshold_monotone() {
391 use columnar::Push;
392 let mut container = <Vec<u64> as Columnar>::Container::default();
393 let wide: Vec<u64> = vec![0u64; 50_000];
395 let mut fired = false;
396 for pushes in 1..=64 {
397 container.push(&wide);
398 let now = at_serialized_capacity(&container.borrow());
399 if fired {
400 assert!(now, "ship signal un-fired at {pushes} records");
401 }
402 fired = fired || now;
403 }
404 assert!(fired, "ship signal never fired");
405 }
406}