CI/CD for data

Part of the free LogicWiz Data Engineering course, Module 10: Working like an engineer. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is Thursday, 4:40 p.m. Tess writes: "Revenue has been exactly double since Monday. Is that real?" It is not. On Monday a pull request changed one join in the orders model. The SQL looked fine and two people approved it. A two-minute automatic check would have turned that pull request red before anyone clicked Merge.

You'll learn to

  • Say what CI and CD are, and what CI runs for data
  • Write data tests as queries that return the failing rows
  • Ship one build through staging to production, and publish data safely
  • Give a deploy job cloud access without storing a key

Learn

Two approvals, and revenue doubled

Two careful people read Monday's pull request. Neither could see the problem, because the problem was not in the code. It was in the data: the new join matched each order to two rows, so every order counted twice.

A person reads a diff. A machine can do what the reviewers could not: build the model on a few sample rows and check the result. Two names for that:

  • CI (continuous integration): on every pull request, a fresh machine builds your change and tests it. If a test fails, the Merge button stays locked.
  • CD (continuous delivery): once merged, a pipeline ships the change, one environment at a time. Not a person with a terminal.

Here is the whole road.

From pull request to production

Six steps downwards: a pull request is tested in its own CI schema, merged as one commit, built once into an image, deployed to staging and tested, approved by a reviewer, and the same image deployed to production.

Read it top to bottom. The first box is CI; everything after the merge is CD. If prod breaks, you roll back by deploying the previous package. Data needs more than that, because the bad run may already have written tables.

A test is a query for bad rows

How does a machine "check the result"? With the idea from Module 7: a data test is a query that returns the rows that break a rule. Zero rows means pass.

  • unique: keys that appear more than once;
  • not null: rows where a required column is NULL;
  • accepted values: a status outside the allowed list;
  • relationships: order lines whose product does not exist.

In CI the model is not built on real data. It is built on fixtures: a small, fixed set of made-up rows that covers the awkward cases: a cancelled order, a NULL email, a duplicate. A run takes seconds, and the right answer is known in advance.

Monday's doubled revenue breaks the unique rule: two rows where there should be one.

Four data tests: each counts its failing rows

SELECT 'orders.status accepted values' AS test, COUNT(*) AS failures
FROM orders
WHERE status NOT IN ('placed', 'shipped', 'delivered', 'cancelled', 'returned')
UNION ALL
SELECT 'order_items unique (order_id, line_no)', COUNT(*)
FROM (
  SELECT order_id, line_no
  FROM order_items
  GROUP BY order_id, line_no
  HAVING COUNT(*) > 1
) dupes
UNION ALL
SELECT 'customers.email not null', COUNT(*)
FROM customers
WHERE email IS NULL
UNION ALL
SELECT 'order_items -> products', COUNT(*)
FROM order_items i
LEFT JOIN products p ON p.product_id = i.product_id
WHERE p.product_id IS NULL;

Before you run it, guess how many of the four pass. Three do. customers.email not null fails with 1 row: customer 7 has no email. In CI that would stop the merge, and the team would decide whether the rule or the data is wrong.

A tiny CI run: build, test, set the exit code

import duckdb

# The model as it is on the pull request's branch
MODEL = """
CREATE TABLE fct_daily_revenue AS
SELECT CAST(o.order_ts AS DATE) AS order_date,
       SUM(i.qty * i.unit_price) AS revenue
FROM read_csv_auto('data/order_items.csv') AS i
JOIN read_csv_auto('data/orders.csv') AS o ON o.order_id = i.order_id
WHERE o.status <> 'cancelled'
GROUP BY 1
"""

# Each test returns the rows that break its rule
TESTS = {
    "one row per day": "SELECT order_date FROM fct_daily_revenue GROUP BY 1 HAVING COUNT(*) > 1",
    "revenue not null": "SELECT * FROM fct_daily_revenue WHERE revenue IS NULL",
    "no negative revenue": "SELECT * FROM fct_daily_revenue WHERE revenue < 0",
    "14 days present": "SELECT 1 WHERE (SELECT COUNT(*) FROM fct_daily_revenue) <> 14",
}

