gaogaotiantian commented on code in PR #59892:
URL: https://github.com/apache/spark/pull/59892#discussion_r4531645361


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/PythonSQLMetrics.scala:
##########
@@ -21,14 +21,16 @@ import org.apache.spark.sql.execution.SparkPlan
 import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics}
 
 trait PythonSQLMetrics { self: SparkPlan =>
+  // Register all phase metrics; Python decides whether to collect them.
+  // A zero pythonNumTimingReports means detailed timing data is unavailable.
   protected val pythonMetrics: Map[String, SQLMetric] = {
     sizeMetricsDesc.map { case (k, v) =>
       k -> SQLMetrics.createSizeMetric(sparkContext, v)
     } ++ timingMetricsDesc.map { case (k, v) =>
       k -> SQLMetrics.createTimingMetric(sparkContext, v)
     } ++ otherMetricsDesc.map { case (k, v) =>
       k -> SQLMetrics.createMetric(sparkContext, v)
-    } ++ additionalMetrics
+    } ++ additionalMetrics ++ createPythonPhaseMetrics()

Review Comment:
   Is it intended that this registers all 7 phase metrics on every operator 
that mixes in `PythonSQLMetrics`, regardless of the config?
   
   Through `StateStoreWriter` (`statefulOperators.scala`) that includes every 
streaming stateful operator, even plain SQL streaming aggregations, dedup and 
joins. It also covers BatchEval, grouped/cogrouped map, window, aggregate and 
UDTF operators. None of them can report these metrics, so they appear as 
always-zero entries and extra accumulators. The `StreamingAggregationSuite` and 
`InProcessPythonUDFSuite` changes are side effects of this.
   
   If it isn't intended, one option that keeps the "Python decides whether to 
collect" model: register the metrics, with no config check, only on operators 
that can report them, i.e. `ArrowEvalPythonExec` for `SQL_ARROW_BATCHED_UDF`, 
and `MapInPandasExec` rather than the shared `MapInBatchExec`.



##########
python/pyspark/eval_handlers/_pandas.py:
##########
@@ -243,49 +246,112 @@ def __init__(
         )
 
     def run(self, split_index: int, data: "Iterator[pa.RecordBatch]") -> 
"Iterator[pa.RecordBatch]":
+        metrics = WorkerMetrics()
+        phase_timers = self._create_phase_timers()
+        if phase_timers is not None:
+            # If the UDF never pulls from its lazy input iterator, the 
serializer's load_stream()
+            # may never start, leaving the read timer unregistered. Register a 
zero for that case.
+            metrics.measure("pythonDataReadTime")

Review Comment:
   This zero doesn't affect the SQL metric: `handleMetricsData` only adds keys 
that are present in the report, so a missing key and a zero end up the same.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/PythonSQLMetrics.scala:
##########
@@ -21,14 +21,16 @@ import org.apache.spark.sql.execution.SparkPlan
 import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics}
 
 trait PythonSQLMetrics { self: SparkPlan =>
+  // Register all phase metrics; Python decides whether to collect them.

Review Comment:
   This comment contradicts the `PythonPickleBatchMetrics` scaladoc below, 
which says operator-specific metrics stay out of the shared trait "so they do 
not surface as always-zero rows". Whichever way the question on line 33 is 
settled, the two comments should agree.



##########
python/pyspark/sql/tests/pandas/test_pandas_map.py:
##########
@@ -627,6 +627,72 @@ def tearDownClass(cls):
         time.tzset()
         ReusedSQLTestCase.tearDownClass()
 
+    def test_phase_metrics(self):
+        def rebatch(dfs):
+            frames = list(dfs)
+            time.sleep(0.01)
+            if frames:
+                combined = pd.concat(frames)
+                yield combined.iloc[:1]
+                yield combined.iloc[1:]
+
+        phase_names = (
+            "pythonDataReadTime",
+            "pythonInputPreparationTime",
+            "pythonUDFExecutionTime",
+            "pythonOutputPreparationTime",
+            "pythonDataWriteTime",
+        )
+        with self.sql_conf(
+            {
+                "spark.sql.execution.arrow.maxRecordsPerBatch": "2",
+                "spark.sql.adaptive.enabled": "false",
+                "spark.sql.execution.pythonUDF.detailedTiming.enabled": "true",
+            }
+        ):
+            for num_rows, legacy in ((5, False), (0, False), (5, True)):

Review Comment:
   The `legacy=True` case doesn't exercise anything new: `PandasMapUDFHandler` 
has no `variant_conf`, so the legacy flag doesn't change which handler runs. 
Could it be dropped?



##########
python/pyspark/sql/tests/pandas/test_pandas_map.py:
##########
@@ -627,6 +627,72 @@ def tearDownClass(cls):
         time.tzset()
         ReusedSQLTestCase.tearDownClass()
 
+    def test_phase_metrics(self):
+        def rebatch(dfs):
+            frames = list(dfs)
+            time.sleep(0.01)
+            if frames:
+                combined = pd.concat(frames)
+                yield combined.iloc[:1]
+                yield combined.iloc[1:]
+
+        phase_names = (
+            "pythonDataReadTime",
+            "pythonInputPreparationTime",
+            "pythonUDFExecutionTime",
+            "pythonOutputPreparationTime",
+            "pythonDataWriteTime",
+        )
+        with self.sql_conf(
+            {
+                "spark.sql.execution.arrow.maxRecordsPerBatch": "2",
+                "spark.sql.adaptive.enabled": "false",
+                "spark.sql.execution.pythonUDF.detailedTiming.enabled": "true",
+            }
+        ):
+            for num_rows, legacy in ((5, False), (0, False), (5, True)):
+                with (
+                    self.subTest(num_rows=num_rows, legacy=legacy),
+                    self.sql_conf(
+                        {
+                            
"spark.sql.legacy.execution.pythonUDF.pandas.conversion.enabled": str(
+                                legacy
+                            ).lower()
+                        }
+                    ),
+                ):
+                    data = self.spark.createDataFrame(
+                        self.sc.parallelize([(i,) for i in range(num_rows)], 
1), "id long"
+                    )
+                    result = data.mapInPandas(rebatch, "id long")
+                    self.assertEqual(result.collect(), [Row(i) for i in 
range(num_rows)])
+                    metrics = 
result._jdf.queryExecution().executedPlan().metrics()
+                    
self.assertEqual(metrics.apply("pythonNumTimingReports").value(), 1)
+                    self.assertEqual(
+                        metrics.apply("pythonNumTimedBatches").value(), 
(num_rows + 1) // 2
+                    )
+                    phases = [metrics.apply(name).value() for name in 
phase_names]
+                    self.assertTrue(all(value >= 0 for value in phases))
+                    self.assertGreaterEqual(phases[2], 10)
+                    self.assertLessEqual(sum(phases), 
metrics.apply("pythonProcessingTime").value())
+
+    def test_phase_metrics_follow_execution_config(self):

Review Comment:
   This duplicates `test_phase_metrics_follow_execution_config` in 
`test_arrow_python_udf.py`. One copy should be enough (if the execution-time 
behavior is intended).



##########
python/pyspark/sql/tests/arrow/test_arrow_python_udf.py:
##########
@@ -651,28 +651,132 @@ def run():
             "pythonNumTimedBatches",
         )
         for name in detailed_metrics:
