Metadata-Version: 2.5
Name: dqflow
Version: 0.5.0
Summary: Data contracts for Python data pipelines. Define, validate, fail fast.
Project-URL: Homepage, https://github.com/dqflow/dqflow
Project-URL: Repository, https://github.com/dqflow/dqflow
Project-URL: Documentation, https://dqflow.readthedocs.io/en/latest/
Project-URL: Issues, https://github.com/dqflow/dqflow/issues
Project-URL: Discussions, https://github.com/dqflow/dqflow/discussions
Project-URL: Changelog, https://github.com/dqflow/dqflow/blob/main/CHANGELOG.md
Project-URL: Roadmap, https://github.com/dqflow/dqflow/blob/main/ROADMAP.md
Author-email: Quang <nguyenvanquang247@gmail.com>
License-Expression: MIT
License-File: LICENSE
Keywords: ci-cd,data-contract,data-contracts,data-engineering,data-quality,data-validation,dataframe,etl,pandas,polars,schema-validation
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: <3.15,>=3.11
Requires-Dist: click<9,>=8.1.7
Requires-Dist: pyyaml<7,>=6.0.2
Provides-Extra: all
Requires-Dist: pandas<4,>=2.3.3; extra == 'all'
Requires-Dist: polars<2,>=1.0; extra == 'all'
Requires-Dist: pyarrow<26,>=22; extra == 'all'
Provides-Extra: dev
Requires-Dist: jsonschema>=4.18; extra == 'dev'
Requires-Dist: mypy>=1.0; extra == 'dev'
Requires-Dist: pandas-stubs>=2.3; extra == 'dev'
Requires-Dist: pandas<4,>=2.3.3; extra == 'dev'
Requires-Dist: polars<2,>=1.0; extra == 'dev'
Requires-Dist: pre-commit>=3.0; extra == 'dev'
Requires-Dist: pyarrow<26,>=22; extra == 'dev'
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff==0.14.14; extra == 'dev'
Requires-Dist: types-pyyaml>=6.0; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs>=1.5; extra == 'docs'
Requires-Dist: mkdocstrings[python]>=0.24; extra == 'docs'
Requires-Dist: pymdown-extensions>=10.0; extra == 'docs'
Provides-Extra: pandas
Requires-Dist: pandas<4,>=2.3.3; extra == 'pandas'
Provides-Extra: pandas-parquet
Requires-Dist: pandas<4,>=2.3.3; extra == 'pandas-parquet'
Requires-Dist: pyarrow<26,>=22; extra == 'pandas-parquet'
Provides-Extra: parquet
Requires-Dist: pandas<4,>=2.3.3; extra == 'parquet'
Requires-Dist: pyarrow<26,>=22; extra == 'parquet'
Provides-Extra: polars
Requires-Dist: polars<2,>=1.0; extra == 'polars'
Description-Content-Type: text/markdown

# dqflow

<p align="center">
  <picture>
    <source
      media="(prefers-color-scheme: dark)"
      srcset="https://raw.githubusercontent.com/dqflow/dqflow/main/docs/assets/dqflow-dark-logo.png"
    />
    <img
      src="https://raw.githubusercontent.com/dqflow/dqflow/main/docs/assets/dqflow-light-logo.png"
      width="360"
      alt="dqflow"
    />
  </picture>
</p>

<h2 align="center">Data contracts for Python data pipelines.</h2>
<p align="center"><strong>Infer → Validate → Diff → Gate the PR</strong></p>

<p align="center">
  <a href="https://pypi.org/project/dqflow/"><img src="https://img.shields.io/pypi/v/dqflow.svg" alt="PyPI version"></a>
  <a href="https://github.com/dqflow/dqflow/actions/workflows/ci.yml"><img src="https://github.com/dqflow/dqflow/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
  <a href="https://dqflow.readthedocs.io/en/latest/"><img src="https://img.shields.io/badge/docs-read%20the%20docs-blue.svg" alt="Docs"></a>
  <a href="https://pypi.org/project/dqflow/"><img src="https://img.shields.io/pypi/pyversions/dqflow.svg" alt="Python versions"></a>
  <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
