spark-test commented on code in PR #59640:
URL: https://github.com/apache/spark/pull/59640#discussion_r4488443641
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/TypeUtils.scala:
##########
@@ -162,4 +165,124 @@ object TypeUtils extends QueryErrorsBase {
messageParameters = scala.collection.immutable.Map.empty)
}
}
+
+ private def containsUnknownFileType(dataType: DataType): Boolean = {
+ dataType.existsRecursively {
+ case ft: FileType => ft.mode == FileTypeMode.UNKNOWN
+ case _ => false
+ }
+ }
+
+ /**
+ * Fails if a FILE in `dataType`, at any nesting depth, has no qualifier, as
a FILE in a table
+ * column definition must be declared `FILE EXTERNAL`.
+ */
+ def checkFileTypeHasQualifier(dataType: DataType): Unit = {
+ if (containsUnknownFileType(dataType)) {
+ throw QueryCompilationErrors.fileTypeMissingQualifierError()
+ }
+ }
+
+ /**
+ * Fails if any of `columns`, which a write such as CREATE TABLE AS SELECT
stores in a table,
+ * holds a FILE without a qualifier, as a table cannot store one.
+ */
+ def checkNoUnknownFileTypeWrite(columns: Seq[Attribute]): Unit = {
+ checkNoUnknownFileTypeInColumns(columns.map(c => Seq(c.name) ->
c.dataType))
+ }
+
+ /**
+ * Fails if a column of `schema`, which a command such as CREATE TABLE LIKE
stores in a new
+ * table, holds a FILE without a qualifier.
+ */
+ def checkNoUnknownFileTypeInTableSchema(schema: StructType): Unit = {
+ checkNoUnknownFileTypeInColumns(schema.fields.toSeq.map(f => Seq(f.name)
-> f.dataType))
+ }
+
+ /**
+ * Fails if any of `columns`, given as the path of a column and the type it
would be stored
+ * with, holds a FILE without a qualifier.
+ */
+ def checkNoUnknownFileTypeInColumns(columns: Seq[(Seq[String], DataType)]):
Unit = {
+ val unknownCols = columns.collect {
+ case (path, dataType) if containsUnknownFileType(dataType) => path
+ }
+ if (unknownCols.nonEmpty) {
+ throw QueryCompilationErrors.fileTypeUnknownWriteError(unknownCols)
+ }
+ }
+
+ /**
+ * Fails if `field` holds a FILE, as FILE is not comparable and so cannot be
a partition column
+ * (`usage` is `PARTITION_COLUMN`), a clustering column
(`CLUSTERING_COLUMN`) or a write-ordering
+ * column (`WRITE_ORDERING_COLUMN`).
+ */
+ def checkNoFileTypeInColumnUsage(field: StructField, usage: String): Unit = {
+ if (field.dataType.existsRecursively(_.isInstanceOf[FileType])) {
+ throw QueryCompilationErrors.fileTypeUnsupportedColumnUsageError(field,
usage)
+ }
+ }
+
+ /** Fails if a clustering column of `clusterBySpec` holds a FILE. */
+ def checkNoFileTypeClusteringColumn(
+ schema: StructType,
+ clusterBySpec: ClusterBySpec,
+ resolver: Resolver): Unit = {
+ clusterBySpec.columnNames.foreach { ref =>
+ schema.findNestedField(ref.fieldNames.toImmutableArraySeq, resolver =
resolver)
Review Comment:
**Non-blocking (P2):** This lookup runs for every CLUSTER BY, with
`spark.sql.fileType.enabled` on or off and whether or not the table holds a
FILE. With its default `includeCollections = false`, `findNestedField` throws
`INVALID_FIELD_NAME` for a path through a non-struct field, and
`AMBIGUOUS_COLUMN_OR_FIELD` when several fields match the resolver. The
clustering normalizer these statements already go through
(`ClusterBySpec.normalizeClusterBySpec` via `SchemaUtils.findColumnPosition`)
accepts a path into an `ARRAY<STRUCT>` and takes the first match. So on a table
without any FILE, these statements succeed on the base branch and now fail at
analysis, even with the flag off:
```sql
CREATE TABLE t (id INT, arr ARRAY<STRUCT<x: INT>>) USING parquet CLUSTER BY
(arr.x);
ALTER TABLE t CLUSTER BY (arr.x);
```
The same holds for V1 CTAS,
`DataFrameWriter.clusterBy("arr.x").saveAsTable`, and `ALTER TABLE ... CLUSTER
BY` on a V2 table, which the base branch leaves to the catalog's
`applyClusterByChanges`. V2 `CREATE TABLE` is not affected, because its
existing reference check already rejects such paths. This contradicts the
description's statement that nothing changes while the FILE type is disabled.
Returning early unless `schema.existsRecursively(_.isInstanceOf[FileType])`
would keep schemas without a FILE exactly as before. For schemas that do hold a
FILE, resolving the path the way `normalizeClusterBySpec` does, descending into
`ARRAY<STRUCT>`, and skipping a path it cannot resolve would still reject a
FILE inside an array element. Invalid references would keep their existing
error.
**Verification:**
- **Regression:** With the FILE flag off and on, CREATE TABLE ... USING
parquet CLUSTER BY (arr.x), the CTAS form, and ALTER TABLE ... CLUSTER BY
(arr.x) on V1 and V2 tables whose arr is ARRAY<STRUCT<x: INT>> succeed as on
the base branch.
- **Behavior:** A FILE EXTERNAL clustering column is rejected with
FILE_TYPE_UNSUPPORTED_COLUMN_USAGE.CLUSTERING_COLUMN in CREATE TABLE, CTAS and
ALTER TABLE ... CLUSTER BY for V1 and V2 tables when it is top-level or in a
struct, and in V1 CREATE TABLE and CTAS and V1 and V2 ALTER TABLE ... CLUSTER
BY when it is a field of an ARRAY<STRUCT> element.
- **Compatibility:** Clustering by an unknown column, or by a path through a
non-struct field, reports the same error as on the base branch.
##########
sql/api/src/main/scala/org/apache/spark/sql/types/FileType.scala:
##########
@@ -25,30 +25,33 @@ import org.apache.spark.annotation.Unstable
/**
* The data type representing a reference to a file, with metadata describing
the file.
*
- * In SQL the type is named `FILE`, and the `EXTERNAL` keyword is planned to
be required when
- * declaring a table column, as in `CREATE TABLE t (f FILE EXTERNAL)`; until
then a bare `FILE` is
- * accepted wherever a type is. Its JSON representation is `"file external"`
for
- * `FileType.external` and `"file unknown"` for `FileType()`, except that an
external file in a
- * struct field is the plain `"file"`. A bare `"file"` is read as external
inside a struct field
- * and as unknown elsewhere.
+ * In SQL the type is named `FILE`. A table column must be declared with the
`EXTERNAL` keyword,
+ * as in `CREATE TABLE t (f FILE EXTERNAL)`, while the signature of a function
declares a bare
+ * `FILE`. Its JSON representation is `"file external"` for
`FileType.external` and
+ * `"file unknown"` for `FileType()`, except that an external file in a struct
field is the plain
+ * `"file"`. A bare `"file"` is read as external inside a struct field and as
unknown elsewhere.
*
* FileType is planned to be physically stored as a struct with the following
fields (see
* `FileType.FIELDS`), but it deliberately does not extend [[StructType]]:
- * - uri (STRING): the opaque URI to the file
+ * - uri (STRING): the URI of the referenced file, which may be absolute or
relative
* - offset (BIGINT): the start of the referenced byte range
- * - size (BIGINT): the size of the file in bytes
- * - content_type (STRING): the MIME/content type of the file
- * - checksum (STRING): an algorithm-tagged integrity token for the file,
e.g. "ETAG:{etag}"
+ * - size (BIGINT): the length of the referenced byte range
+ * - content_type (STRING): the MIME/content type of the referenced bytes
+ * - checksum (STRING): an algorithm-tagged integrity token for the
referenced bytes, e.g.
+ * "MD5:{digest}", or "ETAG:{etag}" for the whole file
* - inline (BINARY): the referenced bytes stored inline in the value
*
* FileType may be EXTERNAL (simple references, lifecycle independent of the
table) or UNKNOWN
* (mode not yet determined, such as the result of a cast or of a UDF). Mode
is part of type
* identity - files with different modes are distinct under `equals`.
*
- * FileType is planned to be not comparable -- it cannot be used in join
expressions, grouping
- * expressions, or as a partition/clustering column. Users can extract the uri
field for such
- * operations. This type currently only guarantees the schema-level pieces
(DDL and JSON); the
- * physical representation and most of the restrictions are added by later
parts.
+ * FileType is not comparable: it defines neither equality nor an ordering, as
it is not clear
+ * what equality of two files should mean. So an operation that needs equality
fails at analysis,
Review Comment:
**Nit (P3):** This now reads as current behavior, but two parts of it are
not true yet:
- Not every operation that needs equality fails at analysis. The aggregates
that the description leaves for later still accept FILE: `count(DISTINCT f)`,
`collect_set(f)`, `approx_count_distinct(f)` and `mode(f)`.
`approx_count_distinct` hashes its input, so "hashing" overstates it as well.
- `f.uri` does not work yet. FileType is not a `StructType` and
`ExtractValue` has no case for it, so the extraction fails with the
unsupported-extraction error.
As this is the published Scaladoc of a public type, it would be clearer to
list the operations that are rejected today and name the aggregates that are
not rejected yet. It could then describe `uri` extraction as planned, together
with the physical representation.
This extends existing discussions
[1](https://github.com/apache/spark/pull/59640#issuecomment-6620602263),
[2](https://github.com/apache/spark/pull/59640#pullrequestreview-5760546015).
**Verification:**
- **Inspection:** Each operation the FileType Scaladoc says is rejected
matches a check in the change or a test in the FILE type restriction tests. The
doc neither claims that deduplicating or hashing aggregates are rejected nor
that the uri field can be extracted today.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckAnalysis.scala:
##########
@@ -1202,6 +1257,28 @@ trait CheckAnalysis extends LookupCatalog with
QueryErrorsBase with PlanToString
}
}
+ /**
+ * Checks that the [[UserDefinedExpression]]s in a query declare only a
plain FILE in their
+ * return type, as
[[TypeUtils.checkNoQualifierInRegisteredRoutineReturnType]] does when a
+ * routine is registered. This covers routines whose signature is not
checked when they are
+ * created, such as UDFs that are not registered and UDAF classes registered
with
+ * `CREATE FUNCTION ... AS`. SQL functions are checked by `CREATE FUNCTION`.
V2 catalog functions
+ * are covered only when they are bound as an [[ApplyFunctionExpression]]. A
non-scalar Python
+ * UDF is skipped, as its data type is the schema of the rows it returns.
+ */
+ private def checkFileTypeInUserDefinedRoutines(plan: LogicalPlan): Unit = {
+ if (SQLConf.get.isFileTypeEnabled) {
+ plan.foreach { operator =>
Review Comment:
**Nit (P3):** This walk visits every operator and expression of the whole
plan on each `checkAnalysis0` call, including sub-plans that are already
analyzed. The main loop skips those with `case p if p.analyzed =>`, and an
analyzed sub-plan already passed this same check if the flag was on when it was
analyzed. So every re-analysis over an analyzed plan repeats the work: each
step of a `withColumn` chain, a query over a Dataset-backed temp view, and each
streaming micro-batch. For every `UserDefinedExpression` it reaches,
`checkNoQualifierInRegisteredRoutineReturnType` also re-reads the flag and
builds `toSQLId(Seq(name))`, which only the error message uses, even when the
return type holds no FILE. This is driver-side analysis CPU in sessions with
the flag on, today tests and preview users. Every query would pay it once the
flag is on by default. Query results and executor work are unchanged.
This extends an [existing
discussion](https://github.com/apache/spark/pull/59640#discussion_r4353281850).
**Recommended change:** Make the UDF return-type pass skip sub-plans that
are already analyzed, the way the main CheckAnalysis loop does, or fold it into
that loop's per-operator expression traversal. Read the FILE flag once per
pass, and for each UDF check whether its return type contains a FILE before
quoting its name or running the qualifier and map-key walks.
**Why this works:** Analyzed sub-plans have already passed checkAnalysis0.
Visiting only operators that are not yet analyzed bounds each analysis to the
work the main loop does. Deferring name quoting to the error path removes the
per-UDF string work for return types that hold no FILE.
**Scope:** Limit the analysis-time UDF return-type check to operators that
are not yet analyzed, and make its per-UDF work lazy.
**Compatibility:** The errors, their parameters and the non-scalar Python
UDF exemption stay the same for routines in newly analyzed operators.
**Risks:** A sub-plan analyzed while spark.sql.fileType.enabled was off,
then reused after the flag is turned on, is no longer re-checked for UDFs whose
return type has a qualified FILE or a FILE map key. That includes unregistered
UDFs and routines registered while the flag was off, as the registration checks
are skipped while it is off. Every other FILE check in CheckAnalysis already
skips such sub-plans, and restoring the whole-plan walk reverts the change.
**Constraints:** Keep the pass gated by spark.sql.fileType.enabled, so
analysis with the flag off is unchanged. Keep the error conditions, quoted
routine names and the non-scalar Python UDF exemption unchanged.
**Exclusions:**
- The registration-time return-type checks in UDFRegistration and
UDTFRegistration are not changed.
**Success:** With the flag on, re-analyzing a plan that embeds
already-analyzed sub-plans runs the UDF return-type check only on the operators
that are not yet analyzed. Unregistered UDFs, UDAF classes registered with
CREATE FUNCTION ... AS, and UDTFs in newly analyzed operators are still
rejected with the same errors. A UDF whose return type holds no FILE no longer
has its name quoted or the flag re-read during analysis.
**Verification:**
- **Behavior:** Unregistered Scala and Python UDFs, and a UDAF class
registered by name, that return FILE EXTERNAL are still rejected at query time
with FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_QUALIFIER and a quoted routine
name.
- **Regression:** When a chain of DataFrame transformations over a plan with
UDFs is analyzed with the flag on, each step checks only the operators it adds,
which can be shown by counting checked operators or by comparing analysis time
with the flag on and off.
- **Compatibility:** With the flag off, analysis results and errors are
unchanged.
--
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]