The user wants a solution for "Safe CSV ingestion" with specific requirements:
Schema Inference: Automatically determining the column names and data types from the file.
Encoding Handling: Detecting and correctly parsing different character encodings (e.g., UTF-8, Latin-1) to avoid decoding errors.
Type Validation: Checking if the data actually matches the inferred or expected types (e.g., ensuring an integer column contains integers).
Quarantine: Separating bad rows (rows that fail validation) from the good rows for further inspection, rather than failing the whole process.
I need to provide a conceptual explanation and a practical code implementation (likely in Python, as it's the standard for data engineering/ingestion tasks). pandas is the most common tool, but csv module or pyarrow or polars are also options. pandas is usually the most accessible for this specific mix of requirements, especially with libraries like chardet for encoding.
Standard csv library (optional, but good for robustness).
Implementation Details (Python Class or Functions):
Encoding Detection: Read raw bytes, use chardet, decode.
Schema Inference: Use pd.read_csv with a small sample or infer_objects().
Validation: Iterate through rows or use vectorized operations to check types. If the inferred schema says "int", ensure the value converts to int.
Quarantine: Move failing rows to a separate DataFrame/CSV.
Refining the "Schema Inference" & "Type Validation" logic:
True type validation in pandas can be tricky because read_csv tries to coerce types automatically. If a column is mixed int/string, pandas might make it object.
Strategy: Read the file. Let pandas infer. Then, enforce strict types based on the inference or a provided schema. If a specific row has "error" in an integer column, pandas reads it as object (or NaN if na_values is set).
Better Strategy: Read as string/object first, infer types from a sample (or top N rows), then iterate to validate and cast.
Drafting the Code Structure:
python
class SafeCSVIngester:
def __init__(self, file_path):
self.file_path = file_path
self.encoding = None
self.schema = {}
self.good_rows = []
self.bad_rows = [] # Quarantine
def detect_encoding(self):
# Use chardet on first N bytes
pass
def infer_schema(self, sample_size=1000):
# Read sample, determine types (int, float, date, string)
pass
def process(self):
# 1. Detect Encoding
# 2. Read file (iterator or chunks)
# 3. Validate against schema
# 4. Separate good/bad
pass
Detailed Logic for Validation:
If the inferred type is int64:
Check if value is numeric.
Check if it fits in the integer range.
If datetime:
Try parsing.
Quarantine Mechanism:
Ideally, we want to keep the original raw data for the bad rows so the user can see why it failed. We should append an error_message column to the bad rows.
Alternative: Pandas Type Enforcement
Pandas has a converters argument, but that raises errors.
A robust way is:
Read everything as str (dtype=str).
Analyze a sample to guess the intended schema.
Attempt to convert columns to intended types. Catch errors -> Quarantine.
Let's build a Python script.
I will provide a complete, copy-pasteable Python solution using pandas and chardet.
Key Components of the Solution:
Encoding Detection:chardet to find the likely encoding.
Schema Inference: Read a head sample to determine target types (Int, Float, Date, String).
Chunked Processing: Process the file in chunks (memory safety) and filter valid vs invalid rows.
Validation Logic: A function that tries to cast a value to the target type. Returns (success, converted_value) or (False, error_message).
Quarantine Output: Save the bad rows to a separate file with an error_reason column.
Refining the Validation Logic:
Simply doing pd.to_numeric on a column works for the whole column. If one fails, it returns NaN or raises.
To quarantine rows, we need row-level validation.
We can iterate through the dataframe df.apply(func, axis=1). This is slower but necessary for row-level quarantine. Or use pandas masks.
Masks approach:
Try to cast column A to int. If fails, mask those rows as "Bad".
Try to cast column B to date. If fails, mask those rows as "Bad".
Combine masks.
Separate DF into valid and invalid.
Problem: If casting fails, pandas usually puts NaN or forces object. We need to know which rows failed before casting.
Solution: Write a custom validation function that checks if a string can be parsed as the target type without actually changing the data frame yet, or using errors='coerce' and checking for nulls (if the original wasn't null).
Let's use the errors='coerce' strategy with a check:
Identify rows where value became NaN but wasn't originally NaN.
Mark these rows as "invalid".
Split chunk into valid_chunk and invalid_chunk.
Append invalid_chunk to quarantine.
Wait, strict type inference:
If the CSV has "1", "2", "A" in an integer column, pandas might just say "it's a string column".
We want to say: "Based on the first 100 rows, this looks like an Int column. Oh, row 101 has 'A', so row 101 is invalid."
This is the "Schema Drift" or "Bad Data" handling.
Final Code Plan:
detect_encoding(file_path)
infer_schema(file_path, encoding): Reads top N rows. Counts types. Assigns a "winner" type per column.
ingest(file_path, schema): Reads main file.
Check row by row (or vectorized if possible) against schema.
Include requirements.txt suggestions (pandas, chardet).
Handle memory efficiency (chunking).
Output to clean.csv and quarantine.csv.
Let's write the prompt response. I will structure it into: The Architecture/Philosophy, The Python Implementation, and Usage Example.
Self-Correction during thought process:
What if the encoding detection is wrong? The user should be able to pass a manual encoding. I'll add a fallback or override option.
What about Dates? ISO-8601 is standard. pandas handles it well. I will stick to standard types: Integer, Float, Boolean, Datetime, String.
Let's refine the validation step to be the core highlight.
Validation Function:
python
def validate_row(row, schema):
errors = []
for col, expected_type in schema.items():
val = row[col]
# logic to check if val matches expected_type
# if not: errors.append(f"Invalid {col}")
return errors
Using apply is slow but easiest to read and robust for mixed types in a single column (which is exactly what we are catching).
Okay, I have the plan. I will provide a robust Python script.
This is a comprehensive guide and a production-ready Python framework for safe CSV ingestion. It covers the four critical pillars you requested: Encoding handling, Schema inference, Type validation, and Quarantine.
The Architecture
Encoding Detection: Uses chardet to guess the file encoding, preventing UnicodeDecodeError.
Schema Inference (Training): Reads a sample of the data to determine data types (Int, Float, Date, String) and constraints (Nullable, Uniqueness).
Validation & Ingestion: Streams the file (to handle large files) and validates every cell against the inferred schema.
Quarantine: Bad rows are separated immediately and saved to a dedicated "quarantine" file with an added error_message column for debugging.
Prerequisites
You will need pandas for data manipulation and chardet for encoding detection.
bash
pip install pandas chardet
The Implementation
Here is the complete SafeCSVLoader class.
python
Breakdown of Features
1. Encoding Handling
The _detect_encoding method reads the first 10KB of the file in binary mode and uses chardet. This solves the common issue where a CSV created on Windows (often cp1252 or latin1) crashes a Python script expecting utf-8.
2. Schema Inference
Instead of relying on Pandas' default type inference (which can be memory-heavy or inconsistent with mixed types), the _infer_type logic checks a sample size. It attempts to cast data to the strictest type possible:
Integer (Is it a whole number?)
Float (Is it a number?)
Datetime (Is it a date?)
String (Fallback)
3. Type Validation (Strictness)
During the process phase, we do not simply load the file. We iterate row-by-row.
If a column is inferred as Integer, we try int(val).
If this fails (e.g., value is "Twelve"), we catch the ValueError.
This prevents "mixed type" columns in your final DataFrame, which cause crashes in SQL databases or downstream analytics.
4. Quarantine Strategy
If a row fails validation, it is not discarded. It is written to the quarantine file.
Crucially, we append a new column: ingestion_error_message.
This tells the data engineer exactly why the row was rejected (e.g., "Type error in 'age': Expected integer, got 'Twenty'").
This allows the "Good" file to be perfectly clean while preserving the data in the "Bad" file for manual cleaning or reprocessing later.
Why not just use pd.read_csv(..., error_bad_lines=False)?
Pandas' built-in error handling is limited:
It drops data silently or with minimal logging.
It does not easily allow you to capture validation errors (like a date format being wrong) vs structural errors (like a missing comma).
It often forces the entire column to become object (string) if there is one bad row, polluting your clean data with garbage types. The approach above enforces strict types for the clean dataset.
import pandas as pd
import chardet
import csv
import os
from datetime import datetime
from typing import Dict, List, Optional, Tuple, Any
class SafeCSVLoader:
def __init__(self, file_path: str, sample_size: int = 1000):
"""
Initialize the loader.
:param file_path: Path to the CSV file.
:param sample_size: Number of rows to use for inferring schema.
"""
self.file_path = file_path
self.sample_size = sample_size
self.encoding = None
self.schema = {} # Stores {column_name: expected_type}
def _detect_encoding(self) -> str:
"""Detects file encoding using chardet."""
print("Step 1: Detecting encoding...")
with open(self.file_path, 'rb') as f:
raw_data = f.read(10000) # Read first 10KB to guess encoding
result = chardet.detect(raw_data)
# Fallback to utf-8 if confidence is low, otherwise use detected
encoding = result['encoding'] if result['confidence'] > 0.7 else 'utf-8'
print(f"--> Detected encoding: {encoding} (Confidence: {result['confidence']:.2f})")
return encoding
def _infer_type(self, series: pd.Series) -> str:
"""Infer the logical data type of a pandas series."""
# Drop NaNs for type checking
s = series.dropna()
if s.empty:
return "string"
# Try Integer
try:
# Check if all values are effectively integers (even if parsed as float)
if pd.to_numeric(s, errors='coerce').notna().all():
if (pd.to_numeric(s) % 1 == 0).all():
return "integer"
except:
pass
# Try Float
try:
if pd.to_numeric(s, errors='coerce').notna().all():
return "float"
except:
pass
# Try Datetime (ISO 8601 common formats)
try:
# Coerce errors will turn invalid dates to NaT
if pd.to_datetime(s, errors='coerce').notna().sum() / len(s) > 0.8:
return "datetime"
except:
pass
return "string"
def infer_schema(self):
"""Reads a sample and determines column types."""
print("Step 2: Inferring schema from sample...")
self.encoding = self._detect_encoding()
try:
# Read sample using the detected encoding
df_sample = pd.read_csv(
self.file_path,
nrows=self.sample_size,
encoding=self.encoding,
sep=',',
engine='python'
)
except Exception as e:
raise ValueError(f"Failed to parse CSV with detected encoding {self.encoding}: {e}")
for col in df_sample.columns:
self.schema[col] = self._infer_type(df_sample[col])
print(f"--> Schema Inferred: {self.schema}")
def _validate_row(self, row: List[str], header: List[str]) -> Tuple[Dict[str, Any], Optional[str]]:
"""
Validates a single row against the schema.
Returns: (parsed_row_dict, error_message_or_None)
"""
parsed_row = {}
# Handle row length mismatch
if len(row) != len(header):
return {}, f"Column count mismatch. Expected {len(header)}, got {len(row)}."
errors = []
for i, col_name in enumerate(header):
raw_val = row[i]
expected_type = self.schema.get(col_name, "string")
# Handle Empty/Null
if raw_val is None or raw_val.strip() == '':
parsed_row[col_name] = None
continue
try:
# Type Coercion / Validation
if expected_type == "integer":
parsed_row[col_name] = int(float(raw_val)) # Handle "1.0" -> 1
elif expected_type == "float":
parsed_row[col_name] = float(raw_val)
elif expected_type == "datetime":
parsed_row[col_name] = pd.to_datetime(raw_val).isoformat()
else:
parsed_row[col_name] = str(raw_val)
except ValueError:
errors.append(f"Type error in '{col_name}': Expected {expected_type}, got '{raw_val}'")
except Exception as e:
errors.append(f"Parse error in '{col_name}': {str(e)}")
if errors:
return parsed_row, "; ".join(errors)
return parsed_row, None
def process(self, output_good: str, output_quarantine: str):
"""
Streams the file, validates rows, and splits into Good and Quarantine files.
"""
if not self.schema:
self.infer_schema()
print("Step 3: Processing and Validating Rows...")
good_rows_count = 0
bad_rows_count = 0
# Open output files
with open(self.file_path, 'r', encoding=self.encoding, newline='') as infile, \
open(output_good, 'w', newline='', encoding='utf-8') as f_good, \
open(output_quarantine, 'w', newline='', encoding='utf-8') as f_bad:
reader = csv.reader(infile)
# Setup Writers
header = next(reader) # Read original header
# Good file writer (Standard CSV)
writer_good = csv.DictWriter(f_good, fieldnames=header)
writer_good.writeheader()
# Bad file writer (Add error column)
bad_header = header + ["ingestion_error_message"]
writer_bad = csv.DictWriter(f_bad, fieldnames=bad_header)
writer_bad.writeheader()
# Process Rows
for row_num, row in enumerate(reader, start=2):
parsed, error = self._validate_row(row, header)
if error:
# Quarantine
bad_row_data = {header[i]: row[i] for i in range(len(row))}
bad_row_data["ingestion_error_message"] = error
writer_bad.writerow(bad_row_data)
bad_rows_count += 1
else:
# Ingest
writer_good.writerow(parsed)
good_rows_count += 1
if row_num % 10000 == 0:
print(f"Processed {row_num} rows...")
print("--------------------------------------------------")
print("Ingestion Complete.")
print(f"Valid Rows: {good_rows_count}")
print(f"Quarantined: {bad_rows_count}")
print(f"Output Files: '{output_good}', '{output_quarantine}'")
print("--------------------------------------------------")
# --- Usage Example ---
if __name__ == "__main__":
# Create a dummy dirty CSV for demonstration
dummy_file = "data_input.csv"
with open(dummy_file, "w", newline="") as f:
f.write("id,age,join_date,salary\n")
f.write("1,25,2023-01-01,50000.00\n") # Good
f.write("2,Twenty,2023-01-02,60000.00\n") # Bad age (Type error)
f.write("3,30,2023-01-03,NotANumber\n") # Bad salary (Type error)
f.write("4,22,2023-01-04,75000\n") # Good
f.write("5,40,InvalidDate,80000\n") # Bad Date
f.write("6,45,2023-01-06,90000\n") # Good
loader = SafeCSVLoader(dummy_file)
# This will generate 'clean_data.csv' and 'quarantine_data.csv'
loader.process("clean_data.csv", "quarantine_data.csv")