spark-test commented on code in PR #60657:
URL: https://github.com/apache/spark/pull/60657#discussion_r4616581920
##########
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:
**Nit (P3):** This doc says that with the conf on, the query's Python UDFs
and the readers of its Python data sources see the session's files, and that
`false` restores "these". The conf gates the artifact state of the whole stream
thread (StreamExecution.scala:237-244), though, so it also moves the
executor-side writers of Python data source sinks, which capture that state
while each batch is planned (PythonStreamingWrite.scala:39), and other code
that runs on the stream thread outside a batch's execution, such as
`SparkFiles.get`, `SparkContext.addFile` or `addJar` in a custom source or an
`onQueryStarted` listener (SparkFiles.scala:30-35,
SparkContext.scala:1869-1870). Since the conf is internal, this doc is the only
place in the code that describes the escape hatch, and someone checking whether
it restores a sink writer's or a custom source's file lookup would conclude
from it that it does not. For example:
```suggestion
.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 a batch's
execution, 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.")
```
**Verification:**
- **Inspection:** The doc of
spark.sql.streaming.propagateArtifactState.enabled in SQLConf.scala names
Python UDFs and other Python functions, the readers of Python data sources,
their executor-side writers, and other code on the stream thread outside a
batch's execution as what the conf changes, and says that false restores the
previous file lookup for all of them.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/streaming/PythonStreamingDataSourceSuite.scala:
##########
@@ -588,6 +639,119 @@ class PythonStreamingDataSourceSuite extends
PythonDataSourceSuiteBase {
q.awaitTermination()
}
+ /**
+ * Reads a file of a new session with the executor-side reader of a
streaming Python data
+ * source, and returns the rows that the query wrote.
+ */
+ private def readSessionFileWithStreamReader(propagateArtifactState:
Boolean): Seq[Row] = {
+ val fileName = "stream_reader_session_file.txt"
+ val sourceName = "SessionFileDataSource"
+ val dataSourceScript =
+ s"""
+ |from pyspark.sql.datasource import DataSource,
DataSourceStreamReader, InputPartition
+ |
+ |class FileStreamReader(DataSourceStreamReader):
+ | def initialOffset(self):
+ | return {"offset": 0}
+ | def latestOffset(self):
+ | return {"offset": 1}
+ | def partitions(self, start: dict, end: dict):
+ | return [InputPartition(i) for i in range(start["offset"],
end["offset"])]
+ | def commit(self, end: dict):
+ | pass
+ | def read(self, partition):
+ | from pyspark import SparkFiles
+ | with open(SparkFiles.get("$fileName")) as f:
+ | yield (f.read(),)
+ |
+ |class $sourceName(DataSource):
+ | def schema(self) -> str:
+ | return "value STRING"
+ | def streamReader(self, schema):
+ | return FileStreamReader()
+ |""".stripMargin
+ // A new session, so that its file is not visible to the other tests.
+ val session = spark.newSession()
+ session.conf.set(
+ SQLConf.STREAMING_PROPAGATE_ARTIFACT_STATE_ENABLED.key,
propagateArtifactState.toString)
+ var rows: Seq[Row] = Nil
+ withTempDir { dir =>
+ val file = new File(dir, fileName)
+ Files.writeString(file.toPath, "session file")
+ session.artifactManager.addArtifact(Paths.get(s"files/$fileName"),
file.toPath, None)
+ session.dataSource.registerPython(
+ sourceName, createUserDefinedPythonDataSource(sourceName,
dataSourceScript))
+ val q = session.readStream.format(sourceName).load()
+
.writeStream.format("memory").queryName("stream_reader_session_file").start()
+ try {
+ q.processAllAvailable()
+ } finally {
+ q.stop()
+ }
+ rows = session.table("stream_reader_session_file").collect().toSeq
+ }
+ rows
+ }
+
+ test("SPARK-61959: Stream reader reads the files of the session") {
+ assume(shouldTestPandasUDFs)
+ assert(readSessionFileWithStreamReader(propagateArtifactState = true) ===
+ Seq(Row("session file")))
+ }
+
+ test("SPARK-61959: Stream reader misses the files of the session without
propagation") {
+ assume(shouldTestPandasUDFs)
+ // The previous behavior: the reader looks in the default files directory.
+ val e = intercept[StreamingQueryException] {
+ readSessionFileWithStreamReader(propagateArtifactState = false)
+ }
+ assert(e.getMessage.contains("FileNotFoundError"), e.getMessage)
+ }
+
+ test("SPARK-61959: Driver-side worker of a stream reader uses the current
artifact state") {
+ assume(shouldTestPandasUDFs)
+ val dataSourceScript =
+ s"""
+ |from pyspark.sql.datasource import DataSource, DataSourceStreamReader
+ |
+ |class RootDirectoryStreamReader(DataSourceStreamReader):
+ | def initialOffset(self):
+ | from pyspark import SparkFiles
+ | return {"root": SparkFiles.getRootDirectory()}
Review Comment:
**Nit (P3):** This only reports `SparkFiles.getRootDirectory()`, which comes
from the files root that `writeSparkFiles` sends
(PythonStreamingSourceRunner.scala:134-135). The other half of the driver-side
change, `SPARK_JOB_ARTIFACT_UUID` at PythonStreamingSourceRunner.scala:119,
makes `PythonWorkerFactory` start the worker in `<files root>/<uuid>`
(PythonWorkerFactory.scala:272-277), and no new test observes that: the
end-to-end tests read through `SparkFiles.get` and import from the files root,
which the worker adds to `sys.path`. So deleting line 119 of
PythonStreamingSourceRunner.scala, or setting the variable with the conf off,
would leave every new test passing, and a driver-side reader method that opens
a session file by a relative path, such as an archive's alias, could break
unnoticed. Returning `os.getcwd()` here as well, and asserting that it ends
with `spark-61959-state` with the state propagated and does not with the conf
off, would cover it.
**Verification:**
- **Behavior:** With an artifact state set and
spark.sql.streaming.propagateArtifactState.enabled on, the driver-side worker
of a streaming Python data source reports a working directory that ends with
the state's UUID, so removing the SPARK_JOB_ARTIFACT_UUID setting from
PythonStreamingSourceRunner makes the test fail.
- **Compatibility:** With the same artifact state and the conf off, the
driver-side worker reports a working directory that does not end with the
state's UUID, as on the base branch.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/streaming/PythonStreamingDataSourceSuite.scala:
##########
@@ -135,6 +136,56 @@ class PythonStreamingDataSourceSimpleSuite extends
PythonDataSourceSuiteBase {
// Verify prefetch and cache pattern of SimpleDataSourceStreamReader handle
empty
// data batch correctly.
+ test("SPARK-61959: Simple stream reader reads the files of the session on
the driver") {
Review Comment:
**Nit (P3):** The comment on the two lines above, at
PythonStreamingDataSourceSuite.scala:137-138, describes the
`SimpleDataSourceStreamReader read empty batch` test, which now starts at line
189. This new test was inserted between them, so the comment now heads a test
that reads a session file and imports a session module on the driver, and the
empty-batch test has lost its explanation. Moving this test above the comment,
or below the empty-batch test, puts the comment back with its test.
**Verification:**
- **Inspection:** In PythonStreamingDataSourceSimpleSuite, the comment about
the prefetch and cache pattern handling an empty batch directly precedes the
"SimpleDataSourceStreamReader read empty batch" test, and the SPARK-61959
simple reader test keeps its content.
##########
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:
**Non-blocking (P2):** Making this the default matches what batch queries of
the same session already do, but it changes behavior for users whose streaming
code relies on files in the default context, and nothing they read when
upgrading tells them. Reading the code, a Spark Connect streaming Python UDF
that opens `SparkFiles.get("conf.json")` for a `--files` or `spark.files` entry
found the file on the base branch and now raises `FileNotFoundError`, and in a
Scala Classic session without Hive support, where isolation is on by default, a
custom source whose `latestOffset` calls `SparkFiles.get` for a `--files` entry
now gets a path under `<driver root>/<stream session UUID>` that does not
exist. This conf brings the old behavior back, but it is internal, so `SET -v`
and the configuration docs leave it out, and
docs/streaming/ss-migration-guide.md has no entry for the change. Spark
documents comparable changes with their rollback conf in the migration guides,
as the foreachBatch cl
oned-session entry does (docs/streaming/ss-migration-guide.md:43), with a
heading of their own for each maintenance release that ships them
(docs/sql-migration-guide.md:51, 107 and 140). That matters here, because the
conf's 4.0.6 version means the fix is headed for maintenance releases.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60657#issuecomment-6980578987).
**Verification:**
- **Inspection:** Under the heading of each release that first ships the
fix, docs/streaming/ss-migration-guide.md has an entry that names
spark.sql.streaming.propagateArtifactState.enabled, says that with artifact
isolation on, streaming Python code and code on the stream thread, such as
SparkFiles.get in a custom source, use the stream session's artifact context
and no longer find files that are only in the default context, and says that
setting the conf to false restores the previous behavior.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamExecution.scala:
##########
@@ -233,7 +230,18 @@ 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.
Review Comment:
**Nit (P3):** With the rebinding of the Spark Connect Python foreach writer
deferred to SPARK-61997, this comment is a natural place to say so. Spark
Connect builds the writer on the request thread under the artifact state of the
session that starts the query, and the writer keeps that UUID
(SparkConnectPlanner.scala:3751-3756, PythonForeachWriter.scala:88), so its
`process` still misses the session's files on the executors while the query's
Python UDFs now find them. Nothing in the code mentions the gap or SPARK-61997,
so a later change could assume that all streaming Python code now sees the
session's files. For example:
```suggestion
// 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.
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/60657#issuecomment-6980578987).
**Verification:**
- **Inspection:** The comment that explains the stream-thread artifact state
in StreamExecution.scala carries a TODO naming SPARK-61997, which says that the
Spark Connect Python foreach writer still takes the starting session's artifact
UUID and so does not see the stream session's files.
--
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]