viirya commented on code in PR #7723:
URL: https://github.com/apache/datafusion-comet/pull/7723#discussion_r4703094422
##########
spark/src/test/scala/org/apache/comet/CometExpressionSuite.scala:
##########
@@ -3819,6 +3819,53 @@ class CometExpressionSuite extends CometTestBase with
AdaptiveSparkPlanHelper {
}
}
+ test("ANSI division with partial readers and shared expressions") {
+ withTempPath { dir =>
+ sql(
+ "SELECT * FROM VALUES (1L, true, true, 2e20D), (0L, NULL, false,
1e20D) AS t(x, p, q, v)")
+ .coalesce(1)
+ .write
+ .parquet(dir.getCanonicalPath)
+ withParquetTable(dir.getCanonicalPath, "divisors") {
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ val query = "SELECT x FROM divisors WHERE p IS NOT NULL AND abs(10
DIV x) > 0"
+ val filtered = sql(query)
+ assert(!filtered.isEmpty)
+ assert(filtered.rdd.take(1).toSeq == Seq(Row(1L)))
+
+ withTable("division_result") {
+ sql("CREATE TABLE division_result (x BIGINT) USING parquet")
+ for (enabled <- Seq("false", "true")) {
+ withSQLConf(CometConf.COMET_ENABLED.key -> enabled) {
+ val error = intercept[Exception] {
+ sql(s"INSERT INTO division_result $query").collect()
+ }
+ assert(arithmeticError(error).getErrorClass ==
"DIVIDE_BY_ZERO")
+ }
+ }
+ }
+
+ // Spark 4.2 evaluates the shared division before testing p and q.
Review Comment:
On 4.2 `canReorder` is false, so Comet keeps the original condition. It
raises only because `p` is NULL and `AND` goes on past a NULL left side. With
`p = false, q = false`, Spark 4.2 still computes `10 DIV x` first and raises,
but Comet short-circuits and doesn't raise. Could the test use a non-NULL
guard, and could the doc list this case?
##########
spark/src/main/scala/org/apache/comet/rules/CometExecRule.scala:
##########
@@ -1066,44 +1072,54 @@ case class CometExecRule(session: SparkSession,
queryStagePrep: Boolean = false)
newPlan
}
- /** A batch observer must not count rows that a short-circuiting consumer
would never read. */
- private def preserveCollectMetricsRowConsumption(plan: SparkPlan): Unit = {
- def visit(node: SparkPlan, requiresRowConsumption: Boolean): Unit = {
+ private def preserveRowConsumption(plan: SparkPlan): Unit = {
+ // None means the consumer is external. Metrics require a known
materializing consumer,
+ // while division reordering is disabled when a visible consumer can stop
mid-batch.
+ def visit(node: SparkPlan, partialReader: Option[Boolean]): Unit = {
val original = node match {
case comet: CometExec => comet.originalPlan
case other => other
}
- val childRequiresRowConsumption = original match {
+ val childReader = original match {
// A join can finish when one input is exhausted without draining the
other input.
- case _: BaseJoinExec => true
+ case _: BaseJoinExec => Some(true)
// User functions can consume only part of the partition iterator.
- case _: MapPartitionsExec => true
+ case _: MapPartitionsExec => Some(true)
// Nonpositive Poisson sampling may return an empty iterator without
reading its input.
case sample: SampleExec
if sample.withReplacement && sample.upperBound - sample.lowerBound
<= 0.0 =>
- true
+ Some(true)
case _: CollectLimitExec | _: LocalLimitExec | _: GlobalLimitExec |
_: TakeOrderedAndProjectExec =>
- true
+ Some(true)
case windowLimit
if ShimCometWindowGroupLimit.windowGroupLimitClass.exists(
_.isInstance(windowLimit)) =>
- true
+ Some(true)
case _: ShuffleExchangeLike | _: BroadcastExchangeLike | _:
QueryStageExec =>
- false
+ Some(false)
// Even a sort or aggregate may never be polled by an external
iterator consumer.
- case _ => requiresRowConsumption
+ case _ => partialReader
}
node match {
- case observation: CollectMetricsExec if requiresRowConsumption =>
+ case observation: CollectMetricsExec if !partialReader.contains(false)
=>
observation.setTagValue(CometCollectMetricsExec.REQUIRES_ROW_CONSUMPTION, true)
+ case _: FilterExec | _: ProjectExec =>
+ if (partialReader.contains(true))
node.setTagValue(CometExecRule.PARTIAL_READER, ())
+ else node.unsetTagValue(CometExecRule.PARTIAL_READER)
case _ =>
}
- node.children.foreach(visit(_, childRequiresRowConsumption))
+ node.children.foreach(visit(_, childReader))
}
// External actions such as foreachPartition or RDD.take can stop reading
without adding a
// physical-plan node. Require a materializing exchange before enabling
batch observation.
- visit(plan, requiresRowConsumption = true)
+ val partial = plan match {
Review Comment:
An unrecognized root gets `None`, which allows the reorder. The metrics
logic above defaults the other way. PySpark's `df.rdd` builds on
`queryExecution.toRdd`, so its root has no `DeserializeToObjectExec`, and
`df.rdd.take(1)` isn't recognized as a partial reader. Since a wrong guess here
fails the query, could an unknown root count as a partial reader for this check?
##########
spark/src/test/scala/org/apache/comet/CometExpressionSuite.scala:
##########
@@ -3819,6 +3819,53 @@ class CometExpressionSuite extends CometTestBase with
AdaptiveSparkPlanHelper {
}
}
+ test("ANSI division with partial readers and shared expressions") {
Review Comment:
This test covers four separate mechanisms: partial readers, the write root,
4.2 shared terms and floating-point reassociation. Could it be split into named
tests so a failure points at the one that broke?
##########
docs/source/user-guide/latest/compatibility/index.md:
##########
@@ -171,6 +171,47 @@ already-ordered `TakeOrderedAndProject` inputs are tracked
in
An error on a row absent from the final result is not always a mismatch: Spark
can also need to
evaluate that row, for example to sort the input or process an `OFFSET` prefix.
+## ANSI division errors in filters and projections
+
+With `spark.sql.ansi.enabled=true`, Spark can raise `DIVIDE_BY_ZERO` even when
a condition
+appears to guard the division. Spark's generated filter checks a column for
NULL when a
+predicate first needs it. A generated projection can evaluate a repeated
expression before
+either operand of an `AND` or `OR`.
+
+With the default code generation settings, Comet raises the same error for
both queries in
+[#7480](https://github.com/apache/datafusion-comet/issues/7480). Whether Comet
can reproduce
+Spark's evaluation order depends on the surrounding expressions and the
consuming operator.
+For example, below a `LIMIT`, moving a division ahead of a filter condition
could raise an
+error on a row beyond the limit. Comet keeps the original order in that filter.
+
+When `spark.sql.codegen.hugeMethodLimit` is below its default of 65535 bytes,
Comet
Review Comment:
With `spark.comet.parquet.rowFilterPushdown.enabled=true` the scan applies
the pushed `IS NOT NULL`, so the row never reaches the reordered filter and
Comet returns rows where Spark raises. Could this paragraph mention that?
--
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]