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


##########
docs/sql-migration-guide.md:
##########
@@ -101,6 +101,7 @@ license: |
 - Since Spark 4.4, a CHECK constraint that `ALTER TABLE ... ADD CONSTRAINT` 
adds to a Data Source V2 table, and whose condition reads the current time, 
date, catalog, user and the like, such as `ts <= current_timestamp()` or `db = 
current_database()`, is checked against their values at the time of each write. 
Previously, it was checked against their values at the time of the `ALTER 
TABLE`, unless a write could not read back a predicate for its condition, such 
as one with a lambda function or one that passes a column to `datediff`, `year` 
or `upper` (SPARK-60032). Such a constraint is stored without a predicate, so 
each write parses and analyzes its SQL text under the session of the write, as 
it does for a constraint without a predicate that `CREATE TABLE` adds. A 
setting of the write such as `spark.sql.ansi.enforceReservedKeywords`, which 
reserves `TIME`, or `spark.sql.ansi.doubleQuotedIdentifiers` can then make it 
fail to parse the text or read it differently. A row-level operation
  that copies unchanged rows, such as a `DELETE` or `UPDATE` on a copy-on-write 
table, fails with `CHECK_CONSTRAINT_VIOLATION` on a copied row that no longer 
satisfies the condition. For example, `ts >= current_timestamp() - INTERVAL 30 
DAYS` now fails such a `DELETE` once a copied row is older than 30 days. A 
condition that Spark detects a write could resolve differently is stored as 
before, so a write accepts and rejects the same rows for it as before. Examples 
are conditions that also read a variable, a `CHAR` column, a name with more 
than one part such as a column qualified by the table name, or a constant that 
depends on the session time zone, such as `'2024-01-01 00:00:00'` cast to a 
timestamp. So are conditions with a name such as `current_date` or `user` 
without parentheses, which a write can read as a column name, and conditions 
whose text the parser settings of the `ALTER TABLE`, such as 
`spark.sql.ansi.doubleQuotedIdentifiers` or 
`spark.sql.parser.escapedStringLiterals`, r
 ead differently from their default values. ANSI mode, 
`spark.sql.timestampType` and the session time zone are taken from the session 
for this comparison, as for a generation expression. A condition that reads the 
current date or time only through a typed literal such as `DATE 'today'` is 
also stored as before. An existing constraint keeps its stored predicate until 
it is dropped and added again. `Check.predicate()` is null for a constraint 
stored without a predicate, so a connector that validates or enforces it itself 
has to evaluate `Check.predicateSql()`. To restore the previous behavior, set 
`spark.sql.legacy.freezeCurrentValuesInCheckConstraint` to `true` before adding 
the constraint. A constraint added without it is not changed.
 - Since Spark 4.4, a function created by `CREATE FUNCTION ... AS 'class'` 
whose class implements 
`org.apache.spark.sql.connector.catalog.functions.UnboundFunction` and extends 
either a Hive UDF class (such as `UDF` or `GenericUDF`) or 
`org.apache.spark.sql.expressions.UserDefinedAggregateFunction` runs as a 
DataSource V2 function instead of a Hive UDF or Spark UDAF, including functions 
created in earlier versions. Its result type, argument coercion, and null 
handling are defined by the V2 implementation selected by 
`UnboundFunction.bind`. Hive's `@UDFType` and Spark UDAF's `deterministic` 
property do not control the V2 path. For scalar functions, determinism uses 
`BoundFunction.isDeterministic()` (default `true`) and the arguments' 
determinism. A call with constant arguments can therefore become eligible for 
constant folding during query planning instead of being evaluated per row.
 - Since Spark 4.4, `next_day` and `last_day` fail with `DATETIME_OVERFLOW` 
