spark-test commented on code in PR #56096: URL: https://github.com/apache/spark/pull/56096#discussion_r4543095089
########## sql/core/src/test/scala/org/apache/spark/sql/ICUCollationSortKeyGoldenSuite.scala: ########## @@ -0,0 +1,575 @@ +/* + * 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.sql + +import java.nio.charset.StandardCharsets +import java.nio.file.{Files, Path} + +import scala.jdk.CollectionConverters._ + +import org.apache.spark.SparkFunSuite +import org.apache.spark.sql.catalyst.util.CollationFactory +import org.apache.spark.unsafe.types.UTF8String +import org.apache.spark.util.Utils + +// scalastyle:off line.size.limit +/** + * Visibility golden suite for ICU collation sort keys. Snapshots the sort-key + * bytes for a representative matrix of (collation, input) cells so that an + * icu4j or CLDR data upgrade produces a readable golden diff for review. + * + * This is NOT a byte-stability contract. Downstream consumers MUST NOT rely + * on sort-key byte equality across Spark versions. The golden file exists to + * trigger reviewer attention on ICU upgrades, not to lock the byte layout. + * + * To re-generate the golden file, run: + * {{{ + * SPARK_GENERATE_GOLDEN_FILES=1 build/sbt "sql/testOnly org.apache.spark.sql.ICUCollationSortKeyGoldenSuite" + * }}} + * + * The regen logic emits `GOLDEN_DISCLAIMER` as line 1 verbatim; the + * disclaimer-survival assert below catches accidental drop on regen. + */ +// scalastyle:on line.size.limit +// scalastyle:off nonascii +class ICUCollationSortKeyGoldenSuite extends SparkFunSuite { + + import ICUCollationSortKeyGoldenSuite._ + + private val goldenFile: Path = getWorkspaceFilePath( + "sql", "core", "src", "test", "resources", + "collations", "ICU-collations-sort-keys.md") + + // Read the golden file once per suite run; tests re-use the same buffer. + private lazy val goldenLines: Seq[String] = + Files.readAllLines(goldenFile, StandardCharsets.UTF_8).asScala.toSeq + + // Locate a row by (collation, input) by parsing pipe-delimited columns. + // Robust to whitespace-only input rendering (D11 empty string). + private def rowFor(collation: String, input: String): Option[String] = + goldenLines.find { line => + val cols = parseRow(line) + cols.length == 3 && cols(0) == collation && cols(1) == renderInput(input) + } + + // Fetch hex column or fail with a regen hint. + private def hexFor(collation: String, input: String): String = { + val row = rowFor(collation, input).getOrElse( + fail(s"golden row missing for ($collation, $input); $REGEN_HINT")) + hexOf(row) + } + + protected override def beforeAll(): Unit = { + super.beforeAll() + if (regenerateGoldenFiles) writeGoldenFile(goldenFile) + } + + test("disclaimer is golden line 1") { + assert(Files.exists(goldenFile), + s"golden file is missing: $goldenFile; $REGEN_HINT") + assert(goldenLines.nonEmpty, s"golden file is empty: $goldenFile; $REGEN_HINT") + assert(goldenLines.head == GOLDEN_DISCLAIMER, + s"expected golden line 1 to be the non-contract disclaimer verbatim; " + + s"got: ${goldenLines.head}") + } + + test("writeGoldenFile is deterministic and writes no BOM") { + val tmpDir = Utils.createTempDir().toPath + val a = tmpDir.resolve("a.md") + val b = tmpDir.resolve("b.md") + writeGoldenFile(a) + writeGoldenFile(b) + val bytesA = Files.readAllBytes(a) + val bytesB = Files.readAllBytes(b) + assert(bytesA.sameElements(bytesB), + "writeGoldenFile must be deterministic: two consecutive writes differ") + assert(bytesA.nonEmpty && bytesA(0) == '<'.toByte, + "writeGoldenFile must not emit a UTF-8 BOM; line 1 must start with '<'") + val firstLineA = Files.readAllLines(a, StandardCharsets.UTF_8).get(0) + assert(firstLineA == GOLDEN_DISCLAIMER, + "writeGoldenFile must emit GOLDEN_DISCLAIMER verbatim as line 1") + val onDisk = Files.readAllBytes(goldenFile) + assert(bytesA.sameElements(onDisk), + s"on-disk golden differs from writeGoldenFile output; $REGEN_HINT") + } + + test("golden file has no control characters, so diffs render as text") { + // Git and GitHub treat a file containing NUL as binary and hide its diff, + // which would hide sort-key drift from reviewers of an ICU upgrade. + val bad = Files.readString(goldenFile, StandardCharsets.UTF_8).zipWithIndex.collect { + case (c, i) if Character.isISOControl(c) && c != '\n' => f"U+${c.toInt}%04X@$i" + } + assert(bad.isEmpty, s"golden file contains control characters ${bad.mkString(", ")}; " + + REGEN_HINT) + } + + test("UNICODE primary order separates basic-Latin letters") { + // Existence baseline: every basic Latin cell reaches the golden as a row. + val inputs = Seq("a", "b", "c", "A", "B", "C") + val missing = inputs.filterNot(rowFor("UNICODE", _).isDefined) + assert(missing.isEmpty, + s"UNICODE basic-Latin rows missing: ${missing.mkString(", ")}; $REGEN_HINT") + } + + test("UNICODE_CI folds tertiary case; UNICODE and en_USA distinguish it") { + // UNICODE_CI must collate 'a'/'A' and 'b'/'B' identically; UNICODE and + // en_USA preserve case at the tertiary level. + val rowsRequired = for { + coll <- Seq("UNICODE_CI", "en_USA") + ch <- Seq("a", "A", "b", "B") + } yield (coll, ch) + val missing = rowsRequired.filterNot { case (c, i) => rowFor(c, i).isDefined } + assert(missing.isEmpty, + s"tertiary-case rows missing: ${missing.mkString(", ")}; $REGEN_HINT") + + assert(hexFor("UNICODE_CI", "a") == hexFor("UNICODE_CI", "A"), + "UNICODE_CI should fold 'a' and 'A' to identical sort keys") + assert(hexFor("UNICODE_CI", "b") == hexFor("UNICODE_CI", "B"), + "UNICODE_CI should fold 'b' and 'B' to identical sort keys") + assert(hexFor("UNICODE", "a") != hexFor("UNICODE", "A"), + "UNICODE should distinguish 'a' from 'A' at tertiary") + assert(hexFor("en_USA", "a") != hexFor("en_USA", "A"), + "en_USA should distinguish 'a' from 'A' at tertiary") + assert(hexFor("en_USA", "b") != hexFor("en_USA", "B"), + "en_USA should distinguish 'b' from 'B' at tertiary") + } + + test("UNICODE_AI and en_USA_AI fold accents; UNICODE distinguishes them") { + // The AI bit collapses accents at the secondary level. + val plain = "e" + val acute = "\u00e9" + for { + coll <- Seq("UNICODE", "UNICODE_AI", "en_USA_AI") + ch <- Seq(plain, acute) + } { + val label = if (ch == acute) "U+00E9" else ch + assert(rowFor(coll, ch).isDefined, + s"secondary-diacritic row missing: ($coll, $label); $REGEN_HINT") + } + + assert(hexFor("UNICODE", plain) != hexFor("UNICODE", acute), + "UNICODE should distinguish 'e' from 'e-acute' at secondary") + assert(hexFor("UNICODE_AI", plain) == hexFor("UNICODE_AI", acute), + "UNICODE_AI should fold 'e' and 'e-acute' to identical sort keys") + assert(hexFor("en_USA_AI", plain) == hexFor("en_USA_AI", acute), + "en_USA_AI should fold 'e' and 'e-acute' to identical sort keys") + } + + test("UNICODE collates NFC and NFD canonically-equivalent forms identically") { + // ICU honours canonical equivalence: the precomposed NFC form U+00E9 and + // the decomposed NFD form "e" + U+0301 must produce the same sort key. + // (This holds despite Spark's NO_DECOMPOSITION ICU option because the + // single-codepoint precomposition is handled by ICU's DUCET contraction + // lookup, not the runtime decomposition path.) + val nfc = "\u00e9" + val nfd = "e\u0301" + assert(hexFor("UNICODE", nfc) == hexFor("UNICODE", nfd), + s"canonical equivalence violated: hex(NFC) != hex(NFD) under UNICODE") + } + + test("UNICODE records both combining-mark orderings for drift visibility") { + // The two canonically-equivalent orderings of "a" + acute + dot-below + // would produce identical sort keys under a normalising configuration, + // but Spark uses ICU's NO_DECOMPOSITION setting and so emits distinct + // sort keys for the two input orders. The golden records both rows so + // that any future change (e.g. enabling decomposition, or canonical- + // closure additions in CLDR) appears as a diff. No byte-equality is + // asserted between the two orderings; the rows are visibility only. + val aboveBelow = "a\u0301\u0323" + val belowAbove = "a\u0323\u0301" + assert(rowFor("UNICODE", aboveBelow).isDefined && + rowFor("UNICODE", belowAbove).isDefined, + s"combining-reorder visibility rows missing under UNICODE; $REGEN_HINT") + } + + test("UNICODE preserves SMP code points through surrogate-pair encoding") { + // SMP code points (U+10000+) round-trip through UTF-16 surrogate pairs + // and UTF-8 4-byte sequences. A regression that drops the surrogate + // before reaching ICU would produce an empty hex. + val emoji = new String(Character.toChars(0x1F600)) // grinning face + val linearB = new String(Character.toChars(0x10000)) // Linear B B008 A + val emojiHex = hexFor("UNICODE", emoji) + val linearBHex = hexFor("UNICODE", linearB) + assert(emojiHex.nonEmpty && linearBHex.nonEmpty, + s"SMP sort-key hex is empty (emoji='$emojiHex', linearB='$linearBHex'); " + + "surrogate pair may have been dropped before ICU sort-key computation") + } + + test("UNICODE preserves BMP precomposed Hangul") { + // Precomposed Hangul Syllables (AC00..D7A3) must reach the sort key and + // not collapse into the UCA-fully-ignorable bucket that swallows C0 + // controls and variation selectors elsewhere in this suite. + val hangeul = "\uD55C\uAE00" // HAN + GEUL ("hangeul") + val hex = hexFor("UNICODE", hangeul) + assert(hex.nonEmpty, + s"Hangul sort-key hex is empty (hex='$hex'); " + + "precomposed Hangul may have been silently ignored") + } + + test("UNICODE places ASCII hyphen and space at primary level (NON_IGNORABLE)") { + // Under ICU's NON_IGNORABLE alternate handling, ASCII punctuation and + // whitespace carry primary weights. The opposite configuration + // (SHIFTED) would collapse them into the UCA-fully-ignorable bucket, + // producing sort keys whose primary segment is just the surrounding + // letters ("ab"-shape, two primary weights only). + val hyphenHex = hexFor("UNICODE", "a-b") + val spaceHex = hexFor("UNICODE", "a b") + assert(hyphenHex.nonEmpty && spaceHex.nonEmpty, + s"punct/space sort-key hex is empty (hyphen='$hyphenHex', space='$spaceHex')") + // NON_IGNORABLE invariant 1: the separator contributes its own primary + // weight, so hyphen and space produce distinct sort keys. Under SHIFTED + // (or SHIFT_TRIMMED with merged shifted weights) both would collapse + // to the same shape as plain "ab". + assert(hyphenHex != spaceHex, + s"hyphen and space sort keys should differ under NON_IGNORABLE alternate " + + s"handling (got hyphen=$hyphenHex space=$spaceHex); a SHIFTED config " + + "would collapse them into the UCA-fully-ignorable bucket") + // NON_IGNORABLE invariant 2 (L1 primary-segment probe): UCA sort keys + // are segmented by 01 byte separators between levels (UTS #10 sec 3.2). + // The primary segment runs from the start to the first 01 byte. Under + // NON_IGNORABLE the separator carries a primary weight, so the L1 + // segment for "a<sep>b" contains 3+ primary weight bytes (a, sep, b). + // Under SHIFTED the separator is removed from L1 (shifted to L4), so + // the L1 segment would contain only 2 primary weights ("ab"-shape). + def primarySegmentBytes(hex: String): Int = { Review Comment: **Nit (P3):** Adding to the byte-count point already raised on this line: the comment above attributes the 01 level separator to UTS #10 sec 3.2, but UTS #10 separates levels with a zero weight. The 01 separator and the 00 terminator are ICU's sort-key byte format, the kind of implementation detail the CJK test's comment distinguishes from a UCA constant, so this probe measures ICU's encoding rather than a property the standard defines. That is also why the `>= 3` threshold depends on byte widths: the hyphen already has a two-byte primary (`05 0e`), so an 'ab'-shaped key would pass under SHIFTED if a and b ever got multi-byte primaries. Since the hyphen-versus-space assertion above would already fail under SHIFTED at Spark's level-3 strength, this probe adds little as written. Comparing the bytes before the first 01 for 'a-b' and 'a b' with those of an 'ab' cell would catch SHIFTED at any strength regardless of byte widths, and the comment could attribute the separator to ICU's fo rmat. This extends an [existing discussion](https://github.com/apache/spark/pull/56096#discussion_r4542042506). **Verification:** - **Regression:** Replacing the recorded key of 'a-b' or of 'a b' with the key of 'ab', as SHIFTED alternate handling would produce, makes the test fail with a message that names the separator. - **Inspection:** No comment in the suite attributes ICU's 01 level separator or 00 terminator to UTS #10. -- 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]