duckdb.sql(MODEL)
failed = 0
for name, sql in TESTS.items():
    bad = len(duckdb.sql(sql).fetchall())
    print("PASS" if bad == 0 else "FAIL", name, f"({bad} failing rows)")
    if bad:
        failed += 1
print("exit code:", 1 if failed else 0)

Now break the model the way Monday's pull request did. Change GROUP BY 1 to GROUP BY 1, o.order_id, so the model has one row per order instead of one per day. Watch "one row per day" fail and the exit code turn to 1. A non-zero exit code is how a program tells the machine that ran it "I failed".

The real thing: a workflow that runs on every pull request

Runs in the cloud:

name: data-ci
on:
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:                       # a throwaway database, just for this run
        image: postgres:16
        env:
          POSTGRES_HOST_AUTH_METHOD: trust
        ports: ["5432:5432"]
        options: --health-cmd pg_isready --health-interval 5s --health-retries 10
    env:
      PGHOST: localhost
      PGUSER: postgres
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install -r requirements.txt
      - name: Lint SQL
        run: sqlfluff lint models/ --dialect postgres
      - name: Load test fixtures
        run: psql -f tests/fixtures.sql
      - name: Build models and run data tests
        run: python -m pytest tests/ -q
Run python -m pytest tests/ -q
...F.
=================================== FAILURES ===================================
_____________________________ test_one_row_per_day _____________________________
>       assert failing == [], f"days with more than one row: {failing}"
E       AssertionError: days with more than one row: [(datetime.date(2025, 6, 3), 2)]
tests/test_fct_daily_revenue.py:18: AssertionError
FAILED tests/test_fct_daily_revenue.py::test_one_row_per_day - AssertionError
1 failed, 4 passed in 1.84s
Error: Process completed with exit code 1.

Read the steps from the top: get the code, install, lint, load the fixtures, build and test. The file (.github/workflows/data-ci.yml) lives in the repository, so it is reviewed like any code. Exit code 1 turns the pull request's check red, and branch protection keeps the Merge button locked until it is fixed.

Which models must CI rebuild?

A small dbt project drawn as a graph from raw sources through staging and intermediate models to two marts; build it in order, break a test to see everything downstream skipped, and try plus-sign selections.

CI has to be quick, so it rebuilds only what the pull request changed and everything downstream of it: every model that reads from it, directly or through others. Pick stg_orders+ to see that set. +fct_orders goes the other way and adds everything upstream.

Build once, promote the same thing

The same code runs in several environments: separate places, each with its own tables and its own login.

  • dev: your sandbox, on sample data.
  • CI: a throwaway schema for each pull request, dropped when it closes.
  • staging: shaped like production. Every merge goes here first and runs the full tests.
  • prod: the tables the dashboards read. Only the deploy pipeline writes here.

Promotion means the exact thing that passed staging is what goes to prod: the same commit, the same built package. Only the settings change on the way: schema names, cluster sizes, alert channels, and which identity the job runs as.

Why so strict? Rebuild for prod from the branch, and you ship something staging never tested.

Four environments, one artifact

devCIstagingprod
Who writesyouthe pull request's jobthe deploy pipelinethe deploy pipeline only
Dataa samplefixturesproduction-likethe real thing
Schemadevrosacipr418staginganalytics
Identityyour own logina CI identity that cannot reach proda staging identitya prod identity behind an approval

Every row is a setting. The code in all four columns is the same commit. The thing being promoted is called an artifact: a commit id, an image digest such as swiftkart-pipeline@sha256:... (next lesson), a dbt manifest.

Readers are watching while you deploy

Shipping code swaps one program for another. Shipping data is harder: people read the tables while you rebuild them. A half-finished rebuild is visible. A wrong one is published.

The first fix is called blue-green. Build the new version next to the live one. Test it. Then switch the readers over in one instant step. In Snowflake that step is ALTER SCHEMA analytics SWAP WITH analytics_next, which exchanges every table and permission between the two schemas at once. Elsewhere you repoint a view at the new table.

The price is a second copy of the data for a while.

Write, audit, publish

