Mental model
Data quality contracts turn assumptions about a batch into executable constraints on schema, values, completeness, uniqueness, and distributions. Deequ computes Spark metrics and evaluates assertions over those metrics; Great Expectations evaluates named expectations and returns per-expectation and suite-level results. A reliable gate binds every result to the exact batch and defines whether failures block, quarantine, or warn.
Learning outcomes
- Translate business assumptions into measurable field-level and dataset-level constraints.
- Distinguish aggregate metric failures from row-level records suitable for quarantine.
- Interpret Deequ check status and Great Expectations suite and expectation results.
- Bind each validation decision to the exact batch, partition, and contract version.
Theory
A data contract is an executable boundary between producers and consumers. It should state which fields are required, their types and allowed domains, what makes a row unique, and which distribution shifts deserve a warning or a block. A hard invariant such as “event_id is present” is different from a statistical monitor such as “the usual event share is near its trailing baseline.” The first can reject malformed rows; the second needs a window, seasonality model, and response policy to avoid mistaking a holiday or product launch for corruption.
Deequ expresses assumptions as checks and constraints over a Spark dataset. A VerificationSuite runs the configured checks, computes the metrics they need with Spark jobs, then evaluates assertions such as completeness, uniqueness, allowed values, or a quantile bound. The result includes suite status and constraint results, so a pipeline can report which condition failed. Deequ can also produce row-level outcomes for supported rules, but a dataset-level row-count or mean constraint does not identify offending records by itself.
Great Expectations organizes checks as Expectations in a suite. Running a Checkpoint produces an ExpectationSuiteValidationResult with a suite-level success flag, individual results, summary statistics, and metadata identifying the batch and resources used. The suite flag is true only when all Expectations pass. A checkpoint result is evidence about the validated batch; orchestration code still decides whether the result blocks a publish, writes a quarantine manifest, or emits a warning.
A reliable gate keeps rule evaluation separate from disposition. First resolve an immutable batch or partition and the contract version. Then evaluate the expectations and persist the result with its batch ID, source snapshot, and run ID. A hard failure can prevent a curated table's commit marker from appearing; recoverable row failures can be written to quarantine with rule identifiers; warnings can proceed only if an owner and expiry policy are defined. This preserves enough evidence to reproduce a decision after the input changes.
Worked completeness calculation
For a required column c in a batch of N rows, define completeness as:
Here, nonNull(c) is the number of non-null values in column c, N is the batch row count, and theta_c is the contract's minimum fraction from 0 to 1. For a 2,000,000-row order batch with 2,600 missing event IDs, completeness is 1,997,400 / 2,000,000 = 0.9987, or 99.87%. If the contract requires 99.95%, it fails by 0.08 percentage points. A separate uniqueness check may also fail if duplicate IDs exist. The gate should retain the immutable batch and validation result, then either quarantine affected rows or block publication according to the declared consumer risk.
Failure modes and misconceptions
- Checking the wrong batch. A successful result can still be misapplied if its validation metadata refers to a different partition or source snapshot. Bind the batch identifier and versioned contract into the result record.
- Treating aggregate metrics as row diagnostics. A low completeness score proves a fraction failed; it does not identify which rows to quarantine unless the validation path retains row-level outcomes.
- Choosing the wrong uniqueness scope. An event ID may be unique only within a tenant. Encode the composite key the consumer relies on instead of enforcing global uniqueness by accident.
- Letting soft expectations silently block or pass. Thresholds need severity and action semantics. A warning that is never reviewed becomes noise; a hard check on a seasonal distribution can stop valid data.
- Ignoring full-dataset cost. Completeness, uniqueness, and distribution checks may trigger Spark scans or shuffles. Reuse computed metrics where possible and measure validation cost on production-size batches.
- Publishing partial work after a failed check. Write staged data first and create the consumer-visible manifest or table commit only after the gate's required constraints pass.
Trade-offs
| Validation design | Advantage | Cost or limitation |
|---|---|---|
| Deequ checks over Spark | Computes large-batch metrics in the same distributed data plane | Spark jobs, scans, and shuffles add latency and cluster cost |
| Great Expectations suites and checkpoints | Gives named expectations, per-expectation outcomes, statistics, and batch metadata | Result detail can be large; callers must map failures to an explicit operational action |
| Hard threshold | Prevents known-invalid data from reaching strict consumers | False positives can block a whole batch and delay downstream SLAs |
| Quarantine with warning | Preserves usable records while retaining rejected rows for repair | Requires row-level identification, retention controls, and owner follow-up |
Treat the contract as versioned production code. A threshold change should be reviewed with the producer and consumer, and results should be compared against known-good history before enforcement. Prefer exact invariant checks for identity, schema, and key uniqueness; use statistical anomaly rules as monitored signals until their false-positive rate is understood.
Decision scenario
An order stream produces 2,000,000 rows. The validation result reports 99.87% completeness for event_id against a 99.95% requirement and also reports duplicate IDs. The business permits a short delay but requires every published order to have one stable identifier. Hold the curated partition's publish marker, retain the exact input snapshot and validation result, and quarantine or repair rows identified by the row-level path. Keep the completeness and uniqueness failures blocking; do not lower the threshold merely to make the checkpoint green. If a separate optional campaign field has only a warning-level expectation, record its failures and let the contract owner review them without weakening identity guarantees.
Implementation pattern
This Deequ example runs batch constraints on a Spark DataFrame and prints individual failed constraints before returning a non-success status to the orchestrator. The object-storage commit should happen only after the verification status succeeds.
scalaimport com.amazon.deequ.VerificationSuiteimport com.amazon.deequ.checks.{Check, CheckLevel, CheckStatus}import com.amazon.deequ.constraints.ConstraintStatusimport org.apache.spark.sql.SparkSessionobject ValidateOrders {def main(args: Array[String]): Unit = {val spark = SparkSession.builder().appName("validate-orders").getOrCreate()val data = spark.read.parquet(args(0))val result = VerificationSuite().onData(data).addCheck(Check(CheckLevel.Error, "order_events").isComplete("event_id").isUnique("event_id").isContainedIn("event_type", Array("view", "purchase"))).run()val failures = result.checkResults.values.flatMap(_.constraintResults).filter(_.status != ConstraintStatus.Success)failures.foreach(f => println(f.constraint.toString + ": " + f.message.getOrElse("failed")))spark.stop()if (result.status != CheckStatus.Success) sys.error("quality gate rejected batch")}}