</p>

<p align="center">
  <a href="https://dqflow.readthedocs.io/en/latest/getting-started/quickstart/"><strong>5-minute quickstart</strong></a> ·
  <a href="https://dqflow.readthedocs.io/en/latest/">Documentation</a> ·
  <a href="https://dqflow.readthedocs.io/en/latest/comparison/">Compare</a> ·
  <a href="https://github.com/dqflow/dqflow/tree/main/examples">Examples</a> ·
  <a href="https://pypi.org/project/dqflow/">PyPI</a> ·
  <a href="https://github.com/dqflow/dqflow/blob/main/ROADMAP.md">Roadmap</a> ·
  <a href="https://github.com/dqflow/dqflow/discussions">Discussions</a>
</p>

---

**dqflow** treats a data contract like a versioned API. Validate data at runtime,
then compare contract revisions during review and block a pull request before a
breaking requirement reaches data producers.

**New to dqflow?** Go from install to first validation with the
**[5-minute quickstart](https://dqflow.readthedocs.io/en/latest/getting-started/quickstart/)**,
then add the copyable **[CI/CD gate](https://dqflow.readthedocs.io/en/latest/workflows/ci-pull-request/)**.

## Workflow

```text
  1. INFER             2. VALIDATE            3. DIFF              4. GATE
  ────────             ───────────            ────────             ────────
  data → draft    ─▶   contract + data   ─▶   old vs new      ─▶   exit 1 blocks
  refine in git        catch bad rows         classify changes     the pull request
```

Validation and diffing catch different failures: `dq validate` catches data that
violates a contract at runtime; `dq diff` catches a contract edit that may reject
previously valid producer data before merge.

## Catch a breaking contract change

| `orders-v1.yaml` | `orders-v2.yaml` |
| --- | --- |
| `amount:`<br>&nbsp;&nbsp;`min: 0`<br>`currency:`<br>&nbsp;&nbsp;`allowed: [USD, EUR]`<br>*(no `discount` column)* | `amount:`<br>&nbsp;&nbsp;`min: 1` **breaking**<br>`currency:`<br>&nbsp;&nbsp;`allowed: [USD, EUR, GBP]` **non-breaking**<br>`discount:`<br>&nbsp;&nbsp;`dtype: float` **non-breaking** |

```console
$ dq diff orders-v1.yaml orders-v2.yaml
orders: 3 changes (1 breaking)

  BREAKING
    ~ column "amount" min: 0 -> 1  (stricter lower bound)

  non-breaking
    ~ column "currency" allowed: +[GBP]  (widened allowed set)
    + column "discount" (float)          (new nullable column)

$ echo $?
1
```

A change is breaking when data accepted by the old contract may be rejected by
the new one. Because `dq diff` exits `1`, the same command is a CI gate—no custom
service required. See the **[contract diff guide](https://dqflow.readthedocs.io/en/latest/guide/diff/)**,
the **[runnable example](https://github.com/dqflow/dqflow/tree/main/examples/contract-diff)**,
and its copyable GitHub Actions workflow.

![dq diff blocks a breaking contract change](https://raw.githubusercontent.com/dqflow/dqflow/main/docs/assets/contract-diff-demo.svg)

## Why dqflow

- **Contracts, not scattered asserts.** One declarative artifact — reviewed, diffed,
  and versioned like the rest of your code.
- **Lightweight.** The base install has only `pyyaml` and `click`; pandas and
  Polars are opt-in backends. No server, database, or daemon.
- **Pythonic.** Plain `Contract` / `Column` objects, or YAML. Validation returns a
  structured result object, not a stack trace.
- **Fail fast, on purpose.** `result.ok` is a boolean; `dq validate --fail-fast`
  returns a non-zero exit code. Wire it into a pipeline task or a CI step.
- **Deliberately scoped.** dqflow emits structured results — it does not try to be a
  monitoring platform.

## How dqflow compares

dqflow's wedge is the **contract pull-request gate for in-memory Python
DataFrames** — not the largest check catalogue or a data platform. Prefer
**Pandera** for typed schema models across many backends and statistical checks;
**Great Expectations** for a huge expectation library and HTML Data Docs;
**Soda** for warehouse-native SQL checks; **Data Contract CLI** for ODCS and
broad format interoperability.

The [comparison guide](https://dqflow.readthedocs.io/en/latest/comparison/) has
the full table, an honest limitations list, and a
[migration guide from Pandera](https://dqflow.readthedocs.io/en/latest/comparison/from-pandera/).

## Installation

```bash
pip install "dqflow[pandas]"

# optional, experimental Polars engine
pip install "dqflow[polars]"

# pandas plus PyArrow-backed Parquet files in the CLI
pip install "dqflow[pandas-parquet]"
```

Supports Python 3.11–3.14. The base `pip install dqflow` includes no dataframe
backend; see the [compatibility matrix](https://dqflow.readthedocs.io/en/latest/reference/compatibility/).

> `dtype` and `pattern` are enforced by both validation engines.
> `freshness_minutes` and `custom` can be declared but are not enforced yet.

## 30-second Quick Start

```python
import pandas as pd
from dqflow import Contract, Column

df = pd.DataFrame({
    "order_id": ["A001", "A002", None, "A004"],
    "amount":   [19.99, -5.00, 42.50, 99.00],
    "currency": ["USD", "EUR", "USD", "GBP"],
})

contract = Contract(
    name="orders",
    columns={
        "order_id": Column(str, not_null=True, unique=True),
        "amount":   Column(float, min=0),
        "currency": Column(str, allowed=["USD", "EUR"]),
    },
    rules=["row_count > 0"],
)

result = contract.validate(df)
print(result.summary())

if not result.ok:
    raise ValueError(result.summary())
```

```text
Contract 'orders': 8/11 checks passed
Failed checks:
  - not_null:order_id: Column 'order_id' has 1 null value
  - min:amount: Column 'amount' has 1 value below the minimum 0
  - allowed:currency: Column 'currency' has 1 value outside the allowed set
```

## Python contract

Contracts also carry table rules and cross-column rules, and hand back a structured
result.

```python
import pandas as pd
from dqflow import Contract, Column, CrossColumnRule

df = pd.DataFrame({
    "order_id":   ["A001", "A002", "A003"],
    "amount":     [19.99, 5.00, 42.50],
    "currency":   ["USD", "EUR", "USD"],
    "created_at": pd.to_datetime(["2026-08-01", "2026-08-02", "2026-08-03"]),
    "shipped_at": pd.to_datetime(["2026-08-02", "2026-08-01", "2026-08-05"]),
})

contract = Contract(
    name="orders",
    description="Orders emitted by the checkout service",
    columns={
        "order_id":   Column(str, not_null=True, unique=True),
        "amount":     Column(float, min=0, max=100_000),
        "currency":   Column(str, allowed=["USD", "EUR"]),
        "created_at": Column("timestamp", not_null=True),
    },
    rules=[
        "row_count > 0",
        "null_rate('amount') < 0.01",
        "unique_count('currency') <= 3",
    ],
    cross_column_rules=[
        CrossColumnRule(
            name="shipped_after_created",
            left="shipped_at", op=">=", right="created_at",
            error_message="shipped_at must not precede created_at",
        ),
    ],
)

result = contract.validate(df)
print(result.summary())

result.ok              # bool  — did every check pass?
result.failed_checks   # list[CheckResult]
result.to_dict()       # JSON-serializable dict for logs / CI
```

```text
Contract 'orders': 17/18 checks passed
Failed checks:
  - cross_column:shipped_after_created: shipped_at must not precede created_at
```

Rule expressions expose the names
`row_count`, `null_rate('column')`, and `unique_count('column')` — column names are
passed as strings. Expressions are evaluated by a shared, whitelisted AST walker
(`dqflow.rules.evaluate_rule`), not `eval` — but that is still not a security
boundary, so do not load contracts from untrusted sources.

## YAML contract

The same contract lives just as well in version control as YAML.

```yaml
# contracts/orders.yaml
name: orders
description: Orders emitted by the checkout service

columns:
  order_id:
    type: string
    not_null: true
    unique: true
  amount:
    type: float
    min: 0
  currency:
    type: string
    allowed: ["USD", "EUR"]

rules:
  - row_count > 0
  - "null_rate('order_id') == 0"
```

```python
from dqflow import Contract

# load from YAML (or write a contract back out with contract.to_yaml(path))
contract = Contract.from_yaml("contracts/orders.yaml")
result = contract.validate(df)
```

## CLI usage

The `dq` command validates data files (`.csv`, `.parquet`, `.json`) against a YAML
contract.

```bash
# Validate data against a contract
dq validate contracts/orders.yaml data/orders.csv

# Non-zero exit code on failure — drop this into CI
dq validate contracts/orders.yaml data/orders.csv --fail-fast

# Only the failures (-q), or every check with its samples (-v)
dq validate contracts/orders.yaml data/orders.csv --quiet

# Machine-readable output
dq validate contracts/orders.yaml data/orders.csv --output json

# Check a contract for schema/structural problems (no data needed)
dq lint contracts/orders.yaml

# Inspect a contract
dq show contracts/orders.yaml

# Infer a draft contract (dtypes and observed constraints) from existing data
dq infer data/orders.csv contracts/orders.yaml --sample 100000

# Diff two contract versions; exits 1 when a change is breaking for producers
dq diff contracts/orders@v1.yaml contracts/orders@v2.yaml
```

Text output is grouped by schema / columns / table rules / cross-column rules,
with per-check failure rates and a bounded sample of the offending values. Colour
is used on a TTY and disabled when piped or when `NO_COLOR` is set; `-q/--quiet`
prints only the failures, `-v/--verbose` prints every check.

`--fail-fast` evaluates the complete contract, prints all failed checks, and then
returns exit code `1` when validation fails. It does not stop after the first
failed check. Parquet input with pandas requires `dqflow[pandas-parquet]`.

Given `data/orders.csv` where `order_id` has a duplicate and a null, `amount` has a
negative value, and `currency` contains `GBP`:

```console
$ dq validate contracts/orders.yaml data/orders.csv --fail-fast
orders · 5 of 11 checks failed on 4 rows

  Schema  3/3 passed

  Columns  4/7 failed
    order_id  ✘ not_null  has 1 null value (25.0%)
              ✘ unique    has 2 non-unique values (50.0%)  ·  e.g. 'A001'
    amount    ✘ min       has 1 value below the minimum 0 (25.0%)
    currency  ✘ allowed   has 1 value outside the allowed set (25.0%)  ·  e.g. 'GBP'

  Table rules  1/1 failed
    ✘ null_rate('order_id') == 0

  6 passed · 5 failed
$ echo $?          # --fail-fast turns a failed contract into a non-zero exit
1
```

## Features

| Capability | Status |
| --- | --- |
| Python contracts — `Contract`, `Column`, `CrossColumnRule` | ✅ Implemented |
| YAML contracts — `Contract.from_yaml()` / `.to_yaml()` | ✅ Implemented |
| Schema check — required columns must be present in the data | ✅ Implemented |
| Validity checks — `dtype`, `not_null`, `min`, `max`, `allowed`, `unique`, `pattern` | ✅ Implemented |
| Table rules — `row_count`, `null_rate('col')`, `unique_count('col')` | ✅ Implemented |
| Cross-column rules — `left`/`op`/`right` or a callable | ✅ Implemented |
| Structured results — `.ok`, `.failed_checks`, `.summary()`, `.to_dict()` | ✅ Implemented |
| CLI — `dq validate` / `dq lint` / `dq show` / `dq infer` / `dq diff` / `dq schema` | ✅ Implemented |
| Contract inference from data (dtypes and observed constraints) | ✅ Implemented |
| Contract diff — breaking / non-breaking classification, JSON, CI exit code | ✅ Implemented |
| Versioned schema — `schema_version`, `dq lint` diagnostics, published JSON Schema for editors | ✅ Implemented |
| pandas engine | ✅ Implemented |
| Polars engine (`dqflow[polars]`) | 🧪 Experimental |
| Logical dtype enforcement | ✅ Implemented for integer, float, string, boolean, and timestamp |
| `freshness_minutes` / `custom` enforcement | 🔜 Declared in the contract, not yet enforced |
| GitHub Action, HTML reports, severity levels | 🔜 Planned — see [ROADMAP.md](https://github.com/dqflow/dqflow/blob/main/ROADMAP.md) |
| PySpark & SQL engines | 🔜 Planned — see [ROADMAP.md](https://github.com/dqflow/dqflow/blob/main/ROADMAP.md) |

> Both engines enforce logical `dtype` and regex `pattern` constraints.
> `freshness_minutes` and `custom` remain descriptive until the roadmap catches up.

## Stability

dqflow is `0.x` and still moving. A small set of surfaces — the `dqflow` /
`dqflow.schema` public API, the `dq` CLI and its exit codes, and the
`--output json` payloads — is treated as a compatibility contract: changes are
listed in the [changelog](https://github.com/dqflow/dqflow/blob/main/CHANGELOG.md)
with a migration note, and a CI snapshot test blocks accidental breakage. See

[Stability & compatibility](https://dqflow.readthedocs.io/en/latest/reference/stability/)
and the [1.0 readiness checklist](https://dqflow.readthedocs.io/en/latest/reference/v1-readiness/).



## Architecture

```text
  Contract                            Python object or YAML file
  columns · rules · cross-column rules
      │
      ▼
  ValidationSpec    ✓                  contract compiled to a shared IR
  dqflow.rules      ✓                  one AST rule evaluator, no eval
  StatsCache        ✓                  shared lazy column-stats cache
  ExecutionContext  ✓                  runtime knobs — engine, cache
      │
      ▼
  Engine  ───────────────────────▶     pandas   default, stable
      │                                Polars   experimental
      ▼
  ValidationResult  ─────────────▶     your pipeline / CI
  .ok · .summary() · .to_dict()        raise · non-zero exit · JSON logs
```

`Contract.validate()` compiles the contract to a shared `ValidationSpec`, rule
expressions run through the shared `dqflow.rules` evaluator (no `eval`), and
table-rule statistics come from a shared lazy `StatsCache` (all shipped in
0.4.0). The run's engine, cache toggle, and (reserved) execution flags are
carried in one `ExecutionContext` — passed as
`contract.validate(df, context=ExecutionContext(...))` or built from the
`engine=` shortcut and `dq validate --engine`
([issue #15](https://github.com/dqflow/dqflow/issues/15)).

## Supported engines

| Engine | Input | Status |
| --- | --- | --- |
| **pandas** | `pandas.DataFrame` | Default, stable |
| **Polars** | `polars.DataFrame` / `LazyFrame` | Experimental — `pip install "dqflow[polars]"` |
| PySpark | `pyspark.sql.DataFrame` | Planned |
| SQL | warehouse table / query | Planned |

```python
from dqflow.engines.polars import PolarsEngine

result = contract.validate(polars_df, engine=PolarsEngine())
```

## Runnable examples

The [`examples/`](https://github.com/dqflow/dqflow/tree/main/examples) directory
contains six self-contained projects. Each one includes sample data or contracts,
a runnable script, and its own README.

| Example | What it demonstrates | Install |
| --- | --- | --- |
| [pandas ETL](https://github.com/dqflow/dqflow/tree/main/examples/pandas-etl) | Validate transformed orders before publishing downstream | `pip install "dqflow[pandas]"` |
| [Polars pipeline](https://github.com/dqflow/dqflow/tree/main/examples/polars-pipeline) | Validate a Polars `LazyFrame` with the experimental engine | `pip install "dqflow[polars]"` |
| [CI validation](https://github.com/dqflow/dqflow/tree/main/examples/ci-validation) | Turn a failed YAML contract into a non-zero CI exit code | `pip install "dqflow[pandas]"` |
| [Infer and refine](https://github.com/dqflow/dqflow/tree/main/examples/infer-refine) | Infer a draft, replace observed bounds with business rules, and validate it | `pip install "dqflow[pandas]"` |
| [Contract diff](https://github.com/dqflow/dqflow/tree/main/examples/contract-diff) | Compare two contract versions and block breaking changes | `pip install dqflow` |
| [First PR gate](https://github.com/dqflow/dqflow/tree/main/examples/first-pr-gate) | Copyable starter — a stricter contract fails the pull-request check | `pip install "dqflow[pandas]"` |

Run them from the repository root:

```bash
python examples/pandas-etl/pipeline.py
python examples/polars-pipeline/pipeline.py
python examples/ci-validation/validate.py
python examples/infer-refine/infer_and_validate.py
python examples/contract-diff/diff.py
python examples/first-pr-gate/gate.py
```

Expected output:

```text
Contract 'orders': 12/12 checks passed
published 3 valid orders

Contract 'events': 12/12 checks passed
validated 3 Polars rows

Contract 'users': 14/14 checks passed

Contract 'customers': 15/15 checks passed
reviewed the inferred draft and validated the curated contract

orders: 3 changes (1 breaking)
blocked: 1 breaking change(s) for data producers

orders: 3 changes (2 breaking)
first-pr-gate: blocked a breaking contract change before merge
```

All six scripts are also exercised by
[`tests/test_examples.py`](https://github.com/dqflow/dqflow/blob/main/tests/test_examples.py).

## When to use dqflow

- You have Python data pipelines — Airflow, Dagster, Prefect, dbt-adjacent scripts,
  notebooks headed for production.
- You want data expectations in git, reviewed in pull requests.
- You want a pipeline step or CI job to **hard-fail** on bad data instead of passing
  it downstream.
- Your data fits in memory as a pandas (or Polars) DataFrame.
- You want structured pass/fail output to feed your own logs or dashboards.

## When *not* to use dqflow

- You need dashboards, alerting, anomaly detection, or lineage — dqflow produces
  files and exit codes, not a web app.
- You need to push checks down to a warehouse table without loading it (SQL engine is
  planned, not available).
- You need Spark-scale distributed validation (PySpark engine is planned).
- You need freshness or `custom` column functions enforced today — those fields
  are declared but not yet checked. Logical dtype and regex `pattern` checks are
  enforced.
- You need to execute contracts from untrusted sources — rule expressions use a
  whitelisted AST evaluator (no `eval`), which is still not a security boundary.

> **dqflow is not a full data observability platform.** It is a small, opinionated
> library meant to be embedded directly into pipelines. Where richer tooling is
> useful, dqflow's job is to emit clean, structured results those systems can consume.

## Roadmap

A GitHub Action, HTML reports, severity levels, Polars parity, and PySpark / SQL
engines are all planned. See **[ROADMAP.md](https://github.com/dqflow/dqflow/blob/main/ROADMAP.md)** for the full
plan, priorities, and non-goals.

## Community

- **Questions & help** — [GitHub Discussions](https://github.com/dqflow/dqflow/discussions)
- **Bugs, features, integrations** — [open an issue](https://github.com/dqflow/dqflow/issues/new/choose)
- **Design proposals & roadmap feedback** — RFC / Roadmap discussions
- **Find something to work on** — [`good first issue`](https://github.com/dqflow/dqflow/labels/good%20first%20issue)

See the [community guide](https://dqflow.readthedocs.io/en/latest/community/) for
maintainer response expectations and how the project grows.

## Contributing

Issues and pull requests are welcome. See [CONTRIBUTING.md](https://github.com/dqflow/dqflow/blob/main/CONTRIBUTING.md)
and the [Code of Conduct](https://github.com/dqflow/dqflow/blob/main/CODE_OF_CONDUCT.md).

```bash
git clone https://github.com/dqflow/dqflow.git
cd dqflow
pip install -e ".[dev]"

pytest              # run tests
ruff check .        # lint
mypy src/dqflow     # type-check
```

## License

[MIT](https://github.com/dqflow/dqflow/blob/main/LICENSE)
