Symptom
A CSV or JSON load "succeeds", but:
- whole columns, or random rows, are
NULLeven though the source file has values; - the row count in the table is lower than
wc -lon the file; df.count()anddf.filter(...).count()disagree in ways that make no sense;- or the opposite: one bad line in a 50 GB file fails the entire job.
All of these come from the same place: how Spark's CSV and JSON parsers handle records that don't match the schema. The default behaviour is to keep going quietly, which is good for availability and bad for data quality.
How the parse modes behave
The mode option controls what happens when a record can't be parsed against the schema:
| Mode | What happens to a bad record | When to use it |
|---|---|---|
PERMISSIVE (default) | Row is kept; fields that fail to parse become NULL; the raw text goes into the corrupt record column if the schema has one | Production loads, with the corrupt column captured and monitored |
DROPMALFORMED | Row is dropped with no error | Rarely; you lose data with no record of it |
FAILFAST | Read fails with an exception on the first bad record | Strict feeds where any bad row should stop the pipeline |
"Bad record" includes more than broken syntax. A value of abc in an IntegerType column, a date that doesn't match dateFormat, or (for CSV) the wrong number of fields all count. With PERMISSIVE, a CSV row with fewer fields than the schema is padded with NULLs; how extra fields are treated has changed between versions, so test with your build.
Checks
1. Is the schema actually what the file contains?
Most "random NULL" incidents are a schema mismatch, not corrupt data. Compare the declared schema with what Spark infers from a sample:
sample = (spark.read.option("header", "true").option("inferSchema", "true")
.option("samplingRatio", 0.1).csv("/landing/orders/2026-11-29/"))
sample.printSchema()
Look for a column inferred as string that you declared as int or timestamp, which usually means a format difference (thousands separators, a different date pattern, N/A for missing values).
2. Is the header being checked?
For CSV with header=true, Spark by default uses your schema positionally and ignores the header names (enforceSchema=true). If the producer adds or reorders a column, every field after it shifts and starts failing to parse. Make Spark validate the header against the schema:
df = (spark.read.schema(schema)
.option("header", "true")
.option("enforceSchema", "false")
.csv(path))
With enforceSchema=false, a header that doesn't match the schema field names produces an error instead of silently shifted data.
3. Capture the bad rows and count them
Add the corrupt record column to the schema as a string. For CSV this is required: Spark only fills the column if it is in the schema you pass.
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, TimestampType
from pyspark.sql.functions import col
schema = StructType([
StructField("order_id", IntegerType()),
StructField("customer_id", StringType()),
StructField("amount", IntegerType()),
StructField("created_at", TimestampType()),
StructField("_corrupt_record", StringType()),
])
df = (spark.read.schema(schema)
.option("header", "true")
.option("mode", "PERMISSIVE")
.option("columnNameOfCorruptRecord", "_corrupt_record")
.option("timestampFormat", "yyyy-MM-dd HH:mm:ss")
.csv("/landing/orders/2026-11-29/"))
df.cache()
bad = df.filter(col("_corrupt_record").isNotNull())
print("total", df.count(), "bad", bad.count())
bad.select("_corrupt_record").show(20, truncate=False)
The default column name is _corrupt_record (set by spark.sql.columnNameOfCorruptRecord). For JSON with schema inference, Spark adds the column automatically when it finds malformed records.
Tip
If you get an
AnalysisExceptionsaying queries over raw JSON/CSV files are disallowed when the referenced columns only include the internal corrupt record column, cache or persist the DataFrame first (as above), then filter on_corrupt_record. Spark blocks that query shape on an uncached file read.
4. Why counts disagree
CSV column pruning means Spark only parses the columns a query needs. df.count() on a DROPMALFORMED read may not parse fields at all, so it can return a higher count than a query that selects columns and actually hits the malformed values. Don't use a bare count() to judge how many rows were dropped; compare against a PERMISSIVE read with the corrupt column instead.
Common causes and fixes
| Symptom | Cause | Fix |
|---|---|---|
Every value after column N is NULL | Producer added or reordered a column; schema applied by position | enforceSchema=false, update the schema, add a data contract check |
| Rows split in half, fields shifted | Quoted fields contain newlines | .option("multiLine", "true") for CSV and JSON |
Fields with "" inside quotes break | File uses RFC 4180 doubled quotes, Spark default escape is backslash | .option("escape", '"') |
All timestamps NULL | timestampFormat doesn't match the data | Set the right pattern; check spark.sql.legacy.timeParserPolicy if Spark raises an upgrade exception about the pattern |
| Accented characters garbled, rows malformed | File is not UTF-8 | .option("encoding", "ISO-8859-1") (or the real charset) |
NULL where the file has N/A or - | Placeholder doesn't parse as a number | .option("nullValue", "N/A") or read as string and clean |
| JSON file reads as one corrupt row per line | File is a JSON array or pretty-printed objects | .option("multiLine", "true") |
| Job fails on unreadable or truncated files | Corrupt or partially uploaded file | Fix the producer; as a stopgap ignoreCorruptFiles=true, but alert on it |
Warning
ignoreCorruptFilesandDROPMALFORMEDboth throw data away without failing the job. Using either without a count or alert means the first sign of trouble is a customer asking why totals are low.
Quarantine bad rows instead of losing them
A pattern that works in production: read PERMISSIVE, split good and bad rows, write the bad ones to a quarantine table, and fail the job only if the bad ratio crosses a threshold.
good = df.filter(col("_corrupt_record").isNull()).drop("_corrupt_record")
bad = (df.filter(col("_corrupt_record").isNotNull())
.select("_corrupt_record")
.withColumnRenamed("_corrupt_record", "raw_line"))
total, n_bad = df.count(), bad.count()
bad.write.mode("append").saveAsTable("quarantine.orders_bad_rows")
if total and n_bad / total > 0.001:
raise RuntimeError(f"{n_bad}/{total} malformed rows in orders load, see quarantine.orders_bad_rows")
good.write.mode("append").saveAsTable("bronze.orders")
On Databricks you can also set badRecordsPath; malformed records and unreadable files are written as JSON under that path with the source file and the reason. It is Databricks-specific, so code that must run on open-source Spark should use the corrupt column instead.
Prevent it next time
- Never rely on
inferSchemain production. Declare the schema, include_corrupt_record, and keep the schema in version control. - Use
enforceSchema=falsefor CSV with headers so column changes fail loudly. - Alert on the malformed-row count and ratio per load, not just on job failure.
- Choose the mode deliberately per feed:
FAILFASTfor financial or contract feeds,PERMISSIVEwith quarantine for everything else,DROPMALFORMEDalmost never. - Agree a file contract with the producer: encoding, delimiter, quoting, date formats and how nulls are written.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get