gaogaotiantian commented on code in PR #60150:
URL: https://github.com/apache/spark/pull/60150#discussion_r4518161289
##########
python/pyspark/sql/profiler.py:
##########
@@ -202,8 +206,20 @@ def _get_ident_from_frame(self, frame: FrameType) -> str:
return f"{code.co_qualname} ({code.co_filename}:{code.co_firstlineno})"
def _get_task_key(self) -> str:
+ # The "sampling_" prefix keeps these keys apart from the other
profilers' keys,
+ # which are UDF result ids (int) or worker module names.
tc = self._task_context
- return
f"{tc.stageId()}_{tc.partitionId()}.{tc.attemptNumber()}_{tc.taskAttemptId()}"
+ if self._aggregation == "query":
+ # The root id groups all micro-batches of a streaming query
together. It is not
+ # set when the UDF does not run in a SQL query, e.g. under
`df.rdd`.
+ root_id = tc.getLocalProperty("spark.sql.execution.root.id")
+ return f"sampling_query_{root_id if root_id is not None else
'unknown'}"
+ elif self._aggregation == "stage":
+ return f"sampling_stage_{tc.stageId()}"
Review Comment:
This is an existing issue rather than one introduced here: the perf and
memory profilers already merge results under the same UDF result id across
tasks, so they take the same unlocked existing-key branch of
`_ProfileResultsParamV2.addInPlace` and can race with `spark.profile.clear()`
on master today. Sharing keys for sampling makes it easier to hit, but the fix
(one lock shared by the merge and the collectors) is independent of this PR, so
it will be fixed in a separate PR.
##########
python/pyspark/sql/profiler.py:
##########
@@ -202,8 +206,20 @@ def _get_ident_from_frame(self, frame: FrameType) -> str:
return f"{code.co_qualname} ({code.co_filename}:{code.co_firstlineno})"
def _get_task_key(self) -> str:
+ # The "sampling_" prefix keeps these keys apart from the other
profilers' keys,
+ # which are UDF result ids (int) or worker module names.
tc = self._task_context
- return
f"{tc.stageId()}_{tc.partitionId()}.{tc.attemptNumber()}_{tc.taskAttemptId()}"
+ if self._aggregation == "query":
+ # The root id groups all micro-batches of a streaming query
together. It is not
+ # set when the UDF does not run in a SQL query, e.g. under
`df.rdd`.
+ root_id = tc.getLocalProperty("spark.sql.execution.root.id")
Review Comment:
Good catch, thanks. Fixed in 05f7f1feffb: the `query` level now uses the
`sql.streaming.queryId` local property if set, then
`spark.sql.execution.root.id`, then `unknown`, so all micro-batches of a
streaming query share one key. The code comment and the conf doc are updated,
and `test_sampling_profiler_aggregation_streaming_query` checks that a query
running in three micro-batches yields a single `sampling_query_<streaming query
id>` result.
The `df.rdd`-over-exchanges split is left as is; it is not a priority for
this PR.
##########
python/pyspark/sql/profiler.py:
##########
@@ -177,19 +180,20 @@ def _start_sampling_thread(self) -> None:
def _sample_loop(self) -> None:
self_tid = threading.get_ident()
while not self._stop_event.wait(self._sampling_interval / 1000):
+ thread_names = {t.ident: t.name for t in threading.enumerate()}
for tid, frame in sys._current_frames().items():
if tid != self_tid:
- self._add_sample(tid, frame)
+ self._add_sample(thread_names.get(tid, str(tid)), frame)
Review Comment:
This is out of scope for this PR, which is about the level at which results
are aggregated. How threads with generated names are grouped within a call tree
is a separate concern, so I'm not changing it here.
##########
python/pyspark/sql/tests/test_udf_profiler.py:
##########
@@ -823,12 +824,83 @@ def collect_idents(node, idents):
self.assertEqual(0, len(self.sampling_profile_results))
self.assertEqual(0,
len(self.spark._profiler_collector._profile_results))
+ def test_sampling_profiler_aggregation(self):
+ import time
+
+ @udf("long")
+ def busy_add1(x):
+ time.sleep(0.05)
+ return x + 1
+
+ df = self.spark.range(10, numPartitions=2).select(busy_add1("id"))
+
+ # Two tasks in one stage of one query.
+ for level, num_results in [("task", 2), ("stage", 1), ("query", 1)]:
Review Comment:
Fixed in 05f7f1feffb. `test_sampling_profiler_aggregation` now runs a query
with a UDF on both sides of a shuffle (two stages of two tasks each, AQE
disabled so the shuffle keeps two partitions), so the levels give different
results: 4 task keys, 2 stage keys and 1 query key matching
`^sampling_query_\d+$` (not `unknown`). It also runs with the level unset and
expects stage keys, pinning the default. `test_sampling_result_param_merge`
checks that same-key call trees are summed node by node.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/PythonUDFRunner.scala:
##########
@@ -57,7 +57,9 @@ abstract class BasePythonUDFRunner(
).getOrElse(Map.empty) ++
Map(
SQLConf.PYTHON_UDF_PROFILER_SAMPLING_INTERVAL.key ->
- SQLConf.get.pythonUDFProfilerSamplingInterval.toString
+ SQLConf.get.pythonUDFProfilerSamplingInterval.toString,
+ SQLConf.PYTHON_UDF_PROFILER_SAMPLING_AGGREGATION.key ->
Review Comment:
Fixed in 05f7f1feffb: `test_sampling_profiler_aggregation` now runs every
level with both `useArrow=True` and `useArrow=False`. I checked that dropping
this entry makes the non-Arrow `task` and `query` subtests fail.
##########
python/pyspark/sql/tests/test_udf_profiler.py:
##########
@@ -823,12 +824,83 @@ def collect_idents(node, idents):
self.assertEqual(0, len(self.sampling_profile_results))
self.assertEqual(0,
len(self.spark._profiler_collector._profile_results))
+ def test_sampling_profiler_aggregation(self):
+ import time
+
+ @udf("long")
+ def busy_add1(x):
+ time.sleep(0.05)
+ return x + 1
+
+ df = self.spark.range(10, numPartitions=2).select(busy_add1("id"))
+
+ # Two tasks in one stage of one query.
+ for level, num_results in [("task", 2), ("stage", 1), ("query", 1)]:
+ with self.subTest(level=level):
+ with self.sql_conf(
+ {
+ "spark.sql.pyspark.udf.profiler": "sampling",
+ "spark.sql.pyspark.udf.profiler.samplingInterval":
"10",
+ "spark.sql.pyspark.udf.profiler.samplingAggregation":
level,
+ }
+ ):
+ df.collect()
+
+ results = self.sampling_profile_results
+ self.spark.profile.clear()
+ self.assertEqual(num_results, len(results), str(list(results)))
+ for key, result in results.items():
+ self.assertTrue(key.startswith(f"sampling_{level}_"), key)
Review Comment:
Fixed in 05f7f1feffb: task-level keys must now match
`^sampling_task_\d+_[01]$` exactly. I checked that re-adding the attempt number
and task attempt id to the key makes the test fail.
--
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]