Skip to content
A small contract

Contracts & drift

A contract makes the assumptions about your data explicit. The cleaner can then check those assumptions on every transform and report drift instead of silently producing a different schema.

Python
from data_cleaner import CleanerConfig, ColumnSpec, DataCleaner, 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("email", role="text", pattern=r"[^@]+@[^@]+\.[^@]+"),
        ColumnSpec("notes", role="ignore"),
        ColumnSpec("coupon", role="category", required=False),
    ],
    strict=True,
)

cleaner = DataCleaner(CleanerConfig(contract=contract, on_drift="warn"))
cleaner.fit(X_train)

X_test_clean = cleaner.transform(X_test)
print(cleaner.drift_report())

The input frame is still cleaned. Drift is reported, not repaired.

Every declared column is required by default. When you pass an explicit contract to :class:DataCleaner, fit() checks the training frame before learning anything and raises ValueError if a required column is missing:

Output
Training data is missing required contract columns: ['customer_id'].
Add them to the training frame or set required=False on the column spec.

This catches a broken training schema immediately instead of surfacing it later as a drift warning. Two cases are always allowed to be absent:

  • ColumnSpec(..., required=False) marks an optional column.
  • ColumnSpec(..., role="ignore") marks a column the cleaner drops anyway.

An inferred contract never needs this check because it is built from the columns that are present. Optional columns that are present during fit() become part of the learned schema and are required at transform() time, like any other learned column.

RoleMeaning
numericA measurement; numeric coercion, imputation, and outlier capping
categoryA categorical value; mode/constant imputation and unseen policy
booleanA boolean value; boolean coercion and imputation
datetimeA timestamp; parsed and expanded into calendar features
idAn identifier; treated as text, never numeric-imputed or capped
textFree text; treated as categorical text and protected from unseen replacement
ignoreDropped from the output and skipped by contract checks

None means “infer from the dtype.” Roles accept common aliases such as measure, categorical, string, bool, date, identifier, and drop.

FieldDefaultPurpose
namerequiredColumn name
roleNoneSemantic role from the table above
dtypeNoneBroad kind or exact dtype to expect
requiredTrueWhether the column must be present in the training frame
nullableTrueWhether missing values are allowed
uniqueFalseWhether non-null values must be unique
allowed_valuesNoneAllowed category values
min_valueNoneInclusive lower bound for numeric values
max_valueNoneInclusive upper bound for numeric values
patternNoneFull-match regular expression for string values
date_formatNoneOptional date format hint
preserve_leading_zerosFalseKeep identifier values as strings
severity"error"Severity of this spec’s contract findings

CheckSeverityTrigger
missing_columnspec severityA required declared column is absent
unexpected_columnwarningstrict=True and the frame has an undeclared column
dtype_changespec severityThe column’s broad kind changed
unexpected_missingspec severityA non-nullable column has missing values
unexpected_categoryspec severityA value falls outside allowed_values
value_out_of_rangespec severityA numeric value falls outside the declared bounds
pattern_mismatchspec severityA string does not fully match pattern
duplicate_valuesspec severityunique=True and duplicate non-null values exist

Identifier and text columns are allowed to arrive as either numeric-looking or object dtype; that is not reported as dtype_change.

Python
CleanerConfig(on_drift="warn")
ValueBehavior
"warn"Log the report and continue (default)
"raise"Raise ValueError when any error-severity finding exists
"ignore"Record findings in drift_report() without logging

Missing fitted input columns are always fatal, regardless of on_drift. The cleaner learned parameters for those columns and cannot safely reconstruct them, so transform() raises instead of silently producing a different feature set. The drift policy governs other findings such as extra columns, dtype changes, categories, and ranges.

Python
report = cleaner.drift_report()

if not report.empty:
    print(report[["column", "check", "severity", "message"]])

DriftReport exposes findings, has_drift, errors, warnings, summary(), to_markdown(), and raise_if_invalid().

If you do not pass a contract and infer_contract=True (the default), the cleaner infers a conservative contract from the training schema:

Python
cleaner = DataCleaner()
cleaner.fit(X_train)

contract = cleaner.fitted_contract()

You can also infer one explicitly:

Python
contract = DataContract.from_frame(X_train, strict=True)

Inference captures column names, broad kinds, and nullability. Add explicit specs when you need allowed values, ranges, patterns, or uniqueness checks.

DataContract.validate() returns the same report type used by the expectations API:

Python
result = contract.validate(X_new)

result.success
result.failures
result.to_markdown()
result.raise_if_failed()

Use contract.check(X_new) when you specifically want the DriftReport with its expected / actual columns.

Contracts are JSON-serializable and can be versioned with the model:

Python
payload = contract.to_json()
restored = DataContract.from_json(payload)

YAML support is optional and requires pyyaml:

Terminal
pip install pyyaml
Python
contract.to_yaml()
DataContract.from_yaml(payload)

Store the contract next to the fitted cleaner so training and serving agree on roles, bounds, and allowed values.

  • Set on_drift="raise" when an unexpected schema change should stop the job.
  • Use role="id" for identifiers so they are never treated as measurements.
  • Use role="ignore" for operational columns you do not want in the output.
  • Keep strict=False if upstream systems may add harmless columns; otherwise strict=True surfaces them as warnings.
  • Prefer explicit specs for anything a model depends on: ranges, categories, regexes, and uniqueness.