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 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
44/// A batcher for columnar storage.
45///
46/// The chunker is supplied to the arrange operator separately. Callers pass
47/// it explicitly: [`ColumnationChunker`](crate::columnation::ColumnationChunker)
48/// for `Vec<_>` input, or [`batcher::Chunker`] (over a `ColumnationStack<_>`) for
49/// [`Column`] input.
50pub type Col2ValBatcher<K, V, T, R> = MergeBatcher<ColInternalMerger<(K, V), T, R>>;
51/// A batcher for columnar storage with unit values.
52pub type Col2KeyBatcher<K, T, R> = Col2ValBatcher<K, (), T, R>;
53
54/// Pageable counterpart to [`Col2ValBatcher`]. Routes every chunk produced
55/// by chunking, merging, or extract through a [`crate::column_pager::ColumnPager`],
56/// so memory pressure can spill chains to a backing store without touching
57/// the merge / extract bodies.
58///
59/// Drop-in shape at the type level: both aliases take `(K, V, T, R)` and
60/// produce a `Batcher<Input = Column<((K, V), T, R)>, Output = Column<((K,
61/// V), T, R)>>`. Call sites can swap with `cargo fix`–style renaming once
62/// downstream `Trace`/`Builder` impls have been wired up. The pager itself
63/// defaults to [`crate::column_pager::ColumnPager::disabled`]; inject a
64/// real one via [`merge_batcher::ColumnMergeBatcher::set_pager`].
65pub type Col2ValPagedBatcher<K, V, T, R> = merge_batcher::ColumnMergeBatcher<(K, V), T, R>;
66
67/// A container based on a columnar store, encoded in aligned bytes.
68///
69/// The type can represent typed data, bytes from Timely, or an aligned allocation. The name
70/// is singular to express that the preferred format is [`Column::Align`]. The [`Column::Typed`]
71/// variant is used to construct the container, and it owns potentially multiple columns of data.
72pub enum Column<C: Columnar> {
73    /// The typed variant of the container.
74    Typed(C::Container),
75    /// The binary variant of the container.
76    Bytes(Bytes),
77    /// Relocated, aligned binary data, if `Bytes` doesn't work for some reason.
78    ///
79    /// Reasons could include misalignment, cloning of data, or wanting
80    /// to release the `Bytes` as a scarce resource.
81    ///
82    /// `Vec<u64>` guarantees `u64` alignment for the contained bytes.
83    Align(Vec<u64>),
84}
85
86impl<C: Columnar> Column<C> {
87    /// Empties the column, retaining the `Typed` variant's allocation so the
88    /// caller can refill it.
89    ///
90    /// [`columnar::Clear`] clears the typed container in place without
91    /// releasing its capacity. The serialized variants (`Bytes`/`Align`) own
92    /// no reusable typed buffer, so they are reset to an empty `Typed`.
93    #[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    /// True when the column holds no records.
102    ///
103    /// The `Typed` variant answers from the container itself. The serialized
104    /// variants have to reconstruct their borrowed view to reach a length, so
105    /// there this costs as much as [`Column::borrow`].
106    #[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    /// Borrows the container as a reference.
115    #[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            // Typed stays typed, although we would have the option to move to aligned data.
142            // If we did it might be confusing why we couldn't push into a cloned column.
143            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                // We really oughtn't be calling this in this case.
179                // We could convert to owned, but need more constraints on `C`.
180                unimplemented!("Pushing into Column::Bytes without first clearing");
181            }
182        }
183    }
184}
185
186/// Words per 2 MiB. `length_in_words` returns serialized size in `u64` units,
187/// so this is the page count we round up to. Picked to match
188/// [`builder::ColumnBuilder`]'s output granularity so chunks shipped from the
189/// merger and chunks shipped from the builder are sized comparably.
190const SHIP_WORDS: usize = 1 << 18;
191
192/// Returns true once the serialized size of `borrow` reaches 10% under
193/// `SHIP_WORDS`.
194///
195/// Monotone in size, deliberately not a window below the boundary. A single
196/// record wider than a window steps clear over it, and a ship signal that
197/// un-fires past the boundary lets a chunk grow until it exceeds the buffer
198/// pool's largest size class, past which a spilled body degrades to
199/// permanently resident. The same heuristic as [`builder::ColumnBuilder`]'s
200/// ship point, lifted out so the builder, the merger, and the
201/// `SizableContainer` impl agree on the signal.
202#[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 `ColumnBuilder`'s ship heuristic: serialized size at the
213        // 2 MiB ship threshold. Aligns chunk-size choices across the two
214        // paths and keeps recipients dealing with a single granularity.
215        //
216        // Serialized chunks (`Bytes` / `Align`) have no typed builder to push
217        // into, so they're trivially "at capacity" — there's no further work
218        // they can absorb.
219        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        // No pre-reservation: chunks are recycled by the merge framework, so
227        // leaf capacities settle to steady-state after the first round and
228        // there is nothing useful to reserve up front. The `SizableContainer`
229        // impl exists so `at_capacity` is callable on result chunks during
230        // `Merger::merge` orchestration; `ensure_capacity` is a required
231        // method on the trait but has no work to do here.
232    }
233}
234
235impl<C: Columnar> ContainerBytes for Column<C> {
236    #[inline]
237    fn from_bytes(bytes: Bytes) -> Self {
238        // Our expectation / hope is that `bytes` is `u64` aligned and sized.
239        // If the alignment is borked, we can relocate. If the size is borked,
240        // not sure what we do in that case. An incorrect size indicates a problem
241        // of `into_bytes`, or a failure of the communication layer, both of which
242        // are unrecoverable.
243        assert_eq!(bytes.len() % 8, 0);
244        if let Ok(_) = bytemuck::try_cast_slice::<_, u64>(&bytes) {
245            Self::Bytes(bytes)
246        } else {
247            // We failed to cast the slice, so we'll reallocate. `Vec<u64>`
248            // is u64-aligned by construction.
249            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/// An exchange function for columnar tuples of the form `((K, V), T, D)`. Rust has a hard
273/// time to figure out the lifetimes of the elements when specified as a closure, so we rather
274/// specify it as a function.
275#[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    /// Produce some bytes that are in columnar format.
296    fn raw_columnar_bytes() -> Vec<u8> {
297        let mut raw = Vec::new();
298        raw.extend(16_u64.to_le_bytes()); // offsets
299        raw.extend(28_u64.to_le_bytes()); // length
300        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]); // padding
304        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    /// Assert the desired contents of raw_columnar_bytes so that diagnosing test failures is
341    /// easier.
342    #[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    /// The ship signal is monotone: once it fires it stays fired, even when
387    /// a single wide record steps far past the 2 MiB boundary in one push.
388    #[mz_ore::test]
389    #[cfg_attr(miri, ignore)] // too slow
390    fn ship_threshold_monotone() {
391        use columnar::Push;
392        let mut container = <Vec<u64> as Columnar>::Container::default();
393        // Wider than 10% of any boundary a 25 MiB run can reach.
394        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}