-            self.assertFalse(metrics.contains(name), name)
+            self.assertEqual(metrics.apply(name).value(), 0, name)
         self.assertTrue(metrics.contains("pythonProcessingTime"))
         self.assertTrue(metrics.contains("pythonNumPipelinedTasks"))
 
-    def test_phase_metrics_on_materialized_plan_after_config_change(self):
+    def test_phase_metrics_follow_execution_config(self):
         add_one = udf(lambda value: value + 1, "long", useArrow=True)
         timing_conf = "spark.sql.execution.pythonUDF.detailedTiming.enabled"
 
         with self.sql_conf({"spark.sql.adaptive.enabled": "false"}):
-            with self.sql_conf({timing_conf: "true"}):
-                result = self.spark.range(2, 
numPartitions=1).select(add_one("id"))
-                plan = result._jdf.queryExecution().executedPlan()
-                while plan.nodeName() != "ArrowEvalPython":
-                    self.assertEqual(plan.children().size(), 1)
-                    plan = plan.children().apply(0)
-                metrics = plan.metrics()
-                self.assertTrue(metrics.contains("pythonNumTimingReports"))
+            for enabled in (True, False):
+                with self.subTest(enabled=enabled):
+                    with self.sql_conf({timing_conf: str(enabled).lower()}):
+                        result = self.spark.range(2, 
numPartitions=1).select(add_one("id"))
+                        plan = result._jdf.queryExecution().executedPlan()
+                        while plan.nodeName() != "ArrowEvalPython":
+                            self.assertEqual(plan.children().size(), 1)
+                            plan = plan.children().apply(0)
+                        metrics = plan.metrics()
+                        
self.assertTrue(metrics.contains("pythonNumTimingReports"))
+                    with self.sql_conf({timing_conf: str(not 
enabled).lower()}):
+                        self.assertEqual([row[0] for row in result.collect()], 
[1, 2])
+                    self.assertEqual(
+                        metrics.apply("pythonNumTimingReports").value(), 
int(not enabled)
+                    )
 
