Skip to main content

vortex_array/scalar/
proto.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Protobuf serialization and deserialization for scalars.
5
6use num_traits::ToBytes;
7use num_traits::ToPrimitive;
8use prost::Message;
9use vortex_buffer::BufferString;
10use vortex_buffer::ByteBuffer;
11use vortex_error::VortexExpect;
12use vortex_error::VortexResult;
13use vortex_error::vortex_bail;
14use vortex_error::vortex_ensure;
15use vortex_error::vortex_ensure_eq;
16use vortex_error::vortex_err;
17use vortex_session::VortexSession;
18
19use crate::dtype::DType;
20use crate::dtype::PType;
21use crate::dtype::half::f16;
22use crate::dtype::i256;
23use crate::proto::scalar as pb;
24use crate::proto::scalar::ListValue;
25use crate::proto::scalar::UnionValue as PbUnionValue;
26use crate::proto::scalar::scalar_value::Kind;
27use crate::scalar::DecimalValue;
28use crate::scalar::PValue;
29use crate::scalar::Scalar;
30use crate::scalar::ScalarValue;
31use crate::scalar::UnionValue;
32
33////////////////////////////////////////////////////////////////////////////////////////////////////
34// Serialize INTO proto.
35////////////////////////////////////////////////////////////////////////////////////////////////////
36
37impl From<&Scalar> for pb::Scalar {
38    fn from(value: &Scalar) -> Self {
39        value
40            .to_proto()
41            .vortex_expect("Failed to convert DType to proto")
42    }
43}
44
45impl Scalar {
46    /// Serializes this scalar into its [protobuf](pb::Scalar) representation.
47    ///
48    /// Prefer this over the infallible `From<&Scalar>` conversion wherever an error can be
49    /// returned, since that conversion panics when the dtype cannot be serialized.
50    ///
51    /// # Errors
52    ///
53    /// Returns an error if the dtype cannot be serialized, for example when an extension dtype's
54    /// metadata serializer fails.
55    pub fn to_proto(&self) -> VortexResult<pb::Scalar> {
56        Ok(pb::Scalar {
57            dtype: Some(self.dtype().try_into()?),
58            value: Some(Box::new(ScalarValue::to_proto(self.value()))),
59        })
60    }
61}
62
63impl ScalarValue {
64    /// Ideally, we would not have this function and instead implement this `From` implementation:
65    ///
66    /// ```ignore
67    /// impl From<Option<&ScalarValue>> for pb::ScalarValue { ... }
68    /// ```
69    ///
70    /// However, we are not allowed to do this because of the Orphan rule (`Option` and
71    /// `pb::ScalarValue` are not types defined in this crate). So we must make this a method on
72    /// `vortex_array::scalar::ScalarValue` directly.
73    pub fn to_proto(this: Option<&Self>) -> pb::ScalarValue {
74        match this {
75            None => pb::ScalarValue {
76                kind: Some(Kind::NullValue(0)),
77            },
78            Some(this) => pb::ScalarValue::from(this),
79        }
80    }
81
82    /// Serialize an optional [`ScalarValue`] to protobuf bytes (handles null values).
83    pub fn to_proto_bytes<B: Default + bytes::BufMut>(value: Option<&ScalarValue>) -> B {
84        let proto = Self::to_proto(value);
85        let mut buf = B::default();
86        proto
87            .encode(&mut buf)
88            .vortex_expect("Failed to encode scalar value");
89        buf
90    }
91}
92
93impl From<&ScalarValue> for pb::ScalarValue {
94    fn from(value: &ScalarValue) -> Self {
95        match value {
96            ScalarValue::Bool(v) => pb::ScalarValue {
97                kind: Some(Kind::BoolValue(*v)),
98            },
99            ScalarValue::Primitive(v) => pb::ScalarValue::from(v),
100            ScalarValue::Decimal(v) => {
101                let inner_value = match v {
102                    DecimalValue::I8(v) => v.to_le_bytes().to_vec(),
103                    DecimalValue::I16(v) => v.to_le_bytes().to_vec(),
104                    DecimalValue::I32(v) => v.to_le_bytes().to_vec(),
105                    DecimalValue::I64(v) => v.to_le_bytes().to_vec(),
106                    DecimalValue::I128(v128) => v128.to_le_bytes().to_vec(),
107                    DecimalValue::I256(v256) => v256.to_le_bytes().to_vec(),
108                };
109
110                pb::ScalarValue {
111                    kind: Some(Kind::BytesValue(inner_value)),
112                }
113            }
114            ScalarValue::Utf8(v) => pb::ScalarValue {
115                kind: Some(Kind::StringValue(v.to_string())),
116            },
117            ScalarValue::Binary(v) => pb::ScalarValue {
118                kind: Some(Kind::BytesValue(v.to_vec())),
119            },
120            ScalarValue::Tuple(v) => {
121                let mut values = Vec::with_capacity(v.len());
122                for elem in v.iter() {
123                    values.push(ScalarValue::to_proto(elem.as_ref()));
124                }
125                pb::ScalarValue {
126                    kind: Some(Kind::ListValue(ListValue { values })),
127                }
128            }
129            ScalarValue::Union(v) => pb::ScalarValue {
130                kind: Some(Kind::UnionValue(Box::new(PbUnionValue {
131                    type_id: u32::from(v.type_id()),
132                    value: Some(Box::new(ScalarValue::to_proto(v.child_value()))),
133                }))),
134            },
135            ScalarValue::Variant(v) => pb::ScalarValue {
136                kind: Some(Kind::VariantValue(Box::new(pb::Scalar::from(v.as_ref())))),
137            },
138        }
139    }
140}
141
142impl From<&PValue> for pb::ScalarValue {
143    fn from(value: &PValue) -> Self {
144        match value {
145            PValue::I8(v) => pb::ScalarValue {
146                kind: Some(Kind::Int64Value(*v as i64)),
147            },
148            PValue::I16(v) => pb::ScalarValue {
149                kind: Some(Kind::Int64Value(*v as i64)),
150            },
151            PValue::I32(v) => pb::ScalarValue {
152                kind: Some(Kind::Int64Value(*v as i64)),
153            },
154            PValue::I64(v) => pb::ScalarValue {
155                kind: Some(Kind::Int64Value(*v)),
156            },
157            PValue::U8(v) => pb::ScalarValue {
158                kind: Some(Kind::Uint64Value(*v as u64)),
159            },
160            PValue::U16(v) => pb::ScalarValue {
161                kind: Some(Kind::Uint64Value(*v as u64)),
162            },
163            PValue::U32(v) => pb::ScalarValue {
164                kind: Some(Kind::Uint64Value(*v as u64)),
165            },
166            PValue::U64(v) => pb::ScalarValue {
167                kind: Some(Kind::Uint64Value(*v)),
168            },
169            PValue::F16(v) => pb::ScalarValue {
170                kind: Some(Kind::F16Value(v.to_bits() as u64)),
171            },
172            PValue::F32(v) => pb::ScalarValue {
173                kind: Some(Kind::F32Value(*v)),
174            },
175            PValue::F64(v) => pb::ScalarValue {
176                kind: Some(Kind::F64Value(*v)),
177            },
178        }
179    }
180}
181
182////////////////////////////////////////////////////////////////////////////////////////////////////
183// Serialize FROM proto.
184////////////////////////////////////////////////////////////////////////////////////////////////////
185
186impl Scalar {
187    /// Creates a [`Scalar`] from a [protobuf `ScalarValue`](pb::ScalarValue) representation.
188    ///
189    /// Note that we need to provide a [`DType`] since protobuf serialization only supports 64-bit
190    /// integers, and serializing _into_ protobuf loses that type information.
191    ///
192    /// # Errors
193    ///
194    /// Returns an error if type validation fails.
195    pub fn from_proto_value(
196        value: &pb::ScalarValue,
197        dtype: &DType,
198        session: &VortexSession,
199    ) -> VortexResult<Self> {
200        let scalar_value = ScalarValue::from_proto(value, dtype, session)?;
201
202        Scalar::try_new(dtype.clone(), scalar_value)
203    }
204
205    /// Creates a [`Scalar`] from its [protobuf](pb::Scalar) representation.
206    ///
207    /// # Errors
208    ///
209    /// Returns an error if the protobuf is missing required fields or if type validation fails.
210    pub fn from_proto(value: &pb::Scalar, session: &VortexSession) -> VortexResult<Self> {
211        let dtype = DType::from_proto(
212            value
213                .dtype
214                .as_ref()
215                .ok_or_else(|| vortex_err!("Scalar missing dtype"))?,
216            session,
217        )?;
218
219        let pb_scalar_value: &pb::ScalarValue = value
220            .value
221            .as_ref()
222            .ok_or_else(|| vortex_err!("Scalar missing value"))?;
223
224        let value: Option<ScalarValue> = ScalarValue::from_proto(pb_scalar_value, &dtype, session)?;
225
226        Scalar::try_new(dtype, value)
227    }
228}
229
230impl ScalarValue {
231    /// Deserialize a [`ScalarValue`] from protobuf bytes.
232    ///
233    /// Note that we need to provide a [`DType`] since protobuf serialization only supports 64-bit
234    /// integers, and serializing _into_ protobuf loses that type information.
235    ///
236    /// # Errors
237    ///
238    /// Returns an error if decoding or type validation fails.
239    pub fn from_proto_bytes(
240        bytes: &[u8],
241        dtype: &DType,
242        session: &VortexSession,
243    ) -> VortexResult<Option<Self>> {
244        let proto = pb::ScalarValue::decode(bytes)?;
245        Self::from_proto(&proto, dtype, session)
246    }
247
248    /// Creates a [`ScalarValue`] from its [protobuf](pb::ScalarValue) representation.
249    ///
250    /// Note that we need to provide a [`DType`] since protobuf serialization only supports 64-bit
251    /// integers, and serializing _into_ protobuf loses that type information.
252    ///
253    /// # Errors
254    ///
255    /// Returns an error if the protobuf value cannot be converted to the given [`DType`].
256    pub fn from_proto(
257        value: &pb::ScalarValue,
258        dtype: &DType,
259        session: &VortexSession,
260    ) -> VortexResult<Option<Self>> {
261        let kind = value
262            .kind
263            .as_ref()
264            .ok_or_else(|| vortex_err!("Scalar value missing kind"))?;
265
266        // `DType::Extension` store their serialized values using the storage `DType`.
267        let dtype = match dtype {
268            DType::Extension(ext) => ext.storage_dtype(),
269            _ => dtype,
270        };
271
272        Ok(match kind {
273            Kind::NullValue(_) => None,
274            Kind::BoolValue(v) => Some(bool_from_proto(*v, dtype)?),
275            Kind::Int64Value(v) => Some(int64_from_proto(*v, dtype)?),
276            Kind::Uint64Value(v) => Some(uint64_from_proto(*v, dtype)?),
277            Kind::F16Value(v) => Some(f16_from_proto(*v, dtype)?),
278            Kind::F32Value(v) => Some(f32_from_proto(*v, dtype)?),
279            Kind::F64Value(v) => Some(f64_from_proto(*v, dtype)?),
280            Kind::StringValue(s) => Some(string_from_proto(s, dtype)?),
281            Kind::BytesValue(b) => Some(bytes_from_proto(b, dtype)?),
282            Kind::ListValue(v) => Some(list_from_proto(v, dtype, session)?),
283            Kind::UnionValue(v) => Some(union_from_proto(v, dtype, session)?),
284            Kind::VariantValue(v) => match dtype {
285                DType::Variant(_) => Some(ScalarValue::Variant(Box::new(Scalar::from_proto(
286                    v, session,
287                )?))),
288                _ => vortex_bail!("expected non-Variant scalar proto for dtype {dtype}"),
289            },
290        })
291    }
292}
293
294/// Deserialize a [`ScalarValue::Bool`] from a protobuf `BoolValue`.
295fn bool_from_proto(v: bool, dtype: &DType) -> VortexResult<ScalarValue> {
296    vortex_ensure!(
297        dtype.is_boolean(),
298        "expected Bool dtype for BoolValue, got {dtype}"
299    );
300
301    Ok(ScalarValue::Bool(v))
302}
303
304/// Deserialize a [`ScalarValue::Primitive`] from a protobuf `Int64Value`.
305///
306/// Protobuf consolidates all signed integers into `i64`, so we narrow back to the original
307/// type using the provided [`DType`].
308fn int64_from_proto(v: i64, dtype: &DType) -> VortexResult<ScalarValue> {
309    vortex_ensure!(
310        dtype.is_primitive(),
311        "expected Primitive dtype for Int64Value, got {dtype}"
312    );
313
314    let pvalue = match dtype.as_ptype() {
315        PType::I8 => v.to_i8().map(PValue::I8),
316        PType::I16 => v.to_i16().map(PValue::I16),
317        PType::I32 => v.to_i32().map(PValue::I32),
318        PType::I64 => Some(PValue::I64(v)),
319        // It was previously possible for unsigned types to get their stats serialised as signed,
320        // so we allow casting back to unsigned for backwards compatibility.
321        PType::U8 => v.to_u8().map(PValue::U8),
322        PType::U16 => v.to_u16().map(PValue::U16),
323        PType::U32 => v.to_u32().map(PValue::U32),
324        PType::U64 => v.to_u64().map(PValue::U64),
325        ftype @ (PType::F16 | PType::F32 | PType::F64) => vortex_bail!(
326            "expected signed integer ptype for serialized Int64Value, got float {ftype}"
327        ),
328    }
329    .ok_or_else(|| vortex_err!("Int64 value {v} out of range for dtype {dtype}"))?;
330
331    Ok(ScalarValue::Primitive(pvalue))
332}
333
334/// Deserialize a [`ScalarValue::Primitive`] from a protobuf `Uint64Value`.
335///
336/// Protobuf consolidates all unsigned integers into `u64`, so we narrow back to the original
337/// type using the provided [`DType`]. Also handles the backwards-compatible case where `f16`
338/// values were serialized as `u64` (via `f16::to_bits() as u64`).
339fn uint64_from_proto(v: u64, dtype: &DType) -> VortexResult<ScalarValue> {
340    vortex_ensure!(
341        dtype.is_primitive(),
342        "expected Primitive dtype for Uint64Value, got {dtype}"
343    );
344
345    let pvalue = match dtype.as_ptype() {
346        PType::U8 => v.to_u8().map(PValue::U8),
347        PType::U16 => v.to_u16().map(PValue::U16),
348        PType::U32 => v.to_u32().map(PValue::U32),
349        PType::U64 => Some(PValue::U64(v)),
350        // It was previously possible for signed types to get their stats serialised as unsigned,
351        // so we allow casting back to signed for backwards compatibility.
352        PType::I8 => v.to_i8().map(PValue::I8),
353        PType::I16 => v.to_i16().map(PValue::I16),
354        PType::I32 => v.to_i32().map(PValue::I32),
355        PType::I64 => v.to_i64().map(PValue::I64),
356        // f16 values used to be serialized as u64, so we need to be able to read an f16 from a u64.
357        PType::F16 => v.to_u16().map(f16::from_bits).map(PValue::F16),
358        ftype @ (PType::F32 | PType::F64) => {
359            vortex_bail!("expected unsigned integer ptype for serialized Uint64Value, got {ftype}")
360        }
361    }
362    .ok_or_else(|| vortex_err!("Uint64 value {v} out of range for dtype {dtype}"))?;
363
364    Ok(ScalarValue::Primitive(pvalue))
365}
366
367/// Deserialize a [`ScalarValue::Primitive`] from a protobuf `F16Value`.
368fn f16_from_proto(v: u64, dtype: &DType) -> VortexResult<ScalarValue> {
369    vortex_ensure!(
370        matches!(dtype, DType::Primitive(PType::F16, _)),
371        "expected F16 dtype for F16Value, got {dtype}"
372    );
373
374    let bits = u16::try_from(v)
375        .map_err(|_| vortex_err!("f16 bitwise representation has more than 16 bits: {v}"))?;
376
377    Ok(ScalarValue::Primitive(PValue::F16(f16::from_bits(bits))))
378}
379
380/// Deserialize a [`ScalarValue::Primitive`] from a protobuf `F32Value`.
381fn f32_from_proto(v: f32, dtype: &DType) -> VortexResult<ScalarValue> {
382    vortex_ensure!(
383        matches!(dtype, DType::Primitive(PType::F32, _)),
384        "expected F32 dtype for F32Value, got {dtype}"
385    );
386
387    Ok(ScalarValue::Primitive(PValue::F32(v)))
388}
389
390/// Deserialize a [`ScalarValue::Primitive`] from a protobuf `F64Value`.
391fn f64_from_proto(v: f64, dtype: &DType) -> VortexResult<ScalarValue> {
392    vortex_ensure!(
393        matches!(dtype, DType::Primitive(PType::F64, _)),
394        "expected F64 dtype for F64Value, got {dtype}"
395    );
396
397    Ok(ScalarValue::Primitive(PValue::F64(v)))
398}
399
400/// Deserialize a [`ScalarValue::Utf8`] or [`ScalarValue::Binary`] from a protobuf
401/// `StringValue`.
402fn string_from_proto(s: &str, dtype: &DType) -> VortexResult<ScalarValue> {
403    match dtype {
404        DType::Utf8(_) => Ok(ScalarValue::Utf8(BufferString::from(s))),
405        DType::Binary(_) => Ok(ScalarValue::Binary(ByteBuffer::copy_from(s.as_bytes()))),
406        _ => vortex_bail!("expected Utf8 or Binary dtype for StringValue, got {dtype}"),
407    }
408}
409
410/// Deserialize a [`ScalarValue`] from a protobuf bytes and a `DType`.
411///
412/// Handles [`Utf8`](ScalarValue::Utf8), [`Binary`](ScalarValue::Binary), and
413/// [`Decimal`](ScalarValue::Decimal) dtypes.
414fn bytes_from_proto(bytes: &[u8], dtype: &DType) -> VortexResult<ScalarValue> {
415    match dtype {
416        DType::Utf8(_) => Ok(ScalarValue::Utf8(BufferString::try_from(bytes)?)),
417        DType::Binary(_) => Ok(ScalarValue::Binary(ByteBuffer::copy_from(bytes))),
418        // TODO(connor): This is incorrect, we need to verify this matches the inner decimal_dtype.
419        DType::Decimal(..) => Ok(ScalarValue::Decimal(match bytes.len() {
420            1 => DecimalValue::I8(bytes[0] as i8),
421            2 => DecimalValue::I16(i16::from_le_bytes(
422                bytes
423                    .try_into()
424                    .ok()
425                    .vortex_expect("Buffer has invalid number of bytes"),
426            )),
427            4 => DecimalValue::I32(i32::from_le_bytes(
428                bytes
429                    .try_into()
430                    .ok()
431                    .vortex_expect("Buffer has invalid number of bytes"),
432            )),
433            8 => DecimalValue::I64(i64::from_le_bytes(
434                bytes
435                    .try_into()
436                    .ok()
437                    .vortex_expect("Buffer has invalid number of bytes"),
438            )),
439            16 => DecimalValue::I128(i128::from_le_bytes(
440                bytes
441                    .try_into()
442                    .ok()
443                    .vortex_expect("Buffer has invalid number of bytes"),
444            )),
445            32 => DecimalValue::I256(i256::from_le_bytes(
446                bytes
447                    .try_into()
448                    .ok()
449                    .vortex_expect("Buffer has invalid number of bytes"),
450            )),
451            l => vortex_bail!("invalid decimal byte length: {l}"),
452        })),
453        _ => vortex_bail!("expected Utf8, Binary, or Decimal dtype for BytesValue, got {dtype}"),
454    }
455}
456
457/// Deserialize a [`ScalarValue::Tuple`] from a protobuf `ListValue`.
458fn list_from_proto(
459    v: &ListValue,
460    dtype: &DType,
461    session: &VortexSession,
462) -> VortexResult<ScalarValue> {
463    let values = match dtype {
464        DType::List(element_dtype, _) | DType::FixedSizeList(element_dtype, ..) => v
465            .values
466            .iter()
467            .map(|elem| ScalarValue::from_proto(elem, element_dtype.as_ref(), session))
468            .collect::<VortexResult<Vec<_>>>()?,
469        DType::Struct(fields, _) => {
470            vortex_ensure_eq!(
471                v.values.len(),
472                fields.nfields(),
473                "ListValue has the wrong number of struct fields"
474            );
475
476            v.values
477                .iter()
478                .zip(fields.fields())
479                .map(|(value, field_dtype)| ScalarValue::from_proto(value, &field_dtype, session))
480                .collect::<VortexResult<Vec<_>>>()?
481        }
482        DType::Map(map, _) => {
483            let entry_dtype = map.entries_dtype();
484            v.values
485                .iter()
486                .map(|entry| ScalarValue::from_proto(entry, &entry_dtype, session))
487                .collect::<VortexResult<Vec<_>>>()?
488        }
489        _ => vortex_bail!("expected a tuple-backed dtype for ListValue, got {dtype}"),
490    };
491    Ok(ScalarValue::Tuple(values))
492}
493
494/// Deserialize a present union scalar value.
495fn union_from_proto(
496    value: &PbUnionValue,
497    dtype: &DType,
498    session: &VortexSession,
499) -> VortexResult<ScalarValue> {
500    let DType::Union(variants, _) = dtype else {
501        vortex_bail!("expected Union dtype for UnionValue, got {dtype}");
502    };
503
504    let type_id = u8::try_from(value.type_id)
505        .map_err(|_| vortex_err!("union type ID {} is outside the u8 range", value.type_id))?;
506
507    let child_index = variants.tag_to_child_index(type_id).ok_or_else(|| {
508        vortex_err!(
509            "union type ID {type_id} is not present in {:?}",
510            variants.type_ids()
511        )
512    })?;
513
514    let child_dtype = variants
515        .variant_by_index(child_index)
516        .ok_or_else(|| vortex_err!("union type ID {type_id} resolved out of bounds"))?;
517
518    let child_proto = value
519        .value
520        .as_deref()
521        .ok_or_else(|| vortex_err!("UnionValue missing child value"))?;
522
523    let child_value = ScalarValue::from_proto(child_proto, &child_dtype, session)?;
524    Scalar::validate(&child_dtype, child_value.as_ref()).map_err(|error| {
525        error.with_context(format!(
526            "union type ID {type_id} has invalid child for dtype {child_dtype}"
527        ))
528    })?;
529
530    Ok(ScalarValue::Union(UnionValue::new(type_id, child_value)))
531}
532
533#[cfg(test)]
534mod tests {
535    use std::f32;
536    use std::f64;
537    use std::sync::Arc;
538
539    use vortex_buffer::BufferString;
540    use vortex_error::vortex_panic;
541    use vortex_session::VortexSession;
542
543    use super::*;
544    use crate::dtype::DType;
545    use crate::dtype::DecimalDType;
546    use crate::dtype::Nullability;
547    use crate::dtype::PType;
548    use crate::dtype::UnionVariants;
549    use crate::dtype::extension::ExtDType;
550    use crate::dtype::extension::ExtId;
551    use crate::dtype::extension::ExtVTable;
552    use crate::dtype::half::f16;
553    use crate::proto::scalar as pb;
554    use crate::scalar::DecimalValue;
555    use crate::scalar::Scalar;
556    use crate::scalar::ScalarValue;
557    use crate::scalar_fn::ScalarFnVTable;
558    use crate::scalar_fn::builtin::literal::Literal;
559
560    fn session() -> VortexSession {
561        VortexSession::empty()
562    }
563
564    fn round_trip(scalar: Scalar) {
565        let decoded = Scalar::from_proto(&pb::Scalar::from(&scalar), &session()).unwrap();
566        assert_eq!(decoded.dtype(), scalar.dtype());
567        assert_eq!(decoded, scalar);
568    }
569
570    #[test]
571    fn test_null() {
572        round_trip(Scalar::null(DType::Null));
573    }
574
575    #[test]
576    fn test_bool() {
577        round_trip(Scalar::new(
578            DType::Bool(Nullability::Nullable),
579            Some(ScalarValue::Bool(true)),
580        ));
581    }
582
583    #[test]
584    fn test_primitive() {
585        round_trip(Scalar::new(
586            DType::Primitive(PType::I32, Nullability::Nullable),
587            Some(ScalarValue::Primitive(42i32.into())),
588        ));
589    }
590
591    #[test]
592    fn test_buffer() {
593        round_trip(Scalar::new(
594            DType::Binary(Nullability::Nullable),
595            Some(ScalarValue::Binary(vec![1, 2, 3].into())),
596        ));
597    }
598
599    #[test]
600    fn test_buffer_string() {
601        round_trip(Scalar::new(
602            DType::Utf8(Nullability::Nullable),
603            Some(ScalarValue::Utf8(BufferString::from("hello".to_string()))),
604        ));
605    }
606
607    #[test]
608    fn test_list() {
609        round_trip(Scalar::new(
610            DType::List(
611                Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)),
612                Nullability::Nullable,
613            ),
614            Some(ScalarValue::Tuple(vec![
615                Some(ScalarValue::Primitive(42i32.into())),
616                Some(ScalarValue::Primitive(43i32.into())),
617            ])),
618        ));
619    }
620
621    #[test]
622    fn test_map() {
623        let dtype = DType::map(
624            DType::Primitive(PType::I32, Nullability::NonNullable),
625            DType::Utf8(Nullability::Nullable),
626            true,
627            Nullability::Nullable,
628        )
629        .unwrap();
630        round_trip(
631            Scalar::try_map(
632                dtype.clone(),
633                [
634                    (
635                        Scalar::primitive(1i32, Nullability::NonNullable),
636                        Scalar::utf8("one", Nullability::Nullable),
637                    ),
638                    (
639                        Scalar::primitive(2i32, Nullability::NonNullable),
640                        Scalar::null(DType::Utf8(Nullability::Nullable)),
641                    ),
642                ],
643            )
644            .unwrap(),
645        );
646        round_trip(Scalar::null(dtype));
647    }
648
649    #[test]
650    fn test_f16() {
651        round_trip(Scalar::primitive(
652            f16::from_f32(0.42),
653            Nullability::Nullable,
654        ));
655    }
656
657    #[test]
658    fn test_i8() {
659        round_trip(Scalar::new(
660            DType::Primitive(PType::I8, Nullability::Nullable),
661            Some(ScalarValue::Primitive(i8::MIN.into())),
662        ));
663
664        round_trip(Scalar::new(
665            DType::Primitive(PType::I8, Nullability::Nullable),
666            Some(ScalarValue::Primitive(0i8.into())),
667        ));
668
669        round_trip(Scalar::new(
670            DType::Primitive(PType::I8, Nullability::Nullable),
671            Some(ScalarValue::Primitive(i8::MAX.into())),
672        ));
673    }
674
675    #[test]
676    fn test_decimal_i32_roundtrip() {
677        // A typical decimal with moderate precision and scale.
678        round_trip(Scalar::decimal(
679            DecimalValue::I32(123_456),
680            DecimalDType::new(10, 2),
681            Nullability::NonNullable,
682        ));
683    }
684
685    #[test]
686    fn test_decimal_i128_roundtrip() {
687        // A large decimal value that requires i128 storage.
688        round_trip(Scalar::decimal(
689            DecimalValue::I128(99_999_999_999_999_999_999),
690            DecimalDType::new(38, 6),
691            Nullability::Nullable,
692        ));
693    }
694
695    #[test]
696    fn test_decimal_null_roundtrip() {
697        round_trip(Scalar::null(DType::Decimal(
698            DecimalDType::new(10, 2),
699            Nullability::Nullable,
700        )));
701    }
702
703    #[test]
704    fn test_scalar_value_serde_roundtrip_binary() {
705        round_trip(Scalar::binary(
706            ByteBuffer::copy_from(b"hello"),
707            Nullability::NonNullable,
708        ));
709    }
710
711    #[test]
712    fn test_scalar_value_serde_roundtrip_utf8() {
713        round_trip(Scalar::utf8("hello", Nullability::NonNullable));
714    }
715
716    #[test]
717    fn test_variant_scalar_roundtrip() {
718        let nums = Scalar::list(
719            Arc::new(DType::Variant(Nullability::NonNullable)),
720            vec![
721                Scalar::variant(Scalar::primitive(-7_i16, Nullability::NonNullable)),
722                Scalar::variant(Scalar::primitive(42_u32, Nullability::NonNullable)),
723                Scalar::variant(Scalar::decimal(
724                    DecimalValue::I128(123_456_789),
725                    DecimalDType::new(18, 0),
726                    Nullability::NonNullable,
727                )),
728            ],
729            Nullability::NonNullable,
730        );
731
732        let nested = Scalar::list(
733            Arc::new(DType::Variant(Nullability::NonNullable)),
734            vec![
735                Scalar::variant(Scalar::from(true)),
736                Scalar::variant(nums),
737                Scalar::variant(Scalar::binary(
738                    ByteBuffer::copy_from(b"abc"),
739                    Nullability::NonNullable,
740                )),
741                Scalar::variant(Scalar::null(DType::Null)),
742            ],
743            Nullability::NonNullable,
744        );
745
746        round_trip(Scalar::variant(nested));
747    }
748
749    #[test]
750    fn test_variant_scalar_proto_preserves_scalar_null_vs_variant_null() {
751        let scalar_null = Scalar::null(DType::Variant(Nullability::Nullable));
752        let variant_null = Scalar::variant(Scalar::null(DType::Null));
753
754        let scalar_null_pb = pb::Scalar::from(&scalar_null);
755        let variant_null_pb = pb::Scalar::from(&variant_null);
756
757        assert_ne!(scalar_null_pb, variant_null_pb);
758        assert_eq!(
759            Scalar::from_proto(&scalar_null_pb, &session()).unwrap(),
760            scalar_null,
761        );
762        assert_eq!(
763            Scalar::from_proto(&variant_null_pb, &session()).unwrap(),
764            variant_null,
765        );
766    }
767
768    #[test]
769    fn test_union_scalar_roundtrip() -> VortexResult<()> {
770        let variants = UnionVariants::try_new(
771            ["int", "string"].into(),
772            vec![
773                DType::Primitive(PType::I32, Nullability::Nullable),
774                DType::Utf8(Nullability::NonNullable),
775            ],
776            vec![5, 9],
777        )?;
778
779        round_trip(Scalar::union(
780            variants.clone(),
781            5,
782            Scalar::primitive(42_i32, Nullability::Nullable),
783            Nullability::Nullable,
784        )?);
785
786        let inner_null = Scalar::union(
787            variants.clone(),
788            5,
789            Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)),
790            Nullability::Nullable,
791        )?;
792        let inner_null_proto = pb::Scalar::from(&inner_null);
793
794        assert!(matches!(
795            inner_null_proto
796                .value
797                .as_deref()
798                .and_then(|value| value.kind.as_ref()),
799            Some(Kind::UnionValue(union_value))
800                if matches!(
801                    union_value
802                        .value
803                        .as_deref()
804                        .and_then(|value| value.kind.as_ref()),
805                    Some(Kind::NullValue(_))
806                )
807        ));
808        let outer_null = Scalar::null(DType::Union(variants, Nullability::Nullable));
809        let outer_null_proto = pb::Scalar::from(&outer_null);
810        assert!(matches!(
811            outer_null_proto
812                .value
813                .as_deref()
814                .and_then(|value| value.kind.as_ref()),
815            Some(Kind::NullValue(_))
816        ));
817
818        assert_ne!(inner_null_proto, outer_null_proto);
819        round_trip(inner_null);
820        round_trip(outer_null);
821
822        let struct_dtype = DType::struct_(
823            [
824                (
825                    "number",
826                    DType::Primitive(PType::I32, Nullability::NonNullable),
827                ),
828                ("label", DType::Utf8(Nullability::Nullable)),
829            ],
830            Nullability::NonNullable,
831        );
832        let struct_scalar = Scalar::struct_(
833            struct_dtype.clone(),
834            [
835                Scalar::primitive(42_i32, Nullability::NonNullable),
836                Scalar::utf8("answer", Nullability::Nullable),
837            ],
838        );
839        let struct_variants =
840            UnionVariants::try_new(["record"].into(), vec![struct_dtype], vec![13])?;
841        round_trip(Scalar::union(
842            struct_variants,
843            13,
844            struct_scalar,
845            Nullability::NonNullable,
846        )?);
847
848        Ok(())
849    }
850
851    #[test]
852    fn test_union_proto_rejects_malformed_values() -> VortexResult<()> {
853        let variants = UnionVariants::try_new(
854            ["int"].into(),
855            vec![DType::Primitive(PType::I32, Nullability::Nullable)],
856            vec![5],
857        )?;
858        let dtype = DType::Union(variants, Nullability::NonNullable);
859
860        let unknown_tag = pb::ScalarValue {
861            kind: Some(Kind::UnionValue(Box::new(PbUnionValue {
862                type_id: 7,
863                value: Some(Box::new(ScalarValue::to_proto(
864                    Scalar::primitive(42_i32, Nullability::Nullable).value(),
865                ))),
866            }))),
867        };
868
869        assert!(ScalarValue::from_proto(&unknown_tag, &dtype, &session()).is_err());
870
871        let missing_child = pb::ScalarValue {
872            kind: Some(Kind::UnionValue(Box::new(PbUnionValue {
873                type_id: 5,
874                value: None,
875            }))),
876        };
877
878        let err = ScalarValue::from_proto(&missing_child, &dtype, &session())
879            .unwrap_err()
880            .to_string();
881        assert!(err.contains("UnionValue missing child value"), "{err}");
882
883        let wrong_child_value = pb::ScalarValue {
884            kind: Some(Kind::UnionValue(Box::new(PbUnionValue {
885                type_id: 5,
886                value: Some(Box::new(ScalarValue::to_proto(
887                    Scalar::utf8("wrong", Nullability::NonNullable).value(),
888                ))),
889            }))),
890        };
891
892        let err = ScalarValue::from_proto(&wrong_child_value, &dtype, &session())
893            .unwrap_err()
894            .to_string();
895        assert!(
896            err.contains("expected Utf8 or Binary dtype for StringValue, got i32?"),
897            "{err}"
898        );
899
900        Ok(())
901    }
902
903    #[test]
904    fn test_backcompat_f16_serialized_as_u64() {
905        // Backwards compatibility test for the legacy f16 serialization format.
906        //
907        // Previously, f16 ScalarValues were serialized as `Uint64Value(v.to_bits() as u64)` because
908        // the proto schema only had 64-bit integer types, and f16's underlying representation is
909        // u16 which got widened to u64.
910        //
911        // The current implementation uses a dedicated `F16Value` proto field, but we must still be
912        // able to deserialize the old format. This test verifies that:
913        //
914        // 1. A `Uint64Value` containing f16 bits can be read as a U64 primitive (the raw bits).
915        // 2. When wrapped in a Scalar with F16 dtype, the value is correctly interpreted as f16.
916        //
917        // This ensures data written with the old serialization format remains readable.
918
919        // Simulate the old serialization: f16(0.42) stored as Uint64Value with its bit pattern.
920        let f16_value = f16::from_f32(0.42);
921        let f16_bits_as_u64 = f16_value.to_bits() as u64; // 14008
922
923        let pb_scalar_value = pb::ScalarValue {
924            kind: Some(Kind::Uint64Value(f16_bits_as_u64)),
925        };
926
927        // Step 1: Verify the normal U64 scalar.
928        let scalar_value = ScalarValue::from_proto(
929            &pb_scalar_value,
930            &DType::Primitive(PType::U64, Nullability::NonNullable),
931            &session(),
932        )
933        .unwrap();
934        assert_eq!(
935            scalar_value.as_ref().map(|v| v.as_primitive()),
936            Some(&PValue::U64(14008u64)),
937        );
938
939        // Step 2: Verify that when we use F16 dtype, the Uint64Value is correctly interpreted.
940        let scalar_value_f16 = ScalarValue::from_proto(
941            &pb_scalar_value,
942            &DType::Primitive(PType::F16, Nullability::Nullable),
943            &session(),
944        )
945        .unwrap();
946
947        let scalar = Scalar::new(
948            DType::Primitive(PType::F16, Nullability::Nullable),
949            scalar_value_f16,
950        );
951
952        assert_eq!(
953            scalar.as_primitive().pvalue().unwrap(),
954            PValue::F16(f16::from_f32(0.42)),
955            "Uint64Value should be correctly interpreted as f16 when dtype is F16"
956        );
957    }
958
959    #[test]
960    fn test_scalar_value_direct_roundtrip_f16() {
961        // Test that ScalarValue with f16 roundtrips correctly without going through Scalar.
962        let f16_values = vec![
963            f16::from_f32(0.0),
964            f16::from_f32(1.0),
965            f16::from_f32(-1.0),
966            f16::from_f32(0.42),
967            f16::from_f32(5.722046e-6),
968            f16::from_f32(f32::consts::PI),
969            f16::INFINITY,
970            f16::NEG_INFINITY,
971            f16::NAN,
972        ];
973
974        for f16_val in f16_values {
975            let scalar_value = ScalarValue::Primitive(PValue::F16(f16_val));
976            let pb_value = ScalarValue::to_proto(Some(&scalar_value));
977            let read_back = ScalarValue::from_proto(
978                &pb_value,
979                &DType::Primitive(PType::F16, Nullability::NonNullable),
980                &session(),
981            )
982            .unwrap();
983
984            match (&scalar_value, read_back.as_ref()) {
985                (
986                    ScalarValue::Primitive(PValue::F16(original)),
987                    Some(ScalarValue::Primitive(PValue::F16(roundtripped))),
988                ) => {
989                    if original.is_nan() && roundtripped.is_nan() {
990                        // NaN values are equal for our purposes.
991                        continue;
992                    }
993                    assert_eq!(
994                        original, roundtripped,
995                        "F16 value {original:?} did not roundtrip correctly"
996                    );
997                }
998                _ => {
999                    vortex_panic!(
1000                        "Expected f16 primitive values, got {scalar_value:?} and {read_back:?}"
1001                    )
1002                }
1003            }
1004        }
1005    }
1006
1007    #[test]
1008    fn test_scalar_value_direct_roundtrip_preserves_values() {
1009        // Test that ScalarValue roundtripping preserves values (but not necessarily exact types).
1010        // Note: Proto encoding consolidates integer types (u8/u16/u32 → u64, i8/i16/i32 → i64).
1011
1012        // Test cases that should roundtrip exactly.
1013        let exact_roundtrip_cases: Vec<(&str, Option<ScalarValue>, DType)> = vec![
1014            ("null", None, DType::Null),
1015            (
1016                "bool_true",
1017                Some(ScalarValue::Bool(true)),
1018                DType::Bool(Nullability::Nullable),
1019            ),
1020            (
1021                "bool_false",
1022                Some(ScalarValue::Bool(false)),
1023                DType::Bool(Nullability::Nullable),
1024            ),
1025            (
1026                "u64",
1027                Some(ScalarValue::Primitive(PValue::U64(18446744073709551615))),
1028                DType::Primitive(PType::U64, Nullability::Nullable),
1029            ),
1030            (
1031                "i64",
1032                Some(ScalarValue::Primitive(PValue::I64(-9223372036854775808))),
1033                DType::Primitive(PType::I64, Nullability::Nullable),
1034            ),
1035            (
1036                "f32",
1037                Some(ScalarValue::Primitive(PValue::F32(f32::consts::E))),
1038                DType::Primitive(PType::F32, Nullability::Nullable),
1039            ),
1040            (
1041                "f64",
1042                Some(ScalarValue::Primitive(PValue::F64(f64::consts::PI))),
1043                DType::Primitive(PType::F64, Nullability::Nullable),
1044            ),
1045            (
1046                "string",
1047                Some(ScalarValue::Utf8(BufferString::from("test"))),
1048                DType::Utf8(Nullability::Nullable),
1049            ),
1050            (
1051                "bytes",
1052                Some(ScalarValue::Binary(vec![1, 2, 3, 4, 5].into())),
1053                DType::Binary(Nullability::Nullable),
1054            ),
1055        ];
1056
1057        for (name, value, dtype) in exact_roundtrip_cases {
1058            let pb_value = ScalarValue::to_proto(value.as_ref());
1059            let read_back = ScalarValue::from_proto(&pb_value, &dtype, &session()).unwrap();
1060
1061            let original_debug = format!("{value:?}");
1062            let roundtrip_debug = format!("{read_back:?}");
1063            assert_eq!(
1064                original_debug, roundtrip_debug,
1065                "ScalarValue {name} did not roundtrip exactly"
1066            );
1067        }
1068
1069        // The wire format widens integers; decoding must restore their original widths.
1070        let unsigned_cases = vec![
1071            (
1072                "u8",
1073                ScalarValue::Primitive(PValue::U8(255)),
1074                DType::Primitive(PType::U8, Nullability::Nullable),
1075                255u64,
1076            ),
1077            (
1078                "u16",
1079                ScalarValue::Primitive(PValue::U16(65535)),
1080                DType::Primitive(PType::U16, Nullability::Nullable),
1081                65535u64,
1082            ),
1083            (
1084                "u32",
1085                ScalarValue::Primitive(PValue::U32(4294967295)),
1086                DType::Primitive(PType::U32, Nullability::Nullable),
1087                4294967295u64,
1088            ),
1089        ];
1090
1091        for (name, value, dtype, expected) in unsigned_cases {
1092            let pb_value = ScalarValue::to_proto(Some(&value));
1093            let read_back = ScalarValue::from_proto(&pb_value, &dtype, &session()).unwrap();
1094
1095            match read_back.as_ref() {
1096                Some(ScalarValue::Primitive(pv)) => {
1097                    assert_eq!(pv.ptype(), dtype.as_ptype(), "{name} primitive width");
1098                    let v = match pv {
1099                        PValue::U8(v) => *v as u64,
1100                        PValue::U16(v) => *v as u64,
1101                        PValue::U32(v) => *v as u64,
1102                        PValue::U64(v) => *v,
1103                        _ => {
1104                            vortex_panic!("Unexpected primitive type for {name}: {pv:?}")
1105                        }
1106                    };
1107                    assert_eq!(
1108                        v, expected,
1109                        "ScalarValue {name} value not preserved: expected {expected}, got {v}"
1110                    );
1111                }
1112                _ => {
1113                    vortex_panic!("Unexpected type after roundtrip for {name}: {read_back:?}")
1114                }
1115            }
1116        }
1117
1118        // Signed integers must also recover their original widths.
1119        let signed_cases = vec![
1120            (
1121                "i8",
1122                ScalarValue::Primitive(PValue::I8(-128)),
1123                DType::Primitive(PType::I8, Nullability::Nullable),
1124                -128i64,
1125            ),
1126            (
1127                "i16",
1128                ScalarValue::Primitive(PValue::I16(-32768)),
1129                DType::Primitive(PType::I16, Nullability::Nullable),
1130                -32768i64,
1131            ),
1132            (
1133                "i32",
1134                ScalarValue::Primitive(PValue::I32(-2147483648)),
1135                DType::Primitive(PType::I32, Nullability::Nullable),
1136                -2147483648i64,
1137            ),
1138        ];
1139
1140        for (name, value, dtype, expected) in signed_cases {
1141            let pb_value = ScalarValue::to_proto(Some(&value));
1142            let read_back = ScalarValue::from_proto(&pb_value, &dtype, &session()).unwrap();
1143
1144            match read_back.as_ref() {
1145                Some(ScalarValue::Primitive(pv)) => {
1146                    assert_eq!(pv.ptype(), dtype.as_ptype(), "{name} primitive width");
1147                    let v = match pv {
1148                        PValue::I8(v) => *v as i64,
1149                        PValue::I16(v) => *v as i64,
1150                        PValue::I32(v) => *v as i64,
1151                        PValue::I64(v) => *v,
1152                        _ => {
1153                            vortex_panic!("Unexpected primitive type for {name}: {pv:?}")
1154                        }
1155                    };
1156                    assert_eq!(
1157                        v, expected,
1158                        "ScalarValue {name} value not preserved: expected {expected}, got {v}"
1159                    );
1160                }
1161                _ => {
1162                    vortex_panic!("Unexpected type after roundtrip for {name}: {read_back:?}")
1163                }
1164            }
1165        }
1166    }
1167
1168    // Backwards compatibility: signed integer stats could previously be serialized as unsigned.
1169    // Therefore, we allow casting between signed and unsigned integers of the same bit width.
1170    #[test]
1171    fn test_backcompat_signed_integer_deserialized_as_unsigned() {
1172        let v = ScalarValue::Primitive(PValue::I64(0));
1173        assert_eq!(
1174            Scalar::from_proto_value(
1175                &pb::ScalarValue::from(&v),
1176                &DType::Primitive(PType::U64, Nullability::Nullable),
1177                &session()
1178            )
1179            .unwrap(),
1180            Scalar::primitive(0u64, Nullability::Nullable)
1181        );
1182    }
1183
1184    // Backwards compatibility: unsigned integer stats could previously be serialized as signed.
1185    // Therefore, we allow casting between signed and unsigned integers of the same bit width.
1186    #[test]
1187    fn test_backcompat_unsigned_integer_deserialized_as_signed() {
1188        let v = ScalarValue::Primitive(PValue::U64(0));
1189        assert_eq!(
1190            Scalar::from_proto_value(
1191                &pb::ScalarValue::from(&v),
1192                &DType::Primitive(PType::I64, Nullability::Nullable),
1193                &session()
1194            )
1195            .unwrap(),
1196            Scalar::primitive(0i64, Nullability::Nullable)
1197        );
1198    }
1199
1200    /// An extension type whose metadata serializer always fails, standing in for a plugin.
1201    #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
1202    struct FailingMetadata;
1203
1204    impl ExtVTable for FailingMetadata {
1205        type Metadata = usize;
1206        type StoredMetadata = Self::Metadata;
1207        type NativeValue<'a> = &'a str;
1208
1209        #[expect(clippy::disallowed_methods, reason = "test-only id")]
1210        fn id(&self) -> ExtId {
1211            ExtId::new("test.failing_metadata")
1212        }
1213
1214        fn serialize_metadata(&self, _metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
1215            vortex_bail!("metadata serializer failed")
1216        }
1217
1218        fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult<Self::StoredMetadata> {
1219            Ok(0)
1220        }
1221
1222        fn metadata_from_storage(
1223            &self,
1224            stored_metadata: Self::StoredMetadata,
1225            _storage_dtype: &DType,
1226        ) -> VortexResult<Self::Metadata> {
1227            Ok(stored_metadata)
1228        }
1229
1230        fn storage_dtype(_metadata: &Self::Metadata) -> DType {
1231            DType::Primitive(PType::I32, Nullability::NonNullable)
1232        }
1233
1234        fn unpack_native<'a>(
1235            _ext_dtype: &'a ExtDType<Self>,
1236            _storage_value: &'a ScalarValue,
1237        ) -> VortexResult<Self::NativeValue<'a>> {
1238            Ok("")
1239        }
1240    }
1241
1242    fn failing_metadata_scalar() -> Scalar {
1243        let ext_dtype = ExtDType::<FailingMetadata>::try_new(0, Nullability::NonNullable).unwrap();
1244        Scalar::new(
1245            DType::Extension(ext_dtype.erased()),
1246            Some(ScalarValue::Primitive(PValue::I32(1))),
1247        )
1248    }
1249
1250    #[test]
1251    fn to_proto_propagates_extension_metadata_error() {
1252        let err = failing_metadata_scalar().to_proto().unwrap_err();
1253        assert!(
1254            err.to_string().contains("metadata serializer failed"),
1255            "{err}"
1256        );
1257    }
1258
1259    #[test]
1260    fn literal_serializer_propagates_extension_metadata_error() {
1261        let err = Literal.serialize(&failing_metadata_scalar()).unwrap_err();
1262        assert!(
1263            err.to_string().contains("metadata serializer failed"),
1264            "{err}"
1265        );
1266    }
1267}