spark-test commented on code in PR #60657: URL: https://github.com/apache/spark/pull/60657#discussion_r4621492430
########## docs/streaming/ss-migration-guide.md: ########## @@ -25,6 +25,8 @@ Please refer [Migration Guide: SQL, Datasets and DataFrame](../sql-migration-gui ## Upgrading from Structured Streaming 4.3 to 4.4 +- Since Spark 4.4, with artifact isolation on (the default in Spark Connect, and in Scala and Java sessions without Hive support), a streaming query uses the artifacts of its own session, a clone of the session that started it, as a batch query of the session does. Its Python UDFs and the readers and writers of its Python data sources now see the files and Python files that the session added with `addArtifact` or `addArtifacts`. As a result, they no longer see files that are only in the default context, such as `--files` or `spark.files` entries, or files added with `SparkContext.addFile`. Python files given with `--py-files` or `spark.submit.pyFiles` are handled by [SPARK-62000](https://issues.apache.org/jira/browse/SPARK-62000). Code on the stream thread outside the execution of a batch, such as `SparkFiles.get` in a custom source or a listener, also resolves to the folder of that session. To restore the previous behavior, set `spark.sql.streaming.propagateArtifactState.enabled` t o `false`. (See [SPARK-61959](https://issues.apache.org/jira/browse/SPARK-61959) for more details.) Review Comment: **Nit (P3):** This entry, the only user-facing description of the change, misstates its scope in three ways, and the conf's doc repeats the second one: - spark-shell sets `spark.sql.artifact.isolation.enabled` to false for the session it creates, independently of Hive (repl/src/main/scala/org/apache/spark/repl/Main.scala:104), so a spark-shell user who reads "Scala and Java sessions without Hive support" concludes they are affected, although they keep the previous behavior. - Of a listener's callbacks, only onQueryStarted runs on the stream thread; onQueryProgress, onQueryIdle and onQueryTerminated run on the asynchronous listener bus thread, which has no job artifact state (StreamingQueryListenerBus.scala:71-77). So `SparkFiles.get` in "a listener" moves only in onQueryStarted, and a file a listener adds with `SparkContext.addFile` in onQueryStarted is not found by `SparkFiles.get` in onQueryProgress. The conf's doc says "in a source or a listener" (sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:5571-5572), wording that came from the earlier review's suggestion. - "handled by SPARK-62000" does not say what happens to `--py-files`. Reading the code, an isolated streaming Python worker now puts only the session's folder and its includes on `sys.path` and starts there (python/pyspark/worker_util.py:213-223, PythonWorkerFactory.scala:272-277), so the .py files that spark-submit puts in the default files folder for `--py-files` in client mode outside YARN, as for a Spark Connect server (SparkSubmit.scala:580-584), are no longer importable from streaming Python UDFs or Python data source readers, as already for batch Python UDFs of a Spark Connect session. Nothing tells those users that the conf brings them back. Saying that spark-shell keeps the previous behavior, naming the onQueryStarted callback of a streaming query listener (and that the other callbacks keep the previous behavior), and saying that such Python files are no longer importable from the query's Python code, with SPARK-62000 tracking them and the conf restoring them meanwhile, would make the entry accurate; in the conf's doc, "in a source or in the onQueryStarted callback of a listener" would do the same. This extends existing discussions [1](https://github.com/apache/spark/pull/60657#discussion_r4616581920), [2](https://github.com/apache/spark/pull/60657#discussion_r4616582021). **Verification:** - **Inspection:** Every Structured Streaming migration-guide entry for the artifact-state change says that spark-shell keeps the previous behavior, that among listener callbacks only onQueryStarted moves to the stream session's folder, and that Python files given with --py-files or spark.submit.pyFiles that reach the workers only through the default files folder are no longer importable from the query's Python code, naming SPARK-62000 and the conf; the doc of spark.sql.streaming.propagateArtifactState.enabled names the onQueryStarted callback rather than listeners in general. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala: ########## @@ -5560,6 +5560,24 @@ object SQLConf { .booleanConf .createWithDefault(true) + val STREAMING_PROPAGATE_ARTIFACT_STATE_ENABLED = + buildConf("spark.sql.streaming.propagateArtifactState.enabled") + .internal() + .doc("When true, a streaming query runs its stream thread with the artifact state of its " + + "own session, a clone of the session that started it, so that the query uses the " + + "artifacts of that session, as a batch query of the session does. This covers its " + + "Python UDFs and other Python functions, the readers of its Python data sources on the " + + "executors and on the driver, the writers of its Python data sources on the executors, " + + "and other code that runs on the stream thread outside the execution of a batch, such " + + "as SparkFiles.get or SparkContext.addFile in a source or a listener. This only " + + "matters when artifact isolation is on. Set to false to restore the previous behavior " + + "for all of them, where they use the default files directory and artifacts of the " + + "Spark context, or a fixed directory for the driver-side reader of a Python data source.") + .version("4.0.6") Review Comment: **Nit (P3):** This version and the new migration-guide entry give the switch two different first releases. The entry sits under "Upgrading from Structured Streaming 4.3 to 4.4" and says "Since Spark 4.4" (docs/streaming/ss-migration-guide.md:26-28), while 4.0.6 says the change first ships in a 4.0 maintenance release, as the backport plan intends. If the change is backported, users who move to a 4.0.x, 4.1.x, 4.2.x or 4.3.x release that carries it get a default-on change in which streaming code stops seeing default-context files, with no migration entry for their release, and the internal conf that restores the previous behavior is named only under 4.4. If it first ships in 4.4, this version misreports when the switch appeared. When maintenance releases ship a change, Spark's migration guides give it an entry under each of their headings and keep the feature-release entry too, as the entries for `spark.sql.execution.arrow.pythonUDF.columnarInput.enabled` show (docs/sql-migration-guide.md:51, 107 and 140). Once the branches are known, name the same first release in both places: if the change is backported, keep 4.0.6 and add the entry, with "Since Spark" naming that release, under a heading for each maintenance release that ships it, such as "Upgrading from Structured Streaming 4.0.5 to 4.0.6"; if it first ships in 4.4, set the version to 4.4.0 and keep the 4.4 entry as it is. This extends an [existing discussion](https://github.com/apache/spark/pull/60657#discussion_r4616582021). **Verification:** - **Inspection:** The version of spark.sql.streaming.propagateArtifactState.enabled equals the release named by the earliest Structured Streaming migration-guide entry for this change, and each release the change ships in has that entry under its own heading. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/python/streaming/PythonStreamingSourceRunner.scala: ########## @@ -108,6 +108,15 @@ class PythonStreamingSourceRunner( envVars.put("SPARK_AUTH_SOCKET_TIMEOUT", authSocketTimeout.toString) envVars.put("SPARK_BUFFER_SIZE", bufferSize.toString) envVars.put("SPARK_PYTHON_RUNTIME", "PYTHON_WORKER") + // The stream thread creates the source under the artifact state of the stream's session, so + // that this worker sees the files of that session, as its executor-side readers do. + val jobArtifactUUID = Review Comment: **Non-blocking (P2):** This gives the Python data source's driver-side worker the stream session's folder, but the other driver-side runner of a streaming query's Python code, StreamingPythonRunner, still sets no `SPARK_JOB_ARTIFACT_UUID` and sends no files root (core/src/main/scala/org/apache/spark/api/python/StreamingPythonRunner.scala:76-126), and the modules it starts read the function without setting up Spark files (python/pyspark/sql/streaming/transform_with_state_driver_worker.py:60, python/pyspark/sql/connect/streaming/worker/foreach_batch_worker.py:100). Two of its users run a query's Python code: the pre-init worker of transformWithStateInPandas and transformWithState, which the stream thread starts while it plans the first batch of every run (TransformWithStateInPySparkExec.scala:187-198), and, in Spark Connect, the foreachBatch worker (StreamingForeachBatchHelper.scala:264-285). Reading the code, under Spark Connect a processor whose class comes from a file added with `addArtifacts(pyfile=True)` is pickled by reference to that module, so the pre-init worker fails with ModuleNotFoundError when the first batch is planned, although the operator's executor-side workers now get the stream session's UUID and could import it. A foreachBatch function that imports a session Python file fails the same way, and `SparkFiles.get` in either worker fails with an AssertionError, because no files root is set there and `getRootDirectory` then asserts a SparkContext (python/pyspark/core/files.py). Unlike the foreach writer, these paths are not deferred, and the conf's doc says the change covers the query's "Python UDFs and other Python functions". Without artifact isolation, as in PySpark Classic, nothing changes for them. **Recommended change:** Let StreamingPythonRunner take an optional job artifact UUID. When TransformWithStateInPySparkPythonPreInitRunner or the Spark Connect foreachBatch helper creates a runner while spark.sql.streaming.propagateArtifactState.enabled is true and a job artifact state is current, pass that state's UUID: the pre-init runner, built on the stream thread, gets the stream session's UUID, and the foreachBatch runner, built while Spark Connect handles the writeStream request, gets the starting session's. With a UUID, StreamingPythonRunner.init sets SPARK_JOB_ARTIFACT_UUID and sends the session folder and the function's Python includes in its init message, and the transformWithState driver worker and the foreachBatch worker apply them with worker_util.setup_spark_files before they unpickle the function; without one, the runner and its workers behave as on the base branch. Every Python module the runner starts, including the listener worker, which gets no UUID, reads the e xtended init message. Add Spark Connect artifact tests of a transformWithStateInPandas processor and a foreachBatch function that use a session Python file and a session file. **Why this works:** A driver-side worker can import session Python files and open session files only if its working directory, sys.path and SparkFiles root point at the session's folder. SPARK_JOB_ARTIFACT_UUID makes PythonWorkerFactory start the worker in <files root>/<uuid> (PythonWorkerFactory.scala lines 272-277), and setup_spark_files puts that folder and the session's .zip and .egg includes on sys.path and makes SparkFiles resolve there, the same setup PythonStreamingSourceRunner now gives the stream reader's worker. The driver already holds each session's files in that folder, because SparkContext.addFile fetches them there when the session, or the stream session's clone, registers them (ArtifactManager.scala lines 433-434 and 614-627). **Compatibility:** Without a job artifact UUID, StreamingPythonRunner workers keep the base branch's working directory and get no files root. **Risks:** With the conf on, the pre-init and foreachBatch workers no longer start in the driver's working directory, so Python code there that opens files by a path relative to it resolves against the session folder instead, as the query's executor-side workers already do; setting spark.sql.streaming.propagateArtifactState.enabled to false restores the previous directory. The foreachBatch worker takes the starting session's artifacts because it starts before the stream session exists, so a file the session adds after the query starts is visible to the foreachBatch function but not to the query's Python UDFs. In local mode the driver and the executor share one files root, and once a session that ran a task there goes 30 minutes without another, the executor evicts it and deletes its folder. The foreachBatch worker uses the starting session's folder while, by default, the query's batches run in the query's own session, so during a long-running local-mode query the foreachBatch func tion can lose the session's files, as the starting session's own driver-side Python planner workers already can. **Constraints:** With spark.sql.streaming.propagateArtifactState.enabled set to false, or without artifact isolation, the pre-init, foreachBatch and listener workers get the same environment and the same usable init content as on the base branch. Every Python module that StreamingPythonRunner starts reads the extended init message, so none of them misreads the function that follows it. **Exclusions:** - The Spark Connect Python foreach writer, which the PR defers to SPARK-61997. - The Spark Connect Python listener worker, which serves the session rather than one streaming query and keeps its current working directory and files. **Verification:** - **Regression:** Under Spark Connect with artifact isolation on, a streaming query whose transformWithStateInPandas processor is defined in a Python file added to the session runs to completion, where on the base branch it fails with ModuleNotFoundError when its first batch is planned. - **Regression:** Under Spark Connect with artifact isolation on, a streaming query whose foreachBatch function imports a Python file added to the session and reads a file added to the session through SparkFiles.get produces the expected output. - **Compatibility:** With spark.sql.streaming.propagateArtifactState.enabled set to false, the transformWithStateInPandas pre-init worker and the foreachBatch worker start without SPARK_JOB_ARTIFACT_UUID and without the session's files root, so the processor-from-a-session-file query fails as on the base branch. - **Compatibility:** A Spark Connect Python streaming query listener still receives its events after the init message of StreamingPythonRunner workers changes. ########## 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: Thanks for explaining. Leaving the release of these pools to SPARK-61998 is fine, since it needs a new mechanism in core that also covers the existing per-session pools. This review raises one small related point: nothing in the code marks this deferral yet. <!-- SPARK_DEV_REVIEW_REPLY {"feedback_id":"inline:4611864868","thread_id":"inline:4611864868","verdict_sha256":"6d45f46e2175a79cd06442d04cf166ec5e3b5c1b767c0a8e5f38e12e19c1e83d"} --> ########## sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamExecution.scala: ########## @@ -233,7 +230,21 @@ 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. + // TODO(SPARK-61997): Spark Connect builds the Python foreach writer on the request + // thread, under the artifact state of the session that starts the query, so its Python + // worker does not see the files of this stream's session yet. + if (sparkSessionForStream.sessionState.conf.getConf( + SQLConf.STREAMING_PROPAGATE_ARTIFACT_STATE_ENABLED)) { + JobArtifactSet.withActiveJobArtifactState(sparkSessionForStream.artifactManager.state) { Review Comment: **Nit (P3):** Running the stream thread under the run's stream-session state gives every Python worker of the run that session's UUID, which is new for each run, so each run leaves one Python worker factory, with its daemon and idle-worker monitor thread, in SparkEnv's cache on each executor that ran its Python tasks, until the executor stops (SparkEnv.scala:216-218, 293, 336). Leaving the release to SPARK-61998 is fine, but only the PR description and the reply on the worker-pool thread say so, and the comment above this line names only TODO(SPARK-61997). Without a marker in the code, a later cleanup could share the default pool again, which would bring the bug back, or the cost could outlive the follow-up's context. A TODO next to the existing one would mark it, for example: ```scala // TODO(SPARK-61998): With artifact isolation on, each run gives its Python workers // its own artifact UUID, so each executor that runs its Python tasks keeps one // more Python worker pool until it stops. ``` This extends an [existing discussion](https://github.com/apache/spark/pull/60657#discussion_r4611864868). **Verification:** - **Inspection:** The comment above the stream-thread artifact-state wrapper in StreamExecution.scala carries a TODO naming SPARK-61998, which says that each run of a streaming query with Python code keeps its own Python worker pool on the executors until they stop. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala: ########## @@ -5560,6 +5560,21 @@ object SQLConf { .booleanConf .createWithDefault(true) + val STREAMING_PROPAGATE_ARTIFACT_STATE_ENABLED = + buildConf("spark.sql.streaming.propagateArtifactState.enabled") + .internal() + .doc("When true, a streaming query runs its stream thread with the artifact state of its " + + "own session, a clone of the session that started it. Its Python UDFs and the readers " + + "of its Python data sources, on the executors and on the driver, then see the files " + + "and Python files of that session, as in a batch query of the session. This only " + + "matters when artifact isolation is on. Set to false to restore the previous " + + "behavior, where these use the default files directory of the Spark context, or a " + + "fixed directory for the driver-side reader of a Python data source.") Review Comment: Thanks, the doc now names the writers and the other code on the stream thread. The words "in a source or a listener" came from my suggestion, and they overstate which listener callbacks the change affects, so this review raises a related correction for that wording. <!-- SPARK_DEV_REVIEW_REPLY {"feedback_id":"inline:4616581920","thread_id":"inline:4616581920","verdict_sha256":"6d45f46e2175a79cd06442d04cf166ec5e3b5c1b767c0a8e5f38e12e19c1e83d"} --> ########## sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala: ########## @@ -5560,6 +5560,21 @@ object SQLConf { .booleanConf .createWithDefault(true) + val STREAMING_PROPAGATE_ARTIFACT_STATE_ENABLED = Review Comment: Thanks, the entry is in and names the conf. This review raises two related issues with it: the release the entry gives and the conf's version disagree, and the entry misstates which sessions and which code the change affects. <!-- SPARK_DEV_REVIEW_REPLY {"feedback_id":"inline:4616582021","thread_id":"inline:4616582021","verdict_sha256":"6d45f46e2175a79cd06442d04cf166ec5e3b5c1b767c0a8e5f38e12e19c1e83d"} --> -- 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]
