Skip to content

[Variant] Align cast logic between variant_get and cast kernel for sc… - #12465

Open
klion26 wants to merge 1 commit into
apache:mainfrom
klion26:scalars2string_for_variant
Open

klion26 wants to merge 1 commit into
apache:mainfrom
klion26:scalars2string_for_variant

Conversation

@klion26

@klion26 klion26 commented Nov 25, 2026

Copy link
Copy Markdown
Member

Which issue does this PR close?

This is part of #10024 , and only for the scalar types

What changes are included in this PR?

Align the logic between variant_get and arrow-cast for Variant::{Null/Bool/Int*/Float/Double/Decimal}to String

Are these changes tested?

Yes, added tests to cover the logic

Are there any significant user-facing changes?

This will change the behavior for variant_get

@boring-cyborg boring-cyborg Bot added the parquet-variant parquet-variant* crates label Nov 25, 2026
@klion26

klion26 commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

@sdf-jkl Please take a look at this, thanks.

@sdf-jkl

sdf-jkl commented Nov 30, 2026

Copy link
Copy Markdown
Member

run benchmark variant_kernels
env:
BENCH_FILTER: "variant_get_utf8"
baseline:
ref: 6747ecd
changed:
ref: 7065eef

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark starting (GKE) | trigger

Target: variant_kernels

Sharding factor: 1 (1 workers).

Comparing 7065eef (7065eef) to 6747ecd diff

Run configuration
run benchmark variant_kernels
baseline:
  ref: 6747ecda382b135ba0fb08868dd859a47c0304ad
changed:
  ref: 7065eef2f4b46badd18494ba3d60b7b44098b6c1
env:
  BENCH_FILTER: variant_get_utf8
shards: 1
Trigger comment
run benchmark variant_kernels
env:
  BENCH_FILTER: "variant_get_utf8"
baseline:
  ref: 6747ecda382b135ba0fb08868dd859a47c0304ad
changed:
  ref: 7065eef2f4b46badd18494ba3d60b7b44098b6c1

Results will be posted when all workers finish.


File an issue against this benchmark runner

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark completed (GKE) | trigger

Target: variant_kernels

Comparing 7065eef (7065eef) to 6747ecd diff

Run configuration
run benchmark variant_kernels
baseline:
  ref: 6747ecda382b135ba0fb08868dd859a47c0304ad
changed:
  ref: 7065eef2f4b46badd18494ba3d60b7b44098b6c1
env:
  BENCH_FILTER: variant_get_utf8
shards: 1
Trigger comment
run benchmark variant_kernels
env:
  BENCH_FILTER: "variant_get_utf8"
baseline:
  ref: 6747ecda382b135ba0fb08868dd859a47c0304ad
changed:
  ref: 7065eef2f4b46badd18494ba3d60b7b44098b6c1
Details
group                                               base                                   changed
-----                                               ----                                   -------
variant_get_utf8_from_date                          1.00    556.2±0.89µs        ? ?/sec    1.06    590.4±1.07µs        ? ?/sec
variant_get_utf8_from_decimal                       1.00    464.6±9.08µs        ? ?/sec    1.90   882.8±35.10µs        ? ?/sec
variant_get_utf8_from_float                         1.00    437.9±5.93µs        ? ?/sec    1.65    723.6±5.98µs        ? ?/sec
variant_get_utf8_from_int                           1.00    438.3±5.77µs        ? ?/sec    1.37    599.2±5.67µs        ? ?/sec
variant_get_utf8_from_list                          1.00   613.8±17.53µs        ? ?/sec    1.11   680.9±19.72µs        ? ?/sec
variant_get_utf8_from_map_in_list                   1.00   632.6±17.81µs        ? ?/sec    1.10   698.7±20.39µs        ? ?/sec
variant_get_utf8_from_time                          1.00    761.2±2.58µs        ? ?/sec    1.03    786.2±2.66µs        ? ?/sec
variant_get_utf8_from_timestamp_with_timezone       1.00    551.0±2.60µs        ? ?/sec    1.07    587.3±2.32µs        ? ?/sec
variant_get_utf8_from_timestamp_without_timezone    1.00    550.4±2.51µs        ? ?/sec    1.07    588.3±2.29µs        ? ?/sec
variant_get_utf8_from_unshredded_string             1.00    487.3±6.46µs        ? ?/sec    1.00    487.0±4.32µs        ? ?/sec