The second fix works batch by batch, and it is the one that would have saved Monday.

  1. Write the new data where no reader looks: a staging table, or a branch of the table.
  2. Audit it: run the data tests on that hidden copy.
  3. Publish it in one step, and only if every test passed. If one fails, throw the batch away and raise an alert. The live table was never touched.

The pattern is called write-audit-publish, WAP for short. Step through it with a file that was delivered twice.

A doubled batch never reaches the readers

A hidden audit table, the audit checks and the live table in four steps: a doubled batch for 7 June is written to the hidden table, the unique-key check fails so nothing is published, the clean batch is written, and after every check passes it is published to the live table in one transaction.

  1. Write. The batch for 7 June arrives. By mistake the file was delivered twice, so every order line is in it two times. It goes into a hidden table. Readers still see six days.

  2. Audit. The tests run on the hidden copy. "Order lines unique" finds the duplicates. Nothing is published, and an alert goes out. The live table was never touched.

  3. Write again. The clean file arrives and replaces the hidden copy.

  4. Audit, then publish. Every test passes. In one transaction the old rows for 7 June are deleted and the new ones inserted. Readers go from six correct days to seven, with nothing in between.

Read it left to right: hidden table, checks, live table. Watch the right-hand box: it only changes in the last step. The next card runs these four steps for real.

Write-audit-publish in DuckDB

import duckdb

REVENUE = """
    select cast(o.order_ts as date) as day, round(sum(i.qty * i.unit_price), 2) as revenue
    from 'data/orders.csv' o join lines__audit i on i.order_id = o.order_id
    where o.status in ('placed', 'shipped', 'delivered') {where}
    group by 1
"""
duckdb.sql("create table lines__audit as select * from 'data/order_items.csv'")
duckdb.sql("create table daily_revenue as " + REVENUE.format(where="and o.order_ts < '2025-06-07'"))

AUDITS = {
    "order lines unique": "select order_id, line_no from lines__audit group by 1, 2 having count(*) > 1",
    "one row for the day": "select 1 where (select count(*) from daily_revenue__audit) <> 1",
    "revenue positive": "select * from daily_revenue__audit where revenue <= 0",
}

def write_audit_publish(day, lines_sql):
    # 1. write where no reader looks
    duckdb.sql(f"create or replace table lines__audit as {lines_sql}")
    where = f"and o.order_ts >= date '{day}' and o.order_ts < date '{day}' + interval 1 day"
    duckdb.sql("create or replace table daily_revenue__audit as " + REVENUE.format(where=where))
    # 2. audit
    failed = [name for name, sql in AUDITS.items() if duckdb.sql(sql).fetchall()]
    if failed:
        print(f"{day}: NOT published, failed: {failed}")
        return
    # 3. publish in one transaction
    duckdb.sql("begin transaction")
    duckdb.sql(f"delete from daily_revenue where day = date '{day}'")
    duckdb.sql("insert into daily_revenue select * from daily_revenue__audit")
    duckdb.sql("commit")
    print(f"{day}: published")

lines = "select * from 'data/order_items.csv'"
write_audit_publish('2025-06-07', lines + " union all " + lines)     # the file was delivered twice
print("days live:", duckdb.sql("select count(*) from daily_revenue").fetchone()[0])
write_audit_publish('2025-06-07', lines)                              # the clean file
print("days live:", duckdb.sql("select count(*) from daily_revenue").fetchone()[0])

The doubled batch would have doubled 7 June's revenue. The unique-key audit stopped it, and readers kept seeing six correct days. Only the clean batch was published, in one transaction, so no reader saw 7 June half-written.

Settings in Git, secrets in a vault

Each environment needs its own settings: which schema, how many threads, where alerts go. That is configuration. It is not secret, so it lives in a file in Git, one block per environment, and a change to it is reviewed like code.

Secrets are different: passwords, keys, tokens. They never go into Git (Lesson 10.1). They live in a secret store, and reach the program as environment variables only at run time. A workflow file holds a reference such as ${{ secrets.WAREHOUSE_PASSWORD }}, never the value.

The program picks the block for its environment and reads the secret. If either is missing, it must fail loudly. It must never fall back to production.

Pick the config, read the secret, fail loudly

