This is an automated email from the ASF dual-hosted git repository.

gaogaotiantian pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.x by this push:
     new d9cb1e0f6a8b [SPARK-61293][PYTHON] Fix a race between profile result 
merges and spark.profile.clear() in classic PySpark
d9cb1e0f6a8b is described below

commit d9cb1e0f6a8b9f48509b2f2b62cdb5ab5aa159fd
Author: Tian Gao <[email protected]>
AuthorDate: Tue Nov 10 16:09:19 2026 -0800

    [SPARK-61293][PYTHON] Fix a race between profile result merges and 
spark.profile.clear() in classic PySpark
    
    ### What changes were proposed in this pull request?
    
    In classic PySpark, the driver's accumulator server thread merges worker 
profile results into the `SQL_UDF_PROFIER_V2` accumulator through 
`_ProfileResultsParamV2.addInPlace`, with no lock. 
`AccumulatorProfilerCollector` returns that same live dict, and 
`spark.profile.clear()` (`clear_perf_profiles` / `clear_memory_profiles` / 
`clear_sampling_profiles`) pops entries from it while holding only the 
collector's own lock, which the merge never takes.
    
    This PR:
    
    - Adds a public class attribute `_ProfileResultsParamV2.lock` (an `RLock`). 
`addInPlace` becomes a classmethod and holds `cls.lock` for the whole merge.
    - Makes `AccumulatorProfilerCollector` use `ProfileResultsParamV2.lock` as 
its `_lock`. Its clear methods, and the result snapshots that show, dump and 
render start from, now take the same lock as the merge.
    - Makes `_perf_profile_results` return copies of the `pstats.Stats` 
objects, made under the lock (`pstats.Stats().add(stats)`). Show, dump and 
render then sort, print and dump the copies outside the lock, while later 
merges keep updating the originals in place through `Stats.add`. Without the 
copy, a merge during `show` can raise `RuntimeError: dictionary changed size 
during iteration` in `sort_stats`.
    
    The lock is a class attribute, not an instance attribute, so it is not 
pickled with the `AccumulatorParam` that `Accumulator.__reduce__` sends along. 
It is held only for in-memory work (the dict merge, clear and snapshot), with 
no JVM calls or job waits under it. A code comment on the lock records this, 
because the DAGScheduler blocks in `PythonAccumulatorV2.merge` until the 
accumulator server thread acknowledges. Merge results and `spark.profile.clear` 
behavior do not change.
    
    The memory and sampling snapshots still return the live objects:
    
    - A memory merge only replaces each file's list in the code map and never 
adds or removes keys, so iterating over it while formatting cannot raise.
    - On master nothing formats sampling results yet. That is left to the 
sampling show/render work in #60150.
    
    Spark Connect was not affected by the merge/clear race, because 
`ConnectProfilerCollector._update` already merges under the collector's lock. 
It keeps its own per-collector lock. The nested acquisition (collector lock, 
then `ProfileResultsParamV2.lock` inside `addInPlace`) always happens in the 
same order, so it can't deadlock. Connect reads perf results through the same 
base-class property, so it gets the copies too.
    
    The legacy `_ProfileResultsParam` (V1) is not changed. It builds a new dict 
instead of mutating `value1`, it is only used on workers, and the driver never 
registers the V1 accumulator id, so the accumulator server drops V1 updates and 
nothing clears them.
    
    ### Why are the changes needed?
    
    If a clear lands between the merge's `key in value1` check and its 
write-back, the merge raises `KeyError` in the accumulator server thread. In 
the other ordering, a cleared entry can be re-attached. Perf and memory results 
already share a key across tasks (the UDF `result_id`), so this can happen on 
master today. It was found during review of #60150, which lets the sampling 
profiler share keys too: 
https://github.com/apache/spark/pull/60150#discussion_r4488925635
    
    Separately, `spark.profile.show(type="perf")`, `dump` and `render` format 
the live `pstats.Stats` objects, which a concurrent merge mutates in place. In 
a two-thread repro, `show` raised `RuntimeError: dictionary changed size during 
iteration` every time.
    
    ### Does this PR introduce _any_ user-facing change?
    
    No, other than fixing the races. A `spark.profile.clear()` or 
`show`/`dump`/`render` that runs while profiles are being merged no longer 
makes either side fail.
    
    ### How was this patch tested?
    
    Added two tests to `UDFProfiler2Tests`. Neither runs a Spark job, and both 
stage the interleaving deterministically:
    
    - `test_clear_during_accumulator_merge` does the server's `accumulator += 
