/bauplan:bauplan-data-quality-checksfrom bauplan
Generates data quality check code for bauplan pipelines and ingestion workflows. Produces expectations.py using @bauplan.expectation() or validate_import() functions for WAP scripts. Requires table, branch, and check specifications.
Ships in bauplan. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
This skill writes data quality check code. It produces one of two things:
expectations.py file using @bauplan.expectation() that runs as part of bauplan run.validate_import() function using the bauplan SDK, embedded in a WAP script between import_data() and merge_branch().Output is always working code. Not reports, not profiling summaries, not markdown.
This skill is invoked by the bauplan-data-pipeline and bauplan-safe-ingestion workflow skills when they determine that quality checks are needed. It can also be invoked directly by the user. Either way, the skill needs to know three things before it can write code:
namespace.table_name and the ref to validate againstmodels.py exists that consumes the table. Read it, derive checks, propose them to the user for confirmation, then write code.If the skill is invoked without enough information, ask for what's missing. But ask for specifics — "which columns and what properties?" — not for a general description of the pipeline's purpose.
NEVER run checks or pipelines on
main. All validation targets a development or import branch.
Branch naming convention: <username>.<branch_name>. Get your username with bauplan info.
Before writing any Python, check whether the project uses uv (look for pyproject.toml or uv.lock). If so, use uv run python to execute scripts and uv add to install packages. Otherwise, use the system python and pip install.
Ensure the required packages are installed:
bauplan (the Bauplan Python SDK — required)polars (if custom expectations need DataFrame operations — zero-copy Arrow interop)Ensure the environment has a typed SDK build (0.3.0+). Typed declarations are only available with SDK 0.3.0+: older versions are not compatible. Use that same environment for all CLI commands and verify connectivity with bauplan info. Models declare their own runtime dependencies via @bauplan.python('3.13', pip={...}); annotation imports require pyarrow locally too.
Do not use pandas. Bauplan's client.query() returns a PyArrow table directly: no .to_arrow() call needed. In pipeline expectations, model inputs arrive as Arrow tables too. Polars reads Arrow natively with zero-copy (pl.DataFrame(table)). Pandas requires a full data copy and is slower.
This section is the foundation. It applies to both pipeline expectations and ingestion validation — the thinking is identical, only the code form differs.
When the user provides explicit specifications, much of this thinking is already done. Translate their specs to code, using the methodology below to fill in gaps (e.g., a check the user phrased as a warning: either give it a threshold worth stopping the run on, or leave it out).
When deriving checks from pipeline code, this methodology is the primary tool.
Profiling is exploratory — you compute statistics to learn what the data looks like. You don't know the shape yet. Use the bauplan-explore-data skill for this.
Testing is confirmatory — you know what the data should look like and you verify that it does. Every check encodes a specific expectation that can pass or fail.
The workflow is: profile once to understand the data, form assumptions from what you learn, then encode those assumptions as tests using this skill. If the user hasn't profiled the data and can't state what they expect, they're not ready for this skill yet — point them to bauplan-explore-data first.
For each column you check, state why you're checking it and what you expect. If you can't state why, drop the check. Each check tests one thing. Ten focused checks with clear assertions beat a hundred random queries nobody reads.
The anti-pattern: running null counts, uniqueness checks, and range queries on every column in a table because they exist. This produces numbers, not insights. Nobody acts on "column X has 3.2% nulls" unless they know whether 3.2% is acceptable.
Every check encodes a hypothesis. Before writing any expectation or validation query, state it:
"I expect [column] to be [property] because [consumer/reason]; otherwise [impact]."
Examples:
order_id to have no nulls because the billing pipeline joins on it; otherwise every downstream table breaks."event_time to be within the last 24 hours because the dashboard shows daily metrics; otherwise the dashboard shows stale numbers."price to be positive because the revenue model sums it; otherwise revenue totals are wrong."If you cannot fill in this template for a check, you do not have enough context to write it. Ask the user, inspect the schema, or read the downstream models.
When the user provides specifications directly, the "because" clause may be implicit. That's fine — they've done the reasoning. But if a spec is phrased as a warning, decide whether it is worth stopping the run on.
When a models.py exists, find bauplan.Model() inside Annotated[pa.Table, ...] parameters and read each referenced projection and output TableSchema.
projection_schema fields → those columns are needed downstream. Check completeness on critical ones. If no projection is declared, inspect the body to identify columns used.TableField metadata → declared types, nullability (Type | None for optional, a bare type for required), documentation, and lineage describe the contract. Use them alongside the transformation to derive value-level checks; a declared type alone does not prove uniqueness or valid ranges.filter expressions → the model assumes data matching this condition. Check that the assumption holds (e.g., filter="total > 0" → check for non-positive values).bauplan.Model() inputs joined on a key) → the join column needs uniqueness in the parent table and no nulls in both.Example: given this model input, with string identifiers and a double-precision total confirmed from the source schema:
from typing import Annotated
import bauplan
import pyarrow as pa
class OrderCheckColumns(bauplan.TableSchema):
"""Order fields used by the downstream consumer."""
order_id: bauplan.String | None
total: bauplan.Float64 | None
customer_id: bauplan.String | None
# Input parameter declaration inside the consuming model's signature
data: Annotated[
pa.Table,
bauplan.Model('orders', projection_schema=OrderCheckColumns, filter="total > 0"),
]
Derive:
order_id: selected column, likely a key → no nulls (FAIL), unique (FAIL)total: filtered to positive → no nulls (FAIL), all values > 0 (FAIL)customer_id: selected column → no nulls (FAIL); if joined to a customers table → unique in that tableAlways propose derived checks to the user for confirmation before writing code. State each as a plain-language assumption and let the user approve, modify, or remove.
Six dimensions, each producing a specific kind of assertion:
Completeness — are required values present?
expect_column_no_nulls, expect_column_some_null, expect_column_all_nullUniqueness — are identifiers actually unique?
expect_column_all_unique, expect_column_not_uniqueValidity — do values conform to expected format and range?
expect_column_accepted_values, expect_column_mean_greater_than, expect_column_mean_smaller_than, expect_column_mean_greater_or_equal_than, expect_column_mean_smaller_or_equal_thanFreshness — is the data current enough for its purpose?
Consistency — do related values agree?
expect_column_equal_concatenation; custom for most casesVolume — is the amount of data within expected bounds?
Not every table needs all six dimensions. Pick the ones that matter for this table's consumers.
Strict mode is on by default: a False fails the job and nothing is materialized. Before writing a check, decide whether a failure is worth stopping the run.
Worth stopping on: downstream use is unsafe. Examples: missing primary key, zero rows, wrong schema, broken join column, negative values in a revenue column that gets summed. Write it as an expectation.
Not worth stopping on: quality is degraded but the output is still safe to publish. Examples: a slightly higher null rate in a non-critical column, data 2 hours stale against a 24-hour SLA. Tighten the threshold until a breach is worth stopping on, or leave the check out.
If you cannot decide, you do not understand the impact yet. Go back to the consumer analysis.
Every check must run against a specific branch and ref. Never check "whatever main looks like right now."
bauplan run handles this — the run executes against the checked-out branch.client.query() calls use ref=branch_name explicitly.This ensures checks are reproducible. If a check fails, you can go back to exactly that data state and investigate.
my-pipeline/
bauplan_project.yml
models.py
expectations.py ← quality checks live here
Expectations are Python functions in expectations.py in the pipeline project directory, alongside models.py.
An expectation is a function decorated with @bauplan.expectation() that takes one or more tables via Annotated[pa.Table, bauplan.Model(...)] parameters and declares -> bool.
from typing import Annotated
import bauplan
import pyarrow as pa
class OrderIdCheckColumns(bauplan.TableSchema):
"""Order identifier checked for completeness."""
order_id: bauplan.String | None
@bauplan.expectation()
@bauplan.python('3.13')
def test_no_null_order_ids(
data: Annotated[
pa.Table, bauplan.Model('clean_orders', projection_schema=OrderIdCheckColumns)
],
) -> bool:
"""order_id must not be null because billing joins on it."""
from bauplan.standard_expectations import expect_column_no_nulls
return expect_column_no_nulls(data, 'order_id')
Key mechanics:
TableSchema, have docstrings, and use names unique across project files.Model accepts only name, projection_schema, and literal filter; $param templating is supported. Run parameters use Annotated[<Python type>, bauplan.Parameter("name")], matching the YAML parameter type.bauplan run, after the model they depend on completes.True = pass, False = fail. Strict mode is on by default, so a False fails the run; --no-strict (strict=False in the SDK) disables it for the whole run, not per check.The built-in library provides vectorized, SIMD-optimized checks. Always prefer these over hand-rolled equivalents — they are faster, more memory-efficient, and easier to maintain.
Each function takes an Arrow table and returns a boolean:
| Function | Dimension | What it checks |
|---|---|---|
expect_column_no_nulls(table, col) | Completeness | Column has zero null values |
expect_column_some_null(table, col) | Completeness | Column has at least one null |
expect_column_all_null(table, col) | Completeness | Column is entirely null |
expect_column_all_unique(table, col) | Uniqueness | All values are distinct |
expect_column_not_unique(table, col) | Uniqueness | Column has at least one duplicate |
expect_column_accepted_values(table, col, values) | Validity | All values are in allowed set |
expect_column_mean_greater_than(table, col, val) | Validity | Mean exceeds threshold |
expect_column_mean_smaller_than(table, col, val) | Validity | Mean below threshold |
expect_column_mean_greater_or_equal_than(table, col, val) | Validity | Mean >= threshold |
expect_column_mean_smaller_or_equal_than(table, col, val) | Validity | Mean <= threshold |
expect_column_equal_concatenation(table, target, cols, sep) | Consistency | Column equals concatenation of others |
Import them inside the function body, not at module level:
class EventTypeCheckColumns(bauplan.TableSchema):
"""Event category checked against accepted values."""
event_type: bauplan.String | None
@bauplan.expectation()
@bauplan.python('3.13')
def test_valid_event_types(
data: Annotated[
pa.Table, bauplan.Model('staging', projection_schema=EventTypeCheckColumns)
],
) -> bool:
"""event_type must be known because downstream filters depend on it."""
from bauplan.standard_expectations import expect_column_accepted_values
return expect_column_accepted_values(
data, 'event_type', ['view', 'cart', 'purchase', 'remove']
)
For checks not covered by the built-in library — freshness, volume, cross-column logic, referential integrity — write custom expectations using the Arrow table directly or with Polars/DuckDB.
Freshness check:
class SummaryDateCheckColumns(bauplan.TableSchema):
"""Summary timestamp checked for freshness."""
date: bauplan.TimestampMicro | None
@bauplan.expectation()
@bauplan.python('3.13', pip={'polars': '2.0.0'})
def test_data_freshness(
data: Annotated[
pa.Table, bauplan.Model('daily_summary', projection_schema=SummaryDateCheckColumns)
],
) -> bool:
"""Most recent date must be within 2 days for the daily dashboard."""
import polars as pl
from datetime import datetime, timedelta
df = pl.DataFrame(data)
max_date = df.select(pl.col('date').max()).item()
threshold = datetime.now() - timedelta(days=2)
return max_date >= threshold
Volume check:
@bauplan.expectation()
@bauplan.python('3.13')
def test_minimum_row_count(
data: Annotated[pa.Table, bauplan.Model('staging')],
) -> bool:
"""Table must have at least 1000 rows to meet the expected source volume."""
row_count = data.num_rows
return row_count >= 1000
Cross-column consistency:
class TripTimeCheckColumns(bauplan.TableSchema):
"""Trip timestamps checked for chronological consistency."""
pickup_datetime: bauplan.TimestampMicro | None
dropoff_datetime: bauplan.TimestampMicro | None
@bauplan.expectation()
@bauplan.python('3.13', pip={'polars': '2.0.0'})
def test_dates_ordered(
data: Annotated[
pa.Table, bauplan.Model('trips', projection_schema=TripTimeCheckColumns)
],
) -> bool:
"""dropoff must be after pickup for valid trip durations."""
import polars as pl
df = pl.DataFrame(data)
violations = df.filter(pl.col('dropoff_datetime') < pl.col('pickup_datetime'))
return violations.height == 0
Models declare output contracts with -> Annotated[pa.Table, OutputSchema]. The return annotation is mandatory and must take this exact form: a bare -> pa.Table and a missing annotation are both rejected at parse time. The schema declares columns and their types, with Type | None for an optional column and a bare type for a required one. A required output column is enforced by counting nulls in the returned data, so it doubles as a not-null check and makes a separate no-nulls expectation on that column redundant. This example assumes string IDs, double-precision totals, and day-precision dates:
class CleanOrdersSchema(bauplan.TableSchema):
"""Order fields retained for downstream consumers."""
order_id: bauplan.String | None
customer_id: bauplan.String | None
total: bauplan.Float64 | None
order_date: bauplan.Date32 | None
@bauplan.model(materialization_strategy='REPLACE')
@bauplan.python('3.13')
def clean_orders(
data: Annotated[
pa.Table, bauplan.Model('raw_orders', projection_schema=CleanOrdersSchema)
],
) -> Annotated[pa.Table, CleanOrdersSchema]:
"""Retain the order fields required downstream."""
return data
Output schemas are exhaustive and enforced on every run with no flag to opt in: the returned table must carry exactly the declared columns, so a missing column, an extra one, or a dtype mismatch fails the run with ModelOutputContractError. Value-level expectations still check ranges, uniqueness, freshness, and business rules. Flag existing dtype-only expectations as potentially redundant when the corresponding contract covers them; propose replacements without deleting checks silently. Decimal columns and nested output fields have no supported schema type and are annotated bauplan.Any, so the contract does not constrain them and they still need explicit checks.
SQL models use -- bauplan: output_schema = SchemaName referencing a TableSchema in the sibling models.py.
Type check first: the annotations on expectations and projection schemas make uvx ty check a local gate that catches misspelled field types, unknown bauplan symbols, and schema classes that do not resolve, in seconds and without submitting a job. Imports of model runtime dependencies (polars, duckdb) resolve only in the remote environment, so add them to the project's dev dependencies (uv add --dev polars) to keep the report clean. Only then go to the platform.
# First gate: annotations are checked locally, before any job is submitted
uvx ty check
# Validate declarations and schema references without materializing
bauplan run --dry-run
# Execute with blocking expectations and output contract validation
bauplan run
After a run, expectation results appear in the run output. Use bauplan job logs <job_id> to review results from a previous run.
Validation logic is embedded directly in the WAP (Write-Audit-Publish) script, between import_data() and the merge decision. No separate file, no decorators — SDK calls and assertions in Python.
# === IMPORT PHASE ===
client.import_data(table=table_name, search_uri=SOURCE_URI, branch=branch_name, ...)
# === VALIDATION PHASE === ← checks go here
validate_import(client, table_name, branch_name, namespace)
# === MERGE PHASE ===
client.merge_branch(source_ref=branch_name, into_branch="main")
If the user already has a working ingestion script and wants to add or strengthen validation:
import_data() and merge_branch().validate_import() function using either the user's specifications or checks derived from pipeline code.validate_import().Do not rewrite the import or merge phases. Only touch the validation logic.
Write a validation function that runs all checks and raises on failure:
def validate_import(client, table_name, branch, namespace="bauplan"):
fq_table = f"{namespace}.{table_name}"
# FAIL checks — assert to block merge
result = client.query(f"SELECT COUNT(*) as n FROM {fq_table}", ref=branch)
row_count = result.column("n")[0].as_py()
assert row_count > 0, f"{fq_table} has 0 rows after import"
# WARN checks — print, don't assert
result = client.query(f"SELECT MIN(total) as lo FROM {fq_table}", ref=branch)
if result.column("lo")[0].as_py() < 0:
print(f"⚠ negative totals found")
# ... see examples/ingestion_validation.py for complete implementation
| Aspect | Pipeline (expectations.py) | Ingestion (WAP script) |
|---|---|---|
| Decorator | @bauplan.expectation() | None — plain Python |
| Input | Arrow table via bauplan.Model() | SDK queries via client.query() |
| Execution | Automatic during bauplan run | Called explicitly in script |
| Data access | In-memory Arrow table | SQL queries against branch |
| Failure handling | Return False (strict mode) | Raise to block the merge |
| Environment | Containerized per-function | Local Python process |
All queries must use ref=branch_name to pin to the import branch.
Volume:
result = client.query(f"SELECT COUNT(*) as n FROM {fq_table}", ref=branch)
row_count = result.column("n")[0].as_py()
Schema:
table_meta = client.get_table(table=table_name, ref=branch, namespace=namespace)
actual_columns = {f.name for f in table_meta.fields}
actual_types = {f.name: f.type for f in table_meta.fields}
Completeness (null count):
result = client.query(
f"SELECT COUNT(*) - COUNT({col}) as nulls FROM {fq_table}", ref=branch
)
Uniqueness (duplicate count):
result = client.query(
f"SELECT COUNT({col}) - COUNT(DISTINCT {col}) as dupes FROM {fq_table}", ref=branch
)
Validity (bounds):
result = client.query(
f"SELECT MIN({col}) as lo, MAX({col}) as hi FROM {fq_table}", ref=branch
)
Freshness:
result = client.query(
f"SELECT MAX({time_col}) as latest FROM {fq_table}", ref=branch
)
Consistency (cross-column):
result = client.query(
f"SELECT COUNT(*) as violations FROM {fq_table} WHERE {col_a} > {col_b}",
ref=branch
)
When unsure about a method signature, CLI flag, or concept, fetch the relevant doc page via WebFetch rather than guessing. Pages are markdown and LLM-friendly.
Python SDK: https://docs.bauplanlabs.com/reference/bauplan.md
Standard expectations: https://docs.bauplanlabs.com/reference/bauplan-standard-expectations.md
Relevant concept pages:
https://docs.bauplanlabs.com/concepts/semantic-annotations.mdhttps://docs.bauplanlabs.com/concepts/expectations.mdFull doc index: https://docs.bauplanlabs.com/llms.txt
CLI: The bauplan CLI is self-documenting:
bauplan --help — lists all available commandsbauplan <command> --help — shows arguments and options for a specific command (e.g., bauplan run --help, bauplan job --help)Validating generated Python: After writing or updating expectations.py or validation code, run uvx ruff check and uvx ruff format to catch syntax errors and style issues, and uvx ty check to catch type errors: these verify the code compiles and the annotations and SDK calls are well-formed without executing it.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub bauplanlabs/bauplan-skills --plugin bauplan9 skills in this plugin
/bauplan-dag-optimizationOptimizes an existing, poorly structured Bauplan DAG so it runs faster without changing its outputs. Reads the code and profiles the data, then restructures the models, decides what is materialized, narrows inputs with projections and filters, merges or splits projects, and proposes a data-driven partitioning plan with concrete columns and transforms. Use whenever the user has a working pipeline and wants it faster or leaner on Bauplan, for example 'optimize this DAG', 'this pipeline is slow, speed it up', 'we write too many intermediate tables', 'should I partition this table', 'make this pipeline more efficient on Bauplan'. Do NOT use to scaffold a new pipeline from scratch (use bauplan-data-pipeline) or to diagnose a single failed job (use bauplan-debug-and-fix-pipeline)./bauplan-data-assessmentAssesses whether a business question can be answered with data available in a Bauplan lakehouse. Maps business concepts to tables and columns, checks data quality on the relevant subset, validates semantic fit, and renders a verdict: answerable, partially answerable, or not answerable. Produces a structured feasibility report. Use when a user brings a business question, asks 'can we answer this', wants to know if the data supports an analysis, or before building a one-off analysis or pipeline.Other plugins' skills for the same job