import os

CONFIG = {
    "dev": {"schema": "dev_rosa", "threads": 1, "alert": None},
    "staging": {"schema": "staging", "threads": 4, "alert": "#data-staging"},
    "prod": {"schema": "analytics", "threads": 8, "alert": "#data-alerts"},
}

def load_settings(env):
    if env not in CONFIG:
        raise ValueError(f"unknown environment {env!r}: expected one of {sorted(CONFIG)}")
    password = os.environ.get("WAREHOUSE_PASSWORD")
    if not password:
        raise RuntimeError("WAREHOUSE_PASSWORD is not set: get it from the secret store")
    return {**CONFIG[env], "password": password}

# In CI the workflow sets these from its secret store; here we fake them for the demo.
os.environ["SWIFTKART_ENV"] = "staging"
os.environ["WAREHOUSE_PASSWORD"] = "demo-only-not-a-secret"

settings = load_settings(os.environ["SWIFTKART_ENV"])
print(settings["schema"], settings["threads"], settings["alert"])
print("password loaded:", bool(settings["password"]))

Try load_settings("prdo"), a typo: it raises an error instead of quietly writing to production. That is the behaviour you want at 3 a.m.

No stored key: the job proves itself

One secret is worse than the rest: the cloud key that lets CI deploy. Stored in CI, it can leak through a log line, and someone has to replace it by hand.

So modern CI stores no key at all. It uses OpenID Connect, OIDC for short. Think of a festival wristband: printed for one person, good for one day.

The job asks GitHub for a signed note that says exactly what is running: this repository, this environment. The cloud checks the signature, then compares the note with a rule you wrote in advance, the trust policy. If they match, the cloud hands back an access token that works for that one job and expires soon after.

A deploy job gets credentials without storing any

A conversation between the GitHub runner, GitHub OIDC, the cloud identity service and Key Vault in four steps: the runner gets a signed token, exchanges it for a short-lived access token after the cloud checks its claims against the trust policy, reads a secret from the vault, and the token expires when the job ends.

  1. Ask for a token. The job asks GitHub's OIDC service for a signed token (a JWT). Its claims say what is running: who issued it (iss), who it is for (aud), when it expires (exp), and the subject, sub: repo:swiftkart/data-pipelines:environment:prod.

  2. Exchange it. The job hands the token to the cloud. The cloud checks the signature and compares aud and sub with its trust policy. They match, so it returns a short-lived access token.

  3. Read what is still secret. A partner's API key is a real secret. It sits in a vault that this short-lived identity may read. The value is masked in the logs.

  4. The job ends. The token expires. Nothing was stored, so there is nothing to leak and nothing to replace by hand.

Read it top to bottom. A pull request from a branch gets a different sub (it names the event or the ref, not the prod environment), so the trust policy refuses it. That is what keeps unreviewed code away from production.

The deploy workflow: OIDC to Azure, one secret from Key Vault

Runs in the cloud:

name: deploy-prod
on:
  push:
    branches: [main]

permissions:
  id-token: write                   # lets the job ask for an OIDC token
  contents: read

jobs:
  prod:
    runs-on: ubuntu-latest
    environment: prod               # required reviewers; sub ends in :environment:prod
    steps:
      - uses: actions/checkout@v4
      - uses: azure/login@v2
        with:
          client-id: ${{ vars.AZURE_CLIENT_ID }}
          tenant-id: ${{ vars.AZURE_TENANT_ID }}
          subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
      - name: Read the partner API key
        run: |
          key=$(az keyvault secret show --vault-name swiftkart-prod-kv --name partner-api-key --query value -o tsv)
          echo "::add-mask::$key"
          echo "PARTNER_API_KEY=$key" >> "$GITHUB_ENV"
      - run: python -m swiftkart_pipeline deploy --image swiftkart-pipeline@${{ needs.build.outputs.digest }}
        env:
          SWIFTKART_ENV: prod

This is .github/workflows/deploy-prod.yml. The three ids are not secrets: they name the identity, and only a token whose claims match its federated credential can act as it. On AWS the same job uses aws-actions/configure-aws-credentials with role-to-assume, and the role's trust policy matches token.actions.githubusercontent.com:sub. A real file would also declare the build job that needs.build refers to.