Per-runner information
variant_kernels — shard 1/1

Node: gk3-benchmark-cluster-nap-18uuhdwp-1344bf78-gp5r

Instance: c4a-highmem-16 (12 vCPU / 65 GiB)

uname:

Linux bench-c7289701223-5972-scwml 6.12.105+ #1 SMP Sat Sep 19 07:55:25 UTC 2026 aarch64 GNU/Linux

BENCH_COMMAND:

cargo bench --features=arrow,async,test_common,experimental,object_store --bench variant_kernels
CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected
Resource Usage

base (merge-base)

Metric Value
Wall time 115.0s
Peak memory 374.3 MiB
Avg memory 353.0 MiB
CPU user 110.8s
CPU sys 0.2s
Peak spill 0 B

branch

Metric Value
Wall time 125.0s
Peak memory 428.5 MiB
Avg memory 361.4 MiB
CPU user 122.0s
CPU sys 0.1s
Peak spill 0 B

File an issue against this benchmark runner

@sdf-jkl sdf-jkl left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @klion26 🙏

Left some suggestions below

Comment on lines +1335 to +1376
fn append_value(&mut self, value: &Variant<'_, '_>) -> Result<bool> {
let value = match value {
// short-circuit the common case of string-like variants to avoid the overhead of casting
Variant::String(value) => value,
Variant::ShortString(value) => value.as_str(),
Variant::Null => {
self.builder.append_null();
return Ok(false);
}
_ => return self.append_cast_value(value),
};

self.builder.append_value(value);
Ok(true)
}

