SavicStefan commented on code in PR #59669: URL: https://github.com/apache/spark/pull/59669#discussion_r4482509886
########## common/variant/src/test/scala/org/apache/spark/types/variant/VariantCanonicalizeSuite.scala: ########## @@ -0,0 +1,860 @@ +/* + * 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 + } + } + + 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)) + + 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) + } + + 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(",")}") + } + + // The input is canonical exactly when it already has the expected bytes. + 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) + } + + test("canonical encoding has pinned value and metadata bytes") { + checkKeyless(bytes(24, 1, 0, 0, 0, 0, 0, 0, 0), bytes(12, 1)) + checkKeyless(bytes(64, 1, 0, 0, 0, 120), bytes(5, 120)) + 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)) + checkKeyless(bytes(2, 0, 0), bytes(2, 0, 0)) + checkKeyless(bytes(3, 0, 0), bytes(3, 0, 0)) + } + + test("metadata helpers encode and decode every offset-width header") { + Seq((1, 0x01), (2, 0x41), (3, 0x81), (4, 0xc1)).foreach { + case (width, header) => + 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") + } + } + + test("isCanonical rejects a metadata last offset past the available string bytes") { + val value = obj(Seq(0 -> integer(1))) + val validMetadata = dictionary("ab") + assert(VariantBuilder.isCanonical(new Variant(value, validMetadata))) + + Seq(1, 2).foreach { missingBytes => + val truncatedMetadata = validMetadata.dropRight(missingBytes) + assert(!VariantBuilder.isCanonical(new Variant(value, truncatedMetadata))) + } + } + + 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")))) + + val decreasingOffsets = bytes(VERSION, 3, 0, 2, 1, 3) ++ utf8("abc") + val outOfBoundsOffset = bytes(VERSION, 3, 0, 4, 2, 3) ++ utf8("abc") + Seq(decreasingOffsets, outOfBoundsOffset).foreach { invalidMetadata => + assert(!VariantBuilder.isCanonical(new Variant(value, invalidMetadata))) + } + } + + test("getMetadataKey rejects a dictionary size whose string start overflows an int") { + 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("dictionary permutation and object payload order canonicalize independently") { + 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") { + 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")) + check(new Variant(integer(1), sourceMetadata), integer(1)) + check(new Variant(integer(1), metadata(Seq(bytes(0xff)))), integer(1)) + check(new Variant(obj(Seq(0 -> integer(1))), bytes(1, 1, 1, 2, 120, 97)), + obj(Seq(0 -> integer(1))), dictionary("a")) + val emptyKey = obj(Seq(0 -> nullValue, 1 -> integer(1))) + check(new Variant(emptyKey, dictionary("", "a")), emptyKey, dictionary("", "a")) + } + + test("duplicate dictionary entries and repeated field IDs are never canonical") { + check(new Variant(array(Seq(obj(Seq(0 -> integer(1))), obj(Seq(1 -> integer(2))))), + dictionary("a", "a")), + array(Seq(obj(Seq(0 -> integer(1))), obj(Seq(0 -> integer(2))))), dictionary("a")) + val repeatedId = new Variant(obj(Seq(0 -> integer(1), 0 -> integer(2))), dictionary("a")) + assert(!VariantBuilder.isCanonical(repeatedId)) + checkError("VARIANT_DUPLICATE_KEY") { VariantBuilder.canonicalize(repeatedId) } + } + + // scalastyle:off nonascii + test("dictionary and fields use unsigned UTF-8 rather than UTF-16 ordering") { + 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))), + expectedValue, expectedMetadata) + } + } + + test("valid multi-byte UTF-8 keys are kept and sorted by their bytes") { + check(new Variant(obj(Seq(2 -> integer(1), 1 -> integer(2), 0 -> integer(3))), + dictionary("\u4f60", "caf\u00e9", "cafe")), + obj(Seq(0 -> integer(1), 1 -> integer(2), 2 -> integer(3))), + dictionary("cafe", "caf\u00e9", "\u4f60")) + } + // scalastyle:on nonascii + + test("all independent metadata ID offset and count widths converge") { + val fields = Seq(0 -> trueValue, 1 -> integer(258, INT2, 2), 2 -> nullValue) + val elements = fields.map(_._2) + val keys = Seq("a", "b", "c").map(utf8) + for { + metadataWidth <- 1 to 4 + idWidth <- 1 to 4 + offsetWidth <- 1 to 4 + largeSize <- Seq(false, true) + } { + withClue(s"metadata=$metadataWidth id=$idWidth offset=$offsetWidth large=$largeSize: ") { + check(new Variant(obj(fields, idWidth, offsetWidth, largeSize), + metadata(keys, metadataWidth)), obj(fields), metadata(keys)) + } + } + for { + metadataWidth <- 1 to 4 + offsetWidth <- 1 to 4 + largeSize <- Seq(false, true) + } { + val keylessMetadata = metadata(Seq.empty, metadataWidth) + check(new Variant(array(elements, offsetWidth, largeSize), keylessMetadata), + array(elements)) + check(new Variant(array(Seq.empty, offsetWidth, largeSize), keylessMetadata), + array(Seq.empty)) + check(new Variant(obj(Seq.empty, 4, offsetWidth, largeSize), keylessMetadata), + obj(Seq.empty)) + } + } + + test("metadata flags and trailing bytes are not part of canonical output") { + Seq(1 << 4, 1 << 5, (1 << 4) | (1 << 5)).foreach { flags => + check(new Variant(integer(1), metadata(Seq.empty, flags = flags)), integer(1)) + } + checkKeyless(integer(1) ++ bytes(0, 0), integer(1)) + check(new Variant(integer(1), emptyMetadata ++ bytes(0, 0)), integer(1)) + } + + test("reserved container header bits are cleared during normalization") { + val objectValue = obj(Seq(0 -> integer(1))) + val objectWithReservedBit = objectValue.clone() + objectWithReservedBit(0) = (objectWithReservedBit(0) | 0x80).toByte + check(new Variant(objectWithReservedBit, dictionary("a")), objectValue, dictionary("a")) + val arrayValue = array(Seq(integer(1))) + Seq(0x20, 0x40, 0x80, 0xe0).foreach { reservedBits => + val arrayWithReservedBits = arrayValue.clone() + arrayWithReservedBits(0) = (arrayWithReservedBits(0) | reservedBits).toByte + checkKeyless(arrayWithReservedBits, arrayValue) + } + } + + test("padding and shared payloads inside containers become contiguous") { + val paddedArray = Array(arrayHeader(false, 1)) ++ bytes(1, 0, 3) ++ integer(1) ++ bytes(0) + checkKeyless(paddedArray, array(Seq(integer(1)))) + val paddedObject = + Array(objectHeader(false, 1, 1)) ++ bytes(1, 0, 0, 3) ++ integer(1) ++ bytes(0) + check(new Variant(paddedObject, dictionary("a")), obj(Seq(0 -> integer(1))), dictionary("a")) + val shared = Array(objectHeader(false, 1, 1)) ++ bytes(2, 0, 1, 0, 0, 2) ++ integer(7) + check(new Variant(shared, dictionary("a", "b")), + obj(Seq(0 -> integer(7), 1 -> integer(7))), dictionary("a", "b")) + } + + test("container count and payload widths change at 255 and 256") { + Seq((255, false, 1, 1), (256, true, 1, 2), (257, true, 2, 2)).foreach { + case (count, largeSize, idWidth, offsetWidth) => + val keys = (0 until count).map(index => utf8(f"key$index%03d")) + val fields = (0 until count).map(index => index -> nullValue) + val expectedMetadata = metadata(keys, 2) + val expectedObject = obj(fields, idWidth, offsetWidth, largeSize) + check(new Variant(obj(fields, 4, 4, largeSize = true), metadata(keys, 4)), + expectedObject, expectedMetadata) + check(new Variant(expectedObject, expectedMetadata), expectedObject, expectedMetadata) + val elements = Seq.fill(count)(nullValue) + checkKeyless(array(elements, 4, largeSize = true), array(elements, offsetWidth, largeSize)) + } + } + + test("object ID width follows the largest referenced global ID") { + val keys = (0 to 256).map(index => utf8(f"key$index%03d")) + val sourceElements = keys.indices.map(index => obj(Seq(index -> nullValue), 4, 4, true)) + val expectedElements = keys.indices.map { index => + obj(Seq(index -> nullValue), idSize = if (index <= U8_MAX) 1 else 2) + } + val expectedValue = array(expectedElements, 2, largeSize = true) + check(new Variant(array(sourceElements, 4, largeSize = true), metadata(keys, 4)), + expectedValue, metadata(keys, 2)) + check(new Variant(obj(Seq(256 -> integer(1)), 2), metadata(keys, 2)), + obj(Seq(0 -> integer(1))), metadata(Seq(keys.last))) + } + + test("metadata and container offsets have real one two and three byte boundaries") { + Seq((255, 1), (256, 2), (65535, 2), (65536, 3)).foreach { + case (size, expectedWidth) => + withClue(s"size=$size width=$expectedWidth: ") { + val key = Array.fill[Byte](size)('a'.toByte) + val objectValue = obj(Seq(0 -> nullValue)) + val expectedMetadata = metadata(Seq(key), expectedWidth) + check(new Variant(objectValue, metadata(Seq(key), 4)), objectValue, expectedMetadata) + check(new Variant(objectValue, expectedMetadata), objectValue, expectedMetadata) + val payload = Array(primitiveHeader(BINARY)) ++ littleEndian(BigInt(size - 5), 4) ++ + Array.fill[Byte](size - 5)(7) + checkKeyless(array(Seq(payload), 4), array(Seq(payload), expectedWidth)) + val expectedObject = obj(Seq(0 -> payload), offsetSize = expectedWidth) + check(new Variant(obj(Seq(0 -> payload), offsetSize = 4), dictionary("a")), + expectedObject, dictionary("a")) + } + } + } + + test("signed integer boundaries choose the smallest encoding") { + val boundaries = Seq( + (Long.MinValue, INT8, 8), (Int.MinValue.toLong - 1, INT8, 8), + (Int.MinValue.toLong, INT4, 4), (Short.MinValue.toLong - 1, INT4, 4), + (Short.MinValue.toLong, INT2, 2), (Byte.MinValue.toLong - 1, INT2, 2), + (Byte.MinValue.toLong, INT1, 1), (-1L, INT1, 1), (0L, INT1, 1), (1L, INT1, 1), + (Byte.MaxValue.toLong, INT1, 1), (Byte.MaxValue.toLong + 1, INT2, 2), + (Short.MaxValue.toLong, INT2, 2), (Short.MaxValue.toLong + 1, INT4, 4), + (Int.MaxValue.toLong, INT4, 4), (Int.MaxValue.toLong + 1, INT8, 8), + (Long.MaxValue, INT8, 8)) + boundaries.foreach { case (number, expectedType, expectedWidth) => + Seq((INT1, 1), (INT2, 2), (INT4, 4), (INT8, 8)).foreach { case (typeInfo, width) => + if (width >= expectedWidth) { + withClue(s"integer=$number width=$width: ") { + checkKeyless(integer(number, typeInfo, width), + integer(number, expectedType, expectedWidth)) + } + } + } + } + } + + test("decimal normalization respects precision scale and signed long promotion limits") { + val cases = Seq( Review Comment: Added scale-0 decimal cases that must be promoted to integers: 5, -5, 100 and the signed long limits 9223372036854775807 and -9223372036854775808. -- 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]