update` with a shared key, pauses that merge midway with a patched 
`SamplingResultParam.addInPlace`, and calls `spark.profile.clear()` from a 
helper thread at that point. It then checks that no exception escapes and that 
no results are left. The helper is a daemon with bounded waits, and the test 
asserts that the pause was actually reached. It fails with `KeyError: 'id'` 
when either the merge's lock or the colle [...]
    - `test_show_perf_during_accumulator_merge` patches 
`pstats.func_std_string`, which `sort_stats` calls for each function, so that a 
merge happens midway through `spark.profile.show(type="perf")`. It checks that 
the output is there and that the merged function is kept. Without the copy, it 
fails with `RuntimeError: dictionary changed size during iteration`.
    
    Both tests failed in every run without their fix and passed in every run 
with it. Also ran `pyspark.sql.tests.test_udf_profiler` (all classes) and 
`pyspark.sql.tests.connect.test_parity_udf_profiler`, and both pass.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Isaac
    
    This pull request and its description were written by Isaac.
    
    Closes #60259 from gaogaotiantian/SPARK-profiler-lock.
    
    Authored-by: Tian Gao <[email protected]>
    Signed-off-by: Tian Gao <[email protected]>
    
    (cherry picked from commit 586cc2a601d2679e168ef23ce02110aee6139528)
    Signed-off-by: Tian Gao <[email protected]>
    
    
    skip-checks: true
---
 python/pyspark/sql/profiler.py                | 59 ++++++++++++++++----------
 python/pyspark/sql/tests/test_udf_profiler.py | 61 ++++++++++++++++++++++++++-
 2 files changed, 96 insertions(+), 24 deletions(-)

diff --git a/python/pyspark/sql/profiler.py b/python/pyspark/sql/profiler.py
index 353f463211ce..77e418387cb3 100644
--- a/python/pyspark/sql/profiler.py
+++ b/python/pyspark/sql/profiler.py
@@ -103,32 +103,41 @@ class 
_ProfileResultsParamV2(AccumulatorParam["ProfileResultsV2"]):
     AccumulatorParam for profilers.
     """
 
+    # Guards a results dict that the driver's accumulator server thread merges 
into while other
+    # threads read or clear it. The DAGScheduler blocks until that thread 
acknowledges, so keep
+    # holds short, and never call into the JVM or wait on a Spark job while 
holding it.
+    # A class attribute, so it is not pickled with the param.
+    lock = RLock()
+
     @staticmethod
     def zero(value: "ProfileResultsV2") -> "ProfileResultsV2":
         return {}
 
-    @staticmethod
-    def addInPlace(value1: "ProfileResultsV2", value2: "ProfileResultsV2") -> 
"ProfileResultsV2":
-        for key, result in value2.items():
-            if key not in value1:
-                value1[key] = result
-            else:
-                perf = PStatsParam.addInPlace(
-                    value1[key].get("perf", None), result.get("perf", None)
-                )
-                if perf is not None:
-                    value1[key]["perf"] = perf
-                memory = MemUsageParam.addInPlace(
-                    value1[key].get("memory", None), result.get("memory", None)
-                )
-                if memory is not None:
-                    value1[key]["memory"] = memory
-                sampling = SamplingResultParam.addInPlace(
-                    value1[key].get("sampling", {}), result.get("sampling", {})
-                )
-                if sampling:
-                    value1[key]["sampling"] = sampling
-        return value1
+    @classmethod
+    def addInPlace(
+        cls, value1: "ProfileResultsV2", value2: "ProfileResultsV2"
+    ) -> "ProfileResultsV2":
+        with cls.lock:
+            for key, result in value2.items():
+                if key not in value1:
+                    value1[key] = result
+                else:
+                    perf = PStatsParam.addInPlace(
+                        value1[key].get("perf", None), result.get("perf", None)
+                    )
+                    if perf is not None:
+                        value1[key]["perf"] = perf
+                    memory = MemUsageParam.addInPlace(
+                        value1[key].get("memory", None), result.get("memory", 
None)
+                    )
+                    if memory is not None:
+                        value1[key]["memory"] = memory
+                    sampling = SamplingResultParam.addInPlace(
+                        value1[key].get("sampling", {}), 
result.get("sampling", {})
+                    )
+                    if sampling:
+                        value1[key]["sampling"] = sampling
+            return value1
 
 
 ProfileResultsParamV2 = _ProfileResultsParamV2()
@@ -355,9 +364,11 @@ class ProfilerCollector(ABC):
 
     @property
     def _perf_profile_results(self) -> Dict[Union[int, str], pstats.Stats]:
+        # Return copies, since merges mutate the stats in place while callers 
sort, print and
+        # dump them outside the lock.
         with self._lock:
             return {
-                result_id: result["perf"]
+                result_id: pstats.Stats().add(result["perf"])
                 for result_id, result in self._profile_results.items()
                 if result.get("perf", None) is not None
             }
@@ -576,6 +587,8 @@ class AccumulatorProfilerCollector(ProfilerCollector):
             self._accumulator = Accumulator(
                 SpecialAccumulatorIds.SQL_UDF_PROFIER_V2, {}, 
ProfileResultsParamV2
             )
+        # Share the lock with the accumulator merge, which mutates the same 
dict.
+        self._lock = ProfileResultsParamV2.lock
 
     @property
     def _profile_results(self) -> "ProfileResultsV2":
diff --git a/python/pyspark/sql/tests/test_udf_profiler.py 
b/python/pyspark/sql/tests/test_udf_profiler.py
index 4f9c9a362452..57d947714120 100644
--- a/python/pyspark/sql/tests/test_udf_profiler.py
+++ b/python/pyspark/sql/tests/test_udf_profiler.py
@@ -17,17 +17,20 @@
 
 import inspect
 import os
+import pstats
 import sys
 import tempfile
+import threading
 import unittest
 import warnings
 from contextlib import contextmanager
 from io import StringIO
 from typing import Iterator
+from unittest import mock
 
 from pyspark import SparkConf
 from pyspark.errors import PySparkValueError
-from pyspark.profiler import UDFBasicProfiler
+from pyspark.profiler import SamplingResultParam, UDFBasicProfiler
 from pyspark.sql import SparkSession
 from pyspark.sql.functions import arrow_udf, col, pandas_udf, udf
 from pyspark.sql.window import Window
@@ -829,6 +832,62 @@ class UDFProfiler2Tests(UDFProfiler2TestsMixin, 
ReusedSQLTestCase):
         super().setUp()
         self.spark._profiler_collector._accumulator._value = {}
 
+    def test_clear_during_accumulator_merge(self):
+        # The accumulator server thread merges worker updates into the same 
dict that
+        # spark.profile.clear() pops from. Pause a merge midway and clear from 
another thread.
+        accumulator = self.spark._profiler_collector._accumulator
+        merging, cleared = threading.Event(), threading.Event()
+        add_in_place = SamplingResultParam.addInPlace
+
+        def paused_add_in_place(value1, value2):
+            merging.set()
+            # Without a shared lock, the clear runs while the merge is waiting 
here.
+            cleared.wait(timeout=0.1)
+            return add_in_place(value1, value2)
+
+        def clear():
+            # Skip the clear if the merge never pauses, so it can't affect 
later tests.
+            if merging.wait(timeout=10):
+                self.spark.profile.clear()
+                cleared.set()
+
+        accumulator += {"id": {"sampling": {"count": 1}}}
+        with mock.patch.object(SamplingResultParam, "addInPlace", 
paused_add_in_place):
+            thread = threading.Thread(target=clear, daemon=True)
+            thread.start()
+            accumulator += {"id": {"sampling": {"count": 1}}}
+            thread.join(timeout=10)
+        self.assertTrue(merging.is_set(), "The merge did not reach the pause")
+        self.assertFalse(thread.is_alive())
+        self.assertEqual({}, self.spark._profiler_collector._profile_results)
+
+    def test_show_perf_during_accumulator_merge(self):
+        # Merges mutate the stats in place. Merge a new function midway 
through show().
+        accumulator = self.spark._profiler_collector._accumulator
+
+        def stats(name):
+            st = pstats.Stats()
+            st.stream = None
+            st.stats = {("udf.py", 1, name): (1, 1, 0.1, 0.1, {})}
+            return st
+
+        accumulator += {"id": {"perf": stats("f")}}
+        func_std_string = pstats.func_std_string
+        merged = False
+
+        def func_std_string_with_merge(func):
+            nonlocal merged
+            if not merged:
+                merged = True
+                accumulator.add({"id": {"perf": stats("g")}})
+            return func_std_string(func)
+
+        with mock.patch("pstats.func_std_string", func_std_string_with_merge):
+            with self.trap_stdout() as io:
+                self.spark.profile.show(type="perf")
+        self.assertIn("Profile of id", io.getvalue())
+        self.assertEqual(2, len(self.profile_results["id"].stats))
+
 
 if __name__ == "__main__":
     from pyspark.testing import main


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to