fn append_cast_value(&mut self, value: &Variant<'_, '_>) -> Result<bool> {
self.buffer.clear();
match variant_cast_with_options(value, self.cast_options, |value| {
match self.cast_mode {
VariantCastMode::Get => match write_variant_to_string(&mut self.buffer, value) {
true => Some(self.buffer.as_str()),
false => None,
},
// this function only handle no-string variant, return None here because we don't support shred non-string to string.
VariantCastMode::Shred => None,
}
}) {
Ok(Some(value)) => {
self.builder.append_value(value);
Ok(true)
}
Ok(None) => {
self.builder.append_null();
Ok(false)
}
Err(_) => Err(ArrowError::CastError(format!(
"Failed to extract primitive of type {} from variant {value:?}",
B::type_name()
))),
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

variant_cast_with_options already returns Ok(None) for Variant::Null in both safe and strict mode, and Variant::as_string() matches exactly String | ShortString. So the string short-circuit and the Null arm can move into the same closure, and append_cast_value is no longer needed. The behavior stays the same for every input and mode, and all existing tests pass.

Suggested change
fn append_value(&mut self, value: &Variant<'_, '_>) -> Result<bool> {
let value = match value {
// short-circuit the common case of string-like variants to avoid the overhead of casting
Variant::String(value) => value,
Variant::ShortString(value) => value.as_str(),
Variant::Null => {
self.builder.append_null();
return Ok(false);
}
_ => return self.append_cast_value(value),
};
self.builder.append_value(value);
Ok(true)
}
fn append_cast_value(&mut self, value: &Variant<'_, '_>) -> Result<bool> {
self.buffer.clear();
match variant_cast_with_options(value, self.cast_options, |value| {
match self.cast_mode {
VariantCastMode::Get => match write_variant_to_string(&mut self.buffer, value) {
true => Some(self.buffer.as_str()),
false => None,
},
// this function only handle no-string variant, return None here because we don't support shred non-string to string.
VariantCastMode::Shred => None,
}
}) {
Ok(Some(value)) => {
self.builder.append_value(value);
Ok(true)
}
Ok(None) => {
self.builder.append_null();
Ok(false)
}
Err(_) => Err(ArrowError::CastError(format!(
"Failed to extract primitive of type {} from variant {value:?}",
B::type_name()
))),
}
}
fn append_value(&mut self, value: &Variant<'_, '_>) -> Result<bool> {
self.buffer.clear();
let buffer = &mut self.buffer;
let cast_mode = self.cast_mode;
let result = variant_cast_with_options(value, self.cast_options, |value| {
value.as_string().or_else(|| {
(matches!(cast_mode, VariantCastMode::Get)
&& write_variant_to_string(buffer, value))
.then_some(buffer.as_str())
})
});
match result {
Ok(Some(value)) => {
self.builder.append_value(value);
Ok(true)
}
Ok(None) => {
self.builder.append_null();
Ok(false)
}
Err(_) => Err(ArrowError::CastError(format!(
"Failed to extract primitive of type {} from variant {value:?}",
B::type_name()
))),
}
}

This one is only for readability. It costs strings about 9 instructions per row (about 1%), because they now go through the closure, and it doesn't change the other paths. Feel free to skip it.

assert!(struct_array.is_null(0));
}

struct StringCastCase<'a> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the tests can be much smaller while keeping the same coverage. Each formatter arm needs one case, and the MIN/MAX-per-precision decimal tables mostly test write_decimal itself. Going through cast_to_variant and variant_get also makes each case a single Arrow array, so the values are not listed twice, and it covers the public path. Something like the version below, which replaces the new tests here (3 tests and about 110 lines instead of 5 tests and about 500 lines).

Proposed tests
    #[test]
    fn test_variant_get_string_matches_cast_kernel() {
        let inputs: Vec<ArrayRef> = vec![
            Arc::new(BooleanArray::from(vec![Some(true), Some(false), None])),
            Arc::new(Int8Array::from(vec![i8::MIN, i8::MAX])),
            Arc::new(Int16Array::from(vec![i16::MIN, i16::MAX])),
            Arc::new(Int32Array::from(vec![i32::MIN, i32::MAX])),
            Arc::new(Int64Array::from(vec![i64::MIN, i64::MAX])),
            Arc::new(Float32Array::from(vec![1.23, -0.0, 1e16, f32::NAN])),
            Arc::new(Float64Array::from(vec![
                0.1 + 0.2,
                -0.0,
                1e16,
                f64::INFINITY,
            ])),
            Arc::new(
                Decimal32Array::from(vec![-12345, 5]).with_data_type(DataType::Decimal32(9, 2)),
            ),
            Arc::new(
                Decimal64Array::from(vec![-12345, 5]).with_data_type(DataType::Decimal64(18, 2)),
            ),
            Arc::new(
                Decimal128Array::from(vec![-12345, 5]).with_data_type(DataType::Decimal128(38, 2)),
            ),
            Arc::new(StringArray::from(vec![
                "short",
                "a string longer than the sixty three bytes a short string can hold",
            ])),
        ];
        // Strict mode and non-default format options must not change the result.
        let options = CastOptions {
            safe: false,
            format_options: FormatOptions::new()
                .with_null("NULL")
                .with_quoted_strings(true),
        };

        for input in &inputs {
            let variants = ArrayRef::from(cast_to_variant(input.as_ref()).unwrap());
            for target_type in [DataType::Utf8, DataType::LargeUtf8, DataType::Utf8View] {
                let field = Arc::new(Field::new("result", target_type.clone(), true));
                let get_options = GetOptions::new()
                    .with_as_type(Some(field))
                    .with_cast_options(options.clone());

                let actual = variant_get(&variants, get_options).unwrap();
                let expected = cast_with_options(input, &target_type, &options).unwrap();
                assert_eq!(
                    actual.as_ref(),
                    expected.as_ref(),
                    "{} -> {target_type}",
                    input.data_type()
                );
            }
        }
    }

    /// `Variant::Null` is NULL in both modes, other unsupported values are NULL or an error.
    #[test]
    fn test_cast_variant_unsupported_to_string() {
        let (metadata, value) = {
            let mut builder = VariantBuilder::new();
            builder.new_object().with_field("key", 42).finish();
            builder.finish()
        };
        let object = Variant::new(&metadata, &value);

        for safe in [true, false] {
            let options = CastOptions {
                safe,
                ..Default::default()
            };
            let mut builder = make_typed_variant_to_arrow_row_builder(
                &DataType::Utf8,
                &options,
                2,
                VariantCastMode::Get,
            )
            .unwrap();

            assert!(!builder.append_value(Variant::Null).unwrap());
            let result = builder.append_value(object.clone());
            if safe {
                assert!(!result.unwrap());
                assert_eq!(builder.finish().unwrap().null_count(), 2);
            } else {
                assert!(matches!(result, Err(ArrowError::CastError(_))));
            }
        }
    }

    #[test]
    fn test_cast_variant_uuid_to_string() {
        let options = CastOptions::default();
        let mut builder = make_typed_variant_to_arrow_row_builder(
            &DataType::Utf8,
            &options,
            1,
            VariantCastMode::Get,
        )
        .unwrap();
        let uuid = Uuid::max();
        assert!(builder.append_value(Variant::Uuid(uuid)).unwrap());

        // Arrow cast has no FixedSizeBinary(16) -> Utf8, so expect the hyphenated form.
        let expected: ArrayRef = Arc::new(StringArray::from(vec![uuid.to_string()]));
        assert_eq!(builder.finish().unwrap().as_ref(), expected.as_ref());
    }

Test imports:

    use crate::type_conversion::VariantCastMode;
    use crate::{GetOptions, cast_to_variant, variant_get};
    use arrow::array::{
        Array, ArrayRef, BooleanArray, Decimal32Array, Decimal64Array, Decimal128Array,
        FixedSizeBinaryArray, Float32Array, Float64Array, Int8Array, Int16Array, Int32Array,
        Int64Array, ListArray, StringArray, StructArray,
    };
    use arrow::compute::{CastOptions, cast_with_options};
    use arrow::datatypes::{DataType, Field, Fields, UnionFields, UnionMode};
    use arrow::error::ArrowError;
    use arrow::util::display::FormatOptions;
    use parquet_variant::{Variant, VariantBuilder, VariantDecimal4};
    use std::sync::Arc;
    use uuid::Uuid;

I checked it by breaking each arm on purpose: dropping the Int16 arm, widening Float to f64, using scale 0 for Decimal8, formatting Double with std, changing the Bool text, skipping ShortString, changing the Uuid format, and returning an error for Variant::Null in strict mode. Each one fails the expected test. test_top_level_null_ignores_null_format moves into test_cast_variant_unsupported_to_string, because cast_to_variant(NullArray) produces SQL NULL rows, not Variant::Null.

}
}

