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


##########
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:
   Used a separate PythonPhaseMetrics trait because StateStoreWriter also 
inherits PythonSQLMetrics for ordinary SQL streaming. This preserves its 
existing common metrics without adding phase fields to non-Python operators. 
Python execution operators, including Python streaming, share the phase schema 
independently of collection; handlers opt into collection through the Python 
gate.



##########
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:
   Yes, this is intentional. The old override kept worker collection aligned 
with the phase fields registered when the plan was built. The shared phase 
schema now registers those fields even when timing is off, so forwarding the 
current setting cannot leave the worker reporting phases that the plan has no 
fields for. It also keeps the collection decision in Python.
   
   For a supported, non-pipelined UDF, a plan created with timing off can now 
collect timing if the setting is enabled before execution creates the runner; 
switching it off before that point disables collection. The integration test 
covers both directions. Added this behavior change to 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:
   Added RunnerConf.is_pipelined and use it for both the worker's execution 
branch and the handler's timing gate. It reads SPARK_PIPELINED_UDF, the actual 
worker mode, so both places use the same definition. The detailed-timing 
configuration value is still forwarded unchanged.



##########
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:
   Removed the explicit zero registration. All seven SQL phase/count fields 
remain registered independently of collection, so an unreported read duration 
still has numeric value zero on the JVM. The serializer registers and updates 
read timing when input is actually consumed.



##########
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:
   Input reads and conversion run inside the UDF's iterator requests, so I now 
keep the full input-iteration duration locally and subtract it from the outer 
UDF timer. Preparation measures the conversion expression after fetching the 
batch. This removes the need to wait for the serializer's read total before 
computing preparation, so record_sub_duration and the report-time subtraction 
are gone.
   
   Iterator bookkeeping outside conversion is left unassigned. A bounded 
identity/Arrow-IPC check found a median residual below 1% of handler processing 
time in the tested narrow and wide cases, including instrumentation overhead. 
That supported the simpler boundary; it is not a production-wide bound.



##########
python/pyspark/worker_metrics.py:
##########
@@ -121,14 +123,23 @@ def measure(self, name: str) -> _WorkerTimer:
         self._duration_totals_ns.setdefault(name, 0)
         return _WorkerTimer(self._duration_totals_ns, name)
 
+    def subtract_duration_at_report(self, *, total_metric: str, nested_metric: 
str) -> None:
+        """Subtract nested_metric from total_metric at report time without 
registering either."""
+        self._duration_subtractions[total_metric] = nested_metric

Review Comment:
   Removed this API entirely with the local timing change. Preparation is 
measured around conversion, and the full nested input iteration is deducted 
from UDF time in the handler. Reporting only converts durations to milliseconds 
now, so it no longer needs to know the nesting relationship.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -5857,7 +5857,10 @@ object SQLConf {
   val PYTHON_UDF_DETAILED_TIMING_ENABLED =
     buildConf("spark.sql.execution.pythonUDF.detailedTiming.enabled")
       .internal()
-      .doc("When true, collect detailed timing metrics for supported Python 
UDFs.")
+      .doc("When true, collect detailed timing metrics for supported Python 
UDFs. " +
+        "With spark.python.udf.pipelined.enabled, phase timings can overlap 
and their sum " +
+        "does not represent elapsed time. Exclude reports with nonzero " +
+        "pythonNumPipelinedTasks from additive phase breakdowns.")

Review Comment:
   Kept detailed timing off in pipeline mode. The background reader's 
serializer therefore writes no detailed read duration, while phase accumulation 
stays on the main worker thread. I left locking and per-thread collection out 
of this PR; either would need to be considered if pipeline timing is added 
later.



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