dongjoon-hyun commented on code in PR #60150:
URL: https://github.com/apache/spark/pull/60150#discussion_r4593453506


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

Review Comment:
   **[7] Following up on item 1 
([thread](https://github.com/apache/spark/pull/60150#discussion_r4519184097)): 
the worker still pickles the call tree recursively, so a deep tree fails the 
task before the driver merges it.** Thank you for the iterative merge. Each 
task's tree is sent by `send_accumulator_updates` (`worker_util.py` L316, 
outside this diff) with `pickle.dumps`, which recurses about twice per dict 
level. I measured the deepest nested dict that pickles: 498 levels on Python 
3.11.7 (recursion limit 1000) and 748 on 3.12.1, whatever the limit, against 
22728 on 3.14. So with `spark.sql.pyspark.udf.profiler=sampling` on Python 
3.11, the minimum supported version, a UDF whose call stack is about 500 frames 
deep runs fine without the profiler but raises `RecursionError` in that pickle 
with it. The worker has already written the accumulator count, so the task 
fails with "Python worker exited unexpectedly", and so does every retry. A tree 
deeper than the driver's recursion limit,
  as in `test_sampling_result_param_merge_deep_tree` (test L1018), cannot come 
from a 3.11 or 3.12 worker at all.
   
   This predates the PR (SPARK-60604, unreleased), but it limits what the 
iterative merge fixes. Could the worker send the tree in a form that pickles 
without deep recursion (see item 14), or at least cut it at a safe depth in 
`save()`, so that the task does not fail? If that is left for a follow-up, 
could the PR description say on which Python versions the deep-tree fix helps?



##########
python/pyspark/sql/profiler.py:
##########
@@ -186,19 +192,25 @@ 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)
+                    self._add_sample(self._thread_names.get(tid, str(tid)), 
frame)

Review Comment:
   **[9] Minor: the `str(tid)` fallback is now merged across tasks and worker 
processes.** A thread that never shows up in `threading.enumerate()`, for 
example one started with `_thread.start_new_thread`, or a C-created thread that 
runs Python callbacks without calling `threading.current_thread()`, keeps the 
`str(tid)` root. At the `stage` and `query` levels those roots are now merged 
across tasks, and workers forked from `daemon.py` share their address-space 
layout, so their thread ids often repeat across worker processes. Two unrelated 
threads in different workers can then be summed into one call tree, which is 
what the PR description says keying by thread id must not do. Could the 
fallback be one explicit name such as `<unknown thread>`, or keep the id but 
add the process id, so that a merged root is not mistaken for one thread?



##########
python/pyspark/sql/profiler.py:
##########
@@ -211,8 +223,31 @@ 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()}"
+        elif self._aggregation == "task":
+            # Stage ids are unique in the application, so this identifies a 
task. All
+            # attempts of the task, e.g. retries, are merged together.
+            return f"sampling_task_{tc.stageId()}_{tc.partitionId()}"
+        else:
+            raise PySparkValueError(

Review Comment:
   **[13] Nit: no test covers this `VALUE_NOT_ALLOWED` branch, which the PR 
description lists as behavior.** If it regressed, e.g. an unknown value fell 
into one of the levels again as in the previous revision, every test would 
still pass. Could a small test construct `WorkerSamplingProfiler` with a mock 
task context and `aggregation="job"`, and check the error with `check_error` 
(at construction if item 12 is taken, otherwise from `_get_task_key()`)?



##########
python/pyspark/sql/profiler.py:
##########
@@ -152,10 +152,16 @@ 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:
   **[11] Minor: keyed by name, threads with the same name that run at the same 
time are summed into one call tree, even at the `task` level.** If a UDF starts 
four `threading.Thread(name="worker")` threads that run together, each sample 
adds up to four counts to the one `worker` tree, where keying by thread id kept 
the four apart. A node's count is then no longer one thread's sampled time, and 
`samplingAggregation=task` cannot show per-thread behavior inside a task 
either. This comes from the key, not from the level, and I understand that how 
threads are grouped is out of scope here. Could the conf doc or the PR 
description say that threads with the same name are merged into one call tree, 
also within a task?



##########
python/pyspark/sql/tests/test_udf_profiler.py:
##########
@@ -826,6 +827,64 @@ 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):
+                    # Clear first, so that a failed subtest does not affect 
the next ones.
+                    self.spark.profile.clear()
+                    df.collect()
+
+                    keys = list(self.sampling_profile_results)
+                    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

Review Comment:
   **[16] Nit: `threading` is already imported at the top of the file (L23).** 
Could this local import go?



##########
python/pyspark/sql/profiler.py:
##########
@@ -211,8 +223,31 @@ 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()}"

Review Comment:
   **[8] Minor: with shared keys, later merges change the stored call trees in 
