Writing / Technical / Build Log · 2 NOV 2026
Every Test Passed but the Bug Was Still There
I broke my own feature on purpose and every check came back green. How I built a tested, point-in-time feature in layers with dbt, the leak that slipped through, how I closed the gap, and the small API that serves the result.
I broke my own feature on purpose, ran the full test suite, and watched every single check come back green.
The bug I'd planted was the most dangerous mistake possible in this project because it was a feature quietly using information from the future. And nothing caught it. It wasn't necessarily because the tests were badly written, but because my data was physically incapable of showing the problem.
This post is about the stage of the Newcomer Credit Data Platform where raw data finally becomes something useful. That is a tested, point-in-time feature that a lending system can request over HTTP. It covers how I built it in layers with dbt, what I learned writing the feature definition before the SQL, the leak that slipped through, how I closed the gap, and the small API that serves the result.
Series so far:
- Before the First Pipeline: setting up the machine and project base
- Fake Data, Real Discipline: generating a seeded synthetic population
- From Files to Tables: loading data idempotently into PostgreSQL
- Every Test Passed but the Bug Was Still There (this post)
The code is on GitHub.
What I ended up with
One command runs the whole pipeline: generate the data, load it, build every model and run every test.
$ make pipeline
Generated with seed 42 (generator v1.0.0)
customers run 4: 0 inserted, 1,000 already loaded
bank_transactions run 5: 0 inserted, 59,801 already loaded
applications run 6: 0 inserted, 1,000 already loaded
...
Done. PASS=26 WARN=0 ERROR=0 SKIP=0
Then a running service answers questions about any application:
$ curl localhost:8000/features/income-regularity/APP-00001
{
"application_id": "APP-00001",
"customer_id": "CUST-00001",
"decided_at": "2024-10-04T17:49:00Z",
"main_income_source": "ALDERWOOD HOSPITALITY",
"income_payments_6m": 6,
"median_income_amount": "1770.00",
"median_gap_days": 30.0,
"income_amount_cv": "0.0000",
"is_regular_income": true,
"feature_version": "v1"
}
This is the project's first vertical slice: one thin path running through every layer, from a CSV file to an HTTP response. Everything after this widens the path rather than starting new ones.
Part 1: What dbt actually does
I already knew SQL. dbt doesn't replace it. It organises it.
Think of a recipe book in a restaurant kitchen. Each recipe makes one dish, built from ingredients or from other recipes. A sauce gets used in three dishes. The book tells the cooks what order to cook in, and every dish gets tasted before it leaves the kitchen.
| In the kitchen | In dbt |
|---|---|
| A recipe | A model: one .sql file containing one SELECT |
| Ingredients from the delivery shelf | A source: a table dbt didn't build, like my raw tables |
| "Use the sauce from recipe 4" | {{ ref('model_name') }} |
| "Use flour from the shelf" | {{ source('raw', 'table_name') }} |
| Tasting before serving | Tests |
| The head chef deciding the order | dbt reads every ref() and works out the order itself |
The {{ }} parts are Jinja, a templating language. Before running anything, dbt replaces {{ ref('stg_applications') }} with a real table name like staging.stg_applications. That's how it knows what depends on what, and why I never have to list the build order by hand.
One command does everything: dbt build creates every model in dependency order and runs every test as it goes. If a test fails, dbt skips everything built on top of it. A broken ingredient never ends up in a finished dish, and a broken feature never reaches the API.
Views and tables
Each model is saved one of two ways:
- A view is a saved query. It stores nothing and always reflects the latest underlying data, but it's recalculated every time someone reads it.
- A table stores its results. It's fast to read, but only as fresh as the last build.
My staging and intermediate models are views: cheap, always fresh, read only by other models. The final feature is a table, because the API reads it constantly and needs it fast.
Three layers, three jobs
raw tables staging intermediate marts
(as loaded) ---> clean and ---> which income was ---> the feature:
standardise visible at decision one row per
time? gaps between application
payments?
- Staging cleans and renames. One model per source table. No business logic.
- Intermediate prepares building blocks that business logic needs.
- Marts answer the actual question, in the shape consumers want.
Keeping these separate means each model does one understandable thing, and when something's wrong, I know which layer to look in.
Part 2: The staging layer
-- dbt/models/staging/stg_bank_transactions.sql
select
transaction_id,
customer_id,
amount,
abs(amount) as amount_abs,
case when amount > 0 then 'credit'
when amount < 0 then 'debit'
else 'zero' end as direction,
upper(currency) as currency,
upper(trim(counterparty)) as counterparty,
description,
event_at,
booked_at,
available_at,
_run_id as loaded_by_run_id
from {{ source('raw', 'bank_transactions') }}
direction turns a sign into a word, so every later model can say where direction = 'credit' instead of remembering that positive means money in. upper(trim(...)) standardises text, so " Pulse Mobile" and "PULSE MOBILE" become the same counterparty. That kind of mismatch silently splits one income source into two.
Tests sit beside the models in YAML:
# dbt/models/staging/_staging.yml (excerpt)
- name: stg_bank_transactions
columns:
- name: transaction_id
data_tests: [unique, not_null]
- name: customer_id
data_tests:
- not_null
- relationships:
arguments:
to: ref('stg_customers')
field: customer_id
- name: direction
data_tests:
- accepted_values:
arguments:
values: ['credit', 'debit']
These are dbt's built-in generic tests:
uniqueandnot_null: keys are present and never repeated.relationships: everycustomer_idhere exists instg_customers. In the previous post, I deliberately left foreign keys out of the raw tables, because real sources arrive in any order. This is where that relationship gets checked instead: tested, not enforced at the door.accepted_values: onlycreditordebit. A zero-amount transaction would show up aszeroand fail, which is exactly the kind of thing I'd want to hear about.
A naming quirk worth knowing
My dbt_project.yml tells each layer which schema to live in:
models:
newcomer_credit:
staging:
+schema: staging
+materialized: view
intermediate:
+schema: intermediate
+materialized: view
marts:
+schema: marts
+materialized: table
By default, dbt glues the connection's default schema onto every custom schema. My default is staging, so +schema: marts would become staging_marts, and staging would become staging_staging. A small macro overrides that:
-- dbt/macros/generate_schema_name.sql
{% macro generate_schema_name(custom_schema_name, node) -%}
{%- if custom_schema_name is none -%}
{{ target.schema }}
{%- else -%}
{{ custom_schema_name | trim }}
{%- endif -%}
{%- endmacro %}
A macro is a reusable piece of Jinja, like a function. Defining one with this exact name replaces dbt's built-in behaviour. Almost everyone runs into this the first time they use custom schemas.
Part 3: Write the definition before the SQL
Before writing a line of the feature, I wrote down what it means, in plain words, in features/CHANGELOG.md:
income_regularity v1
Question it answers: does this applicant have a steady, predictable income?
Data allowed: only incoming money the lender could see at decision time
(available_at <= decided_at), from the 6 months before the decision.
For each source of incoming money:
- at least 3 payments
- median gap between payments of 25 to 35 days
- every payment within 20% of that source's median amount
The main income source is the one with the most payments.
An application with no qualifying source still gets a row, marked not regular.
This felt like paperwork until I realised what it buys. When someone asks "what does is_regular_income actually mean?", the answer is a short document anyone can read, not "go read 80 lines of SQL." When I want to change a threshold, the change is a visible, versioned decision rather than a quiet edit. And writing it first forced me to decide the hard questions, like what happens to someone with no income at all, before the code made the decision for me.
I used the median rather than the average throughout. The median is the middle value when you sort a list. One odd value, like a bonus or a single late payment, barely moves a median but can drag an average a long way.
Part 4: The most important line in the project
The intermediate layer answers one question: for each loan application, which incoming money was the lender actually allowed to see?
-- dbt/models/intermediate/int_income_known_at_decision.sql
with applications as (
select * from {{ ref('stg_applications') }}
),
credits as (
select * from {{ ref('stg_bank_transactions') }}
where direction = 'credit'
)
select
a.application_id,
a.customer_id,
a.decided_at,
c.transaction_id,
c.counterparty,
c.amount,
c.event_at,
c.available_at
from applications a
join credits c
on c.customer_id = a.customer_id
where c.available_at <= a.decided_at -- point in time: no peeking
and c.event_at >= a.decided_at - interval '6 months' -- lookback window
Every transaction in this project carries separate timestamps for when it happened (event_at) and when the lender could see it (available_at). In real banking, those differ: a payment can happen on 30 May and only reach the lender's data feed on 10 June.
The first WHERE line uses available_at. A feature for a decision made on 1 June may only use money the lender could see by 1 June. Using anything later is data leakage: the feature quietly learns from the future. Leaky features look brilliant in testing, because they're effectively cheating, and then fail the moment they meet real decisions.
The next model calculates the gap between consecutive payments from the same source:
-- dbt/models/intermediate/int_income_gaps.sql
select
*,
(event_at at time zone 'UTC')::date
- lag((event_at at time zone 'UTC')::date) over (
partition by application_id, counterparty
order by event_at
) as gap_days
from {{ ref('int_income_known_at_decision') }}
LAG fetches a value from the previous row, and partition by application_id, counterparty restarts the sequence for every application and every income source. The at time zone 'UTC' matters more than it looks. Without it, the date of a timestamp depends on the time zone of whoever runs the query: a payment at 23:30 UTC falls on a different date in Nairobi. Converting explicitly means the answer is the same everywhere.
Part 5: The feature itself
The mart model is a chain of small steps. Four ideas inside it are worth calling out.
Medians in PostgreSQL:
percentile_cont(0.5) within group (order by amount) as median_amount,
percentile_cont(0.5) is the value 50% of the way through the sorted list: the median.
"Every payment" as one expression:
bool_and(abs(g.amount - m.median_amount) <= 0.20 * m.median_amount) as amounts_consistent,
bool_and is true only when the condition holds for every row in the group. One payment far from the median makes it false. It has to happen in a second step, because you can't compare each payment to the median until the median exists.
Deterministic ranking:
row_number() over (
partition by application_id
order by n_payments desc, total_amount desc, counterparty
) as source_rank
To pick one main income source per application, I rank them. The last sort key, counterparty, breaks any remaining tie alphabetically. Without it, two sources tied on everything could swap places between runs, and the feature would change for no reason at all. Rankings should never depend on luck.
Nobody disappears:
from applications a
left join main_source s
on s.application_id = a.application_id
coalesce(
s.n_payments >= 3
and s.median_gap_days between 25 and 35
and s.amounts_consistent,
false
) as is_regular_income,
A plain join would drop applications with no income at all, which are exactly the people a lender most needs to know about. Starting from the full list of applications with a left join keeps everyone. coalesce(..., false) turns "no data to judge" into an explicit answer: no.
The full model is in the appendix.
Part 6: All 1,000 came out the same
I built everything and looked at the results.
SELECT application_id, main_income_source, income_payments_6m,
median_income_amount, median_gap_days, is_regular_income
FROM marts.feat_income_regularity
ORDER BY application_id
LIMIT 4;
application_id | main_income_source | income_payments_6m | median_income_amount | median_gap_days | is_regular_income
----------------+-----------------------+--------------------+----------------------+-----------------+-------------------
APP-00001 | ALDERWOOD HOSPITALITY | 6 | 1770.00 | 30 | t
APP-00002 | HARBOURVIEW LOGISTICS | 5 | 2130.00 | 30 | t
APP-00003 | KESTREL ENGINEERING | 5 | 2590.00 | 30.5 | t
APP-00004 | ALDERWOOD HOSPITALITY | 6 | 2200.00 | 29 | t
Reasonable. Then I checked the distribution:
SELECT is_regular_income, count(*)
FROM marts.feat_income_regularity
GROUP BY 1;
is_regular_income | count
-------------------+-------
t | 1000
Every single application was regular.
That's not a bug in the feature. The first version of my generator only creates salaried customers, so every one of them genuinely is regular. But it exposed two things I hadn't thought about.
First, a feature that's the same for everyone carries no information. A column that's all true should always make you suspicious, either of the feature or of the data feeding it. Checking a new feature's distribution is now a habit.
Second, and more uncomfortable: I had no evidence the feature could ever say "no." The real data never produced an irregular case, so the logic for rejecting one had never actually run. It could have been completely wrong and every test would still have passed.
Part 7: Three kinds of tests
By the end of this stage, the project had all three kinds of dbt test, and the difference between them turned out to be the whole story.
| Kind | Where it lives | What it checks |
|---|---|---|
| Generic | YAML files | A standard rule on a column of real data: unique, not_null, relationships, accepted_values |
| Singular | A .sql file in tests/ |
A query that returns bad rows from real data. Any row returned means failure |
| Unit | unit_tests: in YAML |
Feeds a model hand-made input rows and compares its output to what you expect |
Generic and singular tests check your data. Unit tests check your logic, using data you invent.
The singular guard
-- dbt/tests/assert_no_income_seen_after_decision.sql
select application_id, transaction_id, available_at, decided_at
from {{ ref('int_income_known_at_decision') }}
where available_at > decided_at
Read it as a question: "show me any income the lender couldn't have seen at decision time." The right answer is nothing. Any row returned fails the build.
A unit test that makes the feature say no
Because the real data never produced an irregular case, I invented some:
# dbt/models/marts/_marts.yml (excerpt)
unit_tests:
- name: income_regularity_says_no_when_it_should
model: feat_income_regularity
given:
- input: ref('int_income_gaps')
rows:
# A: a steady salary. Should be regular.
- {application_id: APP-A, counterparty: EMPLOYER, amount: 2000, gap_days: null}
- {application_id: APP-A, counterparty: EMPLOYER, amount: 2000, gap_days: 30}
- {application_id: APP-A, counterparty: EMPLOYER, amount: 2000, gap_days: 31}
# B: gig income, irregular timing. Not regular.
- {application_id: APP-B, counterparty: GIG APP, amount: 300, gap_days: null}
- {application_id: APP-B, counterparty: GIG APP, amount: 320, gap_days: 9}
- {application_id: APP-B, counterparty: GIG APP, amount: 310, gap_days: 4}
- {application_id: APP-B, counterparty: GIG APP, amount: 290, gap_days: 12}
# C: only two payments. Not enough evidence.
- {application_id: APP-C, counterparty: EMPLOYER, amount: 2000, gap_days: null}
- {application_id: APP-C, counterparty: EMPLOYER, amount: 2000, gap_days: 30}
# E: monthly, but one payment far below the others. Not consistent.
- {application_id: APP-E, counterparty: EMPLOYER, amount: 2000, gap_days: null}
- {application_id: APP-E, counterparty: EMPLOYER, amount: 2000, gap_days: 30}
- {application_id: APP-E, counterparty: EMPLOYER, amount: 900, gap_days: 30}
# D has no income rows at all.
- input: ref('stg_applications')
rows:
- {application_id: APP-A, customer_id: C-A}
- {application_id: APP-B, customer_id: C-B}
- {application_id: APP-C, customer_id: C-C}
- {application_id: APP-D, customer_id: C-D}
- {application_id: APP-E, customer_id: C-E}
expect:
rows:
- {application_id: APP-A, income_payments_6m: 3, is_regular_income: true}
- {application_id: APP-B, income_payments_6m: 4, is_regular_income: false}
- {application_id: APP-C, income_payments_6m: 2, is_regular_income: false}
- {application_id: APP-D, income_payments_6m: 0, is_regular_income: false}
- {application_id: APP-E, income_payments_6m: 3, is_regular_income: false}
Five invented applications, each a situation the real data never contains, each with the answer I expect. The test skips everything upstream and feeds rows straight into the model. Now the "no" logic has actually run, and it's proven.
Part 8: The fire drills
A test you've never seen fail hasn't proven anything yet. So I broke the feature three ways and watched what happened.
Drill 1: delete the point-in-time rule
I replaced where c.available_at <= a.decided_at with where true.
Before any unit tests existed, the singular guard caught it immediately:
FAIL 6211 assert_no_income_seen_after_decision
6,211 pieces of future income had slipped into the feature's inputs. And dbt refused to build anything on top of the failed test, so no leaky feature was ever published.
Drill 2: the subtle leak
Then I tried the version of the bug that actually happens in real code. Instead of deleting the rule, I swapped one column for another:
-- correct
where c.available_at <= a.decided_at
-- bug
where c.event_at <= a.decided_at
It's a plausible mistake. Both columns are timestamps. Both sound right. A tired engineer, or a quick code review, would let it through.
I ran the build:
Done. PASS=25 WARN=0 ERROR=0 SKIP=0
Every test passed.
The most dangerous bug in the project was completely invisible, and it took me a minute to understand why. In the first version of my generator, every payment arrives the instant it happens. event_at and available_at are identical in every single row. So swapping one for the other changes nothing in the real data, and no test running on the real data can ever tell the difference.
The bug would have sat there, silent, until the day real late-arriving data turned up. Then features would start quietly using the future, and the tests that were supposed to protect against exactly this would keep coming back green.
Closing the gap
The real data couldn't show the problem, so I wrote data that could:
# dbt/models/intermediate/_intermediate.yml
unit_tests:
- name: late_arriving_income_is_excluded
model: int_income_known_at_decision
given:
- input: ref('stg_applications')
rows:
- {application_id: APP-1, customer_id: C-1, decided_at: "2025-06-01 12:00:00+00"}
- input: ref('stg_bank_transactions')
rows:
# Happened and arrived before the decision: counts.
- {transaction_id: T-ON-TIME, customer_id: C-1, direction: credit, amount: 2000,
event_at: "2025-05-28 06:00:00+00", available_at: "2025-05-28 06:00:00+00"}
# Happened before, but arrived AFTER the decision: must NOT count.
- {transaction_id: T-LATE, customer_id: C-1, direction: credit, amount: 2000,
event_at: "2025-05-30 06:00:00+00", available_at: "2025-06-10 06:00:00+00"}
# Older than the 6-month lookback: must NOT count.
- {transaction_id: T-TOO-OLD, customer_id: C-1, direction: credit, amount: 2000,
event_at: "2024-11-20 06:00:00+00", available_at: "2024-11-20 06:00:00+00"}
# Money going OUT: not income, must NOT count.
- {transaction_id: T-RENT, customer_id: C-1, direction: debit, amount: -800,
event_at: "2025-05-01 09:00:00+00", available_at: "2025-05-01 09:00:00+00"}
expect:
rows:
- {application_id: APP-1, transaction_id: T-ON-TIME}
One payment that happened before the decision but arrived after it. Only T-ON-TIME is allowed through. The same test also checks the six-month window and that outgoing money never counts as income.
With this in place, the same swap fails the build:
FAIL 1 int_income_known_at_decision::late_arriving_income_is_excluded
Done. PASS=14 WARN=0 ERROR=1 SKIP=11
And it changed Drill 1 too. dbt runs a model's unit tests before building the model, so deleting the rule is now caught by this unit test first, with the singular guard still behind it. Two independent checks guard the same rule. That's defence in depth: if one has a gap, the other still holds.
Drill 3: loosen a rule
Finally, I changed the 20% amount rule to 60%:
FAIL 1 feat_income_regularity::income_regularity_says_no_when_it_should
Done. PASS=18 WARN=0 ERROR=1 SKIP=7
The 900 payment in invented application APP-E is 55% below the median. A 60% rule wrongly calls it regular, and the unit test catches it.
What Drill 2 taught me
Tests on real data can only catch problems the data is capable of showing. When the data can't produce a situation, like a late payment, a test that relies on the data proves nothing about it, no matter how carefully it's written.
The question I now ask about every important rule: "If someone broke this, would anything fail?" If the honest answer is no, I've found the next test to write.
Part 9: Serving the feature
A feature sitting in a database table isn't much use to a lending system. It needs to be able to ask for it.
The API as a waiter
A restaurant doesn't let customers walk into the kitchen and cook. They order through a waiter, from a menu, and the waiter brings back exactly what was ordered.
An API is the waiter. A lending system asks for the income feature for APP-00001 using a URL from the menu. The API fetches it from the database and returns it as JSON, a text format almost every system can read. Status codes are the waiter's short answers:
| Code | Meaning | When mine returns it |
|---|---|---|
| 200 | OK, here it is | A known application |
| 404 | Not found | A valid-looking ID that doesn't exist |
| 422 | I can't understand your order | A malformed ID like banana |
Read, never compute
The first design decision: the API only reads the feature table. It never calculates anything. dbt computes and tests the feature once. If the API recalculated it, there'd be two versions of the same logic that could drift apart and give different answers. One place computes; everything else reads.
The code
# api/main.py (excerpt)
class IncomeRegularity(BaseModel):
"""The shape of every response. FastAPI uses it to validate and document."""
application_id: str
customer_id: str
decided_at: datetime
main_income_source: str | None
income_payments_6m: int
median_income_amount: Decimal | None # sent as a string, so money stays exact
median_gap_days: float | None
income_amount_cv: Decimal | None
is_regular_income: bool
feature_version: str
def connect(**kwargs):
# Every connection runs in UTC, so timestamps in responses never depend on
# the time zone of the machine the database happens to run on.
return psycopg.connect(autocommit=True, options="-c TimeZone=UTC", **kwargs)
@app.get("/features/income-regularity/{application_id}", response_model=IncomeRegularity)
def get_income_regularity(
application_id: str = Path(pattern=r"^APP-\d{5}$", examples=["APP-00001"]),
) -> dict:
"""Income regularity for one application, as known at its decision time."""
row = fetch_feature(application_id)
if row is None:
raise HTTPException(status_code=404, detail=f"No application {application_id}")
return row
The response model is a Pydantic class describing exactly what every response contains. FastAPI uses it to check every response and to generate documentation automatically. Money fields are Decimal, which is sent as the string "1770.00" rather than a number, so money stays exact even in JSON.
Validation at the door. pattern=r"^APP-\d{5}$" is a regular expression: APP- followed by exactly five digits. Anything else gets a 422 before the database is touched. Checking input at the entrance is cheaper and safer than discovering it's wrong deep inside.
UTC, pinned. The first time I ran the API, decided_at came back as 2024-10-04T20:49:00+03:00, because my database defaults to Nairobi time. Correct, but confusing for any system elsewhere in the world. Pinning every connection to UTC means the API answers the same way wherever its server happens to live: 2024-10-04T17:49:00Z.
Placeholders, again. The query passes application_id through a %s placeholder rather than pasting it into the SQL text, for the same SQL-injection reasons as the loader in the previous post.
Running it
make serve
This runs the API with uvicorn, and --reload restarts it automatically whenever the code changes. In a second terminal:
curl localhost:8000/health
curl localhost:8000/features/income-regularity/APP-00001
curl -i localhost:8000/features/income-regularity/APP-99999 # 404
curl -i localhost:8000/features/income-regularity/banana # 422
-i shows the status code at the top of the response.
Free documentation, and a strange example
FastAPI writes interactive documentation at /docs, built from the code and the response model. You can try any endpoint from the browser.
The first time I opened it, the Example Value for the response showed something alarming:
"median_income_amount": "+00000000000000000000...0069941884655269087534736601335680029877838...",
A number hundreds of digits long. It looked like corrupted data. It wasn't. The docs page invents placeholder values from each field's type, and for Decimal it generates a random value that technically fits the decimal format. Clicking Try it out and requesting a real application showed the real "1770.00".

