top of page

Catch Data Issues Before They Reach Production

4 days ago
8 min read

I remember a time when I made a simple update late on a Friday and regretted it on Monday. The business wanted to add one column to a critical table. It seemed simple. Just join the current SQL code to one more table and add the new column. Then push to production and clock out for the day.


The code was simple, but the logic was much more complex. Little did I realize that this one small dimension table had a handful of duplicate records. The join ballooned the fact table with duplicate rows and wrecked a key table. That one table then had cascading effects, and reporting was a mess.


Had we built basic checks into our CI/CD pipeline, the push to production would have failed and the original code would have stayed in place. Sure, the business would not have gotten their request completed on time. But at the end of the day, with the rollback and root cause analysis, it was never completed on time in the first place.

This article gives you the code to build proper data contracts that can be placed directly in your CI/CD pipeline. It is all Python, built to replicate dbt tests. You can build and test it in a Jupyter notebook before saving the script and adding it to your pipeline.


The one idea behind every check

The key behind data contracts is proper assertions. dbt’s documentation describes its tests this way:


“Like almost everything in dbt, data tests are SQL queries. In particular, they are select statements that seek to grab “failing” records, ones that disprove your assertion.”

In other words, you don’t ask, “is this data good?” You ask, “show me the rows that are bad.” If the query returns zero rows, the check passes.


Figure 1. A rule in the YAML contract becomes a query that returns failing rows. Zero rows means PASS; any rows means FAIL, or WARN if the rule is marked as a warning.
Figure 1. A rule in the YAML contract becomes a query that returns failing rows. Zero rows means PASS; any rows means FAIL, or WARN if the rule is marked as a warning.

Step 1: Install the tools

To begin, you need to install four packages. In this example, we use DuckDB for testing, but normally the checks would connect to your actual database.

pip install duckdb pandas openpyxl pyyaml


  • pandas (with openpyxl) reads the Excel workbook.

  • PyYAML reads the contract.

  • DuckDB runs SQL directly on pandas DataFrames.


Step 2: Write the contract in dbt's format

The contract is a normal dbt schema.yml file. You can drop it into a dbt project and dbt test will run it. Here is a sample contract for an orders table. Notice that you are declaring data types, looking for values in a list, preventing nulls, checking for duplicates, and even adding your own custom SQL code. Freshness checks can also be added as custom SQL.


version: 2

 

models:

  - name: orders

    meta:

      sql_checks:

        - name: ship_date_not_before_order_date

          description: "A shipment can never happen before the order."

          sql: |

            select order_id, order_date, ship_date

            from {{ this }}

            where ship_date < order_date

        - name: quantity_is_positive

          description: "Every order must have at least one item."

          sql: |

            select order_id, quantity

            from {{ this }}

            where quantity <= 0

 

    columns:

      - name: order_id

        data_type: integer

        data_tests:

          - not_null

          - unique

 

      - name: customer_id

        data_type: integer

        data_tests:

          - not_null

          - relationships:

              to: ref('customers')

              field: customer_id

 

      - name: status

        data_type: varchar

        data_tests:

          - accepted_values:

              values: ['placed', 'shipped', 'delivered', 'returned', 'cancelled']

 

      - name: quantity

        data_type: integer

 

  - name: customers

    columns:

      - name: customer_id

        data_tests:

          - not_null

          - unique


  • Built-in tests (not_null, unique, accepted_values, relationships) are standard dbt. Nothing here is custom.

  • Custom rules live under meta.sql_checks. dbt ignores anything under meta, so the file stays valid for dbt, and the {{ this }} syntax lets you copy the SQL into a dbt test later.


Step 3: Load the contract and the data

Here you will read the YAML file and load each Excel sheet into DuckDB under its dbt model name. The “with open” command reads the YAML file from Step 2. For example purposes, the code reads an Excel file, but in the real world this would be a SQL table. No sample file? Any workbook with an orders sheet and a customers sheet will work, as long as the sheet and column names match the YAML.


import duckdb

import pandas as pd

import yaml

 

with open("orders_basic_contract.yml", encoding="utf-8") as contract_stream:

    contract = yaml.safe_load(contract_stream)

models_by_name = {model["name"]: model for model in contract["models"]}

 

