Skip to content
The short checklist

Production guide

A cleaner that works in a notebook can still fail in production. This page is the deployment checklist: what to fit, what to store, and what to check on every batch.

  1. Split the data before fitting anything.
  2. Audit the split for leakage.
  3. Fit the cleaner on X_train only.
  4. Save the cleaner, contract, and manifest together.
  5. Load the same artifact for test and production batches.
  6. Audit, transform, validate, and monitor drift on every batch.
Python
from data_cleaner import audit_split

audit = audit_split(
    X_train,
    X_test,
    y_train,
    y_test,
    groups=groups,
    time_col="event_time",
    id_cols=["customer_id"],
)

audit.raise_if_invalid()

cleaner = DataCleaner(config).fit(X_train)
cleaner.save("artifacts/data_cleaner.joblib")

The defaults are designed to keep pipelines running. In production, choose the stricter options where a silent change is worse than a failed job.

Python
from data_cleaner import CleanerConfig, ColumnSpec, DataContract

contract = DataContract(
    columns=[
        ColumnSpec("customer_id", role="id"),
        ColumnSpec("age", role="numeric", min_value=0, max_value=120),
        ColumnSpec("plan", role="category", allowed_values=("free", "pro", "team")),
        ColumnSpec("notes", role="text"),
        ColumnSpec("internal_flag", role="ignore"),
    ],
    strict=True,
)

config = CleanerConfig(
    contract=contract,
    on_drift="raise",
    unseen_category="keep",
    add_missing_indicators=True,
    drop_constant_columns=True,
)
SettingProduction recommendation
on_drift"raise" when schema changes should stop the job
contractDeclare roles, ranges, categories, and uniqueness explicitly
unseen_category"keep" for handle_unknown="ignore" encoders; "fill" if downstream must see a known label
add_missing_indicatorsTrue when missingness itself is predictive
drop_constant_columnsKeep True unless a downstream component requires the column
cap_outliersFalse by default; enable it or list outlier_columns only when clipping extremes is intended

Read CSV or Excel input through the contract instead of letting pandas infer types independently on every run:

Python
from data_cleaner import read_csv_safe, read_excel_safe

X_batch, ingestion = read_csv_safe(
    "incoming.csv",
    contract=contract,
    on_error="raise",
)

# Or, with the optional `excel` extra:
X_batch, ingestion = read_excel_safe(
    "incoming.xlsx",
    contract=contract,
    sheet_name="Orders",
    on_error="raise",
)

if not ingestion.success:
    raise RuntimeError(ingestion.summary())

on_error="raise" fails before the model sees an unparseable ID, date, or boolean. Contract unique=True columns are checked within the frame, and iter_csv_safe() checks them across chunks. The report records normalization counts without logging raw cell values. See Safe ingestion for the policy and guardrails.

The most important production rule is also the simplest:

Python
# Once, on training data.
cleaner = DataCleaner(config).fit(X_train)

# Everywhere else, reuse the fitted object or load the saved artifact.
X_test_clean = cleaner.transform(X_test)
X_prod_clean = cleaner.transform(X_prod)

Do not:

  • fit before the train/test split
  • fit a second cleaner on test or production data
  • recompute medians, modes, or outlier bounds in a serving function
  • pass the target column to the cleaner

Identifiers are not measurements. Declare them so they are never numeric-imputed, outlier-capped, or stripped of leading zeros:

Python
ColumnSpec("customer_id", role="id", preserve_leading_zeros=True)

Use role="text" for free-text fields and role="ignore" for operational columns that should not reach the model. See Contracts & drift for the full role reference.

Python
from data_cleaner import DataCleaner

X_batch_clean, report = cleaner.transform_with_report(X_batch)

if report.has_drift:
    print(report.findings[["column", "check", "severity", "message"]])

transform_with_report() returns the cleaned frame and its drift report together. It does not read or write shared instance state, so one fitted cleaner can service concurrent batches safely.

cleaner.transform(X_batch) remains available for existing pipelines. It stores the findings from its most recent call in drift_report_ for backward compatibility. Treat that attribute as per-instance last-call state: two concurrent transform() calls can overwrite each other’s report, even though the returned frames are independent.

With on_drift="raise", error-severity findings stop the batch before the model sees malformed data. With on_drift="warn", the report is logged and cleaning continues. A missing fitted input column is always fatal, regardless of the policy: the cleaner cannot safely reconstruct the learned parameters for a column that is absent.

