Skip to main content

pyspark-contracts

Lightweight schema and data quality validation for PySpark DataFrames.

Validates at runtime — before your pipeline runs — with a structured JSON report queryable in CloudWatch Logs Insights, Datadog, or any log aggregator.

Install

pip install pyspark-contracts

PySpark is assumed to be on your classpath (Glue, Databricks, EMR). For local development: pip install pyspark-contracts[pyspark]

Quick start

from pyspark.sql.types import DateType, FloatType, StringType
from pyspark_contracts import Contract, Field

class OdometerContract(Contract):
    vin           = Field(StringType(), nullable=False, min_length=17, max_length=17)
    odometerStart = Field(FloatType(),  nullable=False, min_value=0)
    odometerEnd   = Field(FloatType(),  nullable=False, min_value=0)
    readingDate   = Field(DateType())

# Hard fail (default) — logs ERROR + raises ContractViolationError
OdometerContract().validate(df)

# Soft fail — logs WARNING + returns ViolationReport
report = OdometerContract().validate(df, mode="soft")
if report:
    print(f"{len(report.violations)} violation(s) found")

Validation modes

Mode On violation Return
"hard" (default) Logs ERROR (JSON), raises ContractViolationError —
"soft" Logs WARNING (JSON), continues ViolationReport

Bringing your own logger

import logging
logger = logging.getLogger("my-etl-job")
OdometerContract().validate(df, logger=logger)

If no logger is passed, the library emits JSON to stdout.

Field options

Option Type Description
nullable bool Default True. Set False to fail on null values.
min_value numeric / date Minimum allowed value.
max_value numeric / date Maximum allowed value.
min_length int Minimum string length.
max_length int Maximum string length.
regex str Regex pattern (must match entire value via rlike).
allowed_values list Allowlist of valid values.

Log output

Both modes emit the same structured JSON before acting:

{
  "level": "ERROR",
  "message": "contract violation — job aborted",
  "contract": "OdometerContract",
  "mode": "hard",
  "violations": [
    {"kind": "missing_column", "column": "odometerStart", "expected_type": "FloatType"},
    {"kind": "value_out_of_range", "column": "odometerEnd", "constraint": "min_value=0", "row_pct": 2.3}
  ],
  "row_count": 1842
}

CloudWatch Logs Insights

-- All contract violations in the last 7 days
filter message = "contract violation — job aborted"
| stats count(*) as failures by contract

-- Violations by column across all runs
filter ispresent(violations)
| flatten violations
| stats count(*) by violations.kind, violations.column

Violation kinds

Kind Trigger
missing_column Column declared in contract is absent from the DataFrame
type_mismatch Column exists but type differs from declared type
null_violation nullable=False column contains null values
value_out_of_range Value below min_value or above max_value
length_out_of_range String length below min_length or above max_length
regex_mismatch Value does not match regex pattern
value_not_allowed Value not in allowed_values list

Performance note

Each quality constraint triggers a Spark action (filter + count). For DataFrames with many constraints, consider caching before validation:

df = df.cache()
OdometerContract().validate(df)

Metadata

Release files for pyspark-contracts 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pyspark-contracts 0.1.0
File Size Uploaded
pyspark_contracts-0.1.0.tar.gz 12.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for pyspark-contracts 0.1.0
File Interpreter ABI Platform
pyspark_contracts-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 26.7 kB

Release files / pyspark_contracts-0.1.0.tar.gz

Download URL pyspark_contracts-0.1.0.tar.gz
Size 12.4 kB
Tags Source
SHA-256 checksum
How to use checksums
ffad1ff631bbf2a62cb4bd2675e13c3c6ee49934a639174a7fc62ac5ce730d78
BLAKE2b-256 checksum
How to use checksums
e9a845a0b2c3cfd12029a318c4aea63530f36842bc23ddb2b6d4a14ed2676175
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 23, 2026.

Transparency log

Release files / pyspark_contracts-0.1.0-py3-none-any.whl

Download URL pyspark_contracts-0.1.0-py3-none-any.whl
Size 14.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
06271072171436913c0a48d58d2068482ffc161266cbe2b42896e60eb0e2b258
BLAKE2b-256 checksum
How to use checksums
c25d4da37a07181b270727edff4be529aae100c64a0be830727150e4e4101521
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 23, 2026.

Transparency log

Release history Release notifications | RSS feed

0.10.0

2 release files

0.9.0

2 release files

0.8.2

2 release files

0.8.1

2 release files

0.8.0

2 release files

0.7.1

2 release files

0.7.0

2 release files

0.6.0

2 release files

0.5.0

2 release files

0.4.0

2 release files

0.3.0

2 release files

0.2.1

2 release files

0.2.0

2 release files

This release

0.1.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page