From 47115154f5b56fad4ac3441a6676527c172ae935 Mon Sep 17 00:00:00 2001 From: Johnny Wilson Dougherty Date: Sat, 28 Nov 2026 16:48:45 +0530 Subject: [PATCH 1/3] style: fix the 112 ruff errors that block the release quality gate release.yml runs `ruff check .` before it builds. On main that step fails with 112 errors, so no release can pass it. - `ruff check --fix`, then `--unsafe-fixes`. The unsafe fixes here keep behavior: `int(round(x))` to `round(x)`, `zip(..., strict=False)`, and `_` prefixes on unused unpacked names. - Hand fixes for the last 20: ClassVar annotations, loop variables bound in benchmark lambdas, an en dash, and `pytest.raises(FrozenInstanceError)` in place of `pytest.raises(Exception)`. - examples/ may use scikit-learn's `X` name (N803, N806). No change to src/ behavior. mypy is clean. The suite passes. --- benchmarks/baselines/__init__.py | 4 +-- benchmarks/bench_outofcore.py | 2 +- benchmarks/bench_v3_lazy_vs_pandas.py | 1 + benchmarks/fixtures/__init__.py | 8 +++--- benchmarks/fixtures/_common.py | 4 +-- benchmarks/fixtures/crm.py | 4 +-- benchmarks/fixtures/finance.py | 2 +- benchmarks/fixtures/gold.py | 2 +- benchmarks/fixtures/wide_schema.py | 2 +- benchmarks/performance/__init__.py | 2 +- benchmarks/performance/baselines.py | 5 ++-- benchmarks/performance/environment.py | 2 +- benchmarks/performance/instrumentation.py | 5 ++-- benchmarks/performance/memory.py | 2 +- benchmarks/performance/models.py | 4 +-- benchmarks/performance/render.py | 2 +- benchmarks/performance/schema.py | 2 +- benchmarks/performance/worker.py | 2 +- benchmarks/run_ground_truth_bench.py | 8 ++---- benchmarks/run_scale_profile.py | 11 ++++---- examples/01_csv_cleaning.py | 2 +- examples/04_outlier_handling.py | 4 +-- examples/10_pyjanitor_interop.py | 2 +- examples/11_great_expectations_recipe.py | 2 +- examples/document_provenance.py | 2 +- .../custom_comparator/initials_comparator.py | 2 +- pyproject.toml | 4 +++ scripts/automate_freshdata.py | 2 +- scripts/debug_50_datasets.py | 5 ++-- scripts/fixture_download.py | 6 ++--- scripts/run_mutmut_audit.py | 3 ++- scripts/verify_amputation.py | 2 +- src/freshdata/__init__.py | 2 +- src/freshdata/_core/backends.py | 5 +++- src/freshdata/_core/engine.py | 6 ++--- src/freshdata/_core/models.py | 4 ++- src/freshdata/_core/stages.py | 27 ++++++++++--------- tests/test_backend_honesty.py | 6 +++-- tests/test_core_api.py | 4 ++- tests/test_models.py | 9 ++++--- tests/test_property_invariants.py | 9 ++++--- tests/test_reviewer_fixes.py | 6 ++--- tests/test_stages.py | 14 +++++----- 43 files changed, 112 insertions(+), 90 deletions(-) diff --git a/benchmarks/baselines/__init__.py b/benchmarks/baselines/__init__.py index a401cd3f..0b9781e4 100644 --- a/benchmarks/baselines/__init__.py +++ b/benchmarks/baselines/__init__.py @@ -19,7 +19,7 @@ import ast import inspect import textwrap -from typing import Callable +from collections.abc import Callable def count_authored_lines(func: Callable) -> int: @@ -65,4 +65,4 @@ def count_authored_lines(func: Callable) -> int: REPAIR_BASELINES = ("pandas_baseline", "pyjanitor_baseline") READONLY_BASELINES = ("ydata_profiling_baseline", "sweetviz_baseline") -__all__ = ["count_authored_lines", "REGISTRY", "REPAIR_BASELINES", "READONLY_BASELINES"] +__all__ = ["READONLY_BASELINES", "REGISTRY", "REPAIR_BASELINES", "count_authored_lines"] diff --git a/benchmarks/bench_outofcore.py b/benchmarks/bench_outofcore.py index 192feca1..2b618f27 100644 --- a/benchmarks/bench_outofcore.py +++ b/benchmarks/bench_outofcore.py @@ -140,7 +140,7 @@ def main() -> None: f"{'peak RSS (MB)':>13} {'seconds':>8}") for r in results: print(f"{r['engine']:<8} {r['output_format']:<13} " - f"{str(r['materialized']):<13} {r['peak_rss_mb']:>13} {r['seconds']:>8}") + f"{r['materialized']!s:<13} {r['peak_rss_mb']:>13} {r['seconds']:>8}") if __name__ == "__main__": diff --git a/benchmarks/bench_v3_lazy_vs_pandas.py b/benchmarks/bench_v3_lazy_vs_pandas.py index 61e6d157..e6e5e18a 100644 --- a/benchmarks/bench_v3_lazy_vs_pandas.py +++ b/benchmarks/bench_v3_lazy_vs_pandas.py @@ -3,6 +3,7 @@ import argparse import json import platform + try: import resource except ImportError: diff --git a/benchmarks/fixtures/__init__.py b/benchmarks/fixtures/__init__.py index 9278f17d..59afa6e0 100644 --- a/benchmarks/fixtures/__init__.py +++ b/benchmarks/fixtures/__init__.py @@ -30,12 +30,12 @@ FRAME_FIXTURES = ("crm", "finance", "event_log", "wide_schema", "provenance") __all__ = [ - "REGISTRY", "FRAME_FIXTURES", + "REGISTRY", "crm", - "finance", "event_log", - "wide_schema", - "provenance", + "finance", "gold", + "provenance", + "wide_schema", ] diff --git a/benchmarks/fixtures/_common.py b/benchmarks/fixtures/_common.py index 0ba19d62..3bc1a78a 100644 --- a/benchmarks/fixtures/_common.py +++ b/benchmarks/fixtures/_common.py @@ -104,7 +104,7 @@ def defect_mask( within tolerance) and stable regardless of ``n``. """ rate = max(0.0, min(1.0, float(rate))) - k = int(round(rate * n)) + k = round(rate * n) mask = np.zeros(n, dtype=bool) if k: idx = rng.permutation(n)[:k] @@ -132,7 +132,7 @@ def uuid_series(rng: np.random.Generator, n: int, prefix: str = "") -> list[str] hi = rng.integers(0, 2**32, size=n, dtype=np.uint64) lo = rng.integers(0, 2**32, size=n, dtype=np.uint64) out = [] - for high, low in zip(hi.tolist(), lo.tolist()): + for high, low in zip(hi.tolist(), lo.tolist(), strict=False): out.append(f"{prefix}{high:08x}-{low:08x}") return out diff --git a/benchmarks/fixtures/crm.py b/benchmarks/fixtures/crm.py index c33ff5cd..c161862b 100644 --- a/benchmarks/fixtures/crm.py +++ b/benchmarks/fixtures/crm.py @@ -68,7 +68,7 @@ def _names(rng: np.random.Generator, n: int) -> np.ndarray: f = pick(rng, _FIRST, n) m = pick(rng, _MIDDLE, n) last = pick(rng, _LAST, n) - return np.array([f"{a} {b} {c}" for a, b, c in zip(f, m, last)], dtype=object) + return np.array([f"{a} {b} {c}" for a, b, c in zip(f, m, last, strict=False)], dtype=object) def generate(n_rows: int, seed: int = 42, defect_rate: float | None = None) -> pd.DataFrame: @@ -169,7 +169,7 @@ def rate(base: float) -> float: df.loc[m, "full_name"] = np.nan # 2% exact duplicate rows (appended verbatim, then index reset) - k = int(round(rate(0.02) * n)) + k = round(rate(0.02) * n) if k: dup_idx = rng.permutation(n)[:k] dup = df.iloc[dup_idx].copy() diff --git a/benchmarks/fixtures/finance.py b/benchmarks/fixtures/finance.py index 5238600d..6b879a7c 100644 --- a/benchmarks/fixtures/finance.py +++ b/benchmarks/fixtures/finance.py @@ -137,7 +137,7 @@ def rate(base: float) -> float: df.loc[m, "posting_date"] = alt # 2% exact-duplicate transaction rows - k = int(round(rate(0.02) * n)) + k = round(rate(0.02) * n) if k: dup_idx = rng.permutation(n)[:k] df = pd.concat([df, df.iloc[dup_idx].copy()], ignore_index=True) diff --git a/benchmarks/fixtures/gold.py b/benchmarks/fixtures/gold.py index 1620a535..22f042a0 100644 --- a/benchmarks/fixtures/gold.py +++ b/benchmarks/fixtures/gold.py @@ -213,7 +213,7 @@ def rate(base: float) -> float: } # -- inject exact duplicate rows (dropped on clean) ------------------- - k = int(round(rate(0.02) * n)) + k = round(rate(0.02) * n) if k: dup_idx = rng.permutation(n)[:k] dirty = pd.concat([dirty, dirty.iloc[dup_idx].copy()], ignore_index=True) diff --git a/benchmarks/fixtures/wide_schema.py b/benchmarks/fixtures/wide_schema.py index 59154ac9..8e81aa4b 100644 --- a/benchmarks/fixtures/wide_schema.py +++ b/benchmarks/fixtures/wide_schema.py @@ -62,7 +62,7 @@ def _column_plan(n_cols: int) -> list[tuple[str, str]]: ("bool", 0.10), ("sentinel", 0.10), ] - counts = {fam: int(round(share * body)) for fam, share in shares} + counts = {fam: round(share * body) for fam, share in shares} # absorb rounding drift into numeric counts["numeric"] += body - sum(counts.values()) k = 0 diff --git a/benchmarks/performance/__init__.py b/benchmarks/performance/__init__.py index fe3961b9..1ad67082 100644 --- a/benchmarks/performance/__init__.py +++ b/benchmarks/performance/__init__.py @@ -1,3 +1,3 @@ from .datasets import DATASET_TYPES, WIDTHS, DatasetSpec, make_mixed_frame -__all__ = ["DATASET_TYPES", "DatasetSpec", "WIDTHS", "make_mixed_frame"] +__all__ = ["DATASET_TYPES", "WIDTHS", "DatasetSpec", "make_mixed_frame"] diff --git a/benchmarks/performance/baselines.py b/benchmarks/performance/baselines.py index 21015078..6020e9d8 100644 --- a/benchmarks/performance/baselines.py +++ b/benchmarks/performance/baselines.py @@ -9,10 +9,11 @@ import tempfile import time import tracemalloc +from collections.abc import Callable from dataclasses import asdict, replace from itertools import product from pathlib import Path -from typing import Callable, NoReturn, Union +from typing import NoReturn import pandas as pd @@ -22,7 +23,7 @@ from .models import BenchmarkCase, BenchmarkResult from .schema import validate_result -Baseline = Callable[[pd.DataFrame], Union[pd.DataFrame, pd.Series]] +Baseline = Callable[[pd.DataFrame], pd.DataFrame | pd.Series] def _numeric_median_fill(frame: pd.DataFrame) -> pd.DataFrame: diff --git a/benchmarks/performance/environment.py b/benchmarks/performance/environment.py index 85064923..13e535d0 100644 --- a/benchmarks/performance/environment.py +++ b/benchmarks/performance/environment.py @@ -30,7 +30,7 @@ def capture_environment() -> EnvironmentInfo: ).stdout ) try: - import psutil # noqa: PLC0415 + import psutil physical = psutil.cpu_count(logical=False) total_ram = int(psutil.virtual_memory().total) diff --git a/benchmarks/performance/instrumentation.py b/benchmarks/performance/instrumentation.py index 801ffd44..c4d401db 100644 --- a/benchmarks/performance/instrumentation.py +++ b/benchmarks/performance/instrumentation.py @@ -4,11 +4,12 @@ import pstats import tracemalloc from collections import Counter +from collections.abc import Callable from contextlib import ExitStack from dataclasses import dataclass from functools import wraps from types import TracebackType -from typing import Callable +from typing import ClassVar from unittest.mock import patch import pandas as pd @@ -30,7 +31,7 @@ class ProfileResult: class OperationCounter: """Observe Python-level pandas method calls made inside the context.""" - METHODS = { + METHODS: ClassVar[dict[str, tuple[type, str]]] = { "dataframe.copy": (pd.DataFrame, "copy"), "series.copy": (pd.Series, "copy"), "series.isna": (pd.Series, "isna"), diff --git a/benchmarks/performance/memory.py b/benchmarks/performance/memory.py index 4430dc62..5839c76c 100644 --- a/benchmarks/performance/memory.py +++ b/benchmarks/performance/memory.py @@ -7,7 +7,7 @@ class PeakRSS: def __init__(self, interval_seconds: float = 0.01) -> None: - import psutil # noqa: PLC0415 + import psutil self._process = psutil.Process() self._interval = interval_seconds diff --git a/benchmarks/performance/models.py b/benchmarks/performance/models.py index cf5c4ed6..4bd65c9c 100644 --- a/benchmarks/performance/models.py +++ b/benchmarks/performance/models.py @@ -10,7 +10,7 @@ if TYPE_CHECKING: from .instrumentation import ProfileResult -JsonValue = Union[ +JsonValue = Union[ # noqa: UP007 None, bool, int, @@ -246,7 +246,7 @@ def from_dict(cls, payload: dict[str, Any]) -> BenchmarkResult: data["case"] = BenchmarkCase(**data["case"]) data["environment"] = EnvironmentInfo(**data["environment"]) if isinstance(data.get("profile"), dict): - from .instrumentation import ProfileResult # noqa: PLC0415 + from .instrumentation import ProfileResult data["profile"] = ProfileResult(**data["profile"]) return cls(**data) diff --git a/benchmarks/performance/render.py b/benchmarks/performance/render.py index 02ac9e05..b3346ee3 100644 --- a/benchmarks/performance/render.py +++ b/benchmarks/performance/render.py @@ -80,7 +80,7 @@ def _table(results: list[dict[str, Any]]) -> list[str]: return lines -def render_report(payload: dict[str, Any]) -> str: # noqa: PLR0915 +def render_report(payload: dict[str, Any]) -> str: validate_finite_numbers(payload, "report payload") environment = payload.get("environment", {}) results = list(payload.get("results", [])) diff --git a/benchmarks/performance/schema.py b/benchmarks/performance/schema.py index f55df027..b9e3b6ed 100644 --- a/benchmarks/performance/schema.py +++ b/benchmarks/performance/schema.py @@ -319,7 +319,7 @@ def validate_finite_numbers(value: object, path: str = "payload") -> None: def validate_result(payload: dict[str, Any]) -> None: - import jsonschema # noqa: PLC0415 + import jsonschema validate_finite_numbers(payload, "result payload") try: diff --git a/benchmarks/performance/worker.py b/benchmarks/performance/worker.py index 51ad60ed..27f74979 100644 --- a/benchmarks/performance/worker.py +++ b/benchmarks/performance/worker.py @@ -104,7 +104,7 @@ def execute_case(case: BenchmarkCase, *, command: str) -> BenchmarkResult: def execute_profile_case(case: BenchmarkCase, *, command: str) -> BenchmarkResult: - from .instrumentation import profile_case # noqa: PLC0415 + from .instrumentation import profile_case result = execute_case(case, command=command) return replace(result, profile=profile_case(case)) diff --git a/benchmarks/run_ground_truth_bench.py b/benchmarks/run_ground_truth_bench.py index 70b6936e..a2e7863e 100644 --- a/benchmarks/run_ground_truth_bench.py +++ b/benchmarks/run_ground_truth_bench.py @@ -3,11 +3,7 @@ import numpy as np import pandas as pd -from sklearn.ensemble import HistGradientBoostingClassifier -from sklearn.impute import KNNImputer, SimpleImputer -from sklearn.linear_model import LogisticRegression -from sklearn.metrics import f1_score, roc_auc_score -from sklearn.model_selection import train_test_split +from sklearn.impute import SimpleImputer import freshdata as fd from freshdata import CleanConfig @@ -88,7 +84,7 @@ def evaluate_cell_repair(clean_gt: pd.DataFrame, dirty_in: pd.DataFrame, repaire def main() -> None: - clean_df, dirty_df, y = generate_ground_truth_dataset() + clean_df, dirty_df, _y = generate_ground_truth_dataset() # 1. freshdata (balanced + outlier handling) fd_bal = fd.clean( diff --git a/benchmarks/run_scale_profile.py b/benchmarks/run_scale_profile.py index aeb6699d..05b89acc 100644 --- a/benchmarks/run_scale_profile.py +++ b/benchmarks/run_scale_profile.py @@ -3,10 +3,11 @@ import time import tracemalloc + import numpy as np import pandas as pd - import polars as pl + import freshdata as fd from freshdata import CleanConfig @@ -37,13 +38,13 @@ def main() -> None: cfg = CleanConfig(strategy="conservative", default_impute="preserve", default_outliers="preserve") for n in (10_000, 100_000, 1_000_000): df = make_scale_df(n) - profile_run(f"n={n} pandas_baseline", lambda: df.assign(cat=df["cat"].str.strip())) - profile_run(f"n={n} freshdata[pandas]", lambda: fd.clean(df, config=cfg)) + profile_run(f"n={n} pandas_baseline", lambda df=df: df.assign(cat=df["cat"].str.strip())) + profile_run(f"n={n} freshdata[pandas]", lambda df=df: fd.clean(df, config=cfg)) pldf = pl.from_pandas(df) - profile_run(f"n={n} freshdata[polars,eager]", lambda: fd.clean(pldf, config=cfg)) + profile_run(f"n={n} freshdata[polars,eager]", lambda pldf=pldf: fd.clean(pldf, config=cfg)) profile_run( f"n={n} freshdata[polars,lazy]", - lambda: fd.clean(pldf.lazy(), config=cfg).collect(), + lambda pldf=pldf: fd.clean(pldf.lazy(), config=cfg).collect(), ) diff --git a/examples/01_csv_cleaning.py b/examples/01_csv_cleaning.py index ea43247a..7e6adde6 100644 --- a/examples/01_csv_cleaning.py +++ b/examples/01_csv_cleaning.py @@ -69,7 +69,7 @@ def main() -> None: print("\n[4] Structured Action Log:") for action in report.actions: print( - f" - Step: {action.step:<18} | Column: {str(action.column):<14} | " + f" - Step: {action.step:<18} | Column: {action.column!s:<14} | " f"Risk: {action.risk:<6} | Confidence: {action.confidence:.2f} | " f"Description: {action.description}" ) diff --git a/examples/04_outlier_handling.py b/examples/04_outlier_handling.py index 32b70d99..85322dfa 100644 --- a/examples/04_outlier_handling.py +++ b/examples/04_outlier_handling.py @@ -71,7 +71,7 @@ def main() -> None: # Approach 2: Controlled capping (Winsorization) print("\n--- [B] Controlled Capping (Winsorization) ---") - capped_df, report_capped = fd.clean( + capped_df, _report_capped = fd.clean( df, outlier_action="cap", preserve_columns=["transaction_id"], @@ -83,7 +83,7 @@ def main() -> None: # Approach 3: Explicit row removal (when explicitly requested) print("\n--- [C] Explicit Row Removal ---") - dropped_df, report_dropped = fd.clean( + dropped_df, _report_dropped = fd.clean( df, outlier_action="remove", preserve_columns=["transaction_id"], diff --git a/examples/10_pyjanitor_interop.py b/examples/10_pyjanitor_interop.py index e42541e3..5936c6a3 100644 --- a/examples/10_pyjanitor_interop.py +++ b/examples/10_pyjanitor_interop.py @@ -4,7 +4,7 @@ pip install freshdata-cleaner "pyjanitor<0.32" -FreshData 2.0 supports pandas 1.5–2.x; PyJanitor 0.31 is the compatible line +FreshData 2.0 supports pandas 1.5-2.x; PyJanitor 0.31 is the compatible line verified for this example. Use PyJanitor for explicit DataFrame reshaping and method-style transforms. diff --git a/examples/11_great_expectations_recipe.py b/examples/11_great_expectations_recipe.py index 5ddd4719..dbd6e5be 100644 --- a/examples/11_great_expectations_recipe.py +++ b/examples/11_great_expectations_recipe.py @@ -15,7 +15,7 @@ os.environ.setdefault("GX_ANALYTICS_ENABLED", "false") -import great_expectations as gx # noqa: E402 +import great_expectations as gx def make_checkpoint(): diff --git a/examples/document_provenance.py b/examples/document_provenance.py index fa14d20b..6453a3f2 100644 --- a/examples/document_provenance.py +++ b/examples/document_provenance.py @@ -36,7 +36,7 @@ def main() -> None: "invoice_no": {"parser_confidence": 0.99, "source_file": "invoice_batch_2024_05.pdf"}, } - cleaned, report = fd.clean( + _cleaned, report = fd.clean( extracted, source_provenance=provenance, return_report=True ) diff --git a/examples/plugins/custom_comparator/initials_comparator.py b/examples/plugins/custom_comparator/initials_comparator.py index effdab9e..fc4ff727 100644 --- a/examples/plugins/custom_comparator/initials_comparator.py +++ b/examples/plugins/custom_comparator/initials_comparator.py @@ -40,5 +40,5 @@ def __call__(self, a: str, b: str) -> float: return 1.0 if not ia or not ib: return 0.0 - matches = sum(1 for x, y in zip(ia, ib) if x == y) + matches = sum(1 for x, y in zip(ia, ib, strict=False) if x == y) return matches / max(len(ia), len(ib)) diff --git a/pyproject.toml b/pyproject.toml index df2df5e1..c937f87e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -180,6 +180,10 @@ src = ["src", "tests", "benchmarks", "scripts"] select = ["E", "F", "I", "B", "UP", "N", "SIM", "RUF"] ignore = ["E501"] +[tool.ruff.lint.per-file-ignores] +# scikit-learn names feature matrices X. +"examples/**" = ["N803", "N806"] + [tool.mypy] python_version = "3.10" files = ["src/freshdata"] diff --git a/scripts/automate_freshdata.py b/scripts/automate_freshdata.py index 15d685f7..8d617554 100644 --- a/scripts/automate_freshdata.py +++ b/scripts/automate_freshdata.py @@ -98,7 +98,7 @@ def main() -> int: rec["step_meta"] = step_meta cleaned.to_csv(out_dir / f"{Path(name).stem}_cleaned.csv", index=False) ok += 1 - except Exception as exc: # noqa: BLE001 + except Exception as exc: rec["error"] = f"{type(exc).__name__}: {exc}" fail += 1 rec["seconds"] = round(time.perf_counter() - t0, 6) diff --git a/scripts/debug_50_datasets.py b/scripts/debug_50_datasets.py index 996adf75..f123c98d 100644 --- a/scripts/debug_50_datasets.py +++ b/scripts/debug_50_datasets.py @@ -14,7 +14,6 @@ sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "tests")) -import freshdata as fd # noqa: E402 from expectations import ( # noqa: E402 ALL_FIXTURES, ALL_ONLINE_FIXTURES, @@ -22,6 +21,8 @@ load_online_fixture, ) +import freshdata as fd # noqa: E402 + EXTERNAL_DATASETS = { "spotify_114k": Path("/Users/kevincostner/Desktop/data science/dataset.csv"), "retail_dirty": Path( @@ -47,7 +48,7 @@ def run_step(df: pd.DataFrame, step: str) -> dict: elif step == "remove_outliers": info["rows_out"] = len(out) return info - except Exception as exc: # noqa: BLE001 + except Exception as exc: return { "ok": False, "sec": round(time.perf_counter() - t0, 3), diff --git a/scripts/fixture_download.py b/scripts/fixture_download.py index 1410e6c5..252333d9 100644 --- a/scripts/fixture_download.py +++ b/scripts/fixture_download.py @@ -12,7 +12,7 @@ import time import urllib.error import urllib.request -from typing import Callable +from collections.abc import Callable USER_AGENT = "freshdata-fixture-fetch/1.0" @@ -45,7 +45,7 @@ def download( req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) for attempt in range(1, attempts + 1): try: - with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310 + with urllib.request.urlopen(req, timeout=timeout) as resp: return resp.read() except (OSError, http.client.HTTPException) as exc: if not _is_transient(exc): @@ -54,5 +54,5 @@ def download( raise TransientFetchError( f"{url}: {type(exc).__name__}: {exc} (after {attempts} attempts)" ) from exc - sleep(base_delay * 2 ** (attempt - 1) + random.uniform(0, 1)) # noqa: S311 + sleep(base_delay * 2 ** (attempt - 1) + random.uniform(0, 1)) raise AssertionError("unreachable: the loop always returns or raises") diff --git a/scripts/run_mutmut_audit.py b/scripts/run_mutmut_audit.py index 9b3b3156..b4259b09 100644 --- a/scripts/run_mutmut_audit.py +++ b/scripts/run_mutmut_audit.py @@ -5,6 +5,7 @@ import subprocess import sys from pathlib import Path +from typing import ClassVar TARGET_FILES = [ "src/freshdata/_core/stages.py", @@ -14,7 +15,7 @@ class ComparisonFlipMutator(ast.NodeTransformer): """Deterministic AST mutator flipping comparison and boolean operators one site at a time.""" - FLIPS = { + FLIPS: ClassVar[dict[type, type]] = { ast.Eq: ast.NotEq, ast.NotEq: ast.Eq, ast.Lt: ast.GtE, diff --git a/scripts/verify_amputation.py b/scripts/verify_amputation.py index 9462d9eb..ca2ca4cd 100644 --- a/scripts/verify_amputation.py +++ b/scripts/verify_amputation.py @@ -1,5 +1,5 @@ -from pathlib import Path import sys +from pathlib import Path FORBIDDEN_PATHS = [ "src/freshdata/compliance", diff --git a/src/freshdata/__init__.py b/src/freshdata/__init__.py index 950d660f..8e0286dc 100644 --- a/src/freshdata/__init__.py +++ b/src/freshdata/__init__.py @@ -17,9 +17,9 @@ __all__ = [ "ActionRecord", "CleanConfig", - "Cleaner", "CleanPlan", "CleanReport", + "Cleaner", "ColumnProfile", "ColumnRule", "ProfileReport", diff --git a/src/freshdata/_core/backends.py b/src/freshdata/_core/backends.py index d654a037..a97accca 100644 --- a/src/freshdata/_core/backends.py +++ b/src/freshdata/_core/backends.py @@ -1,10 +1,13 @@ # src/freshdata/_core/backends.py from __future__ import annotations + import dataclasses import warnings from numbers import Real from typing import TYPE_CHECKING, Any + import pandas as pd + from freshdata._core.models import ( ActionRecord, CleanConfig, @@ -15,10 +18,10 @@ from freshdata._core.stages import ( _impute_strategy, _is_protected, + _normalize_name, _outlier_strategy, _strip_str, flag_column, - _normalize_name, normalize_config, stage_column_names, stage_dtypes, diff --git a/src/freshdata/_core/engine.py b/src/freshdata/_core/engine.py index 510f8d8e..b91a76e7 100644 --- a/src/freshdata/_core/engine.py +++ b/src/freshdata/_core/engine.py @@ -1,18 +1,18 @@ # src/freshdata/_core/engine.py from __future__ import annotations + import dataclasses from typing import Any + from freshdata._core.backends import resolve_backend from freshdata._core.models import ( - ActionRecord, CleanConfig, CleanPlan, CleanReport, - ColumnProfile, - ColumnRule, ProfileReport, ) + def _with_overrides(config: CleanConfig | None, overrides: dict[str, Any]) -> CleanConfig: cfg = config or CleanConfig() return dataclasses.replace(cfg, **overrides) if overrides else cfg diff --git a/src/freshdata/_core/models.py b/src/freshdata/_core/models.py index 1c3dc7f1..00c9e5b3 100644 --- a/src/freshdata/_core/models.py +++ b/src/freshdata/_core/models.py @@ -1,9 +1,11 @@ # src/freshdata/_core/models.py from __future__ import annotations + import warnings +from collections.abc import Mapping from dataclasses import asdict, dataclass, field from numbers import Real -from typing import Any, Literal, Mapping +from typing import Any, Literal _ROLES = ("id", "target", "numeric", "categorical", "datetime", "text") _IMPUTES = ("preserve", "drop", "mean", "median", "mode", "ffill") diff --git a/src/freshdata/_core/stages.py b/src/freshdata/_core/stages.py index b661cabb..a6c8919c 100644 --- a/src/freshdata/_core/stages.py +++ b/src/freshdata/_core/stages.py @@ -1,11 +1,14 @@ # src/freshdata/_core/stages.py from __future__ import annotations + import dataclasses import re from collections.abc import Container -from typing import Any, List, Tuple +from typing import Any + import numpy as np import pandas as pd + from freshdata._core.models import ActionRecord, CleanConfig CURRENCY_REGEX = re.compile(r"^\s*[-+]?\s*[\$€£¥]?\s*[\d,]+(?:\.\d+)?\s*[\$€£¥]?\s*$") @@ -61,10 +64,10 @@ def normalize_config(cfg: CleanConfig) -> CleanConfig: norm_target = _normalize_name(cfg.target_column) if cfg.target_column else None return dataclasses.replace(cfg, rules=norm_rules, id_columns=norm_id, target_column=norm_target) -def stage_column_names(df: pd.DataFrame, cfg: CleanConfig) -> Tuple[pd.DataFrame, List[ActionRecord]]: +def stage_column_names(df: pd.DataFrame, cfg: CleanConfig) -> tuple[pd.DataFrame, list[ActionRecord]]: if not cfg.normalize_names: return df, [] - actions: List[ActionRecord] = [] + actions: list[ActionRecord] = [] rename_map = {} for col in df.columns: norm = _normalize_name(str(col)) @@ -74,10 +77,10 @@ def stage_column_names(df: pd.DataFrame, cfg: CleanConfig) -> Tuple[pd.DataFrame out = df.rename(columns=rename_map) if rename_map else df return out, actions -def stage_strings(df: pd.DataFrame, cfg: CleanConfig) -> Tuple[pd.DataFrame, List[ActionRecord]]: +def stage_strings(df: pd.DataFrame, cfg: CleanConfig) -> tuple[pd.DataFrame, list[ActionRecord]]: if not cfg.strip_strings: return df, [] - actions: List[ActionRecord] = [] + actions: list[ActionRecord] = [] out = df.copy() cfg_eff = normalize_config(cfg) for col in out.columns: @@ -92,10 +95,10 @@ def stage_strings(df: pd.DataFrame, cfg: CleanConfig) -> Tuple[pd.DataFrame, Lis actions.append(ActionRecord("strings", str(col), "strip_strings", {}, int(changed.sum()))) return out, actions -def stage_dtypes(df: pd.DataFrame, cfg: CleanConfig) -> Tuple[pd.DataFrame, List[ActionRecord]]: +def stage_dtypes(df: pd.DataFrame, cfg: CleanConfig) -> tuple[pd.DataFrame, list[ActionRecord]]: if not cfg.fix_dtypes: return df, [] - actions: List[ActionRecord] = [] + actions: list[ActionRecord] = [] out = df.copy() cfg_eff = normalize_config(cfg) for col in out.columns: @@ -114,7 +117,7 @@ def stage_dtypes(df: pd.DataFrame, cfg: CleanConfig) -> Tuple[pd.DataFrame, List actions.append(ActionRecord("dtypes", str(col), "parse_currency", {"target_dtype": "float64"}, parsed)) return out, actions -def stage_duplicates(df: pd.DataFrame, cfg: CleanConfig) -> Tuple[pd.DataFrame, List[ActionRecord]]: +def stage_duplicates(df: pd.DataFrame, cfg: CleanConfig) -> tuple[pd.DataFrame, list[ActionRecord]]: if not cfg.drop_duplicates: return df, [] orig_len = len(df) @@ -124,8 +127,8 @@ def stage_duplicates(df: pd.DataFrame, cfg: CleanConfig) -> Tuple[pd.DataFrame, actions = [ActionRecord("duplicates", "*", "drop_duplicates", {}, dropped)] if dropped > 0 else [] return out, actions -def stage_missing(df: pd.DataFrame, cfg: CleanConfig) -> Tuple[pd.DataFrame, List[ActionRecord]]: - actions: List[ActionRecord] = [] +def stage_missing(df: pd.DataFrame, cfg: CleanConfig) -> tuple[pd.DataFrame, list[ActionRecord]]: + actions: list[ActionRecord] = [] out = df.copy() cfg_eff = normalize_config(cfg) for col in out.columns: @@ -166,8 +169,8 @@ def stage_missing(df: pd.DataFrame, cfg: CleanConfig) -> Tuple[pd.DataFrame, Lis actions.append(ActionRecord("missing", str(col), "impute_ffill", {}, filled_count)) return out, actions -def stage_outliers(df: pd.DataFrame, cfg: CleanConfig) -> Tuple[pd.DataFrame, List[ActionRecord]]: - actions: List[ActionRecord] = [] +def stage_outliers(df: pd.DataFrame, cfg: CleanConfig) -> tuple[pd.DataFrame, list[ActionRecord]]: + actions: list[ActionRecord] = [] out = df.copy() cfg_eff = normalize_config(cfg) for col in list(out.columns): diff --git a/tests/test_backend_honesty.py b/tests/test_backend_honesty.py index c800be53..d5efb606 100644 --- a/tests/test_backend_honesty.py +++ b/tests/test_backend_honesty.py @@ -1,8 +1,10 @@ -import polars as pl import pandas as pd +import polars as pl import pytest + from freshdata._core.backends import resolve_backend -from freshdata._core.models import CleanConfig, ActionRecord, CleanPlan +from freshdata._core.models import ActionRecord, CleanConfig, CleanPlan + def test_lazyframe_preserved_without_collect(monkeypatch): called = [] diff --git a/tests/test_core_api.py b/tests/test_core_api.py index a3eb5298..abf37146 100644 --- a/tests/test_core_api.py +++ b/tests/test_core_api.py @@ -1,7 +1,9 @@ import types + import pandas as pd import polars as pl import pytest + import freshdata as fd EXPECTED_EXPORTS = { @@ -34,7 +36,7 @@ def test_full_clean_workflow_pandas(): assert report.row_count == 2 plan = fd.suggest_plan(df) assert len(plan.actions) > 0 - cleaned, clean_report = fd.apply_plan(df, plan, return_report=True) + cleaned, _clean_report = fd.apply_plan(df, plan, return_report=True) assert list(cleaned.columns) == ["name", "income"] assert pd.api.types.is_numeric_dtype(cleaned["income"]) diff --git a/tests/test_models.py b/tests/test_models.py index fe9c454b..f079fab9 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,14 +1,15 @@ +import dataclasses + import pytest + from freshdata._core.models import ( ActionRecord, CleanConfig, CleanPlan, - CleanReport, - ColumnProfile, ColumnRule, - ProfileReport, ) + def test_clean_config_defaults(): cfg = CleanConfig() assert cfg.strategy == "balanced" @@ -19,7 +20,7 @@ def test_clean_config_defaults(): def test_column_rule_immutability(): rule = ColumnRule(role="numeric", impute="median", outliers="clip", protected=False) - with pytest.raises(Exception): + with pytest.raises(dataclasses.FrozenInstanceError): rule.role = "categorical" # type: ignore def test_action_record_serialization(): diff --git a/tests/test_property_invariants.py b/tests/test_property_invariants.py index 6633efb7..53946deb 100644 --- a/tests/test_property_invariants.py +++ b/tests/test_property_invariants.py @@ -3,10 +3,11 @@ import pandas as pd import polars as pl -from hypothesis import HealthCheck, given, settings, strategies as st +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st import freshdata as fd -from freshdata import CleanConfig, ColumnRule +from freshdata import CleanConfig @st.composite @@ -43,11 +44,11 @@ def test_five_hard_invariants(df: pd.DataFrame) -> None: # 1. Input Non-Mutation: df must not be modified in place df_snapshot = df.copy(deep=True) - res_pd, rep1 = fd.clean(df, config=cfg, return_report=True) + res_pd, _rep1 = fd.clean(df, config=cfg, return_report=True) pd.testing.assert_frame_equal(df, df_snapshot, check_dtype=True) # 2. Idempotence: clean(clean(df)) == clean(df) - res_pd_2, rep2 = fd.clean(res_pd, config=cfg, return_report=True) + res_pd_2, _rep2 = fd.clean(res_pd, config=cfg, return_report=True) pd.testing.assert_frame_equal(res_pd, res_pd_2, check_dtype=True) # 3. Column-Order Invariance: permuted input columns yield identical cleaned columns diff --git a/tests/test_reviewer_fixes.py b/tests/test_reviewer_fixes.py index fdcc27a5..15866c29 100644 --- a/tests/test_reviewer_fixes.py +++ b/tests/test_reviewer_fixes.py @@ -1,10 +1,10 @@ -import numpy as np import pandas as pd import polars as pl -import pytest + import freshdata as fd from freshdata._core.models import ActionRecord, CleanConfig, CleanPlan, ColumnRule + def test_apply_plan_executes_custom_plan_actions(): df = pd.DataFrame({" Name ": [" Alice "], "Val": [None]}) plan = CleanPlan(actions=( @@ -56,7 +56,7 @@ def test_polars_backend_applies_imputation_and_clipping(): ) plan = fd.suggest_plan(df, cfg) assert any(a.stage == "missing" for a in plan.actions) - cleaned = fd.apply_plan(df, plan) + fd.apply_plan(df, plan) lazy_df = df.lazy() lazy_cleaned = fd.apply_plan(lazy_df, plan) assert isinstance(lazy_cleaned, pl.LazyFrame) diff --git a/tests/test_stages.py b/tests/test_stages.py index 8927da93..d39e1f68 100644 --- a/tests/test_stages.py +++ b/tests/test_stages.py @@ -1,15 +1,17 @@ import pandas as pd import pytest + from freshdata._core.models import CleanConfig, ColumnRule from freshdata._core.stages import ( stage_column_names, - stage_strings, stage_dtypes, stage_duplicates, stage_missing, stage_outliers, + stage_strings, ) + def test_stage_column_names_pandas(): df = pd.DataFrame({" First Name ": ["Alice"], "Spend ($)": [100]}) cfg = CleanConfig(normalize_names=True) @@ -27,15 +29,15 @@ def test_stage_strings_pandas(): def test_stage_dtypes_currency_pandas(): df = pd.DataFrame({"price": ["$1,200.50", "350.00", "$45.99"]}) cfg = CleanConfig(fix_dtypes=True) - out_df, actions = stage_dtypes(df, cfg) + out_df, _actions = stage_dtypes(df, cfg) assert pd.api.types.is_numeric_dtype(out_df["price"]) assert out_df["price"].iloc[0] == 1200.50 def test_stage_duplicates_pandas(): df = pd.DataFrame({"a": [1, 1, 2], "b": [3, 3, 4]}) - out_drop, act_drop = stage_duplicates(df, CleanConfig(drop_duplicates=True)) + out_drop, _act_drop = stage_duplicates(df, CleanConfig(drop_duplicates=True)) assert len(out_drop) == 2 - out_keep, act_keep = stage_duplicates(df, CleanConfig(drop_duplicates=False)) + out_keep, _act_keep = stage_duplicates(df, CleanConfig(drop_duplicates=False)) assert len(out_keep) == 3 def test_stage_missing_protected(): @@ -44,7 +46,7 @@ def test_stage_missing_protected(): target_column="target", rules={"val": ColumnRule(impute="median")}, ) - out_df, actions = stage_missing(df, cfg) + out_df, _actions = stage_missing(df, cfg) assert out_df["target"].isna().sum() == 1 # target untouched assert out_df["val"].isna().sum() == 0 # val imputed to 20.0 assert out_df["val"].iloc[1] == 20.0 @@ -55,7 +57,7 @@ def test_stage_outliers_clip(): rules={"x": ColumnRule(outliers="clip")}, iqr_factor=1.5, ) - out_df, actions = stage_outliers(df, cfg) + out_df, _actions = stage_outliers(df, cfg) assert out_df["x"].max() < 100 def test_stage_outliers_short_series(): From 22ddffc20c27b41d6147aa80a12df9877a3f746d Mon Sep 17 00:00:00 2001 From: Johnny Wilson Dougherty Date: Sat, 28 Nov 2026 16:50:00 +0530 Subject: [PATCH 2/3] release: prepare 3.0.0 so main can pass release.yml PyPI has 2.1.0. The README documents the 3.x API on main, so a user who runs `pip install freshdata-cleaner` gets an API the README does not describe. Main cannot release today: - pyproject says 0.4.0, and PyPI already has 0.4.0. - The resolve step reads `__version__` with ast.literal_eval. Main sets it with importlib.metadata, so the step stops with ValueError. - The test job asks for extras that main does not have (ml, docs). Its `pytest -m` names markers that pytest does not know. mkdocs stops on docs/api-reference.md, which names 2.x functions. - The smoke job calls `fd.clean(..., verbose=False)`. 3.x has no `verbose`. Changes: - version 3.0.0, and a 3.0.0 CHANGELOG section that lists the breaking changes from 2.1.0. Entries for 2.x work that never shipped are marked. - pyproject.toml is the one source of the version. The smoke job now checks `fd.__version__` against the resolved version. - A docs extra, registered online/large markers, and an API reference page for the 12 names that 3.x exports. - The pyproject description no longer claims a DuckDB backend. - tests/test_release_workflow.py runs the release scripts offline. This commit does not tag or publish. --- .github/workflows/release.yml | 31 ++++------ .github/workflows/testpypi.yml | 4 +- CHANGELOG.md | 43 ++++++++++++++ docs/api-reference.md | 103 ++++++--------------------------- pyproject.toml | 13 ++++- tests/test_release_workflow.py | 86 +++++++++++++++++++++++++++ 6 files changed, 169 insertions(+), 111 deletions(-) create mode 100644 tests/test_release_workflow.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4de6f25e..126262cf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,7 +11,8 @@ name: Release # downstream job — nothing is re-derived later in the pipeline; # * the resolved version is checked against PyPI *before* build and again # immediately before publish (fail-closed, no --skip-existing, ever); -# * the tag must match the packaged version (pyproject + __version__); +# * the tag must match the packaged version (pyproject.toml; freshdata.__version__ +# reads it from the installed metadata, and the smoke job checks that); # * dist/ is built exactly once and reused by twine-check, smoke test, # PyPI publish, and the GitHub Release — never rebuilt; # * SHA-256 checksums are generated after build and re-verified after download; @@ -129,22 +130,9 @@ jobs: run: | set -euo pipefail PKG=$(python -c "import tomllib,pathlib; print(tomllib.loads(pathlib.Path('pyproject.toml').read_text())['project']['version'])") - # Parsed statically (no import) so this job needs no runtime deps installed. - INIT=$(python -c " - import ast, pathlib - tree = ast.parse(pathlib.Path('src/freshdata/__init__.py').read_text()) - for node in tree.body: - if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == '__version__' for t in node.targets): - print(ast.literal_eval(node.value)) - break - ") + # pyproject.toml is the one source of the version. freshdata.__version__ + # reads the installed metadata, so the smoke job checks it after install. echo "pyproject version: $PKG" - echo "freshdata.__version__: $INIT" - - if [ "$PKG" != "$INIT" ]; then - echo "::error::pyproject.toml version ($PKG) and freshdata.__version__ ($INIT) disagree at commit ${{ steps.target.outputs.sha }}." - exit 1 - fi VERSION="$PKG" # Syntactic validity per PEP 440 (also what setuptools/hatchling/pip enforce). @@ -191,7 +179,7 @@ jobs: # Fail closed if this exact version is already on production PyPI. HTTP_CODE=$(curl -s -o /tmp/pypi.json -w '%{http_code}' "https://pypi.org/pypi/${PACKAGE_NAME}/${VERSION}/json") if [ "$HTTP_CODE" = "200" ]; then - echo "::error::${PACKAGE_NAME} ${VERSION} already exists on PyPI. Refusing to republish (no --skip-existing, no overwrite). Bump the version in pyproject.toml and src/freshdata/__init__.py before releasing." + echo "::error::${PACKAGE_NAME} ${VERSION} already exists on PyPI. Refusing to republish (no --skip-existing, no overwrite). Bump the version in pyproject.toml before releasing." exit 1 elif [ "$HTTP_CODE" != "404" ]; then echo "::error::Unexpected PyPI response code $HTTP_CODE while checking existing releases."; exit 1 @@ -231,7 +219,7 @@ jobs: set -euo pipefail python -m pip install --upgrade pip # mypy targets Python 3.10; NumPy 2.5+ stubs require Python 3.12. - pip install -e ".[dev,ml,docs]" "numpy<2.5" + pip install -e ".[dev,migrate,docs]" "numpy<2.5" - name: Lint run: ruff check . - name: Typecheck @@ -379,6 +367,8 @@ jobs: with: python-version: "3.12" - name: Install the built wheel and import it + env: + EXPECTED_VERSION: ${{ needs.resolve.outputs.version }} run: | set -euo pipefail python -m venv /tmp/smoke @@ -387,11 +377,12 @@ jobs: echo "installing $WHEEL" /tmp/smoke/bin/pip install "$WHEEL" /tmp/smoke/bin/python - <<'PY' + import os import pandas as pd import freshdata as fd print("freshdata", fd.__version__) - out = fd.clean(pd.DataFrame({"a": [1, None, 2], "b": ["x", "x", None]}), - verbose=False) + assert fd.__version__ == os.environ["EXPECTED_VERSION"], fd.__version__ + out = fd.clean(pd.DataFrame({"a": [1, None, 2], "b": ["x", "x", None]})) assert len(out.columns) == 2, out.columns print("smoke ok:", out.shape) PY diff --git a/.github/workflows/testpypi.yml b/.github/workflows/testpypi.yml index 8afd0ffe..fd1b6ed2 100644 --- a/.github/workflows/testpypi.yml +++ b/.github/workflows/testpypi.yml @@ -46,9 +46,7 @@ jobs: python -c "from packaging.version import Version; import sys; Version(sys.argv[1])" "$VERSION" # Only this CI checkout is modified; nothing is committed. sed -i -E "s/^version = \"[^\"]+\"/version = \"${VERSION}\"/" pyproject.toml - sed -i -E "s/^__version__ = \"[^\"]+\"/__version__ = \"${VERSION}\"/" src/freshdata/__init__.py grep -q "^version = \"${VERSION}\"" pyproject.toml - grep -q "^__version__ = \"${VERSION}\"" src/freshdata/__init__.py echo "version=${VERSION}" >> "$GITHUB_OUTPUT" echo "TestPyPI version: \`${VERSION}\`" >> "$GITHUB_STEP_SUMMARY" - name: Build sdist and wheel @@ -123,7 +121,7 @@ jobs: /tmp/smoke/bin/python - <<'PY' import pandas as pd import freshdata as fd - out = fd.clean(pd.DataFrame({"a": [1, None, 2], "b": ["x", "x", None]}), verbose=False) + out = fd.clean(pd.DataFrame({"a": [1, None, 2], "b": ["x", "x", None]})) assert len(out.columns) == 2, out.columns print("smoke ok:", out.shape) PY diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e3484d8..9dce8e34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,45 @@ adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [3.0.0] - Unreleased + +3.0 replaces the 2.x API with a small plan-and-apply core for pandas and +Polars. Code written for 2.x needs changes. `freshdata-migrate` (install +`freshdata-cleaner[migrate]`) rewrites the common calls. + +### Removed (breaking) + +- `freshdata` now exports 12 names: `ActionRecord`, `CleanConfig`, `Cleaner`, + `CleanPlan`, `CleanReport`, `ColumnProfile`, `ColumnRule`, `ProfileReport`, + `apply_plan`, `clean`, `profile`, and `suggest_plan`. The other 85 names in + the 2.1.0 `__all__` are gone, for example `clean_csv`, `clean_text`, + `validate`, `explain_clean`, `compare_plans`, `Pipeline`, `StreamingCleaner`, + and `ContextPolicy`. +- The subpackages `adapters`, `compliance`, `context`, `domains`, `engine`, + `enterprise`, `execution`, `experimental`, `imputation`, `integrations`, + `learning`, `models`, `parsers`, `render`, `schemas`, `semantic`, `steps`, + and `streaming` are gone. So are the DuckDB and Spark backends. + +### Changed (breaking) + +- `fd.ColumnRule` is a per-column cleaning rule: `role`, `impute`, `outliers`, + and `protected`. In 2.x it was the validation rule + `freshdata.validation_suite.ColumnRule`. +- `fd.CleanConfig` has new fields: `strategy`, `rules`, `id_columns`, + `target_column`, `normalize_names`, `strip_strings`, `fix_dtypes`, + `drop_duplicates`, `default_impute`, `default_outliers`, `iqr_factor`, and + `strict_backend`. The 2.x fields such as `verbose`, `preserve_columns`, and + `outlier_action` are gone. +- `fd.suggest_plan`, `fd.apply_plan`, `fd.clean`, and `fd.profile` take a + pandas DataFrame, a Polars DataFrame, or a Polars LazyFrame. A LazyFrame + stays lazy: `apply_plan` returns a LazyFrame and does not collect it. In + 2.1.0, `suggest_plan` converted Polars input to pandas. +- `freshdata.__version__` reads the installed package metadata. + ### Added +- A `docs` extra (`mkdocs-material`, `mkdocstrings[python]`, + `pymdown-extensions`) for building the documentation. - `impute="ffill"` forward-fills a column, and `outliers="flag"` adds a boolean `_outlier` column. Both were accepted before but did nothing. - `fd.clean()` and `fd.Cleaner()` take `CleanConfig` fields as keyword @@ -43,6 +80,12 @@ adheres to [Semantic Versioning](https://semver.org/). nulls that imputation fills or `drop_nulls` removes. Where Polars does not count (to keep planning to one cheap query), `rationale` says so. +### Never released + +The entries from here to `[2.1.0]` describe work on main between 2.1.0 and +the 3.0 rewrite (2026-11-10). The rewrite removed that code, so no release +has it. + - Polars and DuckDB now disclose a pandas fallback for categorical and Arrow dictionary-backed pandas inputs. This preserves pandas text-cleaning and category metadata behavior rather than silently skipping or changing it. diff --git a/docs/api-reference.md b/docs/api-reference.md index 8a5d2d7f..c0e77064 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -1,112 +1,43 @@ --- title: API reference description: >- - Complete freshdata API reference — clean, profile, suggest_plan, - compare_plans, compare_clean, explain_clean, Cleaner, CleanConfig, and reports. -keywords: freshdata api, fd.clean, CleanConfig, CleanReport, pandas cleaning api + freshdata 3.x API reference: suggest_plan, apply_plan, clean, profile, + Cleaner, CleanConfig, ColumnRule, CleanPlan, and reports. +keywords: freshdata api, fd.suggest_plan, fd.apply_plan, CleanConfig, ColumnRule --- # API reference -Auto-generated from the source docstrings. Everything below is available as a -top-level attribute of `freshdata` (e.g. `import freshdata as fd; fd.clean(...)`). +Auto-generated from the source docstrings. freshdata 3.x exports exactly these +12 names (`import freshdata as fd`). Each function takes a pandas DataFrame, a +Polars DataFrame, or a Polars LazyFrame. -## Cleaning +## Plan and apply -::: freshdata.clean - -::: freshdata.clean_csv - -::: freshdata.clean_excel - -::: freshdata.Cleaner - -::: freshdata.pipeline +::: freshdata.suggest_plan -::: freshdata.Pipeline +::: freshdata.apply_plan -## Profiling & inspection +::: freshdata.clean ::: freshdata.profile -::: freshdata.infer_roles - -::: freshdata.explain_clean - -## Context policies - -::: freshdata.compile_context - -::: freshdata.validate - -::: freshdata.ContextPolicy - -## Validation suites - -::: freshdata.validation_suite.ValidationSuite - -::: freshdata.validation_suite.ColumnRule - -::: freshdata.validation_suite.CrossColumnRule - -::: freshdata.validation_suite.ValidationResult - -## Planning & comparison - -::: freshdata.plan - -::: freshdata.suggest_plan - -::: freshdata.compare_plans - -::: freshdata.compare_clean +::: freshdata.Cleaner ## Configuration ::: freshdata.CleanConfig -## Reports & results +::: freshdata.ColumnRule -::: freshdata.CleanReport - -::: freshdata.Action +## Plans and reports ::: freshdata.CleanPlan -::: freshdata.ColumnPlan - -::: freshdata.Profile - -::: freshdata.ColumnProfile +::: freshdata.ActionRecord -::: freshdata.ExplainReport - -## Enterprise layer - -The `freshdata.enterprise` subpackage is documented in the -[feature overview](feature-overview.md). Import its symbols lazily: - -```python -from freshdata.enterprise import clean_enterprise, EnterpriseConfig -``` - -## Compliance - -The `freshdata.compliance` subpackage maps a `CleanReport` onto regulatory control -frameworks; it is documented in the [compliance reports guide](compliance.md). -Import its symbols lazily: - -```python -from freshdata.compliance import generate_compliance_report, ComplianceConfig -``` - -## Integrations +::: freshdata.CleanReport -The `freshdata.integrations` subpackage runs the clean + trust gate inside Dagster, -Airflow, and dbt; it is documented in the -[orchestration integrations guide](integrations.md). The framework-agnostic core is -always importable: +::: freshdata.ProfileReport -```python -from freshdata.integrations import evaluate_trust_gate, TrustGateResult -``` +::: freshdata.ColumnProfile diff --git a/pyproject.toml b/pyproject.toml index c937f87e..8f99240c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,8 +5,8 @@ build-backend = "setuptools.build_meta" [project] name = "freshdata-cleaner" -version = "0.4.0" -description = "Explainable, schema-preserving tabular data cleaning across pandas, Polars, and DuckDB." +version = "3.0.0" +description = "Dry-run cleaning plans for pandas and Polars DataFrames and LazyFrames." readme = "README.md" requires-python = ">=3.10" license = { text = "MIT" } @@ -48,6 +48,11 @@ polars = [ "polars>=1.0.0", "pyarrow>=15.0.0", ] +docs = [ + "mkdocs-material>=9.5", + "mkdocstrings[python]>=0.25", + "pymdown-extensions>=10.0", +] test = [ "pytest>=8.0.0", "pytest-cov>=5.0.0", @@ -102,6 +107,10 @@ addopts = [ "--cov-fail-under=90", ] xfail_strict = true +markers = [ + "online: needs network access", + "large: needs large data or a long run time", +] filterwarnings = [ "error::DeprecationWarning:freshdata.*", "error::RuntimeWarning:freshdata.*", diff --git a/tests/test_release_workflow.py b/tests/test_release_workflow.py new file mode 100644 index 00000000..1a9a0107 --- /dev/null +++ b/tests/test_release_workflow.py @@ -0,0 +1,86 @@ +"""The tree on main must be releasable by .github/workflows/release.yml. + +These checks run the workflow's own scripts offline, so a release breaks here +first and not in the middle of the tag-triggered pipeline. +""" + +import os +import pathlib +import re +import subprocess +import sys + +import pytest + +ROOT = pathlib.Path(__file__).resolve().parents[1] +RELEASE = ROOT / ".github" / "workflows" / "release.yml" + + +def _version() -> str: + # A regex, not tomllib, because Python 3.10 has no tomllib. + pyproject = (ROOT / "pyproject.toml").read_text(encoding="utf-8") + return re.search(r'^version = "([^"]+)"', pyproject, re.MULTILINE).group(1) + + +def _run_block(step_name: str) -> str: + """Return the dedented ``run: |`` script of the release.yml step with this name.""" + lines = RELEASE.read_text(encoding="utf-8").splitlines() + start = lines.index(next(line for line in lines if line.strip() == f"- name: {step_name}")) + run = next(i for i in range(start, len(lines)) if lines[i].strip() == "run: |") + body: list[str] = [] + indent = len(lines[run + 1]) - len(lines[run + 1].lstrip()) + for line in lines[run + 1 :]: + if line.strip() and len(line) - len(line.lstrip()) < indent: + break + body.append(line[indent:]) + return "\n".join(body) + + +def _as_tuple(version: str) -> tuple[int, ...]: + return tuple(int(part) for part in version.split(".")) + + +def test_version_is_newer_than_every_released_version() -> None: + changelog = (ROOT / "CHANGELOG.md").read_text(encoding="utf-8") + released = re.findall(r"^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}", changelog, re.MULTILINE) + assert released, "CHANGELOG.md lists no released versions" + assert _as_tuple(_version()) > max(map(_as_tuple, released)) + + +def test_changelog_has_a_section_for_the_version() -> None: + changelog = (ROOT / "CHANGELOG.md").read_text(encoding="utf-8") + assert f"## [{_version()}]" in changelog + + +@pytest.mark.skipif(sys.platform == "win32", reason="the release job runs bash") +@pytest.mark.skipif(sys.version_info < (3, 11), reason="the release job uses tomllib (3.11+)") +def test_resolve_step_reads_the_version() -> None: + script = _run_block("Resolve and cross-validate version, tag, and PyPI state") + # Keep the version-reading part; the rest needs git tags, PyPI, and GitHub context. + head = script.split('VERSION="$PKG"')[0] + 'VERSION="$PKG"\necho "resolved=$VERSION"\n' + head = re.sub(r"\$\{\{[^}]*\}\}", "ci-expression", head) + # The job calls `python`. Point it at this interpreter. + env = { + **os.environ, + "PATH": f"{pathlib.Path(sys.executable).parent}{os.pathsep}{os.environ['PATH']}", + } + result = subprocess.run(["bash", "-c", head], cwd=ROOT, capture_output=True, text=True, env=env) + assert result.returncode == 0, result.stderr + assert f"resolved={_version()}" in result.stdout + + +def test_smoke_script_runs_against_the_installed_package() -> None: + script = _run_block("Install the built wheel and import it") + smoke = script.split("<<'PY'\n", 1)[1].split("\nPY", 1)[0] + env = {**os.environ, "EXPECTED_VERSION": _version()} + result = subprocess.run([sys.executable, "-c", smoke], capture_output=True, text=True, env=env) + assert result.returncode == 0, result.stderr + assert "smoke ok" in result.stdout + + +def test_release_pytest_markers_are_registered(pytestconfig: pytest.Config) -> None: + # pytest runs with --strict-markers, so `-m` with an unknown marker stops the run. + expr = re.search(r'pytest -m "([^"]+)"', RELEASE.read_text(encoding="utf-8")).group(1) + used = set(re.findall(r"\w+", expr)) - {"not", "and", "or"} + registered = {line.split(":")[0].strip() for line in pytestconfig.getini("markers")} + assert used <= registered, f"release.yml selects unregistered markers: {used - registered}" From 549cc4c80d0a8c28ea219ae63529fde946b86013 Mon Sep 17 00:00:00 2001 From: Johnny Wilson Dougherty Date: Sat, 28 Nov 2026 20:13:38 +0530 Subject: [PATCH 3/3] release: date 3.0.0 in CHANGELOG and keep the version check valid The 3.0.0 section gets its release date before the tag. The release check compared the version with every dated CHANGELOG entry, so the dated 3.0.0 entry made it fail: assert (3, 0, 0) > (3, 0, 0). The check now compares only with entries for older versions. --- CHANGELOG.md | 2 +- tests/test_release_workflow.py | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9dce8e34..150da6dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] -## [3.0.0] - Unreleased +## [3.0.0] - 2026-11-28 3.0 replaces the 2.x API with a small plan-and-apply core for pandas and Polars. Code written for 2.x needs changes. `freshdata-migrate` (install diff --git a/tests/test_release_workflow.py b/tests/test_release_workflow.py index 1a9a0107..7703174e 100644 --- a/tests/test_release_workflow.py +++ b/tests/test_release_workflow.py @@ -43,6 +43,8 @@ def _as_tuple(version: str) -> tuple[int, ...]: def test_version_is_newer_than_every_released_version() -> None: changelog = (ROOT / "CHANGELOG.md").read_text(encoding="utf-8") released = re.findall(r"^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}", changelog, re.MULTILINE) + # The section for the version under release gets its date before the tag. Compare only with older entries. + released = [v for v in released if v != _version()] assert released, "CHANGELOG.md lists no released versions" assert _as_tuple(_version()) > max(map(_as_tuple, released))