Repository navigation
Conversation
|
@sdf-jkl Please take a look at this, thanks. |
|
🤖 Benchmark starting (GKE) | trigger Target: variant_kernels Sharding factor: 1 (1 workers). Comparing 7065eef (7065eef) to 6747ecd diff Run configurationrun benchmark variant_kernels
baseline:
ref: 6747ecda382b135ba0fb08868dd859a47c0304ad
changed:
ref: 7065eef2f4b46badd18494ba3d60b7b44098b6c1
env:
BENCH_FILTER: variant_get_utf8
shards: 1
Trigger commentResults will be posted when all workers finish. File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Target: variant_kernels Comparing 7065eef (7065eef) to 6747ecd diff Run configurationrun benchmark variant_kernels
baseline:
ref: 6747ecda382b135ba0fb08868dd859a47c0304ad
changed:
ref: 7065eef2f4b46badd18494ba3d60b7b44098b6c1
env:
BENCH_FILTER: variant_get_utf8
shards: 1
Trigger commentDetailsPer-runner informationvariant_kernels — shard 1/1Node: gk3-benchmark-cluster-nap-18uuhdwp-1344bf78-gp5r Instance: c4a-highmem-16 (12 vCPU / 65 GiB) uname: BENCH_COMMAND: cargo bench --features=arrow,async,test_common,experimental,object_store --bench variant_kernelsCPU Details (lscpu)Resource Usagebase (merge-base)
branch
File an issue against this benchmark runner |
| 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() | ||
| ))), | ||
| } | ||
| } |
There was a problem hiding this comment.
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.
| 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> { |
There was a problem hiding this comment.
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] |
There was a problem hiding this comment.
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.
| #[inline] | |
| #[inline(never)] |
| out.push_str(buffer.format(f)); | ||
| } | ||
|
|
||
| fn write_lexical_to_string<N: lexical_core::ToLexical>(out: &mut String, n: N) { |
There was a problem hiding this comment.
Keeps the integer formatter out of line, see the first comment above.
| 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 { |
There was a problem hiding this comment.
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.
| 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 { |
| 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"); | ||
| } |
There was a problem hiding this comment.
Uses the helper from the suggestion above.
| 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()), |
|
@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. |
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_getand arrow-cast forVariant::{Null/Bool/Int*/Float/Double/Decimal}toStringAre 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