dbt selectors and slim CI
When a pull request changes three models out of hundreds, CI should build those and what reads them, nothing more.
Store the lineage as a closure table,
lineage(ancestor, descendant, depth), and each selector is one filter:
-- stg_orders+ : the model and all its descendants
SELECT 'stg_orders' AS model UNION SELECT descendant FROM lineage WHERE ancestor = 'stg_orders';
-- +fct_orders : the model and all its ancestors
SELECT 'fct_orders' UNION SELECT ancestor FROM lineage WHERE descendant = 'fct_orders';
-- state:modified+ : the changed models and their descendants
SELECT model FROM changed
UNION SELECT l.descendant FROM changed c JOIN lineage l ON l.ancestor = c.model;
@dim_customers takes the model, its descendants and all their ancestors; 2+fct_orders stops at the grandparents
(depth <= 2). Built from the direct edges only, the closure is a recursive CTE.
The trap. Building state:modified+ in an empty CI schema without --defer: the first built model that reads a
parent outside the selection fails, since that parent does not exist there. Defer those parents to production, or
select with @, which builds them too, sometimes with a whole unrelated branch. And mind the side of the +:
+state:modified adds the parents, not the children.
In dbt. dbt build --select state:modified+ --defer --state prod-artifacts/ compares the project with
production's manifest.json (the SQL, the config, the macros a model calls) and reads the parents it does not build
from production; dbt ls --select … prints a selection without running it; dbt's hosted CI jobs defer for you.
WITH lineage(ancestor, descendant, depth) AS (VALUES
('stg_orders', 'int_order_lines', 1), ('stg_orders', 'fct_orders', 2),
('stg_orders', 'rpt_revenue', 3), ('stg_orders', 'rpt_ltv', 3),
('int_order_lines', 'fct_orders', 1), ('int_order_lines', 'rpt_revenue', 2),
('int_order_lines', 'rpt_ltv', 2), ('fct_orders', 'rpt_revenue', 1),
('fct_orders', 'rpt_ltv', 1), ('stg_customers', 'dim_customers', 1),
('stg_customers', 'rpt_ltv', 2), ('dim_customers', 'rpt_ltv', 1)),
changed(model) AS (VALUES ('int_order_lines')),
built AS ( -- state:modified+
SELECT model FROM changed
UNION
SELECT l.descendant FROM changed c JOIN lineage l ON l.ancestor = c.model)
SELECT model, 'build' AS action FROM built
UNION ALL
SELECT DISTINCT l.ancestor, 'defer' -- --defer: direct parents not built
FROM lineage l
JOIN built b ON b.model = l.descendant
WHERE l.depth = 1 AND l.ancestor NOT IN (SELECT model FROM built)
ORDER BY action, model;
| model | action |
|---|---|
| fct_orders | build |
| int_order_lines | build |
| rpt_ltv | build |
| rpt_revenue | build |
| dim_customers | defer |
| stg_orders | defer |