Sub topic 8
Choosing a schema evolution mode
This chapter assumes you can already read a stream with the cloudFiles source, set cloudFiles.schemaLocation, and know what _rescued_data holds. It covers what Auto Loader does when new columns show up in source files after the stream has started, and how to pick the mode that fits your pipeline.
The problem: sources change without warning
Files in a landing folder come from systems you don't control. An upstream team adds a coupon_code field to their JSON export, and files written after that date contain a key your table has never seen.
Auto Loader has to decide what to do with that key. It could add a column, fail the stream, or keep the value somewhere safe and carry on. The setting cloudFiles.schemaEvolutionMode chooses between these behaviors.
Schema evolution only applies when Auto Loader infers the schema. In that case it keeps a versioned record of the schema in the schemaLocation directory. On each run it compares the incoming data against the latest stored version.
The four modes
| Mode | New column appears | Stream fails? | Schema in schemaLocation changes? | Where the new data goes |
|---|---|---|---|---|
| `addNewColumns` | Added to the schema | Yes, once, then works after restart | Yes | A real column after restart |
| `rescue` | Not added | No | No | `_rescued_data` |
| `failOnNewColumns` | Not added | Yes, on every restart until you act | No | Nowhere. The file is not processed |
| `none` | Ignored | No | No | Dropped, unless you set a rescued data column explicitly |
Two defaults matter:
- If you let Auto Loader infer the schema, the default is
addNewColumns. - If you provide a full schema with
.schema(...), the default isnone, andaddNewColumnsis not allowed.
addNewColumns
When a batch contains an unknown column, the stream stops with an UnknownFieldException. Before it stops, Auto Loader writes the new schema version to schemaLocation. When you restart, the stream reads with the updated schema and the new column appears.
This mode is a good fit when upstream changes are additive and you want them to flow through. It needs something to restart the stream. A scheduled availableNow job restarts naturally on its next run. A continuous job needs retries configured in your job definition, or the stream will stay down.
Files that arrived before the column existed are not reprocessed. Rows already in the table keep NULL in the new column.
rescue
The schema never changes. A column that isn't in the schema is stored in _rescued_data, a JSON string that also records the source file path. The stream keeps running.
This mode suits pipelines that must never stop on a schema change, such as a continuous stream feeding dashboards. It also suits teams that want a human to decide before the table changes. The cost is that new data stays inside a JSON string until someone promotes it to a real column.
failOnNewColumns
The stream fails when a new column appears and keeps failing on restart. To get past it, you do one of the following:
- Update the schema, for example by adding the column through a schema hint.
- Remove the offending file from the source.
Choose it when an unexpected column means something is wrong and you want to look at it before any data moves. It is the strictest option and the one most likely to page someone.
none
The schema is fixed and unknown columns are ignored. They are not rescued unless you set rescuedDataColumn yourself. This is the default when you supply a schema. It is the quietest mode, and the easiest one to lose data in.
Choosing a mode
The deciding questions are whether new columns are welcome and whether the stream may stop.
Example: addNewColumns with a Delta target
Reading with addNewColumns is only half the work. The Delta table you write to must also accept the new column. Without mergeSchema, the write fails even though Auto Loader's own schema has been updated.
from pyspark.sql.functions import col
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.option("cloudFiles.inferColumnTypes", "true")
.option("cloudFiles.schemaEvolutionMode", "addNewColumns")
.load("/Volumes/main/raw/landing/orders")
.withColumn("source_file", col("_metadata.file_path")))
(df.writeStream
.option("checkpointLocation", "/Volumes/main/raw/_checkpoints/orders")
.option("mergeSchema", "true")
.trigger(availableNow=True)
.toTable("main.bronze.orders"))Now follow a new column through this stream:
- A file arrives containing
coupon_code. - The run fails with
UnknownFieldException.schemaLocationnow holds a schema that includescoupon_code. - The next run starts, reads with the new schema, and
mergeSchemalets Delta add the column tomain.bronze.orders. - The file is processed. Older rows show
NULLforcoupon_code.
If your job runs on a schedule, step 3 happens at the next scheduled run, or sooner if you configure job retries.
Example: rescue mode
In rescue mode the stream does not change shape. Unknown columns are captured in _rescued_data.
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders_rescue")
.option("cloudFiles.schemaEvolutionMode", "rescue")
.load("/Volumes/main/raw/landing/orders"))
(df.writeStream
.option("checkpointLocation", "/Volumes/main/raw/_checkpoints/orders_rescue")
.trigger(availableNow=True)
.toTable("main.bronze.orders_rescue"))You can then find what was rescued with a query:
SELECT _rescued_data, count(*) AS row_count
FROM main.bronze.orders_rescue
WHERE _rescued_data IS NOT NULL
GROUP BY _rescued_data;When you decide a rescued field deserves a real column, add it through cloudFiles.schemaHints and restart. New files will populate the column. Older rows keep the value in _rescued_data, so you may need a one-off backfill query.
Type changes are different from new columns
Schema evolution modes govern new columns. They do not change the type of an existing column. If a column is BIGINT in your schema and a file contains "abc", the value goes to _rescued_data and the column is NULL for that row. This is true in every mode that has a rescued data column.
Without inferColumnTypes, JSON and CSV columns are inferred as strings. That avoids many mismatches, but it moves casting work downstream. Pin the columns you care about with schema hints, as covered in the previous chapter.
Gotchas
- Nested structs. A new field inside a struct counts as a schema change, and
addNewColumnshandles it the same way as a top-level column. - Schema location is shared state. Two streams that point at the same
schemaLocationcan overwrite each other's schema versions. Use one location per stream. - Deleting the schema location. The next run re-infers the schema from a sample. Combine this with an existing checkpoint carefully, because the inferred types may differ from what your table already holds.
- Fixed schema, silent loss. When you pass
.schema(...)the default isnone. SetrescuedDataColumnexplicitly if you want a safety net. - Failure counts as normal. With
addNewColumns, one failure per new column is expected behavior. Alert on repeated failures, not on the first one.
Summary of trade-offs
| Goal | Mode | Cost |
|---|---|---|
| New data flows into columns without human work | `addNewColumns` | One failure per change, and the target needs `mergeSchema` |
| Stream never stops | `rescue` | New fields stay in JSON until promoted |
| Every schema change is reviewed | `failOnNewColumns` | Pipeline blocks until someone acts |
| Fixed contract, extra fields are noise | `none` | Unknown data is lost without a rescued data column |
Exercise
A scheduled availableNow job reads JSON with schemaEvolutionMode set to addNewColumns. An upstream file adds a column called coupon_code. The run fails with UnknownFieldException. Your teammate restarts the job and it fails again, this time with a Delta schema error from the write. What went wrong, and what is the fix?
Show answer
Auto Loader updated its own schema in schemaLocation on the first failure, so the read side now includes coupon_code. The Delta target table does not have that column, and the write did not allow the table schema to change. The fix is to add .option("mergeSchema", "true") to the writeStream, or to add the column to the table first with ALTER TABLE. Then restart the job.
Exercise
A continuous stream feeds a live dashboard and must not stop when upstream adds columns. The team also wants to review new fields before they become table columns. Which mode fits, and how do you find new fields?
Show answer
Use rescue. The schema never changes and the stream does not fail. New fields are stored as JSON in rescueddata, so you can query rows where rescueddata IS NOT NULL to see them. When the team approves a field, add it with cloudFiles.schemaHints and restart.