database = duckdb.connect()

workbook_sheets = pd.read_excel("sample_orders.xlsx", sheet_name=None)

 

for model_name in models_by_name:

    if model_name in workbook_sheets:

        database.register(model_name, workbook_sheets[model_name])


After this step, select * from orders works with your spreadsheet.


Step 4: Write one function that runs any check

Because every check returns failing rows, one function can run all of them. It counts the rows and records a status. This is the meat of the logic. Each check is flagged as “PASS,” “WARN,” “FAIL,” or “ERROR.” A “FAIL” should prevent your CI/CD pipeline from copying the code into production. If a “FAIL” is not a critical error, you can add severity: warn under that test’s config: block in the YAML file.


results = []

 

def run_check(table, column, check_name, failing_rows_sql, severity="error"):

    """Run a failing-rows query and record PASS, WARN, FAIL or ERROR."""

    try:

        failing_row_count = database.execute(

            f"select count(*) from ({failing_rows_sql})").fetchone()[0]

        if failing_row_count == 0:

            status = "PASS"

        else:

            status = "WARN" if severity == "warn" else "FAIL"

        detail = ""

    except Exception as error:

        failing_row_count, status, detail = 0, "ERROR", str(error).splitlines()[0]

 

    results.append({"table": table, "column": column, "check": check_name,

                    "status": status, "failing_rows": failing_row_count, "detail": detail})


  • severity: warn under a test’s config: block turns a failure into a warning, the same as in dbt.

  • A broken query becomes an ERROR row instead of crashing the notebook, so one typo doesn't hide every other result.


Step 5: Turn each dbt test into a failing-rows query

This function is the heart of the notebook. It takes a dbt test, converts it to SQL, then finds the failed rows. Notice that this part of the code looks for duplicates, unexpected NULLs, and accepted column values. It also checks foreign key relationships. For example, customer_id needs to exist in the customers table. The one catch is that accepted_values ignores empty values, just as it does in dbt, so pair it with not_null if blanks aren’t allowed.


def test_to_sql(table, column, test_name, arguments):

    """SQL returning the rows that fail a built-in dbt test."""

    quoted_column = f'"{column}"'

 

    if test_name == "not_null":

        return f"select * from {table} where {quoted_column} is null"

 

    if test_name == "unique":

        return (f"select {quoted_column}, count(*) as copies from {table} "

                f"where {quoted_column} is not null "

                f"group by {quoted_column} having count(*) > 1")

 

    if test_name == "accepted_values":

        allowed = ", ".join(f"'{value}'" for value in arguments["values"])

        return f"select * from {table} where cast({quoted_column} as varchar) not in ({allowed})"

 

    if test_name == "relationships":

        parent_table = arguments["to"].split("'")[1]          # ref('customers') -> customers

        parent_column = f'"{arguments["field"]}"'

        return (f"select child.{quoted_column} from {table} as child "

                f"left join {parent_table} as parent "

                f"on child.{quoted_column} = parent.{parent_column} "

                f"where child.{quoted_column} is not null and parent.{parent_column} is null")

 

    return None   # not a built-in test


Then loop over every column's tests. A test can be a plain name (- not_null) or a name with settings (- accepted_values: {...}), so the first line handles both:


for table, model in models_by_name.items():

    for column in model.get("columns", []):

        for test_entry in column.get("data_tests", []):

            test_name, arguments = ((test_entry, {}) if isinstance(test_entry, str)

                                    else next(iter(test_entry.items())))

            failing_rows_sql = test_to_sql(table, column["name"], test_name, arguments)

            if failing_rows_sql:

                severity = (arguments.get("config") or {}).get("severity", "error")

                run_check(table, column["name"], test_name, failing_rows_sql, severity)


Step 6: Add data type and custom SQL checks

Data types use the same pattern. TRY_CAST converts each value to the given type. Any value that can’t be converted becomes NULL and fails the test.

In dbt itself, data_type is only checked when a model sets contract: enforced: true, and that check happens at build time, before the table is created. Data tests run after the table is built. This script runs both kinds of check in one step before production.

Custom SQL needs no translation at all. The loop below replaces {{ this }} with the table name and runs the query.


