spark-test commented on code in PR #59095:
URL: https://github.com/apache/spark/pull/59095#discussion_r4514268788


##########
core/src/main/scala/org/apache/spark/api/java/JavaPairRDD.scala:
##########
@@ -205,8 +205,10 @@ class JavaPairRDD[K, V](val rdd: RDD[(K, V)])
    * Return the union of this RDD and another one. Any identical elements will 
appear multiple
    * times (use `.distinct()` to eliminate them).
    */
-  def union(other: JavaPairRDD[K, V]): JavaPairRDD[K, V] =
-    new JavaPairRDD[K, V](rdd.union(other.rdd))
+  def union(other: JavaPairRDD[K, V]): JavaPairRDD[K, V] = {
+    val kTag = JavaSparkContext.mergeKeyClassTags(kClassTag, other.kClassTag)
+    new JavaPairRDD[K, V](rdd.union(other.rdd))(kTag, vClassTag)

Review Comment:
   **Blocking (P1):** The tag merge added here covers the key tag, but the 
result is still labeled with `this.vClassTag`, and that can be the array tag 
`parallelizePairs` inferred. `keyBy`, `zip` and `cartesian` use a `JavaRDD`'s 
`classTag` as the value tag of the new pair RDD, so after `keys()` the inferred 
`byte[]` tag ends up in the value position:
   
   ```java
   JavaPairRDD<Object, Integer> p = sc.parallelizePairs(
       Arrays.asList(new Tuple2<Object, Integer>(new byte[]{1}, 1)));
   JavaPairRDD<Integer, Object> kb = p.keys().keyBy(k -> 1);
   JavaPairRDD<Integer, Object> o = sc.parallelizePairs(
       Arrays.asList(new Tuple2<Integer, Object>(2, "s")));
   kb.union(o).values().collect();  // fails: ArrayStoreException: 
java.lang.String
   ```
   
   `values()` maps under the reused tag, and `collect` builds a `byte[][]` that 
cannot hold `"s"`. `sc.union(kb, o)` fails the same way through 
`rdds.head.vClassTag`, and so does Scala `RDD.union` on `p.keys().rdd()`, which 
uses the receiver's element tag. On the base branch all three return the 
values. `take()`, `first()`, `glom()` and `MEMORY_ONLY` caching are affected as 
well as `collect()`. The trigger needs a `parallelizePairs` list whose keys all 
share one array class while the declared key type is wider. This was traced in 
the source, not run.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/59095#pullrequestreview-5338837379), 
[2](https://github.com/apache/spark/pull/59095#pullrequestreview-5400511223).
   
   **Recommended change:** Keep Object as the runtime class of the tag 
parallelizePairs infers, and carry the inferred array class on the tag as a 
marker. The array-key checks read that marker as well as the runtime class. 
Combining operations decide merges by the carried array class rather than the 
runtime class, so this change on its own keeps today's merge outcomes.
   
   **Why this works:** With the runtime class at Object, collect, take, glom, 
caching and serializer selection treat a parallelizePairs RDD exactly as on the 
base branch, wherever its tag travels. The checks in combineByKeyWithClassTag, 
partitionBy, cogroup, subtractByKey, reduceByKeyLocally, 
repartitionAndSortWithinPartitions and countByValueApprox recognize the marker. 
So every input that fails fast today still fails, with the same condition.
   
   **Scope:** Turn the inferred array key tag into a non-narrowing marker and 
make the array-key checks and tag merges read it.
   
   **Compatibility:** Every input that fails fast at head keeps failing with 
the same condition. Non-array key lists, fromJavaRDD tags for reference classes 
and Scala RDDs keep their current tags and results.
   
   **Risks:** Every array-key check must read the marker; a check site that is 
missed silently stops detecting inferred array keys. keys() of a 
parallelizePairs RDD with primitive-array keys goes back to the default 
serializer for serialized storage, as on the base branch. No configuration 
gates the change, so rolling it back means reverting it.
   
   **Constraints:** Never narrow the runtime class of a tag derived from a 
list's data; explicit tags from fromJavaRDD(rdd, keyClass), binaryRecords and 
Scala callers keep their declared classes. Merge decisions compare the carried 
array class, not the runtime class, which would make the marker equal to the 
erased Object tag; with this change alone they keep today's outcomes.
   
   **Exclusions:**
   - Extending the checks to mixed lists, merged results and argument operands 
is left to the separate change that widens the array-key checks, which builds 
on this one.
   - Lazily built pair RDDs, such as those from mapToPair, stay unmarked, as 
agreed for a follow-up.
   
   **Success:** Take a parallelizePairs RDD whose byte[] keys are declared as 
Object. If keyBy, zip or cartesian turns its keys() into values, then 
JavaPairRDD.union and JavaSparkContext.union with another pair RDD collect 
every value, and Scala RDD.union on keys().rdd() collects every element. No 
allocation, caching or serializer decision depends on a tag inferred from a 
list's data. Every input that fails fast at head still fails, with the same 
condition.
   
   **Verification:**
   - **Regression:** Take a parallelizePairs RDD with byte[] keys declared as 
Object. Turn its keys() into values with keyBy, zip or cartesian, and union the 
result with a pair RDD holding String values, using both JavaPairRDD.union and 
JavaSparkContext.union. Every value collects and caches, and Scala RDD.union on 
keys().rdd() also collects every element.
   - **Behavior:** Homogeneous byte[] parallelizePairs RDDs still fail 
partitionBy, join, cogroup, subtractByKey, repartitionAndSortWithinPartitions 
and keys().subtract with UNSUPPORTED_ARRAY_KEY.HASH_PARTITIONER, and 
reduceByKey with MAP_SIDE_COMBINE.
   - **Compatibility:** Non-array key lists, fromJavaRDD(rdd, byte[].class) 
RDDs and Scala RDDs with Array keys keep their current tags, results and 
conditions. keys() of a primitive-array parallelizePairs RDD uses the same 
serializer as on the base branch.



##########
core/src/main/scala/org/apache/spark/api/java/JavaPairRDD.scala:
##########
@@ -1081,4 +1122,26 @@ object JavaPairRDD {
     new JavaPairRDD[K, V](rdd.rdd)
   }
 
+  /**
+   * Convert a JavaRDD of key-value pairs to JavaPairRDD with an explicit key 
class.
+   *
+   * @param rdd an RDD of pairs
+   * @param keyClass the runtime class of the keys. When an array class is 
specified,
+   *                 pair operations using a 
[[org.apache.spark.HashPartitioner]]
+   *                 will fail fast with [[org.apache.spark.SparkException]]
+   *                 ("UNSUPPORTED_ARRAY_KEY.HASH_PARTITIONER"), and map-side 
combine
+   *                 operations will fail fast with
+   *                 ("UNSUPPORTED_ARRAY_KEY.MAP_SIDE_COMBINE"). It also 
determines the
+   *                 runtime type of arrays returned by actions on [[keys()]]. 
Must be the
+   *                 runtime reference class (e.g. `Integer.class`, not 
`int.class`).
+   *                 The value class remains erased.
+   * @since 4.4.0
+   */
+  @Since("4.4.0")
+  def fromJavaRDD[K, V](rdd: JavaRDD[(K, V)], keyClass: Class[K]): 
JavaPairRDD[K, V] = {
+    implicit val ctagK: ClassTag[K] = ClassTag(keyClass)

Review Comment:
   **Non-blocking (P2):** `ClassTag(keyClass)` is built without checking 
`keyClass`. Java types `int.class` as `Class<Integer>`, so `fromJavaRDD(rdd, 
int.class)` compiles for `Integer` keys and gives the RDD `ClassTag.Int`. The 
Scaladoc asks for the reference class, but nothing enforces it, and the misuse 
fails silently:
   - `sortByKey(comp, ascending, n)` builds a `RangePartitioner`. For more than 
128 bounds it searches with the `ClassTag.Int` branch of 
`CollectionsUtils.makeBinarySearch`, which runs a natural-order 
`Arrays.binarySearch` on `int[]` and ignores `comp`. With a non-natural 
comparator, records land in the wrong range partitions and the sorted output is 
out of order.
   - A null key collected through `keys()` is stored into an `int[]` and comes 
back as `0`.
   
   Every primitive class behaves the same way. This was traced in the source, 
not run.
   
   **Verification:**
   - **Regression:** fromJavaRDD with int.class, long.class or boolean.class 
fails at the call with an error that names the boxed class.
   - **Compatibility:** fromJavaRDD with Integer.class, String.class or 
byte[].class keeps its current key tag, results and array-key conditions.



##########
core/src/main/scala/org/apache/spark/api/java/JavaSparkContext.scala:
##########
@@ -152,9 +152,34 @@ class JavaSparkContext(val sc: SparkContext) extends 
Closeable {
   /** Distribute a local Scala collection to form an RDD. */
   def parallelizePairs[K, V](list: java.util.List[Tuple2[K, V]], numSlices: 
Int)
   : JavaPairRDD[K, V] = {
-    implicit val ctagK: ClassTag[K] = fakeClassTag
+    val seq = list.asScala.toSeq
+    var firstArrayClass: Class[_] = null
+    var isHomogeneousArray = false
+    val iter = seq.iterator
+    var hasConflict = false
+    while (iter.hasNext && !hasConflict) {
+      val elem = iter.next()
+      if (elem != null && elem._1 != null) {
+        val keyCls = elem._1.getClass
+        if (!keyCls.isArray) {
+          hasConflict = true
+        } else if (firstArrayClass == null) {
+          firstArrayClass = keyCls
+          isHomogeneousArray = true
+        } else if (keyCls != firstArrayClass) {
+          hasConflict = true
+        }
+      }
+    }
+    implicit val ctagK: ClassTag[K] =

Review Comment:
   **Non-blocking (P2):** When this falls back to `fakeClassTag`, every 
array-key check is skipped, so array keys in these inputs still get the 
identity-based results this PR fixes for homogeneous lists:
   
   ```java
   sc.parallelizePairs(Arrays.asList(
       new Tuple2<Object, Integer>(new byte[]{1}, 1),
       new Tuple2<Object, Integer>(new byte[]{1}, 2),
       new Tuple2<Object, Integer>("a", 3)))
     .reduceByKey(Integer::sum).count();  // 3: the equal byte[] keys stay apart
   ```
   
   Without the `"a"` pair, the same call throws 
`UNSUPPORTED_ARRAY_KEY.MAP_SIDE_COMBINE`. The same gap appears when 
`mergeKeyClassTags` gives a `union`, `cogroup`, `groupWith` or outer-join 
result the `Object` tag. It also appears when the array-tagged RDD is an 
argument rather than the receiver: the checks read only the receiver's key 
class, so `fakeTagged.join(arrayTagged)` or 
`fakeTagged.subtractByKey(arrayTagged)` hashes the `byte[]` keys by identity. 
In each case the driver already sees the array keys, or another operand's tag 
carries them. A narrowed tag just can't record that safely. The previous review 
left mixed unions out because an `Object`-tagged result could not carry 
array-ness, but a marker whose runtime class stays `Object` can. That is why 
this pairs with the value-tag leak on `union`. Pair RDDs built lazily, such as 
by `mapToPair`, stay out of scope as agreed for a follow-up.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/59095#issuecomment-6152268008), 
[2](https://github.com/apache/spark/pull/59095#pullrequestreview-5400511223).
   
   **Recommended change:** Building on the non-narrowing marker, 
parallelizePairs marks a list when any non-null key is an array. union, 
cogroup, groupWith, the outer joins and both JavaSparkContext.union overloads 
give their result the marker when any input carries it or an explicit array 
tag. join, leftOuterJoin, rightOuterJoin, fullOuterJoin, cogroup, groupWith and 
subtractByKey check every operand's key tag before delegating, and 
JavaRDD.subtract and intersection check the other operand's element tag.
   
   **Why this works:** Each input that still hashes array keys by identity then 
carries the array-key signal into the existing checks, so it fails fast with 
the same UNSUPPORTED_ARRAY_KEY condition as a homogeneous list. Because the 
runtime class stays Object, marking more inputs never changes what gets 
allocated.
   
   **Scope:** Make the array-key checks cover every Java pair RDD whose keys 
are known to include arrays, whatever the list mix or operand position.
   
   **Compatibility:** Inputs without array keys keep their current array-key 
check outcomes. Every input that fails fast at head keeps its condition.
   
   **Risks:** More Java jobs fail fast: lists that mix array and other keys, 
and unions or cogroups that combine an array-keyed RDD with any other, used to 
return identity-based results without error, so the migration note must cover 
them. parallelizePairs must now read every key of a list that has no array key, 
the common case, where it now stops at the first non-null key that is not an 
array. That adds one allocation-free pass over the list on the driver for each 
call. It is small next to the copy and task serialization the method already 
does for the same list, and folding the check into that copy keeps it smaller. 
No configuration gates the change, so rolling it back means reverting it.
   
   **Constraints:** Mark only lists that contain an array key, and results that 
combine a marked or explicitly array-tagged input; lists and combinations 
without array keys must behave as at head. Leave the runtime class at Object, 
so that marking more inputs never changes allocation.
   
   **Exclusions:**
   - Lazily built pair RDDs (mapToPair, flatMapToPair, mapPartitionsToPair, 
keyBy, groupBy and the one-argument fromJavaRDD) stay outside, as agreed for a 
follow-up.
   - Arrays nested inside other values, such as tuple elements, stay undetected 
as on the base branch.
   
   **Success:** The existing UNSUPPORTED_ARRAY_KEY conditions now also fire 
for: parallelizePairs lists whose non-null keys include any array; union, 
cogroup, groupWith and outer-join results that combine an array-tagged input 
with any other; and calls of the joins, cogroup, groupWith and subtractByKey, 
or of subtract and intersection on keys(), with an array-tagged argument. Lists 
and combinations without array keys behave exactly as at head.
   
   **Verification:**
   - **Regression:** These cases now fail fast. reduceByKey over a 
parallelizePairs list that mixes two content-equal byte[] keys with a String 
key fails with UNSUPPORTED_ARRAY_KEY.MAP_SIDE_COMBINE instead of returning 
three groups. partitionBy with a HashPartitioner fails with HASH_PARTITIONER on 
the union of a byte[] parallelizePairs RDD with a mapToPair RDD. Under a 
HashPartitioner, every binary operation whose check read only the receiver 
(join, leftOuterJoin, rightOuterJoin, fullOuterJoin, cogroup, groupWith and 
subtractByKey, and subtract and intersection on keys()) fails fast when the 
byte[] RDD is an argument of a receiver with an erased key tag.
   - **Compatibility:** Heterogeneous non-array lists, such as Integer and 
Double keys, and unions of non-array RDDs keep partitioning, joining and 
collecting as at head.



##########
core/src/test/java/test/org/apache/spark/JavaAPISuite.java:
##########
@@ -1531,4 +1534,213 @@ public void testGetPersistentRDDs() {
     assertEquals("RDD2", cachedRddsMap.get(1).name());
   }
 
+  @Test
+  public void testArrayKeyUnderHashPartitionerFails() {

Review Comment:
   **Nit (P3):** These tests assert only 
`UNSUPPORTED_ARRAY_KEY.HASH_PARTITIONER`. No Java test checks the 
`MAP_SIDE_COMBINE` or `REDUCE_BY_KEY_LOCALLY` conditions that an array key tag 
now enables on the Java path (`reduceByKey`, `countByKey`, `keys().distinct()`, 
`reduceByKeyLocally`), although the new `fromJavaRDD` doc promises 
`MAP_SIDE_COMBINE`. If a Java wrapper stopped passing the key tag into 
`combineByKeyWithClassTag` or `reduceByKeyLocally`, no test would fail. No case 
gives `parallelizePairs` an empty or all-null-key list either. That is the only 
state where `firstArrayClass` stays `null` and the inference must pick 
`fakeClassTag`, so a regression that built the tag from the null class would 
fail only for such lists, and none of the Java suites passes one.
   
   See **Shared repair plan 1** in the review body.



##########
core/src/main/scala/org/apache/spark/api/java/JavaPairRDD.scala:
##########
@@ -1081,4 +1122,26 @@ object JavaPairRDD {
     new JavaPairRDD[K, V](rdd.rdd)
   }
 
+  /**
+   * Convert a JavaRDD of key-value pairs to JavaPairRDD with an explicit key 
class.
+   *
+   * @param rdd an RDD of pairs
+   * @param keyClass the runtime class of the keys. When an array class is 
specified,
+   *                 pair operations using a 
[[org.apache.spark.HashPartitioner]]
+   *                 will fail fast with [[org.apache.spark.SparkException]]
+   *                 ("UNSUPPORTED_ARRAY_KEY.HASH_PARTITIONER"), and map-side 
combine
+   *                 operations will fail fast with

Review Comment:
   **Nit (P3):** Callers match these conditions through `getCondition()`, but 
this doc does not match what the code throws:
   - `combineByKeyWithClassTag` checks map-side combine first, so 
`reduceByKey`, `aggregateByKey`, `foldByKey`, `combineByKey` and `countByKey` 
throw `MAP_SIDE_COMBINE` even under the default `HashPartitioner`.
   - `reduceByKeyLocally` throws `REDUCE_BY_KEY_LOCALLY` and `countByKeyApprox` 
throws `_LEGACY_ERROR_TEMP_3015`; the doc mentions neither.
   
   The second clause is also missing its noun: "will fail fast with" is 
followed only by the parenthesized condition, where the first clause names 
`SparkException`. Java `keys()` actions return `List`s, so the sentence about 
the runtime type of arrays describes an internal detail. What callers see is 
that `distinct`, `subtract`, `intersection` and `countByValue` on `keys()` now 
fail fast, and that a key that is not an instance of `keyClass` makes `keys()` 
actions throw `ArrayStoreException`. The `parallelizePairs` doc also still 
doesn't say that the key tag is now inferred from the list.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59095#discussion_r4509956543).
   
   **Verification:**
   - **Inspection:** The fromJavaRDD Scaladoc names every condition an array 
key class causes, the operations that raise each one and which condition wins 
under a HashPartitioner, and every clause is grammatical. The parallelizePairs 
doc describes the inference rule that ships.



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