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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/python/PythonMicroBatchStream.scala:
##########
@@ -83,8 +83,9 @@ abstract class PythonMicroBatchStreamBase(
   }
 
   override def createReaderFactory(): PartitionReaderFactory = {
+    val jobArtifactUUID = JobArtifactSet.getCurrentJobArtifactState.map(_.uuid)

Review Comment:
   **Non-blocking (P2):** This gives the executor-side `read()` the stream 
session's UUID, but the driver-side half of the same Python data source still 
uses a fixed root: `PythonStreamingSourceRunner.init` sends 
`Some("streaming_job")` (PythonStreamingSourceRunner.scala:125), a directory 
nothing fills, and sets no `SPARK_JOB_ARTIFACT_UUID`. That single driver worker 
runs `initialOffset`, `latestOffset`, `partitions` and `commit` of every 
`DataSourceStreamReader`, and the `read()` of every 
`SimpleDataSourceStreamReader`, which the prefetching wrapper calls from 
`latestOffset` on the driver (datasource_internal.py:125-131). Reading the 
code, with isolation on, a `latestOffset` or a simple reader's `read` that 
opens `SparkFiles.get("conf.json")` for a file added with 
`addArtifacts(file=True)` would still raise `FileNotFoundError`, and a module 
added with `pyfile=True` still could not be imported there, while the same 
reader's executor-side `read` now succeeds.
   
   `init()` already runs on the stream thread under the state the new wrapper 
sets (PythonScan.scala:42-45), so it can take the root and 
`SPARK_JOB_ARTIFACT_UUID` from `JobArtifactSet.getCurrentJobArtifactState` the 
way this line does, keeping `streaming_job` when no state is set so that the 
isolation-off case stays as it is. The new tests only exercise 
`DataSourceStreamReader.read`; a test with a simple reader and one with a 
driver-side method would cover this.
   
   **Verification:**
   - **Regression:** With artifact isolation on, under Spark Connect both 
locally and on a local cluster, a streaming query on a Python data source whose 
SimpleDataSourceStreamReader.read opens a session file through SparkFiles.get 
returns the file's content, and so does one whose 
DataSourceStreamReader.latestOffset reads that file to choose its end offset; 
on the base branch both fail with FileNotFoundError on the driver.
   - **Behavior:** With artifact isolation on, a streaming Python data source 
whose driver-side reader method imports a module the session added as a Python 
file runs to completion.
   - **Compatibility:** Without artifact isolation, the driver-side worker of a 
streaming Python data source still receives the base branch's files root, so 
SparkFiles resolves there as before.



##########
python/pyspark/sql/tests/connect/client/test_artifact.py:
##########
@@ -178,6 +179,107 @@ def test_add_file(self):
             ).create()
         )
 
