Lab: Docs and dbt build in Pull-Request CI
Document marts in YAML, generate the docs artifacts and persist the descriptions as DuckDB comments, then simulate pull-request CI locally: save the production manifest, change one staging model, build only it and its dependents with state:modified+ and --defer, watch a failing test turn the exit code red, and wire the same command into a GitHub Actions workflow.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Create the project
- Step 2: Write the marts and document them
- Step 3: Build production and generate the docs
- Step 4: Save the production state
- Step 5: Change a model and select what the change affects
- Step 6: Run the CI build with --defer
- Step 7: Turn CI red with a failing test
- Step 8: The same check in GitHub Actions
- Check your understanding
- Apply it
- Review prompt
Lessons of SQL Transformation with dbt
- Why Transformations Belong in Version-Controlled SQL Concept · 15 min
- Lab: Sources, Staging Models and the ref() Graph Lab · 30 min
- Materializations and Incremental Models Worked example · 25 min
- Snapshots, Macros and Keeping Jinja in Check Lab · 25 min
- Lab: Docs and dbt build in Pull-Request CI Lab · 25 min
- Check: Review a dbt Pull Request Knowledge check · 8 questions
What you will learn
- Document models and run dbt build (models plus tests) in CI on every pull request, building only changed models and their dependents.
Prerequisites: SQL Fundamentals
01. Goal and setup
A dbt project is only as safe as the checks that run before a change reaches production. In this lab you do two things. First you document the marts, so that the meaning of each column is written next to the code and shows up in the generated docs and in the warehouse itself. Then you rehearse what a CI (continuous integration) job does on every pull request: build and test only what the change affects, against production data, and fail loudly when a test breaks.
The lab was tested with Python 3.12, dbt Core 1.12.7, dbt-duckdb 1.11.1 and DuckDB 1.5.6. It assumes you know sources, staging models and dbt build from the sources and staging lab. One DuckDB file plays the warehouse, with schema prod for production and schema ci for the CI build.
mkdir shop_ci && cd shop_ci
python3 -m venv .venv && source .venv/bin/activate
pip install "dbt-core==1.12.7" "dbt-duckdb==1.11.1" "duckdb==1.5.6"
mkdir -p models/staging models/marts02. Step 1: Create the project
The profile reads the database path from the DUCKDB_PATH environment variable with env_var(), falling back to warehouse.duckdb. The CI workflow in step 8 sets that variable so that two checkouts share one database. requirements.txt pins dbt and DuckDB, so CI installs the versions you tested. In dbt_project.yml, persist_docs asks dbt to write model and column descriptions of the marts into the warehouse as comments.
name: shop_ci
version: "1.0.0"
profile: shop_ci
models:
shop_ci:
staging:
+materialized: view
marts:
+materialized: table
+persist_docs:
relation: true
columns: trueshop_ci:
target: prod
outputs:
prod:
type: duckdb
path: "{{ env_var('DUCKDB_PATH', 'warehouse.duckdb') }}"
schema: prod
threads: 1
ci:
type: duckdb
path: "{{ env_var('DUCKDB_PATH', 'warehouse.duckdb') }}"
schema: ci
threads: 1dbt-core==1.12.7
dbt-duckdb==1.11.1
duckdb==1.5.6"""Stand-in for the ingestion job: writes raw.customers and raw.orders."""
import os
import duckdb
con = duckdb.connect(os.environ.get("DUCKDB_PATH", "warehouse.duckdb"))
con.execute("CREATE SCHEMA IF NOT EXISTS raw")
con.execute("""CREATE OR REPLACE TABLE raw.customers AS SELECT * FROM (VALUES
(1, 'Ana', '[email protected]', 'gb'),
(2, 'Bo', '[email protected]', 'GB'),
(3, 'Cy', '[email protected]', 'FR'),
(4, 'Bo', '[email protected]', 'GB')
) AS t(id, name, email, country)""")
con.execute("""CREATE OR REPLACE TABLE raw.orders AS SELECT * FROM (VALUES
(101, 1, DATE '2026-07-01', 30.00), (102, 2, DATE '2026-07-01', 12.50),
(103, 1, DATE '2026-07-02', 8.00), (104, 3, DATE '2026-07-02', 41.00)
) AS t(id, customer_id, order_date, amount)""")
print("raw.customers: 4 rows, raw.orders: 4 rows")sources:
- name: shop
schema: raw
tables:
- name: customers
- name: ordersselect
id as customer_id,
name,
email,
country as country_code
from {{ source('shop', 'customers') }}select
id as order_id,
customer_id,
order_date,
amount
from {{ source('shop', 'orders') }}models:
- name: stg_customers
columns:
- name: customer_id
data_tests: [unique, not_null]
- name: email
data_tests: [unique]
- name: stg_orders
columns:
- name: order_id
data_tests: [unique, not_null]03. Step 2: Write the marts and document them
Two marts read the staging models: customer_orders, one row per customer, and daily_revenue, one row per day. Their YAML properties file gives each model a description and describes the columns a reader could misunderstand. A good description states the grain (what one row means), units and edge cases, such as what a customer without orders shows. Descriptions can use Markdown, and longer shared text can live in a {% docs %} block that several models reuse with {{ doc('name') }}.
select
c.customer_id,
c.name,
c.country_code,
count(o.order_id) as order_count,
coalesce(sum(o.amount), 0) as total_spent
from {{ ref('stg_customers') }} as c
left join {{ ref('stg_orders') }} as o using (customer_id)
group by allselect order_date, sum(amount) as revenue
from {{ ref('stg_orders') }}
group by order_datemodels:
- name: customer_orders
description: One row per customer with their order count and total spend.
columns:
- name: customer_id
description: Primary key, from the shop's customer table.
data_tests: [unique, not_null]
- name: country_code
description: ISO 3166-1 alpha-2 code, as entered at sign-up.
- name: total_spent
description: Sum of order amounts in GBP; 0 if no orders.
- name: daily_revenue
description: Revenue per order date, in GBP, before refunds.04. Step 3: Build production and generate the docs
Build everything into prod, which is the default target in this profile. Then dbt docs generate writes the documentation artifacts to target/: manifest.json with the project, its descriptions and its graph, catalog.json with the column types it reads from the warehouse, and index.html, the documentation site. dbt docs serve would open that site on port 8080, with a lineage graph for every model. The script below checks the three places a description can now be found.
"""Print the status and name of every node in dbt's last run, in run order."""
import json
with open("target/run_results.json") as f:
run = json.load(f)
for result in run["results"]:
kind, _, name = result["unique_id"].split(".")[:3]
print(f"{result['status']:<7} {kind:<5} {name}")"""Show where the YAML descriptions of customer_orders ended up."""
import json
import duckdb
NODE = "model.shop_ci.customer_orders"
with open("target/manifest.json") as f:
print("manifest: ", json.load(f)["nodes"][NODE]["description"])
with open("target/catalog.json") as f:
for name, col in json.load(f)["nodes"][NODE]["columns"].items():
print(f"catalog: {name:<13} {col['type']:<14} {col['comment']}")
con = duckdb.connect("warehouse.duckdb", read_only=True)
comment = con.execute("select comment from duckdb_tables() "
"where schema_name = 'prod' "
"and table_name = 'customer_orders'").fetchone()[0]
print("warehouse:", comment)python load_raw.py
dbt build --quiet
python results.py
dbt docs generate --quiet
python docs_check.pyraw.customers: 4 rows, raw.orders: 4 rows
success model stg_customers
success model stg_orders
pass test not_null_stg_customers_customer_id
pass test unique_stg_customers_customer_id
pass test unique_stg_customers_email
pass test not_null_stg_orders_order_id
pass test unique_stg_orders_order_id
success model customer_orders
success model daily_revenue
pass test not_null_customer_orders_customer_id
pass test unique_customer_orders_customer_id
manifest: One row per customer with their order count and total spend.
catalog: customer_id INTEGER Primary key, from the shop's customer table.
catalog: name VARCHAR None
catalog: country_code VARCHAR ISO 3166-1 alpha-2 code, as entered at sign-up.
catalog: order_count BIGINT None
catalog: total_spent DECIMAL(38,2) Sum of order amounts in GBP; 0 if no orders.
warehouse: One row per customer with their order count and total spend.The manifest holds the description from YAML. The catalog shows the comments that dbt read back from DuckDB, and the last line reads the table comment straight from the warehouse: persist_docs worked on DuckDB. A BI (business intelligence) tool or an analyst querying the warehouse now sees the same text without opening the docs site. Columns without a description have no comment. The staging views have no persist_docs setting, so their descriptions, if you add some, stay in the docs site only.
05. Step 4: Save the production state
CI compares a pull request with production. dbt does that with state: the manifest.json of a production run, which records every node and a checksum of its code. Copy it somewhere it will not be overwritten. A real production job would upload it to object storage after each run, and CI would download it.
mkdir -p prod-artifacts && cp target/manifest.json prod-artifacts/
ls prod-artifactsmanifest.json06. Step 5: Change a model and select what the change affects
Now act as a developer on a branch. Customer 1 was stored with the country gb, so normalise the code to upper case in stg_customers:
select
id as customer_id,
name,
email,
upper(country) as country_code
from {{ source('shop', 'customers') }}state:modified selects nodes that are new or whose code or configuration differs from the manifest in --state. The trailing + adds everything downstream of them.
dbt ls --select state:modified+ --state prod-artifacts --output name --quietcustomer_orders
stg_customers
not_null_customer_orders_customer_id
not_null_stg_customers_customer_id
unique_customer_orders_customer_id
unique_stg_customers_customer_id
unique_stg_customers_emailTwo models and their five tests. stg_orders and daily_revenue are untouched by the change, so CI can skip them. In a project with hundreds of models, skipping the unaffected ones can save most of the build.
07. Step 6: Run the CI build with --defer
customer_orders also reads stg_orders, which is not selected and does not exist in the empty ci schema. --defer tells dbt to resolve such a ref() to the relation recorded in the state manifest, here the production table. CI therefore builds two models instead of the whole chain, and tests them against real production inputs. echo "exit code: $?" prints the exit code of dbt build, the number CI uses to decide pass or fail.
dbt build --select state:modified+ --defer --state prod-artifacts \
--target ci --quiet
echo "exit code: $?"
python results.py
grep -E '^(from|left join)' target/run/shop_ci/models/marts/customer_orders.sqlexit code: 0
success model stg_customers
pass test not_null_stg_customers_customer_id
pass test unique_stg_customers_customer_id
pass test unique_stg_customers_email
success model customer_orders
pass test not_null_customer_orders_customer_id
pass test unique_customer_orders_customer_id
from "warehouse"."ci"."stg_customers" as c
left join "warehouse"."prod"."stg_orders" as o using (customer_id)The SQL that ran reads the changed model from ci and the unchanged one from prod. Without --defer, the same build would fail with a missing ci.stg_orders, or you would have to build every parent first.
08. Step 7: Turn CI red with a failing test
The developer also lower-cases the emails, which looks harmless. Change the email line of stg_customers.sql to lower(email) as email, and run the same CI command.
select
id as customer_id,
name,
lower(email) as email,
upper(country) as country_code
from {{ source('shop', 'customers') }}dbt build --select state:modified+ --defer --state prod-artifacts \
--target ci --quiet > ci.log
echo "exit code: $?"
python results.pyexit code: 1
success model stg_customers
pass test not_null_stg_customers_customer_id
pass test unique_stg_customers_customer_id
fail test unique_stg_customers_email
skipped model customer_orders
skipped test not_null_customer_orders_customer_id
skipped test unique_customer_orders_customer_idcat ci.log00:01:12 [ERROR]: in test unique_stg_customers_email (models/staging/_staging.yml)
00:01:12 Got 1 result, configured to fail if != 0Customers 2 and 4 differ only in the case of their email, so lower-casing creates a duplicate and the unique test fails. dbt build then skips everything downstream of the failure and exits with code 1. A CI system marks a step as failed when its command exits with a non-zero code, so the pull request shows a red check, and with branch protection it cannot be merged. The test did its job: two customer records may be one person, and that is a question for the data owner, not something to hide by deleting the test.
09. Step 8: The same check in GitHub Actions
The workflow below runs the CI command on every pull request to main. Because DuckDB is a local file, the job first checks out main, builds production from it and saves its manifest; then it builds the pull request with state:modified+ and --defer. With a cloud warehouse you would skip the production build and download the manifest that your production job published instead. The ci target would then point at a schema of its own for each pull request.
Each action is pinned to a full commit SHA, with the release tag in a comment. A tag such as v7 can be moved to other code; a SHA cannot. persist-credentials: false keeps the checkout token out of the working copy, and permissions: contents: read gives the job no write access. Commit the file, then make the check required in the branch protection rules of main.
name: dbt CI
on:
pull_request:
branches: [main]
permissions:
contents: read
jobs:
dbt-build:
runs-on: ubuntu-24.04
env:
DUCKDB_PATH: ${{ github.workspace }}/warehouse.duckdb
steps:
- name: Check out the pull request
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
path: pr
persist-credentials: false
- name: Check out main
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: main
path: main
persist-credentials: false
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.12"
- name: Install dbt
run: pip install -r pr/requirements.txt
- name: Build production from main and keep its manifest
working-directory: main
run: |
python load_raw.py
dbt build --target prod
mkdir -p ../prod-artifacts
cp target/manifest.json ../prod-artifacts/
- name: Build and test changed models and their dependents
working-directory: pr
run: >-
dbt build --select state:modified+ --defer
--state ../prod-artifacts --target ciThe last step is the command from step 6. If a test fails, dbt build exits with 1, the step fails, and GitHub shows the pull request check as failed. Generating the docs in CI is optional; many teams run dbt docs generate in the production job instead and publish the site from there.
10. Check your understanding
11. Apply it
The practice project requires a CI job that runs dbt build on every pull request and fails when a model or test breaks. Finish it:
- Describe every mart and every column whose meaning, unit or edge case is not obvious, and turn on
persist_docsfor marts. - Push the workflow to a repository, open a pull request that changes one staging model, and confirm in the job log that only it and its descendants were built.
- Open a second pull request that breaks a test and check that the merge button is blocked.
- Change the production step so that it uploads
manifest.jsonas an artifact, and think about where your real production job should publish it.
12. Review prompt
Without looking back, explain in your own words:
- what
manifest.jsonandcatalog.jsoneach contain, and whatpersist_docsadds; - what
state:modified+selects and what it compares against; - when
--deferresolves aref()to production, and why CI needs that; - how a failing test becomes a red check on a pull request.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.