#[inline]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The bench bot shows 1.03-1.11 on variant_get_utf8_from_{date,time,timestamp_*,list,map_in_list}, which still return NULL with this PR. Most of that comes from two calls per row. For every value that isn't a string or null, the string builder now calls variant_cast_with_options::<&str> and then write_variant_to_string, both out of line. write_variant_to_string is about 6.6 KB because ryu, lexical_core and write_decimal all get inlined into it, so LLVM never inlines it into the builder. For a Date it sets up a stack frame and goes through a jump table only to return false. The base had no call on this path.

This suggestion and the next three keep the heavy formatters out of line and let the small match inline. Unsupported types then return without a call, and supported types make one call instead of two. They also need #[inline(always)] on variant_cast_with_options (line 53). That line isn't in the diff, so I can't attach a suggestion there:

#[inline(always)]
pub(crate) fn variant_cast_with_options<'a, 'm, 'v, T>(

Retired instructions per row (perf stat, fixed number of iterations over the bench fixtures, x86-64):

case base this PR with these changes
date (NULL) 1024 1095 1042
timestamp ntz (NULL) 926 997 944
int 821 1037 1001
float 822 1225 1186
decimal 858 1528 1490
unshredded string 968 972 972

variant_get as Int64, Float64, Decimal64, Date32 or Timestamp stays the same or gets slightly cheaper. Tests, clippy and fmt pass with all four suggestions plus the line 53 attribute. I counted instructions rather than timing because my machine was busy, so I haven't checked wall time or aarch64.

