sdf-jkl commented on code in PR #12465:
URL: https://github.com/apache/arrow-rs/pull/12465#discussion_r4724447299
##########
parquet-variant-compute/src/variant_to_arrow.rs:
##########
@@ -1307,6 +1310,76 @@ define_variant_to_primitive_builder!(
type_name: B::type_name()
);
+pub(crate) struct VariantToStringArrowBuilder<'a, B: StringLikeArrayBuilder> {
+ builder: B,
+ cast_options: &'a CastOptions<'a>,
+ cast_mode: VariantCastMode,
+ buffer: String,
+}
+
+impl<'a, B: StringLikeArrayBuilder> VariantToStringArrowBuilder<'a, B> {
+ fn new(cast_options: &'a CastOptions<'a>, capacity: usize, cast_mode:
VariantCastMode) -> Self {
+ Self {
+ builder: B::with_capacity(capacity),
+ cast_options,
+ cast_mode,
+ buffer: String::new(),
+ }
+ }
+
+ fn append_null(&mut self) -> Result<()> {
+ self.builder.append_null();
+ Ok(())
+ }
+
+ 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()
+ ))),
+ }
+ }
Review 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.
```suggestion
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.
##########
parquet-variant-compute/src/type_conversion.rs:
##########
@@ -707,6 +710,57 @@ pub(crate) fn variant_to_boolean(
}
}
+#[inline]
Review 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:
```rust
#[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.
```suggestion
#[inline(never)]
```
##########
parquet-variant-compute/src/type_conversion.rs:
##########
@@ -707,6 +710,57 @@ pub(crate) fn variant_to_boolean(
}
}
+#[inline]
+fn write_float_to_string<F: Float>(out: &mut String, f: F) {
+ let mut buffer = ryu::Buffer::new();
+ out.push_str(buffer.format(f));
+}
+
+fn write_lexical_to_string<N: lexical_core::ToLexical>(out: &mut String, n: N)
{
+ // i64::FORMATTED_SIZE is the upper bound for all integer types we support
+ // (i8/i16/i32/i64). With power-of-two feature it's 128, otherwise 20.
+ // We can't use N::FORMATTED_SIZE in a generic function
(generic_const_exprs).
+ let mut buf = [0u8; i64::FORMATTED_SIZE];
+ let written = lexical_core::write(n, &mut buf);
+ // Lexical core produces valid UTF-8
+ out.push_str(unsafe { std::str::from_utf8_unchecked(written) });
+}
+
+pub(crate) fn write_variant_to_string(out: &mut String, variant: &Variant<'_,
'_>) -> bool {
Review 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.
```suggestion
#[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 {
```
##########
parquet-variant-compute/src/variant_to_arrow.rs:
##########
@@ -1932,4 +2013,511 @@ mod tests {
let struct_array =
struct_array.as_any().downcast_ref::<StructArray>().unwrap();
assert!(struct_array.is_null(0));
}
+
+ struct StringCastCase<'a> {
Review 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).
<details><summary>Proposed tests</summary>
```rust
#[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:
```rust
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;
```
</details>
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`.
##########
parquet-variant-compute/src/type_conversion.rs:
##########
@@ -707,6 +710,57 @@ pub(crate) fn variant_to_boolean(
}
}
+#[inline]
+fn write_float_to_string<F: Float>(out: &mut String, f: F) {
+ let mut buffer = ryu::Buffer::new();
+ out.push_str(buffer.format(f));
+}
+
+fn write_lexical_to_string<N: lexical_core::ToLexical>(out: &mut String, n: N)
{
Review Comment:
Keeps the integer formatter out of line, see the first comment above.
```suggestion
#[inline(never)]
fn write_lexical_to_string<N: lexical_core::ToLexical>(out: &mut String, n:
N) {
```
##########
parquet-variant-compute/src/type_conversion.rs:
##########
@@ -707,6 +710,57 @@ pub(crate) fn variant_to_boolean(
}
}
+#[inline]
+fn write_float_to_string<F: Float>(out: &mut String, f: F) {
+ let mut buffer = ryu::Buffer::new();
+ out.push_str(buffer.format(f));
+}
+
+fn write_lexical_to_string<N: lexical_core::ToLexical>(out: &mut String, n: N)
{
+ // i64::FORMATTED_SIZE is the upper bound for all integer types we support
+ // (i8/i16/i32/i64). With power-of-two feature it's 128, otherwise 20.
+ // We can't use N::FORMATTED_SIZE in a generic function
(generic_const_exprs).
+ let mut buf = [0u8; i64::FORMATTED_SIZE];
+ let written = lexical_core::write(n, &mut buf);
+ // Lexical core produces valid UTF-8
+ out.push_str(unsafe { std::str::from_utf8_unchecked(written) });
+}
+
+pub(crate) fn write_variant_to_string(out: &mut String, variant: &Variant<'_,
'_>) -> bool {
+ match variant {
+ Variant::BooleanTrue => out.push_str("true"),
+ Variant::BooleanFalse => out.push_str("false"),
+ Variant::Int8(i) => write_lexical_to_string(out, *i),
+ Variant::Int16(i) => write_lexical_to_string(out, *i),
+ Variant::Int32(i) => write_lexical_to_string(out, *i),
+ Variant::Int64(i) => write_lexical_to_string(out, *i),
+ Variant::Float(f) => write_float_to_string(out, *f),
+ Variant::Double(d) => write_float_to_string(out, *d),
+ 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");
+ }
Review Comment:
Uses the helper from the suggestion above.
```suggestion
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()),
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]