You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "vranes (via GitHub)" <gi...@apache.org> on 2026/07/07 16:36:07 UTC

[PR] [SPARK-58003][SQL] Add physical execution for BIN BY [spark]

vranes opened a new pull request, #57086:
URL: https://github.com/apache/spark/pull/57086

   ### What changes were proposed in this pull request?
   
   This PR makes the `BIN BY` relation operator (SPARK-57133) execute end-to-end. It adds the `BinByExec` physical operator and wires it into planning, replacing the stub strategy that raised `UNSUPPORTED_FEATURE.BIN_BY`.
   
   `BinByExec` emits one output row per bin overlapping each input row's `[range_start, range_end)`:
   - The `DISTRIBUTE UNIFORM` columns are proportionally rescaled by the bin's overlap fraction. Row assembly follows the `GenerateExec` pattern: a `JoinedRow(childRow, appendedRow)` fed through a per-partition `UnsafeProjection`, where each DISTRIBUTE column's output expression is `Cast(Multiply(Cast(col, DoubleType), ratio), col.dataType)` (the inner cast keeps FLOAT columns from forming a mismatched `Multiply(FloatType, DoubleType)`, since these expressions are bound at execution time and never pass through the analyzer's operand coercion).
   - The other forwarded columns, including the range columns, are replicated unchanged.
   - `bin_start`, `bin_end`, and `bin_distribute_ratio` are appended.
   
   Bin boundaries reuse `DateTimeUtils.timeBucketDTInterval` / `timestampAddDayTime`, matching `time_bucket`: sub-day widths use UTC microsecond arithmetic, multi-day widths use civil-time arithmetic in the session zone (UTC for `TIMESTAMP_NTZ`).
   
   Per-row edge cases: a zero-length range emits one row with ratio `1.0`; an inverted range (`range_start > range_end`) raises the runtime error `BIN_BY_INVALID_RANGE`; a NULL in either range column emits one row with all computed columns NULL (the scaled DISTRIBUTE values and all three appended columns), since no valid bin exists to scale into. Non-DISTRIBUTE passthrough columns are unaffected in every case. `BinByResolution.scaledDistributeAttributes` marks the scaled produced attributes `nullable = true` to reflect the NULL-range case.
   
   Two optimizer changes ride along, both enabled by the produced-attributes shape from SPARK-57858:
   - **Column pruning**: `BinBy` gains `unrequiredChildIndex` / `requiredChildOutput` (mirroring `Generate`) and a `ColumnPruning` arm that trims forwarded pass-through columns while keeping the range and DISTRIBUTE inputs the kernel reads.
   - **Filter pushdown**: `BinBy` is added to `PushPredicateThroughNonJoin.canPushThrough`, so deterministic predicates on forwarded pass-through / range columns push below the operator. Predicates on the scaled DISTRIBUTE or appended columns cannot push (fresh `ExprId`s not in the child output), which is what makes this safe.
   
   ### Why are the changes needed?
   
   `BIN BY` parsed, resolved, and type-checked but had no physical execution: planning threw `UNSUPPORTED_FEATURE.BIN_BY`. This PR provides the JVM execution path so the operator runs end-to-end. It is the physical-execution step of the `BIN BY` feature (SPARK-57133), following the parser/analyzer (SPARK-57133), the config gate (SPARK-57440), and the produced-attributes plan shape (SPARK-57858).
   
   ### Does this PR introduce _any_ user-facing change?
   
   No. `BIN BY` is gated off by default (`spark.sql.binByRelationOperator.enabled`, SPARK-57440) and was not usable end-to-end before this PR (execution was stubbed). This enables execution behind that gate; the gate remains off by default, so there is no change to released or default behavior.
   
   ### How was this patch tested?
   
   - `BinBySuite` (`sql/core`): end-to-end execution over the wired operator: multi-bin proportional split, single-bin passthrough, mixed FLOAT + DOUBLE DISTRIBUTE columns, downstream `GROUP BY` composability, NULL-range rows, inverted-range error (`checkError`), renamed output columns, and the gated-off rejection.
   - `bin-by.sql` golden file: executing scenarios plus representative analysis errors.
   - `ColumnPruningSuite`: a `Project` over `BinBy` prunes unused pass-through columns while keeping range and DISTRIBUTE inputs required.
   - `FilterPushdownSuite`: a predicate on a pass-through column pushes below `BinBy`; a predicate on a produced (fresh-`ExprId`) appended column stays above.
   - `ResolveBinBySuite`: existing analyzer coverage, green after the output-shape and nullability changes.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Claude Code (Anthropic)
   


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58003][SQL] Add physical execution for BIN BY [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan closed pull request #57086: [SPARK-58003][SQL] Add physical execution for BIN BY
URL: https://github.com/apache/spark/pull/57086


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58003][SQL] Add physical execution for BIN BY [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58003][SQL] Add physical execution for BIN BY [spark]

Posted by "vranes (via GitHub)" <gi...@apache.org>.
vranes commented on code in PR #57086:
URL: https://github.com/apache/spark/pull/57086#discussion_r3578981715


##########
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:
   I'll address this by extending PartitioningPreservingUnaryExecNode in a follow up PR. Thanks!



##########
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:
   I'll address this by extending PartitioningPreservingUnaryExecNode in a follow up PR, with the appropriate tests. Thanks!



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58003][SQL] Add physical execution for BIN BY [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on PR #57086:
URL: https://github.com/apache/spark/pull/57086#issuecomment-4976393844

   **Merge Summary:**
   - merged into master https://github.com/apache/spark/commit/99f574b0b4bdca6c6a80424b956838dc97ff2127
   - merged into branch-4.x https://github.com/apache/spark/commit/548bd8e967b5ea338b633d62aeae720408bc7b66
   
   *Posted by `merge_spark_pr.py`*


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58003][SQL] Add physical execution for BIN BY [spark]

Posted by "vranes (via GitHub)" <gi...@apache.org>.
vranes commented on code in PR #57086:
URL: https://github.com/apache/spark/pull/57086#discussion_r3580220050


##########
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:
   Added two executed NTZ checkAnswer tests to BinBySuite: wall-clock epoch default origin, and a multi-day bin across the LA spring-forward. Removed the analyze-only case.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org