Suggested change
#[inline]
#[inline(never)]

out.push_str(buffer.format(f));
}

fn write_lexical_to_string<N: lexical_core::ToLexical>(out: &mut String, n: N) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeps the integer formatter out of line, see the first comment above.

Suggested change
fn write_lexical_to_string<N: lexical_core::ToLexical>(out: &mut String, n: N) {
#[inline(never)]
fn write_lexical_to_string<N: lexical_core::ToLexical>(out: &mut String, n: N) {

out.push_str(unsafe { std::str::from_utf8_unchecked(written) });
}

pub(crate) fn write_variant_to_string(out: &mut String, variant: &Variant<'_, '_>) -> bool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moves the decimal formatting into its own out-of-line helper and forces the small match to inline. Together with #[inline(always)] on variant_cast_with_options, this removes both calls on rows that return NULL.

Suggested change
pub(crate) fn write_variant_to_string(out: &mut String, variant: &Variant<'_, '_>) -> bool {
#[inline(never)]
fn write_decimal_to_string<V: datatypes::DecimalNativeType>(out: &mut String, value: V, scale: u8) {
datatypes::write_decimal(out, value, scale as i8).expect("writing to string shouldn't fail");
}
#[inline(always)]
pub(crate) fn write_variant_to_string(out: &mut String, variant: &Variant<'_, '_>) -> bool {

Comment on lines +739 to +750
Variant::Decimal4(d) => {
datatypes::write_decimal(out, d.integer(), d.scale() as _)
.expect("writing to string shouldn't fail");
}
Variant::Decimal8(d) => {
datatypes::write_decimal(out, d.integer(), d.scale() as _)
.expect("writing to string shouldn't fail");
}
Variant::Decimal16(d) => {
datatypes::write_decimal(out, d.integer(), d.scale() as _)
.expect("writing to string shouldn't fail");
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Uses the helper from the suggestion above.

Suggested change
Variant::Decimal4(d) => {
datatypes::write_decimal(out, d.integer(), d.scale() as _)
.expect("writing to string shouldn't fail");
}
Variant::Decimal8(d) => {
datatypes::write_decimal(out, d.integer(), d.scale() as _)
.expect("writing to string shouldn't fail");
}
Variant::Decimal16(d) => {
datatypes::write_decimal(out, d.integer(), d.scale() as _)
.expect("writing to string shouldn't fail");
}
Variant::Decimal4(d) => write_decimal_to_string(out, d.integer(), d.scale()),
Variant::Decimal8(d) => write_decimal_to_string(out, d.integer(), d.scale()),
Variant::Decimal16(d) => write_decimal_to_string(out, d.integer(), d.scale()),

@klion26

klion26 commented Dec 1, 2026

Copy link
Copy Markdown
Member Author

@sdf-jkl Thanks for the review. For the perf, it is a bit odd; this part of the code was copied over from a previous PR with hardly any changes (which is why I didn't trigger the benchmarks), yet there are still some discrepancies. I’ll take another look tomorrow and make the necessary adjustments.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

parquet-variant parquet-variant* crates

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants