Spenserrrr commented on code in PR #59892:
URL: https://github.com/apache/spark/pull/59892#discussion_r4548190932
##########
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:
Changed preparation timing to cover conversion and track the full input
iteration locally for subtraction from UDF time. Removed record_sub_duration
and the report-time subtraction. Iterator bookkeeping is left unassigned; its
median share was below 1% in the bounded worker-only cases I checked.
##########
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:
Removed the clock-call assertion. The test now checks the output and empty
metrics report.
##########
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:
Replaced the batch/frame/stream proxies with wrappers around the real
conversion methods. The test keeps unequal input/output batch counts and checks
that input and consumer work are excluded from UDF time.
##########
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:
Reduced this to the two lifecycle cases and removed the stream and read-time
checks. Kept it as a short separate test so the main accounting fixture stays
simple.
##########
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:
Split serializer-category checks from the four-case gate test. The test no
longer changes class support metadata.
--
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]