Two CI traps. A test that cannot fail: a not-null test on an empty table passes, so give CI fixture rows that include the awkward cases, and add a row-count test. Production credentials in CI: a pull request's code is untrusted until it is reviewed, so CI uses a throwaway database or a dev schema, never prod's password.

Remember: the code can be right and the data wrong. So test the data on every pull request, and publish it only after it has passed.

Numbers to remember

WhatThe real nameNotes
Slim CI in dbtdbt build --select state:modified+Builds only the changed models and everything downstream of them, in a temporary schema. A pull request is checked in minutes.
Snowflake blue-greenALTER SCHEMA analytics SWAP WITH analyticsnextOne metadata operation: every object and grant changes sides. Zero-copy clones make the second copy cheap.
Iceberg write-audit-publishwrite.wap.enabled, spark.wap.branchA Spark job writes to a branch. CALL catalog.system.fastforward('db.orders', 'main', 'audit') publishes it.
GitHub's OIDC issuerhttps://token.actions.githubusercontent.comThe iss claim. The token is a JWT, and the workflow needs permissions: id-token: write to ask for one.
The trust policyan Azure federated credential, an AWS role trust policyIt matches the token's claims: sub, aud, and if you want ref and environment.
Secret storespick oneGitHub Actions secrets, Azure Key Vault, AWS Secrets Manager, HashiCorp Vault, Databricks secret scopes.
Databricks deploysdatabricks bundle deploy -t prodJobs and environments are described in Databricks Asset Bundles.

Tools such as Datafold post a data diff on every pull request, so the reviewer does not have to run one by hand.

What changed at SwiftKart

Every pull request now gets a two-minute run: the SQL is checked for style, the changed models are built on fixtures, the data tests run, and a data diff is posted. Monday's join would have gone red on "one row per day" before anyone could click Merge.

After the merge, one build goes to staging and then, with an approval, to prod. The nightly load is written to a hidden table, audited, and only then published. And the deploy job holds no cloud key.

Tess's dashboard has not doubled since.

One weak spot is left. Your laptop, the CI machine and production each have their own Python and their own libraries, and "it works on my machine" is not a test. Next: Shell, Docker and environments.

In one line

CI builds every pull request on sample rows and runs data tests before the merge, CD ships one build through staging to production and publishes data only after it passes its checks, and deploy jobs prove who they are with short-lived tokens, not stored keys.

Interview corner

How do you test a data pipeline?

Unit tests of transformations on small fixtures that include edge cases, data tests on outputs (unique, not null, accepted values, relationships, row counts and freshness), and a data diff against production for changed models. CI runs them on every pull request and blocks the merge on failure; the same data tests also run after each production load.

How does your deploy job get cloud credentials, and why not store a key in CI?

With OIDC: the job (with id-token: write) gets a signed JWT from GitHub whose claims name the repository and environment, the cloud's identity service checks it against a trust policy (a federated credential in Azure, a role trust policy in AWS), and returns a short-lived token for that job only. Nothing long-lived is stored, so there is nothing to leak or rotate. The prod rule matches only ...:environment:prod, which sits behind required reviewers, so pull request code can never act as prod; remaining secrets are read from Key Vault or Secrets Manager at run time.

How do you deploy a change to a large table so dashboards never show a half-built or wrong version?

Build it aside and publish atomically. Blue-green: build analytics_next, run the tests, then ALTER SCHEMA analytics SWAP WITH analytics_next in Snowflake, or repoint a view; rollback is swapping back. Write-audit-publish: write to an Iceberg branch or a staging table, run the data tests there, and publish with fast_forward or one transaction only if they pass. Both cost a second copy for a while, which zero-copy clones and branches make small.

How do you handle configuration and secrets across environments?

One codebase, with per-environment configuration (schemas, schedules, sizes) in version-controlled files, selected by an environment variable. Secrets live in a secret store such as Key Vault, Secrets Manager or the CI's secrets, and are injected as environment variables at run time. The code fails loudly if either is missing and never defaults to production.