Dataset constraint testing (K3)
Why This Matters
A model is only as good as the data it learns from, and data breaks silently. A source system starts sending ages as text, a join duplicates customers, an upstream team renames “New York” to “NYC”. Nothing crashes: the model just trains on garbage and gets a little worse. Dataset constraint testing turns your expectations about the data into automatic checks that run before training and on every new batch of data, so garbage is stopped at the door.
This is one of the four K3 learning objectives in CT-AI v2.0: in the exam you apply constraints to a dataset, and the question counts double.
What you will learn
- Write single-value, multi-value and comparison constraints for a dataset
- Apply them to records and find the violations, by hand and in code
- Know what constraints cannot find, and which test approach covers that
Syllabus: AI-5.1.5 (apply dataset constraint testing).
What a constraint is
A dataset constraint is a rule the data must satisfy, like the constraints in a database schema. If the data breaks it, either the data is wrong or the rule is, and both are worth knowing before you train a model. The syllabus groups constraints by how much data a single check looks at:
| Group | Constraint | Checks | Example for the loan data |
|---|---|---|---|
| Single-value (one attribute of one record) | Missing | A value or attribute is not there | income is filled in |
| Type | The value has the declared type | age is a whole number, not “thirty-five” | |
| Range | The value is within bounds, or one of the allowed values | age is 18 to 120; city is one of the bank’s cities | |
| Multi-value (one attribute over many records) | Duplicate | No identical or near-identical records | the same application is not in the data twice |
| Useful | An attribute does not have a different value in every record | id is different in every row, so a model can learn nothing from it | |
| Outlier | No statistical outliers | an income ten standard deviations above the mean | |
| Count | The number of non-empty values meets a limit | at least 95% of the rows have a credit score | |
| Sum | A total equals, exceeds or stays below a limit | the points of all drivers in a race add up to the points awarded | |
| Comparison (across attributes) | Greater than | One attribute is larger than another | lines of code ≥ lines with defects |
| Correlate | Attributes are related as expected | approved is Yes exactly when credit score > 650 and income > $50,000 |
Constraints come from three places: the schema (what the system that produces the data promises), the domain (what is possible in the real world: nobody is 150 years old), and the business rules (how the label was decided). Write down where each one comes from. When a constraint fires, that is the first question: is the data wrong, or did the rule change?
Apply them by hand
This is how the exam asks it. Here are six applications from the training data of the practice loan model:
| id | age | income | creditScore | city | approved |
|---|---|---|---|---|---|
| 7 | 33 | 36178 | 555 | Houston | No |
| 8 | 33 | 36178 | 555 | Houston | No |
| 15 | 150 | 73113 | 782 | New York | Yes |
| 18 | 66 | 80000 | 720 | New York | No |
| 22 | 34 | −5000 | 752 | Houston | Yes |
| 36 | 28 | 47083 | 668 | NYC | No |
Go through the constraints in the table above, one at a time, for every row:
- Row 8 is identical to row 7 except for its id: it breaks the duplicate constraint.
- Row 15 has age 150: a range constraint (age is 18 to 120).
- Row 18 has credit score 720 and income $80,000, so the rule says Yes, but the label is No: the correlate constraint between credit score, income and the label. This is a wrongly labelled record.
- Row 22 breaks two constraints: range (income is not negative) and correlate (an income of −5,000 cannot lead to Yes). One defect, two symptoms: the income was probably corrupted after the decision was made.
- Row 36 has “NYC”, not one of the allowed cities: a range constraint on a categorical attribute. The applicant probably lives in New York, but a model sees “NYC” as a different city.
Row 7 breaks nothing on its own. Whether you call row 7 or row 8 the duplicate is a choice; the usual one is to keep the first.
Apply them in code
Doing this by hand works for six rows. For every new batch of data, you write the constraints as code once. You continue in the practice project from the lesson Set up your practice project:
cd ai-testing-practice
source .venv/bin/activate # Windows: .venv\Scripts\activate
Create the folder module-6 with the file module-6/test_dataset_constraints.py:
"""Lesson "Dataset constraint testing (K3)": write constraints for a dataset and check them automatically."""
import pandas as pd
import pytest
KNOWN_CITIES = {"New York", "Los Angeles", "Chicago", "Houston", "Phoenix"}
def load(api, name):
response = api.get(f"{api.base}/datasets/{name}", timeout=10)
response.raise_for_status()
return pd.DataFrame(response.json()["data"])
# Every constraint is a function that returns, per row, True when the row VIOLATES it.
def age_as_number(df):
return pd.to_numeric(df["age"], errors="coerce")
CONSTRAINTS = {
# single-value: missing and type
"required fields are filled": lambda df: df[["age", "income", "creditScore"]].isna().any(axis=1),
"age is a number": lambda df: df["age"].notna() & age_as_number(df).isna(),
# single-value: range (numbers within bounds, categories from a set)
"age is 18 to 120": lambda df: age_as_number(df).notna() & ~age_as_number(df).between(18, 120),
"income is not negative": lambda df: df["income"] < 0,
"credit score is 300 to 850": lambda df: df["creditScore"].notna() & ~df["creditScore"].between(300, 850),
"city is a known city": lambda df: ~df["city"].isin(KNOWN_CITIES),
# multi-value: duplicates (id must also be unique: a duplicate key)
"id is unique": lambda df: df["id"].duplicated(keep=False),
"no duplicate records": lambda df: df.drop(columns="id").duplicated(keep="first"),
}
# Only for labelled data. Comparison: the label must correlate with the bank's rule.
LABEL_CONSTRAINTS = {
"approved is Yes or No": lambda df: ~df["approved"].isin(["Yes", "No"]),
"label follows the approval rule": lambda df: (
df["income"].notna() & df["creditScore"].notna()
& ((df["approved"] == "Yes") != ((df["creditScore"] > 650) & (df["income"] > 50000)))
),
}
def find_violations(df, constraints):
"""{constraint name: [ids of the rows that violate it]}, only for constraints with violations."""
found = {}
for name, check in constraints.items():
ids = df.loc[check(df), "id"].tolist()
if ids:
found[name] = ids
return found
Each constraint is one line that marks the rows that break it, so adding a rule is adding a line. Notice how the constraints avoid reporting one problem twice: age is 18 to 120 only looks at ages that are numbers, and age is a number ignores ages that are missing, which required fields are filled already reports.
Now the tests. In a real pipeline the gate is simply assert find_violations(...) == {}: any violation stops the training. The practice data has its defects on purpose, so here the test checks that the constraints find exactly the known ones:
def test_training_data_violations(api):
found = find_violations(load(api, "loans-train"), {**CONSTRAINTS, **LABEL_CONSTRAINTS})
for name, ids in found.items():
print(f"{name:35} rows {ids}")
# The known defects of the practice data. In a real pipeline this would be: assert found == {}
assert found == {
"required fields are filled": [5, 12, 28],
"age is a number": [25],
"age is 18 to 120": [15, 41],
"income is not negative": [22],
"city is a known city": [31, 36],
"no duplicate records": [8, 9],
"label follows the approval rule": [18, 22],
}
def test_production_data_contains_cities_the_model_never_saw(api):
production = load(api, "loans-production")
found = find_violations(production, CONSTRAINTS)
assert set(found) == {"city is a known city"}
new_cities = sorted(set(production.loc[production["id"].isin(found["city is a known city"]), "city"]))
print(f"{len(found['city is a known city'])} of {len(production)} applications from {new_cities}")
assert new_cities == ["Boston", "Denver", "Miami", "Seattle"]
@pytest.mark.parametrize("name", sorted({**CONSTRAINTS, **LABEL_CONSTRAINTS}))
def test_a_clean_row_violates_nothing(name):
clean = pd.DataFrame([{"id": 1, "name": "Ann Smith", "age": 40, "income": 60000.0,
"creditScore": 700.0, "city": "Chicago", "approved": "Yes"}])
assert not {**CONSTRAINTS, **LABEL_CONSTRAINTS}[name](clean).any()
The last test is easy to forget and important: a constraint that fires on correct data is a false alarm, and a gate that raises false alarms gets switched off. Test your checks with a row you know is clean.
Run it
pytest module-6 -v -s
module-6/test_dataset_constraints.py::test_training_data_violations
required fields are filled rows [5, 12, 28]
age is a number rows [25]
age is 18 to 120 rows [15, 41]
income is not negative rows [22]
city is a known city rows [31, 36]
no duplicate records rows [8, 9]
label follows the approval rule rows [18, 22]
PASSED
module-6/test_dataset_constraints.py::test_production_data_contains_cities_the_model_never_saw
39 of 50 applications from ['Boston', 'Denver', 'Miami', 'Seattle']
PASSED
module-6/test_dataset_constraints.py::test_a_clean_row_violates_nothing[age is 18 to 120] PASSED
...
============================== 12 passed
Twelve violations in 50 training records, and a production batch in which 39 of 50 applications come from cities the model has never seen. The model was trained on five cities; it knows nothing about Boston. No constraint on a single row can tell you whether that matters, but it is the signal to check whether the training data still represents production (the lesson Testing for data representativeness).
What constraints cannot find
Constraints check the data against rules you know in advance. Three kinds of problem slip through:
- A wrong label without a known rule. The label constraint found row 18 only because the bank’s rule is written down. For most models it is not (that is why there is a model); finding wrong labels then takes label correctness testing: reviewing a sample by hand, or checking where independent labellers disagree.
- A skewed dataset. Every record can be valid while the set as a whole is skewed: 90% of the applicants from one age group, or far fewer women than men. No fixed rule says what the mix should be; you find it by comparing the distribution with the population the model will serve (the lessons Testing for bias and Testing for data representativeness).
- Plausible but wrong values. An income of $36,178 that should have been $63,178 breaks no rule. Only a comparison with the source system finds it.
So constraint testing is the first line, not the only one: cheap, automatic and run on every batch, and it lets the more expensive tests spend their time on what constraints cannot see.
Exercise
- The bank adds a sixth city, Boston. Which constraint changes, and how many of the 50 production applications still violate it?
- Write a constraint for a new field
zipCodethat must be exactly five digits. Which values of"02134","2134","02134-1234"and"abcde"violate it?
Show suggested answer
Only city is a known city: add
"Boston"toKNOWN_CITIES. Of the 39 violations, 17 were from Boston, so 22 remain (Miami, Denver and Seattle). And the testtest_production_data_contains_cities_the_model_never_sawnow fails, because its expected list still contains Boston: the test documents the current agreement about the data, so changing the agreement means changing the test too.As a format constraint with a regular expression:
"zip code is five digits": lambda df: ~df["zipCode"].astype(str).str.fullmatch(r"\d{5}"),"02134"passes;"2134"(four digits),"02134-1234"(ZIP+4) and"abcde"violate it. Note that the zip code must be read as text: read as a number,"02134"becomes 2134 and loses its leading zero, which is exactly the kind of silent defect constraints are for. And"02134-1234"is a valid US format: whether it should pass is a question for whoever owns the data, which is the right question to ask when a constraint fires.
Exam-style questions
1. A dataset has the constraints: age is 18 to 99; income ≥ 0; status is one of {active, closed}. Which record violates exactly one constraint?
- A. age 17, income 25,000, status active
- B. age 45, income −10, status open
- C. age 30, income 0, status closed
- D. age 101, income −1, status active
Show answer
2. In a training set, two records have different ids but identical values in every other field. Which kind of constraint finds this?
- A. A range constraint
- B. A duplicate constraint
- C. A type constraint
- D. A correlate constraint
Show answer
3. Every record in a training set passes all its constraints, but 90% of the records come from one age group. What is true?
- A. The data is fine, because all constraints pass
- B. A stricter range constraint on age will find the problem
- C. Constraint testing checks fixed rules and does not detect this; it needs testing for bias and data representativeness
- D. The duplicates constraint will find it
Show answer
Your project so far
ai-testing-practice/
├── ...
├── module-3/
│ └── test_first_model.py
├── module-4/
│ └── test_metrics.py
└── module-6/
└── test_dataset_constraints.py new in this lesson
The finished version is in the example repository: module-6/test_dataset_constraints.py.