spark-test commented on code in PR #60150:
URL: https://github.com/apache/spark/pull/60150#discussion_r4624085605


##########
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:
   **Nit (P3):** `repartition(2, "id")` builds a `RepartitionByExpression` with 
a fixed partition count, which `SparkStrategies` plans as a shuffle with origin 
`REPARTITION_BY_NUM` 
(sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala:1163-1170),
 in classic PySpark and in Spark Connect alike. `CoalesceShufflePartitions` 
only coalesces `ENSURE_REQUIREMENTS`, `REPARTITION_BY_COL` and the two 
`REBALANCE_PARTITIONS_*` origins (CoalesceShufflePartitions.scala:38-40), so 
with AQE on, this shuffle keeps both reduce partitions. The map-stage job AQE 
submits also keeps the query's local properties 
(`SQLExecution.withThreadLocalCaptured`), so the query key does not change 
either. The override therefore guards nothing, or guards some AQE effect that 
this comment does not name. Unless something else depends on it, consider 
dropping the override and this comment; otherwise, the comment should say what 
it guards.
   
   **Verification:**
   - **Behavior:** With adaptive query execution left at its default, a query 
with a Python UDF on both sides of a repartition to two partitions still yields 
four task results, two stage results and one query result, and stage results 
when the level is unset, for Arrow and non-Arrow UDFs in classic PySpark and 
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:
   **Nit (P3):** Names that CPython generates carry process-wide counters 
(`ThreadPoolExecutor-<K>_<i>`, `Thread-<N> (<target>)`, `Dummy-<N>`), and the 
Arrow, pandas and elementwise eval handlers start a new unnamed 
`ThreadPoolExecutor` for every batch when 
`spark.sql.execution.pythonUDF.arrow.concurrency.level` is set 
(python/pyspark/eval_handlers/_arrow.py:918). Each such thread gets a name that 
no other thread in its worker process shares, so it keeps its own call tree at 
every level. A result therefore grows with the tasks and batches it covers, and 
at the query level with the micro-batches of a running streaming query. You 
left that grouping for a separate change, and this review does not ask for it, 
but nothing here says so. A TODO would keep readers from taking this comment to 
cover every thread:
   
   ```suggestion
           # Keyed by thread name, so that threads from different tasks can be 
merged.
           # TODO: Threads whose names CPython generates with process-wide 
counters, such as
           # ThreadPoolExecutor-<K>_<i> or Thread-<N> (<target>), keep one call 
tree per exact
           # name, so they do not merge across batches or tasks. Grouping them 
is left for later.
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60150#discussion_r4488925631).
   
   **Verification:**
   - **Inspection:** The comment where WorkerSamplingProfiler keys call trees 
by thread name states that threads with CPython-generated names, such as 
per-batch ThreadPoolExecutor workers, keep one call tree per exact name and do 
not merge across batches or tasks, marks their grouping as deferred work, and 
no code changes.



##########
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:
   **Nit (P3):** With `WorkerSamplingProfiler._MAX_STACK_DEPTH`, every call 
tree this version's workers send is at most 257 levels deep, so a call tree is 
no longer as deep as the sampled stack. The comment on 
`_sampling_profile_results` (python/pyspark/sql/profiler.py:475-477) relies on 
exactly that bound to say the recursive `copy.deepcopy` is safe, so the two 
comments now contradict each other. The PR description gives the reason that 
still holds, that the merge should not depend on the recursion limit at all:
   
   ```suggestion
           # Merge with an explicit stack rather than recursion, so that the 
merge does not depend
           # on the recursion limit, even though WorkerSamplingProfiler caps 
the depth of its trees.
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60150#discussion_r4593453506).
   
   **Verification:**
   - **Inspection:** The comment on the explicit-stack merge describes the 
explicit stack as keeping the merge independent of the recursion limit for 
trees from any producer and no longer says that this version's call trees are 
as deep as the sampled stack.



##########
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:
   **Nit (P3):** This is a plain `ConfigEntry` in the always-sent list, so 
`getPythonRunnerConfMap` puts it into the conf of every Arrow-based runner, and 
`BasePythonUDFRunner.runnerConf` adds it for every batch UDF and UDTF 
(sql/core/src/main/scala/org/apache/spark/sql/execution/python/PythonUDFRunner.scala:61-62).
 `BasePythonRunner` writes each pair into every task's worker init message 
(core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala:1260), and 
the worker parses it, but `invoke_udf` reads it only when 
`spark.sql.pyspark.udf.profiler` is `sampling` 
(python/pyspark/worker.py:269-287). So with the profiler off, which is the 
default, every task of every SQL Python operator these runners serve now 
carries one more unused pair: 63 bytes with its length prefixes, plus the 
parse. The cost is small and fixed per task, but it falls on the released 
profiler-off path, and the PR does not state it. `samplingInterval` already 
works this way on the base branch, so sending both
  settings only when the sampling profiler is on keeps them consistent.
   
   **Recommended change:** Send spark.sql.pyspark.udf.profiler.samplingInterval 
and spark.sql.pyspark.udf.profiler.samplingAggregation only when 
spark.sql.pyspark.udf.profiler is 'sampling': in 
ArrowPythonRunner.getPythonRunnerConfMap take both out of the list of 
always-sent entries and add them next to the profiler entry when its value is 
'sampling', and in BasePythonUDFRunner.runnerConf add them only in that case. 
Add a JVM test, for example in PythonUDFSuite, that builds the runner conf of 
both runner families with the profiler unset, set to perf, and set to sampling 
with a non-default interval and level, and checks that only the sampling case 
carries both entries, with the session's values; the existing Python 
aggregation test keeps checking every level end to end through both runner 
families.
   
   **Why this works:** The worker reads the interval and the level only when 
