Reliability · By Divya Madhavan
PySpark to BigQuery Schema Drift: A Production Troubleshooting Runbook
Fix schema mismatch errors, silent CSV column swaps and unexpected nulls without corrupting downstream tables. A practical incident runbook for data engineers and senior data engineers using PySpark, Dataproc, BigQuery and Airflow.
The incident: a successful job with incorrect data
Illustrative scenario: a daily order feed changes from order_id, amount, currency to order_id, currency, amount. An ingestion job using positional parsing may misinterpret values, while a strict warehouse load may fail instead. A second delivery adds a new optional discount_code. These are different changes and need different responses. No employer data or incident is used here.
First 15 minutes: contain the blast radius
Pause publication for the affected feed and dependent refreshes, not unrelated pipelines. Record the orchestration run ID, source object generations, contract version, Spark application ID and BigQuery job ID. Preserve raw data and the last verified output. Check whether incorrect data already reached consumers; communicate the affected date range and whether reports are stale or wrong. Do not enable schema auto-evolution as an emergency fix.
Find the failing boundary
Compare the producer manifest and actual headers with the expected contract, then compare Spark's parsed schema and warehouse metadata. A mismatch before transformation suggests parser or producer drift; a correct Spark schema with a rejected warehouse write suggests destination incompatibility. If all schemas match but totals change, inspect semantic drift such as cents versus dollars. Schema equality cannot detect a unit change.
Inspect BigQuery metadata before touching the table
Run this read-only GoogleSQL query in the correct project and dataset location. Compare column types, nullability and order against the approved contract. For nested fields inspect COLUMN_FIELD_PATHS as well. Replace the example project and dataset identifiers.
SELECT column_name, data_type, is_nullable, ordinal_position
FROM `example_project.analytics.INFORMATION_SCHEMA.COLUMNS`
WHERE table_name = 'orders'
ORDER BY ordinal_position;Prevent silent CSV column swaps in PySpark
For a fixed-order CSV contract, specify the input schema and validate headers rather than forcing a positional schema onto reordered input. This example targets Spark 3.5.x and reads all fields as strings before business validation. FAILFAST and header validation are not a complete row-width or semantic check: Spark CSV does not classify every short or long row as corrupt. Validate record width with a dialect-aware parser upstream when exact width is required. Trigger an action or staging write to execute lazy validation; a printSchema call alone does not scan data.
raw = (spark.read
.option('header', 'true')
.option('enforceSchema', 'false')
.option('mode', 'FAILFAST')
.schema('order_id STRING, amount STRING, currency STRING')
.csv(immutable_input_paths))
# Execute validation against the immutable manifest before publication.Separate accepted rows from rejected rows
Use explicit conversions and a business contract. In this example, amounts must be non-negative decimal values with at most two fractional digits, and currencies must be USD, EUR or GBP. Adapt these rules to the feed owner’s requirements. The syntax check prevents silent rounding; try_cast catches overflow. A null or blank key is rejected. Preserve original strings and rejection reasons in restricted staging/quarantine; avoid logging raw sensitive values.
from pyspark.sql import functions as F
checked = (raw
.withColumn('amount_num', F.expr('try_cast(amount as decimal(18,2))'))
.withColumn('reason',
F.when(F.col('order_id').isNull() | (F.trim('order_id') == ''), 'missing_key')
.when(~F.coalesce(F.col('amount').rlike(r'^[0-9]+(\.[0-9]{1,2})?), F.lit(False))
| F.col('amount_num').isNull(), 'invalid_amount')
.when(~F.coalesce(F.col('currency').isin('USD','EUR','GBP'), F.lit(False)), 'invalid_currency')))
accepted = checked.filter(F.col('reason').isNull())
rejected = checked.filter(F.col('reason').isNotNull())
# Persist to run-scoped staging; reconcile counts before publishing.Decide whether to accept, quarantine or migrate
An approved nullable addition may be backward compatible, provided consumers tolerate it. A renamed field needs an explicit mapping and transition plan. A removed required field, changed key, incompatible type or changed unit should block publication until the contract owner approves a migration. Reordered CSV headers should fail the fixed-order contract; if order-independent ingestion is desired, implement and test explicit header-based mapping rather than ignoring headers.
Deploy an additive warehouse change safely
For an approved optional discount_code addition, review dependent Dataform models, views and positional inserts. Apply the schema change in a controlled release before publishing the new contract. Existing records will have NULL for the new nullable column. IF NOT EXISTS makes rerunning this DDL convenient but does not verify the type of a pre-existing column; check metadata afterward. For breaking changes use a versioned destination and validated consumer cutover instead of destructive changes.
ALTER TABLE `example_project.analytics.orders`
ADD COLUMN IF NOT EXISTS discount_code STRING;Recover the affected window without double counting
Replay the exact immutable delivery into run-scoped staging. Compare expected source counts against accepted plus rejected counts, validate business keys and amounts by currency, and inspect downstream aggregates. For a complete daily snapshot, publish a verified replacement of only the intended partition. For incremental events use a deterministic business key and version-aware merge after deduplicating source rows. Serialize overlapping publication jobs. A successful warehouse write followed by an Airflow timeout must be reconciled before another write. Keep audit status separate from the logical delivery identity.
Data Engineer checklist: prove the fix
Create small fixtures for valid data, reordered headers, missing and extra columns, decimal overflow, blank IDs, unsupported currencies, malformed rows and an approved nullable addition. Verify both expected failures and successful outputs. Rerun the same delivery twice and verify stable destination counts and sums. Simulate failure after publication but before audit success. Test against the actual Spark and warehouse connector versions; these snippets are illustrative and have not been executed against a live cloud environment.
Senior Engineer checklist: prevent the next incident
Assign a producer and consumer owner, version contracts, require compatibility review in CI, and separate ingestion privileges from schema migration privileges. Track schema mismatch count, rejected-row rate, affected partitions, freshness, time to detection and time to validated recovery. Set thresholds with business owners rather than copying generic percentages. Use the same principles on AWS or Azure, but verify the actual warehouse and connector evolution semantics instead of assuming BigQuery behavior is portable.
Exit criteria and incident handover
Resume publication only after approved contract and destination metadata agree, rejected records are accounted for, downstream business totals reconcile, replay is repeatable and the consumer owner accepts the repaired window. Record root cause, corrective change, rollback plan, evidence and a named owner for preventive work. The goal is trustworthy data, not merely a green orchestration dashboard.