gaogaotiantian commented on code in PR #60150:
URL: https://github.com/apache/spark/pull/60150#discussion_r4607251584


##########
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:
   Thank you, you are right. I reproduced it on Python 3.11.14: with the 
sampling profiler on, a UDF that recurses 600 frames deep crashed the worker in 
`send_accumulator_updates` ("Python worker exited unexpectedly"), on master as 
well, while 400 frames worked. The worker's cloudpickle handles about 496 
levels of nested dicts there.
   
   Fixed in 8fb4b629ec3 where the samples are taken: `_add_sample` keeps at 
most the outermost 256 frames of each sample 
(`WorkerSamplingProfiler._MAX_STACK_DEPTH`) and counts the samples that go 
deeper under a `<truncated>` child of the 256th frame. Keeping the outermost 
frames keeps the roots of all samples the same, so trees from different tasks 
still merge. With it, the 600- and 980-frame UDFs succeed on 3.11, with a call 
tree of 257 levels. A UDF body starts about 16 frames deep in the worker, and 
the library calls I measured (pandas, pyarrow, numpy, `ast`, `email`) add 4 to 
54 frames, so the cap only affects deep recursion. 
`test_sampling_profiler_truncate_deep_stack` checks the kept frames and the 
marker.
   
   I kept the iterative merge and its test, so the merge does not depend on the 
recursion limit either.
   



##########
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:
   Agreed, thanks. Fixed in 8fb4b629ec3: `_sampling_profile_results` now 
returns copies made with `copy.deepcopy` under the lock, the same way #60259 
made `_perf_profile_results` return copies. `copy.deepcopy` recurses, but with 
the cap from item 7 a call tree is at most 257 levels deep, and `copy.deepcopy` 
handles about 495 levels on Python 3.11, 3.12 and 3.14. 
`test_sampling_profile_results_are_copies` reads the results, merges another 
update into the same key, and checks that what it read did not change; it fails 
without the copy.
   



##########
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:
   Good point, thanks. I checked when the fallback is used: only for threads 
that `threading.enumerate()` never lists, such as ones started with 
`_thread.start_new_thread()`, or native threads that run Python without calling 
`threading.current_thread()` (one that calls it is listed as `Dummy-N`). For 
threads started through `threading`, none of about 8,500 samples of 3,000 
short-lived threads fell back. And as you said, such ids repeat across forked 
processes: the first such thread got the same id in each of three forked 
children on macOS.
   
   Fixed in 8fb4b629ec3: these samples now all go under one `<unknown thread>` 
call tree instead of `str(tid)`. They are still recorded, but they are not 
taken for one thread and do not add a root per id. 
`test_sampling_profiler_unknown_thread` checks it.
   



##########
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:
   You are right, and my earlier reply was wrong on this point. A thread 
sampled before `_set_ident()` gets no name only if its id has not been seen 
before (with item 9, it now goes under `<unknown thread>`). If the id was 
reused, its first samples go under the previous owner's name until 
`threading.enumerate()` lists the new thread, and the reverse case you describe 
can happen too. Both windows are a few bytecodes at a thread's start or exit, 
so I would like to leave the code and this comment as they are in this PR and 
come back to it later. I corrected the PR description so that it no longer says 
more than the code does.
   



##########
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:
   Thanks. Added to the conf doc in 8fb4b629ec3: "At every level, threads with 
the same name are merged into one call tree, even threads of one task that run 
at the same time." The PR description says the same.
   



##########
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:
   Thanks, done in 8fb4b629ec3. `__init__` now gets the result key with 
`_get_task_key()`, so an unknown level fails when the profiler is created, 
before `run_process()` runs the UDF. `_get_task_key()` keeps the explicit 
`"task"` branch and raises for anything else, so a level added later without 
its own key also fails.
   



##########
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:
   Added `test_sampling_profiler_aggregation_not_allowed` in 8fb4b629ec3. It 
creates a `WorkerSamplingProfiler` with a mock task context and 
`aggregation="job"`, and checks the `VALUE_NOT_ALLOWED` error with 
`check_error`.
   



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