spark-test commented on code in PR #59669:
URL: https://github.com/apache/spark/pull/59669#discussion_r4571226873


##########
common/variant/src/main/java/org/apache/spark/types/variant/VariantBuilder.java:
##########
@@ -527,21 +843,44 @@ public void appendVariant(Variant v) {
   }
 
   private void appendVariantImpl(byte[] value, byte[] metadata, int pos) {
+    appendVariantImpl(value, metadata, pos, null);
+  }
+
+  private void appendVariantImpl(
+      byte[] value, byte[] metadata, int pos, int[] canonicalIds) {
     checkIndex(pos, value.length);
     int basicType = value[pos] & BASIC_TYPE_MASK;
     switch (basicType) {
       case OBJECT:
         handleObject(value, pos, (size, idSize, offsetSize, idStart, 
offsetStart, dataStart) -> {
           ArrayList<FieldEntry> fields = new ArrayList<>(size);
           int start = writePos;
-          for (int i = 0; i < size; ++i) {
-            int id = readUnsigned(value, idStart + idSize * i, idSize);
-            int offset = readUnsigned(value, offsetStart + offsetSize * i, 
offsetSize);
+          Integer[] fieldOrder = null;
+          if (canonicalIds != null && size > 1) {
+            fieldOrder = new Integer[size];
+            int[] newIds = new int[size];
+            for (int fieldIndex = 0; fieldIndex < size; ++fieldIndex) {
+              fieldOrder[fieldIndex] = fieldIndex;
+              int keyId = readUnsigned(value, idStart + idSize * fieldIndex, 
idSize);
+              newIds[fieldIndex] = canonicalIds[keyId];
+            }
+            // Write values in key order; finishWritingObject only sorts the 
header entries.
+            // `buildCanonicalized` adds the keys in sorted order, so new IDs 
follow key order.
+            Arrays.sort(fieldOrder, (left, right) -> 
Integer.compare(newIds[left], newIds[right]));

Review Comment:
   **Nit (P3):** For every object with more than one field, this branch 
allocates an `Integer[size]` and an `int[size]`, boxes each field index 
(indices from 128 allocate) and runs the comparator sort before writing any 
value. As the comment above says, the new ids follow key order, and the spec 
requires field ids to be listed in key order, so for a spec-ordered field list, 
which is everything current Spark writes, `newIds` is already non-decreasing 
and the sort returns the identity. For example, 
`parse_json('{"c":3,"a":1,"b":2}')` has the dictionary `[c, a, b]` and so needs 
a rebuild; its field list holds ids `[1, 2, 0]`, which map to `newIds` `[0, 1, 
2]`. Only field lists in the UTF-16 order of older Spark versions, or from 
out-of-spec writers, need reordering. Once the expression runs before GROUP BY 
or DISTINCT, every multi-field object in every row that needs a rebuild would 
pay for the two arrays and the comparator pass.
   
   Checking, while reading the ids, whether any canonical id is smaller than 
the one before it, and allocating and sorting the permutation only then, writes 
the same bytes and raises the same errors: `Arrays.sort` on objects is stable, 
so equal ids keep source order either way, and `finishWritingObject` still 
reports `VARIANT_DUPLICATE_KEY` for them. The comment could then say that the 
sort reorders only field lists that are not in key order, such as the UTF-16 
order of older Spark versions.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59669#discussion_r4378858949).
   
   **Verification:**
   - **Inspection:** The canonical object rebuild allocates and sorts a field 
permutation only when the canonical ids of the source field list decrease 
somewhere, and writes the fields in source order otherwise.
   - **Compatibility:** Canonical bytes and errors are unchanged for objects 
whose fields are already in key order, for objects in the UTF-16 field order of 
older Spark versions, and for objects that name a key twice, which still fail 
with VARIANT_DUPLICATE_KEY.



##########
common/variant/src/test/scala/org/apache/spark/types/variant/VariantCanonicalizeSuite.scala:
##########
@@ -0,0 +1,767 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.types.variant
+
+import java.nio.charset.StandardCharsets
+
+import scala.util.Random
+
+import org.scalatest.funsuite.AnyFunSuite // scalastyle:ignore funsuite
+
+import org.apache.spark.SparkRuntimeException
+import org.apache.spark.types.variant.VariantUtil._
+
+class VariantCanonicalizeSuite extends AnyFunSuite { // scalastyle:ignore 
funsuite
+  private val emptyMetadata = Array[Byte](VERSION, 0, 0)
+  private val nullValue = Array(primitiveHeader(NULL))
+  private val trueValue = Array(primitiveHeader(TRUE))
+  private val falseValue = Array(primitiveHeader(FALSE))
+
+  private def bytes(values: Int*): Array[Byte] = values.map(_.toByte).toArray
+
+  private def utf8(value: String): Array[Byte] = 
value.getBytes(StandardCharsets.UTF_8)
+
+  private def littleEndian(value: BigInt, width: Int): Array[Byte] =
+    Array.tabulate(width)(index => ((value >> (8 * index)) & 0xff).toByte)
+
+  private def concatenate(parts: Seq[Array[Byte]]): Array[Byte] =
+    parts.iterator.flatMap(_.iterator).toArray
+
+  private def integer(value: Long, typeInfo: Int = INT1, width: Int = 1): 
Array[Byte] =
+    Array(primitiveHeader(typeInfo)) ++ littleEndian(BigInt(value), width)
+
+  private def decimal(
+      unscaled: String,
+      scale: Int,
+      typeInfo: Int,
+      width: Int): Array[Byte] = {
+    Array(primitiveHeader(typeInfo), scale.toByte) ++ 
littleEndian(BigInt(unscaled), width)
+  }
+
+  private def floating(rawBits: Long, typeInfo: Int, width: Int): Array[Byte] =
+    Array(primitiveHeader(typeInfo)) ++ littleEndian(BigInt(rawBits), width)
+
+  private def string(value: Array[Byte], longEncoding: Boolean = false): 
Array[Byte] = {
+    if (longEncoding) {
+      Array(primitiveHeader(LONG_STR)) ++ littleEndian(BigInt(value.length), 
4) ++ value
+    } else {
+      Array(shortStrHeader(value.length)) ++ value
+    }
+  }
+
+  // Metadata binary: header, key count, `keys.size + 1` offsets, then the key 
bytes.
+  private def metadata(
+      keys: Seq[Array[Byte]],
+      offsetSize: Int = 1,
+      flags: Int = 0): Array[Byte] = {
+    val offsets = keys.scanLeft(0)((offset, key) => offset + key.length)
+    bytes(metadataHeader(offsetSize) | flags) ++ 
littleEndian(BigInt(keys.size), offsetSize) ++
+      concatenate(offsets.map(offset => littleEndian(BigInt(offset), 
offsetSize))) ++
+      concatenate(keys)
+  }
+
+  private def dictionary(names: String*): Array[Byte] = 
metadata(names.map(utf8))
+
+  // Array value: header, element count, `elements.size + 1` offsets, then the 
elements.
+  private def array(
+      elements: Seq[Array[Byte]],
+      offsetSize: Int = 1,
+      largeSize: Boolean = false): Array[Byte] = {
+    val offsets = elements.scanLeft(0)((offset, element) => offset + 
element.length)
+    Array(arrayHeader(largeSize, offsetSize)) ++
+      littleEndian(BigInt(elements.size), if (largeSize) 4 else 1) ++
+      concatenate(offsets.map(offset => littleEndian(BigInt(offset), 
offsetSize))) ++
+      concatenate(elements)
+  }
+
+  // Object value from (key id, value bytes) pairs in field order. 
`physicalOrder` stores the values
+  // in another order than the field list, which the spec allows.
+  private def obj(
+      fields: Seq[(Int, Array[Byte])],
+      idSize: Int = 1,
+      offsetSize: Int = 1,
+      largeSize: Boolean = false,
+      physicalOrder: Seq[Int] = Seq.empty): Array[Byte] = {
+    val order = if (physicalOrder.isEmpty) fields.indices else physicalOrder
+    val offsets = new Array[Int](fields.size)
+    var dataSize = 0
+    order.foreach { fieldIndex =>
+      offsets(fieldIndex) = dataSize
+      dataSize += fields(fieldIndex)._2.length
+    }
+    Array(objectHeader(largeSize, idSize, offsetSize)) ++
+      littleEndian(BigInt(fields.size), if (largeSize) 4 else 1) ++
+      concatenate(fields.map { case (keyId, _) => littleEndian(BigInt(keyId), 
idSize) }) ++
+      concatenate((offsets.toSeq :+ dataSize).map(offset =>
+        littleEndian(BigInt(offset), offsetSize))) ++
+      concatenate(order.map(fieldIndex => fields(fieldIndex)._2))
+  }
+
+  private def assertBytes(actual: Array[Byte], expected: Array[Byte], label: 
String): Unit = {
+    assert(actual.sameElements(expected),
+      s"$label: expected ${expected.length} bytes, got ${actual.length} bytes; 
" +
+        s"expected prefix ${expected.take(32).mkString(",")}, " +
+        s"actual prefix ${actual.take(32).mkString(",")}")
+  }
+
+  // Canonicalize `input` and compare with the expected bytes. The input is 
canonical exactly when
+  // it already has those bytes. The input bytes must not change.
+  private def check(
+      input: Variant,
+      expectedValue: Array[Byte],
+      expectedMetadata: Array[Byte] = emptyMetadata): Variant = {
+    val canonicalInput = input.pos == 0 && 
input.value.sameElements(expectedValue) &&
+      input.metadata.sameElements(expectedMetadata)
+    val originalValue = input.value.clone()
+    val originalMetadata = input.metadata.clone()
+    assert(VariantBuilder.isCanonical(input) == canonicalInput)
+    val actual = VariantBuilder.canonicalize(input)
+    assert((actual eq input) == canonicalInput)
+    assert(actual.pos == 0)
+    assertBytes(actual.value, expectedValue, "canonical value")
+    assertBytes(actual.metadata, expectedMetadata, "canonical metadata")
+    assert(VariantBuilder.isCanonical(actual))
+    assert(VariantBuilder.canonicalize(actual) eq actual)
+    Seq(input, actual).foreach { source =>
+      val rebuilt = VariantBuilder.doCanonicalize(source)
+      assertBytes(rebuilt.value, expectedValue, "unconditional rebuild value")
+      assertBytes(rebuilt.metadata, expectedMetadata, "unconditional rebuild 
metadata")
+    }
+    assertBytes(input.value, originalValue, "unchanged input value")
+    assertBytes(input.metadata, originalMetadata, "unchanged input metadata")
+    actual
+  }
+
+  private def checkKeyless(inputValue: Array[Byte], expectedValue: 
Array[Byte]): Unit =
+    check(new Variant(inputValue, emptyMetadata), expectedValue)
+
+  private def checkError(condition: String)(body: => Any): Unit = {
+    assert(intercept[SparkRuntimeException](body).getCondition == condition)
+  }
+
+  // Pins the exact bytes of a few canonical values independently of the 
helpers above.
+  test("canonical encoding has pinned value and metadata bytes") {
+    // INT8 1 becomes INT1 1.
+    checkKeyless(bytes(24, 1, 0, 0, 0, 0, 0, 0, 0), bytes(12, 1))
+    // Long string "x" becomes short string "x".
+    checkKeyless(bytes(64, 1, 0, 0, 0, 120), bytes(5, 120))
+    // {"b":2,"a":1}: value is header, 2 fields, ids [0, 1], offsets [0, 2, 
4], INT1 1, INT1 2;
+    // metadata is header, 2 keys, offsets [0, 1, 2], "ab".
+    check(VariantBuilder.parseJson("{\"b\":2,\"a\":1}", false),
+      bytes(2, 2, 0, 1, 0, 2, 4, 12, 1, 12, 2), bytes(1, 2, 0, 1, 2, 97, 98))
+    // Empty object and empty array.
+    checkKeyless(bytes(2, 0, 0), bytes(2, 0, 0))
+    checkKeyless(bytes(3, 0, 0), bytes(3, 0, 0))
+  }
+
+  test("metadata helpers read every offset width and reject an overflowing 
dictionary size") {
+    Seq((1, 0x01), (2, 0x41), (3, 0x81), (4, 0xc1)).foreach {
+      case (width, header) =>
+        // Keys "a" and "b" with a `width`-byte key count and offsets.
+        val input = bytes(header) ++ littleEndian(BigInt(2), width) ++
+          concatenate(Seq(0, 1, 2).map(offset => littleEndian(BigInt(offset), 
width))) ++
+          bytes(97, 98)
+        assert(metadataHeader(width) == header.toByte)
+        assert(getMetadataOffsetSize(input) == width)
+        assert(getMetadataNumKeys(input, width) == 2)
+        assert(getMetadataStringStart(input, 2, width) == 1 + 4 * width)
+        assert(getMetadataKey(input, 0) == "a")
+        assert(getMetadataKey(input, 1) == "b")
+    }
+    // A key count near Int.MaxValue used to overflow the string start and 
return a wrong key.
+    val forged = Array(metadataHeader(4)) ++ littleEndian(BigInt(Int.MaxValue 
- 1), 4) ++
+      littleEndian(BigInt(0), 4) ++ littleEndian(BigInt(1), 4) ++ utf8("a")
+    checkError("MALFORMED_VARIANT") { getMetadataKey(forged, 0) }
+  }
+
+  test("isCanonical rejects decreasing or out-of-bounds dictionary offsets") {
+    val value = obj(Seq(0 -> integer(1), 1 -> integer(2), 2 -> integer(3)))
+    assert(VariantBuilder.isCanonical(new Variant(value, dictionary("a", "b", 
"c"))))
+
+    // Offsets [0, 2, 1, 3] decrease and [0, 4, 2, 3] exceed the last offset. 
[0, 4, 4, 3] would
+    // reach the key comparison with an out-of-range slice if the bound were 
not checked.
+    val decreasingOffsets = bytes(VERSION, 3, 0, 2, 1, 3) ++ utf8("abc")
+    val outOfBoundsOffset = bytes(VERSION, 3, 0, 4, 2, 3) ++ utf8("abc")
+    val outOfBoundsBeforeCompare = bytes(VERSION, 3, 0, 4, 4, 3) ++ utf8("abc")
+    Seq(decreasingOffsets, outOfBoundsOffset, 
outOfBoundsBeforeCompare).foreach { invalidMetadata =>
+      val variant = new Variant(value, invalidMetadata)
+      assert(!VariantBuilder.isCanonical(variant))
+      checkError("MALFORMED_VARIANT") { VariantBuilder.canonicalize(variant) }
+    }
+  }
+
+  test("dictionary permutation and object value order canonicalize 
independently") {
+    // The spec sorts field ids by key name, not by id, allows the values in 
any order and allows an
+    // unsorted dictionary, so these are four legal encodings of {"a":1,"b":2}.
+    val expectedValue = obj(Seq(0 -> integer(1), 1 -> integer(2)))
+    Seq(Seq("a", "b"), Seq("b", "a")).foreach { keys =>
+      Seq(Seq(0, 1), Seq(1, 0)).foreach { order =>
+        val value = obj(Seq(keys.indexOf("a") -> integer(1), keys.indexOf("b") 
-> integer(2)),
+          physicalOrder = order)
+        check(new Variant(value, dictionary(keys: _*)), expectedValue, 
dictionary("a", "b"))
+      }
+    }
+  }
+
+  test("unused dictionary entries are removed and repeated names share an ID") 
{
+    // Keys "b", "unused", "a", "a": the objects use ids 2, 3 and 0, so 
"unused" is dropped and
+    // both "a" entries become one key.
+    val sourceMetadata = dictionary("b", "unused", "a", "a")
+    val sourceValue = array(Seq(
+      obj(Seq(2 -> integer(1))), obj(Seq(3 -> integer(2))), obj(Seq(0 -> 
integer(3)))))
+    val expectedValue = array(Seq(
+      obj(Seq(0 -> integer(1))), obj(Seq(0 -> integer(2))), obj(Seq(1 -> 
integer(3)))))
+    check(new Variant(sourceValue, sourceMetadata), expectedValue, 
dictionary("a", "b"))
+    // A scalar root keeps no keys at all.
+    check(new Variant(integer(1), sourceMetadata), integer(1))
+    // The empty key is a key like any other.
+    val emptyKey = obj(Seq(0 -> nullValue, 1 -> integer(1)))
+    check(new Variant(emptyKey, dictionary("", "a")), emptyKey, dictionary("", 
"a"))
+  }
+
+  // scalastyle:off nonascii
+  test("keys are sorted by unsigned UTF-8 bytes rather than UTF-16 string 
order") {
+    // U+E000 (EE 80 80) sorts before U+10000 (F0 90 80 80) in UTF-8 bytes but 
after it in UTF-16,
+    // the order of String.compareTo that Spark used before SPARK-58949. The 
first input lists the
+    // fields in that old order.
+    val bmpKey = utf8("\ue000")
+    val supplementaryKey = utf8("\ud800\udc00")
+    val expectedMetadata = metadata(Seq(bmpKey, supplementaryKey))
+    val expectedValue = obj(Seq(0 -> integer(10), 1 -> integer(20)))
+    Seq(Seq(0 -> integer(20), 1 -> integer(10)),
+      Seq(1 -> integer(10), 0 -> integer(20))).foreach { fields =>
+      check(new Variant(obj(fields), metadata(Seq(supplementaryKey, bmpKey))),

Review Comment:
   **Nit (P3):** Both legacy-order cases here use the dictionary `[U+10000, 
U+E000]`, which is not sorted by UTF-8 bytes, so `isCanonical` rejects them at 
the dictionary order check before it reads any field id. The field-id order 
check in `isValueCanonical` (`keyId <= previousId`) is the only rule that 
rejects a UTF-16-ordered object whose dictionary is already sorted, and no 
fixture reaches it: every other input with decreasing ids also has an unsorted 
dictionary, and the fuzzers list fields in UTF-8 order. Reading the tests, 
narrowing that check to `keyId == previousId` would keep every test passing.
   
   Older Spark versions write exactly that shape: `FieldEntry.compareTo` used 
`String.compareTo` before SPARK-58949, as v4.3.0 still does, so parsing 
`[{"\ue000":0},{"\ud800\udc00":2,"\ue000":1}]` there gives the sorted 
dictionary `[U+E000, U+10000]` and a second object with ids `[1, 0]`. Such 
objects break the spec's UTF-8 field order, but Spark still reads them, and 
this test is here so that canonicalization gives them the same bytes as the 
same value written today. With the narrowed check they would be returned 
unchanged, so a later GROUP BY or DISTINCT would split equal values written by 
older and current Spark.
   
   Adding `obj(Seq(1 -> integer(20), 0 -> integer(10)))` over 
`metadata(Seq(bmpKey, supplementaryKey))` to the cases, expected to 
canonicalize to `expectedValue` over `expectedMetadata`, would pin the check.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59669#discussion_r4518416053).
   
   **Verification:**
   - **Regression:** An object over the dictionary [U+E000, U+10000] whose 
field list names U+10000 before U+E000, as released Spark writes it, is 
reported non-canonical and canonicalizes to the object that lists U+E000 first 
with its values in that order, and the test fails if isCanonical rejects only 
repeated field ids rather than every id that does not increase.



##########
common/variant/src/main/java/org/apache/spark/types/variant/VariantBuilder.java:
##########
@@ -205,6 +205,313 @@ public static Variant pickAtPaths(Variant v, PickNode 
tree) {
     return builder.result();
   }
 
+  /**
+   * Return {@code v} in canonical form, or {@code v} itself if it is already 
canonical.
+   * <p>
+   * The variant binary encoding allows the same logical value to be encoded 
in several ways
+   * (dictionary order, unused keys, integer and offset widths, decimal scale, 
...). Canonical form
+   * picks one encoding per value, so that values which are equal under the 
variant equality rules
+   * have identical {@code value} and {@code metadata} bytes and can be 
compared, hashed and
+   * grouped bytewise. It is a Spark-internal normalization, not part of the 
variant spec, and
+   * nothing outside Spark is expected to produce or require it. Only valid 
variants are supported;
+   * malformed bytes fail with {@code MALFORMED_VARIANT} where they are 
detected.

Review Comment:
   **Nit (P3):** This sentence and the note on unknown types at the end are the 
only places the Javadoc states a failure, and the Javadoc is now the spec of 
canonicalization. Two other failures are reachable, and the PR's own tests pin 
both:
   
   - An object that names the same key twice, which the Variant spec calls an 
error whether or not the two fields use different dictionary ids, does not fail 
with `MALFORMED_VARIANT`. `isCanonical` rejects it, the rebuild maps both 
fields to one canonical id, and the duplicate check in `finishWritingObject` 
throws `VARIANT_DUPLICATE_KEY` (the `canonicalize_variant duplicate keys` test).
   - The rebuild throws `VariantSizeLimitException` when its output would 
exceed `SIZE_LIMIT`, from the visited-value count in `collectAllObjectKeys` or 
from `checkCapacity` (the `aliased nested values fail with the size limit` 
test). A valid input can reach it as well: `finishWritingObject` sizes field 
ids by the largest canonical id, so when re-sorting moves a key that many 
objects use above id 255, each of those objects needs 2-byte ids, so a value 
near the limit can grow past it.
   
   `VariantExpressionEvalUtils.canonicalizeVariant` catches the size exception 
and the `CanonicalizeVariant` scaladoc mentions it, but a caller reading this 
Javadoc, including the later change that runs the expression before GROUP BY 
and DISTINCT, would expect neither failure. Naming `VARIANT_DUPLICATE_KEY` for 
repeated field names and adding `@throws VariantSizeLimitException`, as 
`parseJson` in this class does, would complete the contract; the size failure 
comes from valid input whose re-sorted keys widen field ids, or from malformed 
input whose container offsets point several entries at one child.
   
   **Verification:**
   - **Inspection:** The canonicalize Javadoc's failure statement matches what 
the method raises for each input class the tests pin: MALFORMED_VARIANT for 
detected malformed bytes, VARIANT_DUPLICATE_KEY for an object that names a key 
twice, UNKNOWN_PRIMITIVE_TYPE_IN_VARIANT for an unknown type ID, and 
VariantSizeLimitException when the rebuilt value or metadata would exceed the 
size limit.



##########
common/variant/src/test/scala/org/apache/spark/types/variant/VariantCanonicalizeSuite.scala:
##########
@@ -0,0 +1,767 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.types.variant
+
+import java.nio.charset.StandardCharsets
+
+import scala.util.Random
+
+import org.scalatest.funsuite.AnyFunSuite // scalastyle:ignore funsuite
+
+import org.apache.spark.SparkRuntimeException
+import org.apache.spark.types.variant.VariantUtil._
+
+class VariantCanonicalizeSuite extends AnyFunSuite { // scalastyle:ignore 
funsuite
+  private val emptyMetadata = Array[Byte](VERSION, 0, 0)
+  private val nullValue = Array(primitiveHeader(NULL))
+  private val trueValue = Array(primitiveHeader(TRUE))
+  private val falseValue = Array(primitiveHeader(FALSE))
+
+  private def bytes(values: Int*): Array[Byte] = values.map(_.toByte).toArray
+
+  private def utf8(value: String): Array[Byte] = 
value.getBytes(StandardCharsets.UTF_8)
+
+  private def littleEndian(value: BigInt, width: Int): Array[Byte] =
+    Array.tabulate(width)(index => ((value >> (8 * index)) & 0xff).toByte)
+
+  private def concatenate(parts: Seq[Array[Byte]]): Array[Byte] =
+    parts.iterator.flatMap(_.iterator).toArray
+
+  private def integer(value: Long, typeInfo: Int = INT1, width: Int = 1): 
Array[Byte] =
+    Array(primitiveHeader(typeInfo)) ++ littleEndian(BigInt(value), width)
+
+  private def decimal(
+      unscaled: String,
+      scale: Int,
+      typeInfo: Int,
+      width: Int): Array[Byte] = {
+    Array(primitiveHeader(typeInfo), scale.toByte) ++ 
littleEndian(BigInt(unscaled), width)
+  }
+
+  private def floating(rawBits: Long, typeInfo: Int, width: Int): Array[Byte] =
+    Array(primitiveHeader(typeInfo)) ++ littleEndian(BigInt(rawBits), width)
+
+  private def string(value: Array[Byte], longEncoding: Boolean = false): 
Array[Byte] = {
+    if (longEncoding) {
+      Array(primitiveHeader(LONG_STR)) ++ littleEndian(BigInt(value.length), 
4) ++ value
+    } else {
+      Array(shortStrHeader(value.length)) ++ value
+    }
+  }
+
+  // Metadata binary: header, key count, `keys.size + 1` offsets, then the key 
bytes.
+  private def metadata(
+      keys: Seq[Array[Byte]],
+      offsetSize: Int = 1,
+      flags: Int = 0): Array[Byte] = {
+    val offsets = keys.scanLeft(0)((offset, key) => offset + key.length)
+    bytes(metadataHeader(offsetSize) | flags) ++ 
littleEndian(BigInt(keys.size), offsetSize) ++
+      concatenate(offsets.map(offset => littleEndian(BigInt(offset), 
offsetSize))) ++
+      concatenate(keys)
+  }
+
+  private def dictionary(names: String*): Array[Byte] = 
metadata(names.map(utf8))
+
+  // Array value: header, element count, `elements.size + 1` offsets, then the 
elements.
+  private def array(
+      elements: Seq[Array[Byte]],
+      offsetSize: Int = 1,
+      largeSize: Boolean = false): Array[Byte] = {
+    val offsets = elements.scanLeft(0)((offset, element) => offset + 
element.length)
+    Array(arrayHeader(largeSize, offsetSize)) ++
+      littleEndian(BigInt(elements.size), if (largeSize) 4 else 1) ++
+      concatenate(offsets.map(offset => littleEndian(BigInt(offset), 
offsetSize))) ++
+      concatenate(elements)
+  }
+
+  // Object value from (key id, value bytes) pairs in field order. 
`physicalOrder` stores the values
+  // in another order than the field list, which the spec allows.
+  private def obj(
+      fields: Seq[(Int, Array[Byte])],
+      idSize: Int = 1,
+      offsetSize: Int = 1,
+      largeSize: Boolean = false,
+      physicalOrder: Seq[Int] = Seq.empty): Array[Byte] = {
+    val order = if (physicalOrder.isEmpty) fields.indices else physicalOrder
+    val offsets = new Array[Int](fields.size)
+    var dataSize = 0
+    order.foreach { fieldIndex =>
+      offsets(fieldIndex) = dataSize
+      dataSize += fields(fieldIndex)._2.length
+    }
+    Array(objectHeader(largeSize, idSize, offsetSize)) ++
+      littleEndian(BigInt(fields.size), if (largeSize) 4 else 1) ++
+      concatenate(fields.map { case (keyId, _) => littleEndian(BigInt(keyId), 
idSize) }) ++
+      concatenate((offsets.toSeq :+ dataSize).map(offset =>
+        littleEndian(BigInt(offset), offsetSize))) ++
+      concatenate(order.map(fieldIndex => fields(fieldIndex)._2))
+  }
+
+  private def assertBytes(actual: Array[Byte], expected: Array[Byte], label: 
String): Unit = {
+    assert(actual.sameElements(expected),
+      s"$label: expected ${expected.length} bytes, got ${actual.length} bytes; 
" +
+        s"expected prefix ${expected.take(32).mkString(",")}, " +
+        s"actual prefix ${actual.take(32).mkString(",")}")
+  }
+
+  // Canonicalize `input` and compare with the expected bytes. The input is 
canonical exactly when
+  // it already has those bytes. The input bytes must not change.
+  private def check(
+      input: Variant,
+      expectedValue: Array[Byte],
+      expectedMetadata: Array[Byte] = emptyMetadata): Variant = {
+    val canonicalInput = input.pos == 0 && 
input.value.sameElements(expectedValue) &&
+      input.metadata.sameElements(expectedMetadata)
+    val originalValue = input.value.clone()
+    val originalMetadata = input.metadata.clone()
+    assert(VariantBuilder.isCanonical(input) == canonicalInput)
+    val actual = VariantBuilder.canonicalize(input)
+    assert((actual eq input) == canonicalInput)
+    assert(actual.pos == 0)
+    assertBytes(actual.value, expectedValue, "canonical value")
+    assertBytes(actual.metadata, expectedMetadata, "canonical metadata")
+    assert(VariantBuilder.isCanonical(actual))
+    assert(VariantBuilder.canonicalize(actual) eq actual)
+    Seq(input, actual).foreach { source =>
+      val rebuilt = VariantBuilder.doCanonicalize(source)
+      assertBytes(rebuilt.value, expectedValue, "unconditional rebuild value")
+      assertBytes(rebuilt.metadata, expectedMetadata, "unconditional rebuild 
metadata")
+    }
+    assertBytes(input.value, originalValue, "unchanged input value")
+    assertBytes(input.metadata, originalMetadata, "unchanged input metadata")
+    actual
+  }
+
+  private def checkKeyless(inputValue: Array[Byte], expectedValue: 
Array[Byte]): Unit =
+    check(new Variant(inputValue, emptyMetadata), expectedValue)
+
+  private def checkError(condition: String)(body: => Any): Unit = {
+    assert(intercept[SparkRuntimeException](body).getCondition == condition)
+  }
+
+  // Pins the exact bytes of a few canonical values independently of the 
helpers above.
+  test("canonical encoding has pinned value and metadata bytes") {
+    // INT8 1 becomes INT1 1.
+    checkKeyless(bytes(24, 1, 0, 0, 0, 0, 0, 0, 0), bytes(12, 1))
+    // Long string "x" becomes short string "x".
+    checkKeyless(bytes(64, 1, 0, 0, 0, 120), bytes(5, 120))
+    // {"b":2,"a":1}: value is header, 2 fields, ids [0, 1], offsets [0, 2, 
4], INT1 1, INT1 2;
+    // metadata is header, 2 keys, offsets [0, 1, 2], "ab".
+    check(VariantBuilder.parseJson("{\"b\":2,\"a\":1}", false),
+      bytes(2, 2, 0, 1, 0, 2, 4, 12, 1, 12, 2), bytes(1, 2, 0, 1, 2, 97, 98))
+    // Empty object and empty array.
+    checkKeyless(bytes(2, 0, 0), bytes(2, 0, 0))
+    checkKeyless(bytes(3, 0, 0), bytes(3, 0, 0))
+  }
+
+  test("metadata helpers read every offset width and reject an overflowing 
dictionary size") {
+    Seq((1, 0x01), (2, 0x41), (3, 0x81), (4, 0xc1)).foreach {
+      case (width, header) =>
+        // Keys "a" and "b" with a `width`-byte key count and offsets.
+        val input = bytes(header) ++ littleEndian(BigInt(2), width) ++
+          concatenate(Seq(0, 1, 2).map(offset => littleEndian(BigInt(offset), 
width))) ++
+          bytes(97, 98)
+        assert(metadataHeader(width) == header.toByte)
+        assert(getMetadataOffsetSize(input) == width)
+        assert(getMetadataNumKeys(input, width) == 2)
+        assert(getMetadataStringStart(input, 2, width) == 1 + 4 * width)
+        assert(getMetadataKey(input, 0) == "a")
+        assert(getMetadataKey(input, 1) == "b")
+    }
+    // A key count near Int.MaxValue used to overflow the string start and 
return a wrong key.
+    val forged = Array(metadataHeader(4)) ++ littleEndian(BigInt(Int.MaxValue 
- 1), 4) ++
+      littleEndian(BigInt(0), 4) ++ littleEndian(BigInt(1), 4) ++ utf8("a")
+    checkError("MALFORMED_VARIANT") { getMetadataKey(forged, 0) }
+  }
+
+  test("isCanonical rejects decreasing or out-of-bounds dictionary offsets") {
+    val value = obj(Seq(0 -> integer(1), 1 -> integer(2), 2 -> integer(3)))
+    assert(VariantBuilder.isCanonical(new Variant(value, dictionary("a", "b", 
"c"))))
+
+    // Offsets [0, 2, 1, 3] decrease and [0, 4, 2, 3] exceed the last offset. 
[0, 4, 4, 3] would
+    // reach the key comparison with an out-of-range slice if the bound were 
not checked.
+    val decreasingOffsets = bytes(VERSION, 3, 0, 2, 1, 3) ++ utf8("abc")
+    val outOfBoundsOffset = bytes(VERSION, 3, 0, 4, 2, 3) ++ utf8("abc")
+    val outOfBoundsBeforeCompare = bytes(VERSION, 3, 0, 4, 4, 3) ++ utf8("abc")
+    Seq(decreasingOffsets, outOfBoundsOffset, 
outOfBoundsBeforeCompare).foreach { invalidMetadata =>
+      val variant = new Variant(value, invalidMetadata)
+      assert(!VariantBuilder.isCanonical(variant))
+      checkError("MALFORMED_VARIANT") { VariantBuilder.canonicalize(variant) }
+    }
+  }
+
+  test("dictionary permutation and object value order canonicalize 
independently") {
+    // The spec sorts field ids by key name, not by id, allows the values in 
any order and allows an
+    // unsorted dictionary, so these are four legal encodings of {"a":1,"b":2}.
+    val expectedValue = obj(Seq(0 -> integer(1), 1 -> integer(2)))
+    Seq(Seq("a", "b"), Seq("b", "a")).foreach { keys =>
+      Seq(Seq(0, 1), Seq(1, 0)).foreach { order =>
+        val value = obj(Seq(keys.indexOf("a") -> integer(1), keys.indexOf("b") 
-> integer(2)),
+          physicalOrder = order)
+        check(new Variant(value, dictionary(keys: _*)), expectedValue, 
dictionary("a", "b"))
+      }
+    }
+  }
+
+  test("unused dictionary entries are removed and repeated names share an ID") 
{
+    // Keys "b", "unused", "a", "a": the objects use ids 2, 3 and 0, so 
"unused" is dropped and
+    // both "a" entries become one key.
+    val sourceMetadata = dictionary("b", "unused", "a", "a")

Review Comment:
   **Nit (P3):** With `sorted_strings` clear, the Variant spec lets readers 
assume nothing about key order or uniqueness, so a dictionary may repeat a key, 
and canonicalization has to merge the copies. `isCanonical` rejects a 
dictionary whose only flaw is an adjacent repeat solely through the `>= 0` 
result of its key comparison, and no test reaches that equal case. This 
dictionary is rejected earlier, at `"unused" > "a"`; `randomizeBinaryEncoding` 
builds its dictionaries with `.distinct`; and the latest commit removed the 
only legal input that reached it, `dictionary("a", "a")` under two sibling 
objects that use ids 0 and 1, together with the illegal repeated-field-id case. 
Reading the tests, relaxing the comparison to `> 0` would keep every test 
passing, and that input would then be returned unchanged instead of becoming 
the same array over the dictionary `["a"]`, so equal values would keep 
different bytes and a later GROUP BY or DISTINCT would split them.
   
   Restoring that case, for example here as `array(Seq(obj(Seq(0 -> 
integer(1))), obj(Seq(1 -> integer(2)))))` over `dictionary("a", "a")`, 
expected to canonicalize to `array(Seq(obj(Seq(0 -> integer(1))), obj(Seq(0 -> 
integer(2)))))` over `dictionary("a")`, would pin the check. Unlike a repeated 
field id, it is a legal input.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59669#discussion_r4518397523).
   
   **Verification:**
   - **Regression:** A variant whose dictionary is ["a", "a"] with 
sorted_strings clear and whose two sibling objects use ids 0 and 1 is reported 
non-canonical and canonicalizes to the array of two objects using id 0 over the 
dictionary ["a"], and the test fails if isCanonical accepts adjacent equal 
dictionary keys.



-- 
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]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to