Repository navigation
feat(variant): add header-only views of encoded variant bytes - #12309
Conversation
05b97a9 to
a849621
Compare
|
run benchmark variant_validation resources: |
|
run benchmark variant_validation |
|
run benchmark variant_kernels env: resources: |
|
🤖 Benchmark starting (GKE) | trigger Target: variant_validation Sharding factor: 1 (1 workers). Comparing variant-views-2-views (a849621) to 093ef04 (merge-base) diff Run configurationrun benchmark variant_validation
resources:
arch: amd64
shards: 1
Results will be posted when all workers finish. File an issue against this benchmark runner |
|
🤖 Benchmark starting (GKE) | trigger Target: variant_kernels Sharding factor: 1 (1 workers). Comparing variant-views-2-views (a849621) to 093ef04 (merge-base) diff Run configurationrun benchmark variant_kernels
env:
BENCH_FILTER: ^(variant_get|unshred_variant)
resources:
arch: amd64
shards: 1
Results will be posted when all workers finish. File an issue against this benchmark runner |
|
🤖 Benchmark starting (GKE) | trigger Target: variant_validation Sharding factor: 1 (1 workers). Comparing variant-views-2-views (a849621) to 093ef04 (merge-base) diff Run configurationrun benchmark variant_validation
shards: 1
Results will be posted when all workers finish. File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Target: variant_validation Comparing variant-views-2-views (a849621) to 093ef04 (merge-base) diff Run configurationrun benchmark variant_validation
resources:
arch: amd64
shards: 1
DetailsPer-runner informationvariant_validation — shard 1/1Node: gk3-benchmark-cluster-nap-1by8wdmb-66f5cd78-lrns Instance: c4-highmem-16 (12 vCPU / 65 GiB) uname: BENCH_COMMAND: cargo bench --features=arrow,async,test_common,experimental,object_store --bench variant_validationCPU Details (lscpu)Resource Usagebase (merge-base)
branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Target: variant_validation Comparing variant-views-2-views (a849621) to 093ef04 (merge-base) diff Run configurationrun benchmark variant_validation
shards: 1
DetailsPer-runner informationvariant_validation — shard 1/1Node: gk3-benchmark-cluster-nap-ts4i8vqe-9ca2b83f-m8zh Instance: c4a-highmem-16 (12 vCPU / 65 GiB) uname: BENCH_COMMAND: cargo bench --features=arrow,async,test_common,experimental,object_store --bench variant_validationCPU Details (lscpu)Resource Usagebase (merge-base)
branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Target: variant_kernels Comparing variant-views-2-views (a849621) to 093ef04 (merge-base) diff Run configurationrun benchmark variant_kernels
env:
BENCH_FILTER: ^(variant_get|unshred_variant)
resources:
arch: amd64
shards: 1
DetailsPer-runner informationvariant_kernels — shard 1/1Node: gk3-benchmark-cluster-nap-1by8wdmb-4d579947-wjlw Instance: c4-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 |
|
Checking this out |
alamb
left a comment
There was a problem hiding this comment.
Thank you @cetra3 -- this is really nicely structured and I really like the new view API. The performance gains are 👌 very nicw
I had some suggestions to improve the docs but I think those could be done as follow on PRs, though it would be nice to do them here.
Let's wait until @sdf-jkl has a chance to weigh in too, but from my perspective this is a really nice improvement
cc @scovich as well who I remember was discussing something similar to this deferred validation during initial implementation.
Some suggestions for follow ons:
- Add a link to the view types in https://github.com/apache/arrow-rs/blob/a849621adca4a121c7197e09d0c3911df6f68766/parquet-variant/src/variant.rs#L191-L190 so it is easier to discover
| } | ||
| } | ||
|
|
||
| /// A variant value of which only the header byte has been read. |
There was a problem hiding this comment.
for anyone else reviewing this PR, this is a good place to start to understand what is going on
There was a problem hiding this comment.
Should [some of] this be hoisted to a mod doc comment since the concepts apply to all four variant building blocks (value, object, list, metadata)?
There was a problem hiding this comment.
| } | ||
|
|
||
| /// Checks the last field offset, and returns the bounded [`VariantObject`] that uses | ||
| /// `metadata`, the promoted form of this view's metadata dictionary. |
There was a problem hiding this comment.
why do we need to mention the metadata here? It seems unecessary as the function doesn't do anything specific with the metadata 🤔
There was a problem hiding this comment.
Not directly, but every VariantObject has a metadata inside it, that had to come from somewhere.
But I don't know how the "promoted form" part relates, and the error spec is vague at best. Perhaps better to just say something like this?
/// Attempts to interpret this view and `metadata` as a
/// [validated][`VariantObject::try_new#validation`] `VariantObject`
(matches the wording of the linked VariantObject constructor)
There was a problem hiding this comment.
Reworded in e913e33 to "Attempts to interpret this view and metadata as an unvalidated VariantObject, which checks the last field offset", with a link to the VariantObject validation docs. I wrote unvalidated rather than validated, because it does not do the full validation of VariantObject::try_new.
| } | ||
|
|
||
| /// Checks the first and last offsets, and returns the bounded [`VariantList`] that uses | ||
| /// `metadata`, the promoted form of this view's metadata dictionary. |
There was a problem hiding this comment.
same comment here about metadata reference -- I think we should clean up the comment
There was a problem hiding this comment.
Same change for VariantListView::try_into_list in e913e33.
| EMPTY_VARIANT_METADATA, EMPTY_VARIANT_METADATA_BYTES, VARIANT_SPEC_VERSION, VariantMetadata, | ||
| }; | ||
| pub use self::object::VariantObject; | ||
| pub use self::view::{VariantListView, VariantMetadataView, VariantObjectView, VariantView}; |
There was a problem hiding this comment.
Added VariantView to the main APIs in the crate docs in e913e33, and a paragraph on views to the validation section of the Variant docs.
| fn field_name(&self, field_id: usize) -> &str { | ||
| &self.metadata[field_id] | ||
| } | ||
| // Byte order is `str` order, so the comparison needs no UTF-8 validation. |
There was a problem hiding this comment.
This comment seems like it should be attached to the code below
// Byte order is `str` order, so the comparison needs no UTF-8 validation.
name(field_a_id).cmp(name(field_b_id))And then the docstring here should be
/// Compares the field names of two field ids, which must be less than
/// [`Self::num_field_names`]. Panics if a field id is out of bounds.
| pub(crate) struct VariantListHeader { | ||
| num_elements_size: OffsetSizeBytes, | ||
| offset_size: OffsetSizeBytes, | ||
| pub(crate) num_elements_size: OffsetSizeBytes, |
There was a problem hiding this comment.
why do we need to make the fields pub(crate)? The accessors are pub(crate) which should be enough (or maybe we have to change them to return OffsetSizeBytes or something
There was a problem hiding this comment.
Done in 70ce6cc: the fields are private again, and the views read them through accessors that return OffsetSizeBytes.
| pub(crate) struct VariantMetadataHeader { | ||
| version: u8, | ||
| is_sorted: bool, | ||
| pub(crate) is_sorted: bool, |
There was a problem hiding this comment.
likewise here it would be nice to use accessors rather than pub (crate) fields
| num_elements_size: OffsetSizeBytes, | ||
| field_id_size: OffsetSizeBytes, | ||
| field_offset_size: OffsetSizeBytes, | ||
| pub(crate) num_elements_size: OffsetSizeBytes, |
Double checking: The spec requires that a variant object’s field IDs must be listed in lexicographic order of their field names, using unsigned byte ordering of the UTF-8 encodings. So this optimization should not break sort ordering. It might allow an invalid utf8 search key to match an invalid utf8 field that was already present, but hopefully the key was already validated? |
scovich
left a comment
There was a problem hiding this comment.
LGTM except the binary search helper duplication.
| } | ||
|
|
||
| /// Checks the last field offset, and returns the bounded [`VariantObject`] that uses | ||
| /// `metadata`, the promoted form of this view's metadata dictionary. |
There was a problem hiding this comment.
Not directly, but every VariantObject has a metadata inside it, that had to come from somewhere.
But I don't know how the "promoted form" part relates, and the error spec is vague at best. Perhaps better to just say something like this?
/// Attempts to interpret this view and `metadata` as a
/// [validated][`VariantObject::try_new#validation`] `VariantObject`
(matches the wording of the linked VariantObject constructor)
| } | ||
| } | ||
|
|
||
| /// A variant value of which only the header byte has been read. |
There was a problem hiding this comment.
Should [some of] this be hoisted to a mod doc comment since the concepts apply to all four variant building blocks (value, object, list, metadata)?
| let header = first_byte_from_slice(value)?; | ||
| Ok(Self { | ||
| metadata, | ||
| value, | ||
| header, | ||
| }) |
There was a problem hiding this comment.
Other than the header byte itself, length validation is deferred until the operation that would actually reference the bytes in question?
There was a problem hiding this comment.
Yes. Building a VariantView reads only the header byte. Each accessor bounds-checks the bytes it reads when it reads them, and returns an error if they are out of range.
| match self.basic_type() { | ||
| VariantBasicType::Object => { | ||
| VariantObjectView::try_new(self.metadata, self.value).map(Some) | ||
| } | ||
| _ => Ok(None), | ||
| } |
There was a problem hiding this comment.
compact alternative to consider:
| match self.basic_type() { | |
| VariantBasicType::Object => { | |
| VariantObjectView::try_new(self.metadata, self.value).map(Some) | |
| } | |
| _ => Ok(None), | |
| } | |
| (self.basic_type() == VariantBasicType::Object) | |
| .then(|| VariantObjectView::try_new(self.metadata, self.value)) | |
| .transpose() |
(more below)
There was a problem hiding this comment.
I'd rather keep the match here, since it reads as a plain dispatch on the basic type. Happy to switch if you feel strongly.
| match i < self.len() { | ||
| true => Ok(()), | ||
| false => Err(index_error("Variant object field", i, self.len())), | ||
| } |
There was a problem hiding this comment.
aside: It will be nice to have bool.ok_or_else once MSRV bumps to 1.98:
(i < self.len()).ok_or_else(|| index_error("Variant object field", i, self.len()))(some day, not now)
There was a problem hiding this comment.
Agreed, I'll switch once the MSRV allows it.
| /// Binary search over `0..len` with a fallible comparison, which returns the first error it hits. | ||
| /// | ||
| /// Returns the index for which `cmp` returns [`Ordering::Equal`], if any. | ||
| pub(crate) fn try_binary_search( |
There was a problem hiding this comment.
This is a near copy of try_binary_search_range_by below, differing only in:
- Explicit start..end vs. implied 0..len
- Comparator fallibility expressed differently (Result vs. Option)
- Result/Option vs. Option/Result return value
- Not-found None vs. Err
What is the significance of these differences? Can we somehow harmonize the two?
There was a problem hiding this comment.
AFAICT, the new function has superior semantics (returns the actual error from a failed comparison) and none of the old function's call sites actually rely on the Some(Err(insertion_point)) it so carefully returns. Recommend delete the old method and take over its name.
There was a problem hiding this comment.
Done in 70ce6cc: the old helper is gone, and the new one took its name and its Range parameter. borrowed_field_id uses it too.
|
One follow-up question:
These are all fallible, is it intentional to omit the customary |
a849621 to
70ce6cc
Compare
|
@scovich, on your two questions:
The methods on the existing types take
No, renamed in e913e33 to @sdf-jkl, @alamb would like your review before this merges, when you have time. |
|
(looks like there is a merge conflict due to #12430) |
… and lists (apache#12430) # Which issue does this PR close? - Follow-up to apache#11106, which made `unshred_variant_nested_fallback` 1.85x slower on the benchmark runner. # Rationale for this change `VariantObject::iter_try` and `VariantList::iter_try` call `with_full_validation()` on every child, and `ValueBuilder::try_append_variant` then recurses into each child object or list and calls `iter_try` again. A value nested `d` levels deep is fully validated about `d` times. With apache#11106, `unshred_variant` takes this path for fallback values, even though it has already fully validated each value with `Variant::try_new_with_metadata`. Full validation of an object or list recursively validates all of its children, so every child of a validated value is already valid. The accessors build each child with only shallow checks, so the child loses that fact and gets validated again. This is the same problem apache#10879 fixed for metadata dictionary entries. # What changes are included in this PR? `VariantObject` and `VariantList` mark a child as fully validated when they build it from a fully validated parent. `with_full_validation` on such a child returns immediately, so `iter_try`, `try_field` and `try_get` no longer re-validate subtrees. Children of unvalidated parents are built and validated as before. This conflicts with apache#12309 from @cetra3, which rewrites the code that builds child values. The resolution adds the same one-line call where apache#12309 builds children, and I am happy to do it in whichever PR lands second. # Are these changes tested? `test_children_inherit_full_validation` checks that the fields and list elements of a validated value report `is_fully_validated()`, and that those of an unvalidated value do not. It fails if either the object or the list half of the change is removed. `unshred_variant_nested_fallback` from `variant_kernels` (local x86, `codegen-units=1`): | | time | |---|---| | before apache#11106 | 89.7 ms | | apache#11106 | 159.8 ms | | apache#11106 and this PR | 87.1 ms | Removing the `with_full_validation()` calls from both `iter_try` implementations entirely gives about the same time (88.8 ms), so the re-validation accounts for the whole regression. # Are there any significant user-facing changes? Children returned by the accessors of a fully validated `VariantObject` or `VariantList` (`field`, `get`, `iter` and their fallible versions) now report `is_fully_validated() == true`. They reported `false` before, although they were valid. No public API changes. # AI usage disclosure Claude Code helped find the cause, write the change and test, and run the benchmarks. I reviewed the change and the measurements. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
Add `VariantView`, `VariantMetadataView`, `VariantObjectView` and `VariantListView`. Building a view reads one header. Each accessor reads and bounds-checks only the bytes it needs, and compares field names as bytes. `VariantMetadata`, `VariantObject` and `VariantList` are now built by promoting a view, and their accessors delegate to it. `ObjectBuilder::finish` sorts fields with the new `MetadataBuilder::cmp_field_names`. Co-Authored-By: Claude Fable 5.2 <[email protected]>
`try_binary_search_range_by` now returns the comparison's error and `None` when nothing matches, and replaces `try_binary_search`. The view types read the header fields through accessors, so the fields stay private. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`VariantView::to_variant`, `VariantMetadataView::into_metadata`, `VariantObjectView::into_object` and `VariantListView::into_list` can fail, so they become `try_to_variant`, `try_into_metadata`, `try_into_object` and `try_into_list`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`VariantObject::iter` builds each field's `Variant` from the field's bytes, so it does not need the `VariantView` that `read_field` returns. Co-Authored-By: Claude Opus 5.5 <[email protected]>
e913e33 to
5c0b413
Compare
|
run benchmark variant_kernels env: resources: |
|
🤖 Benchmark starting (GKE) | trigger Target: variant_kernels Sharding factor: 1 (1 workers). Comparing variant-views-2-views (5c0b413) to e6977de (merge-base) diff Run configurationrun benchmark variant_kernels
env:
BENCH_FILTER: ^(variant_get|unshred_variant)
resources:
arch: amd64
shards: 1
Results will be posted when all workers finish. File an issue against this benchmark runner |
|
run benchmark variant_kernels env: |
|
🤖 Benchmark starting (GKE) | trigger Target: variant_kernels Sharding factor: 1 (1 workers). Comparing variant-views-2-views (5c0b413) to e6977de (merge-base) diff Run configurationrun benchmark variant_kernels
env:
BENCH_FILTER: ^(variant_get|unshred_variant)
shards: 1
Results will be posted when all workers finish. File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Target: variant_kernels Comparing variant-views-2-views (5c0b413) to e6977de (merge-base) diff Run configurationrun benchmark variant_kernels
env:
BENCH_FILTER: ^(variant_get|unshred_variant)
resources:
arch: amd64
shards: 1
DetailsPer-runner informationvariant_kernels — shard 1/1Node: gk3-benchmark-cluster-nap-lo14axs0-c886a7ad-946f Instance: c4-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 |
|
🤖 Benchmark completed (GKE) | trigger Target: variant_kernels Comparing variant-views-2-views (5c0b413) to e6977de (merge-base) diff Run configurationrun benchmark variant_kernels
env:
BENCH_FILTER: ^(variant_get|unshred_variant)
shards: 1
DetailsPer-runner informationvariant_kernels — shard 1/1Node: gk3-benchmark-cluster-nap-dxmpzwbw-456a4eb2-dvl2 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 |
`VariantObjectHeader` now holds the header byte instead of three decoded sizes. Views copy the header, and a three-byte copy reads bytes that separate stores wrote, so the load waits for both stores to commit. The old constructor's error path was unreachable, because both sizes come from two masked bits, so the constructor is now infallible. `try_field_with_shallow_validation` reads the field bytes instead of building a throwaway `VariantView`. `iter` keeps reading through one view, and `iter_try` returns to main's accessor calls, which keep its `next` small enough to inline into the builder. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
run benchmark variant_kernels env: |
|
🤖 Benchmark starting (GKE) | trigger Target: variant_kernels Sharding factor: 1 (1 workers). Comparing variant-views-2-views (8745630) 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-2-views (8745630) 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-4y0dwbxz-925fcc3a-dpkf 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 |
|
Not caused by this PR, but since it rewrites let md = VariantMetadata::new(&[0x01, 0, 0]);
let obj = VariantObject::new(md, &[0x32, 1, 0xFF, 0xFF, 0xFF, 0xFF, 0, 1, 0x00]);
obj.get("x"); // panics: Invalid variant object field nameEither |
sdf-jkl
left a comment
There was a problem hiding this comment.
Thanks @cetra3, this is really cool.
I did some digging in Spark and it seems like they avoid eager validation and use views in all of their kernels.
I think it's a great idea to move all variant kernels to be using view.
I want to file a follow up issue to track this
|
EPIC! |

Which issue does this PR close?
This PR is the first open PR of the stack split out of #11511. #12308 has merged, so the diff is this PR's change alone.
Rationale for this change
Every access to a variant value pays for checks that the access does not use. The unvalidated constructors of
VariantMetadata,VariantObjectandVariantListread the first and last offsets of each header and trim the byte slices. A field lookup then validates the UTF-8 of every dictionary name that its binary search probes.For most kernel work, a value needs much less: the header of each object or list along a path, the names that the binary search probes, and the bytes of the value that it finds.
This PR adds the types that read that way, and builds the existing types on them. The kernels start to use the views in the next PRs of the stack.
What changes are included in this PR?
VariantView,VariantMetadataView,VariantObjectViewandVariantListView.strdoes, so a search does not validate UTF-8.VariantMetadataView::try_into_metadata,VariantObjectView::try_into_object,VariantListView::try_into_listandVariantView::try_to_variantadd the first and last offset checks that unvalidated instances guarantee.VariantMetadata,VariantObjectandVariantListare now built by promoting a view, and their accessors (get,field,field_name,iter,get_entry) delegate to it. Their public behavior is unchanged.ObjectBuilder::finishsorts fields with a newMetadataBuilder::cmp_field_names.ReadOnlyMetadataBuildercompares the names as bytes.The docs of
VariantViewdescribe the design.Are these changes tested?
The existing types now delegate to the views, so their tests also cover the views. The views also have direct tests: agreement with
VariantMetadata,VariantObjectandVariantList, and every truncation and single-byte corruption of a sample value, which must not panic.Benchmark runner results, this PR against
main:variant_validationon x86_64 and Neoverse V2, andvariant_kernelson x86_64.metadata_iter/8metadata_iter/32metadata_iter/128bench_validate_complex_objectbench_validate_large_objectbench_validate_large_nested_listobject_field_name/{8,32,128}object_get_by_name/8object_get_by_name/32object_get_by_name/128object_iter/8object_iter/32object_iter/128variant_get_unshredded_object_path_262k_rowsvariant_get_list_index_unshreddedvariant_get_utf8_from_listvariant_get_utf8_from_map_in_listvariant_get_utf8_from_unshredded_stringvariant_get_decimal_short_string_to_decimal256(76,2)_wide_8192_safevariant_get_decimal_string_to_decimal128(38,3)_long_8192_safevariant_get_decimal_string_to_decimal128(38,3)_long_8192_strictunshred_variant_objectunshred_variant_listunshred_variant_partial_objectunshred_variant_partial_object_unsorted_metadataSlower inputs:
metadata_iteris 4–5% slower on x86_64 at 32 and 128 entries, and 5–7% faster on Neoverse V2. My local x86_64 machine measured it 13–16% slower.variant_getbenchmarks that cast long strings to decimals are 6–11% slower on x86_64. I have not found the cause. This PR does not change the string decoding or decimal parsing code. On that path it only changes howVariantMetadatais built, which does the same checks as before.variant_getbenchmarks that read objects or lists are 2–3% slower on x86_64. The next PR of the stack movesvariant_getonto the views.Are there any user-facing changes?
New public API in
parquet-variant:VariantView,VariantMetadataView,VariantObjectViewandVariantListView, with their methods.VariantMetadata::view,VariantObject::viewandVariantList::view.MetadataBuilder::cmp_field_names, a provided trait method.VariantBasicType, whichVariantView::basic_typereturns.No existing public API changes. Some out-of-range errors from metadata and list accessors have new message text.
🤖 Generated with Claude Code