dongjoon-hyun commented on code in PR #60150:
URL: https://github.com/apache/spark/pull/60150#discussion_r4519184103
##########
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:
**[2] Minor: the thread names are read before the frames, so a thread that
starts or ends in between gets the wrong root.** A thread that
`sys._current_frames()` returns but this snapshot misses, because it started in
between or was still starting, is keyed as `str(tid)`, a root that never merges
across tasks. A thread that ended in between and whose ident was reused is
keyed under the old thread's name. Both are rare, but
`test_sampling_profiler_merge_threads_by_name` starts a `helper` thread in
every call and checks the exact set `{"MainThread", "helper"}`
(test_udf_profiler.py:882), so they can make it flaky. This is about the race,
not about how generated names are grouped. Could the frames be taken first and
the names read right after, and could the test check that both names are among
the roots instead of the exact set?
##########
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:
**[1] With shared keys, a deep call tree can break the driver-side merge.**
With these keys, every update after the first one for a stage or query takes
the existing-key branch of `_ProfileResultsParamV2.addInPlace` and runs
`SamplingResultParam.addInPlace` (`python/pyspark/profiler.py` L172, outside
this diff). That merge recurses once per level of the shared path, and a call
tree is as deep as the sampled stack. So if a UDF raises
`sys.setrecursionlimit` and recurses past about 1,000 frames, for example a
recursive parser, the second task of a stage hits the driver's default limit
and raises `RecursionError`:
- In classic PySpark, it is raised in the accumulator server before the
acknowledgement, so the JVM keeps reusing a dead connection and later Python
accumulator updates are lost, as described in the `clear()` race
[thread](https://github.com/apache/spark/pull/60150#discussion_r4488925635).
- In Spark Connect, `ConnectProfilerCollector._update` is called from the
response loop in `connect/client/core.py` with no handler, so `collect()` fails
after the query itself has succeeded.
Before this PR, each attempt had its own key, so these trees were only
inserted. This is about the depth, not the merge cost you already answered.
Could `SamplingResultParam.addInPlace` merge with an explicit stack instead of
recursion?
##########
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:
**[3] Minor: in Spark Connect, the level does not change the driver's
memory.** The server collects every task's update in the session's
`collectionAccumulator` (`SessionHolder.pythonAccumulator`) and sends them all
to the client as the `__python_accumulator__` observed metrics, and only the
client merges them by key. So the server driver holds one call tree per task
until the `ExecutePlan` ends (for a streaming query started from Connect, until
the next one of the session), whatever the level. Could this say that a finer
level uses more memory where the results are collected, i.e. on the driver in
classic PySpark and on the client in Spark Connect?
##########
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:
**[5] Nit: the results are cleared only after a successful `collect()`.** If
`df.collect()` fails in one subtest, for example a non-Arrow `task` run, the
results of its finished tasks stay, and every later subtest fails its count
check too, which hides the first failure. Could each subtest clear the results
first, or 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()
+ 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:
**[4] Nit: this waits with no timeout, and the query is not stopped if the
test fails.** If the `availableNow` run stops making progress,
`q.awaitTermination()` hangs until the CI job times out. Could it be
`self.assertTrue(q.awaitTermination(60))`, with `q.stop()` in a `finally`, so a
stuck run fails the test and does not outlive the `TemporaryDirectory`?
##########
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":
+ return f"sampling_stage_{tc.stageId()}"
+ else:
Review Comment:
**[6] Nit: an unknown level quietly becomes `task`.** This `else` takes
every value other than `query` and `stage`. `SQLConf` checks the values, so
nothing else arrives today, but a level added there later without a branch here
would run as `task` with no error. Could this check `"task"` explicitly and
raise on anything else?
--
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]