Skip to main content

vortex_array/arrays/decimal/vtable/plugin/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! [`ArrayPlugin`] implementation for [`Decimal`], including legacy nodes.
5//!
6//! [`Decimal`] writes a [`DecimalArray`] as a `vortex.decimal` node, and reads every such node as
7//! the canonical decimal array or a decimal [`Widen`]. [`StoredDecimal::is_legacy`] defines a
8//! legacy node.
9//!
10//! A canonical node keeps its buffer without a copy or a scan, so the buffer can stay on a device,
11//! and its valid values are trusted to fit the precision. A legacy node goes through
12//! [`WidenArray::from_stored_decimal`], which scans its valid values on the host, so a legacy node
13//! in device memory fails to read.
14//!
15//! Each legacy read scans the valid values once, because the deserializer attaches stored
16//! statistics only after the plugin returns. This cost is not limited to old files, because IPC
17//! and writes without a compressor still write a decimal `Widen` as a legacy node.
18//!
19//! [`DecimalArray`]: super::DecimalArray
20
21mod stored;
22
23use prost::Message;
24use vortex_error::VortexResult;
25use vortex_error::vortex_bail;
26use vortex_error::vortex_ensure_eq;
27use vortex_error::vortex_err;
28use vortex_session::VortexSession;
29
30use self::stored::StoredDecimal;
31use super::Decimal;
32use crate::ArrayRef;
33use crate::IntoArray;
34use crate::VortexSessionExecute;
35use crate::array::Array;
36use crate::array::ArrayDeserialization;
37use crate::array::ArrayId;
38use crate::array::ArrayPlugin;
39use crate::array::ArraySerialization;
40use crate::array::VTable;
41use crate::arrays::Widen;
42use crate::arrays::WidenArray;
43use crate::arrays::decimal::DecimalDataParts;
44use crate::dtype::DecimalType;
45use crate::stats::Precision;
46
47/// The metadata of a `vortex.decimal` node.
48#[derive(prost::Message)]
49struct DecimalMetadata {
50    /// The [`DecimalType`] discriminant of the stored width.
51    ///
52    /// The width is recorded apart from the dtype, because a legacy node can store a width other
53    /// than the canonical width of its precision.
54    #[prost(int32, tag = "1")]
55    values_type: i32,
56}
57
58impl DecimalMetadata {
59    fn get_values_type(&self) -> VortexResult<DecimalType> {
60        DecimalType::try_from(self.values_type).map_err(|_| {
61            vortex_err!(
62                "DecimalMetadata values_type must be a known DecimalType, got {}",
63                self.values_type
64            )
65        })
66    }
67}
68
69impl ArrayPlugin for Decimal {
70    fn id(&self) -> ArrayId {
71        VTable::id(self)
72    }
73
74    fn serialize(
75        &self,
76        array: &ArrayRef,
77        _session: &VortexSession,
78    ) -> VortexResult<Option<ArraySerialization>> {
79        let Some(decimal) = array.as_opt::<Decimal>() else {
80            vortex_bail!(
81                "Decimal plugin serializes only Decimal arrays, got {}",
82                array.encoding_id()
83            );
84        };
85        let metadata = DecimalMetadata {
86            values_type: decimal.values_type() as i32,
87        };
88
89        Ok(Some(ArraySerialization::from_array(
90            ArrayPlugin::id(self),
91            array,
92            metadata.encode_to_vec(),
93        )))
94    }
95
96    fn deserialize(
97        &self,
98        parts: ArrayDeserialization<'_>,
99        session: &VortexSession,
100    ) -> VortexResult<ArrayRef> {
101        vortex_ensure_eq!(
102            parts.serialized_id,
103            ArrayPlugin::id(self),
104            "Decimal plugin reads only its own serialized ID",
105        );
106
107        let stored = StoredDecimal::deserialize(
108            parts.dtype,
109            parts.len,
110            parts.metadata,
111            parts.buffers,
112            parts.children,
113        )?;
114
115        if !stored.is_legacy() {
116            return Ok(Array::<Decimal>::try_from_parts(stored.into_array_parts())?.into_array());
117        }
118
119        // This is a legacy node, whose width a `Decimal` leaf no longer allows, so the valid values
120        // pick the canonical array or a `Widen`.
121        let parts = DecimalDataParts {
122            decimal_dtype: stored.decimal_dtype,
123            values: stored.values,
124            values_type: stored.values_type,
125            validity: stored.validity,
126        };
127
128        // Stored statistics are attached only after this returns, so no range is known yet.
129        WidenArray::from_stored_decimal(
130            parts,
131            Precision::Absent,
132            &mut session.create_execution_ctx(),
133        )
134    }
135
136    fn is_supported_encoding(&self, id: &ArrayId) -> bool {
137        *id == VTable::id(&Decimal) || *id == VTable::id(&Widen)
138    }
139}
140
141#[cfg(test)]
142mod tests;