gaogaotiantian commented on code in PR #60150:
URL: https://github.com/apache/spark/pull/60150#discussion_r4544718556
##########
python/pyspark/sql/profiler.py:
##########
@@ -202,8 +206,23 @@ 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":
+ # Each micro-batch of a streaming query is its own SQL execution,
so prefer the
+ # streaming query id to group all of them together. Neither id is
set when the
+ # UDF does not run in a SQL query, e.g. under `df.rdd`.
+ query_id = tc.getLocalProperty("sql.streaming.queryId") or
tc.getLocalProperty(
+ "spark.sql.execution.root.id"
+ )
+ return f"sampling_query_{query_id if query_id is not None else
'unknown'}"
+ elif self._aggregation == "stage":
Review Comment:
Thanks, fixed in 706910db277. `SamplingResultParam.addInPlace` now merges
with an explicit stack of node pairs instead of recursing, so the merge depth
no longer depends on the recursion limit. The result is the same as the
recursive merge (I compared both on 2,000 random tree pairs).
`test_sampling_result_param_merge_deep_tree` merges two call trees 100 levels
deeper than the recursion limit and checks every node's count; it fails with
`RecursionError` against the previous recursive version.
##########
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()}
Review Comment:
Fixed in 706910db277. The sampler now takes `sys._current_frames()` first
and then updates a thread-name map that is kept across samples, instead of
building a new one before the frames. A thread that started between the two
calls is found, and a reused thread id gets the new thread's name once it is
enumerated. Keeping the map also covers the end of a thread: `Thread._delete()`
removes it from `threading.enumerate()` before its last frames are gone, so a
per-sample map could never find it, while the kept map still has its name from
earlier samples.
The remaining gap is a thread whose first frame is sampled before
`_set_ident()` runs at the very start of `_bootstrap_inner`, which falls back
to `str(tid)`. Since that window is a few bytecodes, I kept the exact-set check
in `test_sampling_profiler_merge_threads_by_name`, which passed 10 of 10 runs
in classic and both Connect suites.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -5558,6 +5558,22 @@ object SQLConf {
.checkValue(v => v > 0L, "The sampling interval must be at least 1
millisecond.")
.createWithDefault(100)
+ val PYTHON_UDF_PROFILER_SAMPLING_AGGREGATION =
+ buildConf("spark.sql.pyspark.udf.profiler.samplingAggregation")
+ .doc("The level at which the sampling profiler aggregates the sampled
call stacks: " +
+ "\"query\" merges samples from the same SQL query, or from all
micro-batches of the " +
+ "same streaming query (samples outside a SQL query are merged under
\"unknown\"), " +
+ "\"stage\" merges samples from the same stage, and " +
+ "\"task\" keeps one result per task, merging its attempts. A finer
level uses more " +
Review Comment:
Right, thanks. Updated in 706910db277: the conf doc now says that a finer
level uses more memory where the results are merged, on the driver in classic
PySpark and on the client in Spark Connect, where the server keeps every task's
result until it sends them to the client, whatever the level. The PR
description says the same.
##########
python/pyspark/sql/tests/test_udf_profiler.py:
##########
@@ -823,12 +824,127 @@ 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)
+ # One query with two stages, split by the shuffle, of two tasks
each.
+ df = (
+ self.spark.range(10, numPartitions=2)
+ .select(add1("id").alias("id"))
+ .repartition(2, "id")
+ .select(add1("id"))
+ )
+ 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.
+ "spark.sql.adaptive.enabled": "false",
+ }
+ if level is not None:
+ conf["spark.sql.pyspark.udf.profiler.samplingAggregation"]
= level
+ with self.subTest(use_arrow=use_arrow, level=level),
self.sql_conf(conf):
+ df.collect()
+
+ keys = list(self.sampling_profile_results)
+ self.spark.profile.clear()
+ self.assertEqual(num_results, len(keys), keys)
+ for key in keys:
+ self.assertRegex(key, key_pattern)
+
+ def test_sampling_profiler_merge_threads_by_name(self):
+ import threading
+ import time
+
+ @udf("long")
+ def add1_in_thread(x):
+ t = threading.Thread(target=time.sleep, args=(0.05,),
name="helper")
+ t.start()
+ t.join()
+ return x + 1
+
+ with self.sql_conf(
+ {
+ "spark.sql.pyspark.udf.profiler": "sampling",
+ "spark.sql.pyspark.udf.profiler.samplingInterval": "10",
+ "spark.sql.pyspark.udf.profiler.samplingAggregation": "stage",
+ }
+ ):
+ self.spark.range(10,
numPartitions=2).select(add1_in_thread("id")).collect()
+
+ results = list(self.sampling_profile_results.values())
+ self.assertEqual(1, len(results))
+ # The threads of both tasks are merged by name into one call tree per
name.
+ self.assertEqual({"MainThread", "helper"},
set(results[0]["callstack"]))
+
class UDFProfiler2Tests(UDFProfiler2TestsMixin, ReusedSQLTestCase):
def setUp(self) -> None:
super().setUp()
self.spark._profiler_collector._accumulator._value = {}
+ 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()
+ )
+ q.awaitTermination()
Review Comment:
Done in 706910db277: the test now does
`self.assertTrue(q.awaitTermination(60))`, with `q.stop()` in a `finally`.
##########
python/pyspark/sql/tests/test_udf_profiler.py:
##########
@@ -823,12 +824,127 @@ 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)
+ # One query with two stages, split by the shuffle, of two tasks
each.
+ df = (
+ self.spark.range(10, numPartitions=2)
+ .select(add1("id").alias("id"))
+ .repartition(2, "id")
+ .select(add1("id"))
+ )
+ 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.
+ "spark.sql.adaptive.enabled": "false",
+ }
+ if level is not None:
+ conf["spark.sql.pyspark.udf.profiler.samplingAggregation"]
= level
+ with self.subTest(use_arrow=use_arrow, level=level),
self.sql_conf(conf):
+ df.collect()
+
+ keys = list(self.sampling_profile_results)
+ self.spark.profile.clear()
Review Comment:
Done in 706910db277: each subtest now clears the results before running its
query, so a failed subtest no longer affects the later ones.
--
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]