Drift is only one signal. CleanerReport combines the profile, contract, validation, ingestion, and the fitted cleaner’s decisions into one review object:

Python
from data_cleaner import CleanerReport

report = CleanerReport.from_cleaner(
    cleaner,
    X_batch,
    source="production",
    ingestion=ingestion,
)
report.raise_if_failed("Batch rejected")

if report.has_warnings:
    logger.warning(report.summary())

In a deploy or scheduled job, run the CLI and let the exit code gate the batch:

Terminal
python -m data_cleaner audit incoming.csv \
  --cleaner artifacts/data_cleaner.joblib \
  --format json \
  --output artifacts/audit.json \
  --fail-on-warning

0 means the batch passed, 1 means error findings (or warnings with --fail-on-warning), and 2 means the input or artifact could not be read. See Batch reporting for all options.

artifacts/branchdata_cleaner.joblibbranchcontract.jsonbranchmanifest.json
Python
from pathlib import Path

cleaner.save("artifacts/data_cleaner.joblib")
Path("artifacts/contract.json").write_text(contract.to_json())
manifest = cleaner.to_manifest(X_train, include_fingerprint=True)

See Artifacts & reproducibility for the manifest and fingerprint details.

A final guard catches values that survived cleaning:

Python
from data_cleaner import assert_frame_clean

X_batch_clean = cleaner.transform(X_batch)
assert_frame_clean(X_batch_clean)

assert_frame_clean() raises when the output still contains missing or infinite values. Run it in tests and in a pre-model validation step.

For batch files that do not fit in memory, stream chunks and aggregate the reports rather than the frames:

Python
from data_cleaner import combine_drift_reports, combine_ingestion_reports, iter_csv_safe

ingestion_reports = []
drift_reports = []
for chunk, ingestion_report in iter_csv_safe(
    "incoming.csv", contract=contract, chunksize=100_000
):
    ingestion_reports.append(ingestion_report)
    cleaned, drift = cleaner.transform_with_report(chunk)
    drift_reports.append(drift)
    write_batch(cleaned)

ingestion = combine_ingestion_reports(ingestion_reports)
transform = combine_drift_reports(drift_reports)
ingestion.raise_if_failed()
transform.raise_if_errors()

transform_chunks() wraps the same loop. The aggregated TransformReport holds findings and row counts, not the cleaned data, so its size depends on the number of findings rather than the file size. See Performance and large data for measured behavior and the supported workload.

SymptomLikely causeFix
Required column missingUpstream schema changedRestore the column; a missing fitted column is always fatal. Use a contract + on_drift="raise" for other drift
IDs gained .0 or lost zerosID was treated as numericColumnSpec(..., role="id") and read_csv_safe()
Excel IDs lost leading zerosCell was stored as a numberStore IDs as text; read_excel_safe() reports numeric_identifier
Currency or percent strings stayed textSpreadsheet formatting leaked into the fileread_csv_safe() / read_excel_safe() and a numeric ColumnSpec
Category exploded into rare labelsUnseen values keptunseen_category="fill" or encoder handle_unknown
Scores dropped after deployDifferent imputation or boundsReuse the saved fitted cleaner
Dates disappearedDatetime column not declaredAdd it to datetime_columns
Constant feature reached the modelConstant dropping disableddrop_constant_columns=True
Batch rows vanishedLeakage bug or bad joinAudit the join and the split

Release builds attach PEP 740 provenance to each PyPI artifact, signed through the publish.yml workflow with GitHub OIDC. Verify a downloaded package against the source repository:

Terminal
uvx "pypi-attestations==0.0.31" verify pypi \
  --repository https://github.com/devlprkhan/universal-data-cleaner \
  pypi:universal_data_cleaner-<version>-py3-none-any.whl

GitHub also stores a build-provenance attestation for the same artifacts under the repository’s Attestations tab. Check it with the GitHub CLI:

Terminal
gh attestation verify universal_data_cleaner-<version>-py3-none-any.whl \
  --repo devlprkhan/universal-data-cleaner

Repeat both commands for the .tar.gz source distribution. Then confirm a clean install from PyPI works:

Terminal
uv venv /tmp/udc-check
uv pip install --python /tmp/udc-check/bin/python universal-data-cleaner==<version>
/tmp/udc-check/bin/data-cleaner --version

the repository. The workflow refuses to publish if the .publish.attestation files are missing.

Run these checks after every publication. 2.9.0 predates the attestation workflow, so its artifacts have no provenance. 2.9.1 is the first release with verified PyPI and GitHub provenance.