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


##########
python/pyspark/sql/profiler.py:
##########
@@ -569,6 +576,8 @@ def clear_sampling_profiles(self, id: Optional[Union[int, 
str]] = None) -> None:
 class AccumulatorProfilerCollector(ProfilerCollector):
     def __init__(self) -> None:
         super().__init__()
+        # Share the lock with the accumulator merge, which mutates the same 
dict.
+        self._lock = _profile_results_lock

Review Comment:
   **Nit (P3):** With this lock shared, an accumulator merge that arrives 
during a full `spark.profile.clear()` also waits while the clear frees every 
`pstats.Stats`, memory code map, and sampling result it removes. The clear 
methods drop each popped value inside `with self._lock:`, and the DAGScheduler 
event loop waits in `PythonAccumulatorV2.merge` until the merge is 
acknowledged, so task-completion handling stalls for every job in the 
application. In a repro against this code on Python 3.12 with 1,000 retained 
202-function perf profiles, such a merge waited 82 to 90 ms, versus 6 to 9.5 ms 
with the base branch's locking, where the merge does not wait for the clear 
(428 to 436 ms versus 17 to 22 ms at 5,000 profiles). The stall grows with the 
number of retained profiles.
   
   Collecting the popped values in a local list inside the `with` block and 
freeing them one at a time after it, for example with `while removed: 
removed.pop()`, brought the wait down to about 9.5 ms at 1,000 profiles. Just 
letting that list go after the lock did not help (74 to 87 ms), because CPython 
frees the whole list in one step that holds the GIL, which the accumulator 
server thread also needs before it can merge and acknowledge.
   
   **Verification:**
   - **Behavior:** Clearing everything, clearing by id, and clearing by type 
leave exactly the same remaining perf, memory, and sampling results as before 
the change, including dropping entries that become empty.
   - **Regression:** Time a merge that arrives during a full 
`spark.profile.clear()` of about 1,000 retained 202-function perf results, from 
when its update is sent until the accumulator server writes the 
acknowledgement, for example with a second process that sends updates to an 
accumulator server thread while the main thread clears: the worst wait stays 
close to the base branch's (about 10 ms on the host this review measured, 
versus 82 to 90 ms at the head and 74 to 87 ms when the whole list of popped 
payloads is dropped at once).
   - **Inspection:** In each clear method, every popped payload stays 
referenced by a local list until the `with self._lock:` block has exited, and 
the list is then emptied one item per loop step rather than dropped as a whole.



##########
python/pyspark/sql/tests/test_udf_profiler.py:
##########
@@ -829,6 +831,32 @@ def setUp(self) -> None:
         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():
+            merging.wait()

Review Comment:
   **Nit (P3):** `merging` is set only inside the patched 
`SamplingResultParam.addInPlace`, and nothing bounds this wait: the helper is a 
non-daemon thread, and `thread.join()` has no timeout either. If a later change 
keeps the second merge from reaching that step, both threads block until the 
module hits `PYSPARK_TEST_TIMEOUT` (450 s in CI) instead of the test failing. 
If the merge raises before that step, the error is reported, but the blocked 
helper keeps the test process from exiting.
   
   A daemon helper with a timeout on this wait, as already suggested for this 
helper, removes the hang but is not enough on its own: the helper would then 
time out and clear, and the final `assertEqual({}, ...)` would pass without the 
interleaving ever happening. Also skip the clear when the wait times out, so a 
helper left over from a failed run cannot clear the shared session's results 
during a later test, and after the second merge assert in the main thread that 
`merging` is set and that a bounded `thread.join(...)` finished.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60259#discussion_r4519126861).
   
   **Verification:**
   - **Regression:** When the second merge does not reach the patched sampling 
step, for example because the update uses a key with no existing entry, the 
test fails within its timeout with an assertion that the pause was not reached, 
and no helper thread is left running.
   - **Regression:** When the second merge raises before the patched sampling 
step, the test reports that error, and once its wait times out the helper exits 
without calling `spark.profile.clear()`.
   - **Regression:** Reverting either the lock in the V2 merge or the 
collector's use of that lock still makes the test fail with the merge's 
KeyError.
   - **Behavior:** With the fix in place the test passes and its helper thread 
has finished by the time the test ends.



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