vortex-array 0.94.0

Vortex in memory columnar data format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

//! Serde of canonical and legacy `vortex.decimal` nodes.
//!
//! Hand-built nodes cover legacy widths without constructing invalid decimal arrays. Their raw
//! slots include nonzero null payloads, and absent validity denotes a non-nullable node.

mod device;

use std::sync::LazyLock;

use prost::Message;
use rstest::rstest;
use vortex_buffer::Buffer;
use vortex_buffer::ByteBuffer;
use vortex_buffer::ByteBufferMut;
use vortex_buffer::buffer;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_session::VortexSession;
use vortex_session::registry::ReadContext;

use super::DecimalMetadata;
use crate::ArrayContext;
use crate::ArrayRef;
use crate::IntoArray;
use crate::VortexSessionExecute;
use crate::aggregate_fn::NumericalAggregateOpts;
use crate::aggregate_fn::fns::min_max::min_max;
use crate::array::ArrayDeserialization;
use crate::array::ArrayPlugin;
use crate::arrays::BoolArray;
use crate::arrays::Decimal;
use crate::arrays::DecimalArray;
use crate::arrays::Widen;
use crate::arrays::decimal::DecimalArrayExt;
use crate::arrays::widen::WidenArraySlotsExt;
use crate::assert_arrays_eq;
use crate::buffer::BufferHandle;
use crate::dtype::BigCast;
use crate::dtype::DType;
use crate::dtype::DecimalDType;
use crate::dtype::DecimalType;
use crate::dtype::Nullability;
use crate::dtype::i256;
use crate::match_each_decimal_value_type;
use crate::serde::SerializeOptions;
use crate::serde::SerializedArray;
use crate::validity::Validity;

static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);

/// An array read from a node, with the address of the buffer of the node to check its reuse.
struct ReadNode {
    array: ArrayRef,
    /// The original host allocation address, used only to check buffer identity.
    stored_ptr: *const u8,
}

/// Reads a node that stores `slots` as `values_type` integers, with the dtype `decimal_dtype`.
fn read_node(
    values_type: DecimalType,
    decimal_dtype: DecimalDType,
    slots: &[i128],
    validity: Option<&[bool]>,
) -> VortexResult<ReadNode> {
    let values = stored_values(values_type, slots);
    let stored_ptr = values.as_host().as_ptr();
    let (nullability, children) = match validity {
        Some(validity) => (
            Nullability::Nullable,
            vec![BoolArray::from_iter(validity.iter().copied()).into_array()],
        ),
        None => (Nullability::NonNullable, Vec::new()),
    };

    let array = deserialize(
        &DType::Decimal(decimal_dtype, nullability),
        slots.len(),
        &metadata(values_type),
        &[values],
        &children,
    )?;

    Ok(ReadNode { array, stored_ptr })
}

/// Deserializes the parts of a node through the [`Decimal`] plugin.
fn deserialize(
    dtype: &DType,
    len: usize,
    metadata: &[u8],
    buffers: &[BufferHandle],
    children: &[ArrayRef],
) -> VortexResult<ArrayRef> {
    let id = ArrayPlugin::id(&Decimal);
    let parts = ArrayDeserialization::new(id, dtype, len, metadata, buffers, &children);

    ArrayPlugin::deserialize(&Decimal, parts, &SESSION)
}

/// Serializes `array` through the session, then decodes it with the dtype `dtype`.
fn serialize_and_decode(array: &ArrayRef, dtype: &DType) -> VortexResult<ArrayRef> {
    let array_ctx = ArrayContext::empty();
    let mut bytes = ByteBufferMut::empty();
    for buffer in array.serialize(&array_ctx, &SESSION, &SerializeOptions::default())? {
        bytes.extend_from_slice(buffer.as_ref());
    }

    SerializedArray::try_from(bytes.freeze())?.decode(
        dtype,
        array.len(),
        &ReadContext::new(array_ctx.to_ids()),
        &SESSION,
    )
}

fn metadata(values_type: DecimalType) -> Vec<u8> {
    DecimalMetadata {
        values_type: values_type as i32,
    }
    .encode_to_vec()
}

/// Returns `slots` as a host buffer of `values_type` integers.
fn stored_values(values_type: DecimalType, slots: &[i128]) -> BufferHandle {
    let bytes = match_each_decimal_value_type!(values_type, |T| {
        slots
            .iter()
            .map(|&slot| <T as BigCast>::from(slot).vortex_expect("a slot fits its stored width"))
            .collect::<Buffer<T>>()
            .into_byte_buffer()
    });

    BufferHandle::new_host(bytes)
}

/// Returns the canonical array of the valid values of a node, with zeros in its null slots.
fn canonical_reference(
    decimal_dtype: DecimalDType,
    slots: &[i128],
    validity: Option<&[bool]>,
) -> VortexResult<DecimalArray> {
    let valid_slots = slots
        .iter()
        .enumerate()
        .map(|(row, &slot)| match validity {
            Some(validity) if !validity[row] => 0,
            _ => slot,
        })
        .collect::<Vec<_>>();
    let validity = match validity {
        Some(validity) => Validity::from_iter(validity.iter().copied()),
        None => Validity::NonNullable,
    };

    let canonical_type = decimal_dtype.canonical_values_type();

    DecimalArray::try_new_handle(
        stored_values(canonical_type, &valid_slots),
        canonical_type,
        decimal_dtype,
        validity,
        &mut SESSION.create_execution_ctx(),
    )
}

