7.2 Auto Loader Schema Inference, Evolution, & Rescued Data Column
Key Takeaways
- Auto Loader automatically infers schemas across semi-structured and structured formats (JSON, CSV, Parquet, Avro, XML) and persists the inferred contract as JSON in 'cloudFiles.schemaLocation'.
- Schema evolution is controlled via 'cloudFiles.schemaEvolutionMode', offering four distinct behaviors: 'addNewColumns' (default), 'failOnNewColumns', 'rescue', and 'none'.
- The '_rescued_data' column automatically captures unparseable data, type mismatches, and undeclared columns in a JSON string/struct, guaranteeing that no source data is silently lost during ingestion.
- Schema hints ('cloudFiles.schemaHints') allow engineers to enforce strict data types (e.g., parsing strings as TIMESTAMP or DECIMAL) while allowing Auto Loader to infer the remainder of the schema dynamically.
- When combined with Delta Lake's 'mergeSchema = true' option, Auto Loader seamlessly updates downstream Delta table schemas when new fields appear in source files.
7.2 Auto Loader Schema Inference, Evolution, & Rescued Data Column
DP-750 Exam Focus: Master Auto Loader schema management. Understand how
cloudFiles.schemaLocationpersists inferred schemas, evaluate the fourcloudFiles.schemaEvolutionModesettings (addNewColumns,failOnNewColumns,rescue,none), enforce specific data types withcloudFiles.schemaHints, and explain the behavior and utility of the_rescued_datacolumn.
1. Schema Inference & cloudFiles.schemaLocation
In raw Bronze ingestion, source systems frequently emit files with dynamic, unannounced schema variations—such as newly added attributes, omitted fields, or slight data type variations.
Standard Spark structured streaming file readers require a rigidly predefined static schema (.schema(my_schema)). If a file arrives with an unexpected schema change, standard Spark readers either fail immediately or parse new columns as null, causing silent data loss.
Auto Loader eliminates manual schema definitions through automatic schema inference and persistent schema storage.
+-----------------------------------------------------------------------------------+
| SCHEMA INFERENCE & EVOLUTION FLOW |
+-----------------------------------------------------------------------------------+
| |
| [ Ingest Files (JSON / CSV / Parquet) ] |
| | |
| v |
| [ Auto Loader Schema Engine ] <====> [ cloudFiles.schemaLocation ] |
| - Samples initial files (Persists schema contract as JSON) |
| - Applies schemaHints overrides /_schemas/0/schema.json |
| | |
| v |
| [ Schema Drift Detection ] |
| | |
| +---------------------------------------+ |
| | (New column detected) | (Type mismatch / corrupt data) |
| v v |
| [ schemaEvolutionMode ] [ _rescued_data Column ] |
| - addNewColumns (Default) - Stores invalid record payload |
| - failOnNewColumns - Captures unmapped columns |
| - rescue - Prevents silent data corruption |
| - none | |
| | | |
| +-------------------+-------------------+ |
| | |
| v |
| [ Target Bronze Delta Table ] |
| (Auto-evolved schema with rescued records) |
+-----------------------------------------------------------------------------------+
The cloudFiles.schemaLocation Option
To enable schema inference and evolution, data engineers must provide cloudFiles.schemaLocation. This directory stores the learned schema contract in cloud storage (ADLS Gen2):
# Auto Loader with Schema Inference
df_inferred = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "abfss://checkpoints@myadls.dfs.core.windows.net/iot_schema")
.option("cloudFiles.inferColumnTypes", "true") # Informs Auto Loader to infer types beyond STRING for JSON/CSV
.load("abfss://raw@myadls.dfs.core.windows.net/iot-telemetry/"))
Key Operational Behaviors
- Initial Sampling: When the stream launches for the first time, Auto Loader samples the first 1,000 files (or up to 50 GB of data by default) to establish the initial schema definition.
- Schema Persistence: The inferred schema is written to
cloudFiles.schemaLocationas an immutable JSON schema file. On subsequent stream restarts, Auto Loader reads the schema directly from this location, skipping redundant sampling. cloudFiles.inferColumnTypes: By default for JSON and CSV, Auto Loader infers all columns asStringTypeto avoid premature type casting errors. SettingcloudFiles.inferColumnTypestotrueinstructs Auto Loader to infer numeric, boolean, timestamp, and complex nested types.
2. Schema Evolution Modes
When a newly ingested file contains columns that are not present in the persisted schema contract, Auto Loader's behavior is dictated by cloudFiles.schemaEvolutionMode.
| Schema Evolution Mode | Behavior on New Column Detection | Schema Location Updated? | Pipeline Behavior |
|---|---|---|---|
addNewColumns (Default) | Adds new columns to the schema contract. | Yes | Stream continues (or auto-restarts in DLT/workflows) and appends new columns to the downstream Delta table. |
failOnNewColumns | Throws an UnknownFieldException and fails the micro-batch immediately. | No | Stream fails. Prevents accidental schema modifications until an engineer validates the new fields. |
rescue | Does not modify the schema contract. New unmapped columns are captured inside the _rescued_data column. | No | Stream continues running without altering table structure. |
none | Ignores new columns completely; does not add them to schema or rescue column. New columns are dropped. | No | Stream continues running; new columns are silently discarded. |
Mode Comparison & Production Scenarios
1. addNewColumns (Default)
Ideal for Bronze lakehouse ingestion where all landing data must be preserved. When a new column (e.g., battery_temp) appears, Auto Loader updates the schema file in schemaLocation and restarts the stream with the updated schema.
# Ingesting with addNewColumns and Delta schema merging
(spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "abfss://checkpoints@myadls/schema_sales")
.option("cloudFiles.schemaEvolutionMode", "addNewColumns")
.load("abfss://raw@myadls/sales_json/")
.writeStream
.format("delta")
.option("checkpointLocation", "abfss://checkpoints@myadls/cp_sales")
.option("mergeSchema", "true") # Required for target Delta table to accept evolved columns
.toTable("bronze.sales.raw_transactions"))
2. failOnNewColumns
Used in strict governance environments where upstream source schema changes require manual approval or schema registry validation before entering the lakehouse.
3. rescue
Recommended when the downstream Delta table schema must remain strictly static, but unmapped attributes must be preserved for forensic analysis in _rescued_data rather than discarded.
3. The _rescued_data Column: Deep Dive
To prevent data loss and pipeline downtime from schema mismatches or corrupt records, Auto Loader automatically provisions a hidden column named _rescued_data by default.
RESCUED DATA INGESTION MATRIX
Source Record in ADLS Gen2:
{"device_id": 101, "reading": "INVALID_FLOAT", "new_sensor_val": 42.8}
Target Schema:
- device_id: BIGINT
- reading: DOUBLE
+-----------------------------------------------------------------------------------+
| INGESTED DELTA ROW |
+-----------+---------+-------------------------------------------------------------+
| device_id | reading | _rescued_data |
+-----------+---------+-------------------------------------------------------------+
| 101 | null | {"reading":"INVALID_FLOAT", "new_sensor_val":42.8, |
| | | "_file_path":"abfss://raw@storage/data_01.json"} |
+-----------+---------+-------------------------------------------------------------+
What Is Captured in _rescued_data?
- Data Type Mismatches: If a column is defined as
DOUBLE(e.g.,reading), but a source record contains a non-numeric string ("INVALID_FLOAT"), the column value in the main table is set tonull, and the raw unparsed value is preserved inside_rescued_data. - Undeclared Columns: Under
schemaEvolutionMode = 'rescue'(or if schema evolution is disabled), any column in the source file not declared in the schema is routed into_rescued_data. - Malformed Records: Unparseable JSON or CSV lines that violate standard formatting syntax.
- Case Sensitivity Clashes: When case sensitivity is enabled, differences in column casing (e.g.,
CustomerIdvscustomerId) are preserved in_rescued_datato prevent accidental overwrites.
Querying Rescued Data with Databricks SQL
Data engineers can easily query, inspect, and extract rescued fields using standard SQL JSON extraction functions:
-- Query: Identify rows with data rescue events and extract original values
SELECT
device_id,
reading,
_rescued_data,
get_json_object(_rescued_data, '$.reading') AS original_reading_str,
get_json_object(_rescued_data, '$._file_path') AS source_file
FROM bronze.telemetry.raw_events
WHERE _rescued_data IS NOT NULL;
Exam Tip: To disable the rescued data column, set
.option("cloudFiles.schemaEvolutionMode", "none")and.option("cloudFiles.schemaHints", "")or set.option("cloudFiles.rescuedDataColumn", "")(empty string). In production, leaving_rescued_dataenabled is the recommended practice for Bronze ingestion.
4. Schema Hints & Explicit Overrides
While Auto Loader infers schemas effectively, automated inference may choose overly permissive or generic data types (for example, inferring an ISO timestamp string as StringType or an integer ID as LongType).
Schema Hints (cloudFiles.schemaHints) allow data engineers to explicitly enforce exact data types for specific columns while allowing Auto Loader to automatically infer the rest of the schema.
# Applying Schema Hints for precise datatype enforcement
df_hints = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "csv")
.option("cloudFiles.schemaLocation", "abfss://checkpoints@myadls/csv_schema")
.option("header", "true")
.option("cloudFiles.inferColumnTypes", "true")
.option("cloudFiles.schemaHints", """
transaction_id BIGINT,
amount DECIMAL(10, 2),
transaction_timestamp TIMESTAMP,
is_fraudulent BOOLEAN
""")
.load("abfss://raw@myadls/finance_csv/"))
Rules Governing Schema Hints
- Precedence: Explicit definitions in
cloudFiles.schemaHintsoverride both inferred types and types loaded fromcloudFiles.schemaLocation. - Partial Specification: Engineers only need to specify the subset of columns requiring strict typing; unmentioned columns are dynamically inferred.
- Type Casting Resilience: If incoming data cannot be cast to the type specified in
schemaHints(e.g.,"N/A"in aDECIMALcolumn), the column receivesnulland the raw value is safely captured in_rescued_data.
A data engineer configures an Auto Loader stream to ingest JSON files. The upstream source unexpectedly introduces a new column named 'loyalty_tier' that was not present in the initial schema inference. The engineering team wants the stream to continue running without failure, while ensuring that the new column is automatically added to the target Delta Lake table. Which configuration is required?
During an Auto Loader ingestion run on CSV files, a source record contains a non-numeric string 'UNCONFIRMED' in a column typed as DOUBLE. How does Auto Loader handle this record when the default '_rescued_data' column is active?
An engineer wants Auto Loader to dynamically infer the schema for 50 JSON attributes, but must strictly enforce that 'transaction_timestamp' is parsed as TIMESTAMP and 'amount' is parsed as DECIMAL(18, 4). What is the recommended Auto Loader configuration?