Changelog
All notable changes to this project are documented here.
The format follows Keep a Changelog and the project uses Semantic Versioning.
- The documentation site is now the
docs/generator, published at the repository root. The MkDocs site underdocs/andmkdocs.ymlare retired. The API reference is generated from the package docstrings at build time.
DriftPolicy,DriftProfile,DistributionDriftReport, andcompare_distributions()add reference-versus-current statistical drift. Reports cover PSI over reference quantile bins, an approximate 1-D Wasserstein distance from bounded reference quantiles plus a scale-free ratio, missingness deltas, category share deltas, and anotherbucket for levels outside the retained reference categories. Numeric and datetime columns are supported; booleans compare as categorical.DriftPolicydocuments and validates thresholds: PSI0.10/0.25, a5percentage-point missingness warning, a10percentage-point category warning, an optional Wasserstein ratio threshold, andmin_sample=20, which downgrades errors to warnings on small batches. Thresholds must be finite and non-negative and counts must be integers; policies serialize to and from JSON.DriftProfile.from_frame()stores a bounded, JSON-serializable reference summary (bin edges, shares, scales, exactly 512 midpoint quantiles per numeric column, and the top 20 category levels per categorical column), so the same reference can be reused or persisted without retaining a sorted column.to_json()/from_json()round-trip the profile and its policy, and the defaultrepris redacted.data_cleaner.rulesadds composable validation rules:col()conditions with explicit.eq,.ne,.lt,.le,.gt,.ge,.isin,.not_in,.between,.isna,.notna, and.matchesmethods;&,|, and~composition;row_rule()for cross-column predicates;conditional()for scoped rules;grouped()for per-group checks;unique_combination()for multi-key uniqueness; andsum_equals()for arithmetic consistency. Comparisons skip missing operands, so nulls do not fail a predicate unless it asks for them with.isna().Validatableis the public protocol behindvalidate().validate()accepts expectations, rules, custom objects withname,column,severity, andcheck(frame), and mixed lists. A custom rule may return severalValidationResultobjects from one check.ValidationReport.diagnose(frame, limit=5, include_values=False, include_index=True, max_value_length=32)samples failing rows withRowDiagnostics: bounded per failing rule, no cell values by default, truncated values when enabled, index labels optionally omitted, and only failing frame-level or grouped rules listed inskipped.JsonlReportSinkappendsCleanerReport,DistributionDriftReport, or mapping records to a JSON Lines file, reads them back in order, summarizes batch history, and exposesdrift_against_previous(), which reuses the stored reference profile and policy for a reproducible historical comparison.history()andlatest(kind=..., source=...)query the audit trail.
ValidationReportgainssourcesandfrom_results(..., sources=...)so diagnostics can attribute failures. Reports built from contract findings have no sources and produce an empty diagnostic sample.- JSON-safe conversion is shared by reporting, drift, and sinks. Drift profiles and reports now serialize NaN and infinity as
nulland leak no non-standard JSON literals. DriftProfilerequires a non-empty reference and current frame with unique string column labels, reports missing or kind-changed columns as errors with metrics skipped, and never mutates the caller’s frames.sum_equals()now fails rows with present non-numeric components or targets instead of silently skipping them, andJsonlReportSinkreads records withsplit("\n")so Unicode line separators in metadata cannot corrupt history.
- New Statistical drift guide covering policy, thresholds, profiles, report fields, batch history, privacy, and scope.
- Validation, joins & dedup documents the rule layer, the custom validation protocol, and row diagnostics.
DataCleaner.transform_chunks(chunks)streams an iterable of DataFrames and yields(cleaned_chunk, DriftReport)without touching shared instance state, keeping one chunk in memory at a time. A bare DataFrame is rejected.combine_drift_reports(reports)rolls per-chunk reports into aTransformReportwith summed rows, chunk count, and concatenated findings.TransformReportexposes the samehas_drift,errors,warnings,summary(), andraise_if_errors()surface asDriftReport.DriftReport.rowsrecords the batch size, so aggregated reports can report a run-level row count without retaining cleaned frames.read_parquet_safe()anditer_parquet_safe()add optional Parquet ingestion through PyArrow, with the same contract-driven audit, cross-batch uniqueness tracking, and report aggregation as the CSV readers. Install theparquetextra.- A reproducible benchmark suite (
benchmarks/run_benchmarks.py) measures ingestion, fit, transform, chunked transform, reporting, and validation at 100K, 1M, and 2M rows across narrow, wide, and high-cardinality frames. Runtime and peak memory are measured separately, and each case runs in a fresh subprocess. docs/content/performance.mddocuments the methodology, measured results, supported workload, and chunked workflow.
transform()no longer deep-copies the input frame. The cleaner never mutates the caller’s data, so the copy was unnecessary; removing it lowers peak memory on large batches.transform()skips redundant column selection and reindexing when the input already matches the fitted schema.- CI runs the benchmark smoke matrix, so the suite cannot silently rot.
DataCleaner.transform_with_report(X)returns(cleaned_frame, drift_report)for one batch and does not read or write the shareddrift_report_state, so a fitted cleaner can safely serve concurrent batches.transform()remains backward compatible and documentsdrift_report_as last-call state.CleanerConfig.preserve_integer_dtypes(defaultTrue) keeps integral numeric columns asint64after imputation and clipping when the learned fill value and outlier bounds are integral. Otherwise the column falls back tofloat64and logs the fallback.CleanerConfig.on_precision_lossselects"coerce"(default),"warn", or"raise"whenfloat64cannot represent an integer exactly. Detection is exact at the2^53boundary rather than a blanket threshold.iter_csv_safe()gainedunique_tracking("memory","disk", or"auto"),unique_tracking_limit, andunique_tracking_path. Disk tracking uses a temporary SQLite database, and"auto"migrates from memory once the limit is exceeded.combine_ingestion_reports(reports, source=None)rolls per-chunk reports into one whole-file report with the summed row count and concatenated findings.DataCleaner.load(..., strict_environment=True)raisesArtifactCompatibilityErrorwhen the recorded pandas, NumPy, or scikit-learn major version differs from the current runtime. The default logs a warning.
DataCleaner.save()now writes to a temporary file, validates the written artifact, and atomically replaces the target withos.replace. A failed or interrupted save keeps the previous artifact and removes partial files.DataCleaner.load()wraps unreadable artifacts in aValueErrorwith the underlying cause instead of leaking an arbitrary unpickling exception.
- Integer columns are no longer silently rounded through
float64during cleaning. Values above2^53are preserved exactly by default. - Cross-chunk uniqueness tracking no longer stores an ever-growing pandas index per column; the default
"auto"mode is bounded and switches to disk.
- CI now tests the minimum supported dependency versions on Python 3.10, the latest stable dependency set, and pandas 3.x.
- CI installs the built wheel in a clean environment and checks imports, public exports, the CLI, and a small end-to-end cleaning workflow.
- Release builds generate PEP 740 attestations for PyPI and GitHub build-provenance attestations, so published artifacts can be verified against the workflow that built them.
iter_csv_safe()now infers the schema from the first chunk and reuses it for every later chunk. A later value that does not fit the inferred type is reported asunparseable_valuesinstead of silently changing the column dtype. Pass an explicit contract when the first chunk may not be representative.- Safe ingestion now enforces
ColumnSpec(unique=True)and reportsduplicate_values. Duplicates are detected within a frame and, foriter_csv_safe(), across chunks. Missing values are ignored. DataContract.check()now ignores missing values forunique=True, matching the documented “non-null values must be unique” behavior and the validation helper.DataCleaner.transform()now states that a missing fitted input column is always fatal, regardless ofon_drift, because the cleaner cannot safely reconstruct it. The documentation matches the behavior.
2.9.1is the first release built with the attestation workflow. Verify its provenance with the commands in the production guide;2.9.0predates the workflow and has no PyPI provenance.
ColumnSpec(required=...)marks a contract column as required or optional.ArtifactCompatibilityErroris raised byDataCleaner.load()when a saved artifact has an incompatible artifact format or library major version.allow_incompatible=Trueloads it with a warning, andverify_version=Falseskips the check entirely. The docs now state the pickle trust boundary.iter_csv_safe()streams a large CSV in typed chunks and yields one(frame, IngestionReport)pair per chunk, using bounded memory.CleanerConfig.outlier_columnsnames the numeric columns that may be capped. When set it acts as an allowlist and overridescap_outliers.read_csv_safe()emits aninteger_precisionwarning for integer values beyond2^53that are coerced tofloat64, because they may already have lost precision.
- Contracts:
DataCleaner.fit()now validates an explicit contract before learning and raisesValueErrorwhen a required training column is missing, instead of deferring the failure totransform(). Columns withrequired=Falseorrole="ignore"may be absent. diagnose_join()now computes matched and unmatched rows from grouped key frequencies, so duplicated keys no longer expand into a many-to-many join or risk exhausting memory. Reported row counts are unchanged.- Outlier clipping is now opt-in:
CleanerConfig.cap_outliersdefaults toFalse. Set it toTrue, or listoutlier_columns, to keep the previous clipping behavior. - CSV ingestion now normalizes blank cells in place instead of copying the whole frame, reducing peak memory for large inputs.
- Docs: the public API is documented in stable, experimental, and internal tiers with a deprecation policy.
data_cleaner.__all__is the canonical surface. - Docs: refined the documentation site chrome with a light header, quieter navigation and active states, a calmer type scale, and consistent spacing, radii, and motion. The “Where to go next” and “Documentation map” sections now render as one joined, rounded table with aligned columns and link-only hover.
read_excel_safe(): read one Excel worksheet as values, normalize every cell to text, apply the same contract-driven guards asread_csv_safe(), and return the typed frame with anIngestionReport.- Worksheet selection with
sheet_name, accepting either a name or a zero-based index. The resolved sheet is recorded onIngestionReport.sheet. CleanerReport.from_excel(): attach Excel ingestion findings to the same profile, contract, validation, and decision report as CSV input.read_excel_safe()keeps native cell types long enough to detect numeric IDs, then applies per-cell date guards, so a column can mix real dates,YYYYMMDDtext, and Excel serials.- Worksheet selection is by name or non-negative zero-based index; duplicate headers after string conversion are rejected rather than collapsed.
data-cleaner auditnow detects.xlsx,.xlsm,.xls,.xlsb, and.odsinput and accepts--sheet NAMEor--sheet-index N.numeric_identifierwarning when a contract ID column is stored as numbers in the spreadsheet and has already lost its leading zeros.- Optional
excelextra (openpyxl>=3.1) for.xlsxand.xlsmworkbooks.read_csv_safe()remains dependency-free. - Docs: Excel sections across the ingestion, reporting, quickstart, production, and API guides.
IngestionReportgains asheetfield (defaultNone) and includes it into_dict().to_markdown()now names the source and sheet.IngestionReport.locationcombines the source and resolved sheet, and both warning logs andIngestionErrormessages use it.- URL-shaped source labels are stored without credentials or query strings, so signed or authenticated URLs do not leak into reports or logs.
- Undeclared-column findings now say the column was typed by inference and point to the detected/output kinds in
report.columns, rather than claiming the column was kept as text. IngestionReport.raise_if_failed()defaults to the format-neutral message"Ingestion failed". The exception raised byread_csv_safe()still names CSV.
- The artifact format remains
2; this release is additive. - Real Excel date cells are parsed directly. Numbers in a datetime column are treated as Excel serial dates and flagged with
excel_serial_date. - Excel cannot preserve leading zeros in a cell stored as a number. The reader warns with
numeric_identifier, but store identifiers as text to avoid the loss in the first place. .xls,.xlsb, and.odsfiles need the matching pandas engine (xlrd,pyxlsb, orodfpy); theexcelextra covers.xlsxand.xlsm.
CleanerReport: one review object per batch combining the dataset profile, contract drift, validation results, ingestion findings, and the fitted cleaner’s decision log.CleanerReport.from_frame(),from_csv(), andfrom_cleaner()entry points. None of them transform the input frame or re-fit the cleaner.- A tidy
findingstable withsource,column,check,severity,message, andcount, pluserrors,warnings,success,summary(),to_markdown(),to_dict(),to_json(), andraise_if_failed(). - Profile warnings for empty datasets, empty columns, constant columns, high missingness (configurable via
high_missing_threshold), and duplicate rows. python -m data_cleaner audit data.csvand thedata-cleanerconsole script, with--contract,--cleaner,--name,--format markdown|json,--output,--no-profile, and--fail-on-warning.- Stable CLI exit codes:
0success,1error findings (or warnings with--fail-on-warning),2input or configuration errors. - Docs: batch reporting guide and cross-links from ingestion, quickstart, and the production guide.
- None. Tier 6 is additive and the artifact format remains
2.
CleanerReport.from_csv()defaults toon_error="ignore"so a report is always returned; error-severity findings still makesuccessfalse.- Reports contain column names, counts, and messages only; they never include raw cell values, so they are safe to log or attach to an artifact.
- The CLI reads with
on_error="ignore"and derives failure from the report instead of raising during ingestion.
read_csv_safe(): string-first CSV ingestion with contract-driven coercion and anIngestionReportcovering per-column detection, output dtypes, missing counts, and every normalization performed.- Identifier protection: ID columns and values with leading zeros stay text, and the report records
leading_zeros_preserved. - Spreadsheet artifact handling for numeric fields: thousands separators, currency symbols, percent signs, accounting parentheses, and decimal commas are normalized with one finding per transformation.
- Date guards for compact
YYYYMMDDvalues and Excel serial dates when the contract declaresrole="datetime", plus explicitdate_formatsupport and anambiguous_date_formatwarning for day/month ambiguity. - Boolean normalization for Y/N-style tokens with
boolean_tokensfindings. IngestionErrorand theon_error="warn" | "raise" | "ignore"policy. Error findings make the report fail without hiding the frame when policy is"warn".mixed_typesandempty_columnfindings; mixed columns stay text instead of silently losing values.- Docs: safe ingestion guide and an Upcoming page for release planning.
- None. Tier 5 is additive and the artifact format remains
2.
- The ingestion report contains column names, counts, and messages only; it never includes raw cell values, so it is safe to log or attach to an artifact.
- Without a contract,
YYYYMMDDand Excel serial values remain numeric. Declare a datetime role when they are dates. - CSV is the supported input for this release; the report model is designed to extend to other tabular readers later.
- Make the documentation site the single source of truth. The README is now a concise entry point with install, quick start, and a guide index.
- Add artifacts/reproducibility and production guides to the docs site.
- Documentation-only release; no runtime behavior changes and the artifact format remains
2.
- Add a MkDocs Material documentation site with task guides, an API reference, and GitHub Pages deployment.
- Expose the documentation site in the package project URLs and README so PyPI and GitHub point to the same central reference.
- Documentation-only release; no runtime behavior changes and the artifact format remains
2.
audit_split()andSplitAudit: a pure-function train/test split audit that reports exact duplicate overlap, near-duplicate overlap, group leakage, temporal leakage, target-leakage heuristics, constant and near-constant columns, high-cardinality identifiers, missingness shift, numeric and categorical distribution shift, unseen target classes, and target shift.- Findings carry a
check,column,severity,message, and train/test values. Schema problems, empty splits, exact duplicates, group leakage, temporal leakage, and unparseable or numeric timestamps are errors; statistical and heuristic checks are warnings. High-cardinality declared identifiers are reported separately ashigh_cardinality_identifier. SplitAuditexposesfindings,valid,errors,warnings,summary(),to_markdown(),to_dict(), andraise_if_invalid().- Findings never include raw cell values; messages contain column names, counts, rates, and statistics only.
- None. Tier 4 is additive and the artifact format remains
2.
- The audit never mutates inputs, never fits anything, and never repairs a split. Duplicate checks exclude declared
id_colsandtime_col. - Near-duplicates use a deterministic rounded-feature hash rather than a nearest-neighbour search, so the result is reproducible without extra dependencies. Exact duplicate hashing is dtype-independent, so
1and1.0compare equal while object numbers and strings stay distinct. groupsmay cover both splits or training rows only whengroups_testis supplied.
- Lightweight expectations API:
not_null(),unique(),in_set(),between(),matches_pattern(),has_dtype(), androw_count_between(), plusExpectation,ValidationResult,ValidationReport, andvalidate(). Reports exposesuccess,results,failures,to_markdown(), andraise_if_failed(). DataContract.from_frame()andDataContract.validate();Contractis a shorthand alias forDataContract.diagnose_join()andJoinDiagnosis: left/right duplicate keys, cardinality class, output row multiplier, unmatched counts, null keys, warnings, andraise_if_unsafe().check_referential_integrity()andReferentialIntegrityReport: orphan rows and keys, null keys, duplicate parent keys, andraise_if_invalid().deduplicate_by_business_key()andDeduplicationReport: audited removal with the actual removed rows, duplicate-key counts, null-key warnings, and tie-breaker details.
- None. Tier 3 is additive and the artifact format remains
2.
- All new helpers are pure functions: they never mutate their inputs and do not require fitting.
ValidationReport.successignores warning-severity failures;raise_if_failed()raises only for error-severity failures.
CleaningDecisionandDataCleaner.decision_log(): a tidy audit trail of every learned or configured cleaning decision (column,action,reason,source,before,after).DataCleaner.to_manifest()andartifact_manifest(): JSON-serializable manifests with library/artifact versions, Python/pandas/numpy/scikit-learn versions, config, contract, input schema, output columns, fit summary, decisions, and an optional data fingerprint.fingerprint_dataframe(),compare_fingerprints(), andassert_schema_stable(): stable SHA-256 fingerprints of schema plus summary statistics for lineage checks. Raw values are never hashed.DataCleaner.fingerprint(X)for on-demand fingerprints andCleanerConfig.fingerprint_on_fitto compute the training fingerprint duringfit().
save()now embeds the manifest and fingerprint in the artifact;load()restores them and warns when an artifact predates audit metadata.- Older artifacts are backfilled on load:
decision_log()returns an empty, correctly-shaped DataFrame instead of failing. - Artifact format version bumped to
2.
- Fully backwards compatible: existing configuration, public imports, and v2.0.0–v2.2.0 joblib artifacts continue to work.
- Typed public package: the library now ships as
src/data_cleaner/with a PEP 561py.typedmarker, so type checkers and IDEs pick up the annotations. - Continuous integration now runs
ruff(lint + format),mypy(type checking), and the test matrix on Python 3.10–3.13, plus a build/twine checkjob. pre-commitconfiguration for local linting, formatting, and type checking.- A cross-version artifact compatibility test that reproduces the pre-package (flat module) pickle layout and verifies the artifact still loads and cleans.
- Internal structure split from a single module into a package (
_version,_roles,contract,config,cleaner,profiling). The public API andimport data_cleanerare unchanged. - Project tooling now enforces linting, formatting, and typing on every change.
- Fully backwards compatible:
import data_cleanerand all public names are re-exported from the package root, and v2.0.0/v2.1.0 joblib artifacts still load.
ColumnSpecfor declarative per-column expectations: role, dtype kind, nullability, uniqueness, allowed values, numeric range, regex pattern, date format, leading-zero preservation, and severity.DataContractfor grouping column specs, withinfer_from(),check()/diff(), andto_dict()/from_dict()/to_json()/from_json()serialization. Optionalto_yaml()/from_yaml()when PyYAML is installed.DriftReportwithhas_drift,errors,warnings,summary(),to_markdown(), andraise_if_errors().- Transform-time schema/type/nullability/range/category drift detection, available through
DataCleaner.drift_report(). - Semantic roles, including
idandtextcolumns that are never numeric coerced, median-imputed, or IQR-capped, andignorecolumns that are dropped. CleanerConfig.contract,CleanerConfig.on_drift(raise/warn/ignore), andCleanerConfig.infer_contractto control drift handling.DataCleaner.fitted_contract()to inspect the contract in use.
transform()now records a drift report and applies the configuredon_driftpolicy. Conservative contracts are inferred automatically from the training schema by default, so drift is reported without any configuration.- Missing required columns raise a
ValueErrorthat includes drift details.
- Fully backwards compatible: existing
CleanerConfig/DataCleanerusage and v2.0.0 joblib artifacts continue to work. All new behavior is opt-in except drift reporting, which only logs by default.
CleanerConfigfor explicit, validated cleaning configuration.DataCleanertransformer with scikit-learncloneandPipelinesupport.- Train-only learning for numeric imputation, categorical modes, and IQR outlier bounds.
- Numeric coercion for dirty string columns.
- Boolean and datetime handling, including configurable calendar features.
- Optional missing-value indicator columns.
- Optional constant-column removal.
- Unseen-category policy: keep or replace.
- Stable output schema and column ordering.
cleaning_summary()andoutlier_summary()audit helpers.- Joblib
save()/load()with artifact version metadata. profile_dataframe,dataset_summary,drop_duplicate_rows, andassert_frame_cleanutilities.- End-to-end notebook with a leak-safe train/test workflow.
- Unit and integration test suite.
- uv-managed packaging, development dependencies, and CI workflow.
[2.1.0]: https://github.com/devlprkhan/universal-data-cleaner/releases/tag/v2.1.0 [2.0.0]: https://github.com/devlprkhan/universal-data-cleaner/releases/tag/v2.0.0