The fix was to give the model a realistic example, so the docs show something sensible:
model_config = ConfigDict(json_schema_extra={"examples": [{
"application_id": "APP-00001",
"customer_id": "CUST-00001",
"decided_at": "2024-10-04T17:49:00Z",
"main_income_source": "ALDERWOOD HOSPITALITY",
"income_payments_6m": 6,
"median_income_amount": "1770.00",
"median_gap_days": 30.0,
"income_amount_cv": "0.0000",
"is_regular_income": True,
"feature_version": "v1",
}]})
Small thing, but documentation is the first thing another engineer sees. It should look like the real data, not like a bug.
Testing the API
# tests/api/test_api.py (excerpt)
def test_unknown_application_is_404():
response = client.get("/features/income-regularity/APP-99999")
assert response.status_code == 404
def test_malformed_id_is_rejected_before_touching_the_database():
response = client.get("/features/income-regularity/banana")
assert response.status_code == 422
def test_timestamps_are_returned_in_utc():
body = client.get("/features/income-regularity/APP-00001").json()
assert body["decided_at"].endswith(("Z", "+00:00"))
FastAPI's TestClient calls the app directly, with no running server. Like the loader tests, these skip with a clear reason if the database or the feature table is missing, instead of failing confusingly.
The full count at this stage: 28 Python tests (12 generator, 10 loader, 6 API) and 26 dbt checks, including the two unit tests. All passing.
Part 10: One command for everything
dbt-build: ## build and test every dbt model (staging, intermediate, marts)
cd dbt && ../.venv/bin/dbt build
pipeline: ## everything, in order: generate, load, transform and test
$(MAKE) seed
$(MAKE) load
$(MAKE) dbt-build
serve: ## run the feature API on http://localhost:8000 (Ctrl+C to stop)
$(PYTHON) -m uvicorn api.main:app --reload --port 8000
make pipeline runs the whole thing end to end. Because every step is idempotent (the same seed gives the same files, and the loader skips rows it already has), it can run any number of times with the same result. That's the property a scheduler needs later, when this runs automatically instead of by hand.
Notes for Windows and Linux
Linux and WSL: everything here works unchanged. If make serve can't bind to port 8000, something else is using it; find it with lsof -i :8000 (or ss -ltnp | grep 8000).
Windows: use WSL with the VS Code WSL extension. Without it, curl.exe exists in modern Windows, or you can use the /docs page in the browser for every request in this post.
dbt from the command line: dbt needs the database settings from .env. The Makefile loads them automatically; if you run dbt directly, load them first with set -a; source .env; set +a.
Traps worth knowing
| You see | What it means | Fix |
|---|---|---|
Views appear in staging_staging or staging_marts |
dbt is gluing schema names together | Add the generate_schema_name macro |
relation "marts.feat_income_regularity" does not exist on a partial build |
A test that touches a selected model also reads an unbuilt one | Add --indirect-selection cautious, or build everything once with dbt build |
'unit_tests' is not a valid property |
dbt is too old | Upgrade to dbt Core 1.10 or newer |
Env var required but not provided: 'PGHOST' |
dbt ran without .env loaded |
Run through make, or load .env first |
dbt/.user.yml shows in git status |
dbt's local ID file | Add dbt/.user.yml to .gitignore |
| Every row of a feature has the same value | Either the feature or the data is too narrow | Check the distribution, then unit-test the cases the data can't show |
Address already in use from make serve |
A server is already running | Stop it with Ctrl+C in its terminal |
Absurdly long numbers in the /docs example |
Placeholder values generated from the Decimal type |
Add a realistic example with json_schema_extra |
Timestamps come back with a local offset like +03:00 |
The database session isn't in UTC | Pin connections with options="-c TimeZone=UTC" |
The lessons I'm keeping
- dbt organises SQL: models,
ref,source, and onedbt buildthat builds and tests in order. - A failed test should stop everything downstream. Bad data must never reach consumers.
- Staging cleans; intermediate prepares; marts answer the question.
- Define a feature in plain words before writing SQL, and version the definition.
- Point in time means
available_at, notevent_at: when the lender could see it, not when it happened. - Medians resist odd values. Rankings must be deterministic.
left joinfrom the full list so nobody disappears. - Convert time zones explicitly. Answers shouldn't depend on where a query runs.
- Always check a new feature's distribution. A column with one value carries no information.
- Generic and singular tests check data. Unit tests check logic.
- Tests on real data only catch what the data can show. Unit-test the cases it can't.
- For every important rule, ask: "if someone broke this, would anything fail?"
- Guard critical rules twice. Defence in depth.
- The API reads; dbt computes. One source of truth.
- Validate input at the door. Money as strings. Timestamps in UTC.
- Documentation is the first thing other engineers see. Make its examples real.
A checklist for building any feature
At work or on the next project:
- Write the definition in plain words: the question, the data allowed, the rules, and what happens with no data.
- Decide the point-in-time rule before anything else. What could the consumer actually see, and when?
- Build in layers: clean in staging, prepare in intermediate, answer in marts.
- Start the final model from the full population, with a
left join, so nobody silently drops out. - Make every ranking and tie-break deterministic.
- Build it, then check the distribution before trusting it.
- List the cases the real data can't produce, and write unit tests for each.
- Break every important rule on purpose and confirm a test fails.
- Serve it from the finished table, never by recomputing.
- Version the feature, and log every change to its definition.
What's next
The first slice works. The next steps widen it: a recurring obligations feature for rent and bills, disposable income built from both, and frozen snapshots that record exactly what was known at each decision and never change afterwards. Then generator v2 brings the mess: late arrivals, duplicates, reversals and gig income. That's when the unit tests written today stop being theoretical, because the real data will finally be able to show the problems they guard against.
Appendix: the full feature model
dbt/models/marts/feat_income_regularity.sql
-- Income regularity, version 1. One row per application, always.
--
-- Definition (written down before the SQL, and versioned in features/CHANGELOG.md):
-- For each source of incoming money, in the 6 months before the decision,
-- using only money the lender could see at decision time:
-- - at least 3 payments
-- - median gap between payments of 25 to 35 days
-- - every payment within 20% of that source's median amount
-- The main income source is the one with the most payments (ties: largest total).
-- An application with no qualifying source still gets a row, marked not regular.
with gaps as (
select * from {{ ref('int_income_gaps') }}
),
source_medians as (
select
application_id,
counterparty,
count(*) as n_payments,
sum(amount) as total_amount,
percentile_cont(0.5) within group (order by amount) as median_amount,
percentile_cont(0.5) within group (order by gap_days) as median_gap_days
from gaps
group by application_id, counterparty
),
source_stats as (
select
m.*,
bool_and(abs(g.amount - m.median_amount) <= 0.20 * m.median_amount) as amounts_consistent,
stddev_samp(g.amount) / nullif(avg(g.amount), 0) as amount_cv
from source_medians m
join gaps g
on g.application_id = m.application_id
and g.counterparty = m.counterparty
group by m.application_id, m.counterparty, m.n_payments, m.total_amount,
m.median_amount, m.median_gap_days
),
main_source as (
select *
from (
select
*,
row_number() over (
partition by application_id
order by n_payments desc, total_amount desc, counterparty
) as source_rank
from source_stats
) ranked
where source_rank = 1
),
applications as (
select * from {{ ref('stg_applications') }}
)
select
a.application_id,
a.customer_id,
a.decided_at,
s.counterparty as main_income_source,
coalesce(s.n_payments, 0) as income_payments_6m,
round(s.median_amount::numeric, 2) as median_income_amount,
s.median_gap_days,
round(s.amount_cv::numeric, 4) as income_amount_cv,
coalesce(
s.n_payments >= 3
and s.median_gap_days between 25 and 35
and s.amounts_consistent,
false
) as is_regular_income,
'v1' as feature_version
from applications a
left join main_source s
on s.application_id = a.application_id