spark-test commented on code in PR #60150:
URL: https://github.com/apache/spark/pull/60150#discussion_r4488925631
##########
python/pyspark/sql/profiler.py:
##########
@@ -177,19 +180,20 @@ 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):
+ thread_names = {t.ident: t.name for t in threading.enumerate()}
for tid, frame in sys._current_frames().items():
if tid != self_tid:
- self._add_sample(tid, frame)
+ self._add_sample(thread_names.get(tid, str(tid)), frame)
Review Comment:
**Non-blocking (P2):** Keying by the raw `Thread.name` fragments threads
whose names CPython generates. Those names embed process-wide counters
(`Thread-<N> (<target>)`, `ThreadPoolExecutor-<K>_<i>`, `Dummy-<N>`), and when
`spark.sql.execution.pythonUDF.arrow.concurrency.level` is set, the Arrow,
pandas and elementwise eval handlers build a new unnamed `ThreadPoolExecutor`
for every batch of every UDF; UDFs that start threads or pools per call behave
the same way. Each thread lifetime now becomes its own root, where keying by
`threading.get_ident()` folded sequential threads through ident reuse. Driving
this `WorkerSamplingProfiler` for one task with a new 4-thread pool per batch
gave 41 roots (26 KB pickled) after 10 batches and 201 roots (125 KB) after 50,
against 5 roots (about 4 KB) with ident keys. The growth also hits the task
level and single-task stages, where results never merge, and at the stage and
query levels these names line up across tasks only by accident of worker
history, so retained driver state can end up larger than one result per task.
In Spark Connect, the larger per-task payloads also enlarge the single
observed-metrics response that the client receives.
**Recommended change:** Before keying a sampled thread's call tree, remove
the process-wide counters from the names CPython generates, so that
ThreadPoolExecutor-<K>_<i> becomes ThreadPoolExecutor_<i>, Thread-<N>
(<target>) becomes Thread (<target>), and Thread-<N> and Dummy-<N> lose their
numbers, while explicitly chosen names such as MainThread, helper or a custom
thread_name_prefix stay as they are. Add Python UDF profiler tests in which a
UDF starts a new unnamed thread or thread pool on every call, as Spark's Arrow
eval handlers do when spark.sql.execution.pythonUDF.arrow.concurrency.level is
set.
**Why this works:** Pool workers with the same slot, and unnamed threads
with the same target, now share one call tree within a task and across tasks
and worker processes, so each result's roots are bounded by the number of
distinct thread roles instead of the number of thread lifetimes sampled.
Explicit names keep the cross-task merging that keying by thread name
introduced.
**Scope:** Fold CPython-generated thread names in the Python sampling
profiler's call-tree keys, plus tests for per-call unnamed threads and pools.
**Compatibility:** Result keys, sample counts, aggregation levels and the
merging of explicitly named threads across tasks stay as they are.
**Risks:** Unnamed threads with the same target, or pool workers with the
same slot, that run at the same time now share one call tree where the base
branch kept one per live thread; their samples are summed, so per-thread detail
among them is lost. The rule lives only in the sampler's key derivation, so
reverting it restores per-name trees. A thread that a user explicitly names
like a generated name, such as Thread-3, is grouped with the generated ones.
**Constraints:** Explicitly chosen thread names, including MainThread and
custom thread_name_prefix values, must keep keying their call trees unchanged.
Sample counts must be preserved: trees that come to share a key are summed,
never dropped.
**Exclusions:**
- Thread names that other libraries generate with their own counters are
left as they are.
**Success:** When a UDF starts a new unnamed thread pool on every call or
batch, each task's result has at most one root per pool slot plus its other
threads, however many calls or batches the task runs. At the stage and query
levels, tasks of the same stage or query merge such threads into the same
roots. Explicitly named threads, including MainThread and helper, still key and
merge as they do now.
**Verification:**
- **Regression:** UDFs that start a new unnamed threading.Thread, or map
work over a new unnamed ThreadPoolExecutor, on every call yield call trees
whose number of roots does not grow with the number of calls, both at the task
level and for a single-task query at the default stage level.
- **Behavior:** At the stage level, two tasks whose UDFs use per-call
unnamed pools merge those pool threads into shared roots, while MainThread and
an explicitly named helper thread keep their own roots.
##########
python/pyspark/sql/profiler.py:
##########
@@ -202,8 +206,20 @@ 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":
+ # The root id groups all micro-batches of a streaming query
together. It is not
+ # set when the UDF does not run in a SQL query, e.g. under
`df.rdd`.
+ root_id = tc.getLocalProperty("spark.sql.execution.root.id")
Review Comment:
**Non-blocking (P2):** This key does not group a streaming query's
micro-batches, despite the comment above it. `spark.sql.execution.root.id` is
set by `SQLExecution.withNewExecutionId0` only when no root is set, and cleared
when that root execution ends; `MicroBatchExecution` runs every batch's
`addBatch` in its own `SQLExecution.withNewExecutionId`, on a stream thread
that carries no root id. So with `samplingAggregation=query` each micro-batch
gets a fresh `sampling_query_<executionId>` result, these pile up on the driver
(or the Connect client) for the life of the stream, and streaming is left with
no level that aggregates across batches, since stage keys are per batch too.
The same lifecycle splits a `df.rdd` action over a plan with exchanges: AQE map
stages run inside `javaToPython`'s execution and get its root id, and only the
final stage lands in `sampling_query_unknown`. Suggest preferring the
`sql.streaming.queryId` local property (set by `StreamExecution.runStream` and
shipped to the worker with all local properties), then the root id, then
`unknown`, and updating this comment and the conf doc to describe streaming
queries and the unknown bucket as implemented.
**Verification:**
- **Behavior:** A micro-batch streaming query that evaluates a Python UDF
over several batches, profiled at the query level, yields exactly one
sampling_query_ result, keyed by that streaming query's id.
- **Regression:** Two separate batch queries profiled at the query level
still yield two distinct results keyed by their root execution ids, and a UDF
evaluated only by a df.rdd action still yields sampling_query_unknown.
##########
python/pyspark/sql/tests/test_udf_profiler.py:
##########
@@ -823,12 +824,83 @@ 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):
+ import time
+
+ @udf("long")
+ def busy_add1(x):
+ time.sleep(0.05)
+ return x + 1
+
+ df = self.spark.range(10, numPartitions=2).select(busy_add1("id"))
+
+ # Two tasks in one stage of one query.
+ for level, num_results in [("task", 2), ("stage", 1), ("query", 1)]:
Review Comment:
**Nit (P3):** On this fixture (two tasks in one stage of one query), the
stage and query levels necessarily produce one result each, and the assertions
check only counts, the `sampling_<level>_` prefix and a `MainThread` tree.
Keying `query` by the stage id, losing the root id (every key becomes
`sampling_query_unknown`, which still matches), a merge that keeps one task's
tree instead of summing counts, or a different default level would all pass;
every sampling test sets `samplingAggregation` explicitly, so the `stage`
default is never observed. Suggest adding a query with Python UDFs on both
sides of a shuffle (one result per UDF stage, but a single query result keyed
by a root execution id), a direct check that merging same-key results sums
their call-tree counts, and a run with the level unset.
See **Shared repair plan 1** in the review body.
##########
python/pyspark/sql/profiler.py:
##########
@@ -202,8 +206,20 @@ 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":
+ # The root id groups all micro-batches of a streaming query
together. It is not
+ # set when the UDF does not run in a SQL query, e.g. under
`df.rdd`.
+ root_id = tc.getLocalProperty("spark.sql.execution.root.id")
+ return f"sampling_query_{root_id if root_id is not None else
'unknown'}"
+ elif self._aggregation == "stage":
+ return f"sampling_stage_{tc.stageId()}"
Review Comment:
**Blocking (P1):** With this shared key, every task after the first in a
stage now takes the existing-key branch of `_ProfileResultsParamV2.addInPlace`,
which the accumulator server thread runs with no lock, while
`spark.profile.clear()` pops entries from the same live dict on the user's
thread under `ProfilerCollector._lock` only. If a clear lands between the `key
in value1` check and the final `value1[key]['sampling'] = ...`, the merge
raises `KeyError` inside `accum_updates`; in the other interleaving, the
cleared tree is re-attached. A two-thread run of this code raised `KeyError` in
169 of 3380 merges with a shared `sampling_stage_0` key, and in none with
per-attempt keys. The exception aborts the handler before the acknowledgement,
so the task's remaining updates are dropped. Because
`PythonAccumulatorV2.openSocket` reconnects only when its channel is closed
locally, every later merge then reuses the dead connection and fails: from that
point all Python accumulator updates f
or the SparkContext, user accumulators included, are lost, and the only
signals are a traceback on the driver's stderr and JVM error logs. This applies
to classic PySpark, for example when a background streaming query or a job on
another thread completes tasks while the user clears profiles; Spark Connect
merges under the collector lock. Perf and memory entries keyed by UDF id
already take this branch on the base branch, so a fix at the results map covers
them too.
**Recommended change:** Guard the profile-results map with one shared
re-entrant lock. _ProfileResultsParamV2.addInPlace holds it for the whole
merge, and the profiler collectors use the same lock for their clear methods
and result reads, so an accumulator merge and a spark.profile.clear() can no
longer interleave. Add a concurrency test to the Python UDF profiler tests.
**Why this works:** With merge and clear mutually exclusive, the
existing-entry branch always sees the entry it just checked, so it cannot
raise. A clear either removes a fully merged entry or runs before a later merge
inserts a fresh one, so a clear can no longer be undone. Because the
accumulator server no longer raises from this merge, the connection the JVM
reuses stays alive and no update batch is dropped.
**Scope:** Shared locking for the Python profile-results map, plus a
concurrency test.
**Compatibility:** Result keys, merge semantics and outputs for the perf,
memory and sampling profilers stay as they are; only concurrent interleavings
of merges and clears are serialized.
**Risks:** While a user thread holds the lock, accumulator merges wait, and
so does the scheduler thread waiting for their acknowledgement, so lock holds
must stay short (no long iteration or formatting under the lock). Holding the
lock while waiting on a Spark job would deadlock against that acknowledgement
wait.
**Constraints:** Profiler collector methods must not call into the JVM or
run Spark jobs while holding the lock. Merge results for sequential updates
must stay unchanged for perf, memory and sampling profilers.
**Exclusions:**
- Hardening the accumulator server and the JVM client so that any exception
in a Python accumulator merge no longer leaves the connection permanently
broken is a separate, pre-existing transport issue and is left out of this
change.
**Success:** A spark.profile.clear() that overlaps accumulator updates for
an existing sampling, perf or memory entry raises no error on the accumulator
server, and no update batch is dropped. After such a clear, no data that
existed when it ran reappears in the results. Sequential merges produce the
same results as before for every profiler type and aggregation level.
**Verification:**
- **Regression:** One thread merges many updates under a single shared
sampling key while another repeatedly clears sampling results. This completes
with no exception from the merge, and a final clear leaves no sampling results.
- **Compatibility:** Perf, memory and sampling profiler results, and
spark.profile.clear behavior, are unchanged in classic and Spark Connect
sessions.
##########
python/pyspark/sql/tests/test_udf_profiler.py:
##########
@@ -823,12 +824,83 @@ 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):
+ import time
+
+ @udf("long")
+ def busy_add1(x):
+ time.sleep(0.05)
+ return x + 1
+
+ df = self.spark.range(10, numPartitions=2).select(busy_add1("id"))
+
+ # Two tasks in one stage of one query.
+ for level, num_results in [("task", 2), ("stage", 1), ("query", 1)]:
+ with self.subTest(level=level):
+ with self.sql_conf(
+ {
+ "spark.sql.pyspark.udf.profiler": "sampling",
+ "spark.sql.pyspark.udf.profiler.samplingInterval":
"10",
+ "spark.sql.pyspark.udf.profiler.samplingAggregation":
level,
+ }
+ ):
+ df.collect()
+
+ results = self.sampling_profile_results
+ self.spark.profile.clear()
+ self.assertEqual(num_results, len(results), str(list(results)))
+ for key, result in results.items():
+ self.assertTrue(key.startswith(f"sampling_{level}_"), key)
Review Comment:
**Nit (P3):** For the `task` level this checks only the `sampling_task_`
prefix (plus the count of two). The documented behavior, one result per task
with its attempts merged, relies on the key leaving out `attemptNumber` and
`taskAttemptId`. Re-adding them, as in the old
`<stage>_<partition>.<attempt>_<taskAttemptId>` key, would keep both the prefix
and the count for these single-attempt tasks, and `local[4]` never retries a
failed task, so retried, speculative or recomputed tasks could silently stop
merging without any test failing. Asserting the exact shape, for example
`^sampling_task_\d+_[01]$` for the two partitions, pins it without needing
retries.
See **Shared repair plan 1** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/PythonUDFRunner.scala:
##########
@@ -57,7 +57,9 @@ abstract class BasePythonUDFRunner(
).getOrElse(Map.empty) ++
Map(
SQLConf.PYTHON_UDF_PROFILER_SAMPLING_INTERVAL.key ->
- SQLConf.get.pythonUDFProfilerSamplingInterval.toString
+ SQLConf.get.pythonUDFProfilerSamplingInterval.toString,
+ SQLConf.PYTHON_UDF_PROFILER_SAMPLING_AGGREGATION.key ->
Review Comment:
**Nit (P3):** This entry is the only way the level reaches non-Arrow Python
UDFs (`BatchEvalPythonExec`, `BatchEvalPythonUDTFExec`), but no test exercises
it: every sampling test declares a bare `@udf("long")`, and with
`spark.sql.execution.pythonUDF.arrow.enabled` defaulting to true such a UDF is
planned as an Arrow-batched UDF, so only
`ArrowPythonRunner.getPythonRunnerConfMap` is covered. If this entry were
dropped or mis-keyed, non-Arrow UDFs would silently fall back to the worker's
`stage` default and every test would still pass. The perf profiler tests in the
same suite cover both runner paths; running the sampling aggregation coverage
with `useArrow=False` as well would close this.
**Verification:**
- **Regression:** With non-Arrow Python UDFs, the task, stage and query
levels produce the same result counts and key shapes as with Arrow-optimized
UDFs.
--
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]