cloud-fan commented on code in PR #57086:
URL: https://github.com/apache/spark/pull/57086#discussion_r3572038008


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/BinByExec.scala:
##########
@@ -0,0 +1,213 @@
+/*
+ * 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.execution
+
+import java.time.ZoneOffset
+
+import org.apache.spark.SparkException
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeMap, 
AttributeSet, BindReferences, BoundReference, Cast, Expression, 
GenericInternalRow, JoinedRow, Literal, Multiply, UnsafeProjection}
+import org.apache.spark.sql.catalyst.util.{DateTimeUtils, TimestampFormatter}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics}
+import org.apache.spark.sql.types.DoubleType
+
+/**
+ * Physical node for the `BIN BY` relation operator. For each input row it 
emits one output row per
+ * bin overlapping `[rangeStart, rangeEnd)`.
+ *
+ * Per output sub-row: the DISTRIBUTE UNIFORM columns are scaled by the 
overlap fraction (the bin's
+ * half-open intersection with `[rangeStart, rangeEnd)`); the other forwarded 
columns, including the
+ * range columns, are replicated unchanged; `bin_start`, `bin_end`, 
`bin_distribute_ratio` are
+ * appended. Bin boundaries reuse [[DateTimeUtils.timeBucketDTInterval]] /
+ * [[DateTimeUtils.timestampAddDayTime]], so they match `time_bucket`: sub-day 
widths use UTC
+ * microsecond arithmetic, multi-day widths use civil-time arithmetic in the 
session zone (UTC for
+ * TIMESTAMP_NTZ).
+ *
+ * DISTRIBUTE UNIFORM columns are FLOAT or DOUBLE only (enforced by 
`ResolveBinBy`); scaling is IEEE
+ * multiplication by the ratio, no rounding. Per-row edge cases: a NULL in 
either range column emits
+ * one row with all computed columns NULL (scaled DISTRIBUTE values and all 
three appended columns);
+ * a zero-length range emits one row with ratio 1.0; an inverted range raises
+ * `BIN_BY_INVALID_RANGE`.
+ *
+ * Output shape mirrors the logical `BinBy`: the child columns with each 
DISTRIBUTE slot swapped to
+ * its scaled produced attribute, then the three appended columns.
+ */
+case class BinByExec(
+    binWidthMicros: Long,
+    originMicros: Long,
+    rangeStart: Attribute,
+    rangeEnd: Attribute,
+    distributeColumns: Seq[Attribute],
+    scaledDistributeColumns: Seq[Attribute],
+    appendedAttributes: Seq[Attribute],
+    timeZoneId: Option[String],
+    child: SparkPlan)
+  extends UnaryExecNode {
+
+  override lazy val metrics: Map[String, SQLMetric] = Map(
+    "numOutputRows" -> SQLMetrics.createMetric(sparkContext, "number of output 
rows"))
+
+  private val distributeReplacements: AttributeMap[Attribute] =
+    AttributeMap(distributeColumns.zip(scaledDistributeColumns))
+
+  // Appended columns are [bin_start, bin_end, bin_distribute_ratio]; the 
ratio is the last one.
+  private val numAppended: Int = appendedAttributes.length
+  assert(numAppended == 3,
+    s"BinBy appends exactly 3 columns (bin_start, bin_end, 
bin_distribute_ratio), got $numAppended")
+
+  override def output: Seq[Attribute] =
+    child.output.map(a => distributeReplacements.getOrElse(a, a)) ++ 
appendedAttributes
+
+  override def producedAttributes: AttributeSet =

Review Comment:
   `BinByExec` doesn't override `outputPartitioning`, so it falls back to the 
`SparkPlan` default `UnknownPartitioning(0)`. The `GenerateExec` analogue this 
operator otherwise mirrors sets `outputPartitioning = child.outputPartitioning` 
(GenerateExec.scala:74). As a result, a downstream operator clustered on a 
*passthrough* column the child already partitions on would get an unnecessary 
shuffle here.
   
   Non-blocking. Note the naive fix (copy `child.outputPartitioning` verbatim) 
would be *unsafe*: DISTRIBUTE columns are rescaled with fresh `exprId`s, so a 
child `HashPartitioning` on a DISTRIBUTE column would reference an attribute 
that no longer exists in `output`. The safe enhancement preserves the child's 
partitioning restricted to passthrough columns (those whose `exprId` survives 
in `output`).



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/BinByExec.scala:
##########
@@ -0,0 +1,213 @@
+/*
+ * 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.execution
+
+import java.time.ZoneOffset
+
+import org.apache.spark.SparkException
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeMap, 
AttributeSet, BindReferences, BoundReference, Cast, Expression, 
GenericInternalRow, JoinedRow, Literal, Multiply, UnsafeProjection}
+import org.apache.spark.sql.catalyst.util.{DateTimeUtils, TimestampFormatter}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics}
+import org.apache.spark.sql.types.DoubleType
+
+/**
+ * Physical node for the `BIN BY` relation operator. For each input row it 
emits one output row per
+ * bin overlapping `[rangeStart, rangeEnd)`.
+ *
+ * Per output sub-row: the DISTRIBUTE UNIFORM columns are scaled by the 
overlap fraction (the bin's
+ * half-open intersection with `[rangeStart, rangeEnd)`); the other forwarded 
columns, including the
+ * range columns, are replicated unchanged; `bin_start`, `bin_end`, 
`bin_distribute_ratio` are
+ * appended. Bin boundaries reuse [[DateTimeUtils.timeBucketDTInterval]] /
+ * [[DateTimeUtils.timestampAddDayTime]], so they match `time_bucket`: sub-day 
widths use UTC
+ * microsecond arithmetic, multi-day widths use civil-time arithmetic in the 
session zone (UTC for
+ * TIMESTAMP_NTZ).
+ *
+ * DISTRIBUTE UNIFORM columns are FLOAT or DOUBLE only (enforced by 
`ResolveBinBy`); scaling is IEEE
+ * multiplication by the ratio, no rounding. Per-row edge cases: a NULL in 
either range column emits
+ * one row with all computed columns NULL (scaled DISTRIBUTE values and all 
three appended columns);
+ * a zero-length range emits one row with ratio 1.0; an inverted range raises
+ * `BIN_BY_INVALID_RANGE`.
+ *
+ * Output shape mirrors the logical `BinBy`: the child columns with each 
DISTRIBUTE slot swapped to
+ * its scaled produced attribute, then the three appended columns.
+ */
+case class BinByExec(
+    binWidthMicros: Long,
+    originMicros: Long,
+    rangeStart: Attribute,
+    rangeEnd: Attribute,
+    distributeColumns: Seq[Attribute],
+    scaledDistributeColumns: Seq[Attribute],
+    appendedAttributes: Seq[Attribute],
+    timeZoneId: Option[String],
+    child: SparkPlan)
+  extends UnaryExecNode {
+
+  override lazy val metrics: Map[String, SQLMetric] = Map(
+    "numOutputRows" -> SQLMetrics.createMetric(sparkContext, "number of output 
rows"))
+
+  private val distributeReplacements: AttributeMap[Attribute] =
+    AttributeMap(distributeColumns.zip(scaledDistributeColumns))
+
+  // Appended columns are [bin_start, bin_end, bin_distribute_ratio]; the 
ratio is the last one.
+  private val numAppended: Int = appendedAttributes.length
+  assert(numAppended == 3,
+    s"BinBy appends exactly 3 columns (bin_start, bin_end, 
bin_distribute_ratio), got $numAppended")
+
+  override def output: Seq[Attribute] =
+    child.output.map(a => distributeReplacements.getOrElse(a, a)) ++ 
appendedAttributes
+
+  override def producedAttributes: AttributeSet =
+    AttributeSet(scaledDistributeColumns ++ appendedAttributes)
+
+  override protected def withNewChildInternal(newChild: SparkPlan): BinByExec =
+    copy(child = newChild)
+
+  protected override def doExecute(): RDD[InternalRow] = {
+    val width = binWidthMicros
+    val origin = originMicros
+    val zone = 
timeZoneId.map(DateTimeUtils.getZoneId).getOrElse(ZoneOffset.UTC)

Review Comment:
   The `timeZoneId = None -> ZoneOffset.UTC` branch is the NTZ execution path, 
but `BinBySuite`'s NTZ coverage only calls `.assertAnalyzed()` — NTZ inputs are 
never actually executed via `checkAnswer`/`collect`. So the NTZ branch of the 
boundary arithmetic and error formatting has no runtime coverage, even though 
the LTZ paths are covered thoroughly.
   
   Non-blocking: consider adding one end-to-end NTZ `checkAnswer` (NTZ differs 
from LTZ in the origin default and the absence of DST, both worth one executed 
assertion).



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