dongjoon-hyun commented on code in PR #60542:
URL: https://github.com/apache/spark/pull/60542#discussion_r4581752395
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala:
##########
@@ -751,6 +751,14 @@ abstract class SparkStrategies extends
QueryPlanner[SparkPlan] {
case PhysicalAggregation(groupingExpressions, aggExpressions,
resultExpressions, child)
if
aggExpressions.forall(_.aggregateFunction.isInstanceOf[PythonAggregate]) =>
+ // A batch session window groups by one provisional session per input
row and relies on
+ // the aggregate operator to merge the overlapping ones (see
`UpdatingSessionsExec`). The
+ // incremental operators group by the exact session value and never
merge sessions, so
+ // they would silently return the unmerged sessions; reject the query
instead.
+ if
(groupingExpressions.exists(_.metadata.contains(SessionWindow.marker))) {
Review Comment:
Since SPARK-58736 is not released yet, could we merge the sessions here
instead of introducing a new user-facing error condition? I understand the PR
description mentions it as a separate improvement, but if we ship this error
now, we need to remove
`UNSUPPORTED_FEATURE.PYTHON_AGGREGATOR_WITH_SESSION_WINDOW` again later.
`AggUtils.planAggregateWithOneDistinct` already handles this case via
`mayAppendUpdatingSessionExec`. `UpdatingSessionsExec` requires
`ClusteredDistribution` on the grouping keys without the session column (with
the sort order) and rewrites the session column to the merged session. If we
put it below `PythonIncrementalAggregatePartialExec`, both the PARTIAL and
FINAL stages can keep grouping by the exact session value.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala:
##########
@@ -751,6 +751,14 @@ abstract class SparkStrategies extends
QueryPlanner[SparkPlan] {
case PhysicalAggregation(groupingExpressions, aggExpressions,
resultExpressions, child)
if
aggExpressions.forall(_.aggregateFunction.isInstanceOf[PythonAggregate]) =>
+ // A batch session window groups by one provisional session per input
row and relies on
+ // the aggregate operator to merge the overlapping ones (see
`UpdatingSessionsExec`). The
+ // incremental operators group by the exact session value and never
merge sessions, so
+ // they would silently return the unmerged sessions; reject the query
instead.
+ if
(groupingExpressions.exists(_.metadata.contains(SessionWindow.marker))) {
+ throw QueryCompilationErrors.pythonAggregateWithSessionWindowError(
Review Comment:
Since `SessionWindow.marker` is already in the grouping expressions of the
analyzed `Aggregate`, could we reject this at analysis time, like the
DISTINCT/FILTER (`FunctionResolution`) and pivot (`ResolvePivot`) rejections of
this aggregator? Currently, `df.schema`, `createOrReplaceTempView`, and `CREATE
VIEW` succeed, and the error is raised only when the query is planned (e.g.
`collect()`, `explain()`, or `cache()`). I know the streaming rejection and
`INVALID_PYTHON_UDF_PLACEMENT` are also raised during planning, so this is only
a suggestion.
##########
python/pyspark/sql/tests/arrow/test_arrow_python_aggregator.py:
##########
@@ -347,6 +348,44 @@ def test_pivot_rejected(self):
with self.assertRaises(AnalysisException):
df.groupBy("k").pivot("p").agg(udaf(Mean())(sf.col("v"))).collect()
+ def test_session_window_rejected(self):
+ # A batch session window groups by one provisional session per row and
relies on the
+ # aggregate operator to merge the overlapping ones. The incremental
operators do not
+ # merge sessions, so grouping by a session window is rejected rather
than returning one
+ # row per unmerged session. A tumbling window needs no merging and
still works.
+ df = self.spark.createDataFrame(
+ [
+ (datetime.datetime(2026, 1, 1, 10, 0), 1.0),
+ (datetime.datetime(2026, 1, 1, 10, 2), 3.0),
+ ],
+ "ts timestamp, v double",
+ )
+ mean = udaf(Mean())
+ df.createOrReplaceTempView("session_input")
+ self.spark.udf.register("session_mean", mean)
+ queries = {
+ "dataframe": lambda: df.groupBy(sf.session_window("ts", "5
minutes")).agg(
+ mean(sf.col("v"))
+ ),
+ "sql": lambda: self.spark.sql(
+ "SELECT session_mean(v) FROM session_input GROUP BY
session_window(ts, '5 minutes')"
+ ),
+ }
+ for name, query in queries.items():
+ with self.subTest(query=name):
+ with self.assertRaises(AnalysisException) as ctx:
+ query().collect()
+ self.assertEqual(
+ ctx.exception.getCondition(),
+
"UNSUPPORTED_FEATURE.PYTHON_AGGREGATOR_WITH_SESSION_WINDOW",
+ )
+
+ result = (
+ df.groupBy(sf.window("ts", "5
minutes")).agg(mean(sf.col("v")).alias("m")).collect()
Review Comment:
Both rows (10:00 and 10:02) fall into the same window `[10:00, 10:05)`, so
this comparison has only one group and does not catch a regression that mixes
rows of different windows. Could we add a row in another window and sort both
sides before comparing?
In addition, the PR description says sliding windows keep working, but there
is no test for it. How about adding a sliding window case like `sf.window("ts",
"5 minutes", "1 minute")`?
##########
python/pyspark/sql/tests/arrow/test_arrow_python_aggregator.py:
##########
@@ -347,6 +348,44 @@ def test_pivot_rejected(self):
with self.assertRaises(AnalysisException):
df.groupBy("k").pivot("p").agg(udaf(Mean())(sf.col("v"))).collect()
+ def test_session_window_rejected(self):
+ # A batch session window groups by one provisional session per row and
relies on the
+ # aggregate operator to merge the overlapping ones. The incremental
operators do not
+ # merge sessions, so grouping by a session window is rejected rather
than returning one
+ # row per unmerged session. A tumbling window needs no merging and
still works.
+ df = self.spark.createDataFrame(
+ [
+ (datetime.datetime(2026, 1, 1, 10, 0), 1.0),
+ (datetime.datetime(2026, 1, 1, 10, 2), 3.0),
+ ],
+ "ts timestamp, v double",
+ )
+ mean = udaf(Mean())
+ df.createOrReplaceTempView("session_input")
+ self.spark.udf.register("session_mean", mean)
+ queries = {
+ "dataframe": lambda: df.groupBy(sf.session_window("ts", "5
minutes")).agg(
Review Comment:
Could we also cover a session window with another grouping key, e.g.
`df.groupBy("k", sf.session_window("ts", "5 minutes"))`? It is the typical
usage of session windows (e.g. per-user sessions), and the current test covers
only a grouping by the session window alone.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala:
##########
@@ -751,6 +751,14 @@ abstract class SparkStrategies extends
QueryPlanner[SparkPlan] {
case PhysicalAggregation(groupingExpressions, aggExpressions,
resultExpressions, child)
if
aggExpressions.forall(_.aggregateFunction.isInstanceOf[PythonAggregate]) =>
Review Comment:
nit: This check runs only when every aggregate function is an incremental
Python aggregator. When it is mixed with a SQL aggregate function, e.g. `SELECT
session_mean(v), count(*) FROM session_input GROUP BY session_window(ts, '5
minutes')`, the fallback case below raises `INVALID_PYTHON_UDF_PLACEMENT`
first, and users hit this new error only after removing `count(*)`. If we move
the check to the analysis (see the other comment) or also check it in the
fallback case, users can see the root cause at once.
##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -9851,6 +9851,11 @@
"Purge table."
]
},
+ "PYTHON_AGGREGATOR_WITH_SESSION_WINDOW" : {
+ "message" : [
+ "The incremental Python aggregate function(s) <functionList> in an
aggregation grouped by a session window."
Review Comment:
nit: Could we tell users what to do instead? For example, `... grouped by a
session window. Use a built-in aggregate function, or group by a tumbling or
sliding window instead.`
--
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]