nsivabalan commented on code in PR #20524:
URL: https://github.com/apache/hudi/pull/20524#discussion_r4474744669


##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/dataskipping/RangeRule.scala:
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.hudi.dataskipping
+
+import org.apache.spark.sql.catalyst.expressions.{Expression, If, Literal}
+import org.apache.spark.sql.hudi.dataskipping.rules.{CastRule, 
ConstantOperandRule, DateTimeFormatRule, MonotonicFunctionRule, PrefixRule, 
TimeZoneShiftRule}
+
+/**
+ * Stage 3 (Range), rules: how does a function of the child map the child's 
range?
+ *
+ * A [[Step]] says: `term` is a function of `child` with this [[Direction]], 
so the range of `term`
+ * is the range of `child` pushed through it. Invariant: a rule only emits a 
step when its guard
+ * holds for this `term`; a term no rule knows has no range (and the file is 
kept).
+ *
+ * Emitting a Step is a correctness claim: `term` is order-preserving in 
`child`.
+ * <ul>
+ *   <li>[[Increasing]]: a <= b implies f(a) <= f(b)</li>
+ *   <li>[[Decreasing]]: a <= b implies f(a) >= f(b)</li>
+ * </ul>
+ * The claim must hold for every value the file's range can hold (or wherever 
the step's
+ * `fileGuard` is true). If it is false, data skipping drops files that have 
matching rows. When
+ * unsure, return Nil: that only costs pruning, never correctness.
+ */
+sealed trait Direction
+
+/**
+ * Order-preserving (non-decreasing): a <= b implies f(a) <= f(b), so f(lo) is 
the low bound and
+ * f(hi) the high bound. Every step today is increasing.
+ */
+case object Increasing extends Direction
+
+/**
+ * Order-reversing (non-increasing): a <= b implies f(a) >= f(b), so f(hi) is 
the low bound and
+ * f(lo) the high bound. Unused today; negative factors would use it.
+ */
+case object Decreasing extends Direction
+
+/**
+ * One rule application.
+ *
+ * @param term      the function application being ranged, for ex `x + 1`
+ * @param child     the operand whose range is pushed through, for ex `x`
+ * @param direction whether `term` grows or shrinks with `child`
+ * @param fileGuard per-file condition under which the mapping holds (for ex, 
no overflow); outside it
+ *                  the bounds become NULL, i.e. unknown. `None` for every 
step today
+ * @param partial   whether `term` can be NULL for a non-NULL `child` (for ex, 
`log` of a negative), in
+ *                  which case null / value counts of the child no longer 
describe `term`. No behavioral
+ *                  effect yet: IS NULL / IS NOT NULL only take bare columns
+ */
+case class Step(term: Expression,
+                child: Expression,
+                direction: Direction,
+                fileGuard: Option[Range => Expression],
+                partial: Boolean) {
+
+  def apply(r: Range): Range = {
+    val (lo, hi) = direction match {
+      case Increasing => (r.lo, r.hi)
+      case Decreasing => (r.hi, r.lo)

Review Comment:
   💬 **SUGGESTION.** `Decreasing` and the `fileGuard` branch of `guarded` are 
unreachable today, which is probably most of the 54 uncovered lines codecov 
reports. The follow-ups will rely on them being correct, so a small 
`Step.apply` test would help now: swapped lo/hi for `Decreasing`, the 
`If(guard, bound, NULL)` shape, and `partial` dropping the counts. Otherwise 
the first PR that uses them is also the first to test them.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/dataskipping/rules/CastRule.scala:
##########
@@ -77,4 +80,13 @@ object HoodieSparkTypeUtils {
 
       case _ => true
     }
+
+  override def steps(term: Expression): Seq[Step] = term match {
+    // NOTE: Some casts (for ex, string to date in non-ANSI mode) return NULL 
on malformed input;
+    //       `partial` is left false for now, as it has no behavioral effect 
yet
+    case cast @ Cast(child, _, _, _) if preservesOrder(cast.child.dataType, 
cast.dataType) =>

Review Comment:
   💬 **SUGGESTION.** On master the matcher's 
`Cast(OrderPreservingTransformation(attrRef), ...)` ran the extractor first, so 
the guard never saw an unresolved child. Here 
`preservesOrder(cast.child.dataType, ...)` runs first, and with 
`strictResolution = false` (expression index) an unresolved child throws from 
`dataType`. This is the 'one unreachable case' from the equivalence run. 
`SparkBaseIndexSupport` catches `NonFatal`, so the worst case is losing 
pruning. Still, `if cast.child.resolved && preservesOrder(...)` makes it 
impossible rather than unreachable, and costs nothing.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/dataskipping/Range.scala:
##########
@@ -0,0 +1,99 @@
+/*
+ * 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.hudi.dataskipping
+
+import org.apache.hudi.ColumnStatsIndexSupport.{getMaxColumnNameFor, 
getMinColumnNameFor, getNullCountColumnNameFor, getValueCountColumnNameFor}
+import org.apache.hudi.SparkAdapterSupport.sparkAdapter
+
+import org.apache.spark.sql.catalyst.expressions.{AttributeReference, 
Expression}
+import org.apache.spark.sql.functions.col
+import org.apache.spark.sql.hudi.DataSkippingUtils.getTargetIndexedColumnName
+
+/**
+ * Stage 3 (Range): what values can the term take in a file?
+ *
+ * `lo` / `hi` are expressions over the stats table bounding the term within 
one file; `nulls` / `rows`
+ * are its null and value counts, when known. A range is read from a 
[[RangeSource]] for a column,
+ * or derived through a chain of [[Step]]s from the range of the step's child.
+ *
+ * Invariant: no range means unknown, and unknown keeps the file.
+ */
+case class Range(lo: Expression, hi: Expression, nulls: Option[Expression], 
rows: Option[Expression])
+
+/**
+ * Where ranges come from. Returns `None` for anything it does not hold stats 
for.
+ */
+sealed trait RangeSource {
+  def rangeOf(term: Expression): Option[Range]
+}
+
+/**
+ * Column stats index: a column maps to its min / max / null-count / 
value-count columns.
+ *
+ * NOTE: Expression indexes go through this source too, but only with the bare 
column:
+ *       `ExpressionIndexSupport` strips the indexed f(col) down to col before 
translating, so the
+ *       stored f(col) bounds are compared as is
+ */
+case class ColumnStatsSource(indexedCols: Seq[String]) extends RangeSource {
+  override def rangeOf(term: Expression): Option[Range] = term match {
+    case column: AttributeReference =>
+      getTargetIndexedColumnName(column, indexedCols).map { colName =>
+        Range(
+          lo = statsColumn(getMinColumnNameFor(colName)),
+          hi = statsColumn(getMaxColumnNameFor(colName)),
+          nulls = Some(statsColumn(getNullCountColumnNameFor(colName))),
+          rows = Some(statsColumn(getValueCountColumnNameFor)))
+      }
+    case _ => None
+  }
+
+  /** A column of the transposed column stats table, for ex `qty_minValue`. */
+  private def statsColumn(name: String): Expression = 
sparkAdapter.getExpressionFromColumn(col(name))
+}
+
+object Range {
+
+  def derive(term: Expression, source: RangeSource): Option[Range] =
+    viaRules(term, source).map(rebindOffChainReferences(term, source, _))
+
+  /**
+   * The source first; otherwise the first rule step whose child derives a 
range. Several steps
+   * only arise for operators accepted on either side (for ex, `BitwiseOr`), 
tried in today's order.
+   */
+  private def viaRules(term: Expression, source: RangeSource): Option[Range] =
+    source.rangeOf(term).orElse(
+      RangeRules.of(term).view.flatMap(step => viaRules(step.child, 
source).map(step.apply)).headOption)
+
+  /**
+   * Re-binds EVERY reference to the column, including ones in operands off 
the rule chain (for ex,
+   * the days operand of `date_add(d, dayofmonth(d))`), matching the pre-stage 
translator. A [[Step]]
+   * only rebuilds its chain slot, so the leftover references are re-bound to 
the same bound here.
+   * Such terms are not order-preserving in general; kept as is so the output 
stays identical.
+   */
+  private def rebindOffChainReferences(term: Expression, source: RangeSource, 
r: Range): Range = {

Review Comment:
   ⚠️ **IMPORTANT.** This re-binds every off-chain reference to the column's 
**lo** for the low bound and **hi** for the high bound. That only lines up 
while every step is `Increasing`. With a `Decreasing` step, `Step.apply` builds 
the low bound from `r.hi`, but this function then re-binds the off-chain 
operands of that same expression to `r.lo`. The result mixes bounds and isn't a 
bound of anything.
   
   Today nothing emits `Decreasing`, so there's no impact. But the plan has 
'order-reversing ranges for negative factors and datediff' and 'constant 
operands for DateAdd / DateSub / ShiftLeft / ShiftRight / DateDiff' as separate 
follow-ups. If the datediff `start` one lands first, `datediff(<expr of d>, d)` 
hits exactly this path.
   
   Could you make the dependency explicit in code, not just in the plan? For 
example:
   - skip the re-binding, and return no range at all, when any step in the 
chain is `Decreasing`; or
   - require a constant other operand in any rule that emits `Decreasing`, and 
add a `require` in `Step` saying so.
   
   Either way, please add a test that pins it.



##########
hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/TestHoodieCatalystExpressionUtils.scala:
##########
@@ -41,8 +42,14 @@ class TestHoodieCatalystExpressionUtils extends 
SparkAdapterSupport {
   private val boolAttr = AttributeReference("b", BooleanType)()
   private val binAttr = AttributeReference("bin", BinaryType)()
 
-  private def matched(expr: Expression): Option[AttributeReference] =
-    
sparkAdapter.getCatalystExpressionUtils.tryMatchAttributeOrderingPreservingTransformation(expr)
+  /**
+   * Walks the rule table down to a bare column: the attribute itself, else 
the first rule step
+   * whose child resolves to one. Like the stage-3 range walk, it does not 
check reference count.
+   */
+  private def matched(expr: Expression): Option[AttributeReference] = expr 
match {

Review Comment:
   💬 **SUGGESTION.** This helper re-implements the range walk instead of 
calling it, so the test now pins the rule table but not `Range.derive` (the 
source-first order, the either-side fall-through, the re-binding). A stub 
`RangeSource` that returns a marker `Range` for one attribute, used with 
`Range.derive(expr, stub)`, would keep the assertions and exercise the 
production path.



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

Reply via email to