Skip to main content

mz_timely_util/
columnar.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License in the LICENSE file at the
6// root of this repository, or online at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Container for columnar data.
17
18#![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
49/// A batcher for columnar storage.
50///
51/// `Chu` melds raw input containers into the chunks the batcher merges:
52/// [`ColumnationChunker`](crate::columnation::ColumnationChunker) for `Vec<_>`
53/// input, or [`batcher::Chunker`] (over a `ColumnationStack<_>`) for [`Column`]
54/// input. `Se` seals each extracted chain into a batch. A caller that wants the
55/// chain itself takes [`ConsolidatingBatcher`](crate::operator::ConsolidatingBatcher)
56/// instead, which is this batcher without the seal.
57pub type Col2ValBatcher<K, V, T, R, Chu, Se> =
58    MergeBatcher<Chu, ColInternalMerger<(K, V), T, R>, Se>;
59/// A batcher for columnar storage with unit values.
60pub type Col2KeyBatcher<K, T, R, Chu, Se> = Col2ValBatcher<K, (), T, R, Chu, Se>;
61
62/// Columnar-native counterpart to [`Col2ValBatcher`], holding
63/// [`body::ColumnBody`] chunks rather than columnation stacks and merging
64/// them through [`batcher::ColumnMerger`].
65///
66/// Pairs with [`batcher::ColumnChunker`] and any builder whose `Input` is
67/// `ColumnBody<((K, V), T, R)>`.
68pub type Col2ValColBatcher<K, V, T, R, Chu, Se> =
69    MergeBatcher<Chu, batcher::ColumnMerger<(K, V), T, R>, Se>;
70
71/// A container based on a columnar store, encoded in aligned bytes: the container on dataflow
72/// edges.
73///
74/// The type can represent typed data, bytes from Timely, or an aligned allocation. The name
75/// is singular to express that the preferred format is [`Column::Align`]. The [`Column::Typed`]
76/// variant is used to construct the container, and it owns potentially multiple columns of data.
77///
78/// Data at rest behind an edge, in a merge batcher's chains, a spill-backed chunk, or a batch
79/// builder, is a [`body::ColumnBody`] instead, which has no channel-bytes form.
80pub enum Column<C: Columnar> {
81    /// The typed variant of the container.
82    Typed(C::Container),
83    /// The binary variant of the container.
84    Bytes(Bytes),
85    /// Relocated, aligned binary data, if `Bytes` doesn't work for some reason.
86    ///
87    /// Reasons could include misalignment, cloning of data, or wanting
88    /// to release the `Bytes` as a scarce resource.
89    ///
90    /// `Vec<u64>` guarantees `u64` alignment for the contained bytes.
91    Align(Vec<u64>),
92}
93
94impl<C: Columnar> Column<C> {
95    /// Empties the column, retaining the `Typed` variant's allocation so the
96    /// caller can refill it.
97    ///
98    /// [`columnar::Clear`] clears the typed container in place without
99    /// releasing its capacity. The serialized variants (`Bytes`/`Align`) own
100    /// no reusable typed buffer, so they are reset to an empty `Typed`.
101    #[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    /// True when the column holds no records.
110    ///
111    /// The `Typed` variant answers from the container itself. The serialized
112    /// variants have to reconstruct their borrowed view to reach a length, so
113    /// there this costs as much as [`Column::borrow`].
114    #[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    /// Borrows the container as a reference.
123    // NOTE: `inline(always)` measured 7.1 ns to 5.8 ns per call for a per-element borrow of an
124    // `Align` column. The header decode stays per call, so loops still hoist the borrow.
125    #[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            // Typed stays typed, although we would have the option to move to aligned data.
152            // If we did it might be confusing why we couldn't push into a cloned column.
153            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                // We really oughtn't be calling this in this case.
189                // We could convert to owned, but need more constraints on `C`.
190                unimplemented!("Pushing into Column::Bytes without first clearing");
191            }
192        }
193    }
194}
195
196/// Re-encodes a column's times into a refining timestamp, so a columnar collection can enter
197/// an iterative scope.
198impl<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            // Only the times change, so the data and diff columns move across whole.
216            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            // A serialized column owns no typed sub-containers, so only the times are
224            // materialized. The data and diff columns go from their borrowed views
225            // straight into the output allocation, a copy per column rather than a
226            // decode and re-encode per record.
227            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
243/// Advances a column's times by `step`, so a columnar collection can be a loop variable.
244///
245/// A time that the summary does not advance drops its record, so the data and diff columns
246/// cannot move across whole the way [`Enter`] moves them: a record's position in one column
247/// has to keep matching its position in the others. The times are read and advanced first,
248/// and the rest is rebuilt only when the step actually dropped something.
249impl<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        // Advance the times first. Whether the step dropped any record decides whether the
264        // data and diff columns still line up with the new times, which is what lets them
265        // be reused rather than rebuilt.
266        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                // Only the times changed, so the data and diff columns move across whole.
289                Column::Typed((data, _, diffs)) => Column::Typed((data, times, diffs)),
290                // A serialized column owns no typed sub-containers, so its data and diff
291                // columns go from their borrowed views straight into the output allocation.
292                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
318/// Words per 2 MiB. `length_in_words` returns serialized size in `u64` units,
319/// so this is the page count we round up to. Picked to match
320/// [`builder::ColumnBuilder`]'s output granularity so chunks shipped from the
321/// merger and chunks shipped from the builder are sized comparably.
322const SHIP_WORDS: usize = 1 << 18;
323
324/// Returns true once the serialized size of `borrow` reaches 10% under
325/// `SHIP_WORDS`.
326///
327/// Monotone in size, deliberately not a window below the boundary. A single
328/// record wider than a window steps clear over it, and a ship signal that
329/// un-fires past the boundary lets a chunk grow until it exceeds the buffer
330/// pool's largest size class, past which a spilled body degrades to
331/// permanently resident. The same heuristic as [`builder::ColumnBuilder`]'s
332/// ship point, lifted out so the builder, the merger, and the
333/// `SizableContainer` impl agree on the signal.
334#[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 `ColumnBuilder`'s ship heuristic: serialized size at the
345        // 2 MiB ship threshold. Aligns chunk-size choices across the two
346        // paths and keeps recipients dealing with a single granularity.
347        //
348        // Serialized chunks (`Bytes` / `Align`) have no typed builder to push
349        // into, so they're trivially "at capacity" — there's no further work
350        // they can absorb.
351        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        // No pre-reservation: chunks are recycled by the merge framework, so
359        // leaf capacities settle to steady-state after the first round and
360        // there is nothing useful to reserve up front. The `SizableContainer`
361        // impl exists so `at_capacity` is callable on result chunks during
362        // `Merger::merge` orchestration; `ensure_capacity` is a required
363        // method on the trait but has no work to do here.
364    }
365}
366
367impl<C: Columnar> ContainerBytes for Column<C> {
368    #[inline]
369    fn from_bytes(bytes: Bytes) -> Self {
370        // Our expectation / hope is that `bytes` is `u64` aligned and sized.
371        // If the alignment is borked, we can relocate. If the size is borked,
372        // not sure what we do in that case. An incorrect size indicates a problem
373        // of `into_bytes`, or a failure of the communication layer, both of which
374        // are unrecoverable.
375        assert_eq!(bytes.len() % 8, 0);
376        if let Ok(_) = bytemuck::try_cast_slice::<_, u64>(&bytes) {
377            Self::Bytes(bytes)
378        } else {
379            // We failed to cast the slice, so we'll reallocate. `Vec<u64>`
380            // is u64-aligned by construction.
381            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/// An exchange function for columnar tuples of the form `((K, V), T, D)`. Rust has a hard
405/// time to figure out the lifetimes of the elements when specified as a closure, so we rather
406/// specify it as a function.
407#[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
419/// Routes a `(D, T, R)` column by the hash of its data column.
420///
421/// Counterpart to [`columnar_exchange`] for collections whose data is not a
422/// key/value pair. Consolidation sites want [`columnar_consolidate_exchange`]
423/// instead.
424pub 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
434/// Routes a `(D, T, R)` column for consolidation, by a fixed-seed AHash of its data column.
435///
436/// Worker assignment is `hash % workers`, so the low bits alone decide the split and the
437/// [`Hashable`] default (FNV) the other exchange functions use diffuses them poorly. The
438/// seed is fixed, so routing is identical across builds and replicas.
439///
440/// Spelled as a function rather than a closure over the hasher state, because the argument
441/// is higher-ranked in its lifetime and closure inference cannot express that.
442pub 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    /// Produce some bytes that are in columnar format.
464    fn raw_columnar_bytes() -> Vec<u8> {
465        let mut raw = Vec::new();
466        raw.extend(16_u64.to_le_bytes()); // offsets
467        raw.extend(28_u64.to_le_bytes()); // length
468        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]); // padding
472        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    /// Assert the desired contents of raw_columnar_bytes so that diagnosing test failures is
509    /// easier.
510    #[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    /// The ship signal is monotone: once it fires it stays fired, even when
555    /// a single wide record steps far past the 2 MiB boundary in one push.
556    #[mz_ore::test]
557    #[cfg_attr(miri, ignore)] // too slow
558    fn ship_threshold_monotone() {
559        use columnar::Push;
560        let mut container = <Vec<u64> as Columnar>::Container::default();
561        // Wider than 10% of any boundary a 25 MiB run can reach.
562        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}