SavicStefan commented on code in PR #59669:
URL: https://github.com/apache/spark/pull/59669#discussion_r4574814660


##########
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:
   add the tests that make sure that a canonical dictionary must be unique as 
well as sorted



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