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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/QueryPlanConstraints.scala:
##########
@@ -126,6 +128,232 @@ trait ConstraintHelper {
     inferred -- constraints
   }
 
+  /**
+   * Infers additional constraints for a given set of constraints by combining 
the equality-based
+   * inferences above ([[inferAdditionalConstraints]], 
[[inferConstraintsFromLiteralBindings]])
+   * with transitive inequality chaining ([[inferInequalityConstraints]]).
+   *
+   * One round of the equality passes is followed by one inequality pass so 
the latter can chain
+   * through equality-derived edges and bounds. Non-literal equalities are 
deliberately not used
+   * as chaining edges in [[inferInequalityConstraints]] and the equality 
passes are not re-run on
+   * the inferred inequalities, so multi-hop equality chains (e.g.
+   * `a = c AND c = d AND d < b AND b < 5`) may leave a bound on `a` 
uninferred without further
+   * optimization rounds.
+   */
+  def inferAllAdditionalConstraints(constraints: ExpressionSet): ExpressionSet 
= {
+    val equalityInferred =
+      inferAdditionalConstraints(constraints) ++ 
inferConstraintsFromLiteralBindings(constraints)
+    equalityInferred ++ inferInequalityConstraints(constraints ++ 
equalityInferred)
+  }
+
+  /**
+   * True when `e` cannot raise an error during evaluation: a non-null 
literal, or an upcast of
+   * one admitted by [[UpCastRule.canUpCast]]. Used by 
[[inferInequalityConstraints]] to decide
+   * which literals are safe to treat as chain anchors without risking an ANSI 
eval failure.
+   * Arbitrary expressions (such as a parsing cast `CAST('abc' AS INT)` or 
arithmetic that can
+   * fail under ANSI) are excluded.
+   */
+  @tailrec
+  private def isSafeBoundLiteral(e: Expression): Boolean = e match {
+    case l: Literal => l.value != null

Review Comment:
   **Nit (P3):** This check is the only thing that keeps NULL literals out of 
the bound graph. CAST(NULL AS t) reaches it too, through the Cast arm, because 
canUpCast(NullType, _) is true. None of the tests this PR adds uses a NULL 
comparison operand, so removing or weakening the check would leave every test 
green. NULL comparisons can still be unfolded when constraints are computed, 
for example when EliminateOuterJoin reads a Filter's constraints before 
NullPropagation runs in the same batch. Without the check, a chain such as `b < 
a AND a < 'm' AND a < CAST(NULL AS STRING)` makes isTighter compare a null 
value with the string ordering and fail during optimization, and on primitive 
sites the null is compared as zero. A ConstraintPropagationSuite case that puts 
a NULL bound next to a valid one would pin the check.
   
   **Verification:**
   - **Regression:** With the NULL-literal exclusion removed, a chain such as 
`b < a AND a < 'm' AND a < CAST(NULL AS STRING)` fails the test, either by 
raising during constraint inference or by inferring a bound against NULL.
   - **Behavior:** With the exclusion in place, the same constraints infer `b < 
'm'`, and no inferred constraint compares against a NULL literal.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/QueryPlanConstraints.scala:
##########
@@ -126,6 +128,232 @@ trait ConstraintHelper {
     inferred -- constraints
   }
 
+  /**
+   * Infers additional constraints for a given set of constraints by combining 
the equality-based
+   * inferences above ([[inferAdditionalConstraints]], 
[[inferConstraintsFromLiteralBindings]])
+   * with transitive inequality chaining ([[inferInequalityConstraints]]).
+   *
+   * One round of the equality passes is followed by one inequality pass so 
the latter can chain
+   * through equality-derived edges and bounds. Non-literal equalities are 
deliberately not used
+   * as chaining edges in [[inferInequalityConstraints]] and the equality 
passes are not re-run on
+   * the inferred inequalities, so multi-hop equality chains (e.g.
+   * `a = c AND c = d AND d < b AND b < 5`) may leave a bound on `a` 
uninferred without further
+   * optimization rounds.
+   */
+  def inferAllAdditionalConstraints(constraints: ExpressionSet): ExpressionSet 
= {
+    val equalityInferred =
+      inferAdditionalConstraints(constraints) ++ 
inferConstraintsFromLiteralBindings(constraints)
+    equalityInferred ++ inferInequalityConstraints(constraints ++ 
equalityInferred)
+  }
+
+  /**
+   * True when `e` cannot raise an error during evaluation: a non-null 
literal, or an upcast of
+   * one admitted by [[UpCastRule.canUpCast]]. Used by 
[[inferInequalityConstraints]] to decide
+   * which literals are safe to treat as chain anchors without risking an ANSI 
eval failure.
+   * Arbitrary expressions (such as a parsing cast `CAST('abc' AS INT)` or 
arithmetic that can
+   * fail under ANSI) are excluded.
+   */
+  @tailrec
+  private def isSafeBoundLiteral(e: Expression): Boolean = e match {
+    case l: Literal => l.value != null
+    case Cast(child, toType, _, _) =>
+      UpCastRule.canUpCast(child.dataType, toType) && isSafeBoundLiteral(child)
+    case _ => false
+  }
+
+  private def hasBoundOperand(e: Expression): Boolean = e match {
+    case b: BinaryComparison => isSafeBoundLiteral(b.left) || 
isSafeBoundLiteral(b.right)
+    case _ => false
+  }
+
+  /**
+   * True when `e` is safe to copy into a newly inferred, single-side filter 
produced by
+   * [[inferInequalityConstraints]] without risking an error on rows that 
never evaluated it
+   * before: an attribute reference, or an upcast of one admitted by 
[[UpCastRule.canUpCast]].
+   * While some upcasts may lose precision (e.g. Long to Float/Double), 
relocation is sound
+   * because they cannot fail and reuse the existing Cast expression. 
Arbitrary expressions -- a

Review Comment:
   **Nit (P3):** This comment says admitted up-casts cannot fail, and 
isSafeBoundLiteral's Scaladoc says an admitted literal cannot raise an error 
during evaluation, but both guards accept whatever UpCastRule.canUpCast 
accepts. canUpCast admits DECIMAL(19,0) to BIGINT, because 
DecimalType.isTighterThan only checks that 19 is below the 20-digit decimal 
precision of BIGINT, yet under ANSI the cast raises CAST_OVERFLOW for 19-digit 
values above Long.MaxValue. It also admits DATE to timestamp, which overflows 
for dates outside the documented 0001-01-01 to 9999-12-31 range. A relocated 
`CAST(d AS BIGINT) < lit` never runs in default configurations, because 
UnwrapCastInBinaryComparison later rewrites it onto the uncast decimal, but 
that protection lives outside these guards. toBound has no such protection. 
Under ANSI, `(SELECT * FROM x WHERE d = 9999999999999999999) x RIGHT JOIN y ON 
x.k = y.k AND CAST(x.d AS BIGINT) < y.b` now fails during planning: literal 
binding turns the condition int
 o `CAST(9999999999999999999 AS BIGINT) < y.b`, and toBound evaluates that 
cast. The base branch plans this query and fails only if a key-matched pair 
evaluates the cast; the inner-join form already fails there. Excluding 
decimal-to-integral casts from both guards and stating the DATE-range 
assumption in both comments would make the documented contract hold.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/59258#discussion_r4237673518), 
[2](https://github.com/apache/spark/pull/59258#discussion_r4263386983), 
[3](https://github.com/apache/spark/pull/59258#discussion_r4263387034).
   
   **Verification:**
   - **Behavior:** Under ANSI, a chain such as `CAST(x.d AS BIGINT) < y.b AND 
y.b < 5` with x.d of type DECIMAL(19,0) infers no bound on x. A right outer 
join whose left side filters x.d to 9999999999999999999 and whose condition 
includes `CAST(x.d AS BIGINT) < y.b` plans without error, as on the base branch.
   - **Compatibility:** Widening casts such as INT to BIGINT and DATE to 
TIMESTAMP are still relocated and still infer their existing expected bounds.
   - **Inspection:** The comments on both guards state the admitted cast set 
and the documented-range assumption for datetime casts, without an 
unconditional no-failure claim.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/QueryPlanConstraints.scala:
##########
@@ -126,6 +128,232 @@ trait ConstraintHelper {
     inferred -- constraints
   }
 
+  /**
+   * Infers additional constraints for a given set of constraints by combining 
the equality-based
+   * inferences above ([[inferAdditionalConstraints]], 
[[inferConstraintsFromLiteralBindings]])
+   * with transitive inequality chaining ([[inferInequalityConstraints]]).
+   *
+   * One round of the equality passes is followed by one inequality pass so 
the latter can chain
+   * through equality-derived edges and bounds. Non-literal equalities are 
deliberately not used
+   * as chaining edges in [[inferInequalityConstraints]] and the equality 
passes are not re-run on
+   * the inferred inequalities, so multi-hop equality chains (e.g.
+   * `a = c AND c = d AND d < b AND b < 5`) may leave a bound on `a` 
uninferred without further
+   * optimization rounds.
+   */
+  def inferAllAdditionalConstraints(constraints: ExpressionSet): ExpressionSet 
= {
+    val equalityInferred =
+      inferAdditionalConstraints(constraints) ++ 
inferConstraintsFromLiteralBindings(constraints)
+    equalityInferred ++ inferInequalityConstraints(constraints ++ 
equalityInferred)
+  }
+
+  /**
+   * True when `e` cannot raise an error during evaluation: a non-null 
literal, or an upcast of
+   * one admitted by [[UpCastRule.canUpCast]]. Used by 
[[inferInequalityConstraints]] to decide
+   * which literals are safe to treat as chain anchors without risking an ANSI 
eval failure.
+   * Arbitrary expressions (such as a parsing cast `CAST('abc' AS INT)` or 
arithmetic that can
+   * fail under ANSI) are excluded.
+   */
+  @tailrec
+  private def isSafeBoundLiteral(e: Expression): Boolean = e match {
+    case l: Literal => l.value != null
+    case Cast(child, toType, _, _) =>
+      UpCastRule.canUpCast(child.dataType, toType) && isSafeBoundLiteral(child)
+    case _ => false
+  }
+
+  private def hasBoundOperand(e: Expression): Boolean = e match {
+    case b: BinaryComparison => isSafeBoundLiteral(b.left) || 
isSafeBoundLiteral(b.right)
+    case _ => false
+  }
+
+  /**
+   * True when `e` is safe to copy into a newly inferred, single-side filter 
produced by
+   * [[inferInequalityConstraints]] without risking an error on rows that 
never evaluated it
+   * before: an attribute reference, or an upcast of one admitted by 
[[UpCastRule.canUpCast]].
+   * While some upcasts may lose precision (e.g. Long to Float/Double), 
relocation is sound
+   * because they cannot fail and reuse the existing Cast expression. 
Arbitrary expressions -- a
+   * parsing/narrowing cast, arithmetic that can overflow under ANSI, etc. -- 
are excluded, since
+   * the comparison they came from may have been a cross-side join condition 
that only ever ran
+   * on matched rows.
+   */
+  private def isSafeToRelocate(e: Expression): Boolean = e match {
+    case _: Attribute => true
+    case Cast(a: Attribute, toType, _, _) => UpCastRule.canUpCast(a.dataType, 
toType)
+    case _ => false
+  }
+
+  /**
+   * A known literal bound discovered while chaining inequality constraints in
+   * [[inferInequalityConstraints]]: `site {<,<=} lit` when `upper`, or `lit 
{<,<=} site`
+   * otherwise. `value` stores the evaluated literal value to avoid repeatedly 
evaluating `lit`
+   * during optimization.
+   */
+  private case class InequalityBound(
+      upper: Boolean,
+      site: Expression,
+      lit: Expression,
+      strict: Boolean,
+      value: Any)
+
+  /**
+   * Converts a canonicalized comparison into an [[InequalityBound]] when 
exactly one side is a
+   * safe literal bound ([[isSafeBoundLiteral]]); `None` for 
attribute-to-attribute comparisons.
+   */
+  private def toBound(e: Expression): Option[InequalityBound] = e match {
+    case b: BinaryComparison =>
+      val strict = b.isInstanceOf[LessThan]
+      if (isSafeBoundLiteral(b.right) && !isSafeBoundLiteral(b.left)) {
+        Some(InequalityBound(upper = true, b.left, b.right, strict, 
b.right.eval()))
+      } else if (isSafeBoundLiteral(b.left) && !isSafeBoundLiteral(b.right)) {
+        Some(InequalityBound(upper = false, b.right, b.left, strict, 
b.left.eval()))
+      } else {
+        None
+      }
+    case _ => None
+  }
+
+  /**
+   * Infers tightest literal inequality bounds on relocatable sites by 
transitively chaining
+   * inequality constraints with literal bounds. For e.g., if an operator has 
constraints of the
+   * form (`a > b`, `b > 5`), this returns an additional constraint of the 
form `a > 5`; a longer
+   * chain such as `a < b && b < c && c < 5` derives both `b < 5` and `a < 5` 
in this same call.
+   * Note that attribute-to-attribute inequalities without literal bounds 
(e.g., `a < c` from
+   * `a < b && b < c`) are not inferred.
+   *
+   * This is computed as a worklist over a directed bound graph rather than a 
repeated fixed point
+   * over the full candidate set: each candidate comparison becomes a directed 
edge once, and each
+   * newly discovered bound is propagated only along its adjacent edges, 
instead of rescanning the
+   * full candidates x bounds product after every newly inferred bound (which 
costs O(n^3) on a
+   * sparse n-element chain such as `x1 < x2 < ... < xn < lit`). A site only 
ever keeps its single
+   * tightest bound per direction, so reaching it via multiple literals (e.g. 
`b < 5` and `b < 10`
+   * both reaching `a` through `a < b`) converges to one inferred predicate 
instead of one per
+   * literal; a relaxation only re-enters the worklist when it strictly 
tightens that site's bound,
+   * which bounds the number of relaxations per site by the number of distinct 
literals that can
+   * reach it and guarantees termination.
+   */
+  private def inferInequalityConstraints(constraints: ExpressionSet): 
ExpressionSet = {
+    // Admits only comparisons between binary-stable types. This is a 
conservative guard, not a
+    // strict requirement: chaining never substitutes a value the way
+    // inferConstraintsFromLiteralBindings does, it only reuses an operand 
under the same
+    // collation-aware comparison, so a non-binary-stable collation could in 
principle still order
+    // consistently with its binary form here. EqualTo is admitted only when 
at least one side is
+    // a safe literal bound (acting as a directional upper and lower bound). 
Non-literal equalities
+    // -- attribute-to-attribute (handled by inferAdditionalConstraints's 
transitivity), as well as
+    // any other shape without a safe literal bound such as `a + 1 = b` -- are 
deliberately
+    // excluded from serving as chaining edges to keep the graph focused on 
literal bounds.
+    val validComparisons = constraints.toSeq.filter {
+      case b: BinaryComparison =>
+        b.deterministic && !b.throwable && !b.isInstanceOf[EqualNullSafe] &&
+          (!b.isInstanceOf[EqualTo] || hasBoundOperand(b)) &&
+          isBinaryStable(b.left.dataType) && isBinaryStable(b.right.dataType)
+      case _ => false
+    }
+
+    if (!validComparisons.exists(hasBoundOperand)) {
+      return ExpressionSet()
+    }
+
+    // Canonicalize comparisons into LessThan / LessThanOrEqual direction. 
EqualTo is expanded
+    // into both directions, unlike GreaterThan/GreaterThanOrEqual, because an 
equality acts as
+    // both an upper and a lower bound and the matching below is 
direction-sensitive on which
+    // side carries the literal. Kept as a Seq, not an ExpressionSet: 
ExpressionSet canonicalizes
+    // EqualTo(l, r) and EqualTo(r, l) to the same entry and would silently 
keep only one of the
+    // two directions just expanded.
+    val canonical = validComparisons.flatMap {
+      case GreaterThan(l, r) => LessThan(r, l) :: Nil
+      case GreaterThanOrEqual(l, r) => LessThanOrEqual(r, l) :: Nil
+      case EqualTo(l, r) => EqualTo(l, r) :: EqualTo(r, l) :: Nil
+      case other => other :: Nil
+    }
+
+    val (initialBounds, candidates) = canonical.partition(hasBoundOperand)
+    if (initialBounds.isEmpty || candidates.isEmpty) return ExpressionSet()
+
+    // Index candidate edges by the semantic key of the endpoint a bound would 
match, so a newly
+    // discovered bound only revisits the edges that touch it instead of the 
full candidate list.
+    // An edge `l < r` (or `l <= r`) propagates an upper bound on `r` to `l`, 
and a lower bound on
+    // `l` to `r`.
+    val upperEdges = new mutable.HashMap[Expression, 
mutable.Buffer[(Expression, Boolean)]]
+    val lowerEdges = new mutable.HashMap[Expression, 
mutable.Buffer[(Expression, Boolean)]]
+    candidates.foreach {
+      case c @ BinaryComparison(l, r) =>
+        val strict = c.isInstanceOf[LessThan]
+        if (isSafeToRelocate(l)) {
+          upperEdges.getOrElseUpdate(r.canonicalized, mutable.Buffer.empty) += 
(l -> strict)
+        }
+        if (isSafeToRelocate(r)) {
+          lowerEdges.getOrElseUpdate(l.canonicalized, mutable.Buffer.empty) += 
(r -> strict)
+        }
+      case _ =>
+    }
+
+    if (upperEdges.isEmpty && lowerEdges.isEmpty) return ExpressionSet()
+
+    // Key: (upper, site.canonicalized) -> tightest bound discovered for that 
site so far, keyed
+    // without the literal so that bounding the same site via different 
literals (e.g. `b < 5` and
+    // `b < 10` both reaching `a` through `a < b`) converges to the single 
tightest predicate
+    // instead of emitting one inferred conjunct per literal it was ever 
bounded by.
+    type BoundKey = (Boolean, Expression)
+    val bestBound = new mutable.HashMap[BoundKey, InequalityBound]
+    val inferredBounds = new mutable.LinkedHashMap[BoundKey, InequalityBound]
+    val worklist = new mutable.Queue[InequalityBound]
+
+    // True when `candidate` improves on `current` for the same key: a smaller 
upper-bound literal
+    // (or larger lower-bound one), or an equal literal newly made strict. 
Compares with the same
+    // per-type ordering BinaryComparison.eval itself uses, so tightness 
agrees with the actual
+    // `<`/`<=` runtime semantics (decimal scale, etc.) instead of a parallel 
notion of "smaller".
+    def isTighter(upper: Boolean, candidate: InequalityBound, current: 
InequalityBound): Boolean = {
+      val cmp = TypeUtils.getInterpretedOrdering(candidate.site.dataType)
+        .compare(candidate.value, current.value)
+      if (cmp == 0) {
+        candidate.strict && !current.strict

Review Comment:
   **Blocking (P1):** Consider two join inputs that are otherwise identical, 
such as a self-join with matching filters or a deterministic CTE inlined twice, 
where both carry the same non-strict range bound on the columns of a strict 
cross-instance inequality. This check lets an equal-valued strict copy win over 
the site's own bound. For `WITH r AS (SELECT user, ts FROM events WHERE ts >= 
DATE'2020-03-01') SELECT count(*) FROM r a JOIN r b ON a.user = b.user AND a.ts 
< b.ts`, inference carries `a.ts >= DATE'2020-03-01'` across `a.ts < b.ts` as 
`b.ts > DATE'2020-03-01'`, and inferNewFilter adds it to b only, because b's 
constraints hold just the non-strict form. With a shared BETWEEN bound, a also 
gains `ts < hi`. When both inputs are shuffled, they no longer canonicalize 
equally, so the stage cache under AQE, or ReuseExchangeAndSubquery without it, 
stops reusing the first exchange. The shared input is then scanned and shuffled 
twice, where the base branch does it once. The extra conju
 nct removes only rows exactly equal to the literal, and results are unchanged. 
Event-attribution self-joins under a shared date filter have exactly this 
shape, and no test plans exchanges for it.
   
   **Recommended change:** Keep using strictness to propagate bounds along 
chains in the inequality inference, but stop emitting a derived bound on a site 
that the input constraints already bound in the same direction with an equal 
literal value. Emit only bounds that are new for the site or tighter in value. 
Add exchange-reuse planning coverage for a self-join and a twice-referenced 
CTE, alongside the existing inequality-inference optimizer tests.
   
   **Why this works:** Record the bound that the input comparisons give each 
direction and site, then compare each derived bound with it at emission, using 
the site type's interpreted ordering. Drop the derived bound when the two 
values are equal. Identical non-strict bounds on both instances then stay 
identical after inference, so their exchanges canonicalize equally again, while 
strict tightening among derived bounds still applies.
   
   **Scope:** Adjust the emission rule of the inequality inference and add 
exchange-reuse coverage for self-join and CTE shapes.
   
   **Compatibility:** Strictness still propagates along chains, and strict 
tightening among derived bounds on the same site is still emitted when the 
input constraints held no equal-valued bound for that site.
   
   **Risks:** A join side that already carries `x >= lit` no longer gains the 
strict `x > lit` derived through a strict edge, so pruning of rows or 
partitions exactly equal to that literal on that side is given up. The join 
condition still removes those rows, so results are unchanged and the loss is 
limited to the boundary value. The change is contained in the inference and can 
be reverted on its own.
   
   **Constraints:** Inferred bounds must remain implied by the input 
constraints, keep their deterministic emission order, and keep one tightest 
bound per direction and site.
   
   **Exclusions:**
   - Plan-identity effects of other inferred constraints, such as equality and 
literal-binding inference, are unchanged and out of scope.
   
   **Success:** A self-join or twice-referenced deterministic CTE whose 
instances share a non-strict literal bound, joined by an equi-key plus a strict 
cross-instance inequality, plans one reused exchange or query stage, as on the 
base branch. Sites without an equal-valued existing bound still receive strict 
derived bounds, and the TPC-H Q12 plan keeps its two inferred lineitem bounds.
   
   **Verification:**
   - **Regression:** For a twice-referenced CTE that filters `ts >= lo` and is 
joined to itself on an equi-key with `a.ts < b.ts`, and for the variant with a 
shared BETWEEN bound, the optimized plan adds no strict copy of the shared 
bound to either instance, and the physical plan reuses one exchange or query 
stage.
   - **Behavior:** A strict bound is still inferred where the target site has 
no bound or only a weaker one, for example `left.b < right.b` with `right.b <= 
1` still infers `left.b < 1`.
   - **Compatibility:** Existing inequality-inference expectations for 
tightest-bound convergence, strictness composition, cycles and the TPC-H Q12 
plan stay unchanged.



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