Skip to main content

vortex_array/arrays/widen/vtable/
plugin.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Wire layout of a `vortex.widen` node.
5//!
6//! A node has one child and no buffers of its own. The enclosing format supplies the logical dtype
7//! and length of the [`Widen`]. The child has the same length and nullability. A decimal child
8//! also has the same scale.
9//!
10//! Readers require the first child and ignore any children after it, as well as any node buffers.
11//! A later writer may append a child or buffer under this ID only if decoding without it yields the
12//! same values, such as a statistic or an index. A child, buffer or metadata field that changes the
13//! decoded values needs a new ID.
14//!
15//! A protobuf `oneof` supplies the rest of the child dtype. Tag 1 holds the integer [`PType`].
16//! Tag 2 holds the decimal precision as a `uint32`. The child dtype must meet the requirements
17//! of [`WidenArray::try_new`].
18
19use prost::Message as _;
20use vortex_error::VortexResult;
21use vortex_error::vortex_bail;
22use vortex_error::vortex_ensure;
23use vortex_error::vortex_ensure_eq;
24use vortex_error::vortex_err;
25use vortex_session::VortexSession;
26
27use crate::ArrayDeserialization;
28use crate::ArrayId;
29use crate::ArrayPlugin;
30use crate::ArrayRef;
31use crate::ArraySerialization;
32use crate::ArrayVTable;
33use crate::IntoArray;
34use crate::arrays::Decimal;
35use crate::arrays::Widen;
36use crate::arrays::WidenArray;
37use crate::arrays::widen::WidenArraySlotsExt;
38use crate::arrays::widen::array::validate_dtypes;
39use crate::dtype::DType;
40use crate::dtype::DecimalDType;
41use crate::dtype::PType;
42use crate::session::ArraySessionExt;
43
44#[derive(Clone, prost::Message)]
45struct WidenMetadata {
46    #[prost(oneof = "ChildType", tags = "1, 2")]
47    child_type: Option<ChildType>,
48}
49
50#[derive(Clone, prost::Oneof)]
51enum ChildType {
52    #[prost(enumeration = "PType", tag = "1")]
53    Integer(i32),
54    #[prost(uint32, tag = "2")]
55    DecimalPrecision(u32),
56}
57
58/// Reads and writes serialized [`Widen`] arrays.
59///
60/// Writing reuses the child without executing its values or validity. When the child is a
61/// [`Decimal`] array, this plugin writes `vortex.decimal` so older readers can read it. The decimal
62/// reader handles those nodes.
63#[derive(Clone, Debug)]
64pub struct WidenPlugin;
65
66impl ArrayPlugin for WidenPlugin {
67    fn id(&self) -> ArrayId {
68        ArrayVTable::id(&Widen)
69    }
70
71    fn write_ids(&self) -> Vec<ArrayId> {
72        // Older editions allow `vortex.decimal`, which can store the child's narrow buffer
73        // under the parent's decimal dtype.
74        vec![ArrayVTable::id(&Decimal), self.id()]
75    }
76
77    fn serialize(
78        &self,
79        array: &ArrayRef,
80        session: &VortexSession,
81    ) -> VortexResult<Option<ArraySerialization>> {
82        let widen = array.as_opt::<Widen>().ok_or_else(|| {
83            vortex_err!(
84                "Widen serialization requires a Widen array, got {}",
85                array.encoding_id()
86            )
87        })?;
88        let values = widen.values();
89        if values.is::<Decimal>() {
90            // The wire node gets the buffer width and validity from the child. The enclosing
91            // format supplies the parent dtype, and serialization keeps the parent's statistics.
92            return session.array_serialize(values);
93        }
94
95        let child_type = match values.dtype() {
96            DType::Primitive(ptype, _) if ptype.is_int() => ChildType::Integer(*ptype as i32),
97            DType::Decimal(dtype, _) => ChildType::DecimalPrecision(u32::from(dtype.precision())),
98            dtype => {
99                vortex_bail!(
100                    "Widen serialization requires an integer or decimal child, got {dtype}"
101                )
102            }
103        };
104        let metadata = WidenMetadata {
105            child_type: Some(child_type),
106        };
107
108        Ok(Some(ArraySerialization::new(
109            self.id(),
110            metadata.encode_to_vec(),
111            vec![],
112            vec![values.clone()],
113        )))
114    }
115
116    fn deserialize(
117        &self,
118        parts: ArrayDeserialization<'_>,
119        _session: &VortexSession,
120    ) -> VortexResult<ArrayRef> {
121        vortex_ensure_eq!(parts.serialized_id, self.id(), "expected the Widen wire ID");
122        // NB: Node buffers and children after the first child are optional extensions, so they
123        // are ignored. See the module documentation.
124        vortex_ensure!(
125            !parts.children.is_empty(),
126            "Widen must carry at least one child"
127        );
128
129        let child_type = WidenMetadata::decode(parts.metadata)?
130            .child_type
131            .ok_or_else(|| vortex_err!("Widen metadata must name the child type"))?;
132        let nullability = parts.dtype.nullability();
133        let child_dtype = match (child_type, parts.dtype) {
134            (ChildType::Integer(ptype), DType::Primitive(parent, _)) if parent.is_int() => {
135                DType::Primitive(PType::try_from(ptype)?, nullability)
136            }
137            (ChildType::DecimalPrecision(precision), DType::Decimal(parent, _)) => {
138                let precision = u8::try_from(precision).map_err(|_| {
139                    vortex_err!("Widen child precision {precision} is out of range")
140                })?;
141                DType::Decimal(
142                    DecimalDType::try_new(precision, parent.scale())?,
143                    nullability,
144                )
145            }
146            (_, dtype) => {
147                vortex_bail!("Widen child metadata does not match the parent dtype {dtype}")
148            }
149        };
150
151        // The child decoder uses this dtype to read its buffers, so check it against the parent
152        // before decoding.
153        validate_dtypes(&child_dtype, parts.dtype)?;
154        let values = parts.children.get(0, &child_dtype, parts.len)?;
155
156        Ok(WidenArray::try_new(values, parts.dtype.clone())?.into_array())
157    }
158}