Skip to main content

rudb_vector/
vector.rs

1//! The vector itself.
2//!
3//! `spec/07-execution.md` section 7.1 calls this the widest interface in the system, says every
4//! operator depends on it, and says changing it after twenty operators exist is expensive. So it
5//! is written before the first operator rather than after the fifth.
6//!
7//! A vector is a type, a length of at most [`VECTOR_SIZE`], a physical form, a validity
8//! representation and some data. The four forms are the ones in `spec/04-architecture.md` section
9//! 4.3: flat, constant, sequence and dictionary. Encoded, the fifth, is the M3 work and it arrives
10//! with the specialization contract rather than before it.
11//!
12//! **What is not here yet.** Buffers are owned. Section 7.1 says a vector borrowed from a buffer
13//! managed page carries a pin, and there is no buffer manager until M2, so there is nothing to pin
14//! and pretending otherwise would be an interface built against an imaginary caller. Nested types
15//! are not stored yet either, for the same reason: a `LIST(STRUCT(...))` is offsets plus child
16//! column chunks, and child column chunks are storage.
17
18use rudb_common::{Error, LogicalType, Result, Value};
19
20use crate::string::{StringColumn, StringView};
21use crate::validity::Validity;
22
23/// How many values are in a full vector.
24///
25/// 1024 rather than DuckDB's 2048, per `spec/04-architecture.md` section 4.3. It is the FastLanes
26/// unit, it makes a validity mask exactly 16 `u64` words, and it keeps a vector of 16 byte string
27/// views at 16 KiB, which is the size at which several of these fit in L1 together rather than
28/// evicting each other.
29pub const VECTOR_SIZE: usize = 1024;
30
31/// Which physical form a vector is in.
32///
33/// An operator asks this once per vector and then takes the path it wants, which is the one branch
34/// per vector that the whole design is willing to spend.
35///
36/// Not exhaustive, and that is a decision rather than an oversight. `Encoded` is the fifth form
37/// and it arrives at layer three with the specialization contract. If this enum were exhaustive,
38/// the day it lands is the day every kernel in the workspace stops compiling, and the pressure at
39/// that moment would be to add an arm to each of them in a hurry rather than to think about what
40/// each one should do with an encoded vector. A required fallback arm means each kernel already
41/// has a correct answer for a form it has never seen, and specializing it is then a change that
42/// can be made one kernel at a time with a benchmark next to it.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44#[non_exhaustive]
45pub enum Form {
46    /// One value per position.
47    Flat,
48    /// One value, repeated.
49    Constant,
50    /// A start and a step, computed rather than stored.
51    Sequence,
52    /// Codes into a smaller vector of distinct values.
53    Dictionary,
54}
55
56/// The values of a flat vector, one Rust vector per physical type.
57///
58/// The variants are physical rather than logical, which is what lets `DATE` and `INTEGER` share
59/// storage and share a kernel. What a run of `i32` means is the vector's logical type's business.
60#[derive(Debug, Clone, PartialEq)]
61#[non_exhaustive]
62pub enum Data {
63    /// No values, for the type of an untyped `NULL`.
64    Empty,
65    /// One byte per value.
66    Bool(Vec<bool>),
67    /// 8 bit signed.
68    Int8(Vec<i8>),
69    /// 16 bit signed.
70    Int16(Vec<i16>),
71    /// 32 bit signed.
72    Int32(Vec<i32>),
73    /// 64 bit signed.
74    Int64(Vec<i64>),
75    /// 128 bit signed.
76    Int128(Vec<i128>),
77    /// 8 bit unsigned.
78    UInt8(Vec<u8>),
79    /// 16 bit unsigned.
80    UInt16(Vec<u16>),
81    /// 32 bit unsigned.
82    UInt32(Vec<u32>),
83    /// 64 bit unsigned.
84    UInt64(Vec<u64>),
85    /// 128 bit unsigned.
86    UInt128(Vec<u128>),
87    /// IEEE 754 binary32.
88    Float32(Vec<f32>),
89    /// IEEE 754 binary64.
90    Float64(Vec<f64>),
91    /// The months, days and microseconds triple.
92    Interval(Vec<(i32, i32, i64)>),
93    /// Strings, as 16 byte views plus the arena the long ones live in.
94    Varlen(StringColumn),
95}
96
97impl Data {
98    /// How many values are stored.
99    #[must_use]
100    pub fn len(&self) -> usize {
101        match self {
102            Self::Empty => 0,
103            Self::Bool(v) => v.len(),
104            Self::Int8(v) => v.len(),
105            Self::Int16(v) => v.len(),
106            Self::Int32(v) => v.len(),
107            Self::Int64(v) => v.len(),
108            Self::Int128(v) => v.len(),
109            Self::UInt8(v) => v.len(),
110            Self::UInt16(v) => v.len(),
111            Self::UInt32(v) => v.len(),
112            Self::UInt64(v) => v.len(),
113            Self::UInt128(v) => v.len(),
114            Self::Float32(v) => v.len(),
115            Self::Float64(v) => v.len(),
116            Self::Interval(v) => v.len(),
117            Self::Varlen(v) => v.len(),
118        }
119    }
120
121    /// Whether there are no values.
122    #[must_use]
123    pub fn is_empty(&self) -> bool {
124        self.len() == 0
125    }
126
127    /// An integer at `index`, widened, for any of the signed integer layouts.
128    ///
129    /// Used by the decimal path, which needs the unscaled value out of whichever width the width
130    /// and scale picked, and by anything else that would otherwise repeat the same five arms.
131    #[must_use]
132    pub fn signed_at(&self, index: usize) -> Option<i128> {
133        match self {
134            Self::Int8(v) => v.get(index).map(|&x| i128::from(x)),
135            Self::Int16(v) => v.get(index).map(|&x| i128::from(x)),
136            Self::Int32(v) => v.get(index).map(|&x| i128::from(x)),
137            Self::Int64(v) => v.get(index).map(|&x| i128::from(x)),
138            Self::Int128(v) => v.get(index).copied(),
139            _ => None,
140        }
141    }
142
143    /// An unsigned integer at `index`, widened.
144    #[must_use]
145    pub fn unsigned_at(&self, index: usize) -> Option<u128> {
146        match self {
147            Self::UInt8(v) => v.get(index).map(|&x| u128::from(x)),
148            Self::UInt16(v) => v.get(index).map(|&x| u128::from(x)),
149            Self::UInt32(v) => v.get(index).map(|&x| u128::from(x)),
150            Self::UInt64(v) => v.get(index).map(|&x| u128::from(x)),
151            Self::UInt128(v) => v.get(index).copied(),
152            _ => None,
153        }
154    }
155
156    /// The string at `index`, for a `Varlen`.
157    #[must_use]
158    pub fn str_at(&self, index: usize) -> Option<&str> {
159        match self {
160            Self::Varlen(column) => column.get(index),
161            _ => None,
162        }
163    }
164}
165
166/// A type, a length, a validity representation and some data.
167#[derive(Debug, Clone, PartialEq)]
168pub struct Vector {
169    ty: LogicalType,
170    len: usize,
171    validity: Validity,
172    body: Body,
173}
174
175/// What the vector holds, which is what its form is decided by.
176#[derive(Debug, Clone, PartialEq)]
177enum Body {
178    Flat(Data),
179    Constant(Box<Value>),
180    Sequence { start: i64, step: i64 },
181    Dictionary { codes: Vec<u32>, values: Box<Vector> },
182}
183
184impl Vector {
185    /// A flat vector of `data`, all valid.
186    ///
187    /// # Errors
188    ///
189    /// If the data's physical layout is not the one the type calls for. That check is here rather
190    /// than left to the caller because a vector whose type and layout disagree is a wrong answer
191    /// waiting to be read out, and it costs one comparison at construction to prevent.
192    pub fn flat(ty: LogicalType, data: Data) -> Result<Self> {
193        let len = data.len();
194        if !matches!(data, Data::Empty) && layout_of(&data) != ty.physical() {
195            return Err(Error::internal(format!(
196                "a {ty} vector cannot hold {:?} data",
197                layout_of(&data)
198            )));
199        }
200        Ok(Self { ty, len, validity: Validity::AllValid, body: Body::Flat(data) })
201    }
202
203    /// A flat vector built from single values, with the nulls among them turning into validity.
204    ///
205    /// The slow way in, and the only way in that anything outside this crate has. It is what an
206    /// `INSERT`, a `VALUES` clause and a test build a column with, all of which arrive holding
207    /// values rather than a run of `i32`. Nothing on a scan path calls it: a scan produces a run of
208    /// data directly and hands it to [`Self::flat`].
209    ///
210    /// # Errors
211    ///
212    /// If a value is not one the type can hold, or if the type is one that cannot be stored flat
213    /// yet, which today means the nested types.
214    pub fn from_values(ty: LogicalType, values: &[Value]) -> Result<Self> {
215        let mut data = empty_data_for(&ty)?;
216        for value in values {
217            push_value(&mut data, value)?;
218        }
219        let validity = Validity::from_iter(values.len(), |index| !values[index].is_null());
220        Ok(Self { ty, len: values.len(), validity, body: Body::Flat(data) })
221    }
222
223    /// A vector of `len` copies of one value.
224    ///
225    /// Costs one value regardless of the length, which is what makes a literal in a predicate free
226    /// and what makes a projection of a constant free.
227    #[must_use]
228    pub fn constant(ty: LogicalType, value: Value, len: usize) -> Self {
229        let validity = if value.is_null() { Validity::AllInvalid } else { Validity::AllValid };
230        Self { ty, len, validity, body: Body::Constant(Box::new(value)) }
231    }
232
233    /// A vector of `len` values starting at `start` and stepping by `step`.
234    ///
235    /// This is what a row identifier column is, and it costs sixteen bytes rather than eight
236    /// kilobytes. A scan that produces row ids for a later fetch produces one of these.
237    #[must_use]
238    pub fn sequence(start: i64, step: i64, len: usize) -> Self {
239        Self {
240            ty: LogicalType::BigInt,
241            len,
242            validity: Validity::AllValid,
243            body: Body::Sequence { start, step },
244        }
245    }
246
247    /// A vector of codes into a smaller vector of distinct values.
248    ///
249    /// The form the whole M3 thesis rests on. A dictionary vector handed to a group by is an
250    /// integer column, and an aggregate over one is an aggregate over integers no matter what the
251    /// logical type says.
252    ///
253    /// A dictionary over a dictionary is composed into one level here rather than left as two, so
254    /// the form has a depth of one always and a kernel that reads [`Self::dictionary_parts`] is
255    /// reading the values rather than another layer of codes. Two filters over the same chunk build
256    /// the second case and four conjuncts pushed down separately build four of it.
257    ///
258    /// The cost of leaving them stacked turned out to be a cliff rather than a slope. Every loop in
259    /// `rudb-kernels` reaches for the values behind the codes with [`Self::data`], a dictionary
260    /// pointing at a dictionary has no data to hand back, so the second level does not make the
261    /// kernels slower, it turns them off and drops the work onto the row at a time path that exists
262    /// to be correct rather than fast. Measured on server3 over a chunk of two numeric columns and a
263    /// consumer of two vectorized passes, one level reads at 3.5 nanoseconds a row and two levels at
264    /// 104, and the third and fourth levels cost almost nothing more because the first one had
265    /// already given up everything there was to give. Composing is one pass over the outer codes,
266    /// which the range check above is already making.
267    ///
268    /// The one dictionary that is not composed past is one carrying a validity of its own. A
269    /// dictionary is built all valid and only [`Self::with_validity`] can change that, so such a
270    /// vector is saying that its nulls are at this level rather than in the values it points at, and
271    /// composing past it would drop them.
272    ///
273    /// # Errors
274    ///
275    /// If any code is past the end of the value vector.
276    pub fn dictionary(codes: Vec<u32>, values: Vector) -> Result<Self> {
277        if let Some(&bad) = codes.iter().find(|&&code| code as usize >= values.len()) {
278            return Err(Error::internal(format!(
279                "dictionary code {bad} is past the end of a {} value dictionary",
280                values.len()
281            )));
282        }
283        let (codes, values) = compose(codes, values);
284        Ok(Self {
285            ty: values.ty.clone(),
286            len: codes.len(),
287            validity: Validity::AllValid,
288            body: Body::Dictionary { codes, values: Box::new(values) },
289        })
290    }
291
292    /// The same vector with a different validity.
293    #[must_use]
294    pub fn with_validity(mut self, validity: Validity) -> Self {
295        self.validity = validity;
296        self
297    }
298
299    /// What kind of values these are.
300    #[must_use]
301    pub fn logical_type(&self) -> &LogicalType {
302        &self.ty
303    }
304
305    /// How many values there are.
306    #[must_use]
307    pub fn len(&self) -> usize {
308        self.len
309    }
310
311    /// Whether there are no values.
312    #[must_use]
313    pub fn is_empty(&self) -> bool {
314        self.len == 0
315    }
316
317    /// Which of the values are not null.
318    #[must_use]
319    pub fn validity(&self) -> &Validity {
320        &self.validity
321    }
322
323    /// Which physical form this vector is in.
324    #[must_use]
325    pub fn form(&self) -> Form {
326        match self.body {
327            Body::Flat(_) => Form::Flat,
328            Body::Constant(_) => Form::Constant,
329            Body::Sequence { .. } => Form::Sequence,
330            Body::Dictionary { .. } => Form::Dictionary,
331        }
332    }
333
334    /// The data, for a flat vector, and `None` for any other form.
335    ///
336    /// A kernel that wants a slice asks for it and takes the flat path if it gets one. A kernel
337    /// that can do better on a constant or a dictionary checks [`Self::form`] first.
338    #[must_use]
339    pub fn data(&self) -> Option<&Data> {
340        match &self.body {
341            Body::Flat(data) => Some(data),
342            _ => None,
343        }
344    }
345
346    /// The one value, for a constant vector, and `None` for any other form.
347    ///
348    /// A kernel comparing a column against a literal wants the literal once rather than 1024
349    /// times, and [`Self::value_at`] on a constant clones it on every call because it has to be
350    /// able to hand back a `Value` for any form. This is the accessor that lets the specialized
351    /// path hoist the clone out of the loop.
352    #[must_use]
353    pub fn constant_value(&self) -> Option<&Value> {
354        match &self.body {
355            Body::Constant(value) => Some(value.as_ref()),
356            _ => None,
357        }
358    }
359
360    /// The codes and the values, for a dictionary vector, and `None` for any other form.
361    ///
362    /// The reason a kernel needs this rather than reading the dictionary through
363    /// [`Self::value_at`] is the entire argument for the form existing. A filter against a
364    /// dictionary column of 1024 rows and 40 distinct values is 40 comparisons and 1024 lookups,
365    /// not 1024 comparisons, and there is no way to write that loop without seeing the codes.
366    ///
367    /// Note what the validity of the returned vector means. A dictionary keeps its nulls in the
368    /// vector it points at, and the dictionary's own validity says nothing about them, so a caller
369    /// deciding whether row `i` is null has to ask the value vector about `codes[i]` rather than
370    /// asking this vector about `i`. [`Self::flatten`] has the same note on it for the same
371    /// reason, because getting this wrong is a null that survives being selected and comes out as
372    /// a zero.
373    #[must_use]
374    pub fn dictionary_parts(&self) -> Option<(&[u32], &Self)> {
375        match &self.body {
376            Body::Dictionary { codes, values } => Some((codes, values.as_ref())),
377            _ => None,
378        }
379    }
380
381    /// The start and the step, for a sequence vector, and `None` for any other form.
382    #[must_use]
383    pub fn sequence_parts(&self) -> Option<(i64, i64)> {
384        match self.body {
385            Body::Sequence { start, step } => Some((start, step)),
386            _ => None,
387        }
388    }
389
390    /// The value at `index`, as a single value.
391    ///
392    /// This is the slow path on purpose. It is what a result set is read out with and what a test
393    /// asserts on, and an operator that calls it per row is an operator that has already lost the
394    /// argument the vector interface exists to win.
395    #[must_use]
396    pub fn value_at(&self, index: usize) -> Value {
397        if index >= self.len || !self.validity.is_valid(index) {
398            return Value::Null;
399        }
400        match &self.body {
401            Body::Constant(value) => value.as_ref().clone(),
402            Body::Sequence { start, step } => Value::BigInt(start + step * index as i64),
403            Body::Dictionary { codes, values } => match codes.get(index) {
404                Some(&code) => values.value_at(code as usize),
405                None => Value::Null,
406            },
407            Body::Flat(data) => value_from(&self.ty, data, index),
408        }
409    }
410
411    /// Every value in order, as single values.
412    pub fn iter(&self) -> impl Iterator<Item = Value> + '_ {
413        (0..self.len).map(|index| self.value_at(index))
414    }
415
416    /// The same values in flat form.
417    ///
418    /// Flattening a vector that is already flat is free. Flattening any other form costs a copy,
419    /// which is exactly why the other forms exist and why nothing on the hot path should call
420    /// this. It is here for the operators that genuinely cannot do better and for the tests that
421    /// check the other forms against it.
422    ///
423    /// # Errors
424    ///
425    /// If the type is one this crate cannot store flat yet, which today means the nested types.
426    pub fn flatten(&self) -> Result<Self> {
427        if let Body::Flat(_) = self.body {
428            return Ok(self.clone());
429        }
430        self.copied((0..self.len).collect(), false)
431    }
432
433    /// The values at the given positions, copied, in a form that does not point back at this vector.
434    ///
435    /// This is the copying counterpart to [`Self::dictionary`], and the two are the two halves of
436    /// the decision `spec/07-execution.md` section 7.1 describes. Which half is right is measured
437    /// rather than argued, and [`Chunk::compact`](crate::Chunk::compact) is where the measurement
438    /// is written down.
439    ///
440    /// A dictionary chain is walked to its leaf first and the codes composed on the way down, so the
441    /// copy runs once over the data rather than once per level, and a position that is null at any
442    /// level comes out null here. The copy is a typed loop per physical layout rather than a `Value`
443    /// per row, which is the whole point of it and is what [`Self::flatten`] now goes through too.
444    ///
445    /// # Errors
446    ///
447    /// If the type has no flat layout, which today means the nested types.
448    pub fn gather(&self, indices: &[u32]) -> Result<Self> {
449        self.copied(indices.iter().map(|&index| index as usize).collect(), true)
450    }
451
452    /// The copy both [`Self::gather`] and [`Self::flatten`] are.
453    ///
454    /// `constants_stay` is the one thing the two want differently. A gather of a constant is a
455    /// shorter constant and copying it out would be a thousand writes of the same value for nothing,
456    /// but flattening promises flat form to a caller that is about to read the data slice, so for
457    /// that one the constant has to be written out.
458    fn copied(&self, at: Vec<usize>, constants_stay: bool) -> Result<Self> {
459        let rows = at.len();
460        let (at, leaf) = self.resolve(at);
461        let live: Vec<bool> = at.iter().map(|&index| index != NOWHERE).collect();
462        let validity = Validity::from_run(&live);
463        let body = match &leaf.body {
464            // Every position holds the same value, so the only thing the gather can change is the
465            // length and which positions are null. A gather with no null in it is still a constant.
466            Body::Constant(value) => {
467                if constants_stay && matches!(validity, Validity::AllValid) {
468                    return Ok(Self::constant(self.ty.clone(), value.as_ref().clone(), rows));
469                }
470                let mut data = empty_data_for(&self.ty)?;
471                for &index in &at {
472                    push_value(&mut data, if index == NOWHERE { &Value::Null } else { value })?;
473                }
474                Body::Flat(data)
475            }
476            // A sequence is arithmetic rather than storage, so the gather is the arithmetic done at
477            // the positions asked for, and a null writes the zero every other layout writes.
478            Body::Sequence { start, step } => Body::Flat(Data::Int64(
479                at.iter()
480                    .map(|&index| if index == NOWHERE { 0 } else { start + step * index as i64 })
481                    .collect(),
482            )),
483            // A flat body with no values is the untyped null, so every position asked for is null
484            // whatever was asked for. Going through the copy would build a run of no values and
485            // call it `rows` long, which is a vector whose length and data disagree.
486            Body::Flat(Data::Empty) => {
487                return Ok(Self::constant(self.ty.clone(), Value::Null, rows));
488            }
489            Body::Flat(data) => Body::Flat(copy_of(data, &at)),
490            // Unreachable, because `resolve` stops at the first body that is not a dictionary.
491            Body::Dictionary { .. } => {
492                return Err(Error::internal("a dictionary survived being resolved"));
493            }
494        };
495        Ok(Self { ty: self.ty.clone(), len: rows, validity, body })
496    }
497
498    /// Where each wanted position lives in the first body that is not a dictionary, and that body.
499    ///
500    /// A position that is null anywhere on the way down, or past the end of anything on the way
501    /// down, comes back as [`NOWHERE`]. That single sentinel is what keeps the copy loop from
502    /// carrying a validity mask alongside the positions it is already walking.
503    fn resolve(&self, mut at: Vec<usize>) -> (Vec<usize>, &Self) {
504        let mut source = self;
505        loop {
506            for slot in &mut at {
507                if *slot >= source.len || !source.validity.is_valid(*slot) {
508                    *slot = NOWHERE;
509                }
510            }
511            let Body::Dictionary { codes, values } = &source.body else {
512                return (at, source);
513            };
514            for slot in &mut at {
515                *slot = match codes.get(*slot) {
516                    Some(&code) => code as usize,
517                    None => NOWHERE,
518                };
519            }
520            source = values.as_ref();
521        }
522    }
523}
524
525/// One level of dictionary out of however many levels were handed to [`Vector::dictionary`].
526///
527/// Every dictionary in the system is built through that constructor and every one of them comes
528/// through here first, so the invariant this maintains is that the vector a dictionary points at is
529/// never itself a dictionary that could have been composed away. That makes the work a single `if`
530/// rather than a loop: the inner vector was already composed when it was built, so composing the
531/// outer codes through it leaves the result no deeper than the inner vector already was.
532///
533/// The codes are indexed rather than fetched with `get`, because the caller has already walked the
534/// whole outer array to check that every code is in range and the inner array is exactly as long as
535/// the vector those codes were checked against.
536fn compose(codes: Vec<u32>, values: Vector) -> (Vec<u32>, Vector) {
537    // A dictionary carrying a validity of its own is one whose nulls live at this level rather than
538    // in the values, which is the one thing composition cannot carry down with it.
539    if !matches!(values.validity, Validity::AllValid) {
540        return (codes, values);
541    }
542    let Vector { ty, len, validity, body } = values;
543    match body {
544        Body::Dictionary { codes: inner, values: leaf } => {
545            debug_assert!(
546                !matches!(leaf.body, Body::Dictionary { .. })
547                    || !matches!(leaf.validity, Validity::AllValid),
548                "a dictionary was stacked on a dictionary without going through the constructor"
549            );
550            (codes.iter().map(|&code| inner[code as usize]).collect(), *leaf)
551        }
552        body => (codes, Vector { ty, len, validity, body }),
553    }
554}
555
556/// The position of a value that is not anywhere, because it is null or out of range.
557///
558/// `usize::MAX` rather than an `Option<usize>`, because the copy loop's bounds check rejects it for
559/// free and an `Option` would put a second branch next to the one already there.
560const NOWHERE: usize = usize::MAX;
561
562/// A run of data copied at the given positions, with a zero wherever the position is [`NOWHERE`].
563///
564/// A zero and not a skip, because every layout here is a parallel array to a validity mask and a
565/// short one would put every value after the first null at the wrong index. It is the same rule
566/// [`push_value`] follows for a null.
567fn copy_of(data: &Data, at: &[usize]) -> Data {
568    macro_rules! copied {
569        ($values:expr, $variant:path, $zero:expr) => {{
570            let values = $values;
571            let mut out = Vec::with_capacity(at.len());
572            for &index in at {
573                // One bounds check rather than a null test and a bounds check, because `NOWHERE` is
574                // past the end of every slice there can be.
575                out.push(values.get(index).copied().unwrap_or($zero));
576            }
577            $variant(out)
578        }};
579    }
580    match data {
581        Data::Empty => Data::Empty,
582        Data::Bool(values) => copied!(values, Data::Bool, false),
583        Data::Int8(values) => copied!(values, Data::Int8, 0),
584        Data::Int16(values) => copied!(values, Data::Int16, 0),
585        Data::Int32(values) => copied!(values, Data::Int32, 0),
586        Data::Int64(values) => copied!(values, Data::Int64, 0),
587        Data::Int128(values) => copied!(values, Data::Int128, 0),
588        Data::UInt8(values) => copied!(values, Data::UInt8, 0),
589        Data::UInt16(values) => copied!(values, Data::UInt16, 0),
590        Data::UInt32(values) => copied!(values, Data::UInt32, 0),
591        Data::UInt64(values) => copied!(values, Data::UInt64, 0),
592        Data::UInt128(values) => copied!(values, Data::UInt128, 0),
593        Data::Float32(values) => copied!(values, Data::Float32, 0.0),
594        Data::Float64(values) => copied!(values, Data::Float64, 0.0),
595        Data::Interval(values) => copied!(values, Data::Interval, (0, 0, 0)),
596        // The one layout where a gather is a copy of bytes rather than a copy of fixed width slots,
597        // and the reason compaction is a decision rather than a default on a string column.
598        Data::Varlen(values) => {
599            let mut out = StringColumn::with_capacity(at.len());
600            // The bytes are known before any of them are copied, because a view carries its length
601            // and the wanted positions are already in hand, so the arena is one allocation rather
602            // than a run of doublings that each copy what the last one copied.
603            let views = values.views();
604            out.reserve_bytes(
605                at.iter()
606                    .filter_map(|&index| views.get(index))
607                    .filter(|view| !view.is_inline())
608                    .map(StringView::len)
609                    .sum(),
610            );
611            for &index in at {
612                out.push(values.get(index).unwrap_or(""));
613            }
614            Data::Varlen(out)
615        }
616    }
617}
618
619/// The physical layout a run of data is in, for the check that it matches its type.
620fn layout_of(data: &Data) -> rudb_common::PhysicalType {
621    use rudb_common::PhysicalType as P;
622    match data {
623        Data::Empty => P::Empty,
624        Data::Bool(_) => P::Bool,
625        Data::Int8(_) => P::Int8,
626        Data::Int16(_) => P::Int16,
627        Data::Int32(_) => P::Int32,
628        Data::Int64(_) => P::Int64,
629        Data::Int128(_) => P::Int128,
630        Data::UInt8(_) => P::UInt8,
631        Data::UInt16(_) => P::UInt16,
632        Data::UInt32(_) => P::UInt32,
633        Data::UInt64(_) => P::UInt64,
634        Data::UInt128(_) => P::UInt128,
635        Data::Float32(_) => P::Float32,
636        Data::Float64(_) => P::Float64,
637        Data::Interval(_) => P::Interval,
638        Data::Varlen(_) => P::Varlen,
639    }
640}
641
642/// One value out of a run of data, given what the run means.
643///
644/// The match is on the logical type rather than on the data, because the data cannot tell a `DATE`
645/// from an `INTEGER` and that is the whole reason the two are kept apart.
646fn value_from(ty: &LogicalType, data: &Data, index: usize) -> Value {
647    let signed = || data.signed_at(index);
648    let unsigned = || data.unsigned_at(index);
649    let value = match ty {
650        LogicalType::Boolean => match data {
651            Data::Bool(v) => v.get(index).map(|&x| Value::Boolean(x)),
652            _ => None,
653        },
654        LogicalType::TinyInt => signed().and_then(|x| i8::try_from(x).ok()).map(Value::TinyInt),
655        LogicalType::SmallInt => signed().and_then(|x| i16::try_from(x).ok()).map(Value::SmallInt),
656        LogicalType::Integer => signed().and_then(|x| i32::try_from(x).ok()).map(Value::Integer),
657        LogicalType::BigInt => signed().and_then(|x| i64::try_from(x).ok()).map(Value::BigInt),
658        LogicalType::HugeInt => signed().map(Value::HugeInt),
659        LogicalType::UTinyInt => unsigned().and_then(|x| u8::try_from(x).ok()).map(Value::UTinyInt),
660        LogicalType::USmallInt => {
661            unsigned().and_then(|x| u16::try_from(x).ok()).map(Value::USmallInt)
662        }
663        LogicalType::UInteger => {
664            unsigned().and_then(|x| u32::try_from(x).ok()).map(Value::UInteger)
665        }
666        LogicalType::UBigInt => unsigned().and_then(|x| u64::try_from(x).ok()).map(Value::UBigInt),
667        LogicalType::UHugeInt => unsigned().map(Value::UHugeInt),
668        LogicalType::Float => match data {
669            Data::Float32(v) => v.get(index).map(|&x| Value::Float(x)),
670            _ => None,
671        },
672        LogicalType::Double => match data {
673            Data::Float64(v) => v.get(index).map(|&x| Value::Double(x)),
674            _ => None,
675        },
676        LogicalType::Decimal { width, scale } => {
677            signed().map(|unscaled| Value::Decimal { unscaled, width: *width, scale: *scale })
678        }
679        LogicalType::Varchar => data.str_at(index).map(|s| Value::Varchar(s.to_string())),
680        LogicalType::Blob | LogicalType::Bit => {
681            data.str_at(index).map(|s| Value::Blob(s.as_bytes().to_vec()))
682        }
683        LogicalType::Date => signed().and_then(|x| i32::try_from(x).ok()).map(Value::Date),
684        LogicalType::Time | LogicalType::TimeTz => {
685            signed().and_then(|x| i64::try_from(x).ok()).map(Value::Time)
686        }
687        LogicalType::Timestamp
688        | LogicalType::TimestampS
689        | LogicalType::TimestampMs
690        | LogicalType::TimestampNs
691        | LogicalType::TimestampTz => {
692            signed().and_then(|x| i64::try_from(x).ok()).map(Value::Timestamp)
693        }
694        LogicalType::Interval => match data {
695            Data::Interval(v) => {
696                v.get(index).map(|&(months, days, micros)| Value::Interval { months, days, micros })
697            }
698            _ => None,
699        },
700        _ => None,
701    };
702    value.unwrap_or(Value::Null)
703}
704
705/// An empty run of data of the right layout for a type.
706fn empty_data_for(ty: &LogicalType) -> Result<Data> {
707    use rudb_common::PhysicalType as P;
708    Ok(match ty.physical() {
709        P::Empty => Data::Empty,
710        P::Bool => Data::Bool(Vec::new()),
711        P::Int8 => Data::Int8(Vec::new()),
712        P::Int16 => Data::Int16(Vec::new()),
713        P::Int32 => Data::Int32(Vec::new()),
714        P::Int64 => Data::Int64(Vec::new()),
715        P::Int128 => Data::Int128(Vec::new()),
716        P::UInt8 => Data::UInt8(Vec::new()),
717        P::UInt16 => Data::UInt16(Vec::new()),
718        P::UInt32 => Data::UInt32(Vec::new()),
719        P::UInt64 => Data::UInt64(Vec::new()),
720        P::UInt128 => Data::UInt128(Vec::new()),
721        P::Float32 => Data::Float32(Vec::new()),
722        P::Float64 => Data::Float64(Vec::new()),
723        P::Interval => Data::Interval(Vec::new()),
724        P::Varlen => Data::Varlen(StringColumn::new()),
725        other => {
726            return Err(Error::not_implemented(format!(
727                "a flat vector of {other:?} data, which arrives with the storage layer"
728            )));
729        }
730    })
731}
732
733/// Appends one value to a run of data, or a zero of the right shape when it is null.
734///
735/// The zero matters. A null still occupies a position, the validity mask is what says it is null,
736/// and a run of data with a hole in it would put every value after the hole in the wrong place.
737fn push_value(data: &mut Data, value: &Value) -> Result<()> {
738    macro_rules! push {
739        ($vec:expr, $variant:path, $zero:expr) => {
740            match value {
741                Value::Null => $vec.push($zero),
742                $variant(x) => $vec.push(*x),
743                other => {
744                    return Err(Error::internal(format!(
745                        "{other:?} does not belong in this vector"
746                    )));
747                }
748            }
749        };
750    }
751    // A decimal is stored as its unscaled integer in whatever width its precision needs, which
752    // `LogicalType::physical` decides and which is why the same `Value::Decimal` is at home in four
753    // different runs. The narrowing cannot fail for a value the binder produced, because the width
754    // that chose the run is the width in the value, but it is checked rather than assumed because
755    // an unchecked cast here would silently store a different number.
756    macro_rules! decimal {
757        ($vec:expr, $ty:ty, $unscaled:expr) => {
758            match <$ty>::try_from(*$unscaled) {
759                Ok(x) => $vec.push(x),
760                Err(_) => {
761                    return Err(Error::internal(format!(
762                        "an unscaled decimal of {} does not fit the run its precision chose",
763                        $unscaled
764                    )));
765                }
766            }
767        };
768    }
769    match data {
770        Data::Empty => {}
771        Data::Bool(v) => push!(v, Value::Boolean, false),
772        Data::Int8(v) => push!(v, Value::TinyInt, 0),
773        Data::Int16(v) => match value {
774            Value::Null => v.push(0),
775            Value::SmallInt(x) => v.push(*x),
776            Value::Decimal { unscaled, .. } => decimal!(v, i16, unscaled),
777            other => return Err(Error::internal(format!("{other:?} is not a 16 bit value"))),
778        },
779        Data::Int32(v) => match value {
780            Value::Null => v.push(0),
781            Value::Integer(x) | Value::Date(x) => v.push(*x),
782            Value::Decimal { unscaled, .. } => decimal!(v, i32, unscaled),
783            other => return Err(Error::internal(format!("{other:?} is not a 32 bit value"))),
784        },
785        Data::Int64(v) => match value {
786            Value::Null => v.push(0),
787            Value::BigInt(x) | Value::Time(x) | Value::Timestamp(x) => v.push(*x),
788            Value::Decimal { unscaled, .. } => decimal!(v, i64, unscaled),
789            other => return Err(Error::internal(format!("{other:?} is not a 64 bit value"))),
790        },
791        Data::Int128(v) => match value {
792            Value::Null => v.push(0),
793            Value::HugeInt(x) => v.push(*x),
794            Value::Decimal { unscaled, .. } => v.push(*unscaled),
795            other => return Err(Error::internal(format!("{other:?} is not a 128 bit value"))),
796        },
797        Data::UInt8(v) => push!(v, Value::UTinyInt, 0),
798        Data::UInt16(v) => push!(v, Value::USmallInt, 0),
799        Data::UInt32(v) => push!(v, Value::UInteger, 0),
800        Data::UInt64(v) => push!(v, Value::UBigInt, 0),
801        Data::UInt128(v) => push!(v, Value::UHugeInt, 0),
802        Data::Float32(v) => push!(v, Value::Float, 0.0),
803        Data::Float64(v) => push!(v, Value::Double, 0.0),
804        Data::Interval(v) => match value {
805            Value::Null => v.push((0, 0, 0)),
806            Value::Interval { months, days, micros } => v.push((*months, *days, *micros)),
807            other => return Err(Error::internal(format!("{other:?} is not an interval"))),
808        },
809        Data::Varlen(column) => match value {
810            Value::Null => {
811                column.push("");
812            }
813            Value::Varchar(text) => {
814                column.push(text);
815            }
816            // A blob is bytes and this column is text, so the only blobs that survive a round trip
817            // here are the ones that happen to be valid UTF-8. Real blob storage is a byte column
818            // and it arrives with the storage layer at M2 rather than being faked now.
819            Value::Blob(bytes) => match std::str::from_utf8(bytes) {
820                Ok(text) => {
821                    column.push(text);
822                }
823                Err(_) => {
824                    return Err(Error::not_implemented(
825                        "a blob that is not valid UTF-8, which needs the byte column from M2",
826                    ));
827                }
828            },
829            other => return Err(Error::internal(format!("{other:?} is not a string"))),
830        },
831    }
832    Ok(())
833}
834
835#[cfg(test)]
836mod tests {
837    use rudb_common::{LogicalType, Value};
838
839    use super::{Data, Form, VECTOR_SIZE, Vector};
840    use crate::string::StringColumn;
841    use crate::validity::Validity;
842
843    fn integers(values: &[i32]) -> Vector {
844        Vector::flat(LogicalType::Integer, Data::Int32(values.to_vec())).unwrap()
845    }
846
847    #[test]
848    fn the_vector_size_is_the_one_the_design_is_built_around() {
849        // 1024 and not DuckDB's 2048. A validity mask is 16 u64 words and a vector of string views
850        // is 16 KiB, both of which are consequences of this number rather than coincidences.
851        assert_eq!(VECTOR_SIZE, 1024);
852        assert_eq!(VECTOR_SIZE / 64, 16);
853    }
854
855    #[test]
856    fn a_flat_vector_reads_back_what_was_put_in_it() {
857        let vector = integers(&[1, 2, 3]);
858        assert_eq!(vector.form(), Form::Flat);
859        assert_eq!(vector.len(), 3);
860        assert_eq!(vector.value_at(1), Value::Integer(2));
861        assert_eq!(
862            vector.iter().collect::<Vec<_>>(),
863            vec![Value::Integer(1), Value::Integer(2), Value::Integer(3)]
864        );
865    }
866
867    #[test]
868    fn a_vector_built_from_values_reads_the_same_values_back() {
869        let vector = Vector::from_values(
870            LogicalType::Varchar,
871            &[
872                Value::Varchar("a".to_string()),
873                Value::Null,
874                Value::Varchar("a string too long to sit inside a view".to_string()),
875            ],
876        )
877        .expect("strings and a null");
878        assert_eq!(vector.len(), 3);
879        assert_eq!(vector.value_at(0), Value::Varchar("a".to_string()));
880        assert_eq!(vector.value_at(1), Value::Null);
881        assert_eq!(
882            vector.value_at(2),
883            Value::Varchar("a string too long to sit inside a view".to_string())
884        );
885    }
886
887    /// A null still occupies a position. If it did not then every value after it would read back
888    /// one place to the left, which is the kind of bug that looks like a storage bug for a week.
889    #[test]
890    fn a_null_in_the_middle_does_not_move_the_values_after_it() {
891        let vector = Vector::from_values(
892            LogicalType::Integer,
893            &[Value::Integer(1), Value::Null, Value::Integer(3)],
894        )
895        .expect("integers and a null");
896        assert_eq!(vector.value_at(2), Value::Integer(3));
897        assert!(vector.validity().has_nulls(3), "the middle one is null");
898    }
899
900    #[test]
901    fn a_value_the_type_cannot_hold_is_refused() {
902        let wrong = Vector::from_values(LogicalType::Integer, &[Value::Varchar("x".to_string())]);
903        assert!(wrong.is_err(), "a string is not an integer");
904    }
905
906    #[test]
907    fn a_type_that_does_not_match_its_layout_is_refused_at_construction() {
908        // One comparison here against a wrong answer read out three layers later.
909        let wrong = Vector::flat(LogicalType::Varchar, Data::Int32(vec![1]));
910        assert!(wrong.is_err());
911        let right = Vector::flat(LogicalType::Date, Data::Int32(vec![1]));
912        assert!(right.is_ok(), "a date is stored in an i32 and that has to be allowed");
913    }
914
915    #[test]
916    fn a_constant_vector_costs_one_value_whatever_its_length() {
917        let vector = Vector::constant(LogicalType::Integer, Value::Integer(7), VECTOR_SIZE);
918        assert_eq!(vector.form(), Form::Constant);
919        assert_eq!(vector.len(), VECTOR_SIZE);
920        assert_eq!(vector.value_at(0), Value::Integer(7));
921        assert_eq!(vector.value_at(VECTOR_SIZE - 1), Value::Integer(7));
922        assert_eq!(vector.value_at(VECTOR_SIZE), Value::Null, "past the end is null, not a panic");
923    }
924
925    #[test]
926    fn a_constant_null_is_all_invalid_without_being_told() {
927        let vector = Vector::constant(LogicalType::Integer, Value::Null, 8);
928        assert_eq!(vector.validity(), &Validity::AllInvalid);
929        assert_eq!(vector.value_at(3), Value::Null);
930    }
931
932    #[test]
933    fn a_sequence_vector_is_sixteen_bytes_of_row_identifiers() {
934        let vector = Vector::sequence(100, 1, VECTOR_SIZE);
935        assert_eq!(vector.form(), Form::Sequence);
936        assert_eq!(vector.value_at(0), Value::BigInt(100));
937        assert_eq!(vector.value_at(923), Value::BigInt(1023));
938        let stepped = Vector::sequence(0, 5, 4);
939        assert_eq!(
940            stepped.iter().collect::<Vec<_>>(),
941            vec![Value::BigInt(0), Value::BigInt(5), Value::BigInt(10), Value::BigInt(15)]
942        );
943    }
944
945    #[test]
946    fn a_dictionary_vector_reads_through_its_codes() {
947        let mut column = StringColumn::new();
948        column.push("red");
949        column.push("green");
950        let values = Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap();
951        let vector = Vector::dictionary(vec![0, 1, 1, 0], values).unwrap();
952        assert_eq!(vector.form(), Form::Dictionary);
953        assert_eq!(vector.logical_type(), &LogicalType::Varchar);
954        assert_eq!(vector.value_at(2), Value::Varchar("green".into()));
955        assert_eq!(vector.len(), 4);
956    }
957
958    #[test]
959    fn a_dictionary_code_past_the_end_is_refused() {
960        // The alternative is a silent read of the wrong value, which is the failure mode the
961        // entire M3 design has to be careful about.
962        let values = integers(&[1, 2]);
963        assert!(Vector::dictionary(vec![0, 2], values).is_err());
964    }
965
966    #[test]
967    fn every_form_flattens_to_the_same_values_it_reads_out() {
968        // This is the shape of the equivalence testing in spec/16-testing.md section 16.2, in
969        // miniature and long before there is an encoded kernel to point it at. A form that reads
970        // out one way and flattens another is the exact bug that testing exists to catch.
971        let mut column = StringColumn::new();
972        column.push("alpha");
973        column.push("beta");
974        let dictionary = Vector::dictionary(
975            vec![1, 0, 1],
976            Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap(),
977        )
978        .unwrap();
979        let cases = [
980            Vector::constant(LogicalType::Integer, Value::Integer(3), 5),
981            Vector::sequence(7, -2, 5),
982            dictionary,
983        ];
984        for vector in cases {
985            let flat = vector.flatten().unwrap();
986            assert_eq!(flat.form(), Form::Flat);
987            assert_eq!(flat.len(), vector.len());
988            for index in 0..vector.len() {
989                assert_eq!(flat.value_at(index), vector.value_at(index), "at {index}");
990            }
991        }
992    }
993
994    #[test]
995    fn a_null_still_occupies_a_position_after_flattening() {
996        // The reason push_value writes a zero for a null rather than skipping it. A run of data
997        // with a hole in it puts every value after the hole in the wrong place, and the validity
998        // mask is what says the position is null.
999        let vector = Vector::sequence(0, 1, 4).with_validity(Validity::from_iter(4, |i| i != 1));
1000        let flat = vector.flatten().unwrap();
1001        assert_eq!(flat.value_at(0), Value::BigInt(0));
1002        assert_eq!(flat.value_at(1), Value::Null);
1003        assert_eq!(flat.value_at(2), Value::BigInt(2));
1004        assert_eq!(flat.value_at(3), Value::BigInt(3));
1005    }
1006
1007    /// A dictionary holds its nulls in the vector it points at, so its own validity is all valid
1008    /// and reading that instead of the values turns a null into whatever zero means for the type.
1009    /// A filter over a nullable column produces exactly this vector, so the bug reaches a result
1010    /// set as `LEFT JOIN` padding that comes back as zeros.
1011    #[test]
1012    fn a_null_behind_a_dictionary_survives_flattening() {
1013        let values =
1014            Vector::from_values(LogicalType::Integer, &[Value::Integer(3), Value::Null]).unwrap();
1015        let dictionary = Vector::dictionary(vec![1, 0, 1], values).unwrap();
1016        let flat = dictionary.flatten().unwrap();
1017        assert_eq!(flat.value_at(0), Value::Null);
1018        assert_eq!(flat.value_at(1), Value::Integer(3));
1019        assert_eq!(flat.value_at(2), Value::Null);
1020    }
1021
1022    /// The property that makes `gather` usable at all: it has to be the same function as reading the
1023    /// wanted positions one at a time, over every form, or compaction changes answers.
1024    #[test]
1025    fn gathering_reads_what_reading_one_position_at_a_time_reads() {
1026        let mut column = StringColumn::new();
1027        column.push("alpha");
1028        column.push("beta");
1029        column.push("gamma");
1030        let cases = [
1031            integers(&[10, 20, 30, 40]),
1032            integers(&[10, 20, 30, 40]).with_validity(Validity::from_iter(4, |i| i != 2)),
1033            Vector::constant(LogicalType::Integer, Value::Integer(9), 4),
1034            Vector::sequence(100, -7, 4),
1035            Vector::sequence(100, -7, 4).with_validity(Validity::from_iter(4, |i| i % 2 == 0)),
1036            Vector::dictionary(
1037                vec![2, 0, 1, 2],
1038                Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap(),
1039            )
1040            .unwrap(),
1041            Vector::dictionary(
1042                vec![1, 0, 1, 0],
1043                Vector::from_values(LogicalType::Integer, &[Value::Integer(5), Value::Null])
1044                    .unwrap(),
1045            )
1046            .unwrap(),
1047        ];
1048        let wanted = [3_u32, 0, 2, 2, 1];
1049        for vector in cases {
1050            let gathered = vector.gather(&wanted).unwrap();
1051            assert_eq!(gathered.len(), wanted.len());
1052            assert_eq!(gathered.logical_type(), vector.logical_type());
1053            for (slot, &index) in wanted.iter().enumerate() {
1054                assert_eq!(
1055                    gathered.value_at(slot),
1056                    vector.value_at(index as usize),
1057                    "slot {slot} of {:?}",
1058                    vector.form()
1059                );
1060            }
1061        }
1062    }
1063
1064    /// A gather past the end is not an error, because the selection that produced the indices is
1065    /// checked by its caller and the one thing that must not happen here is a read of the wrong
1066    /// value. An index nothing answers is null, which is what an outer join pad needs anyway.
1067    #[test]
1068    fn gathering_a_position_that_is_not_there_is_a_null_and_not_a_wrong_value() {
1069        let vector = integers(&[1, 2, 3]);
1070        let gathered = vector.gather(&[2, 9]).unwrap();
1071        assert_eq!(gathered.value_at(0), Value::Integer(3));
1072        assert_eq!(gathered.value_at(1), Value::Null);
1073    }
1074
1075    /// The vector with nothing in it at all, which is what an untyped `NULL` is stored as. Every
1076    /// position asked for is past its end, so the answer is nulls and the length has to be the
1077    /// length that was asked for rather than the length that was there.
1078    #[test]
1079    fn gathering_from_a_vector_of_no_values_is_that_many_nulls() {
1080        let vector = Vector::flat(LogicalType::Null, Data::Empty).unwrap();
1081        let gathered = vector.gather(&[0, 1, 2]).unwrap();
1082        assert_eq!(gathered.len(), 3);
1083        assert_eq!(gathered.value_at(0), Value::Null);
1084        assert_eq!(gathered.value_at(2), Value::Null);
1085    }
1086
1087    /// Every position holds the same value, so a gather with no hole in it has nothing to copy and
1088    /// the result is the constant again rather than a run of a thousand copies of it.
1089    #[test]
1090    fn gathering_a_constant_stays_a_constant() {
1091        let vector = Vector::constant(LogicalType::Integer, Value::Integer(4), 100);
1092        let gathered = vector.gather(&[7, 7, 99]).unwrap();
1093        assert_eq!(gathered.form(), Form::Constant);
1094        assert_eq!(gathered.len(), 3);
1095        assert_eq!(gathered.value_at(2), Value::Integer(4));
1096    }
1097
1098    /// A dictionary over a dictionary is what a second filter over an already filtered chunk builds,
1099    /// and the gather has to walk to the bottom of that chain rather than one step down it. The
1100    /// constructor composes the ordinary chain away, so the one built here is the kind it cannot,
1101    /// which is a level holding nulls of its own.
1102    #[test]
1103    fn gathering_walks_a_dictionary_over_a_dictionary_to_the_values() {
1104        let inner = Vector::dictionary(vec![2, 1, 0], integers(&[7, 8, 9]))
1105            .unwrap()
1106            .with_validity(Validity::from_iter(3, |index| index != 2));
1107        let outer = Vector::dictionary(vec![1, 2], inner).unwrap();
1108        let gathered = outer.gather(&[0, 1]).unwrap();
1109        assert_eq!(gathered.form(), Form::Flat);
1110        assert_eq!(gathered.value_at(0), Value::Integer(8));
1111        assert_eq!(gathered.value_at(1), Value::Null);
1112    }
1113
1114    /// Two filters over one chunk build a dictionary over a dictionary, four conjuncts pushed down
1115    /// separately build four levels of it, and every level is a dependent load on every later read
1116    /// of every row plus a code array that cannot be freed. Composing at construction is one pass
1117    /// over the codes the range check was walking anyway.
1118    #[test]
1119    fn a_dictionary_over_a_dictionary_is_composed_into_one_level() {
1120        let inner = Vector::dictionary(vec![2, 1, 0], integers(&[7, 8, 9])).unwrap();
1121        let outer = Vector::dictionary(vec![1, 2], inner).unwrap();
1122        let (codes, values) = outer.dictionary_parts().unwrap();
1123        assert_eq!(codes, [1, 0]);
1124        assert_eq!(values.form(), Form::Flat);
1125        assert_eq!(outer.value_at(0), Value::Integer(8));
1126        assert_eq!(outer.value_at(1), Value::Integer(7));
1127    }
1128
1129    /// The invariant stated as the thing it is there for, which is that the depth does not grow with
1130    /// the number of filters. Four levels stacked one at a time are one level at the end of it.
1131    #[test]
1132    fn stacking_dictionaries_does_not_make_them_deeper() {
1133        let mut vector = integers(&[10, 20, 30, 40]);
1134        for _ in 0..4 {
1135            vector = Vector::dictionary(vec![3, 2, 1, 0], vector).unwrap();
1136        }
1137        let (codes, values) = vector.dictionary_parts().unwrap();
1138        assert_eq!(values.form(), Form::Flat);
1139        assert_eq!(codes, [0, 1, 2, 3]);
1140        assert_eq!(
1141            vector.iter().collect::<Vec<_>>(),
1142            integers(&[10, 20, 30, 40]).iter().collect::<Vec<_>>()
1143        );
1144    }
1145
1146    /// Composing has to carry the nulls down with it. The values hold them, the codes point at them,
1147    /// and a composed code that lands on a null position is still a null.
1148    #[test]
1149    fn composing_a_dictionary_keeps_the_nulls_its_values_hold() {
1150        let values =
1151            Vector::from_values(LogicalType::Integer, &[Value::Integer(3), Value::Null]).unwrap();
1152        let inner = Vector::dictionary(vec![1, 0, 1], values).unwrap();
1153        let outer = Vector::dictionary(vec![0, 1], inner).unwrap();
1154        assert_eq!(outer.dictionary_parts().unwrap().1.form(), Form::Flat);
1155        assert_eq!(outer.value_at(0), Value::Null);
1156        assert_eq!(outer.value_at(1), Value::Integer(3));
1157    }
1158
1159    /// The one level composition cannot go past. A dictionary that was given a validity of its own is
1160    /// saying its nulls are at that level rather than in the values, and pointing the outer codes
1161    /// straight at the values would read through the holes instead of stopping at them.
1162    #[test]
1163    fn a_dictionary_holding_its_own_nulls_is_not_composed_past() {
1164        let inner = Vector::dictionary(vec![0, 1, 2], integers(&[1, 2, 3]))
1165            .unwrap()
1166            .with_validity(Validity::from_iter(3, |index| index != 1));
1167        let outer = Vector::dictionary(vec![1, 2, 0], inner).unwrap();
1168        assert_eq!(outer.dictionary_parts().unwrap().1.form(), Form::Dictionary);
1169        assert_eq!(outer.value_at(0), Value::Null);
1170        assert_eq!(outer.value_at(1), Value::Integer(3));
1171        assert_eq!(outer.value_at(2), Value::Integer(1));
1172    }
1173
1174    #[test]
1175    fn flattening_a_flat_vector_is_the_same_vector() {
1176        let vector = integers(&[1, 2, 3]);
1177        assert_eq!(vector.flatten().unwrap(), vector);
1178    }
1179
1180    #[test]
1181    fn a_decimal_reads_its_width_and_scale_from_the_type_and_not_the_data() {
1182        let ty = LogicalType::decimal(9, 2).unwrap();
1183        let vector = Vector::flat(ty, Data::Int32(vec![1234])).unwrap();
1184        assert_eq!(vector.value_at(0), Value::Decimal { unscaled: 1234, width: 9, scale: 2 });
1185        assert_eq!(vector.value_at(0).to_string(), "12.34");
1186    }
1187
1188    #[test]
1189    fn a_decimal_writes_into_whichever_of_the_four_runs_its_precision_chose() {
1190        // The read path worked at every width and the write path only accepted the 128 bit run, so
1191        // `SELECT 2.5` produced a value nothing could store. All four widths round trip now.
1192        for (width, scale, unscaled) in
1193            [(4u8, 1u8, 25i128), (9, 2, 1234), (18, 3, 123_456), (38, 4, 1_234_567)]
1194        {
1195            let ty = LogicalType::decimal(width, scale).unwrap();
1196            let value = Value::Decimal { unscaled, width, scale };
1197            let vector = Vector::from_values(ty, &[value.clone(), Value::Null]).unwrap();
1198            assert_eq!(vector.value_at(0), value, "a decimal of width {width}");
1199            assert_eq!(vector.value_at(1), Value::Null, "a null decimal of width {width}");
1200        }
1201    }
1202
1203    #[test]
1204    fn a_decimal_too_wide_for_the_run_its_type_chose_is_an_error_and_not_a_wrong_number() {
1205        // Only reachable by hand, since a value's width is what picked the run. Truncating here
1206        // would store a different number and say nothing about it.
1207        let ty = LogicalType::decimal(4, 1).unwrap();
1208        let value = Value::Decimal { unscaled: 1_000_000, width: 4, scale: 1 };
1209        let error = Vector::from_values(ty, &[value]).unwrap_err();
1210        assert!(error.to_string().contains("does not fit"), "{error}");
1211    }
1212}