Data Quality Audit for Flight Delay Prediction Models
Machine LearningModel answerLast updated
Perform a comprehensive data quality audit, leakage check, and data contract design for an aviation dataset intended for delay prediction.
You are tasked with auditing a raw flight operation dataset before using it to train a regression model that predicts arrival delay (arr_delay in minutes).
The provided documentation slide claims the dataset contains the following schema:
flight_date: String representing local date (YYYY-MM-DD).dep_time/arr_time: String or integer formatted as localHHMM.dep_delay/arr_delay: Integer minutes (negative values indicate early events).cancelled: Binary flag (0or1).tail_num: Unique aircraft identifier.origin/dest: 3-letter airport codes.aircraft_type: Optional string.weather_code: Optional integer/string.
Perform a thorough data audit by answering the following key areas:
- Concrete Data Quality & Semantic Issues: Detail at least 8 specific high-risk failure modes you must test for (covering timestamp/timezone anomalies, impossible values, data leakage, operational contradictions, and schema drifts).
- Detection Logic & Impact Metrics: For each issue, specify exact programmatic detection criteria (SQL/Python pseudo-logic or regex) and define how to measure its impact on model input/target feeds.
- Leakage-Safe Mitigation & Validation: Explain how to resolve these errors without introducing target leakage or temporal snooping. Describe the statistical and diagnostic techniques used to verify the fixes.
- Data Contract & CI/CD Enforcement: Define a concrete specification for an upstream data contract and describe how to automate validation checks in production pipelines.
Hints
Hint 1
Establish the exact point in time when the prediction is executed. Features available only post-departure or post-arrival must be flagged as leakage.
Hint 2
Local timestamps in HHMM format lack timezone context and offset information, which causes severe errors around Daylight Saving Time (DST) changes.
Hint 3
Target definition: decide how to handle cancelled or diverted flights when defining the modeling dataset versus evaluation metrics.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. High-Risk Data Quality Issues, Detection Logic & Impact Metrics
Before performing any data checks, we must establish the explicit prediction point in time. Assuming the goal is to predict flight arrival delay prior to departure (e.g., at scheduled departure time $T_{sched_dep}$), any feature generated after $T_{sched_dep}$ is a potential vector for target leakage.
Below are 10 concrete, high-risk issues found in raw flight feeds:
| # | High-Risk Failure Mode | Exact Programmatic Detection Logic | Impact & Coverage Metric |
|---|---|---|---|
| 1 | Invalid Local Time Formatting | `dep_time NOT REGEXP '^(0[0-9] | 1[0-9] |
| 2 | Timezone & Offset Ambiguity | Convert local dep_time and arr_time to UTC using origin/destination IANA maps. Flag if flight_duration_utc = (arr_utc - dep_utc) <= 0 or flight_duration_utc > 1200 minutes (20h). | Percentage of affected flights; geographic clustering by airport pair. |
| 3 | Daylight Saving Time (DST) Shifts | Check if local time falls into nonexistent hours during spring-forward transitions (e.g., 02:15 AM on transition date) or unhandled duplicate hours during fall-back transitions without a explicit UTC offset. | Row count per transition window; systematic drift in route median elapsed time (±60 min error). |
| 4 | Physically Implausible Delays | arr_delay < -90 OR arr_delay > 1440 (early by >1.5h or delayed >24h). | Percentage of target rows; proportion of overall target variance explained by extreme outliers. |
| 5 | Cancellation Logic Inconsistencies | (cancelled = 1 AND (arr_time IS NOT NULL OR arr_delay IS NOT NULL)) OR (cancelled = 0 AND arr_delay IS NULL). | Total invalid records; potential label distortion in training dataset. |
| 6 | Aircraft Sequence & Identity Contradictions | Group by tail_num sorted by time. Flag if origin_{t} $\neq$ dest_{t-1} OR if time gap dep_utc_{t} - arr_utc_{t-1} < 0 (overlapping flights for same aircraft). Also detect dummy tail IDs: tail_num IN ('00000', 'UNKNOW', 'N/A'). | Rate of corrupted sequential/lagged features (e.g., inbound turnaround delay). |
| 7 | Target & Post-Facto Feature Leakage | Feature timestamp $T_{feature} > T_{sched_dep}$. Examples: weather_code captured at arrival, or dep_delay containing actual pushed-back times when predicting at scheduled time. Measure via univariate feature-target correlations ($R^2 > 0.8$). | Decrease in model metric (e.g., RMSE / MAE) when leaking features are stripped out. |
| 8 | Unit Inconsistency Across Feeds | Detect raw feeds recording delays in seconds instead of minutes: MEDIAN(ABS(dep_delay)) > 300 within a specific carrier/source partition, or SUM(CASE WHEN dep_delay % 60 = 0 THEN 1 ELSE 0 END) / COUNT(*) > 0.5. | Count and percentage of corrupted partitions/rows. |
| 9 | Invalid Categorical Airport Codes | origin NOT IN (SELECT iata_code FROM iata_master) OR dest NOT IN (SELECT iata_code FROM iata_master) OR origin = dest. | Unmatched row count; feature loss in downstream categorical embeddings. |
| 10 | Inconsistent Optional Metadata | Dynamic mapping changes over time: COUNT(DISTINCT aircraft_type) > 1 per tail_num within a 30-day window, or non-random missingness of aircraft_type ($P(\text{missing} \mid \text{carrier}) \neq P(\text{missing})$). | Non-random missingness rates; high cardinality expansion. |
2. Leakage-Safe Mitigation Strategy
A. Time Normalization & Alignment
- IANA Timezone Mapping: Join each
originanddestto an authoritative IANA Airport Timezone Database (e.g.,America/New_York,America/Phoenix). - Timestamp Parsing: Combine
flight_dateanddep_time/arr_timeinto a ISO-8601 string with explicit offset handling via Python'szoneinfoor SQLAT TIME ZONE. - DST Handling:
- For spring-forward gaps (nonexistent local times), forward-shift the timestamp to the start of the valid offset window (e.g., 02:00 $\rightarrow$ 03:00).
- For fall-back duplicates (ambiguous local times), use aircraft sequential state (
arr_utcof previous leg) to infer the correct fold index.
B. Data Cleaning vs. Filtering
- Deterministic Fixes: Normalize standard midnight notation (
2400$\rightarrow$0000of the next date). Rescale identified second-based delay columns to minutes by dividing by 60. - Target Quarantine: Exclude
cancelled = 1rows from the continuous arrival delay regression target. (Cancelled flights represent a separate classification task). - Outlier Capping: Clip ground truth arrival delays to a bounded window $[-60, +1200]$ minutes for loss stability, but calculate performance metrics against raw values.
C. Preventing Target & Temporal Leakage
- Pipeline Order: All transformations, target encoders, median imputers, and scaling operations must be calculated only within training folds in a temporal cross-validation setup (
TimeSeriesSplit). - Feature Exclusions: Drop
arr_timeand all ground weather features recorded after $T_{sched_dep}$. For historical delay aggregations (e.g.,tail_numpast 24h delay), enforce a safety lag: $T_{event_arr} + \Delta t_{buffer} \le T_{sched_dep}$.
3. Verification & Validation Metrics
To ensure raw data cleaning fixes issues without distorting fundamental distributions:
-
Reconciliation Accounting: $$\text{Total Raw Rows} = \text{Clean Rows} + \text{Quarantined Rows} + \text{Dropped Malformed Rows}$$ Verify that total row losses do not exceed predefined thresholds (e.g., $< 0.5%$).
-
Distributional Invariance (Kolmogorov-Smirnov Test): Run a two-sample KS test comparing the delay distributions of clean partitions against historical baseline partitions: $$D = \sup_x |F_1(x) - F_2(x)|$$ Ensure $D < 0.05$ across rolling weekly windows to verify no systematic bias was introduced during normalization.
-
Temporal Out-of-Fold Validation: Compare Model performance (MAE/RMSE) on a strict temporal holdout set (e.g., Month $T+1$). If removing a feature causes a massive metric drop on training folds but zero drop on holdout evaluation, target leakage was successfully identified and eradicated.
4. Production Data Contract & CI Automated Checks
Below is a declarative data contract specification (YAML structure) to enforce upstream data health:
version: 1.0
dataset: flight_operations_v1
owner: data-engineering-team
schema:
flight_date:
type: string
format: date # YYYY-MM-DD
nullable: false
dep_time:
type: string
pattern: "^([0-1][0-9]|2[0-3])[0-5][0-9]$|^2400$"
nullable_if: "cancelled == 1"
arr_time:
type: string
pattern: "^([0-1][0-9]|2[0-3])[0-5][0-9]$|^2400$"
nullable_if: "cancelled == 1"
dep_delay:
type: integer
range: [-120, 1440]
unit: minutes
nullable_if: "cancelled == 1"
arr_delay:
type: integer
range: [-120, 1440]
unit: minutes
nullable_if: "cancelled == 1"
cancelled:
type: integer
allowed_values: [0, 1]
nullable: false
tail_num:
type: string
pattern: "^N[0-9]{1,5}[A-Z]{0,2}$"
blacklisted_values: ["000000", "UNKNOWN", "N/A"]
origin:
type: string
lookup: iata_master_codes
nullable: false
dest:
type: string
lookup: iata_master_codes
nullable: false
semantic_rules:
- rule_id: route_validity
expression: "origin != dest"
- rule_id: cancellation_consistency
expression: "IF cancelled == 1 THEN arr_delay IS NULL AND arr_time IS NULL"
- rule_id: sequential_flight_consistency
expression: "tail_num PREV(dest) == CURRENT(origin)"
- rule_id: max_null_rate_aircraft_type
target_column: aircraft_type
max_null_percentage: 15.0
drift_rules:
- column: arr_delay
metric: ks_statistic
threshold: 0.05
baseline: rolling_30_days
CI/CD Enforcement Mechanisms
- Pre-Ingestion Batch Checks: Run tools like Great Expectations or Soda SQL over staging data before ETL execution. Fail pipeline execution if mandatory integrity checks (e.g., null constraints, strict regex patterns) are breached.
- Statistical Sampling & Anomaly Detection: For large-scale data ingestion, sample 5% of incoming batches and execute distribution checks (e.g., null rate jumps, unexpected zero values) against historical baselines.
- Dead-Letter Queue (DLQ): Divert non-compliant rows into an isolated DLQ table (
flight_operations_quarantine) with error diagnostic tags for operational remediation without halting downstream pipelines.