-            self.assertEqual(self.spark.conf.get(timing_conf), "false")
-            self.assertEqual([row[0] for row in result.collect()], [1, 2])
-            self.assertEqual(metrics.apply("pythonNumTimingReports").value(), 
1)
-            self.assertEqual(metrics.apply("pythonNumTimedBatches").value(), 1)
+    def test_phase_metrics_disabled_for_unsupported_handlers(self):

Review Comment:
   This and `test_phase_metrics_disabled_when_plan_switches_to_legacy` (~110 
lines together) could be merged into one test that just checks 
`pythonNumTimingReports == 0` on the Python node of each plan. The in-UDF 
`WorkerMetrics` asserts and the JVM `getPythonRunnerConfMap` check don't add 
coverage, and the legacy-switch test overlaps the "legacy" subtest here.



##########
python/pyspark/eval_handlers/_pandas.py:
##########
@@ -243,49 +246,112 @@ def __init__(
         )
 
     def run(self, split_index: int, data: "Iterator[pa.RecordBatch]") -> 
"Iterator[pa.RecordBatch]":
+        metrics = WorkerMetrics()
+        phase_timers = self._create_phase_timers()
+        if phase_timers is not None:
+            # If the UDF never pulls from its lazy input iterator, the 
serializer's load_stream()
+            # may never start, leaving the read timer unregistered. Register a 
zero for that case.
+            metrics.measure("pythonDataReadTime")
+
+            # Sequential input intervals include reads. Record their nesting 
because
+            # the serializer may publish its read total after the handler 
finishes.
+            metrics.record_sub_duration(
+                parent_metric="pythonInputPreparationTime", 
sub_metric="pythonDataReadTime"
+            )
+
+        clock = time.perf_counter_ns
+        input_duration_ns = 0
+        udf_duration_ns = 0
+        output_duration_ns = 0
+        num_timed_batches = 0
+
         def dataframe_iter() -> "Iterator[Any]":
+            nonlocal input_duration_ns, num_timed_batches
             # Input batches have a single struct column (see 
MapInBatchEvaluatorFactory);
             # convert lazily so peakmem stays bounded by one batch.
