data-validation-contracts
БесплатноБез исполняемых скриптовНе проверенUse when data crosses a boundary into your code (file, API, warehouse table, upload, model input or output), when a join or cleaning step can change row…
от makifbaysal★ 123 звезды на GitHubОб этом скилле
Data Validation and Contracts
Overview
Code that trusts its input computes wrong numbers quietly. A contract states what the data must look like at a boundary and stops the pipeline, with a readable message, when it does not. EDA finds the facts (eda-and-data-profiling); contracts keep them true.
Core principle: validate at every boundary, fail loudly with the column and the bad values, and never catch a validation error just to keep going.
1. What to check — the dimensions
| Dimension | Question | Typical check |
|---|---|---|
| Completeness | Are required values present? | not-null on keys and required fields |
| Uniqueness | Is the grain what we think? | unique on the (composite) key |
| Validity | Are values in range and in the allowed set? | ge/le, isin, regex, dtype |
| Consistency | Do columns agree with each other? | shipped_at not null when status == "shipped" |
| Referential integrity | Do foreign keys point at something? | relationship test, anti-join count |
| Timeliness | Is the data fresh and the period complete? | max timestamp within N hours |
| Volume | Is the batch plausibly sized? | row count within a range of recent batches |
Check the columns your logic depends on, not every column — a contract nobody can maintain gets disabled.
2. Which tool where — follow the repo
| Boundary | Tool (if the repo has none yet) |
|---|---|
| DataFrames inside Python code and tests | pandera (import pandera.pandas as pa; pandera.polars for Polars) |
| Pipeline checkpoints with stored results and docs | Great Expectations (GX Core 1.x) — only if the repo already runs it |
| Single records: API payloads, configs, messages | Pydantic 2 models |
| Warehouse tables built by dbt | dbt data tests and model contracts (sql-analytics-and-dbt) |
Never add a second validation library beside the one the repository uses (rule stack-choice).
3. pandera schemas as code
import pandas as pd
import pandera.pandas as pa
from pandera.typing import DataFrame, Series
class Orders(pa.DataFrameModel):
order_id: Series[str] = pa.Field(unique=True)
customer_id: Series[str]
amount: Series[float] = pa.Field(ge=0)
status: Series[str] = pa.Field(isin=["placed", "shipped", "refunded"])
shipped_at: Series[pd.Timestamp] = pa.Field(nullable=True)
class Config:
strict = True
coerce = True
@pa.dataframe_check
def shipped_orders_have_a_date(cls, df: pd.DataFrame) -> pd.Series:
return ~((df["status"] == "shipped") & df["shipped_at"].isna())
@pa.check_types(lazy=True)
def clean_orders(raw: DataFrame[Orders]) -> DataFrame[Orders]:
...
lazy=Truecollects every failure instead of stopping at the first; theSchemaErrors.failure_casesframe names column, check and value.strict = Truerejects unexpected columns — a renamed upstream column fails here instead of turning into all-NaN later.coerce = Trueis a decision: it converts"12"to12.0, but a value that cannot be coerced still fails. Turn it off where a wrong type means a broken upstream.- With pandas 3 the default string dtype is
str(Arrow-backed when PyArrow is installed); keep pandera and pandas versions pinned together and run the schema tests after either moves.
4. Test the contract itself — TDD applies
def test_orders_schema_rejects_negative_amount() -> None:
bad = valid_orders().assign(amount=[-1.0, 5.0])
with pytest.raises(pa.errors.SchemaErrors) as err:
Orders.validate(bad, lazy=True)
assert set(err.value.failure_cases["column"]) == {"amount"}
One failing-fixture test per rule you add: a rule that never failed a test may not be checking anything.
5. Joins: assert the cardinality you assume
# ❌ silently duplicates orders when a customer has two rows
df = orders.merge(customers, on="customer_id", how="left")
# ✅ fails immediately if customers is not unique on the key
df = orders.merge(customers, on="customer_id", how="left", validate="many_to_one")
assert len(df) == len(orders)
In SQL, compare COUNT(*) with COUNT(DISTINCT key) before and after the join, or put a unique test on the dimension's key (analytics-result-qa).
6. Great Expectations (GX Core 1.x), when the repo uses it
import great_expectations as gx
context = gx.get_context(mode="ephemeral")
batch = (
context.data_sources.add_pandas("in_memory")
.add_dataframe_asset("orders")
.add_batch_definition_whole_dataframe("all")
.get_batch(batch_parameters={"dataframe": df})
)
suite = gx.ExpectationSuite(name="orders")
suite.add_expectation(gx.expectations.ExpectColumnValuesToNotBeNull(column="order_id"))
suite.add_expectation(gx.expectations.ExpectColumnValuesToBeBetween(column="amount", min_value=0))
assert batch.validate(suite).success
GX 1.x removed the 0.x CLI (great_expectations init) and DataContext.run_checkpoint patterns; production runs use a ValidationDefinition inside a `Checkpo
Установить data-validation-contracts в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл data-validation-contracts?
Use when data crosses a boundary into your code (file, API, warehouse table, upload, model input or output), when a join or cleaning step can change row counts, or when adding pandera, Great Expectations, Pydantic or dbt checks
Как установить скилл data-validation-contracts?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл data-validation-contracts запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic