gaogaotiantian commented on code in PR #60150:
URL: https://github.com/apache/spark/pull/60150#discussion_r4636596452
##########
python/pyspark/sql/tests/test_udf_profiler.py:
##########
@@ -826,6 +828,65 @@ 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):
+ for use_arrow in [True, False]:
+ add1 = udf(lambda x: x + 1, "long", useArrow=use_arrow)
+ for level, num_results, key_pattern in [
+ ("task", 4, r"^sampling_task_\d+_[01]$"),
+ ("stage", 2, r"^sampling_stage_\d+$"),
+ ("query", 1, r"^sampling_query_\d+$"),
+ (None, 2, r"^sampling_stage_\d+$"), # The default level is
"stage".
+ ]:
+ conf = {
+ "spark.sql.pyspark.udf.profiler": "sampling",
+ # Disable AQE so that the shuffle is not coalesced into
one partition.
Review Comment:
Thanks, you are right: `CoalesceShufflePartitions` does not coalesce a
`REPARTITION_BY_NUM` shuffle, so the override guarded nothing. Dropped the
override and its comment in 0036d4a137b. With AQE at its default,
`test_sampling_profiler_aggregation` passed 3 of 3 runs in classic and in Spark
Connect.
##########
python/pyspark/sql/profiler.py:
##########
@@ -148,14 +149,27 @@ class WorkerSamplingProfiler:
SamplingProfiler is a profiler for sampling profiling.
"""
+ # The most frames kept per sample. Pickling a call tree recurses about
twice per level,
+ # which on Python 3.11 counts against the recursion limit (1000 by
default), so a much
+ # deeper tree would fail the task when its result is sent.
+ _MAX_STACK_DEPTH = 256
+
def __init__(
self,
task_context: "TaskContext",
sampling_interval: float = 100,
+ aggregation: str = "stage",
) -> None:
- self._callstack_data: dict[int, dict] = {}
+ # Keyed by thread name, so that threads from different tasks can be
merged.
Review Comment:
Thanks. Added a TODO there in 0036d4a137b: threads whose names CPython
generates from process-wide counters, such as `ThreadPoolExecutor-0_0` or
`Thread-1 (run)`, get a new name with each new thread in a worker, so they
mostly keep separate call trees. I checked both name formats on Python 3.11 and
3.14, and that the Arrow, pandas and elementwise eval handlers start a new pool
per batch when `spark.sql.execution.pythonUDF.arrow.concurrency.level` is set.
The PR description now says so too, including in "Why are the changes needed?".
Grouping them is still left for a separate change.
##########
python/pyspark/profiler.py:
##########
@@ -170,15 +170,18 @@ def zero(value: Dict[str, Any]) -> Dict[str, Any]:
@staticmethod
def addInPlace(value1: Dict[str, Any], value2: Dict[str, Any]) ->
Dict[str, Any]:
- # Combine recursively
- for key, value in value2.items():
- if key not in value1:
- value1[key] = value
- else:
- if isinstance(value, int):
- value1[key] += value
+ # Merge with an explicit stack rather than recursion, because a call
tree is as
+ # deep as the sampled call stack, which can exceed the recursion limit.
Review Comment:
Thanks, updated in 0036d4a137b. The comment now says the explicit stack
keeps the merge independent of the recursion limit, even though
`WorkerSamplingProfiler` caps the depth of the call trees it sends. The comment
on `_MAX_STACK_DEPTH` now also says that the cap bounds the recursive copy in
`_sampling_profile_results`.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/ArrowPythonRunner.scala:
##########
@@ -194,6 +194,7 @@ object ArrowPythonRunner {
SQLConf.PYSPARK_BINARY_AS_BYTES,
SQLConf.PYTHON_UDF_ARROW_WORKER_OUTPUT_BATCH_MAX_BYTES,
SQLConf.PYTHON_UDF_PROFILER_SAMPLING_INTERVAL,
+ SQLConf.PYTHON_UDF_PROFILER_SAMPLING_AGGREGATION,
Review Comment:
Thanks. Not changed in this revision: the new entry is sent the same way as
`spark.sql.pyspark.udf.profiler.samplingInterval` already is on the base
branch, and the PR description says the conf is passed that way. I will follow
up on this thread.
##########
python/pyspark/sql/tests/test_udf_profiler.py:
##########
@@ -888,6 +962,141 @@ def func_std_string_with_merge(func):
self.assertIn("Profile of id", io.getvalue())
self.assertEqual(2, len(self.profile_results["id"].stats))
+ def test_sampling_profiler_aggregation_query_unknown(self):
+ @udf("long")
+ def add1(x):
+ return x + 1
+
+ # Under `df.rdd` the UDF does not run in a SQL query, so there is no
query id.
+ with self.sql_conf(
+ {
+ "spark.sql.pyspark.udf.profiler": "sampling",
+ "spark.sql.pyspark.udf.profiler.samplingAggregation": "query",
+ }
+ ):
+ self.spark.range(10,
numPartitions=2).select(add1("id")).rdd.collect()
+
+ self.assertEqual(["sampling_query_unknown"],
list(self.sampling_profile_results))
+
+ def test_sampling_profiler_aggregation_streaming_query(self):
+ @udf("long")
+ def add1(x):
+ return x + 1
+
+ with tempfile.TemporaryDirectory() as d:
+ for i in range(3):
+ self.spark.range(i, i + 1,
numPartitions=1).write.mode("append").parquet(d)
+
+ with self.sql_conf(
+ {
+ "spark.sql.pyspark.udf.profiler": "sampling",
+ "spark.sql.pyspark.udf.profiler.samplingAggregation":
"query",
+ }
+ ):
+ # One file per micro-batch, so the query runs in three
micro-batches.
+ q = (
+ self.spark.readStream.schema("id long")
+ .option("maxFilesPerTrigger", 1)
+ .parquet(d)
+ .select(add1("id"))
+ .writeStream.format("noop")
+ .trigger(availableNow=True)
+ .start()
+ )
+ try:
+ self.assertTrue(q.awaitTermination(60))
+ finally:
+ q.stop()
+
+ self.assertEqual(3, len(q.recentProgress))
+ # All micro-batches are merged under the streaming query id.
+ self.assertEqual([f"sampling_query_{q.id}"],
list(self.sampling_profile_results))
+
+ def test_sampling_profiler_aggregation_not_allowed(self):
+ # An unknown level fails when the profiler is created, before the UDF
runs.
+ with self.assertRaises(PySparkValueError) as pe:
+ WorkerSamplingProfiler(task_context=mock.Mock(), aggregation="job")
+
+ self.check_error(
+ exception=pe.exception,
+ errorClass="VALUE_NOT_ALLOWED",
+ messageParameters={
+ "arg_name":
"spark.sql.pyspark.udf.profiler.samplingAggregation",
+ "allowed_values": "['query', 'stage', 'task']",
+ },
+ )
+
+ def test_sampling_profiler_unknown_thread(self):
+ import _thread
+ import time
+
+ done = threading.Event()
+
+ def run():
+ time.sleep(0.2)
+ done.set()
+
+ profiler = WorkerSamplingProfiler(task_context=mock.Mock(),
sampling_interval=10)
+ with profiler:
+ # A thread started without the threading module has no name.
+ _thread.start_new_thread(run, ())
+ self.assertTrue(done.wait(10))
+
+ # It is kept under one shared name, not under its thread id.
+ roots = profiler._callstack_data["<unknown thread>"]
+ self.assertTrue(any(".<locals>.run " in ident for ident in roots),
list(roots))
+ self.assertFalse([name for name in profiler._callstack_data if
name.isdigit()])
+
+ def test_sampling_profiler_truncate_deep_stack(self):
Review Comment:
Thanks. Not added in this revision. So far the end-to-end case was checked
by hand: on Python 3.11, with the sampling profiler on, a UDF that recurses 600
frames deep crashed the worker before the cap, on master as well, and now
succeeds with a call tree of 257 levels. I will follow up on this thread.
##########
python/pyspark/sql/tests/test_udf_profiler.py:
##########
@@ -888,6 +962,141 @@ def func_std_string_with_merge(func):
self.assertIn("Profile of id", io.getvalue())
self.assertEqual(2, len(self.profile_results["id"].stats))
+ def test_sampling_profiler_aggregation_query_unknown(self):
+ @udf("long")
+ def add1(x):
+ return x + 1
+
+ # Under `df.rdd` the UDF does not run in a SQL query, so there is no
query id.
+ with self.sql_conf(
+ {
+ "spark.sql.pyspark.udf.profiler": "sampling",
+ "spark.sql.pyspark.udf.profiler.samplingAggregation": "query",
+ }
+ ):
+ self.spark.range(10,
numPartitions=2).select(add1("id")).rdd.collect()
+
+ self.assertEqual(["sampling_query_unknown"],
list(self.sampling_profile_results))
+
+ def test_sampling_profiler_aggregation_streaming_query(self):
+ @udf("long")
+ def add1(x):
+ return x + 1
+
+ with tempfile.TemporaryDirectory() as d:
+ for i in range(3):
+ self.spark.range(i, i + 1,
numPartitions=1).write.mode("append").parquet(d)
+
+ with self.sql_conf(
+ {
+ "spark.sql.pyspark.udf.profiler": "sampling",
+ "spark.sql.pyspark.udf.profiler.samplingAggregation":
"query",
+ }
+ ):
+ # One file per micro-batch, so the query runs in three
micro-batches.
+ q = (
+ self.spark.readStream.schema("id long")
+ .option("maxFilesPerTrigger", 1)
+ .parquet(d)
+ .select(add1("id"))
+ .writeStream.format("noop")
+ .trigger(availableNow=True)
+ .start()
+ )
+ try:
+ self.assertTrue(q.awaitTermination(60))
+ finally:
+ q.stop()
+
+ self.assertEqual(3, len(q.recentProgress))
+ # All micro-batches are merged under the streaming query id.
+ self.assertEqual([f"sampling_query_{q.id}"],
list(self.sampling_profile_results))
+
+ def test_sampling_profiler_aggregation_not_allowed(self):
+ # An unknown level fails when the profiler is created, before the UDF
runs.
+ with self.assertRaises(PySparkValueError) as pe:
+ WorkerSamplingProfiler(task_context=mock.Mock(), aggregation="job")
+
+ self.check_error(
+ exception=pe.exception,
+ errorClass="VALUE_NOT_ALLOWED",
+ messageParameters={
+ "arg_name":
"spark.sql.pyspark.udf.profiler.samplingAggregation",
+ "allowed_values": "['query', 'stage', 'task']",
+ },
+ )
+
+ def test_sampling_profiler_unknown_thread(self):
+ import _thread
+ import time
+
+ done = threading.Event()
+
+ def run():
+ time.sleep(0.2)
+ done.set()
+
+ profiler = WorkerSamplingProfiler(task_context=mock.Mock(),
sampling_interval=10)
+ with profiler:
+ # A thread started without the threading module has no name.
+ _thread.start_new_thread(run, ())
+ self.assertTrue(done.wait(10))
+
+ # It is kept under one shared name, not under its thread id.
+ roots = profiler._callstack_data["<unknown thread>"]
+ self.assertTrue(any(".<locals>.run " in ident for ident in roots),
list(roots))
+ self.assertFalse([name for name in profiler._callstack_data if
name.isdigit()])
+
+ def test_sampling_profiler_truncate_deep_stack(self):
+ profiler = WorkerSamplingProfiler(task_context=mock.Mock())
+ max_depth = WorkerSamplingProfiler._MAX_STACK_DEPTH
+ stack = []
+
+ def recurse(depth):
+ if depth > 0:
+ return recurse(depth - 1)
+ frame = f = sys._getframe()
+ while f is not None:
+ stack.insert(0, profiler._get_ident_from_frame(f))
+ f = f.f_back
+ profiler._add_sample("MainThread", frame)
+
+ recurse(max_depth)
+
+ idents = []
+ node = profiler._callstack_data["MainThread"]
+ while children := [key for key in node if key != "count"]:
+ idents.extend(children)
+ node = node[children[0]]
+ # The outermost frames are kept, and the deeper ones are counted as
truncated.
+ self.assertGreater(len(stack), max_depth)
Review Comment:
Thanks. Not added in this revision;
`test_sampling_profiler_truncate_deep_stack` covers only a stack deeper than
the cap, as you say. I will follow up on this thread.
##########
python/pyspark/sql/profiler.py:
##########
@@ -186,21 +200,35 @@ 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):
- for tid, frame in sys._current_frames().items():
+ # Take the frames first, then update the names, so that a thread
started in
+ # between is found. A reused thread id gets the new thread's name.
+ frames = sys._current_frames()
+ self._thread_names.update(
+ (t.ident, t.name) for t in threading.enumerate() if t.ident is
not None
+ )
+ for tid, frame in frames.items():
if tid != self_tid:
- self._add_sample(tid, frame)
-
- def _add_sample(self, tid: int, frame: Optional[FrameType]) -> None:
- if tid not in self._callstack_data:
- self._callstack_data[tid] = {}
+ # A thread never listed by threading.enumerate(), e.g. one
started with
+ # _thread.start_new_thread(), has no name. Its id means
nothing across
+ # tasks, so all such threads share one call tree.
Review Comment:
Thanks, you are right. I reproduced it on Python 3.11 and 3.14: a
`_thread.start_new_thread()` thread that reused the id of a joined `helper`
thread was recorded under `helper`, not under `<unknown thread>`. The code is
unchanged, and in 0036d4a137b the comment now says what happens: a thread is
named once `threading.enumerate()` lists it with its id; before that, or always
if it is never listed, its samples go under the name last seen for its id,
which a reused id keeps from an exited thread, or else under `<unknown
thread>`. The PR description says the same. The comment above it, on taking the
frames before the names, no longer claims more than that either.
--
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]