sdf-jkl commented on code in PR #12303:
URL: https://github.com/apache/arrow-rs/pull/12303#discussion_r4724415395
##########
parquet-variant/src/canonicalize.rs:
##########
@@ -0,0 +1,552 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! Canonical encoding of [`Variant`] values.
+//!
+//! The Variant binary encoding allows one logical value to be written in many
ways: the metadata
+//! dictionary may hold unused or unsorted field names, an integer may use a
wider width than it
+//! needs, a decimal may carry trailing zeros, and so on. Byte-oriented
operations such as hashing
+//! for `GROUP BY` or a join therefore treat equal values as different.
+//!
+//! [`Variant::canonicalize`] rebuilds a value so that equal values share one
encoding.
+
+use std::collections::BTreeSet;
+
+use arrow_schema::ArrowError;
+
+use crate::{
+ ObjectFieldBuilder, Variant, VariantBuilder, VariantBuilderExt,
VariantDecimal4,
+ VariantDecimal8, VariantDecimal16, VariantObject,
+};
+
+impl Variant<'_, '_> {
+ /// Returns the canonical `(metadata, value)` encoding of this variant.
+ ///
+ /// Two variants that are logically equal canonicalize to identical bytes,
so the result can be
+ /// hashed or compared byte-wise. The rules follow the canonical form
proposed for Apache Spark
+ /// ([apache/spark#59669]):
+ ///
+ /// * The metadata dictionary holds only the field names the value
references, sorted by their
+ /// unsigned UTF-8 bytes, with the smallest offset width that fits.
+ /// * Object fields are written in dictionary (key) order; list elements
keep their order.
+ /// * Integers use the smallest of `INT8`, `INT16`, `INT32`, `INT64` that
holds the value.
+ /// * Decimals drop trailing zeros. An integral decimal that fits an `i64`
becomes an integer;
+ /// otherwise the smallest of `DECIMAL4`, `DECIMAL8`, `DECIMAL16` that
holds it is used.
+ /// * `FLOAT` and `DOUBLE` keep their type; `-0.0` becomes `0.0` and every
NaN becomes the
+ /// same bit pattern ([`f32::NAN`] / [`f64::NAN`]).
+ /// * Strings use the short-string encoding when they fit (at most 63
bytes).
+ /// * Booleans, `NULL`, dates, times, timestamps, binary and UUID have one
encoding already and
+ /// are copied as-is.
+ ///
+ /// Canonicalizing an already canonical value returns the same bytes.
+ ///
+ /// Note that the canonical form may change the Rust-level type of a
value: `Variant::Int64(1)`
+ /// canonicalizes to the bytes of `Variant::Int8(1)`, and
`Variant::Decimal4(1.0)` to those of
+ /// `Variant::Int8(1)`.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if the variant is malformed or an object holds the
same field name twice.
+ ///
+ /// # Example
+ /// ```
+ /// # use parquet_variant::{Variant, VariantBuilder};
+ /// // Two builders write the same object with a different dictionary order
+ /// let mut a = VariantBuilder::new().with_field_names(["b", "a",
"unused"]);
+ /// a.new_object().with_field("a", 1i64).with_field("b", 2i8).finish();
+ /// let (am, av) = a.finish();
+ ///
+ /// let mut b = VariantBuilder::new();
+ /// b.new_object().with_field("a", 1i8).with_field("b", 2i32).finish();
+ /// let (bm, bv) = b.finish();
+ ///
+ /// assert_ne!((&am, &av), (&bm, &bv));
+ /// let a_canonical = Variant::try_new(&am,
&av).unwrap().canonicalize().unwrap();
+ /// let b_canonical = Variant::try_new(&bm,
&bv).unwrap().canonicalize().unwrap();
+ /// assert_eq!(a_canonical, b_canonical);
+ /// ```
+ ///
+ /// [apache/spark#59669]: https://github.com/apache/spark/pull/59669
+ pub fn canonicalize(&self) -> Result<(Vec<u8>, Vec<u8>), ArrowError> {
+ let mut field_names = BTreeSet::new();
+ collect_field_names(self, &mut field_names)?;
+ // `str` orders by bytes, so the set is already in unsigned UTF-8
order.
+ let mut builder =
VariantBuilder::new().with_field_names(field_names.iter().copied());
+ append_canonical(&mut builder, self)?;
+ builder.try_finish()
+ }
+}
+
+/// Collects every field name referenced anywhere inside `value`.
+fn collect_field_names<'m>(
+ value: &Variant<'m, '_>,
+ names: &mut BTreeSet<&'m str>,
+) -> Result<(), ArrowError> {
+ match value {
+ Variant::Object(object) => {
+ for field in object.iter_try() {
+ let (name, value) = field?;
+ names.insert(name);
+ collect_field_names(&value, names)?;
+ }
+ }
+ Variant::List(list) => {
+ for item in list.iter_try() {
+ collect_field_names(&item?, names)?;
+ }
+ }
+ _ => {}
+ }
+ Ok(())
+}
+
+/// Appends `value` to `builder` in canonical form. The builder's metadata
dictionary must already
+/// hold every field name `value` references, in sorted order.
+fn append_canonical<B: VariantBuilderExt>(
+ builder: &mut B,
+ value: &Variant<'_, '_>,
+) -> Result<(), ArrowError> {
Review Comment:
I'd keep it out of this PR. `variant_from_number` lives in
parquet-variant-json, so making it `pub` there doesn't help canonicalize. The
reuse goes the other way: the JSON crate could later reuse parquet-variant's
narrowing instead of its own copy, once there is a reason to expose it. That
fits better as a follow-up.
##########
parquet-variant/src/canonicalize.rs:
##########
@@ -0,0 +1,469 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! Canonical encoding of [`Variant`] values.
+//!
+//! The Variant binary encoding allows one logical value to be written in many
ways: the metadata
+//! dictionary may hold unused or unsorted field names, an integer may use a
wider width than it
+//! needs, a decimal may carry trailing zeros, and so on. Byte-oriented
operations such as hashing
+//! for `GROUP BY` or a join therefore treat equal values as different.
+//!
+//! [`Variant::canonicalize`] rebuilds a value so that equal values share one
encoding.
+
+use std::collections::BTreeSet;
+
+use arrow_schema::ArrowError;
+
+use crate::{ObjectFieldBuilder, Variant, VariantBuilder, VariantBuilderExt};
+
+impl Variant<'_, '_> {
+ /// Returns the canonical `(metadata, value)` encoding of this variant.
+ ///
+ /// Two variants that are logically equal canonicalize to identical bytes,
so the result can be
+ /// hashed or compared byte-wise. The rules follow the canonical form used
by Apache Spark
+ /// ([apache/spark#59669]):
+ ///
+ /// * The metadata dictionary holds only the field names the value
references, sorted by their
+ /// unsigned UTF-8 bytes, with the smallest offset width that fits.
+ /// * Object fields are written in dictionary (key) order; list elements
keep their order.
+ /// * Each primitive uses the representative encoding of its equivalence
class in the Variant
+ /// spec, see [`Variant::canonical_primitive`]: the narrowest integer,
decimals with trailing
Review Comment:
`canonical_primitive` is `pub(crate)`, so this link fails
`rustdoc::private_intra_doc_links`. Our docs job (`cargo +nightly doc
--document-private-items` with `-Dwarnings`) errors on it: it was skipped on
this PR, but it runs on every push to main. The bullet already lists the rules,
so dropping the link is enough:
```suggestion
/// * Each primitive uses the representative encoding of its equivalence
class in the Variant
/// spec: the narrowest integer, decimals with trailing
```
##########
parquet-variant/src/canonicalize.rs:
##########
@@ -0,0 +1,469 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! Canonical encoding of [`Variant`] values.
+//!
+//! The Variant binary encoding allows one logical value to be written in many
ways: the metadata
+//! dictionary may hold unused or unsorted field names, an integer may use a
wider width than it
+//! needs, a decimal may carry trailing zeros, and so on. Byte-oriented
operations such as hashing
+//! for `GROUP BY` or a join therefore treat equal values as different.
+//!
+//! [`Variant::canonicalize`] rebuilds a value so that equal values share one
encoding.
+
+use std::collections::BTreeSet;
+
+use arrow_schema::ArrowError;
+
+use crate::{ObjectFieldBuilder, Variant, VariantBuilder, VariantBuilderExt};
+
+impl Variant<'_, '_> {
+ /// Returns the canonical `(metadata, value)` encoding of this variant.
+ ///
+ /// Two variants that are logically equal canonicalize to identical bytes,
so the result can be
+ /// hashed or compared byte-wise. The rules follow the canonical form used
by Apache Spark
+ /// ([apache/spark#59669]):
+ ///
+ /// * The metadata dictionary holds only the field names the value
references, sorted by their
+ /// unsigned UTF-8 bytes, with the smallest offset width that fits.
+ /// * Object fields are written in dictionary (key) order; list elements
keep their order.
+ /// * Each primitive uses the representative encoding of its equivalence
class in the Variant
+ /// spec, see [`Variant::canonical_primitive`]: the narrowest integer,
decimals with trailing
+ /// zeros dropped (promoted to an integer when integral and within
`i64`), `-0.0` as `0.0`
+ /// and one NaN pattern per float type, short strings when they fit,
microsecond timestamps
+ /// unless sub-microsecond digits are present. Null, booleans, dates,
times, binary and UUID
+ /// have one encoding already.
+ ///
+ /// Canonicalizing an already canonical value returns the same bytes.
+ ///
+ /// Note that the canonical form may change the Rust-level type of a
value: `Variant::Int64(1)`
+ /// canonicalizes to the bytes of `Variant::Int8(1)`, and
`Variant::Decimal4(1.0)` to those of
+ /// `Variant::Int8(1)`.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if the variant does not pass [full validation], for
example when an object
+ /// holds unsorted or repeated field names. Validation is cached, so this
is free for values
+ /// created with [`Variant::try_new`].
+ ///
+ /// # Example
+ /// ```
+ /// # use parquet_variant::{Variant, VariantBuilder};
+ /// // Two builders write the same object with a different dictionary order
+ /// let mut a = VariantBuilder::new().with_field_names(["b", "a",
"unused"]);
+ /// a.new_object().with_field("a", 1i64).with_field("b", 2i8).finish();
+ /// let (am, av) = a.finish();
+ ///
+ /// let mut b = VariantBuilder::new();
+ /// b.new_object().with_field("a", 1i8).with_field("b", 2i32).finish();
+ /// let (bm, bv) = b.finish();
+ ///
+ /// assert_ne!((&am, &av), (&bm, &bv));
+ /// let a_canonical = Variant::try_new(&am,
&av).unwrap().canonicalize().unwrap();
+ /// let b_canonical = Variant::try_new(&bm,
&bv).unwrap().canonicalize().unwrap();
+ /// assert_eq!(a_canonical, b_canonical);
+ /// ```
+ ///
+ /// [apache/spark#59669]: https://github.com/apache/spark/pull/59669
Review Comment:
```suggestion
/// [equivalence classes]:
https://github.com/apache/parquet-format/blob/master/VariantEncoding.md#encoding-types
```
##########
parquet-variant/src/variant/equivalence.rs:
##########
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! Equivalence classes of [`Variant`] primitive types.
+//!
+//! The [Variant spec] groups physical types into equivalence classes: `int8`
through `int64` and
+//! the three decimal widths are all *Exact Numeric*, short and long strings
are both *String*,
+//! micro- and nanosecond timestamps are both *Timestamp*, and so on. Two
values in the same class
+//! that denote the same thing are logically equal, even though their bytes
differ.
+//!
+//! [`Variant::canonical_primitive`] picks one representative encoding per
value in each class, so
+//! that logically equal primitives produce identical bytes. The rules match
the canonical form
+//! used by Apache Spark ([apache/spark#59669]).
+//!
+//! [Variant spec]:
https://github.com/apache/parquet-format/blob/master/VariantEncoding.md#encoding-types
+//! [apache/spark#59669]: https://github.com/apache/spark/pull/59669
Review Comment:
Since this module is the home of the classes, could the doc list them? One
bullet per class with its types reads as a quick reference. And since the
classes come from the Parquet spec, I'd drop the Spark reference here:
```suggestion
//! Equivalence classes of [`Variant`] primitive types, from the [Variant
spec]. Two values in one
//! class that denote the same thing are logically equal even when their
bytes differ.
//!
//! * Exact Numeric: `Int8`, `Int16`, `Int32`, `Int64`, `Decimal4`,
`Decimal8`, `Decimal16`
//! * String: `ShortString`, `String`
//! * Timestamp: `TimestampMicros`, `TimestampNanos`
//! * TimestampNTZ: `TimestampNtzMicros`, `TimestampNtzNanos`
//! * Boolean: `BooleanTrue`, `BooleanFalse`
//! * Float: `Float`
//! * Double: `Double`
//! * Date: `Date`
//! * TimeNTZ: `Time`
//! * Binary: `Binary`
//! * UUID: `Uuid`
//! * NullType: `Null`
//!
//! [`Variant::canonical_primitive`] picks one representative encoding per
value in each class, so
//! that logically equal primitives produce identical bytes.
//!
//! [Variant spec]:
https://github.com/apache/parquet-format/blob/master/VariantEncoding.md#encoding-types
```
##########
parquet-variant/src/canonicalize.rs:
##########
@@ -0,0 +1,469 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! Canonical encoding of [`Variant`] values.
+//!
+//! The Variant binary encoding allows one logical value to be written in many
ways: the metadata
+//! dictionary may hold unused or unsorted field names, an integer may use a
wider width than it
+//! needs, a decimal may carry trailing zeros, and so on. Byte-oriented
operations such as hashing
+//! for `GROUP BY` or a join therefore treat equal values as different.
+//!
+//! [`Variant::canonicalize`] rebuilds a value so that equal values share one
encoding.
+
+use std::collections::BTreeSet;
+
+use arrow_schema::ArrowError;
+
+use crate::{ObjectFieldBuilder, Variant, VariantBuilder, VariantBuilderExt};
+
+impl Variant<'_, '_> {
+ /// Returns the canonical `(metadata, value)` encoding of this variant.
+ ///
+ /// Two variants that are logically equal canonicalize to identical bytes,
so the result can be
+ /// hashed or compared byte-wise. The rules follow the canonical form used
by Apache Spark
+ /// ([apache/spark#59669]):
Review Comment:
On second thought about my earlier Spark comment: the rules come from the
Parquet spec's equivalence classes, so I'd point there instead of at Spark:
```suggestion
/// Two variants that are logically equal under the Variant spec's
[equivalence classes]
/// canonicalize to identical bytes, so the result can be hashed or
compared byte-wise:
```
##########
parquet-variant/src/variant/equivalence.rs:
##########
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! Equivalence classes of [`Variant`] primitive types.
+//!
+//! The [Variant spec] groups physical types into equivalence classes: `int8`
through `int64` and
+//! the three decimal widths are all *Exact Numeric*, short and long strings
are both *String*,
+//! micro- and nanosecond timestamps are both *Timestamp*, and so on. Two
values in the same class
+//! that denote the same thing are logically equal, even though their bytes
differ.
+//!
+//! [`Variant::canonical_primitive`] picks one representative encoding per
value in each class, so
+//! that logically equal primitives produce identical bytes. The rules match
the canonical form
+//! used by Apache Spark ([apache/spark#59669]).
+//!
+//! [Variant spec]:
https://github.com/apache/parquet-format/blob/master/VariantEncoding.md#encoding-types
+//! [apache/spark#59669]: https://github.com/apache/spark/pull/59669
+
+use crate::{Variant, VariantDecimal4, VariantDecimal8, VariantDecimal16};
+
+impl<'m, 'v> Variant<'m, 'v> {
+ /// Returns the representative encoding of this value within its
equivalence class.
+ ///
+ /// * Exact Numeric: the smallest of `INT8`, `INT16`, `INT32`, `INT64`
that holds the value.
+ /// Decimals drop trailing zeros; an integral decimal that fits an `i64`
becomes an integer,
+ /// otherwise the smallest of `DECIMAL4`, `DECIMAL8`, `DECIMAL16` that
holds it is used.
+ /// * Float and Double keep their type; `-0.0` becomes `0.0` and every NaN
becomes the same
+ /// bit pattern ([`f32::NAN`] / [`f64::NAN`]).
+ /// * String: the short-string encoding when the value fits (at most 63
bytes).
+ /// * Timestamp and TimestampNTZ: microseconds unless the value has
sub-microsecond digits.
+ /// * Null, Boolean, Date, Time, Binary and UUID have one encoding and are
returned unchanged.
+ /// * Objects and lists are returned unchanged; their contents are not
visited.
+ ///
+ /// The match is exhaustive on purpose: a type added to the spec must be
classified here.
+ pub(crate) fn canonical_primitive(&self) -> Variant<'m, 'v> {
+ match self {
+ Variant::Int8(v) => canonical_int(*v as i64),
+ Variant::Int16(v) => canonical_int(*v as i64),
+ Variant::Int32(v) => canonical_int(*v as i64),
+ Variant::Int64(v) => canonical_int(*v),
+ Variant::Decimal4(d) => canonical_decimal(d.integer() as i128,
d.scale()),
+ Variant::Decimal8(d) => canonical_decimal(d.integer() as i128,
d.scale()),
+ Variant::Decimal16(d) => canonical_decimal(d.integer(), d.scale()),
Review Comment:
The int arms widen to `i64` and narrow back (`canonical_int(*v as i64)`), so
an `Int8` walks the whole ladder to come back as itself. The existing accessors
already narrow each source type directly: `as_int8`..`as_int64` take every
exact numeric that fits, integral decimals included. Building on them, the
seven arms can share one helper, which also drops the integral-decimal branch,
and the narrowest-decimal pick can use the existing `TryFrom<VariantDecimal16>`
for `VariantDecimal4` / `VariantDecimal8`:
```rust
Variant::Int8(_)
| Variant::Int16(_)
| Variant::Int32(_)
| Variant::Int64(_)
| Variant::Decimal4(_)
| Variant::Decimal8(_)
| Variant::Decimal16(_) => self.canonical_exact_numeric(),
```
```rust
/// The narrowest integer that holds an integral value, otherwise the
narrowest decimal after
/// dropping trailing zeros.
fn canonical_exact_numeric(&self) -> Variant<'static, 'static> {
if let Some(v) = self.as_int8() {
return Variant::Int8(v);
}
if let Some(v) = self.as_int16() {
return Variant::Int16(v);
}
if let Some(v) = self.as_int32() {
return Variant::Int32(v);
}
if let Some(v) = self.as_int64() {
return Variant::Int64(v);
}
// Only exact numerics reach this point, and every one of them is a
valid DECIMAL16
let d = self.as_decimal16().expect("exact numeric fits DECIMAL16");
let (mut integer, mut scale) = (d.integer(), d.scale());
while scale > 0 && integer % 10 == 0 {
integer /= 10;
scale -= 1;
}
// Stripping zeros only shrinks the unscaled value and the scale, so the
result stays valid
let d = VariantDecimal16::try_new(integer, scale).expect("stripped
decimal fits DECIMAL16");
VariantDecimal4::try_from(d)
.map(Variant::from)
.or_else(|_| VariantDecimal8::try_from(d).map(Variant::from))
.unwrap_or_else(|_| Variant::from(d))
}
```
This replaces `canonical_int` and `canonical_decimal`. I tried it locally on
14cecc3e82 and the existing tests and clippy pass unchanged.
--
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]