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


##########
common/variant/src/main/java/org/apache/spark/types/variant/VariantBuilder.java:
##########
@@ -205,6 +205,231 @@ 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.
+   * <p>
+   * A variant is canonical when all of the following hold.
+   * <ul>
+   *   <li>Metadata header: version {@link VariantUtil#VERSION}, the minimal 
offset size for
+   *       {@code max(lastOffset, numKeys)}, i.e. 1, 2, 3 or 4 bytes as given 
by
+   *       {@code getIntegerSize}, and {@code sorted_strings} and the unused 
bit 5 clear.
+   *       {@code sorted_strings} stays clear although canonical keys are 
sorted, so that builder
+   *       output, which never sets it, is already canonical.</li>
+   *   <li>Metadata dictionary: the first offset is 0, offsets are 
non-decreasing, the key bytes
+   *       end exactly at the last offset (no trailing bytes), keys are 
strictly increasing under
+   *       unsigned byte comparison (so they are unique), and every key is 
referenced by at least
+   *       one object field. Key bytes are preserved as is, including invalid 
UTF-8.</li>
+   *   <li>Value root: starts at position 0 and spans exactly {@code 
value.length} bytes.</li>
+   *   <li>Object: field ids strictly increasing (fields are stored in key 
order and no key is
+   *       repeated), field data stored contiguously in field order, the end 
offset equal to the
+   *       data size, and the header using the minimal id size for the largest 
id, the minimal
+   *       offset size for the data size, {@code is_large} only for more than 
255 fields, and the
+   *       reserved bit 7 clear.</li>
+   *   <li>Array: element order preserved, element data stored contiguously in 
element order, the
+   *       end offset equal to the data size, and the header using the minimal 
offset size for the
+   *       data size, {@code is_large} only for more than 255 elements, and 
the reserved bits 5 to
+   *       7 clear.</li>
+   *   <li>Integer: the smallest of INT1, INT2, INT4 and INT8 that holds the 
value.</li>
+   *   <li>Decimal: trailing zeros stripped, and a scale that stripping made 
negative (for example
+   *       1E+20 for 10^20) set back to 0. An integral decimal that fits in a 
signed 64-bit integer
+   *       is stored as an integer instead. Otherwise the smallest of DECIMAL4 
(precision and scale
+   *       at most 9), DECIMAL8 (at most 18) and DECIMAL16 that holds the 
value.</li>
+   *   <li>Float and double: -0.0 is stored as 0.0 and NaN as the canonical 
NaN bit pattern of
+   *       {@link Float#floatToIntBits} and {@link Double#doubleToLongBits}. 
The type is kept, so
+   *       a float and a double are never identical.</li>
+   *   <li>String: at most {@link VariantUtil#MAX_SHORT_STR_SIZE} bytes uses 
the short-string
+   *       encoding, anything longer the long-string encoding. Bytes are 
preserved as is, including
+   *       invalid UTF-8.</li>
+   *   <li>Every other type (null, boolean, date, timestamps, binary, uuid, 
...) has a single
+   *       encoding in the spec and is copied unchanged.</li>
+   * </ul>
+   * {@code isCanonical} checks exactly these rules and {@code doCanonicalize} 
produces them; the
+   * two must be changed together when a rule changes or a type with 
alternative encodings is
+   * added to the spec.
+   */
+  public static Variant canonicalize(Variant v) {
+    if (isCanonical(v)) {
+      return v;
+    }
+    return doCanonicalize(v);
+  }
+
+  // Check whether `v` already satisfies every rule listed in `canonicalize`. 
Return false at the
+  // first non-canonical encoding. Malformed bytes that the check can reject 
from what it has
+  // already read return false, and the rebuild then decides whether they 
fail. This includes a
+  // container whose declared data runs past the value and a child whose 
encoding runs past its
+  // container's declared data: the rebuild accepts both when every child it 
reaches is in bounds,
+  // and re-encodes each child from its own header. Malformed bytes that the 
check has to decode
+  // throw instead, for example `MALFORMED_VARIANT` for an unreadable metadata 
table, a truncated
+  // container size field or offset list, or a decimal whose precision or 
scale is out of range,
+  // and `UNKNOWN_PRIMITIVE_TYPE_IN_VARIANT` for an unknown type ID. When the 
check throws,
+  // `canonicalize` fails with that error. Returning false does not establish 
validity.
+  static boolean isCanonical(Variant v) {
+    if (v.pos != 0) {
+      return false;
+    }
+    byte[] value = v.value;
+    byte[] metadata = v.metadata;
+    int offsetSize = getMetadataOffsetSize(metadata);
+    int numKeys = getMetadataNumKeys(metadata, offsetSize);
+    int stringStart = getMetadataStringStart(metadata, numKeys, offsetSize);
+    int lastOffset = readUnsigned(metadata, stringStart - offsetSize, 
offsetSize);
+    // The key bytes must end exactly at lastOffset; trailing bytes are not 
canonical.
+    if (metadata.length != stringStart + lastOffset) {
+      return false;
+    }
+    int canonicalOffsetSize = getIntegerSize(Math.max(lastOffset, numKeys));
+    if (metadata[0] != metadataHeader(canonicalOffsetSize)) {
+      return false;
+    }
+    int firstOffset = readUnsigned(metadata, 1 + offsetSize, offsetSize);
+    if (firstOffset != 0) {
+      return false;
+    }
+    int previousOffset = 0;
+    int currentOffset = 0;
+    for (int keyId = 0; keyId < numKeys; ++keyId) {
+      int nextOffset = readUnsigned(metadata, 1 + (keyId + 2) * offsetSize, 
offsetSize);
+      if (currentOffset > nextOffset || nextOffset > lastOffset) {
+        return false;
+      }
+      if (keyId > 0 && Arrays.compareUnsigned(
+          metadata, stringStart + previousOffset, stringStart + currentOffset,
+          metadata, stringStart + currentOffset, stringStart + nextOffset) >= 
0) {
+        return false;
+      }
+      previousOffset = currentOffset;
+      currentOffset = nextOffset;
+    }
+    boolean[] referenced = new boolean[numKeys];
+    if (valueSize(value, 0) != value.length || !isValueCanonical(value, 0, 
referenced)) {
+      return false;
+    }
+    for (boolean keyReferenced : referenced) {
+      if (!keyReferenced) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  // Check canonical value encoding and mark key IDs in referenced as they are 
visited.
+  // On false, referenced may be incomplete. Keep these checks in sync with
+  // appendCanonicalizedScalar, canonical object/array rebuilding in 
appendVariantImpl,
+  // finishWritingObject, and finishWritingArray.
+  private static boolean isValueCanonical(byte[] value, int pos, boolean[] 
referenced) {
+    int encodedSize = valueSize(value, pos);
+    if (encodedSize <= 0 || (long) pos + encodedSize > value.length) {
+      return false;
+    }
+    switch (getType(value, pos)) {
+      case OBJECT:
+        return handleObject(value, pos,
+            (size, idSize, offsetSize, idStart, offsetStart, dataStart) -> {
+          int previousId = -1;
+          int dataSize = 0;
+          for (int fieldIndex = 0; fieldIndex < size; ++fieldIndex) {
+            int keyId = readUnsigned(value, idStart + idSize * fieldIndex, 
idSize);
+            if (keyId <= previousId || keyId >= referenced.length) {
+              return false;
+            }
+            previousId = keyId;
+            referenced[keyId] = true;
+            int offset = readUnsigned(value, offsetStart + offsetSize * 
fieldIndex, offsetSize);
+            if (offset != dataSize) {
+              return false;
+            }
+            int elementPos = dataStart + offset;
+            if (!isValueCanonical(value, elementPos, referenced)) {
+              return false;
+            }
+            dataSize += valueSize(value, elementPos);
+          }
+          int lastOffset = readUnsigned(value, offsetStart + offsetSize * 
size, offsetSize);
+          if (lastOffset != dataSize) {
+            return false;
+          }
+          int maxId = size == 0 ? 0 : previousId;
+          return value[pos] ==
+              objectHeader(size > U8_MAX, getIntegerSize(maxId), 
getIntegerSize(dataSize));
+        });
+      case ARRAY:
+        return handleArray(value, pos, (size, offsetSize, offsetStart, 
dataStart) -> {
+          int dataSize = 0;
+          for (int elementIndex = 0; elementIndex < size; ++elementIndex) {
+            int offset = readUnsigned(value, offsetStart + offsetSize * 
elementIndex, offsetSize);
+            if (offset != dataSize) {
+              return false;
+            }
+            int elementPos = dataStart + offset;
+            if (!isValueCanonical(value, elementPos, referenced)) {
+              return false;
+            }
+            dataSize += valueSize(value, elementPos);
+          }
+          int lastOffset = readUnsigned(value, offsetStart + offsetSize * 
size, offsetSize);
+          return lastOffset == dataSize &&
+              value[pos] == arrayHeader(size > U8_MAX, 
getIntegerSize(dataSize));
+        });
+      case LONG:
+        return getTypeInfo(value, pos) == minimalLongTypeInfo(getLong(value, 
pos));
+      case DECIMAL: {

Review Comment:
   it cant be negative, because the scale byte is read as unsigned in 
`getDecimalWithOriginalScale` and `checkDecimal` caps it at 38. The negative 
scale in `canonicalDecimalForm` only comes from `stripTrailingZeros()`, and 
resetting it to 0 never adds digits beyond the original unscaled value, so it 
always fits `decimal16`



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