Play ►Runtime 6 min#data#ai#dbt
Migrating, transforming and testing data for AI with dbt
How to use dbt to move data off a legacy system, shape it into training sets and AI-ready documents, and test it so bad data never reaches a model.
Most AI projects that disappoint do not fail at the model. They fail at the data underneath it: customer records duplicated across two systems, a status column that means three different things, a training set that quietly includes information the model would never have had at prediction time. The model learns all of it faithfully.
The fix is a pipeline that moves data off the systems it is stuck in, cleans and reshapes it in code everyone can read, and tests it on every run so problems stop the pipeline instead of reaching the model. dbt is the tool I reach for. It is open source, it is just SQL and YAML, and a team that knows SQL can own it after I leave.
The full example project is in the companion repository. It uses PostgreSQL and dbt 1.10 or later, but works on Snowflake, BigQuery, Databricks or Redshift with small changes.
The shape of the project
legacy CRM, orders DB, help centre
│
▼
sources ── raw tables, untouched, freshness checked
│
staging ── one model per source table: renamed, typed, cleaned
│
snapshots ─ history of records that change, for point-in-time joins
│
marts ──── customer_features · training_churn · ai_documents
│
├─▶ model training and scoring
└─▶ embedding job for search and assistants
dbt does not move data between systems. Something else loads the raw tables, and dbt does everything after that, inside the database. Keeping the two jobs separate makes the pipeline easy to reason about: raw data is always there exactly as it arrived, and every change to it is a reviewed SQL file in Git.
1. Migrating off the legacy system
Declare the raw tables as sources with a freshness check, so the pipeline knows when the loader has stopped delivering. Then write one staging model per table. This is where decades of legacy habits are undone, once, in one place:
select
cust_no::int as customer_id,
lower(trim(email_addr)) as email,
nullif(trim(status_cd), '') as status_code,
nullif(trim(plan_cd), '') as plan,
created_dt::timestamp as created_at,
last_mod_dt::timestamp as updated_at
from {{ source('legacy_crm', 'customers') }}
where cust_no is not null
The hardest part of any migration is proving the new system gives the same answers as the old one. So run both side by side and make the comparison a test. The parity test compares the legacy report with the rebuilt model using except in both directions, and fails on any row that differs.
Every row it returns is a discrepancy to explain. Sometimes the new model is wrong. Often the old one was, and the migration is the first time anyone noticed. When the test has passed for a few weeks, you can switch the old system off with confidence. For a column-by-column breakdown, the audit_helper package does the same job with a report.
2. Transforming data into something a model can use
Features, computed the same way every time
A feature table holds one row per thing you want to predict about. Writing it in dbt means the definition of “lifetime value” or “days since last order” lives in one reviewed file, not in a notebook on someone’s laptop. The customer feature model takes the date as a variable:
{% set as_of = var('as_of_date', run_started_at.strftime('%Y-%m-%d')) %}
That matters. A model that calls current_date gives a different answer every day and cannot be tested or reproduced. One that takes the date as an input can be rerun for any day in the past, and that is how training sets are built.
Training sets without leakage
The most common silent bug in machine learning data is leakage: training on information that was not available when the prediction would have been made. If a customer’s plan changed to “cancelled” the day after they churned, and the training set uses today’s plan, the model learns to cheat. It looks brilliant right up until it is used for real.
A dbt snapshot records how each customer looked over time, with dbt_valid_from and dbt_valid_to columns. The training set then joins each label to the customer as they were on that date:
join {{ ref('customers_snapshot') }} as s
on s.customer_id = l.customer_id
and l.label_date >= s.dbt_valid_from
and l.label_date < coalesce(s.dbt_valid_to, 'infinity'::timestamp)
Start snapshotting early. History you did not capture cannot be recovered, and it is often the difference between a model you can train next month and one you have to wait a year for.
Documents for AI assistants and search
Assistants that answer questions about your business run on documents: product descriptions, policies, support articles. Those need the same care as numeric data, so build them as a dbt model too. Filter out drafts and stubs in reviewed SQL, and include a hash of the content so the embedding job only re-embeds what changed.
3. Testing, so bad data stops the pipeline
Tests run in the same command as the models, in dependency order, and a failing test stops everything downstream of it, so a broken load never reaches the training set or the assistant. All of these are in _marts.yml.
- Data tests on every important column. The built-in tests catch duplicates, missing values, orphaned records and unexpected categories. A new plan code nobody told the data team about is exactly the kind of thing that skews a model for months. Since dbt 1.10, a test’s inputs go under
arguments. - Custom tests for AI-specific problems. A feature that is suddenly 40% null still lets the model train, just badly. A small custom test catches that. A join that fans out silently duplicates training examples, and a singular test guards against it.
- Unit tests for the business logic. Data tests check the data you have. Unit tests check the logic against data you choose, including edge cases that have not happened yet. The example pins down what “churned” means, including that a customer who never ordered counts as churned. That is a business decision, and now it is written down, reviewed and enforced.
- Contracts for what other systems depend on. The embedding job and training code depend on the exact shape of
ai_documents. With an enforced contract, renaming a column or changing a type fails at build time, in front of the person who made the change, instead of breaking the assistant in production overnight.
Running it
dbt source freshness
dbt build
dbt build runs snapshots, models, unit tests and data tests in dependency order, and skips anything downstream of a failure. Schedule it after the nightly load, and start training and embedding jobs only when it succeeds. On pull requests, dbt build --select state:modified+ --defer --state ./prod-artifacts builds and tests only what changed, against real data, before it merges.
What you end up with
- One definition of every number. Lifetime value, churn and every other feature is defined once, in reviewed SQL, and the reports, models and assistants all use it.
- A migration you can prove. The old system is switched off when the parity tests say it is safe, not when a deadline says so.
- Training data you can trust and reproduce. Point-in-time joins remove leakage, and any training set can be rebuilt for any date.
- Problems caught before the model sees them. A broken load or a bad change stops the pipeline and tells you why.
None of it needs a large data platform. For a small or medium business, PostgreSQL and dbt Core on a single server, like the $40 a month setup, is enough to start, and the same project moves to a cloud warehouse unchanged when you outgrow it.
If you have data stuck in a legacy system, or an AI project that is not living up to the demo, this is the kind of work I do. Email hello@byrenhigg.in with a few lines on where your data lives and what you want it to do.