HeartSaVioR commented on code in PR #60657:
URL: https://github.com/apache/spark/pull/60657#discussion_r4615042187
##########
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:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks, confirmed. On the previous head, a `SimpleDataSourceStreamReader`
whose `read` imports a Python file added with `pyfile=True` fails on the driver
with `ModuleNotFoundError`. This was so on master too.
Fixed in fd256e6d51d. `PythonStreamingSourceRunner.init` now takes the
current job artifact state. That is the stream session's state, since `init`
runs on the stream thread. The driver-side worker uses that UUID as its files
root and gets `SPARK_JOB_ARTIFACT_UUID`, like `PythonPlannerRunner` does for
batch planning. Without a state (isolation off), or with
`spark.sql.streaming.propagateArtifactState.enabled` set to `false`, it keeps
`streaming_job` as before.
The driver has those files: `SparkContext.addFile` fetches each file into
`<driver root>/<uuid>` when the session (here, the stream's cloned session)
registers it.
New tests: `PythonStreamingDataSourceSimpleSuite` and the Spark Connect
`ArtifactTests` check a simple reader that reads a session file and imports a
session Python file on the driver.
##########
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:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks. It is true that streaming Python workers now get a pool per query
run. But the missing release is not new, and I'd like to keep it out of this PR.
- `SparkEnv` stops Python worker factories only in `SparkEnv.stop`, for
every UUID. On master, each Spark Connect session already gets its own pool
that is never released.
- Since 4.3.0, each run of a Python `foreachBatch` gets one too, because the
batch runs in the stream's cloned session by default
(`spark.sql.connect.streaming.foreachBatch.useClonedSession`).
- This PR moves streaming Python UDFs onto the same pattern. The pool per
UUID is what makes the worker use the session's files. Sharing the default pool
would bring back the bug.
Releasing factories when a session's UUID ends needs a new mechanism in
core: `SparkEnv`, `PythonWorkerFactory`'s monitor thread, executor session
eviction and the artifact cleanup. That mechanism fixes the existing cases too,
so I filed SPARK-61998 for it, to handle in its own PR. Until then,
`spark.sql.streaming.propagateArtifactState.enabled=false` brings streaming
back to the shared pool.
##########
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:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks, fixed in fd256e6d51d. The streaming Python data source tests now use
`@unittest.skipIf(not have_pyarrow, pyarrow_requirement_message)`. The Arrow
UDF case had the same problem, so it is now its own test,
`test_add_file_streaming_arrow`, with the same skip.
--
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]