-            for batch in data:
-                yield ArrowToPandasConversion.to_pandas(
-                    batch,
+            while True:
+                if phase_timers is not None:
+                    input_start_ns = clock()

Review Comment:
   `record_sub_duration` (and the `to_dict` changes in `worker_metrics.py`) are 
needed only because this input interval wraps `next(data)`, which includes the 
serializer's read. This could be avoided while keeping the `phase_timers is not 
None` switch:
   
   - Time only `ArrowToPandasConversion.to_pandas` as input preparation, as 
`ArrowBatchedUDFArrowHandler` does (its input preparation also excludes the 
read).
   - Keep a separate local total of all time spent inside `dataframe_iter`, 
from resume to yield, which includes the read.
   - Subtract that total from UDF time.
   
   The serializer keeps reporting `pythonDataReadTime` itself, and the phases 
still add up. `record_sub_duration`, the `to_dict` changes and 
`test_record_sub_duration` could then go.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/ArrowEvalPythonExec.scala:
##########
@@ -90,20 +89,8 @@ case class ArrowEvalPythonExec(
     throw SparkException.internalError(s"Unexpected eval type $evalType")
   }
 
-  override protected def additionalMetrics: Map[String, SQLMetric] = {
-    if (evalType == PythonEvalType.SQL_ARROW_BATCHED_UDF &&
-        !conf.legacyPandasConversionUDF && 
conf.pythonUDFDetailedTimingEnabled) {
-      createPythonPhaseMetrics()
-    } else {
-      Map.empty
-    }
-  }
-
-  // SQL metrics are fixed with the plan; use that decision if the session 
setting changes later.
   private def pythonRunnerConfMap: Map[String, String] =
-    ArrowPythonRunner.getPythonRunnerConfMap(conf).updated(
-      SQLConf.PYTHON_UDF_DETAILED_TIMING_ENABLED.key,
-      pythonMetrics.contains("pythonNumTimingReports").toString)
+    ArrowPythonRunner.getPythonRunnerConfMap(conf)

Review Comment:
   This removes the override that pinned the runner config to the plan's 
decision ("SQL metrics are fixed with the plan; use that decision if the 
session setting changes later"), and 
`test_phase_metrics_on_materialized_plan_after_config_change` became 
`test_phase_metrics_follow_execution_config`, which asserts the opposite. That 
reverses a deliberate earlier choice. Is the execution-time behavior intended? 
If so, could you call it out in the PR description?



##########
python/pyspark/eval_handlers/_base.py:
##########
@@ -170,6 +175,11 @@ def __init__(
         self._udf_descs: list[Any] = udf_descs
         self._runner_conf = runner_conf
         self._eval_conf = eval_conf
+        self._detailed_timing_enabled = (
+            self._supports_detailed_timing
+            and runner_conf.detailed_timing_enabled
+            and os.environ.get("SPARK_PIPELINED_UDF") != "1"

Review Comment:
   This repeats the `SPARK_PIPELINED_UDF` check in `worker.py` (`is_pipelined = 
os.environ.get("SPARK_PIPELINED_UDF") == "1"`). It would be better to have one 
source, e.g. a `RunnerConf` property or a value the worker passes in.



##########
python/pyspark/eval_handlers/tests/test_pandas_eval_type_handlers.py:
##########
@@ -431,6 +433,198 @@ def double_v(df_iter):
         out = list(handler.run(0, iter([struct_batch])))
         self.assertEqual(out[0].column(0).field("v").to_pylist(), [2, 4, 6])
 
+    def test_detailed_timing_disabled(self):
+        metrics = WorkerMetrics()
+        metrics.reset()
+        self.addCleanup(metrics.reset)
+        batch = ArrowBatchTransformer.wrap_struct(self._batch(v=[1, 2]))
+        handler = self._handler(lambda dfs: dfs, self._return_type)
+        with patch(
+            "pyspark.eval_handlers._pandas.time.perf_counter_ns",
+            side_effect=AssertionError("Timing is disabled"),

Review Comment:
   `metrics.to_dict() == {}` is enough here. Asserting that `perf_counter_ns` 
is never called fixes an implementation detail in place.



##########
python/pyspark/eval_handlers/tests/test_pandas_eval_type_handlers.py:
##########
@@ -431,6 +433,198 @@ def double_v(df_iter):
         out = list(handler.run(0, iter([struct_batch])))
         self.assertEqual(out[0].column(0).field("v").to_pylist(), [2, 4, 6])
 
+    def test_detailed_timing_disabled(self):
+        metrics = WorkerMetrics()
+        metrics.reset()
+        self.addCleanup(metrics.reset)
+        batch = ArrowBatchTransformer.wrap_struct(self._batch(v=[1, 2]))
+        handler = self._handler(lambda dfs: dfs, self._return_type)
+        with patch(
+            "pyspark.eval_handlers._pandas.time.perf_counter_ns",
+            side_effect=AssertionError("Timing is disabled"),
+        ):
+            output = list(handler.run(0, iter([batch])))
+        self.assertEqual(output[0].num_rows, 2)
+        self.assertEqual(metrics.to_dict(), {})
+
+    def test_phase_timing_excludes_nested_input_and_output_writes(self):

Review Comment:
   This could be a much smaller fake-clock test. Patch `to_pandas`, 
`from_pandas` and `perf_counter_ns` instead of subclassing 
`RecordBatch`/`DataFrame`; the current proxies depend on which methods the 
conversion code happens to call internally (`column()`, `__getitem__`). The 
`TimedStream` serializer I/O part can go, since `ArrowStreamTimingTests` 
already covers serializer timing; simulate the read by advancing the clock 
inside the `data()` generator. For example:
   
   ```python
   clock_ns = 0
   def advancing(ns, fn):
       def wrapped(*args, **kwargs):
           nonlocal clock_ns
           clock_ns += ns
           return fn(*args, **kwargs)
       return wrapped
   # patch perf_counter_ns -> lambda: clock_ns
   # patch to_pandas / from_pandas with advancing(3ms / 5ms, original)
   # data() advances 17ms per batch (read); the UDF advances 7ms per call
   # assert input == 3 * n, output == 5 * m, UDF == 7 (excludes read + input)
   ```



##########
python/pyspark/sql/tests/pandas/test_pipelined_udf.py:
##########
@@ -78,6 +78,66 @@ def check_env(x: pd.Series) -> pd.Series:
             plan = plan.children().apply(0)
         
self.assertEqual(plan.metrics().apply("pythonNumPipelinedTasks").value(), 1)
 
+    def test_detailed_timing_is_disabled(self):

Review Comment:
   Checking `pythonNumPipelinedTasks == 1` and `pythonNumTimingReports == 0` 
for the two handlers should be enough. Existing tests already cover the general 
boot/init/total/processing timing, and the in-UDF `check_untimed` is redundant.



##########
python/pyspark/eval_handlers/tests/test_base_eval_type_handlers.py:
##########
@@ -99,13 +103,44 @@ class 
_CoGrouped(CoGroupedEvalTypeHandler["pa.RecordBatch"]):
             def run(self, split_index, data):
                 return data
 
-        self.assertIsInstance(_Batch([], RunnerConf({}), None).serializer, 
ArrowStreamSerializer)
-        self.assertIsInstance(
-            _Grouped([], RunnerConf({}), None).serializer, 
ArrowStreamGroupSerializer
-        )
-        self.assertIsInstance(
-            _CoGrouped([], RunnerConf({}), None).serializer, 
ArrowStreamCoGroupSerializer
-        )
+        for handler_class, serializer_class in (
+            (_Batch, ArrowStreamSerializer),
+            (_Grouped, ArrowStreamGroupSerializer),
+            (_CoGrouped, ArrowStreamCoGroupSerializer),
+        ):
+            for supported, enabled, pipelined in (

Review Comment:
   This runs a matrix of 3 categories x 4 cases and mutates 
`_supports_detailed_timing` on the classes. How about keeping the original 
three `assertIsInstance` checks, and adding a separate small gate test on one 
batch handler with 4 cases: not supported, not enabled, pipelined, and all on?



##########
python/pyspark/eval_handlers/tests/test_pandas_eval_type_handlers.py:
##########
@@ -431,6 +433,198 @@ def double_v(df_iter):
         out = list(handler.run(0, iter([struct_batch])))
         self.assertEqual(out[0].column(0).field("v").to_pylist(), [2, 4, 6])
 
+    def test_detailed_timing_disabled(self):
+        metrics = WorkerMetrics()
+        metrics.reset()
+        self.addCleanup(metrics.reset)
+        batch = ArrowBatchTransformer.wrap_struct(self._batch(v=[1, 2]))
+        handler = self._handler(lambda dfs: dfs, self._return_type)
+        with patch(
+            "pyspark.eval_handlers._pandas.time.perf_counter_ns",
+            side_effect=AssertionError("Timing is disabled"),
+        ):
+            output = list(handler.run(0, iter([batch])))
+        self.assertEqual(output[0].num_rows, 2)
+        self.assertEqual(metrics.to_dict(), {})
+
+    def test_phase_timing_excludes_nested_input_and_output_writes(self):
+        metrics = WorkerMetrics()
+        metrics.reset()
+        self.addCleanup(metrics.reset)
+        clock_ns = 0
+        input_ns = 0
+        output_ns = 0
+
+        class TimedBatch:
+            def __init__(self, batch):
+                self.batch = batch
+
+            def __getattr__(self, name):
+                return getattr(self.batch, name)
+
+            def column(self, index):
+                nonlocal clock_ns, input_ns
+                clock_ns += 3_000_000
+                input_ns += 3_000_000
+                return self.batch.column(index)
+
+        class OutputFrame(pd.DataFrame):
+            def __getitem__(self, key):
+                nonlocal clock_ns, output_ns
+                clock_ns += 5_000_000
+                output_ns += 5_000_000
+                return super().__getitem__(key)
+
+        class TimedStream(BytesIO):
+            read_ns = 0
+            write_ns = 0
+
+            def read(self, size=-1):
+                nonlocal clock_ns
+                clock_ns += 17_000_000
+                self.read_ns += 17_000_000
+                return super().read(size)
+
+            def write(self, data):
+                nonlocal clock_ns
+                clock_ns += 19_000_000
+                self.write_ns += 19_000_000
+                return super().write(data)
+
+        def udf(dfs):
+            nonlocal clock_ns
+            clock_ns += 7_000_000
+            combined = pd.concat(list(dfs))
+
+            def results():
+                nonlocal clock_ns
+                for start, end in ((0, 1), (1, 4), (4, 5)):
+                    clock_ns += 13_000_000
+                    yield OutputFrame(combined.iloc[start:end])
+                clock_ns += 11_000_000
+
+            return results()
+
+        handler = self._handler(
+            udf,
+            self._return_type,
+            
RunnerConf({"spark.sql.execution.pythonUDF.detailedTiming.enabled": "true"}),
+        )
+        batches = [
+            ArrowBatchTransformer.wrap_struct(self._batch(v=[1, 2])),
+            ArrowBatchTransformer.wrap_struct(self._batch(v=[3, 4, 5])),
+        ]
+        raw_input = BytesIO()
+        with pa.ipc.new_stream(raw_input, batches[0].schema) as writer:
+            for batch in batches:
+                writer.write_batch(batch)
+        input_stream = TimedStream(raw_input.getvalue())
+        output_stream = TimedStream()
+
+        def data():
+            nonlocal clock_ns, input_ns
+            for batch in handler.serializer.load_stream(input_stream):
+                clock_ns += 23_000_000
+                input_ns += 23_000_000
+                yield TimedBatch(batch)
+            clock_ns += 29_000_000
+            input_ns += 29_000_000
+
+        with patch("pyspark.eval_handlers._pandas.time.perf_counter_ns", 
new=lambda: clock_ns):
+            handler.serializer.dump_stream(handler.run(0, data()), 
output_stream)
+
+        output = list(pa.ipc.open_stream(output_stream.getvalue()[4:]))
+        self.assertEqual([batch.num_rows for batch in output], [1, 3, 1])
+        report = metrics.to_dict()
+        self.assertEqual(report["pythonNumTimedBatches"], 2)
+        self.assertEqual(report["pythonDataReadTime"], input_stream.read_ns // 
1_000_000)
+        self.assertEqual(report["pythonInputPreparationTime"], input_ns // 
1_000_000)
+        self.assertGreater(input_ns, 0)
+        self.assertEqual(report["pythonUDFExecutionTime"], 7 + 3 * 13 + 11)
+        self.assertEqual(report["pythonOutputPreparationTime"], output_ns // 
1_000_000)
+        self.assertGreater(output_ns, 0)
+        self.assertEqual(report["pythonDataWriteTime"], output_stream.write_ns 
// 1_000_000)
+        self.assertEqual(
+            sum(
+                report[name]
+                for name in (
+                    "pythonDataReadTime",
+                    "pythonInputPreparationTime",
+                    "pythonUDFExecutionTime",
+                    "pythonOutputPreparationTime",
+                    "pythonDataWriteTime",
+                )
+            ),
+            clock_ns // 1_000_000,
+        )
+
+    def test_timing_with_unconsumed_input_and_early_close(self):

Review Comment:
   This could be folded into the phase-accounting test above as `subTest`s 
(`consumed=0`, and `consumed=1` plus `close()`), asserting only 
`pythonNumTimedBatches` and `pythonUDFExecutionTime`. Without the zero 
pre-registration, the read-time checks aren't needed.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingAggregationSuite.scala:
##########
@@ -862,6 +862,13 @@ class StreamingAggregationSuite extends 
StateStoreMetricsTest with Assertions {
       StartStream(additionalConfs = Map(SQLConf.SHUFFLE_PARTITIONS.key -> 
"3")),
       AddData(inputData, 3, 2, 1, 3),
       CheckLastBatch((3, 2), (2, 1), (1, 1)),
+      Execute { query =>
+        val stores = query.lastExecution.executedPlan.collect {
+          case store: StateStoreSaveExec => store
+        }
+        assert(stores.nonEmpty)
+        assert(stores.forall(_.metrics("pythonNumTimingReports").value == 0))

Review Comment:
   This asserts that `StateStoreSaveExec` carries `pythonNumTimingReports`, 
which is a side effect of the shared-trait registration in `PythonSQLMetrics` 
(see the comment there). This change and the `InProcessPythonUDFSuite` one 
would go away if the metrics are registered only on operators that can report 
them.



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