Skip to main content

rudb_vector/
chunk.rs

1//! A batch of columns, which is the unit every operator passes to the next one.
2//!
3//! A chunk is some vectors of the same length plus that length. It is not a table and it is not a
4//! result set: it is at most [`VECTOR_SIZE`] rows, because the whole point of the number in
5//! `spec/04-architecture.md` section 4.3 is that a batch of this width stays in L1 while an
6//! operator works on it, and a type that can hold ten times that many rows is a type that lets an
7//! operator quietly stop being vectorized.
8//!
9//! The row count is stored rather than derived, which matters for the one case that looks like a
10//! mistake and is not. `SELECT count(*) FROM t` scans no columns, so the chunk the scan produces
11//! has no vectors in it and still has to say how many rows went past, and a chunk that derived its
12//! length from its first column would say zero.
13
14use rudb_common::{Error, LogicalType, Result, Value};
15
16use crate::selection::Selection;
17use crate::vector::{Form, VECTOR_SIZE, Vector};
18
19/// A batch of columns of equal length.
20#[derive(Debug, Clone, PartialEq)]
21pub struct Chunk {
22    columns: Vec<Vector>,
23    rows: usize,
24    /// The rows a filter kept, when it marked them on the whole chunk rather than cutting them out.
25    /// See [`Chunk::marked`].
26    marked: Option<Selection>,
27}
28
29/// The scheduler's half of the data plane contract, imposed now rather than at layer eight.
30///
31/// `spec/engine/03-data-plane.md` section 3.10. A chunk is what one thread hands another, so a chunk
32/// is `Send`, and that is not free: it rules out an `Rc` anywhere in a vector, it rules out a borrow
33/// of thread local state, and it is what the pin handle in [`Buffer`](crate::Buffer) is protecting
34/// against a lifetime parameter.
35///
36/// It is a static assertion rather than a comment because the failure mode is quiet. Every one of
37/// those mistakes compiles perfectly well on its own and is only a problem the day a chunk is put in
38/// a queue, which is eight layers from here and far too late to be told. This way the build breaks
39/// on the commit that introduces it.
40const _: () = {
41    const fn assert_send<T: Send>() {}
42    assert_send::<Chunk>();
43};
44
45impl Chunk {
46    /// A chunk of `columns`, taking the row count from the first of them.
47    ///
48    /// # Errors
49    ///
50    /// If the columns are not all the same length, or if there are more rows than [`VECTOR_SIZE`].
51    pub fn new(columns: Vec<Vector>) -> Result<Self> {
52        let rows = columns.first().map_or(0, Vector::len);
53        Self::with_rows(columns, rows)
54    }
55
56    /// A chunk of `columns` that is `rows` long, for the case where there are no columns to take
57    /// the count from.
58    ///
59    /// # Errors
60    ///
61    /// If any column is not `rows` long, or if `rows` is more than [`VECTOR_SIZE`].
62    pub fn with_rows(columns: Vec<Vector>, rows: usize) -> Result<Self> {
63        if rows > VECTOR_SIZE {
64            return Err(Error::internal(format!(
65                "a chunk of {rows} rows is longer than the {VECTOR_SIZE} row vector"
66            )));
67        }
68        for (index, column) in columns.iter().enumerate() {
69            if column.len() != rows {
70                return Err(Error::internal(format!(
71                    "column {index} of a chunk is {} rows and the chunk is {rows}",
72                    column.len()
73                )));
74            }
75        }
76        Ok(Self { columns, rows, marked: None })
77    }
78
79    /// A chunk of the given types with no rows in it.
80    ///
81    /// What a scan of an empty table returns and what an operator returns when it is done. The
82    /// types are kept, because a consumer asks a chunk what its columns are before it asks whether
83    /// there are any.
84    #[must_use]
85    pub fn empty(types: &[LogicalType]) -> Self {
86        let columns =
87            types.iter().map(|ty| Vector::constant(ty.clone(), Value::Null, 0)).collect::<Vec<_>>();
88        Self { columns, rows: 0, marked: None }
89    }
90
91    /// The columns.
92    #[must_use]
93    pub fn columns(&self) -> &[Vector] {
94        &self.columns
95    }
96
97    /// One column.
98    ///
99    /// # Errors
100    ///
101    /// If there is no column at `index`.
102    pub fn column(&self, index: usize) -> Result<&Vector> {
103        self.columns.get(index).ok_or_else(|| {
104            Error::internal(format!(
105                "column {index} of a chunk that has {} columns",
106                self.columns.len()
107            ))
108        })
109    }
110
111    /// The columns, given up.
112    #[must_use]
113    pub fn into_columns(self) -> Vec<Vector> {
114        self.columns
115    }
116
117    /// How many columns.
118    #[must_use]
119    pub fn width(&self) -> usize {
120        self.columns.len()
121    }
122
123    /// How many rows.
124    #[must_use]
125    pub fn len(&self) -> usize {
126        self.rows
127    }
128
129    /// Whether there are no rows.
130    #[must_use]
131    pub fn is_empty(&self) -> bool {
132        self.rows == 0
133    }
134
135    /// How many bytes of memory this chunk is holding.
136    ///
137    /// What the memory limit charges for a chunk somebody kept. A chunk handed from one operator to
138    /// the next and dropped is not charged at all, because charging it would count the same
139    /// megabyte once per level of the tree, and the levels of the tree are not where a query runs
140    /// out of memory.
141    ///
142    /// Every size in this workspace counts the thing itself as well as what it owns, so a column's
143    /// own bytes are already in its own number and are not added again here.
144    #[must_use]
145    pub fn footprint(&self) -> usize {
146        size_of::<Self>() + self.columns.iter().map(Vector::footprint).sum::<usize>()
147    }
148
149    /// This chunk with every column's payload held as a page, so that a copy of it is free.
150    ///
151    /// For a chunk that is going to be stored and handed out many times, which is what an in memory
152    /// table's chunks are. See [`Vector::into_pages`] for what it does to each form.
153    #[must_use]
154    pub fn into_pages(self) -> Self {
155        Self {
156            columns: self.columns.into_iter().map(Vector::into_pages).collect(),
157            rows: self.rows,
158            marked: self.marked,
159        }
160    }
161
162    /// This chunk with the rows a filter kept marked on it, and every row still in its columns.
163    ///
164    /// Cutting the kept rows out of a chunk copies every column, and when a filter keeps nearly
165    /// all of them that copy is most of what the filter costs. In TPC-H q01 the date filter keeps
166    /// 98 percent of lineitem and the copy was a fifth of the query. An aggregate can read the
167    /// whole columns instead and count a dropped row into no group, so a filter that feeds one
168    /// directly marks the rows rather than cutting them. Only a consumer that asked for this is
169    /// handed a marked chunk, and [`Chunk::len`] is still the count of every row in the columns.
170    /// Anything that wants the kept rows alone calls [`Chunk::settled`].
171    #[must_use]
172    pub fn marked(mut self, kept: Selection) -> Self {
173        self.marked = Some(kept);
174        self
175    }
176
177    /// The rows a filter kept, when it marked them instead of cutting them out.
178    #[must_use]
179    pub fn kept(&self) -> Option<&Selection> {
180        self.marked.as_ref()
181    }
182
183    /// How many rows the chunk stands for, which is the kept rows of a marked chunk.
184    #[must_use]
185    pub fn live(&self) -> usize {
186        self.marked.as_ref().map_or(self.rows, Selection::len)
187    }
188
189    /// The kept rows alone, cut out the way a filter that did not mark them would have cut them.
190    ///
191    /// # Errors
192    ///
193    /// Whatever [`Chunk::select`] raises.
194    pub fn settled(mut self) -> Result<Self> {
195        match self.marked.take() {
196            Some(kept) => self.select(&kept),
197            None => Ok(self),
198        }
199    }
200
201    /// The type of each column.
202    #[must_use]
203    pub fn types(&self) -> Vec<LogicalType> {
204        self.columns.iter().map(|column| column.logical_type().clone()).collect()
205    }
206
207    /// Validate every storage-backed value reachable from this chunk.
208    pub fn validate_external(&self) -> Result<()> {
209        self.columns.iter().try_for_each(Vector::validate_external)
210    }
211
212    /// The value at a row and a column, or null if either is past the end.
213    ///
214    /// The slow path, same as [`Vector::value_at`]. It is what a result set is read out with and
215    /// what a test asserts on.
216    #[must_use]
217    pub fn value_at(&self, row: usize, column: usize) -> Value {
218        match self.columns.get(column) {
219            Some(held) => held.value_at(row),
220            None => Value::Null,
221        }
222    }
223
224    /// The value at a row and column, preserving storage read and validation failures.
225    pub fn try_value_at(&self, row: usize, column: usize) -> Result<Value> {
226        match self.columns.get(column) {
227            Some(held) => held.try_value_at(row),
228            None => Ok(Value::Null),
229        }
230    }
231
232    /// One row, left to right.
233    pub fn row(&self, row: usize) -> impl Iterator<Item = Value> + '_ {
234        self.columns.iter().map(move |column| column.value_at(row))
235    }
236
237    /// The rows a selection kept, without moving any of the values.
238    ///
239    /// Every column becomes a dictionary vector whose codes are the selection, which is the form
240    /// `spec/07-execution.md` section 7.1 asks a filter to produce rather than compacting. It takes
241    /// the chunk by value because that is what makes it free: the payload is moved into the new
242    /// vector rather than copied, so a filter that keeps one row in a thousand still costs the
243    /// selection and nothing else.
244    ///
245    /// A column that is already a stable dictionary is the one exception, and it composes the two
246    /// levels of codes instead of stacking them. Stacking is just as cheap here and it hides the
247    /// thing that matters: a stable dictionary is a promise that codes from separate chunks name the
248    /// same values, and the aggregate, the group key store and the string kernels all read that
249    /// promise off the outermost body. Wrapping it in a second dictionary breaks the promise, so a
250    /// `GROUP BY SearchPhrase` behind a `WHERE SearchPhrase <> ''` fell off the code path and hashed
251    /// strings instead, which measured at 30 ms of processor time against 4 ms for the same group by
252    /// with nothing in front of it. Composing costs one lookup per kept row and keeps the promise.
253    ///
254    /// # Errors
255    ///
256    /// If the selection points past the end of the chunk.
257    pub fn select(self, selection: &Selection) -> Result<Self> {
258        marked_twice(self.marked.as_ref())?;
259        // See `below` for why this is not the largest position, and every filtered chunk comes
260        // through here.
261        if !crate::vector::below(selection.indices(), self.rows) {
262            let bad = selection.indices().iter().max().copied().unwrap_or_default();
263            return Err(Error::internal(format!(
264                "a selection keeps row {bad} of a chunk that has {} rows",
265                self.rows
266            )));
267        }
268        let rows = selection.len();
269        let codes = selection.indices();
270        let mut columns = Vec::with_capacity(self.columns.len());
271        for column in self.columns {
272            // A packed column read through a dictionary is unpacked again by every reader, and
273            // unpacking it once here costs what one of those reads does. So it is copied out, which
274            // is never worse than selecting it once anything reads it and better as soon as two do.
275            if column.stable_dictionary_parts().is_some() || column.form() == Form::BitPacked {
276                columns.push(column.gather(codes)?);
277            } else {
278                columns.push(Vector::dictionary(codes.to_vec(), column)?);
279            }
280        }
281        Self::with_rows(columns, rows)
282    }
283
284    /// The rows a selection kept, copied, so that nothing downstream reads through an indirection.
285    ///
286    /// The copying counterpart to [`Self::select`], and the two exist because neither one is right
287    /// twice. Which one to call is measured rather than argued, and the measurement says something
288    /// other than what the argument does, so here is both.
289    ///
290    /// The argument is that selecting pays nothing now and one redirection on every later read of
291    /// every kept row, while compacting pays a copy now and nothing afterwards, so the deciding
292    /// variable is selectivity: keep a few rows and select, keep most of them and compact. The
293    /// measurement says the deciding variable is not selectivity at all, it is how many times the
294    /// rows are read again afterwards, and selectivity barely moves the line. On server3, over a
295    /// chunk of two integer columns, compacting loses to selecting at every selectivity from one
296    /// percent to a hundred when there is one later pass over the kept rows, and beats it at every
297    /// selectivity from one percent to a hundred when there are sixteen. With four later passes the
298    /// two are within a few percent of each other everywhere. Put a varchar column in the chunk and
299    /// compaction loses almost everywhere, because copying string bytes is most of what it costs and
300    /// the dictionary it avoids is most of what it saves.
301    ///
302    /// Which is why nothing in the streaming pipeline calls this yet. A filter today feeds an
303    /// aggregate or a projection and that is one pass or two, and end to end on two million rows
304    /// `SELECT sum(a), sum(b), count(*) FROM t WHERE a > ?` measures the same either way at one
305    /// percent selectivity and fifty percent slower compacting at fifty percent selectivity. The
306    /// operators that will want this are the ones that hold chunks rather than pass them on, the
307    /// hash join build side and the sort, because a chunk that is kept alive as a selection keeps
308    /// the whole chunk it was selected from alive with it, and that is a hundred to one on memory
309    /// rather than a few percent on time.
310    ///
311    /// Takes the chunk by value like [`Self::select`] does, even though the payload is copied rather
312    /// than moved, because a caller that still wanted the original after compacting it would be
313    /// holding both copies and should say so.
314    ///
315    /// # Errors
316    ///
317    /// If the selection points past the end of the chunk, or if a column has a type there is no
318    /// vector for, which today means `ARRAY` and `UNION`.
319    pub fn compact(self, selection: &Selection) -> Result<Self> {
320        marked_twice(self.marked.as_ref())?;
321        if let Some(bad) = selection.iter().find(|&index| index >= self.rows) {
322            return Err(Error::internal(format!(
323                "a selection keeps row {bad} of a chunk that has {} rows",
324                self.rows
325            )));
326        }
327        let rows = selection.len();
328        let indices = selection.indices();
329        let mut columns = Vec::with_capacity(self.columns.len());
330        for column in &self.columns {
331            columns.push(column.gather(indices)?);
332        }
333        Self::with_rows(columns, rows)
334    }
335
336    /// The columns at the given positions, in that order.
337    ///
338    /// A position may appear twice, which is what `SELECT x, x FROM t` is, and the second one costs
339    /// a copy. Every other position is moved.
340    ///
341    /// # Errors
342    ///
343    /// If a position is past the end of the chunk.
344    pub fn project(self, positions: &[usize]) -> Result<Self> {
345        let width = self.columns.len();
346        if let Some(&bad) = positions.iter().find(|&&position| position >= width) {
347            return Err(Error::internal(format!(
348                "column {bad} of a chunk that has {width} columns"
349            )));
350        }
351        let rows = self.rows;
352        let mut sources: Vec<Option<Vector>> = self.columns.into_iter().map(Some).collect();
353        let mut columns = Vec::with_capacity(positions.len());
354        for (at, &position) in positions.iter().enumerate() {
355            let last_use = !positions[at + 1..].contains(&position);
356            let taken = if last_use { sources[position].take() } else { sources[position].clone() };
357            match taken {
358                Some(column) => columns.push(column),
359                // Only reachable if the last-use bookkeeping above is wrong, since a position is
360                // taken on its last appearance and cloned on every earlier one.
361                None => {
362                    return Err(Error::internal(format!("column {position} was taken twice")));
363                }
364            }
365        }
366        Self::with_rows(columns, rows)
367    }
368
369    /// The same rows with every column in flat form.
370    ///
371    /// Costs a copy per column that was not already flat. It is here for the result set at the top
372    /// of a query, where the dictionary vectors a filter left behind would otherwise be handed to a
373    /// caller who has to understand them.
374    ///
375    /// # Errors
376    ///
377    /// If a column has a type there is no vector for, which today means `ARRAY` and `UNION`. A `LIST`
378    /// and a `MAP` flatten to themselves and a `STRUCT` to a struct of flattened fields, since none of
379    /// the three has a data slice for a caller to read and there is nothing flatter to become.
380    pub fn flatten(&self) -> Result<Self> {
381        let mut columns = Vec::with_capacity(self.columns.len());
382        for column in &self.columns {
383            // flatten: this is the chunk wide version of the vector call and it exists so that the
384            // one caller at the top of a query can say it once instead of per column. Whether the
385            // copy is deserved is decided where this is called from, which today is one line in
386            // `rudb::database`, and that line says why.
387            columns.push(column.flatten()?);
388        }
389        Self::with_rows(columns, self.rows)
390    }
391
392    /// The same rows in flat form, taking the chunk rather than borrowing it.
393    ///
394    /// The same answer [`Self::flatten`] gives and it costs less for the column that is already
395    /// flat, which is most of them: that column is moved out of this chunk and into the new one
396    /// rather than copied. Borrowing had no way to do that, so flattening a chunk of four flat
397    /// columns of eight thousand rows copied every value for nothing, and at the top of a query of
398    /// six million rows that was a hundred and sixty megabytes copied to produce the bytes it
399    /// already had.
400    ///
401    /// # Errors
402    ///
403    /// The same as [`Self::flatten`].
404    pub fn into_flat(self) -> Result<Self> {
405        let rows = self.rows;
406        let mut columns = Vec::with_capacity(self.columns.len());
407        for column in self.columns {
408            columns.push(column.into_flat()?);
409        }
410        Self::with_rows(columns, rows)
411    }
412}
413
414/// A selection over a chunk that is marked already would pick rows of the whole columns rather than
415/// of the kept ones, so it is refused rather than answered wrong. See [`Chunk::settled`].
416fn marked_twice(marked: Option<&Selection>) -> Result<()> {
417    match marked {
418        Some(_) => Err(Error::internal("a marked chunk was cut before it was settled".to_string())),
419        None => Ok(()),
420    }
421}
422
423#[cfg(test)]
424mod tests {
425    use std::sync::Arc;
426
427    use rudb_common::LogicalType;
428
429    use super::*;
430    use crate::vector::{Data, Form};
431
432    fn integers(values: &[i32]) -> Vector {
433        Vector::flat(LogicalType::Integer, Data::Int32(values.to_vec().into()))
434            .expect("integers are an i32 layout")
435    }
436
437    #[test]
438    fn a_chunk_takes_its_length_from_its_columns() {
439        let chunk = Chunk::new(vec![integers(&[1, 2, 3]), integers(&[4, 5, 6])])
440            .expect("two columns of three");
441        assert_eq!(chunk.len(), 3);
442        assert_eq!(chunk.width(), 2);
443        assert_eq!(chunk.value_at(2, 1), Value::Integer(6));
444    }
445
446    #[test]
447    fn a_ragged_chunk_is_caught() {
448        let error = Chunk::new(vec![integers(&[1, 2, 3]), integers(&[4])])
449            .expect_err("a chunk is not ragged");
450        assert!(error.message().contains("column 1"), "{error}");
451    }
452
453    /// `SELECT count(*) FROM t` scans no columns and the row count still has to survive, which is
454    /// the reason the length is a field rather than the first column's length.
455    #[test]
456    fn a_chunk_with_no_columns_can_still_have_rows() {
457        let chunk = Chunk::with_rows(Vec::new(), 900).expect("no columns and nine hundred rows");
458        assert_eq!(chunk.len(), 900);
459        assert_eq!(chunk.width(), 0);
460        assert!(!chunk.is_empty(), "nine hundred rows is not empty");
461    }
462
463    #[test]
464    fn a_chunk_longer_than_a_vector_is_caught() {
465        let error = Chunk::with_rows(Vec::new(), VECTOR_SIZE + 1).expect_err("too long");
466        assert!(error.message().contains("longer than"), "{error}");
467    }
468
469    #[test]
470    fn an_empty_chunk_keeps_its_types() {
471        let chunk = Chunk::empty(&[LogicalType::Integer, LogicalType::Varchar]);
472        assert_eq!(chunk.len(), 0);
473        assert_eq!(chunk.types(), vec![LogicalType::Integer, LogicalType::Varchar]);
474    }
475
476    #[test]
477    fn selecting_keeps_the_rows_it_selected_and_no_others() {
478        let chunk = Chunk::new(vec![integers(&[10, 20, 30, 40]), integers(&[1, 2, 3, 4])])
479            .expect("four rows");
480        let kept = Selection::from_predicate(4, |index| index % 2 == 1);
481        let chunk = chunk.select(&kept).expect("rows one and three exist");
482        assert_eq!(chunk.len(), 2);
483        assert_eq!(chunk.row(0).collect::<Vec<_>>(), vec![Value::Integer(20), Value::Integer(2)]);
484        assert_eq!(chunk.row(1).collect::<Vec<_>>(), vec![Value::Integer(40), Value::Integer(4)]);
485    }
486
487    /// The reason `select` takes the chunk by value. If it copied the payload then a filter would
488    /// cost the same as a compaction and the selection would be a pure loss.
489    #[test]
490    fn selecting_leaves_the_values_where_they_were() {
491        let chunk = Chunk::new(vec![integers(&[10, 20, 30, 40])]).expect("four rows");
492        let kept = Selection::from_predicate(4, |index| index == 0);
493        let chunk = chunk.select(&kept).expect("row zero exists");
494        assert_eq!(chunk.column(0).expect("one column").form(), Form::Dictionary);
495    }
496
497    /// The promise a stable dictionary makes is about the outermost body, so a filter in front of a
498    /// group by has to compose the codes rather than stack a second dictionary on top of them.
499    #[test]
500    fn selecting_a_stable_dictionary_composes_the_codes_instead_of_stacking_them() {
501        let values = Arc::new(integers(&[10, 20, 30]));
502        let column = Vector::stable_dictionary(vec![2, 0, 1, 2], values).expect("three codes");
503        let chunk = Chunk::new(vec![column]).expect("four rows");
504        let kept = Selection::from_predicate(4, |index| index % 2 == 1);
505        let chunk = chunk.select(&kept).expect("rows one and three exist");
506        let column = chunk.column(0).expect("one column");
507        let (codes, values) = column.stable_dictionary_parts().expect("still a stable dictionary");
508        assert_eq!(codes, [0, 2]);
509        assert_eq!(values.len(), 3);
510        assert_eq!(column.value_at(0), Value::Integer(10));
511        assert_eq!(column.value_at(1), Value::Integer(30));
512    }
513
514    #[test]
515    fn a_selection_past_the_end_is_caught() {
516        let chunk = Chunk::new(vec![integers(&[1, 2])]).expect("two rows");
517        let mut kept = Selection::empty();
518        kept.push(7);
519        let error = chunk.select(&kept).expect_err("row seven does not exist");
520        assert!(error.message().contains("row 7"), "{error}");
521    }
522
523    /// The two halves of section 7.1's decision have to answer the same question the same way, or
524    /// the threshold between them is a place where a query changes its answer.
525    #[test]
526    fn compacting_keeps_the_same_rows_selecting_does_and_leaves_no_indirection() {
527        let chunk = Chunk::new(vec![integers(&[10, 20, 30, 40]), integers(&[1, 2, 3, 4])])
528            .expect("four rows");
529        let kept = Selection::from_predicate(4, |index| index % 2 == 1);
530        let selected = chunk.clone().select(&kept).expect("rows one and three exist");
531        let compacted = chunk.compact(&kept).expect("rows one and three exist");
532        assert_eq!(compacted.len(), selected.len());
533        for row in 0..compacted.len() {
534            assert_eq!(
535                compacted.row(row).collect::<Vec<_>>(),
536                selected.row(row).collect::<Vec<_>>()
537            );
538        }
539        assert_eq!(compacted.column(0).expect("one column").form(), Form::Flat);
540    }
541
542    #[test]
543    fn a_selection_past_the_end_is_caught_by_compacting_too() {
544        let chunk = Chunk::new(vec![integers(&[1, 2])]).expect("two rows");
545        let mut kept = Selection::empty();
546        kept.push(7);
547        let error = chunk.compact(&kept).expect_err("row seven does not exist");
548        assert!(error.message().contains("row 7"), "{error}");
549    }
550
551    #[test]
552    fn projecting_reorders_and_can_repeat_a_column() {
553        let chunk = Chunk::new(vec![integers(&[1, 2]), integers(&[3, 4])]).expect("two by two");
554        let chunk = chunk.project(&[1, 0, 1]).expect("both columns exist");
555        assert_eq!(chunk.width(), 3);
556        assert_eq!(
557            chunk.row(0).collect::<Vec<_>>(),
558            vec![Value::Integer(3), Value::Integer(1), Value::Integer(3)]
559        );
560    }
561
562    #[test]
563    fn projecting_a_column_that_is_not_there_is_caught() {
564        let chunk = Chunk::new(vec![integers(&[1, 2])]).expect("one column");
565        let error = chunk.project(&[0, 4]).expect_err("there is no column four");
566        assert!(error.message().contains("column 4"), "{error}");
567    }
568
569    #[test]
570    fn flattening_a_selected_chunk_gives_the_same_values() {
571        let chunk = Chunk::new(vec![integers(&[10, 20, 30])]).expect("three rows");
572        let kept = Selection::from_predicate(3, |index| index != 1);
573        let selected = chunk.select(&kept).expect("rows zero and two exist");
574        let flat = selected.flatten().expect("integers flatten");
575        assert_eq!(flat.column(0).expect("one column").form(), Form::Flat);
576        for row in 0..flat.len() {
577            assert_eq!(flat.value_at(row, 0), selected.value_at(row, 0), "row {row}");
578        }
579    }
580
581    /// Taking the chunk rather than borrowing it, which is the same flatten and is the one that
582    /// gets to move a column that is already flat instead of copying it.
583    #[test]
584    fn flattening_a_chunk_of_mixed_forms_moves_the_column_that_is_already_flat() {
585        let flat = integers(&[10, 20, 30]);
586        let address = |vector: &Vector| match vector.data() {
587            Some(Data::Int32(values)) => values.as_slice().as_ptr() as usize,
588            _ => panic!("the layout changed under the test"),
589        };
590        let stored = address(&flat);
591        let coded = Vector::dictionary(vec![2, 1, 0], integers(&[1, 2, 3])).expect("three codes");
592        let chunk = Chunk::new(vec![flat, coded]).expect("three rows of two columns");
593        let want: Vec<Vec<_>> = (0..3).map(|row| chunk.row(row).collect()).collect();
594        let flattened = chunk.into_flat().expect("integers flatten");
595        assert_eq!(address(flattened.column(0).expect("the first column")), stored);
596        for column in flattened.columns() {
597            assert_eq!(column.form(), Form::Flat);
598        }
599        let got: Vec<Vec<_>> = (0..3).map(|row| flattened.row(row).collect()).collect();
600        assert_eq!(got, want);
601    }
602
603    #[test]
604    fn a_chunk_costs_what_its_columns_cost() {
605        let chunk = Chunk::new(vec![integers(&[1; 1000]), integers(&[2; 1000])])
606            .expect("two columns of a thousand");
607        let columns: usize = chunk.columns().iter().map(Vector::footprint).sum();
608        assert_eq!(chunk.footprint(), size_of::<Chunk>() + columns);
609        assert!(chunk.footprint() >= 8000, "two thousand i32: {}", chunk.footprint());
610    }
611}