when the result is later than the maximum `DATE`, `+5881580-07-11`, and `trunc` 
fails with it when the result is earlier than the minimum `DATE`, 
`-5877641-06-23`, regardless of `spark.sql.ansi.enabled`. Previously, these 
functions silently returned a wrong date, in most cases one at the other end of 
the `DATE` range; for example, `last_day(DATE'+5881580-07-11')` returned 
`-5877641-07-12` and `trunc(DATE'-5877641-06-23', 'MONTH')` returned 
`+5881580-06-20`, while `trunc` to `QUARTER` failed with `ARITHMETIC_OVERFLOW`. 
`next_day` and `trunc` to `WEEK` also returned a wrong date for the first days 
of the `DATE` range; for example, `next_day(DATE'-5877641-06-23', 'MO')` and 
`trunc(DATE'-5877641-07-01', 'WEEK')` returned `-5877641-06-25`, a Thursday, 
and now return `-5877641-06-29`.
+- Since Spark 4.4, `LIST FILES`, `LIST JARS` and `LIST ARCHIVES` in a session 
whose artifacts are isolated, which are the sessions of Spark Connect and the 
Scala and Java sessions without Hive support, list the files, jars and archives 
added to the session and those added to the `SparkContext` outside of any 
session, such as with `--files`, `--jars` and `--archives`, but no longer those 
added by the other sessions, such as with `ADD FILE` or 
`SparkSession.addArtifact`. Previously, they listed those of every session. The 
sessions with Hive support, of `spark-shell` and of PySpark, whose artifacts 
are not isolated, still list all of them, and `SparkContext.listFiles`, 
`SparkContext.listJars` and `SparkContext.listArchives` are unchanged.

Review Comment:
   **Nit (P3):** Which sessions are scoped is decided only by 
`spark.sql.artifact.isolation.enabled`, not by the product or by Hive support, 
so this entry misclassifies some of them:
   
   - A Hive catalog set in the SparkConf, such as with `--conf 
spark.sql.catalogImplementation=hive` or in `spark-defaults.conf`, never 
reaches the builder hook that turns isolation off 
(`classic/SparkSession.scala:999-1004`), because `build` copies only the 
builder's own options. Such Scala and Java sessions, and the sessions of a 
`start-connect-server.sh` server with a Hive catalog, are isolated and their 
`LIST` output changes, although the entry says that sessions with Hive support 
still list all of them.
   - PySpark turns isolation off only in the conf of a `SparkContext` that 
Python creates (`python/pyspark/core/context.py:86-90, 270-271`), so a PySpark 
session over a `SparkContext` created in the JVM is isolated too.
   - Every `spark-shell` session is unisolated (`repl/Main.scala:104`). The 
`SessionResources` comment (`resources.scala:61-63`) calls Scala sessions 
without Hive support isolated, which includes `spark-shell`, so it needs the 
same fix.
   
   Users in the first two groups can read this entry and conclude that their 
`LIST` output is unchanged. A wording keyed to the setting could be:
   
   ```suggestion
   - Since Spark 4.4, `LIST FILES`, `LIST JARS` and `LIST ARCHIVES` in a 
session whose artifacts are isolated list the files, jars and archives added to 
the session and those added to the `SparkContext` outside of any session, such 
as with `--files`, `--jars` and `--archives`, but no longer those added by the 
other sessions, such as with `ADD FILE` or `SparkSession.addArtifact`. 
Previously, they listed those of every session. Artifacts are isolated by 
default, and always in the sessions of a Spark Connect server started with 
`start-connect-server.sh`. Spark does not isolate them in `spark-shell`, in 
PySpark when PySpark creates the `SparkContext`, or in Scala and Java sessions 
whose builder enables Hive support, such as with `enableHiveSupport()`, so 
those sessions still list all of them. `SparkContext.listFiles`, 
`SparkContext.listJars` and `SparkContext.listArchives` are unchanged.
   ```
   
   **Verification:**
   - **Inspection:** Read the migration-guide entry and the SessionResources 
comment against how Spark sets spark.sql.artifact.isolation.enabled, and 
confirm that both name the affected sessions by that setting. Three kinds of 
session must fall among the scoped ones: a Scala or Java session whose Hive 
catalog comes from the SparkConf rather than its builder, a Spark Connect 
server with a Hive catalog, and a PySpark session over a SparkContext created 
in the JVM. spark-shell sessions with or without Hive, PySpark sessions whose 
SparkContext PySpark created, and Scala and Java sessions whose builder enables 
Hive support must fall among the unchanged ones.



