peter-toth commented on code in PR #55885:
URL: https://github.com/apache/spark/pull/55885#discussion_r4630042147


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -87,64 +183,269 @@ case class TransformExpression(
    * It compares the transforms only. A caller that compares partition keys 
has to consult
    * `reducedWith` as well, since a reduced key space is not the one its 
transform names.
    *
+   * Two transforms are the same when they have the same function name, the 
same arity, and each
+   * pair of corresponding children matches:
+   *   - literal arguments must be equal (e.g. numBuckets for bucket, width 
for truncate), so that
+   *     `bucket(32, c)` is not the same as `bucket(16, c)`;
+   *   - nested transform arguments must recursively be the same function, so 
that
+   *     `bucket(4, years(c))` is not the same as `bucket(4, days(c))`;
+   *   - a bare column must face a bare column. Which column is intentionally 
ignored (it is
+   *     reconciled separately, via `keyPositions`);
+   *   - any other argument must be the same expression of its one column, so 
that
+   *     `bucket(4, c + 1)` is the same as `bucket(4, d + 1)` but not as 
`bucket(4, c + 2)` or
+   *     `bucket(4, c)`. An argument over several columns, or a 
non-deterministic one, leaves a
+   *     transform with no identity, so it is not the same as anything.
+   *
+   * The comparison is of [[functionId]], which is per position rather than a 
set of literal
+   * values. Comparing only the values would make `truncate(id, 2)` and 
`truncate(2, store_id)` the
+   * same function; `isCompatible` short-circuits on this method, so 
`sameArgumentLayout` -- which
+   * guards exactly that, but only inside `reducerOutcome` -- would never run, 
and the pair would be
+   * paired as-is with no reduce. `hasSameReducedKeys` compares the same 
identity, so the two never
+   * disagree about which transforms are the same.
+   *
    * @param other the transform expression to compare to
    * @return true if this and `other` has the same semantics w.r.t to 
transform, false otherwise.
    */
-  def isSameFunction(other: TransformExpression): Boolean = functionId == 
other.functionId
+  def isSameFunction(other: TransformExpression): Boolean =
+    functionId.isDefined && functionId == other.functionId
 
   /**
    * Whether this [[TransformExpression]]'s function is compatible with the 
`other`
    * [[TransformExpression]]'s function.
    *
-   * This is true if both are instances of [[ReducibleFunction]] and there 
exists a [[Reducer]] r(x)
-   * such that r(t1(x)) = t2(x), or r(t2(x)) = t1(x), for all input x.
+   * This is true if both are the same function, or if [[pairReducers]] finds 
a reducer in either
+   * direction: both are instances of [[ReducibleFunction]], their arguments 
line up, both sides
+   * have an identity, neither direction threw, and a reducer in one direction 
comes with an answer
+   * from the other. So it is false for a pair the connector could reduce but 
Spark does not trust.
    *
    * @param other the transform expression to compare to
    * @return true if compatible, false if not
    */
-  def isCompatible(other: TransformExpression): Boolean = {
-    if (isSameFunction(other)) {
-      true
-    } else {
-      (function, other.function) match {
-        case (f: ReducibleFunction[_, _], o: ReducibleFunction[_, _]) =>
-          val thisReducer = reducer(f, numBucketsOpt, o, other.numBucketsOpt)
-          val otherReducer = reducer(o, other.numBucketsOpt, f, numBucketsOpt)
-          thisReducer.isDefined || otherReducer.isDefined
-        case _ => false
-      }
+  def isCompatible(other: TransformExpression): Boolean =
+    isSameFunction(other) || {
+      val (r1, r2) = pairReducers(other)
+      r1.isDefined || r2.isDefined
+    }
+
+  /**
+   * Extract all literal parameters of this transform as V2 [[V2Literal]]s, 
preserving each value's
+   * internal representation and its `DataType`, with no coercion. The 
generalized reducer is asked
+   * only when they match the declared input types 
([[literalParamsMatchInputTypes]]); the
+   * deprecated one reads a single `IntegerType` parameter as an `Int`. 
Memoized.
+   *
+   * Examples:
+   *   bucket(4, col)        => [Literal(4, IntegerType)]
+   *   truncate(col, 3)      => [Literal(3, IntegerType)]
+   *   days(col)             => []  (no literals)
+   */
+  private lazy val extractParameters: Array[V2Literal[_]] =
+    literalChildren.map(l => LiteralValue(l.value, l.dataType): 
V2Literal[_]).toArray
+
+  /**
+   * Whether every literal parameter has the type the bound function declares 
at its position in
+   * `inputTypes()`. Asked before the generalized reducer, which gets the 
literals' values without
+   * Analyzer type coercion: a literal of another type (a legal implicit cast 
under
+   * [[BoundFunction]]) would be handed to a connector that reads it as the 
declared type. Then the
+   * generalized overload counts as not implemented, and the other overloads, 
which read no literal
+   * by type, may still be asked. A literal past the declared arity has no 
declared type to compare
+   * against, e.g. for an arity-flexible function. Column arguments are not 
checked, since they are
+   * not passed to the connector; where Spark evaluates a transform, 
[[evaluableFunction]] checks
+   * every argument. A transform with no literal parameter has nothing to 
check, so the connector's
+   * `inputTypes()` is not called for it, as master never called it on this 
path.
+   */
+  lazy val literalParamsMatchInputTypes: Boolean = literalChildren.isEmpty || {
+    val declaredTypes = function.inputTypes()
+    children.zipWithIndex.forall {
+      case (l: Literal, i) => i >= declaredTypes.length || l.dataType == 
declaredTypes(i)
+      case _ => true
     }
   }
 
   /**
-   * Return a [[Reducer]] for this transform expression on another
-   * on the transform expression.
-   * <p>
-   * A [[Reducer]] exists for a transform expression function if it is
-   * 'reducible' on the other expression function.
-   * <p>
-   * @return reducer function or None if not reducible on the other transform 
expression
+   * Whether each position holds a literal on both sides, a bare column on 
both sides, the same
+   * nested transform on both sides, or the same expression of one column on 
both sides (e.g.
+   * `b + 1` and `c + 1`, or `s.a` and `t.a`). These are the shapes 
[[functionId]] tells apart, and
+   * a nested transform is compared as it does, by identity, so two instances 
of one function bound
+   * for two scans line up. A pair this admits differs at most in literal 
values and arity, which
+   * the connector reducer decides.
+   */
+  private def sameArgumentLayout(other: TransformExpression): Boolean =
+    children.zip(other.children).forall {
+      case (_: Literal, _: Literal) => true
+      case (_: Attribute, _: Attribute) => true
+      case (t1: TransformExpression, t2: TransformExpression) => 
t1.isSameFunction(t2)
+      case (c1, c2) => TransformExpression.sameShape(c1, c2)
+    }
+
+  /**
+   * Whether no literal parameter is null or has an array, map, struct or UDT 
type; those are not
+   * passed to a connector reducer. Other scalars, such as intervals, are.
+   */
+  private def literalParamsPassable: Boolean =
+    literalChildren.forall(l => l.value != null && (l.dataType match {
+      case _: ArrayType | _: MapType | _: StructType | _: UserDefinedType[_] 
=> false
+      case _ => true
+    }))
+
+  /**
+   * Return a [[Reducer]] that maps this transform's partition keys onto 
`other`'s, or None if there
+   * is none: when either function is not a [[ReducibleFunction]], when the 
argument layouts or
+   * literal parameters rule a reducer out, or when the connector reports it 
is not reducible.
+   * Handles both parameterized (bucket, truncate) and non-parameterized 
(days, hours) functions.
+   *
+   * This answers one direction only, so it must not decide a pair: a 
direction that threw would
+   * look merely not reducible, and the other direction like a one-side 
reduce. Use
+   * [[pairReducers]].
+   */
+  private[sql] def reducers(other: TransformExpression): Option[Reducer[_, _]] 
=
+    TransformExpression.reducerOf(reducerOutcome(other))
+
+  /**
+   * Both directions' reducers, `reducers(other)` and `other.reducers(this)`, 
or `(None, None)` when
+   * either direction's reducer threw: then the pair is not reducible at all 
and shuffles. Reading a
+   * thrown direction as merely "not reducible" would leave the other 
direction looking like a
+   * one-side reduce, which is only right for a reducer that satisfies 
`r(f1(x)) = f2(x)`; a
+   * two-sided one such as a gcd of bucket counts would then pair keys from 
two different spaces.
+   *
+   * For the same reason, a reducer in one direction counts only if the other 
direction answered,
+   * by returning a reducer or `null`. A direction that implements no reducer, 
or was not asked
+   * because its literal types differ, says nothing about whether this one is 
one-sided, so the
+   * pair is `(None, None)` too.
+   *
+   * Also `(None, None)` when either side has no identity, since a reduce 
could be neither recorded
+   * (`reducedTogetherWith`) nor reported for it. `sameArgumentLayout` already 
refuses every such
+   * pair; deciding it here keeps `isCompatible` and `reducersBothWays` from 
disagreeing on one.
+   *
+   * A pair is decided once: the answer is kept on both expressions, the other 
side's swapped, so
+   * `isCompatible`, which admits a pair, and `reducersBothWays`, which then 
reduces it, read the
+   * same one. Asking the connector again could get another answer, e.g. a 
failure that does not
+   * repeat, or `null` for one side where both reduced, and the reduce would 
then not be the one
+   * the pair was admitted on.
+   */
+  def pairReducers(other: TransformExpression)
+      : (Option[Reducer[_, _]], Option[Reducer[_, _]]) = {
+    val known = decidedPairs.get(other)
+    if (known != null) return known
+    val decided = decidePair(other)
+    decidedPairs.putIfAbsent(other, decided)
+    other.decidedPairs.putIfAbsent(this, decided.swap)
+    decidedPairs.get(other)
+  }
+
+  /**
+   * The pairs [[pairReducers]] decided, by the other side. Not serialized: an 
executor never
+   * decides a pair.
    */
-  def reducers(other: TransformExpression): Option[Reducer[_, _]] = {
-    (function, other.function) match {
-      case(e1: ReducibleFunction[_, _], e2: ReducibleFunction[_, _]) =>
-        reducer(e1, numBucketsOpt, e2, other.numBucketsOpt)
-      case _ => None
+  @transient private lazy val decidedPairs =
+    new ConcurrentHashMap[TransformExpression, (Option[Reducer[_, _]], 
Option[Reducer[_, _]])]()

Review Comment:
   **Finding 41.** This is the memo I suggested as the first option in 30 
([r4589254158](https://github.com/apache/spark/pull/55885#discussion_r4589254158)).
 Each entry holds the other side's transform, `pairReducers` adds one on both 
sides, and nothing removes one. So it grows while one of the two transforms 
outlives its query.
   
   `InMemoryTableScanExec.outputPartitioning` passes the cached plan's own 
transform on as it is when the relation's output equals the cached plan's. That 
is the case for a DataFrame over a `DataSourceV2Relation` with no qualifier, 
such as one from `spark.read.format(...).load()`. Each join planned against it 
then adds an entry, keyed by that query's transform. What I ran: a `bucket(4, 
id)` table read through `DataSourceV2Relation.create` with no qualifier, 
cached, then joined four times with a fresh `spark.table` scan of a `bucket(2, 
id)` table, under `allowCompatibleTransforms`. Every join returns all 16 rows 
with no shuffle, and the cached transform's map holds 1, 2, 3 and 4 entries, 
with AQE on and off. Master has no memo.
   
   Weak keys would bound it, but I'd rather remove what needs it. The memo, the 
veto in `decidePair`, `Threw` with its `ownCode`, and the `guarded` calls all 
handle a connector that fails or changes its answer:
   - Master lets a reducer's exception fail the query, and expects the 
connector to answer the same way each time.
   - This PR catches connector failures and makes the pair not reducible. 12, 
30 and 37 each fixed a case that exists only because of that catch, so this 
reverses what I asked for there. Sorry for the back and forth.
   - The evaluate path has caught connector failures since #59760. But it 
decides per expression, in a `lazy val`, so it holds one answer per expression 
and does not grow.
   
   Keeping `UnsupportedOperationException` as "not implemented", which the 
dispatch needs, and letting anything else through as master does, removes all 
of it. I tried that on this head: `guarded` evaluates its argument as it is, 
and `pairReducers` calls `decidePair` directly. Catalyst stays green, and in 
`sql` only the nine tests that pin this handling fail:
   - "a non-UOE reducer exception is logged and treated as not reducible"
   - "connector code that fails while deciding a pair makes it not reducible"
   - "a pair asks the connector once, whichever side asks"
   - "a pair is decided from one answer of the connector"
   - "a reducer that throws in one direction makes the pair not reducible"
   - "a connector failure is reported against the function whose code threw"
   - "a reducer that throws for a pair of the same function is not reported"
   - "a reducer warning is logged once per function"
   - "a throwing generalized overload is surfaced, not masked by the deprecated 
one"
   
   The last one still holds, since the exception now surfaces as the query's 
failure, so it can become an `intercept`. `logReducerThrew`, the fixtures 
behind these tests, and the description's "rather than failing the query" and 
"decided once" sentences go too.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2670,13 +2674,18 @@ case class KeyedShuffleSpec(
         val columnType = te.references.head.dataType
         positionSet.iterator.map(clustering)
           .find(key => !TransformExpression.keysStoredAlike(key.dataType, 
columnType))
-          .orElse(Option.when(!canEvaluate(t))(t.children.head))
+          // The key the transform was rebuilt over is its column argument; 
its other children
+          // are literal parameters.
+          .orElse(Option.when(!canEvaluate(t))(t.columnSlots.head))
           .foreach { key =>
             // `name()` and `inputTypes()` are connector code, which must not 
replace this error.
             val functionClass = t.function.getClass.getName
             val name = TransformExpression.orElse(t.function.name(), 
functionClass)
             throw 
QueryExecutionErrors.storagePartitionJoinKeyTypeMismatchError(
-              t.numBucketsOpt.fold(name)(n => s"$name($n)"),
+              t.literalChildren.map(_.value) match {

Review Comment:
   **Finding 42.** `_.value` is the internal value, so a `DATE` parameter 
prints as days since the epoch, and a `BINARY` one as an array reference. `DATE 
'2020-01-01'` and `X'0102'` print as `18262, [B@567d830f`. `.sql` prints them 
as they are written, and still gives `bucket(4)` for a bucket count. Before 
this PR, only the `INT` bucket count reached this message. With `.sql`, 
`EnsureRequirementsSuite` passes, including the cases that expect `bucket(4)`.
   
   ```suggestion
                 t.literalChildren.map(_.sql) match {
   ```
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -87,64 +183,269 @@ case class TransformExpression(
    * It compares the transforms only. A caller that compares partition keys 
has to consult
    * `reducedWith` as well, since a reduced key space is not the one its 
transform names.
    *
+   * Two transforms are the same when they have the same function name, the 
same arity, and each
+   * pair of corresponding children matches:
+   *   - literal arguments must be equal (e.g. numBuckets for bucket, width 
for truncate), so that
+   *     `bucket(32, c)` is not the same as `bucket(16, c)`;
+   *   - nested transform arguments must recursively be the same function, so 
that
+   *     `bucket(4, years(c))` is not the same as `bucket(4, days(c))`;
+   *   - a bare column must face a bare column. Which column is intentionally 
ignored (it is
+   *     reconciled separately, via `keyPositions`);
+   *   - any other argument must be the same expression of its one column, so 
that
+   *     `bucket(4, c + 1)` is the same as `bucket(4, d + 1)` but not as 
`bucket(4, c + 2)` or
+   *     `bucket(4, c)`. An argument over several columns, or a 
non-deterministic one, leaves a
+   *     transform with no identity, so it is not the same as anything.
+   *
+   * The comparison is of [[functionId]], which is per position rather than a 
set of literal
+   * values. Comparing only the values would make `truncate(id, 2)` and 
`truncate(2, store_id)` the
+   * same function; `isCompatible` short-circuits on this method, so 
`sameArgumentLayout` -- which
+   * guards exactly that, but only inside `reducerOutcome` -- would never run, 
and the pair would be
+   * paired as-is with no reduce. `hasSameReducedKeys` compares the same 
identity, so the two never
+   * disagree about which transforms are the same.
+   *
    * @param other the transform expression to compare to
    * @return true if this and `other` has the same semantics w.r.t to 
transform, false otherwise.
    */
-  def isSameFunction(other: TransformExpression): Boolean = functionId == 
other.functionId
+  def isSameFunction(other: TransformExpression): Boolean =
+    functionId.isDefined && functionId == other.functionId
 
   /**
    * Whether this [[TransformExpression]]'s function is compatible with the 
`other`
    * [[TransformExpression]]'s function.
    *
-   * This is true if both are instances of [[ReducibleFunction]] and there 
exists a [[Reducer]] r(x)
-   * such that r(t1(x)) = t2(x), or r(t2(x)) = t1(x), for all input x.
+   * This is true if both are the same function, or if [[pairReducers]] finds 
a reducer in either
+   * direction: both are instances of [[ReducibleFunction]], their arguments 
line up, both sides
+   * have an identity, neither direction threw, and a reducer in one direction 
comes with an answer
+   * from the other. So it is false for a pair the connector could reduce but 
Spark does not trust.
    *
    * @param other the transform expression to compare to
    * @return true if compatible, false if not
    */
-  def isCompatible(other: TransformExpression): Boolean = {
-    if (isSameFunction(other)) {
-      true
-    } else {
-      (function, other.function) match {
-        case (f: ReducibleFunction[_, _], o: ReducibleFunction[_, _]) =>
-          val thisReducer = reducer(f, numBucketsOpt, o, other.numBucketsOpt)
-          val otherReducer = reducer(o, other.numBucketsOpt, f, numBucketsOpt)
-          thisReducer.isDefined || otherReducer.isDefined
-        case _ => false
-      }
+  def isCompatible(other: TransformExpression): Boolean =
+    isSameFunction(other) || {
+      val (r1, r2) = pairReducers(other)
+      r1.isDefined || r2.isDefined
+    }
+
+  /**
+   * Extract all literal parameters of this transform as V2 [[V2Literal]]s, 
preserving each value's
+   * internal representation and its `DataType`, with no coercion. The 
generalized reducer is asked
+   * only when they match the declared input types 
([[literalParamsMatchInputTypes]]); the
+   * deprecated one reads a single `IntegerType` parameter as an `Int`. 
Memoized.
+   *
+   * Examples:
+   *   bucket(4, col)        => [Literal(4, IntegerType)]
+   *   truncate(col, 3)      => [Literal(3, IntegerType)]
+   *   days(col)             => []  (no literals)
+   */
+  private lazy val extractParameters: Array[V2Literal[_]] =
+    literalChildren.map(l => LiteralValue(l.value, l.dataType): 
V2Literal[_]).toArray
+
+  /**
+   * Whether every literal parameter has the type the bound function declares 
at its position in
+   * `inputTypes()`. Asked before the generalized reducer, which gets the 
literals' values without
+   * Analyzer type coercion: a literal of another type (a legal implicit cast 
under
+   * [[BoundFunction]]) would be handed to a connector that reads it as the 
declared type. Then the
+   * generalized overload counts as not implemented, and the other overloads, 
which read no literal
+   * by type, may still be asked. A literal past the declared arity has no 
declared type to compare
+   * against, e.g. for an arity-flexible function. Column arguments are not 
checked, since they are
+   * not passed to the connector; where Spark evaluates a transform, 
[[evaluableFunction]] checks
+   * every argument. A transform with no literal parameter has nothing to 
check, so the connector's
+   * `inputTypes()` is not called for it, as master never called it on this 
path.
+   */
+  lazy val literalParamsMatchInputTypes: Boolean = literalChildren.isEmpty || {
+    val declaredTypes = function.inputTypes()
+    children.zipWithIndex.forall {
+      case (l: Literal, i) => i >= declaredTypes.length || l.dataType == 
declaredTypes(i)
+      case _ => true
     }
   }
 
   /**
-   * Return a [[Reducer]] for this transform expression on another
-   * on the transform expression.
-   * <p>
-   * A [[Reducer]] exists for a transform expression function if it is
-   * 'reducible' on the other expression function.
-   * <p>
-   * @return reducer function or None if not reducible on the other transform 
expression
+   * Whether each position holds a literal on both sides, a bare column on 
both sides, the same
+   * nested transform on both sides, or the same expression of one column on 
both sides (e.g.
+   * `b + 1` and `c + 1`, or `s.a` and `t.a`). These are the shapes 
[[functionId]] tells apart, and
+   * a nested transform is compared as it does, by identity, so two instances 
of one function bound
+   * for two scans line up. A pair this admits differs at most in literal 
values and arity, which
+   * the connector reducer decides.
+   */
+  private def sameArgumentLayout(other: TransformExpression): Boolean =
+    children.zip(other.children).forall {
+      case (_: Literal, _: Literal) => true
+      case (_: Attribute, _: Attribute) => true
+      case (t1: TransformExpression, t2: TransformExpression) => 
t1.isSameFunction(t2)
+      case (c1, c2) => TransformExpression.sameShape(c1, c2)
+    }
+
+  /**
+   * Whether no literal parameter is null or has an array, map, struct or UDT 
type; those are not
+   * passed to a connector reducer. Other scalars, such as intervals, are.
+   */
+  private def literalParamsPassable: Boolean =
+    literalChildren.forall(l => l.value != null && (l.dataType match {
+      case _: ArrayType | _: MapType | _: StructType | _: UserDefinedType[_] 
=> false
+      case _ => true
+    }))
+
+  /**
+   * Return a [[Reducer]] that maps this transform's partition keys onto 
`other`'s, or None if there
+   * is none: when either function is not a [[ReducibleFunction]], when the 
argument layouts or
+   * literal parameters rule a reducer out, or when the connector reports it 
is not reducible.
+   * Handles both parameterized (bucket, truncate) and non-parameterized 
(days, hours) functions.
+   *
+   * This answers one direction only, so it must not decide a pair: a 
direction that threw would
+   * look merely not reducible, and the other direction like a one-side 
reduce. Use
+   * [[pairReducers]].
+   */
+  private[sql] def reducers(other: TransformExpression): Option[Reducer[_, _]] 
=
+    TransformExpression.reducerOf(reducerOutcome(other))
+
+  /**
+   * Both directions' reducers, `reducers(other)` and `other.reducers(this)`, 
or `(None, None)` when
+   * either direction's reducer threw: then the pair is not reducible at all 
and shuffles. Reading a
+   * thrown direction as merely "not reducible" would leave the other 
direction looking like a
+   * one-side reduce, which is only right for a reducer that satisfies 
`r(f1(x)) = f2(x)`; a
+   * two-sided one such as a gcd of bucket counts would then pair keys from 
two different spaces.
+   *
+   * For the same reason, a reducer in one direction counts only if the other 
direction answered,
+   * by returning a reducer or `null`. A direction that implements no reducer, 
or was not asked
+   * because its literal types differ, says nothing about whether this one is 
one-sided, so the
+   * pair is `(None, None)` too.
+   *
+   * Also `(None, None)` when either side has no identity, since a reduce 
could be neither recorded
+   * (`reducedTogetherWith`) nor reported for it. `sameArgumentLayout` already 
refuses every such
+   * pair; deciding it here keeps `isCompatible` and `reducersBothWays` from 
disagreeing on one.
+   *
+   * A pair is decided once: the answer is kept on both expressions, the other 
side's swapped, so
+   * `isCompatible`, which admits a pair, and `reducersBothWays`, which then 
reduces it, read the
+   * same one. Asking the connector again could get another answer, e.g. a 
failure that does not
+   * repeat, or `null` for one side where both reduced, and the reduce would 
then not be the one
+   * the pair was admitted on.
+   */
+  def pairReducers(other: TransformExpression)
+      : (Option[Reducer[_, _]], Option[Reducer[_, _]]) = {
+    val known = decidedPairs.get(other)
+    if (known != null) return known
+    val decided = decidePair(other)
+    decidedPairs.putIfAbsent(other, decided)
+    other.decidedPairs.putIfAbsent(this, decided.swap)
+    decidedPairs.get(other)
+  }
+
+  /**
+   * The pairs [[pairReducers]] decided, by the other side. Not serialized: an 
executor never
+   * decides a pair.
    */
-  def reducers(other: TransformExpression): Option[Reducer[_, _]] = {
-    (function, other.function) match {
-      case(e1: ReducibleFunction[_, _], e2: ReducibleFunction[_, _]) =>
-        reducer(e1, numBucketsOpt, e2, other.numBucketsOpt)
-      case _ => None
+  @transient private lazy val decidedPairs =
+    new ConcurrentHashMap[TransformExpression, (Option[Reducer[_, _]], 
Option[Reducer[_, _]])]()
+
+  private def decidePair(other: TransformExpression)
+      : (Option[Reducer[_, _]], Option[Reducer[_, _]]) = {
+    import TransformExpression._
+    if (functionId.isEmpty || other.functionId.isEmpty) return (None, None)
+    (reducerOutcome(other), other.reducerOutcome(this)) match {
+      case (Threw(_, _), _) | (_, Threw(_, _)) => (None, None)
+      case (Reducible(_), Unimplemented | LiteralTypesDiffer) |
+           (Unimplemented | LiteralTypesDiffer, Reducible(_)) => (None, None)
+      case (o1, o2) => (reducerOf(o1), reducerOf(o2))
     }
   }
 
-  // Return a Reducer for a reducible function on another reducible function
-  private def reducer(
-      thisFunction: ReducibleFunction[_, _],
-      thisNumBucketsOpt: Option[Int],
-      otherFunction: ReducibleFunction[_, _],
-      otherNumBucketsOpt: Option[Int]): Option[Reducer[_, _]] = {
-    val res = (thisNumBucketsOpt, otherNumBucketsOpt) match {
-      case (Some(numBuckets), Some(otherNumBuckets)) =>
-        thisFunction.reducer(numBuckets, otherFunction, otherNumBuckets)
-      case _ => thisFunction.reducer(otherFunction)
+  /** What probing the connector for a reducer onto `other` gave, logged when 
it failed. */
+  private def reducerOutcome(other: TransformExpression): 
TransformExpression.Outcome = {
+    import TransformExpression._
+    val thisFunction: ReducibleFunction[_, _] = function match {
+      case f: ReducibleFunction[_, _] => f
+      case _ => return NotReducible
+    }
+    val otherFunction: ReducibleFunction[_, _] = other.function match {
+      case o: ReducibleFunction[_, _] => o
+      case _ => return NotReducible
+    }
+    if (!sameArgumentLayout(other) || !literalParamsPassable || 
!other.literalParamsPassable) {
+      return NotReducible
+    }
+
+    val thisParams = extractParameters
+    val otherParams = other.extractParameters
+    val thisName = function.canonicalName()
+
+    // A single IntegerType parameter on each side is the shape the deprecated
+    // reducer(int, ..., int) overload accepts. Null parameters were refused 
above.
+    def isSingleInt(p: Array[V2Literal[_]]): Boolean = {
+      p.length == 1 && p(0).dataType == IntegerType
+    }
+
+    // Connector code that throws, a `LinkageError` included, e.g. a 
`NoClassDefFoundError` for a
+    // missing dependency, makes the outcome `Threw`, so the pair is not 
reducible rather than
+    // failing the query. `Try` alone would let a `LinkageError` through. 
`ownCode` says whose code
+    // it is, see `Threw`.
+    def guarded(outcome: => Outcome, ownCode: Boolean = true): Outcome =
+      try outcome catch {
+        case e @ (NonFatal(_) | _: LinkageError) => Threw(e, ownCode)
+      }
+
+    // Probe one reducer overload into an Outcome. Pure -- logging is decided 
once, below.
+    def probe(call: => Reducer[_, _]): Outcome = guarded {
+      try Option(call).fold[Outcome](NotReducible)(Reducible(_)) catch {
+        case _: UnsupportedOperationException => Unimplemented
+      }
+    }
+
+    // Prefer the generalized overload. It reads its literal parameters by 
type, so it is asked only
+    // when they have their declared types; otherwise it counts as not 
implemented. Use another
+    // overload only if the generalized one is not implemented; any other 
outcome is final. The type
+    // check reads the connector's `inputTypes()`, so it is guarded too.
+    val outcome =
+      guarded {
+        if (!literalParamsMatchInputTypes) {
+          LiteralTypesDiffer
+        } else {
+          // The other side's check runs the other connector's code. A failure 
there is that
+          // side's to report, which the other direction does when it asks; 
here it only vetoes
+          // the pair. `probe` guards the reducer call itself, as this side's 
code.
+          guarded(ownCode = false, outcome =
+            if (!other.literalParamsMatchInputTypes) {
+              LiteralTypesDiffer
+            } else {
+              // A copy of the memoized arrays per call, so a connector cannot 
change them.
+              probe(thisFunction.reducer(thisParams.clone(), otherFunction, 
otherParams.clone()))
+            })
+        }
+      } match {
+        // A parameterless pair falls back to the parameterless overload.
+        case Unimplemented if thisParams.isEmpty && otherParams.isEmpty =>
+          probe(thisFunction.reducer(otherFunction))
+        // The deprecated overload is documented for bucket against bucket, 
and master offered it
+        // only a pair resolved from two V2 `bucket` transforms, see 
`fromBucketTransform`. Same
+        // function means the same canonical name, or the same function where 
it keeps
+        // `canonicalName()`'s default, a fresh name on every call.
+        // If that finds nothing either, the outcome stays why the generalized 
one was not asked.
+        case skipped @ (Unimplemented | LiteralTypesDiffer)
+            if fromBucketTransform && other.fromBucketTransform &&
+              isSingleInt(thisParams) && isSingleInt(otherParams) &&
+              (thisName == other.function.canonicalName() || function == 
other.function) =>

Review Comment:
   **Finding 43.** `22cd902c0d4` added this check so that the deprecated 
overload is offered only a pair of bucket transforms, as on master, before 
`fromBucketTransform` existed. `fromBucketTransform` on both sides now says 
exactly what master's `numBucketsOpt` said, so this check only narrows it 
further. Two different functions, each resolved from a V2 `bucket`, were 
offered `reducer(int, ReducibleFunction, int)` on master, and shuffle here. 
What it protects is a connector that does not check `otherBucketFunction`, 
which master did not guard against either. The `function == other.function` arm 
exists only because of it (32).
   
   Dropping the check keeps master's behaviour. I tried it on this head: the 
only test that fails is "the deprecated int reducer is only offered a pair of 
the same function", which pins it. `thisName`, the comment above, 
`CarelessLegacyBucketFunction`, `CarelessLookalikeFunction` and the 
description's "two different bucket functions" sentence can go too.
   
   ```suggestion
               if fromBucketTransform && other.fromBucketTransform &&
                 isSingleInt(thisParams) && isSingleInt(otherParams) =>
   ```
   



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