szehon-ho commented on code in PR #57644:
URL: https://github.com/apache/spark/pull/57644#discussion_r4556469969
##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/autocdc/AutoCdcReservedNames.scala:
##########
@@ -40,4 +45,332 @@ private[pipelines] object AutoCdcReservedNames {
* Note that the schema of the CDC metadata column however can and does
differ on the SCD-type.
*/
val cdcMetadataColName: String = s"${prefix}metadata"
+
+ // A field is engine-owned when its name carries the reserved prefix.
Matching goes through the
+ // caller's `resolver` so a user-declared column is still recognized as
reserved under
+ // case-insensitive analysis, and the length guard keeps `substring` safe
for shorter names.
+ private def isReservedFieldName(name: String, resolver: Resolver): Boolean =
+ name.length >= prefix.length && resolver(name.substring(0, prefix.length),
prefix)
+
+ /** The engine-owned reserved AUTO CDC column(s) present in `schema`, if
any. */
+ private[pipelines] def reservedFields(schema: StructType, resolver:
Resolver): Seq[StructField] =
+ schema.fields.toSeq.filter(f => isReservedFieldName(f.name, resolver))
+
+ /** `schema` with the engine-owned reserved AUTO CDC column(s) removed. */
+ private[pipelines] def stripReservedFields(schema: StructType, resolver:
Resolver): StructType =
+ StructType(schema.fields.filterNot(f => isReservedFieldName(f.name,
resolver)))
+
+ /**
+ * The schema a materialized AUTO CDC target carries when the user declares
a schema: the user's
+ * columns with the engine-owned type/nullability substituted into any
declared reserved column,
+ * followed by the engine-owned reserved column(s) the declaration omitted.
`flowInferredSchema`
+ * must be flow-derived (no user-declared columns merged in), so its
reserved fields are exactly
+ * the engine-produced ones and never a user column that happens to carry
the prefix.
+ *
+ * A declared reserved field keeps its own spelling, position, and metadata
(e.g. a `COMMENT`);
+ * only its type and nullability are replaced with the engine's. That
matters on the upgrade path:
+ * an already-materialized
+ * target may carry the reserved column under a different casing (e.g. an
older definition
+ * declared it upper-cased under case-insensitive analysis), `evolveTable`
merges that existing
+ * spelling in, and this schema -- which also feeds the analysis-time read
path -- must agree with
+ * it so a downstream `SELECT *` plans against the column the target
actually has.
+ *
+ * The reserved column itself is made nullable so a target created from a
declared schema matches
+ * one created from an omitted schema (that path materializes the inferred
schema `asNullable`),
+ * avoiding a spurious nullability diff when the column declaration is added
or removed. That
+ * deliberately overrides a top-level `NOT NULL` a declaration might place
on the engine-owned
+ * reserved column; parity between the declared and omitted paths is what
the omit-the-column
+ * capability rests on, and the column is engine-written bookkeeping the
user does not populate.
+ * Its nested nullability is the union of the declaration's and the
engine's: forcing
+ * a declared nested `NOT NULL` sequencing field nullable would churn an
unchanged, already
+ * materialized target, and `evolveTable` cannot apply a nullability change
beneath nested arrays
+ * (`diffSchemas` rejects it as an unsupported nested-complex-type
evolution). Omitted (appended)
+ * fields stay fully nullable, matching the omitted-schema path.
+ */
+ private[pipelines] def appendEngineOwnedReservedFields(
+ declaredSchema: StructType,
+ flowInferredSchema: StructType,
+ resolver: Resolver): StructType = {
+ // Engine-owned reserved fields in the engine's actual inferred
nullability (not blanket
+ // `asNullable`). A declared reserved field reconciles against these, so
its nested nullability
+ // follows what the engine writes and an unchanged declaration does not
churn the target.
+ // Omitted fields are made nullable where they are appended below.
+ val engineReserved = StructType(reservedFields(flowInferredSchema,
resolver)).fields
+
+ // A declaration carries at most one field matching each engine-owned
reserved column. In both
+ // contexts the declaration is validated first -- at materialization by
+ // GraphValidations.validateUserSpecifiedSchemas before DatasetManager
materializes, and on the
+ // same-graph read path by VirtualTableInput.load just before it calls
this method -- and
+ // `validateDeclaredReservedFields` rejects a case-insensitive duplicate,
so this guard is
+ // defense-in-depth.
+ engineReserved.foreach { ef =>
+ val matches = declaredSchema.fields.filter(df => resolver(df.name,
ef.name))
+ if (matches.length > 1) {
+ throw SparkException.internalError(
+ s"Ambiguous reserved AUTO CDC field:
${matches.map(_.name).mkString(", ")} all match " +
+ s"the engine-owned column ${ef.name}.")
+ }
+ }
+
+ // Rebuild the declared schema in place: a declared reserved field keeps
its spelling and
+ // position but takes the engine-owned type/nullability. Both contexts
validate the
+ // declaration first (see the duplicate guard above), rejecting a
reserved-prefixed field with
+ // no engine counterpart, so `case None => df` is defense-in-depth.
+ val usedEngineNames = scala.collection.mutable.Set.empty[String]
+ val rebuilt = declaredSchema.fields.map { df =>
+ if (isReservedFieldName(df.name, resolver)) {
+ engineReserved.find(ef => resolver(df.name, ef.name)) match {
+ case Some(ef) =>
+ usedEngineNames += ef.name
+ // Force the reserved column itself nullable to match the
omitted-declaration path, so
+ // adding or removing the declaration is not a top-level
nullability change. Nested
+ // fields follow the union below (not the omitted path's blanket
nullable), so parity
+ // holds only at the reserved column itself.
+ reconcileReservedField(df, ef.copy(nullable = true), resolver)
+ case None => df
+ }
+ } else {
+ df
+ }
+ }
+
+ // Append engine-owned reserved fields the declaration omitted, in
canonical form and fully
+ // nullable to match the no-declaration path (DatasetManager materializes
the inferred schema
+ // `asNullable`).
+ val appended =
+ StructType(engineReserved.filterNot(ef =>
usedEngineNames.contains(ef.name)))
+ .asNullable.fields
+ StructType(rebuilt ++ appended)
+ }
+
+ /**
+ * Reject a declared AUTO CDC target schema whose reserved metadata
column(s) are shaped in a way
+ * reconciliation cannot honor, so `appendEngineOwnedReservedFields` and the
casing-drift check
+ * can assume a well-formed declaration instead of a guard elsewhere. Both
callers that
+ * reconcile run this first: `GraphValidations.validateUserSpecifiedSchemas`
before
+ * materialization, and
+ * `VirtualTableInput.load` on the same-graph read path, which runs during
flow analysis -- before
+ * graph validation -- and so must validate the declaration itself rather
than rely on that later
+ * pass. Recursively through structs and array-of-struct elements it throws
a user-facing
+ * `AnalysisException` when a declared reserved-prefixed field has no
engine-owned counterpart (a
+ * typo or an extra reserved-namespace column), when two declared fields
resolve to one engine
+ * field, or when a declared nested field under a reserved column is not one
the engine produces.
+ */
+ private[pipelines] def validateDeclaredReservedFields(
+ tableName: String,
+ declaredSchema: StructType,
+ flowInferredSchema: StructType,
+ resolver: Resolver): Unit =
+ validateReservedLevel(
+ tableName,
+ reservedColumn = None,
+ reservedFields(declaredSchema, resolver),
+ reservedFields(flowInferredSchema, resolver),
+ resolver)
+
+ // Validate one level of reserved fields against the engine's.
`reservedColumn` is the enclosing
+ // reserved column's (possibly dotted) name for nested-field messages, None
at the top level. At
+ // the top level `declared`/`engine` are the reserved-prefixed columns;
within a reserved struct
+ // every field is engine-owned, so the recursion passes all of a matched
struct's fields.
+ private def validateReservedLevel(
+ tableName: String,
+ reservedColumn: Option[String],
+ declared: Seq[StructField],
+ engine: Seq[StructField],
+ resolver: Resolver): Unit = {
+ declared.filterNot(df => engine.exists(ef => resolver(df.name,
ef.name))).foreach { df =>
+ reservedColumn match {
+ case None =>
+ throw new AnalysisException(
+ "AUTOCDC_INVALID_RESERVED_SCHEMA.UNKNOWN_COLUMN",
+ Map("tableName" -> tableName, "columnName" -> df.name,
+ "reservedColumnNamePrefix" -> prefix))
+ case Some(col) =>
+ throw new AnalysisException(
+ "AUTOCDC_INVALID_RESERVED_SCHEMA.UNKNOWN_NESTED_FIELD",
+ Map("tableName" -> tableName, "reservedColumnName" -> col,
"fieldName" -> df.name))
+ }
+ }
+ engine.foreach { ef =>
+ val matches = declared.filter(df => resolver(df.name, ef.name))
+ if (matches.length > 1) {
+ val names = matches.map(f => s"`${f.name}`").mkString(", ")
+ reservedColumn match {
+ case None =>
+ throw new AnalysisException(
+ "AUTOCDC_INVALID_RESERVED_SCHEMA.DUPLICATE_COLUMN",
+ Map("tableName" -> tableName, "columnNames" -> names,
"engineColumnName" -> ef.name))
+ case Some(col) =>
+ throw new AnalysisException(
+ "AUTOCDC_INVALID_RESERVED_SCHEMA.DUPLICATE_NESTED_FIELD",
+ Map("tableName" -> tableName, "reservedColumnName" -> col,
"fieldNames" -> names,
+ "engineFieldName" -> ef.name))
+ }
+ }
+ }
+ declared.foreach { df =>
+ engine.find(ef => resolver(df.name, ef.name)).foreach { ef =>
+ val col = Some(reservedColumn.map(c =>
s"$c.${df.name}").getOrElse(df.name))
+ validateReservedType(tableName, col, df.dataType, ef.dataType,
resolver)
+ }
+ }
+ }
+
+ // Descend a matched reserved field's type to validate its nested fields: a
struct checks its
+ // fields one level down, and an array recurses into its element type so the
struct inside an
+ // arbitrarily nested sequencing type (e.g. `ARRAY<ARRAY<STRUCT<...>>>`) is
still reached. This
+ // mirrors how `reconcileReservedType` descends, so validation rejects
exactly the nested shapes
+ // reconciliation would otherwise carry into the target. Any other type has
no reserved nested
+ // field to check.
+ private def validateReservedType(
+ tableName: String,
+ reservedColumn: Option[String],
+ declared: DataType,
+ engine: DataType,
+ resolver: Resolver): Unit =
+ (declared, engine) match {
+ case (ds: StructType, es: StructType) =>
+ validateReservedLevel(tableName, reservedColumn, ds.fields.toSeq,
es.fields.toSeq, resolver)
+ case (da: ArrayType, ea: ArrayType) =>
+ validateReservedType(tableName, reservedColumn, da.elementType,
ea.elementType, resolver)
+ case _ =>
+ }
+
+ /**
+ * Reconcile a declared reserved field against its engine-owned counterpart:
keep the declared
+ * field's spelling and its metadata (e.g. a user `COMMENT`), take the
engine field's type and the
+ * union of the declared and engine nullability, and reconcile the types
recursively (see
+ * `reconcileReservedType`) so declared nested spelling survives through
structs and arrays.
+ * Building from the declared field is what keeps the comment:
`SchemaInferenceUtils` merges the
+ * declaration in to carry such metadata, and dropping it here would lose it
from the created
+ * target and the analysis-time read path.
+ */
+ private def reconcileReservedField(
+ declared: StructField,
+ engine: StructField,
+ resolver: Resolver): StructField =
+ declared.copy(
+ dataType = reconcileReservedType(declared.dataType, engine.dataType,
resolver),
+ // Union so a declared `NOT NULL` the engine also produces is preserved
(an unchanged target
+ // does not churn), while a field the engine may null is widened to
nullable.
+ nullable = declared.nullable || engine.nullable)
+
+ /**
+ * Reconcile a declared data type against its engine-owned counterpart: keep
the declared nested
+ * spelling and the engine's field ordering and types, and union the
declared and engine
+ * nullability (`containsNull` for arrays). Recurse through structs -- the
AUTO CDC metadata
+ * column is one -- and through array element types, since a sequencing
column can be
+ * `ARRAY<STRUCT<...>>`; any other shape takes the engine's type as-is.
+ */
+ private def reconcileReservedType(
+ declared: DataType,
+ engine: DataType,
+ resolver: Resolver): DataType =
+ (declared, engine) match {
+ case (declaredStruct: StructType, engineStruct: StructType) =>
+ reconcileReservedStruct(declaredStruct, engineStruct, resolver)
+ case (declaredArray: ArrayType, engineArray: ArrayType) =>
+ engineArray.copy(
+ elementType =
+ reconcileReservedType(declaredArray.elementType,
engineArray.elementType, resolver),
+ // Union `containsNull` for the same reason as field nullability:
keep a declared
+ // non-nullable element the engine also produces so an unchanged
target does not churn.
+ containsNull = declaredArray.containsNull ||
engineArray.containsNull)
+ case _ => engine
Review Comment:
Could we recurse through `MapType` here, and in `validateReservedType` /
`typeCasingDrifts`, as well? SCD1 metadata now contains `__VERSION_MAP:
MAP<STRING, sequencingType>`. For a case-insensitive flow with a struct
sequencing type, a declaration whose map value spells a field `ORDINAL` is
accepted, but this fallback replaces the whole map with the engine's `ordinal`;
a case-sensitive same-graph reader referencing `.ORDINAL` then fails analysis.
On an existing target, the drift checker also stops at the map and misses the
persisted-vs-planned casing difference. `StructType.merge` already recurses
through map keys and values, so these three helpers should
preserve/validate/check them too.
##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/autocdc/AutoCdcReservedNames.scala:
##########
@@ -40,4 +45,332 @@ private[pipelines] object AutoCdcReservedNames {
* Note that the schema of the CDC metadata column however can and does
differ on the SCD-type.
*/
val cdcMetadataColName: String = s"${prefix}metadata"
+
+ // A field is engine-owned when its name carries the reserved prefix.
Matching goes through the
+ // caller's `resolver` so a user-declared column is still recognized as
reserved under
+ // case-insensitive analysis, and the length guard keeps `substring` safe
for shorter names.
+ private def isReservedFieldName(name: String, resolver: Resolver): Boolean =
+ name.length >= prefix.length && resolver(name.substring(0, prefix.length),
prefix)
+
+ /** The engine-owned reserved AUTO CDC column(s) present in `schema`, if
any. */
+ private[pipelines] def reservedFields(schema: StructType, resolver:
Resolver): Seq[StructField] =
+ schema.fields.toSeq.filter(f => isReservedFieldName(f.name, resolver))
+
+ /** `schema` with the engine-owned reserved AUTO CDC column(s) removed. */
+ private[pipelines] def stripReservedFields(schema: StructType, resolver:
Resolver): StructType =
+ StructType(schema.fields.filterNot(f => isReservedFieldName(f.name,
resolver)))
+
+ /**
+ * The schema a materialized AUTO CDC target carries when the user declares
a schema: the user's
+ * columns with the engine-owned type/nullability substituted into any
declared reserved column,
+ * followed by the engine-owned reserved column(s) the declaration omitted.
`flowInferredSchema`
+ * must be flow-derived (no user-declared columns merged in), so its
reserved fields are exactly
+ * the engine-produced ones and never a user column that happens to carry
the prefix.
+ *
+ * A declared reserved field keeps its own spelling, position, and metadata
(e.g. a `COMMENT`);
+ * only its type and nullability are replaced with the engine's. That
matters on the upgrade path:
+ * an already-materialized
+ * target may carry the reserved column under a different casing (e.g. an
older definition
+ * declared it upper-cased under case-insensitive analysis), `evolveTable`
merges that existing
+ * spelling in, and this schema -- which also feeds the analysis-time read
path -- must agree with
+ * it so a downstream `SELECT *` plans against the column the target
actually has.
+ *
+ * The reserved column itself is made nullable so a target created from a
declared schema matches
+ * one created from an omitted schema (that path materializes the inferred
schema `asNullable`),
+ * avoiding a spurious nullability diff when the column declaration is added
or removed. That
+ * deliberately overrides a top-level `NOT NULL` a declaration might place
on the engine-owned
+ * reserved column; parity between the declared and omitted paths is what
the omit-the-column
+ * capability rests on, and the column is engine-written bookkeeping the
user does not populate.
+ * Its nested nullability is the union of the declaration's and the
engine's: forcing
+ * a declared nested `NOT NULL` sequencing field nullable would churn an
unchanged, already
+ * materialized target, and `evolveTable` cannot apply a nullability change
beneath nested arrays
+ * (`diffSchemas` rejects it as an unsupported nested-complex-type
evolution). Omitted (appended)
+ * fields stay fully nullable, matching the omitted-schema path.
+ */
+ private[pipelines] def appendEngineOwnedReservedFields(
+ declaredSchema: StructType,
+ flowInferredSchema: StructType,
+ resolver: Resolver): StructType = {
+ // Engine-owned reserved fields in the engine's actual inferred
nullability (not blanket
+ // `asNullable`). A declared reserved field reconciles against these, so
its nested nullability
+ // follows what the engine writes and an unchanged declaration does not
churn the target.
+ // Omitted fields are made nullable where they are appended below.
+ val engineReserved = StructType(reservedFields(flowInferredSchema,
resolver)).fields
+
+ // A declaration carries at most one field matching each engine-owned
reserved column. In both
+ // contexts the declaration is validated first -- at materialization by
+ // GraphValidations.validateUserSpecifiedSchemas before DatasetManager
materializes, and on the
+ // same-graph read path by VirtualTableInput.load just before it calls
this method -- and
+ // `validateDeclaredReservedFields` rejects a case-insensitive duplicate,
so this guard is
+ // defense-in-depth.
+ engineReserved.foreach { ef =>
+ val matches = declaredSchema.fields.filter(df => resolver(df.name,
ef.name))
+ if (matches.length > 1) {
+ throw SparkException.internalError(
+ s"Ambiguous reserved AUTO CDC field:
${matches.map(_.name).mkString(", ")} all match " +
+ s"the engine-owned column ${ef.name}.")
+ }
+ }
+
+ // Rebuild the declared schema in place: a declared reserved field keeps
its spelling and
+ // position but takes the engine-owned type/nullability. Both contexts
validate the
+ // declaration first (see the duplicate guard above), rejecting a
reserved-prefixed field with
+ // no engine counterpart, so `case None => df` is defense-in-depth.
+ val usedEngineNames = scala.collection.mutable.Set.empty[String]
+ val rebuilt = declaredSchema.fields.map { df =>
+ if (isReservedFieldName(df.name, resolver)) {
+ engineReserved.find(ef => resolver(df.name, ef.name)) match {
+ case Some(ef) =>
+ usedEngineNames += ef.name
+ // Force the reserved column itself nullable to match the
omitted-declaration path, so
+ // adding or removing the declaration is not a top-level
nullability change. Nested
+ // fields follow the union below (not the omitted path's blanket
nullable), so parity
+ // holds only at the reserved column itself.
+ reconcileReservedField(df, ef.copy(nullable = true), resolver)
+ case None => df
+ }
+ } else {
+ df
+ }
+ }
+
+ // Append engine-owned reserved fields the declaration omitted, in
canonical form and fully
+ // nullable to match the no-declaration path (DatasetManager materializes
the inferred schema
+ // `asNullable`).
+ val appended =
+ StructType(engineReserved.filterNot(ef =>
usedEngineNames.contains(ef.name)))
+ .asNullable.fields
+ StructType(rebuilt ++ appended)
+ }
+
+ /**
+ * Reject a declared AUTO CDC target schema whose reserved metadata
column(s) are shaped in a way
+ * reconciliation cannot honor, so `appendEngineOwnedReservedFields` and the
casing-drift check
+ * can assume a well-formed declaration instead of a guard elsewhere. Both
callers that
+ * reconcile run this first: `GraphValidations.validateUserSpecifiedSchemas`
before
+ * materialization, and
+ * `VirtualTableInput.load` on the same-graph read path, which runs during
flow analysis -- before
+ * graph validation -- and so must validate the declaration itself rather
than rely on that later
+ * pass. Recursively through structs and array-of-struct elements it throws
a user-facing
+ * `AnalysisException` when a declared reserved-prefixed field has no
engine-owned counterpart (a
+ * typo or an extra reserved-namespace column), when two declared fields
resolve to one engine
+ * field, or when a declared nested field under a reserved column is not one
the engine produces.
+ */
+ private[pipelines] def validateDeclaredReservedFields(
+ tableName: String,
+ declaredSchema: StructType,
+ flowInferredSchema: StructType,
+ resolver: Resolver): Unit =
+ validateReservedLevel(
+ tableName,
+ reservedColumn = None,
+ reservedFields(declaredSchema, resolver),
+ reservedFields(flowInferredSchema, resolver),
+ resolver)
+
+ // Validate one level of reserved fields against the engine's.
`reservedColumn` is the enclosing
+ // reserved column's (possibly dotted) name for nested-field messages, None
at the top level. At
+ // the top level `declared`/`engine` are the reserved-prefixed columns;
within a reserved struct
+ // every field is engine-owned, so the recursion passes all of a matched
struct's fields.
+ private def validateReservedLevel(
+ tableName: String,
+ reservedColumn: Option[String],
+ declared: Seq[StructField],
+ engine: Seq[StructField],
+ resolver: Resolver): Unit = {
+ declared.filterNot(df => engine.exists(ef => resolver(df.name,
ef.name))).foreach { df =>
+ reservedColumn match {
+ case None =>
+ throw new AnalysisException(
+ "AUTOCDC_INVALID_RESERVED_SCHEMA.UNKNOWN_COLUMN",
+ Map("tableName" -> tableName, "columnName" -> df.name,
+ "reservedColumnNamePrefix" -> prefix))
+ case Some(col) =>
+ throw new AnalysisException(
+ "AUTOCDC_INVALID_RESERVED_SCHEMA.UNKNOWN_NESTED_FIELD",
+ Map("tableName" -> tableName, "reservedColumnName" -> col,
"fieldName" -> df.name))
+ }
+ }
+ engine.foreach { ef =>
+ val matches = declared.filter(df => resolver(df.name, ef.name))
+ if (matches.length > 1) {
+ val names = matches.map(f => s"`${f.name}`").mkString(", ")
+ reservedColumn match {
+ case None =>
+ throw new AnalysisException(
+ "AUTOCDC_INVALID_RESERVED_SCHEMA.DUPLICATE_COLUMN",
+ Map("tableName" -> tableName, "columnNames" -> names,
"engineColumnName" -> ef.name))
+ case Some(col) =>
+ throw new AnalysisException(
+ "AUTOCDC_INVALID_RESERVED_SCHEMA.DUPLICATE_NESTED_FIELD",
+ Map("tableName" -> tableName, "reservedColumnName" -> col,
"fieldNames" -> names,
+ "engineFieldName" -> ef.name))
+ }
+ }
+ }
+ declared.foreach { df =>
+ engine.find(ef => resolver(df.name, ef.name)).foreach { ef =>
+ val col = Some(reservedColumn.map(c =>
s"$c.${df.name}").getOrElse(df.name))
+ validateReservedType(tableName, col, df.dataType, ef.dataType,
resolver)
+ }
+ }
+ }
+
+ // Descend a matched reserved field's type to validate its nested fields: a
struct checks its
+ // fields one level down, and an array recurses into its element type so the
struct inside an
+ // arbitrarily nested sequencing type (e.g. `ARRAY<ARRAY<STRUCT<...>>>`) is
still reached. This
+ // mirrors how `reconcileReservedType` descends, so validation rejects
exactly the nested shapes
+ // reconciliation would otherwise carry into the target. Any other type has
no reserved nested
+ // field to check.
+ private def validateReservedType(
+ tableName: String,
+ reservedColumn: Option[String],
+ declared: DataType,
+ engine: DataType,
+ resolver: Resolver): Unit =
+ (declared, engine) match {
+ case (ds: StructType, es: StructType) =>
+ validateReservedLevel(tableName, reservedColumn, ds.fields.toSeq,
es.fields.toSeq, resolver)
+ case (da: ArrayType, ea: ArrayType) =>
+ validateReservedType(tableName, reservedColumn, da.elementType,
ea.elementType, resolver)
+ case _ =>
+ }
+
+ /**
+ * Reconcile a declared reserved field against its engine-owned counterpart:
keep the declared
+ * field's spelling and its metadata (e.g. a user `COMMENT`), take the
engine field's type and the
+ * union of the declared and engine nullability, and reconcile the types
recursively (see
+ * `reconcileReservedType`) so declared nested spelling survives through
structs and arrays.
+ * Building from the declared field is what keeps the comment:
`SchemaInferenceUtils` merges the
+ * declaration in to carry such metadata, and dropping it here would lose it
from the created
+ * target and the analysis-time read path.
+ */
+ private def reconcileReservedField(
+ declared: StructField,
+ engine: StructField,
+ resolver: Resolver): StructField =
+ declared.copy(
+ dataType = reconcileReservedType(declared.dataType, engine.dataType,
resolver),
+ // Union so a declared `NOT NULL` the engine also produces is preserved
(an unchanged target
+ // does not churn), while a field the engine may null is widened to
nullable.
+ nullable = declared.nullable || engine.nullable)
+
+ /**
+ * Reconcile a declared data type against its engine-owned counterpart: keep
the declared nested
+ * spelling and the engine's field ordering and types, and union the
declared and engine
+ * nullability (`containsNull` for arrays). Recurse through structs -- the
AUTO CDC metadata
+ * column is one -- and through array element types, since a sequencing
column can be
+ * `ARRAY<STRUCT<...>>`; any other shape takes the engine's type as-is.
+ */
+ private def reconcileReservedType(
+ declared: DataType,
+ engine: DataType,
+ resolver: Resolver): DataType =
+ (declared, engine) match {
+ case (declaredStruct: StructType, engineStruct: StructType) =>
+ reconcileReservedStruct(declaredStruct, engineStruct, resolver)
+ case (declaredArray: ArrayType, engineArray: ArrayType) =>
+ engineArray.copy(
+ elementType =
+ reconcileReservedType(declaredArray.elementType,
engineArray.elementType, resolver),
+ // Union `containsNull` for the same reason as field nullability:
keep a declared
+ // non-nullable element the engine also produces so an unchanged
target does not churn.
+ containsNull = declaredArray.containsNull ||
engineArray.containsNull)
+ case _ => engine
+ }
+
+ /**
+ * Rebuild `engine`'s struct in the engine's field order, carrying the
declared nested spelling
+ * and metadata: each engine nested field takes a matching declared field's
name and comment
+ * (recursively), and engine nested fields the declaration omitted stay in
canonical form. The
+ * order is the engine's, not the declaration's. These structs are
engine-owned, and a sequencing
+ * struct -- the type of a reserved sequencing field
(`${prefix}metadata.upsertSequence` /
+ * `deleteSequence` for SCD1, `recordStartAt` for SCD2) when `SEQUENCE BY`
yields a struct -- is
+ * compared positionally during AUTO CDC processing (struct ordering is
name-blind). A partial or
+ * reordered declaration must therefore not change the engine's field order:
the target stores the
+ * sequencing struct in that order, and a mismatch against the
engine-ordered microbatch would
+ * mis-pair the fields -- letting an older event overwrite a newer one in an
SCD1 merge, or
+ * mis-ordering the history intervals in SCD2 (SPARK-58118). A declared
nested field with no
+ * engine counterpart is rejected upstream by `validateReservedLevel`, so
the trailing
+ * `filterNot` is defense-in-depth, unreachable from a validated declaration.
+ */
+ private def reconcileReservedStruct(
+ declared: StructType,
+ engine: StructType,
+ resolver: Resolver): StructType = {
+ val usedDeclaredNames = scala.collection.mutable.Set.empty[String]
+ val rebuilt = engine.fields.map { ef =>
+ declared.fields.find(df => resolver(df.name, ef.name)) match {
+ case Some(df) =>
+ usedDeclaredNames += df.name
+ reconcileReservedField(df, ef, resolver)
+ case None => ef
Review Comment:
Should unmatched engine fields be made recursively nullable here? The
whole-reserved-column omission path applies `.asNullable`, but `case None =>
ef` retains the engine-inferred nested nullability. For example, with
sequencing type `ARRAY<ARRAY<STRUCT<ordinal: BIGINT NOT NULL>>>`, a partial
metadata declaration that lists only `deleteSequence` appends `upsertSequence`
with non-null element/leaf flags. If the next run removes the metadata
declaration, the desired schema comes through `.asNullable`; `diffSchemas` then
tries to relax those flags beneath nested arrays and fails with
`PIPELINE_NESTED_COMPLEX_TYPE_SCHEMA_EVOLUTION_UNSUPPORTED`, including on full
refresh. Making omitted nested fields nullable would keep partial and total
omission consistent.
--
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]