Repository navigation
Conversation
64ba87e to
994563b
Compare
| /// | ||
| /// ``` | ||
| /// # use parquet_variant::{Variant, VariantBuilder, VariantMetadataView, VariantView}; | ||
| /// # use parquet_variant::{Variant, VariantBuilder, VariantMetadataView, VariantPath, VariantView}; |
There was a problem hiding this comment.
maybe adding a new example that has paths would be clearer than moding the existing example?
There was a problem hiding this comment.
Done in 0bdfda4: the type-level example is back to the step-by-step get_field / get_index version, and get_path has its own example, including a path that does not exist.
78891e4 to
fc232ec
Compare
aea8314 to
fdec92b
Compare
|
run benchmark variant_kernels env: |
|
🤖 Benchmark starting (GKE) | trigger Target: variant_kernels Sharding factor: 1 (1 workers). Comparing variant-views-3-get (fdec92b) to e6977de (merge-base) diff Run configurationrun benchmark variant_kernels
env:
BENCH_FILTER: ^(variant_get|unshred_variant)
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 variant-views-3-get (fdec92b) to e6977de (merge-base) diff Run configurationrun benchmark variant_kernels
env:
BENCH_FILTER: ^(variant_get|unshred_variant)
shards: 1
Trigger commentDetailsPer-runner informationvariant_kernels — shard 1/1Node: gk3-benchmark-cluster-nap-r75scce3-df3e8234-njrs 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 |
`variant_get` reads each row of an unshredded column through `VariantView::get_path`. A row reads only the headers and field names along the path, and decodes only the value that it finds. Co-Authored-By: Claude Fable 5.2 <[email protected]>
fdec92b to
71b4a58
Compare
…_path its own Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01USkuh43UDwSoij2az8NwbM
|
run benchmark variant_kernels env: |
|
🤖 Benchmark starting (GKE) | trigger Target: variant_kernels Sharding factor: 1 (1 workers). Comparing variant-views-3-get (0bdfda4) to 3f109cd (merge-base) diff Run configurationrun benchmark variant_kernels
env:
BENCH_FILTER: ^variant_get_utf8_from_(list|map_in_list)$
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 variant-views-3-get (0bdfda4) to 3f109cd (merge-base) diff Run configurationrun benchmark variant_kernels
env:
BENCH_FILTER: ^variant_get_utf8_from_(list|map_in_list)$
shards: 1
Trigger commentDetailsPer-runner informationvariant_kernels — shard 1/1Node: gk3-benchmark-cluster-nap-8jswyi8a-b1859a01-gcpt 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 |
`VariantMetadataHeader` and `VariantListHeader` hold the header byte and decode it in their accessors, as `VariantObjectHeader` does. Every row of an unshredded column builds a metadata view, and every list row builds a list view, so both are copied often, and one byte is cheaper to build and copy than the decoded fields. `VariantMetadataHeader::try_new` keeps the version check, its only error. `VariantListHeader::new` is infallible, because every two-bit offset size is valid. `OffsetSizeBytes::try_new` lost its last callers and is removed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01USkuh43UDwSoij2az8NwbM
|
run benchmark variant_kernels env: |
|
🤖 Benchmark starting (GKE) | trigger Target: variant_kernels Sharding factor: 1 (1 workers). Comparing variant-views-3-get (b5c17dc) to 3f109cd (merge-base) diff Run configurationrun benchmark variant_kernels
env:
BENCH_FILTER: ^variant_get_utf8_from_(list|map_in_list)$
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 variant-views-3-get (b5c17dc) to 3f109cd (merge-base) diff Run configurationrun benchmark variant_kernels
env:
BENCH_FILTER: ^variant_get_utf8_from_(list|map_in_list)$
shards: 1
Trigger commentDetailsPer-runner informationvariant_kernels — shard 1/1Node: gk3-benchmark-cluster-nap-11jkhbhj-434a965e-s885 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 |
|
Sorry about the benchmark spam for anyone that has been subscribed. There was a regression in a couple of the benchmarks on ARM that weren't showing up locally, and I had to get to the bottom of it. Both of which look like they're fixed as part of b5c17dc So we're back to speed wins across the board. |
|
|
||
| /// Follows `path` from this value, or returns `None` if a step does not exist. | ||
| /// | ||
| /// A [`VariantPathElement::ListElement`] step does not exist, as in [`Variant::get_path`]. |
There was a problem hiding this comment.
I don't understand this sentence. Maybe an example would help (is it saying this function doesn't follow list access like [0])?
There was a problem hiding this comment.
If it doesn't support lists, is that something that is added in a follow on PR?
There was a problem hiding this comment.
ListElement is the [*] wildcard, not an index. Index steps like [0] are followed (the example below reads scores[1]). [*] matches nothing here, same as Variant::get_path, and variant_get rejects it before it gets this far. Maybe the doc could say that directly:
| /// A [`VariantPathElement::ListElement`] step does not exist, as in [`Variant::get_path`]. | |
| /// Index steps such as `[0]` are followed. A `[*]` step ([`VariantPathElement::ListElement`]) | |
| /// matches nothing and returns `None`, as in [`Variant::get_path`]. |
So I don't think a follow-up is needed. [*] only makes sense when building shredding schemas (ShreddedSchemaBuilder), and Spark's variant_get path grammar has keys and indexes only, no wildcard.
| } | ||
|
|
||
| impl OffsetSizeBytes { | ||
| /// Build from the `offset_size_minus_one` bits (see spec). |
There was a problem hiding this comment.
So the point is that the error handling takes too much space / messes up inlining?
I was wondering if removing this somehow removed required validation, but I think given it is only looking at 2 bits there are only 4 possible values, so that should be ok
There was a problem hiding this comment.
No validation was dropped here. Both old callers of try_new already passed only 2 bits (header_byte >> 6 for metadata, value_header & 0x03 for lists), so its error branch could never run, and from_bits masks the same way.
It became dead code once the headers store the raw byte, like VariantObjectHeader in #12309. The description gives the reason for that: one byte is cheaper to build and copy than the decoded fields.
| } else { | ||
| as_field.map(|f| f.data_type()) | ||
| }; | ||
| if target.typed_value_column().is_none() { |
There was a problem hiding this comment.
With this early return, every non-empty path goes to get_path_from_bytes: the only caller that passes one is the NotShredded step, and its target has no typed_value. That allows two follow-on changes:
- The loop below now always gets an empty path, so
VariantPathRowBuilder, theWithPathvariant and thepathparameter ofmake_variant_to_arrow_row_builderare unreachable. - The
unshred_variantcall above can move into the empty-path return. Today an explicitVariantoutput (as_typewith theVariantTypeextension, which is what datafusion-variant passes) unshreds theNotShreddedtarget beforeget_path_from_bytesreads the same bytes. When some rows have a null leftovervalue,unshred_variantfalls back to its row loop and validates and re-encodes every row first.
Together that is +7/-61:
diff
diff --git a/parquet-variant-compute/src/variant_get.rs b/parquet-variant-compute/src/variant_get.rs
index 4fb2faf4b9..9fe5b44a4a 100644
--- a/parquet-variant-compute/src/variant_get.rs
+++ b/parquet-variant-compute/src/variant_get.rs
@@ -209,7 +209,6 @@ fn get_path_from_bytes(
) -> Result<ArrayRef> {
let mut builder = make_variant_to_arrow_row_builder(
target.metadata_column(),
- VariantPath::default(),
as_type,
cast_options,
target.len(),
@@ -287,20 +286,8 @@ fn shredded_get_path(
));
}
- // Collapse any shredding back to binary. Only the `NotShredded` step below passes a
- // non-empty `path`, and there `target` is already a plain `value` column (no
- // `typed_value`) -- so `unshred_variant` hits its clone fast-path, with nothing deeper
- // to shred. The builder then walks any remaining path per-row, emitting variant output
- // because `as_type` is `None`.
- let target = if requested_variant {
- unshred_variant(&target)?
- } else {
- target
- };
-
- // Path exhausted, variant requested: return the target directly.
if requested_variant && path.is_empty() {
- return Ok(ArrayRef::from(target));
+ return Ok(ArrayRef::from(unshred_variant(&target)?));
}
let as_type = if requested_variant {
@@ -311,9 +298,11 @@ fn shredded_get_path(
if target.typed_value_column().is_none() {
return get_path_from_bytes(&target, &path, as_type, cast_options);
}
+ // Only the `NotShredded` step passes a non-empty `path`, and its target has no
+ // `typed_value`.
+ debug_assert!(path.is_empty() && !requested_variant);
let mut builder = make_variant_to_arrow_row_builder(
target.metadata_column(),
- path,
as_type,
cast_options,
target.len(),
diff --git a/parquet-variant-compute/src/variant_to_arrow.rs b/parquet-variant-compute/src/variant_to_arrow.rs
index 52c3956403..59c35fd876 100644
--- a/parquet-variant-compute/src/variant_to_arrow.rs
+++ b/parquet-variant-compute/src/variant_to_arrow.rs
@@ -25,7 +25,7 @@ use arrow::compute::{CastOptions, DecimalCast, cast_with_options};
use arrow::datatypes::{self, DataType, DecimalType};
use arrow::error::{ArrowError, Result};
use arrow_schema::{FieldRef, Fields, TimeUnit, UnionFields, UnionMode};
-use parquet_variant::{Variant, VariantPath};
+use parquet_variant::Variant;
use std::sync::Arc;
/// Builder for converting variant values into strongly typed Arrow arrays.
@@ -40,9 +40,6 @@ pub(crate) enum VariantToArrowRowBuilder<'a> {
Map(MapVariantToArrowRowBuilder<'a>),
Encoded(EncodedVariantToArrowRowBuilder<'a>),
BinaryVariant(VariantToBinaryVariantArrowRowBuilder),
-
- // Path extraction wrapper - contains a boxed enum for any of the above
- WithPath(VariantPathRowBuilder<'a>),
}
impl VariantToArrowRowBuilder<'_> {
@@ -56,7 +53,6 @@ impl VariantToArrowRowBuilder<'_> {
Map(b) => b.append_null(),
Encoded(b) => b.append_null(),
BinaryVariant(b) => b.append_null(),
- WithPath(path_builder) => path_builder.append_null(),
}
}
@@ -70,7 +66,6 @@ impl VariantToArrowRowBuilder<'_> {
Map(b) => b.append_value(&value),
Encoded(b) => b.append_value(value),
BinaryVariant(b) => b.append_value(value),
- WithPath(path_builder) => path_builder.append_value(value),
}
}
@@ -84,7 +79,6 @@ impl VariantToArrowRowBuilder<'_> {
Map(b) => b.finish(),
Encoded(b) => b.finish(),
BinaryVariant(b) => b.finish(),
- WithPath(path_builder) => path_builder.finish(),
}
}
}
@@ -162,14 +156,13 @@ fn make_typed_variant_to_arrow_row_builder<'a>(
pub(crate) fn make_variant_to_arrow_row_builder<'a>(
metadata: &ArrayRef,
- path: VariantPath<'a>,
data_type: Option<&'a DataType>,
cast_options: &'a CastOptions,
capacity: usize,
) -> Result<VariantToArrowRowBuilder<'a>> {
use VariantToArrowRowBuilder::*;
- let mut builder = match data_type {
+ Ok(match data_type {
// If no data type was requested, build an unshredded VariantArray.
None => BinaryVariant(VariantToBinaryVariantArrowRowBuilder::new(
metadata.clone(),
@@ -181,17 +174,7 @@ pub(crate) fn make_variant_to_arrow_row_builder<'a>(
capacity,
VariantCastMode::Get,
)?,
- };
-
- // Wrap with path extraction if needed
- if !path.is_empty() {
- builder = WithPath(VariantPathRowBuilder {
- builder: Box::new(builder),
- path,
- })
- }
-
- Ok(builder)
+ })
}
/// Builder for converting primitive variant values to Arrow arrays. It is used by both
@@ -1168,32 +1151,6 @@ impl<'a> ArrayVariantToArrowRowBuilder<'a> {
}
}
-/// A thin wrapper whose only job is to extract a specific path from a variant value and pass the
-/// result to a nested builder.
-pub(crate) struct VariantPathRowBuilder<'a> {
- builder: Box<VariantToArrowRowBuilder<'a>>,
- path: VariantPath<'a>,
-}
-
-impl VariantPathRowBuilder<'_> {
- fn append_null(&mut self) -> Result<()> {
- self.builder.append_null()
- }
-
- fn append_value(&mut self, value: Variant<'_, '_>) -> Result<bool> {
- if let Some(v) = value.get_path(&self.path) {
- self.builder.append_value(v)
- } else {
- self.builder.append_null()?;
- Ok(false)
- }
- }
-
- fn finish(self) -> Result<ArrayRef> {
- self.builder.finish()
- }
-}
-
macro_rules! define_variant_to_primitive_builder {
(struct $name:ident<$lifetime:lifetime $(, $generic:ident: $bound:path )?>
|$array_param:ident $(, $field:ident: $field_type:ty)?| -> $builder_name:ident $(< $array_type:ty >)? { $init_expr: expr },The crate tests pass, and the output matches this PR on everything I tried (unshredded, sliced, dictionary metadata, and partially shredded objects, for typed, None and explicit Variant outputs, safe and strict). On 8192 partially shredded objects where half the rows have nothing left over, variant_get of a leftover field with an explicit Variant output went from about 2.6 ms to 0.6 ms locally, the same as with as_type: None. No existing benchmark covers that case, so I can add one in a separate PR.
One side effect: on that route, malformed bytes outside the path no longer raise an error in strict mode, because unshred_variant no longer validates the whole row. That matches the as_type: None route and #12513.
| } | ||
| } | ||
|
|
||
| /// A binary-like column whose array type is resolved once, not on every row. |
There was a problem hiding this comment.
nit: only BinaryView is resolved once here. Binary, LargeBinary and dictionary or run-end metadata still go through binary_array_value on every row.
| /// A binary-like column whose array type is resolved once, not on every row. | |
| /// A binary-like column that resolves `BinaryView` once and other array types on every row. |
|
|
||
| /// Follows `path` from this value, or returns `None` if a step does not exist. | ||
| /// | ||
| /// A [`VariantPathElement::ListElement`] step does not exist, as in [`Variant::get_path`]. |
There was a problem hiding this comment.
ListElement is the [*] wildcard, not an index. Index steps like [0] are followed (the example below reads scores[1]). [*] matches nothing here, same as Variant::get_path, and variant_get rejects it before it gets this far. Maybe the doc could say that directly:
| /// A [`VariantPathElement::ListElement`] step does not exist, as in [`Variant::get_path`]. | |
| /// Index steps such as `[0]` are followed. A `[*]` step ([`VariantPathElement::ListElement`]) | |
| /// matches nothing and returns `None`, as in [`Variant::get_path`]. |
So I don't think a follow-up is needed. [*] only makes sense when building shredding schemas (ShreddedSchemaBuilder), and Spark's variant_get path grammar has keys and indexes only, no wildcard.
| } | ||
|
|
||
| impl OffsetSizeBytes { | ||
| /// Build from the `offset_size_minus_one` bits (see spec). |
There was a problem hiding this comment.
No validation was dropped here. Both old callers of try_new already passed only 2 bits (header_byte >> 6 for metadata, value_header & 0x03 for lists), so its error branch could never run, and from_bits masks the same way.
It became dead code once the headers store the raw byte, like VariantObjectHeader in #12309. The description gives the reason for that: one byte is cheaper to build and copy than the decoded fields.
klion26
left a comment
There was a problem hiding this comment.
LGTM, thanks for this improvment
| // A row with neither `value` nor `typed_value` is `Variant::Null`, which has no fields. | ||
| let Some(value) = value.value(i) else { | ||
| match path.is_empty() { | ||
| true => builder.append_value(Variant::Null).map(drop)?, |
There was a problem hiding this comment.
why do we need to call map(drop) here?
Which issue does this PR close?
Rationale for this change
For a path over unshredded data,
variant_getbuilds aVariantfor every row and then walks the path through it. Building theVariantchecks the first and last offsets of the metadata and of each object and list, and each field lookup validates the UTF-8 of the names that it probes. Rows that do not contain the path do all of that and produce a null.What changes are included in this PR?
VariantView::get_pathfollows a path of field names and list indexes through the views added in feat(variant): add header-only views of encoded variant bytes #12309.variant_getreads a column that has notyped_valuethrough it, for field and index paths and for typed andVariantoutput. A row reads only the headers and names along the path, and decodes only the value that it finds.BinaryColumnresolves the array type of themetadataandvaluecolumns once, not on every row.VariantObjectHeaderin feat(variant): add header-only views of encoded variant bytes #12309,VariantMetadataHeaderandVariantListHeadernow hold the header byte and decode it in their accessors. Every row builds a metadata view and every list row builds a list view, and one byte is cheaper to build and copy than the decoded fields.VariantListHeader::newcannot fail, and the now unusedOffsetSizeBytes::try_newis removed.The gain comes from skipping the per-row
Variantconstruction and the UTF-8 validation of probed names. A scalar result also never reads the metadata dictionary.Are these changes tested?
The existing
variant_gettests cover the new path, because their unshredded input now takes it.VariantView::get_pathhas a test that compares it withVariant::get_path.Benchmarks (local run, x86_64 Linux, against #12309 before it merged):
variant_get_binary_from_stringvariant_get_binary_from_unshredded_binaryvariant_get_list_index_all_oob_int64_64_rowsvariant_get_list_index_shreddedvariant_get_list_index_unshreddedvariant_get_shredded_utf8variant_get_unshredded_object_path_262k_rowsvariant_get_utf8_from_datevariant_get_utf8_from_decimalvariant_get_utf8_from_floatvariant_get_utf8_from_intvariant_get_utf8_from_listvariant_get_utf8_from_map_in_listvariant_get_utf8_from_timevariant_get_utf8_from_timestamp_with_timezonevariant_get_utf8_from_timestamp_without_timezonevariant_get_utf8_from_unshredded_stringThe shredded benchmarks (
variant_get_shredded_utf8,variant_get_list_index_shredded,variant_get_list_index_all_oob_int64_64_rows) do not take the new path.Are there any user-facing changes?
New public API in
parquet-variant:VariantView::get_path.On malformed variant bytes,
variant_geton an unshredded column returns an error, or a null under safe casting. Before, this path could panic.🤖 Generated with Claude Code
https://claude.ai/code/session_01USkuh43UDwSoij2az8NwbM