/// Returns the decimal leaf that holds the values of `array`: the child of a `Widen`, or `array`.
fn decimal_leaf(array: &ArrayRef) -> DecimalArray {
    let leaf = match array.as_opt::<Widen>() {
        Some(widen) => widen.values().clone(),
        None => array.clone(),
    };

    leaf.as_::<Decimal>().into_owned()
}

/// Checks the encoding, the leaf dtype and width, the reuse of the stored buffer, and the values.
///
/// The cases cover each result of a read: a canonical node keeps its buffer, and a legacy node
/// reads as a `Widen` or as the canonical array. The tests of [`WidenArray::from_stored_decimal`]
/// cover the rule that picks the child precision.
///
/// [`WidenArray::from_stored_decimal`]: crate::arrays::WidenArray::from_stored_decimal
#[rstest]
#[case::canonical_reuse(
    DecimalType::I32, DecimalDType::new(9, 2),
    vec![-999_999_999, 0, 999_999_999], None,
    None, true,
)]
#[case::canonical_null_payload(
    DecimalType::I32, DecimalDType::new(9, 2),
    vec![-999_999_999, i32::MAX.into(), 999_999_999], Some(vec![true, false, true]),
    None, true,
)]
#[case::narrow_reuse(
    DecimalType::I16, DecimalDType::new(18, 2),
    vec![-9_999, 0, 9_999], None,
    Some(4), true,
)]
#[case::wider_to_canonical(
    DecimalType::I128, DecimalDType::new(5, 2),
    vec![-99_999, 0, 99_999], None,
    None, false,
)]
#[case::nullable_reuse(
    DecimalType::I16, DecimalDType::new(18, 2),
    vec![-9_999, 32_767, 9_999], Some(vec![true, false, true]),
    Some(4), true,
)]
fn reads_node_at_any_width(
    #[case] values_type: DecimalType,
    #[case] decimal_dtype: DecimalDType,
    #[case] slots: Vec<i128>,
    #[case] validity: Option<Vec<bool>>,
    #[case] child_precision: Option<u8>,
    #[case] reuses_buffer: bool,
) -> VortexResult<()> {
    let mut ctx = SESSION.create_execution_ctx();

    let node = read_node(values_type, decimal_dtype, &slots, validity.as_deref())?;

    assert_eq!(node.array.is::<Widen>(), child_precision.is_some());
    let leaf = decimal_leaf(&node.array);
    let leaf_dtype = match child_precision {
        Some(precision) => DecimalDType::new(precision, decimal_dtype.scale()),
        None => decimal_dtype,
    };
    assert_eq!(leaf.decimal_dtype(), leaf_dtype);
    assert_eq!(leaf.values_type(), leaf_dtype.canonical_values_type());

    // A leaf at another width than the stored width is a copy. Two empty buffers can share an
    // address, so only a reuse is checked by address.
    assert_eq!(leaf.values_type() == values_type, reuses_buffer);
    if reuses_buffer {
        assert_eq!(leaf.buffer_handle().as_host().as_ptr(), node.stored_ptr);
    }

    assert_arrays_eq!(
        node.array,
        canonical_reference(decimal_dtype, &slots, validity.as_deref())?,
        &mut ctx
    );

    Ok(())
}

/// A canonical node trusts its declared precision. Consumers that produce a scalar still validate
/// its value, including both extrema in an aggregate over multiple rows.
#[rstest]
#[case::one_value(&[100], 0)]
#[case::maximum(&[1, 100], 1)]
#[case::minimum(&[-100, 1], 0)]
fn invalid_stored_value_errors_on_access(
    #[case] slots: &[i128],
    #[case] invalid_row: usize,
) -> VortexResult<()> {
    let mut ctx = SESSION.create_execution_ctx();
    let node = read_node(DecimalType::I8, DecimalDType::new(2, 0), slots, None)?;
    let decimal = node.array.as_::<Decimal>();
    assert_eq!(decimal.buffer_handle().as_host().as_ptr(), node.stored_ptr);

    let scalar_error = node
        .array
        .execute_scalar(invalid_row, &mut ctx)
        .unwrap_err();
    assert!(
        scalar_error
            .to_string()
            .contains("does not fit in precision"),
        "{scalar_error}"
    );

    let aggregate_error =
        min_max(&node.array, &mut ctx, NumericalAggregateOpts::default()).unwrap_err();
    assert!(
        aggregate_error
            .to_string()
            .contains("does not fit in precision"),
        "{aggregate_error}"
    );

    Ok(())
}