place, but `_sampling_profile_results` still returns them as they are.** After 
the first task of a stage or query, every update with that key runs 
`SamplingResultParam.addInPlace` into the stored tree (L135-139), on the 
accumulator server thread in classic PySpark and in 
`ConnectProfilerCollector._update` in Spark Connect. 
`_sampling_profile_results` (L458-464, outside this diff) hands out those live 
dicts, so a reader that walks one outside the lock while a concurrent job or a 
running streaming query merges into the same key can get `RuntimeError: 
dictionary changed size during iteration` or a half-merged tree. With 
per-attempt keys, a stored tree was never changed after it arrived.
   
   Nothing reads these trees outside the tests yet, but #60259 made 
`_perf_profile_results` return copies for this reason and left the sampling 
snapshot to "the sampling show/render work in #60150", and it is this PR that 
makes the trees change in place. Could `_sampling_profile_results` return 
copies made under the lock, with an iterative copy since `copy.deepcopy` 
recurses, or could the PR description note it for the show/render follow-up?



##########
python/pyspark/worker_util.py:
##########
@@ -448,6 +448,10 @@ def udf_profiler(self) -> Optional[str]:
     def udf_profiler_sampling_interval(self) -> int:
         return int(self.get("spark.sql.pyspark.udf.profiler.samplingInterval", 
100))
 
+    @property
+    def udf_profiler_sampling_aggregation(self) -> str:
+        return self.get("spark.sql.pyspark.udf.profiler.samplingAggregation", 
"stage")

Review Comment:
   **[15] Nit: the default `stage` and the list of levels are now spelled in 
four places.** They are in `SQLConf` (`createWithDefault` and `checkValues`), 
in this default, in the `WorkerSamplingProfiler.__init__` default 
(`sql/profiler.py` L155), and in the `allowed_values` list (`sql/profiler.py` 
L248). Both runners in this diff always send the key, so the two Python 
defaults are not used in practice, and changing the `SQLConf` default or adding 
a level means updating the Python side by hand. `samplingInterval` has the same 
shape, so keeping it for consistency is fine too. Could the Python side keep 
one constant for the default and the levels, for example next to 
`WorkerSamplingProfiler`?



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

Review Comment:
   **[14] Minor: the nested-dict call tree is what makes merge, pickle and copy 
recursive.** The iterative merge fixes one of them, but the worker's 
`pickle.dumps` (item 7) and any later copy (item 8), `==` or recursive renderer 
still hit the depth limit one by one. A flat form per thread, a counter keyed 
by the stack tuple, e.g. `{thread_name: {(ident_0, ..., ident_k): count}}`, 
pickles with shallow recursion, merges by adding the counts per key and is 
cheap to copy, and the tree view can be rebuilt when it is shown. It repeats 
shared stack prefixes, so it can be larger for wide trees. Since the sampling 
profiler is not released yet, could the format be changed now, or in a 
follow-up before the release?



##########
python/pyspark/sql/profiler.py:
##########
@@ -186,19 +192,25 @@ 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.

Review Comment:
   **[10] Nit: following up on item 2 
([thread](https://github.com/apache/spark/pull/60150#discussion_r4519184103)), 
a reused thread id keeps the old name until the new thread is enumerated.** 
Thank you for keeping the map. Sequential threads usually reuse thread ids, and 
a new thread is in `_limbo` with `ident` None until `_set_ident()` runs, so the 
`t.ident is not None` filter skips it while `sys._current_frames()` already has 
its frame. Its first samples then go under the earlier owner's name, e.g. 
`ThreadPoolExecutor-0_0`, not under `str(tid)` as your reply says. The other 
way round, a thread that exits between `sys._current_frames()` and 
`threading.enumerate()` and whose id is reused right away has its last frames 
recorded under the new thread's name. Both windows are short, so the counts 
move little, but the comment here says more than the code does. Could the 
comment say that the name is updated once the new thread is enumerated, or 
could the map drop the ids that are no longe
 r in `frames`?



##########
python/pyspark/sql/profiler.py:
##########
@@ -211,8 +223,31 @@ 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()}"
+        elif self._aggregation == "task":
+            # Stage ids are unique in the application, so this identifies a 
task. All
+            # attempts of the task, e.g. retries, are merged together.
+            return f"sampling_task_{tc.stageId()}_{tc.partitionId()}"
+        else:

Review Comment:
   **[12] Nit: following up on item 6 
([thread](https://github.com/apache/spark/pull/60150#discussion_r4519184117)), 
the level is checked only after the task has done its work.** Thank you for the 
explicit branch. `_get_task_key()` runs in `save()`, after `run_process()` has 
processed the whole partition and written all its output, so a level this 
worker does not know fails the task only at the end, and every retry does the 
same work again. `SQLConf` rejects such values today, so this is about a future 
level or a direct caller. Could `__init__` check the value, so that it fails 
before the UDF runs?



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