spark-test commented on code in PR #59095:
URL: https://github.com/apache/spark/pull/59095#discussion_r4509956506
##########
core/src/main/scala/org/apache/spark/api/java/JavaSparkContext.scala:
##########
@@ -152,9 +152,33 @@ 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] =
+ if (isHomogeneousArray && !hasConflict) {
+ ClassTag(firstArrayClass).asInstanceOf[ClassTag[K]]
Review Comment:
**Blocking (P1):** This tag comes from one list's contents, but
`JavaPairRDD` treats `kClassTag` as valid for the declared key type and reuses
the receiver's tag for results that also hold another RDD's keys. For example:
```java
JavaPairRDD<Object, Integer> a = sc.parallelizePairs(
Arrays.asList(new Tuple2<Object, Integer>(new byte[]{1}, 1)));
JavaPairRDD<Object, Integer> b = sc.parallelizePairs(
Arrays.asList(new Tuple2<Object, Integer>("x", 2)));
a.union(b).keys().collect(); // ArrayStoreException: java.lang.String
```
`a` gets `ClassTag(byte[])` here while `b` keeps `fakeClassTag`. `union`
wraps the result under `a`'s key tag (JavaPairRDD.scala:208-209), `keys()` maps
under it, and `RDD.collect` runs `iter.toArray` with that tag, so it allocates
a `byte[][]` that cannot hold `"x"`. Before this PR the same code returned both
keys. The same happens through `JavaSparkContext.union(a, b)`, through
`cogroup`, `groupWith`, `rightOuterJoin` and `fullOuterJoin` when the
partitioner is not a `HashPartitioner`, and through `JavaRDD.union` on
`a.keys()`. Besides `collect()`, it affects `glom()`, `take()` and `first()`
when they scan a partition holding the foreign key, `count()` after
`keys().cache()`, and `sortByKey`'s range sampling. `b.union(a)` keeps `b`'s
Object tag and works, so the failure depends on operand order and list
contents, and the in-list heterogeneity tests cannot catch it. Only Java pair
RDDs from `parallelizePairs` whose declared key type is wider than the array
class are affected. Thi
s is traced in the source; it was not run.
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:** Make parallelizePairs mark the array key tag it
infers from its list, so that it can be told apart from a tag that comes from a
declared type; for example, build it as a private ClassTag implementation that
still equals the plain ClassTag of the same class, which every RDD derived from
that result alone inherits with the tag. Then make every Java API operation
that builds one RDD from several operands check the tag it would reuse: when
that tag carries the mark and another operand's tag differs from it, give the
result the Object tag the base branch always used, and otherwise keep the
receiver's or first operand's tag as these operations do now. Apply this in
JavaPairRDD.union, in every cogroup, groupWith, fullOuterJoin and
rightOuterJoin overload, in JavaRDD.union, and in both JavaSparkContext.union
overloads, building the underlying union under the chosen tag. Add Java API
tests that combine a parallelizePairs RDD whose keys are all byte[], declared
with
a wider key type, with an RDD holding keys of another class, and that union an
explicitly tagged array RDD with an Object-tagged one.
**Why this works:** Only parallelizePairs takes a key tag from data, so only
its tag can be narrower than the declared key type. Every other producer takes
the tag from that type (fakeClassTag, a Class argument, or a Scala ClassTag),
and all operands of the same Java RDD type share it, so reusing such a tag
stays valid for every key. A marked tag that differs from another operand's tag
says nothing about that operand's keys, so the result falls back to Object; a
marked tag equal to every other operand's tag, or an unmarked one, still admits
every key and keeps the array-key checks firing.
**Scope:** Mark the key tag parallelizePairs infers and make the Java API
operations that merge several RDDs replace a marked tag with the Object tag
when another operand's tag differs, with Java API tests for the cross-RDD and
explicit-tag cases.
**Compatibility:** Single-source derivations of a parallelizePairs RDD, such
as filter, mapValues, coalesce and keys(), keep its key tag, so every array-key
check and the new subtract checks on them still fire; and every combining
operation whose reused tag came from a declared type keeps the tag, and the
array-key checks it triggers, that it has now.
**Risks:** The result of a union or cogroup-family operation that mixes an
RDD whose key tag parallelizePairs inferred with an RDD whose tag differs gets
the Object tag, so later operations on it skip the array-key checks, as
parallelizePairs already does for a list that mixes key classes; array keys in
it are then partitioned by identity, as they were before this PR. The change
spans many public overloads, and an overload left out keeps throwing
ArrayStoreException, so the tests should cover each operation family. A
derivation that rebuilt the key tag from its class instead of passing the tag
along would lose the mark, and its later unions would keep the narrow tag and
throw as they do now; the Java API's single-operand operations pass the tag
along, so the tests should also cover a union after filter or mapValues.
**Constraints:** Fall back only when the reused tag is one parallelizePairs
inferred. A tag that comes from a declared type, such as fakeClassTag, the
Class argument of fromJavaRDD(rdd, keyClass) or the Hadoop input methods, or a
Scala ClassTag, already admits every key of that type, and replacing it would
drop array-key checks that apply today, for example distinct() on
binaryRecords(...).union(parallelize(...)). Keep the inferred tag equal to the
plain ClassTag of the same array class, so the array-key checks in
PairRDDFunctions, serializer choice and array allocation for RDDs derived from
one parallelizePairs result behave as they do now, and do not change which
lists parallelizePairs specializes.
**Exclusions:**
- A caller that passes an unrelated RDD to the public wrapRDD still gets the
receiver's tag; closing that route needs a separate guard-hint design.
- Detecting array keys inside a union that mixes key classes is out of
scope, since the Object-tagged operand carries no key-class information.
**Success:** A union, JavaSparkContext.union, cogroup, groupWith,
fullOuterJoin or rightOuterJoin result that combines an RDD whose key tag
parallelizePairs inferred with an RDD whose key tag differs carries the Object
key tag, so keys().collect(), take(), first(), glom(), caching and sortByKey on
it handle every key; the same holds for JavaRDD.union and
JavaSparkContext.union over keys() of such an RDD. Combining RDDs that all
carry the same array key tag keeps that tag, so partitionBy with a
HashPartitioner and the other array-key checks still fail fast on the result. A
parallelizePairs RDD with homogeneous array keys, and RDDs derived from it
alone, still reject partitionBy, join, cogroup and subtractByKey with
UNSUPPORTED_ARRAY_KEY.HASH_PARTITIONER. A combining operation whose reused tag
did not come from the inference in parallelizePairs keeps that tag as it does
now, so a union whose receiver carries an explicit array tag, for example from
binaryRecords or fromJavaRDD(rdd, b
yte[].class), still fails fast in distinct() or partitionBy(new
HashPartitioner(n)) when the other operand is Object-tagged.
**Verification:**
- **Regression:** With a JavaPairRDD<Object, Integer> from parallelizePairs
whose only keys are byte[] and another whose keys are Strings, keys().collect()
on their union, on JavaSparkContext.union of the two, on their union after
filter on the byte[] side, and on their cogroup, fullOuterJoin and
rightOuterJoin under a non-hash partitioner returns every key instead of
throwing ArrayStoreException, count() after keys().cache() on their union
succeeds, and the same holds for keys() of the byte[] RDD unioned with a
JavaRDD of Strings.
- **Behavior:** The union of two parallelizePairs RDDs whose keys are all
byte[] still fails partitionBy(new HashPartitioner(n)) with
UNSUPPORTED_ARRAY_KEY.HASH_PARTITIONER, and the existing array-key and
heterogeneous-key Java API tests still pass.
- **Compatibility:** Combining JavaPairRDDs or JavaRDDs whose tags are
equal, including RDDs wrapped with explicit ClassTags, keeps that tag and
behaves as before, and an explicitly tagged array RDD, such as one from
fromJavaRDD(rdd, byte[].class) or its keys(), unioned as the receiver with an
Object-tagged RDD keeps its byte[] tag, so partitionBy(new HashPartitioner(n))
or distinct() on the result still fails with UNSUPPORTED_ARRAY_KEY.
##########
core/src/main/scala/org/apache/spark/rdd/PairRDDFunctions.scala:
##########
@@ -908,7 +908,10 @@ class PairRDDFunctions[K, V](self: RDD[(K, V)])
/**
* Return an RDD with the pairs from `this` whose keys are not in `other`.
*/
- def subtractByKey[W: ClassTag](other: RDD[(K, W)], p: Partitioner): RDD[(K,
V)] = self.withScope {
+ def subtractByKey[W: ClassTag](
+ other: RDD[(K, W)],
+ p: Partitioner): RDD[(K, V)] = self.withScope {
+ failOnHashPartitionerWithArrayKey(p)
Review Comment:
**Non-blocking (P2):** This closes the `subtractByKey` path, but
`OrderedRDDFunctions.repartitionAndSortWithinPartitions`
(OrderedRDDFunctions.scala:76-87) still builds `new ShuffledRDD[K, V, V](self,
partitioner)`, or takes its existing-partitioner shortcut, without this check,
and both `JavaPairRDD.repartitionAndSortWithinPartitions` overloads delegate to
it. With a `HashPartitioner`, array keys are partitioned by their identity hash
code (Partitioner.scala:118-121), so arrays with equal contents land in
different partitions, which breaks the secondary-sort pattern this operation is
meant for. After this PR it is the one key-partitioned shuffle among the pair
operations that skips the check: on a `parallelizePairs` RDD with `byte[]`
keys, `partitionBy(new HashPartitioner(2))` now throws while
`repartitionAndSortWithinPartitions(new HashPartitioner(2), comp)` is accepted,
so a caller whose `partitionBy` starts failing can switch to it and silently
get identity-based partitioning.
Running the same check before both branches, as `partitionBy` does, closes
it; since `failOnHashPartitionerWithArrayKey` is private to `PairRDDFunctions`,
a shared `private[spark]` helper would let both classes call one check.
**Verification:**
- **Regression:** repartitionAndSortWithinPartitions(new HashPartitioner(n))
fails with UNSUPPORTED_ARRAY_KEY.HASH_PARTITIONER on a Scala RDD with Array
keys and an Ordering, and on a JavaPairRDD from parallelizePairs with byte[]
keys and a comparator.
- **Compatibility:** repartitionAndSortWithinPartitions with a custom
partitioner on array keys, and with a HashPartitioner on non-array keys, still
repartitions and sorts as before.
##########
core/src/test/scala/org/apache/spark/PartitioningSuite.scala:
##########
@@ -243,6 +243,9 @@ class PartitioningSuite extends SparkFunSuite with
SharedSparkContext with Priva
verify("HASH_PARTITIONER")(arrPairs.cogroup(arrPairs))
verify("HASH_PARTITIONER")(arrPairs.cogroup(arrPairs, arrPairs))
verify("HASH_PARTITIONER")(arrPairs.cogroup(arrPairs, arrPairs, arrPairs))
+ verify("HASH_PARTITIONER")(arrPairs.subtractByKey(arrPairs))
Review Comment:
**Nit (P3):** The new check also changes `RDD.subtract`: all three overloads
run `this.map(x => (x, null)).subtractByKey(other.map((_, null)), p)` with the
element tag as the key tag, and use a `HashPartitioner` unless the RDD already
has a partitioner or the caller passes one (RDD.scala:1158-1190). So
`arrs.subtract(arrs)` now throws `UNSUPPORTED_ARRAY_KEY.HASH_PARTITIONER` where
it used to silently return every element, and so does Java
`keys().subtract(...)` on a pair RDD with an array key tag. Neither this suite
nor `JavaAPISuite` runs `subtract` on arrays, so this behavior could regress
unnoticed; adding `verify("HASH_PARTITIONER")(arrs.subtract(arrs))` here, plus
the partition-count and `HashPartitioner` overloads, would pin it. Similarly,
`fromJavaRDD(rdd, byte[].class)` is only used for the four `assertThrows`
checks, so a test that its `collect()`, `keys().collect()` and
`values().collect()` return the input pairs would catch a regression such as
also tagging the values w
ith `keyClass`.
**Verification:**
- **Regression:** subtract on an RDD whose elements are arrays fails with
UNSUPPORTED_ARRAY_KEY.HASH_PARTITIONER through the default, explicit
partition-count and explicit HashPartitioner overloads, and JavaRDD.subtract on
keys() of a parallelizePairs RDD with byte[] keys fails the same way.
- **Behavior:** The RDD built by fromJavaRDD(rdd, byte[].class) returns the
input pairs from collect() and the matching keys and values from
keys().collect() and values().collect().
##########
core/src/main/scala/org/apache/spark/api/java/JavaPairRDD.scala:
##########
@@ -1081,4 +1081,12 @@ object JavaPairRDD {
new JavaPairRDD[K, V](rdd.rdd)
}
+ /** Convert a JavaRDD of key-value pairs to JavaPairRDD with an explicit key
class. */
Review Comment:
**Nit (P3):** This is the doc Java users see for the new overload, but it
does not say what `keyClass` controls. It becomes the key `ClassTag`, so an
array class makes `partitionBy`, `join`, `cogroup`, `subtractByKey` and the
map-side-combine operations fail fast with `UNSUPPORTED_ARRAY_KEY`, which is
why the overload exists, and it also types the arrays that `keys()` actions
build. The doc should also require the keys' runtime reference class: Java
types `int.class` as `Class<Integer>`, so `fromJavaRDD(rdd, int.class)`
compiles and yields a primitive key tag whose arrays cannot hold a null key.
Noting that the value class stays erased would complete it. The version appears
only in `@Since("4.4.0")`, which `Since.scala` says does not show up in the
generated Java API documentation; the `filterByRange` members of this class
pair `@Since` with an `@since` doc tag, so adding `@since 4.4.0` here would
match.
**Verification:**
- **Inspection:** The overload's doc comment describes keyClass's effect on
the array-key checks, requires the keys' runtime reference class, notes that
the value class stays erased, and includes an @since 4.4.0 tag consistent with
its @Since annotation.
--
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]