spark-test commented on code in PR #59892:
URL: https://github.com/apache/spark/pull/59892#discussion_r4407199423


##########
python/pyspark/sql/tests/pandas/test_pandas_map.py:
##########
@@ -627,6 +627,71 @@ 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))

Review Comment:
   **Nit (P3):** `SQLMetric.value()` returns 0 for a metric that was never 
updated, and `SQLMetric.add` ignores negative values, so this line can't fail. 
If `pythonDataReadTime`, `pythonInputPreparationTime`, 
`pythonOutputPreparationTime` or `pythonDataWriteTime` stopped reaching the 
JVM, each would read 0. That covers a renamed key, a dropped report entry, or a 
negative derived value. Zero values also satisfy the sum bound below, so only 
UDF time and the counts would catch anything. 
`ArrowPythonUDFNonLegacyTests.test_phase_metrics` checks `isZero()` per phase 
for this. The handler and `dump_stream` report all five phases whenever a timed 
task runs, so the check also holds for the empty-partition subtest:
   
   ```suggestion
                       for name in phase_names:
                           self.assertFalse(metrics.apply(name).isZero(), name)
   ```
   
   **Verification:**
   - **Regression:** With detailed timing enabled, the mapInPandas end-to-end 
test asserts that every phase metric was recorded. The assertion must fail when 
a phase report never reaches the JVM metric, for example when the worker omits 
the key or reports a negative value that the metric ignores.



##########
python/pyspark/worker.py:
##########
@@ -201,6 +201,9 @@ def pipelined_process():
             Pipelined variant of process() that pre-fetches input batches in a 
background
             reader thread while the main thread computes the UDF and writes 
output.
             This allows input deserialization to overlap with UDF computation.
+            Detailed phase timings still measure these overlapping operations; 
their sum

Review Comment:
   **Nit (P3):** For mapInPandas this sentence doesn't hold. 
`PandasMapUDFHandler.run` registers the report-time subtraction of 
`pythonDataReadTime` from `pythonInputPreparationTime` in every mode 
(`_pandas.py:257-259`). Under pipelining, `load_stream` and its read timer run 
on the reader thread (line 222), but the handler's input interval covers only 
`input_queue.get()` plus `to_pandas`. The reported value is therefore queue 
wait plus conversion minus concurrent reads. That is not an input-preparation 
time:
   - when the reader is the bottleneck, each batch nets about -(UDF + output + 
write time);
   - when the UDF is the bottleneck, each batch nets conversion minus read.
   
   A standalone model of these interval boundaries gave about +21 ms 
sequentially, but about -17 ms (reader-bound) and -7 ms (UDF-bound) pipelined, 
for 10 batches with 2 ms of real conversion each. A negative task total floors 
to negative milliseconds and `SQLMetric.add` ignores it, so the operator total 
silently omits those tasks while `pythonNumTimingReports` still counts them.
   
   The other three caveats have the same gap: the 
`spark.sql.execution.pythonUDF.detailedTiming.enabled` doc in `SQLConf.scala`, 
the `spark.python.udf.pipelined.enabled` doc in `Python.scala`, and the 
`_WorkerTimer` docstring. They limit the exclusion to additive breakdowns, 
which implies single phases stay usable. The PR description says pipelined 
derived durations can be negative and that pipelined reports must be excluded 
from phase analysis, but none of the four caveats says so. Only mapInPandas 
input preparation in pipelined mode is affected. Sequential timing and the 
Arrow-batched UDF handler, which starts its input interval after the pull, are 
fine.
   
   **Verification:**
   - **Inspection:** The pipelined worker docstring, the internal 
detailed-timing config doc and the worker timer docstring describe mapInPandas 
input preparation as invalid for pipelined tasks. Those three caveats and the 
public pipelined config doc all say that pipelined reports are excluded from 
phase analysis. None of them claims that every phase remains a valid 
measurement under pipelining.



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