the runner conf says the profiler is 'sampling', and only these two builders 
send that value, so sending both settings under the same condition, in the same 
place, removes them from every profiler-off init message while every task that 
runs the sampling profiler still gets the session's values.
   
   **Compatibility:** Every task that runs the sampling profiler receives the 
session's sampling interval and aggregation level through both runner families.
   
   **Risks:** A future path that turns the sampling profiler on without sending 
spark.sql.pyspark.udf.profiler through these builders would fall back to the 
worker's defaults, 100 ms and 'stage', without an error; today the worker turns 
the profiler on only from that entry. samplingInterval also stops being sent on 
profiler-off tasks, which changes the base branch's worker init message; no 
release has that entry, the worker reads it only on the sampling path, and 
reverting the condition restores both entries.
   
   **Constraints:** Test the same value of spark.sql.pyspark.udf.profiler that 
the worker checks, in the same builder that adds that entry, so that a task 
running the sampling profiler always receives both settings. Keep the worker's 
defaults for the interval and the level equal to the SQLConf defaults.
   
   **Exclusions:**
   - Other runner-conf entries that the base branch sends to every task whether 
or not the worker reads them, which this review does not judge.
   
   **Verification:**
   - **Regression:** With the sampling profiler off, the runner conf built for 
an Arrow-based Python UDF and for a batch Python UDF contains neither the 
samplingInterval nor the samplingAggregation entry.
   - **Compatibility:** With the sampling profiler on, both the Arrow and the 
non-Arrow runner send the session's sampling interval and aggregation level, 
and every level still gives the same result counts and key shapes as before the 
change.



##########
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:
   **Nit (P3):** This test calls `_add_sample` directly and checks the kept 
frames, so it pins how the cap works but not what it is for: keeping the 
worker's pickling on Python 3.11 and the recursive `copy.deepcopy` in 
`_sampling_profile_results` within the recursion limit. Reading the code, with 
`_MAX_STACK_DEPTH` raised to 600 this test would still pass, while reading back 
the result of a 700-frame sample would raise `RecursionError`, since 
`copy.deepcopy` handles about 495 levels, as you measured. The worker's 
pickling on Python 3.11, which you measured at about 496 levels, would fail the 
same way. The 600-frame check in the PR description was done by hand. An 
end-to-end case in the shared mixin, which runs in classic PySpark and Spark 
Connect, with a UDF that recurses about 600 frames and waits at the bottom long 
enough to be sampled, would catch both.
   
   **Verification:**
   - **Regression:** A sampled Python UDF that recurses about 600 frames deep 
and waits at the bottom finishes with the sampling profiler on, and reading its 
results back gives a tree whose branch through the UDF stops at the cap with a 
'<truncated>' node, in classic PySpark and Spark Connect; without the cap the 
case fails, when the worker sends the tree on Python 3.11 or when the results 
are copied on read on later versions.



##########
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:
   **Nit (P3):** This test drives only a stack deeper than the cap, as this 
assertion checks, so only that side of the condition at 
python/pyspark/sql/profiler.py:227 is tested. The other sampling tests look for 
a UDF ident, a root, a thread name or a key count, never at a sample's leaf, so 
changing `>` to `>=` there, or appending `<truncated>` to every sample, would 
leave the whole file passing while every ordinary profile gained a 
`<truncated>` leaf. A boundary case next to this one, with one sample exactly 
`_MAX_STACK_DEPTH` frames deep and one a frame deeper, would pin both sides.
   
   **Verification:**
   - **Regression:** A sample whose stack is exactly as deep as the cap is 
recorded frame for frame with no '<truncated>' node, while one a frame deeper 
ends in '<truncated>' after its outermost frames, so a condition that adds the 
marker at the cap or to every sample fails.



##########
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:
   **Nit (P3):** `_thread_names` is kept for the whole task (lines 165-167) and 
filled only from `threading.enumerate()`, and the lookup on line 214 falls back 
to `<unknown thread>` only for an id it has never recorded. So a thread that 
`threading.enumerate()` never lists but that reuses the id of a listed thread 
that has exited, for example a `_thread.start_new_thread()` thread started 
after a joined `helper` thread, is recorded under `helper` for its whole life, 
and at the stage and query levels it merges into the `helper` trees of other 
tasks. This is not one of the short windows at a thread's start or exit that 
you chose to leave as they are: for these threads the name is never corrected. 
The code can stay as it is, but this comment, and the matching bullet in the PR 
description, should say what happens:
   
   ```suggestion
                       # A thread never listed by threading.enumerate(), e.g. 
one started with
                       # _thread.start_new_thread(), gets no name of its own: 
if a listed thread
                       # that has exited used its id earlier in this task, its 
samples go under
                       # that thread's name, and otherwise all such threads 
share one call tree,
                       # since their ids mean nothing across tasks.
   ```
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60150#discussion_r4593453537), 
[2](https://github.com/apache/spark/pull/60150#discussion_r4593453544).
   
   **Verification:**
   - **Inspection:** The comment on threads that threading.enumerate() never 
lists no longer says that every such thread shares the '<unknown thread>' tree, 
and it describes the case in which such a thread reuses the id of an exited 
named thread and takes its name.



-- 
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]

Reply via email to