for table, model in models_by_name.items():

    for column in model.get("columns", []):

        if "data_type" in column:

            name, declared_type = column["name"], column["data_type"]

            run_check(table, name, f"data_type: {declared_type}",

                      f'select "{name}" from {table} where "{name}" is not null '

                      f'and try_cast("{name}" as {declared_type}) is null')

 

    for sql_check in (model.get("meta") or {}).get("sql_checks", []):

        run_check(table, None, f"sql: {sql_check['name']}",

                  sql_check["sql"].replace("{{ this }}", table),

                  sql_check.get("severity", "error"))


That's every check. The rest is reading the results.


Step 7: Review the results and the failing rows

Now, collect the results into a table and count each status.


results_df = pd.DataFrame(results)

print(results_df["status"].value_counts())

 

To test the notebook, I generated 1,000 sample orders and deliberately planted a handful of defects. They include duplicate IDs, missing and unknown customers, an invalid status, negative quantities, and shipments dated before their orders.

The notebook ran 13 checks. Seven passed and six failed, one for each defect the contract checks for.


Figure 2. Results on 1,000 sample orders. Red bars are standard dbt tests; orange bars are custom SQL rules. For unique, the count is duplicated IDs, not rows.
Figure 2. Results on 1,000 sample orders. Red bars are standard dbt tests; orange bars are custom SQL rules. For unique, the count is duplicated IDs, not rows.

Notice that the order_id is flagged for a uniqueness failure. That is my Friday bug in miniature. My join created duplicate keys, and a unique test on the fact table’s key would have failed the push before it ever reached production.


Every result is backed by a query, so you can run it yourself to see the bad rows:


database.execute("""

    select order_id, order_date, ship_date

    from orders

    where ship_date < order_date

""").df()


Output:

   order_id order_date  ship_date

0    500027 2025-05-09 2025-05-05

1    500045 2025-03-16 2025-03-12

2    500473 2025-07-29 2025-07-25

3    500518 2025-07-31 2025-07-30


A check that shows you the bad rows is a check people will actually fix.


Step 8: Make failures stop the load

Since a report alone would not have prevented my original problem, the checks need to run directly in the CI/CD pipeline. Tristan Handy, founder of dbt Labs, made this point in his article Contracts have consequences:


“If you have a test coverage requirement that doesn’t break your CI, you don’t have a contract, you have a suggestion.”

This final step is the most important. It stops the run if it finds a failure and saves you from an uncomfortable meeting with the executives.


if results_df["status"].isin(["FAIL", "ERROR"]).any():

    raise ValueError("Data contract failed. See the results above.")


Where it fits in your pipeline

In a CI/CD pipeline, these checks run as one step between deploying to staging and promoting to production. Point Step 3 at your staging tables instead of the Excel file, and save the notebook as a Python script (jupyter nbconvert --to script does this in one command). Pointing at staging means using your warehouse’s Python connector instead of DuckDB, and the SQL may need small changes for your database. BigQuery, for example, uses SAFE_CAST instead of TRY_CAST. When a check fails, the script ends with an error, and CI/CD tools such as GitHub Actions, Azure DevOps and GitLab stop the pipeline at that step. Production keeps running the old code.


Figure 3. The contract checks are the gate between staging and production. A failure stops the release and leaves production unchanged.
Figure 3. The contract checks are the gate between staging and production. A failure stops the release and leaves production unchanged.

That is the step that would have saved my Friday release, and the frustration of the ensuing Monday.


What to do next

  • Start small: not_null and unique on keys, accepted_values on status fields, relationships on foreign keys.

  • Add one custom SQL rule for the business logic that has burned you before.

  • Move the same YAML into dbt when you're ready. Your rules come with you.


Conclusion

As a data engineer, coding is only one piece of the job. Making sure nothing breaks is the piece that keeps the business afloat. The business relies on key reports, and gaps in reporting can be costly. As you grow in the field, building proper validations is a must.


The issue I described earlier was completely preventable. It took a day to locate the root cause and even more time to mend the relationship with the client. Everyone makes mistakes, and even the best of us are careless at times. That is why preventive checks should be added early and tested regularly to ensure nothing gets missed.


Hopefully, this saves you from a Monday like mine. Write the rule once and let the pipeline say no for you.

Comments


bottom of page