+    def streaming_input(self, spark_session, d):
+        with open(os.path.join(d, "input.json"), "w") as f:
+            f.write('{"id": 0}\n')
+        return spark_session.readStream.schema("id BIGINT").json(d)
+
+    def collect_streaming_query(self, df):
+        query_name = f"artifact_streaming_{uuid.uuid4().hex}"
+        q = 
df.writeStream.format("memory").queryName(query_name).trigger(availableNow=True).start()
+        try:
+            q.awaitTermination()
+        finally:
+            q.stop()
+        return [tuple(r) for r in df.sparkSession.table(query_name).collect()]
+
+    def check_add_file_streaming(self, spark_session, use_arrow):
+        with tempfile.TemporaryDirectory(prefix="check_add_file_streaming") as 
d:
+            # Each file has its own name because Spark Classic shares files 
between sessions.
+            file_name = f"my_streaming_file_{use_arrow}.txt"
+            with open(os.path.join(d, file_name), "w") as f:
+                f.write("Hello streaming!!")
+            spark_session.addArtifacts(os.path.join(d, file_name), file=True)
+
+            @udf("string", useArrow=use_arrow)
+            def func(x):
+                from pyspark import SparkFiles
+
+                with open(SparkFiles.get(file_name), "r") as my_file:
+                    return my_file.read().strip()
+
+            input_dir = os.path.join(d, "input")
+            os.mkdir(input_dir)
+            df = self.streaming_input(spark_session, 
input_dir).select(func("id"))
+            self.assertEqual(self.collect_streaming_query(df), [("Hello 
streaming!!",)])
+
+    def test_add_file_streaming(self):
+        # A streaming query plans its micro-batches in its own thread, which 
must still see the
+        # files of the session.
+        self.check_add_file_streaming(self.spark, use_arrow=False)
+        self.check_add_file_streaming(self.spark, use_arrow=True)
+
+    def test_add_pyfile_streaming(self):
+        with tempfile.TemporaryDirectory(prefix="test_add_pyfile_streaming") 
as d:
+            pyfile_path = os.path.join(d, "my_streaming_pyfile.py")
+            with open(pyfile_path, "w") as f:
+                f.write("my_func = lambda: 10")
+
+            @udf("int")
+            def func(x):
+                import my_streaming_pyfile
+
+                return my_streaming_pyfile.my_func()
+
+            self.spark.addArtifacts(pyfile_path, pyfile=True)
+            input_dir = os.path.join(d, "input")
+            os.mkdir(input_dir)
+            df = self.streaming_input(self.spark, input_dir).select(func("id"))
+            self.assertEqual(self.collect_streaming_query(df), [(10,)])
+
+    def test_add_file_python_streaming_data_source(self):

Review Comment:
   **Nit (P3):** This test needs pyarrow: streaming from a Python data source 
starts the driver-side worker 
`pyspark.sql.streaming.python_streaming_source_runner`, which imports 
`plan_data_source_read` (python_streaming_source_runner.py:50), and that module 
imports pyarrow at module level (plan_data_source_read.py:22). The Spark 
Connect classes are skipped without Connect's dependencies, but the Spark 
Classic `ArtifactTests` in pyspark/sql/tests/test_artifact.py inherits this 
mixin with no skip, so without pyarrow (a plain `pip install pyspark` does not 
include it) this test would end in an error instead of a skip. The sibling 
streaming data source tests use `@unittest.skipIf(not have_pyarrow, 
pyarrow_requirement_message)` with both names imported from 
`pyspark.testing.utils` (test_python_streaming_datasource.py:43, 82); the same 
decorator and import would fix it here.
   
   **Verification:**
   - **Inspection:** The streaming Python data source test of the shared 
PySpark artifact test mixin, and any other Python data source test added to 
that mixin, carries the repository's pyarrow skip condition and message, as the 
sibling Python streaming data source tests do.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamExecution.scala:
##########
@@ -233,7 +230,13 @@ abstract class StreamExecution(
         // To fix call site like "run at <unknown>:0", we bridge the call site 
from the caller
         // thread to this micro batch thread
         sparkSession.sparkContext.setCallSite(callSite)
-        runStream()
+        // The batches run in `sparkSessionForStream`, a clone of the session 
with its own copy
+        // of the artifacts. `SQLExecution` applies its artifact state only to 
run the jobs, but
+        // the batches are planned before that, and some plan nodes keep the 
state they are built
+        // with, for example the Python UDFs.
+        
JobArtifactSet.withActiveJobArtifactState(sparkSessionForStream.artifactManager.state)
 {

Review Comment:
   **Non-blocking (P2):** With this wrapper, every Python worker that a 
streaming query starts in an isolated session gets `SPARK_JOB_ARTIFACT_UUID` 
set to that run's stream session UUID, which is new for every run, because 
`cloneSession` creates a random `sessionUUID`. `SparkEnv` keys 
`PythonWorkerFactory` by the full worker environment and stops factories only 
in `SparkEnv.stop` (SparkEnv.scala:328-337), and each factory keeps a 
`pyspark.daemon` process and an idle-worker monitor thread whose loop never 
exits (PythonWorkerFactory.scala:142, 465-479). Neither the executor's 
isolated-session cleanup (Executor.scala:216-239) nor the stream session's 
artifact cleanup releases them.
   
   Reading the code, a query with a Python UDF that is started and stopped N 
times, for example a scheduled `availableNow` query, leaves N more daemons and 
monitor threads on each executor that ran its Python tasks, plus one factory 
per run on the driver when a Python data source is planned on the stream 
thread; on the base branch these workers shared one pool. Idle workers are 
reaped after a minute, but the daemons and threads stay until the JVM exits, so 
a long-lived Spark Connect cluster can eventually run into memory, process or 
thread limits. How fast depends on how often queries start, which the review 
did not measure.
   
   **Recommended change:** Add a SparkEnv operation that removes and stops 
every Python worker factory whose environment carries a given 
SPARK_JOB_ARTIFACT_UUID (core/src/main/scala/org/apache/spark/SparkEnv.scala), 
make PythonWorkerFactory.stop also end its idle-worker monitor thread, whose 
loop never exits today 
(core/src/main/scala/org/apache/spark/api/python/PythonWorkerFactory.scala, 
lines 465-479), and call the new operation where a UUID's lifetime ends: in the 
executor's isolated session cleanup 
(core/src/main/scala/org/apache/spark/executor/Executor.scala, lines 216-239) 
and in the driver's session artifact cleanup 
(sql/core/src/main/scala/org/apache/spark/sql/artifact/ArtifactManager.scala, 
lines 774-789). Add Python worker lifecycle tests that start and stop several 
streaming queries with a Python UDF in an isolated session and check that their 
stream sessions' factories are gone once those sessions are cleaned up.
   
   **Why this works:** A factory keyed by a job artifact UUID only serves 
workers that run in that UUID's directory, and once the executor has evicted 
the session and deleted that directory, or the driver has dropped the session's 
artifacts, no new task of that session can use them. Stopping the matching 
factories at those points, together with their monitor threads, bounds the 
retained Python daemons and threads by the sessions that are still alive 
instead of by every session and query run since the JVM started.
   
   **Compatibility:** Factories of live sessions and of the default UUID keep 
reusing their workers as before.
   
   **Risks:** Spark Connect sessions' batch Python worker pools are also 
released when an executor evicts the session after 30 minutes without a task or 
when the session's artifacts are cleaned up, so a session that becomes active 
again pays the Python daemon start-up once more; skipping the new calls rolls 
this back. In local mode the driver and the executor share one SparkEnv, so an 
executor eviction also releases the driver's planner worker factories of that 
UUID, which the next planner call creates again.
   
   **Constraints:** Never stop a factory while a worker it handed out is still 
in use; defer the stop until that worker is returned.
   
   **Exclusions:**
   - Factories keyed by the default UUID, which serve sessions without artifact 
isolation and stay until SparkEnv stops, as on the base branch.
   
   **Verification:**
   - **Regression:** Starting and stopping several streaming queries with a 
Python UDF in an isolated session and then cleaning up their stream sessions 
leaves no Python worker factory, daemon process or monitor thread for those 
UUIDs in the executor's and the driver's worker registry, where without this 
repair one is kept for every run.
   - **Behavior:** Stopping a Python worker factory ends its idle-worker 
monitor thread and its daemon process.
   - **Compatibility:** A Python task that holds a worker while the session of 
that worker's UUID is cleaned up completes normally, and the worker's factory 
stops only after the worker is returned.



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