Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 11 additions & 20 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
4 changes: 1 addition & 3 deletions .github/workflows/testpypi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
43 changes: 43 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,45 @@ adheres to [Semantic Versioning](https://semver.org/).

## [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
`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
`<col>_outlier` column. Both were accepted before but did nothing.
- `fd.clean()` and `fd.Cleaner()` take `CleanConfig` fields as keyword
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions benchmarks/baselines/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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"]
2 changes: 1 addition & 1 deletion benchmarks/bench_outofcore.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__":
Expand Down
1 change: 1 addition & 0 deletions benchmarks/bench_v3_lazy_vs_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import argparse
import json
import platform

try:
import resource
except ImportError:
Expand Down
8 changes: 4 additions & 4 deletions benchmarks/fixtures/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
4 changes: 2 additions & 2 deletions benchmarks/fixtures/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions benchmarks/fixtures/crm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/fixtures/finance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/fixtures/gold.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/fixtures/wide_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/performance/__init__.py
Original file line number Diff line number Diff line change
@@ -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"]
5 changes: 3 additions & 2 deletions benchmarks/performance/baselines.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/performance/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 3 additions & 2 deletions benchmarks/performance/instrumentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"),
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/performance/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions benchmarks/performance/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
if TYPE_CHECKING:
from .instrumentation import ProfileResult

JsonValue = Union[
JsonValue = Union[ # noqa: UP007
None,
bool,
int,
Expand Down Expand Up @@ -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)
2 changes: 1 addition & 1 deletion benchmarks/performance/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -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", []))
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/performance/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/performance/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Loading
Loading