SavicStefan commented on code in PR #59669: URL: https://github.com/apache/spark/pull/59669#discussion_r4482430703
########## 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") Review Comment: good catch, addressed it. -- 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]