#[rstest]
#[case::first_unused(6)]
#[case::negative(-1)]
#[case::max(i32::MAX)]
fn unknown_values_type_fails(#[case] raw: i32) -> VortexResult<()> {
    let dtype = DType::Decimal(DecimalDType::new(2, 0), Nullability::NonNullable);
    let metadata = DecimalMetadata { values_type: raw }.encode_to_vec();
    let values = BufferHandle::new_host(ByteBuffer::zeroed(4));

    let result = deserialize(&dtype, 4, &metadata, &[values], &[]);

    let expected = format!("DecimalMetadata values_type must be a known DecimalType, got {raw}");
    assert!(result.is_err_and(|error| error.to_string().contains(&expected)));

    Ok(())
}

/// Wire length and alignment must be checked before reading the stored integers.
#[rstest]
#[case::short_buffer(18, DecimalType::I32, 4, stored_values(DecimalType::I32, &[1, 2, 3]),
    "byte length of 4 i32 values")]
#[case::overflowing_length(18, DecimalType::I16, usize::MAX / 2 + 1,
    stored_values(DecimalType::I16, &[]), "fits in usize")]
#[case::misaligned_buffer(9, DecimalType::I32, 2,
    BufferHandle::new_host(ByteBuffer::copy_from([0u8; 8])), "alignment")]
fn invalid_buffer_fails(
    #[case] precision: u8,
    #[case] values_type: DecimalType,
    #[case] len: usize,
    #[case] values: BufferHandle,
    #[case] expected: &str,
) -> VortexResult<()> {
    let dtype = DType::Decimal(DecimalDType::new(precision, 2), Nullability::NonNullable);

    let result = deserialize(&dtype, len, &metadata(values_type), &[values], &[]);

    assert!(result.is_err_and(|error| error.to_string().contains(expected)));

    Ok(())
}

#[rstest]
#[case::extra_child(Nullability::Nullable, 2, "got 2")]
#[case::non_nullable_node(Nullability::NonNullable, 1, "requires a nullable dtype")]
fn invalid_validity_children_fail(
    #[case] nullability: Nullability,
    #[case] child_count: usize,
    #[case] expected: &str,
) -> VortexResult<()> {
    let dtype = DType::Decimal(DecimalDType::new(18, 2), nullability);
    let values = stored_values(DecimalType::I32, &[1, 2]);
    let validity = BoolArray::from_iter([true, false]).into_array();

    let result = deserialize(
        &dtype,
        2,
        &metadata(DecimalType::I32),
        &[values],
        &vec![validity; child_count],
    );

    assert!(result.is_err_and(|error| error.to_string().contains(expected)));

    Ok(())
}

#[rstest]
#[case::i32_nullable(
    DecimalArray::new(
        buffer![1_234_567i32, 0, -9_999_999],
        DecimalDType::new(7, 3),
        Validity::from_iter([true, false, true]),
        &mut SESSION.create_execution_ctx(),
    ),
    DecimalType::I32
)]
#[case::i8(
    DecimalArray::from_iter([1i8, -2, 3], DecimalDType::new(2, 0)),
    DecimalType::I8
)]
#[case::i16(
    DecimalArray::from_iter([1i16, -2, 3], DecimalDType::new(4, 0)),
    DecimalType::I16
)]
#[case::i32(
    DecimalArray::from_iter([1i32, -2, 3], DecimalDType::new(9, 2)),
    DecimalType::I32
)]
#[case::i64(
    DecimalArray::from_iter([1i64, -2, 3], DecimalDType::new(18, 2)),
    DecimalType::I64
)]
#[case::i128(
    DecimalArray::from_iter([1i128, -2, 3], DecimalDType::new(38, 2)),
    DecimalType::I128
)]
#[case::i256(
    DecimalArray::from_iter(
        [i256::from_i128(1), i256::from_i128(-2), i256::from_i128(3)],
        DecimalDType::new(76, 2),
    ),
    DecimalType::I256
)]
fn round_trips_each_values_type(
    #[case] array: DecimalArray,
    #[case] values_type: DecimalType,
) -> VortexResult<()> {
    let array = array.into_array();

    let decoded = serialize_and_decode(&array, array.dtype())?;

    assert_eq!(decoded.as_::<Decimal>().values_type(), values_type);
    assert_arrays_eq!(decoded, array, &mut SESSION.create_execution_ctx());

    Ok(())
}

/// Writes a canonical array of precision 2 and decodes it at precision 10, as a legacy node.
///
/// This goes through the deserializer, which asserts that the plugin supports the encoding of the
/// result, here a `Widen`.
#[test]
fn decode_legacy_node_through_serialized_array() -> VortexResult<()> {
    let mut ctx = SESSION.create_execution_ctx();
    let values = [-99, 0, 99];
    let written = canonical_reference(DecimalDType::new(2, 0), &values, None)?.into_array();
    let read_dtype = DecimalDType::new(10, 0);

    let decoded = serialize_and_decode(
        &written,
        &DType::Decimal(read_dtype, Nullability::NonNullable),
    )?;

    assert!(decoded.is::<Widen>());
    assert_arrays_eq!(
        decoded,
        canonical_reference(read_dtype, &values, None)?,
        &mut ctx
    );

    Ok(())
}