##########
sql/core/src/test/scala/org/apache/spark/sql/artifact/ArtifactManagerSuite.scala:
##########
@@ -398,6 +399,68 @@ class ArtifactManagerSuite extends SharedSparkSession {
     assert(ArtifactManager.artifactRootDirectory.toFile.exists())
   }
 
+  test("SPARK-61671: LIST FILES, JARS and ARCHIVES list only the artifacts of 
the session") {
+    val session1 = spark.newSession()
+    val session2 = spark.newSession()
+    val sc = spark.sparkContext
+    val dir = Utils.createTempDir().toPath
+    // A zip file, which is also a valid jar and archive.
+    def newFile(name: String): Path = {
+      val path = dir.resolve(name)
+      Utils.tryWithResource(new ZipOutputStream(Files.newOutputStream(path))) 
{ out =>
+        out.putNextEntry(new ZipEntry("my_file.txt"))
+        out.write("listed".getBytes(StandardCharsets.UTF_8))
+      }
+      path
+    }
+    // The paths of the artifacts of a session under the URI of the file 
server, which differs
+    // between runs, and the names of the other ones.
+    def list(session: SparkSession, kind: String): Seq[String] =
+      session.sql(s"LIST $kind").collect().map { row =>
+        val uri = row.getString(0)
+        val i = uri.indexOf("/artifacts/")
+        if (i >= 0) uri.substring(i) else uri.substring(uri.lastIndexOf('/'))
+      }.sorted.toSeq
+
+    // Added to the SparkContext outside of any session, as with --jars, 
--files and --archives.
+    val contextFile = newFile("context.txt").toString
+    val contextJar = newFile("context.jar").toString
+    val contextArchive = newFile("context.zip").toString
+    val contextKeys = Seq(sc.addedFiles, sc.addedJars, sc.addedArchives).map { 
added =>
+      added.get("default").map(_.keySet.toSet).getOrElse(Set.empty)
+    }
+    sc.addFile(contextFile)

Review Comment:
   **Nit (P3):** In this test, session1 never adds the context file, jar or 
archive registered here, so no URI is recorded both under session1's UUID and 
under `default`. That is the only case that reaches the `.distinct` in 
`SessionResources.list` (`resources.scala:79`). From reading the code, deleting 
that call would not fail any new Scala or Python assertion. Yet without it, a 
session that adds a resource from `--files`, `--jars` or `--archives`, or one 
added with `SparkContext.addFile`, again with `ADD FILE`, `ADD JAR` or `ADD 
ARCHIVE` would list it twice, because `SparkContext` keys the same path the 
same way under both keys. The base branch could not list duplicates, since 
`SparkContext.listFiles()` merges the maps with `toMap`. Letting session1 also 
run `ADD FILE`, `ADD JAR` and `ADD ARCHIVE` on `contextFile`, `contextJar` and 
`contextArchive`, and asserting that each is listed once, including through 
`LIST JAR context.jar` and `LIST ARCHIVE context.zip`, would cover it.
   
   **Verification:**
   - **Regression:** Use an isolated session that adds, with ADD FILE, ADD JAR 
and ADD ARCHIVE, the same file, jar and archive that were added to the 
SparkContext outside any session. Each of the three listings, and LIST JAR and 
LIST ARCHIVE filtered by name, must return that resource exactly once, and the 
assertion must fail when the deduplication of entries under both keys is 
removed.



##########
sql/core/src/test/scala/org/apache/spark/sql/artifact/ArtifactManagerSuite.scala:
##########
@@ -398,6 +399,68 @@ class ArtifactManagerSuite extends SharedSparkSession {
     assert(ArtifactManager.artifactRootDirectory.toFile.exists())
   }
 
+  test("SPARK-61671: LIST FILES, JARS and ARCHIVES list only the artifacts of 
the session") {

Review Comment:
   **Nit (P3):** Since the second commit, sessions also list what was added to 
the `SparkContext` outside any session, and this test asserts that: session2, 
which adds nothing, lists `/context.txt`, `/context.jar` and `/context.zip`. 
The name still states the first commit's contract, so a maintainer who reads a 
failure or extends the test gets the wrong rule. The comment `A session lists 
only its own files and archives, and can add the same ones.` in 
`python/pyspark/sql/tests/connect/client/test_artifact.py:219` states the same 
old contract and needs the same rewording.
   
   ```suggestion
     test("SPARK-61671: LIST FILES, JARS and ARCHIVES list the artifacts of the 
session and of " +
       "the SparkContext but not those of other sessions") {
   ```
   
   **Verification:**
   - **Inspection:** Confirm that neither the SPARK-61671 test name nor the 
Spark Connect test comment still says that a session lists only its own 
artifacts, and that both agree with the assertions that sessions also list the 
resources added outside any session.



##########
python/pyspark/sql/session.py:
##########
@@ -2345,6 +2345,76 @@ def addArtifacts(
 
     addArtifact = addArtifacts
 
+    def listFiles(self) -> List[str]:
+        """
+        Returns the paths of the files added to resources, as 
:attr:`SparkContext.listFiles`.
+
+        These are the files added with :meth:`SparkSession.addArtifacts` with 
``file`` or
+        ``pyfile`` set, or with the ``ADD FILE`` SQL statement, and those 
added to the
+        :class:`SparkContext`, such as with ``--files``. Without Spark 
Connect, these are all the
+        files added to the :class:`SparkContext`, also by other sessions. With 
Spark Connect, these
+        are the files added to this session and those added to the server 
outside of any session,
+        but not those of the other sessions, which servers before Spark 4.4 
also list. A file
+        uploaded with :meth:`SparkSession.addArtifacts` is listed as the URI 
of its copy on the
+        server, and one added with ``ADD FILE`` as 
:attr:`SparkContext.listFiles` lists it, such as
+        by the path it was added with when the server runs in local mode.
+
+        .. versionadded:: 4.4.0
+
+        Returns
+        -------
+        list of str
+            The paths of the files, in no particular order.
+
+        See Also
+        --------
+        :meth:`SparkSession.addArtifacts`
+        :meth:`SparkSession.listArchives`
+
+        Examples
+        --------
+        >>> spark.addArtifacts("/tmp/my_file.txt", file=True)  # doctest: +SKIP
+        >>> spark.listFiles()  # doctest: +SKIP
+        ['file:/tmp/my_file.txt']

Review Comment:
   **Nit (P3):** The Spark Connect methods reuse this docstring 
(`connect/session.py:1179`, and `:1184` for `listArchives`). With Spark 
Connect, `addArtifacts` uploads the file, and `listFiles()` returns the URI of 
the server's copy, such as 
`spark://<host>:<port>/artifacts/<session-uuid>/files/my_file.txt`, as the 
prose above says. `file:/tmp/my_file.txt` is what Spark Classic returns only in 
local mode; outside local mode it returns the driver file server's URI. So a 
check modeled on this example, such as `'file:/tmp/my_file.txt' in 
spark.listFiles()`, would be `False` on Spark Connect, the audience these 
methods were added for. The `listArchives` example at line 2414 has the same 
problem. Labeling each output with the mode that returns it, for example 
keeping this line as Spark Classic local-mode output and adding the Spark 
Connect URI form, would make the examples right for both readers. Showing only 
the `spark://` form without a label would mislead Classic users instead.
   
   **Verification:**
   - **Inspection:** Check the listFiles and listArchives documentation for 
both Spark Classic and Spark Connect. Each example output must be labeled with 
the mode that returns it unless both modes return it, a Spark Connect output 
must show the URI of the server's copy and a Spark Classic local-mode output 
the path the file or archive was added with, and the examples must remain 
skipped by doctest.



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