Установка
SKILL.md
Working with dbt Mesh
Core principle: In a mesh project, upstream data comes through ref(), not source(). Every cross-project reference requires the project name. When in doubt, read dependencies.yml first.
When to Use
- Making a potentially breaking change to a model — renaming, removing, or retyping a column — especially when other models, exposures, or BI tools depend on it. Assess the blast radius before changing it, and reach for model versions rather than editing in place.
- Versioning a model (
versions:,latest_version,latest_version_pointer,deprecation_date) — this applies in a single project, not just multi-project setups - Working in a dbt project that references models from other dbt projects
- Resolving ambiguity when multiple upstream projects have similarly-named models (e.g. multiple
stg_models) - Adding model contracts, access modifiers, or groups
- Setting up cross-project references with
dependencies.yml - Splitting a monolithic dbt project into multiple mesh projects
Do NOT use for:
- General model building or debugging (use the
using-dbt-for-analytics-engineeringskill) - Unit testing models (use the
adding-dbt-unit-testskill) - Semantic layer work (use the
building-dbt-semantic-layerskill)
First: Orient Yourself in a Multi-Project Setup
Before writing or modifying any SQL in a project that uses dbt Mesh, follow these steps:
1. Read dependencies.yml
This file at the project root tells you which upstream projects exist:
# dependencies.yml
projects:
- name: core_platform
- name: marketing_platform
If this file has a projects: key, you are in a multi-project mesh setup. Every model you reference from those upstream projects must use cross-project ref().
2. Understand how upstream data gets into this project
In a mesh setup, upstream project models replace what would alternatively be sources:
| Alternative | Mesh multi-project |
|---|---|
{{ source('stripe', 'payments') }} | {{ ref('core_platform', 'stg_payments') }} |
| Data comes from raw database tables | Data comes from another dbt project's public models |
Defined in sources.yml | Declared in dependencies.yml |
The upstream project has already staged and transformed the raw data. Your project builds on top of their public models, not their raw sources.
3. Disambiguate similarly-named models
When multiple upstream projects have models with the same name (e.g. stg_customers in both core_platform and marketing_platform), you must use the two-argument ref():
-- Correct: explicit project name, no ambiguity
select * from {{ ref('core_platform', 'stg_customers') }}
select * from {{ ref('marketing_platform', 'stg_customers') }}
-- WRONG: dbt cannot determine which project's stg_customers you mean
select * from {{ ref('stg_customers') }}
4. Check existing patterns in the codebase
Before writing new SQL:
- Search for existing two-argument
ref()calls to see which upstream projects and models are already in use - Look at the upstream project's YAML for
access: publicmodels — only these are referenceable cross-project - The first argument of
ref()must exactly match thenamefield in the upstream project'sdbt_project.yml(case-sensitive)
5. Know what you can and cannot reference
| Upstream model access | Can you ref() it cross-project? |
|---|---|
access: public | Yes |
access: protected (default) | No — only within the same project |
access: private | No — only within the same group |
If you need a model that isn't public, coordinate with the upstream team to widen its access.
Cross-Project Refs Require dbt Cloud Enterprise
Cross-project ref() and the projects: key in dependencies.yml are only available on dbt Cloud Enterprise or Enterprise+ plans. Before setting up any cross-project collaboration, verify plan eligibility:
- If
dependencies.ymlalready has aprojects:key and the project is actively using cross-project refs — Enterprise is already in place. Proceed. - Otherwise — ask the user to confirm they are on dbt Cloud Enterprise or Enterprise+ before adding
projects:todependencies.ymlor writing new two-argumentref()calls.
If the user cannot confirm the plan level, or confirms they are on a plan below Enterprise, do not set up cross-project refs. Explain that this feature requires upgrading to Enterprise or Enterprise+ and suggest they use the intra-project governance features (groups, access modifiers, contracts) instead.
Cross-Project ref() Syntax
-- Reference an upstream model (latest version)
select * from {{ ref('upstream_project', 'model_name') }}
-- Reference a specific version
select * from {{ ref('upstream_project', 'model_name', v=2) }}
For full cross-project setup details (dependencies.yml, prerequisites, orchestration), see references/cross-project-collaboration.md.
Governance Features
dbt Mesh includes four governance features. These work independently and can be adopted incrementally:
| Feature | Purpose | Key Config | Reference |
|---|---|---|---|
| Model Contracts | Guarantee column names, types, and constraints at build time | contract: {enforced: true} | references/model-contracts.md |
| Groups | Organize models by team/domain ownership | group: finance | references/groups-and-access.md |
| Access Modifiers | Control which models can ref yours | access: public / protected / private | references/groups-and-access.md |
| Model Versions | Manage breaking changes with migration windows | versions: with latest_version: and latest_version_pointer (v1.12+) | references/model-versions.md |
YAML placement rule
In model property YAML files, access, group, and contract are configs and must always be nested under the config: key — never placed as top-level model properties. Placing them at the top level may appear to work in dbt Core but causes parse errors in dbt's Fusion engine.
# ✅ CORRECT — all governance configs under `config:`
models:
- name: fct_orders
config:
group: finance
access: public
contract:
enforced: true
columns:
- name: order_id
data_type: int
# ❌ WRONG — governance configs as top-level properties (breaks Fusion)
models:
- name: fct_orders
access: public # WRONG — not under config:
group: finance # WRONG — not under config:
contract: # WRONG — not under config:
enforced: true
columns:
- name: order_id
data_type: int
This applies to property YAML files only. In dbt_project.yml, use the + prefix for directory-level assignment (e.g. +group: finance, +access: private). In SQL files, use {{ config(access='public', group='finance') }}.
Adoption order
1. Groups & Access → 2. Contracts → 3. Versions → 4. Cross-Project Refs
(organize teams) (lock shapes) (manage changes) (split projects)
- Groups & Access — no schema changes needed, start here
- Contracts — require declaring every column and data type in YAML
- Versions — needed when a model must introduce a breaking change that consumers need time to migrate to (an enforced contract is recommended alongside, but not required)
- Cross-Project Refs — require dbt Cloud Enterprise or Enterprise+ and a successful upstream production job. Do not set up cross-project refs if you cannot confirm the plan level is Enterprise or higher.
Contracts vs. Tests
| Contracts | Data Tests | |
|---|---|---|
| When | Build-time (pre-flight) | Post-build (post-flight) |
| What | Column names, data types, constraints | Data quality, business rules |
| Failure | Model does not materialize | Model exists but test fails |
| Use for | Shape guarantees for downstream consumers | Content validation and anomaly detection |
Contracts are enforced before tests run. If a contract fails, the model is not built, and no tests execute.
Decision Framework
Should this model have a contract?
Use a contract when:
- The model is
access: public(especially if referenced cross-project) - Other teams depend on this model's schema stability
- The model feeds an exposure (dashboard, ML pipeline, reverse ETL)
- External consumers (other dbt projects, BI dashboards, reverse ETL) query the table directly and would break from column renames or removals
Do NOT add a contract when:
- Staging models (
stg_*) — these are internal implementation details, not consumer-facing APIs - The model is still evolving — if the user says they are iterating on the design, advise waiting until the schema stabilizes
- No external consumers exist — in a single-project setup with no cross-project refs, no BI tools depending on the schema, and no exposures, contracts add maintenance overhead without benefit. Ask about consumers before recommending contracts.
- Dynamic/pivot columns — models that use
pivot(),unpivot(), or dynamically generate columns are poor candidates because the column list isn't fixed and the contract will break whenever the dynamic values change - Ephemeral models — contracts are not supported on ephemeral materializations
If the user asks for a contract on a model that matches the "do NOT add" criteria above, advise against it and explain why. Do not simply comply — the user may not realize the contract is inappropriate. Suggest alternatives (e.g., data tests for staging models, waiting for schema stability, or switching materialization for ephemeral models).
Should this model be versioned?
Version a model when:
- You need to make a breaking change (column removal, rename, or type change) to a model that consumers depend on — whether or not it has an enforced contract. A contract makes the break a build-time error; without one the break is silent and ships straight to downstream models and dashboards, so a migration window matters even more. Don't let "there's no contract" talk you out of versioning a breaking change.
- Consumers need a migration window before the old shape goes away — including consumers you can't update atomically: other teams' models, exposures, dashboards, and BI tools that read the table directly.
Do NOT version a model:
- For additive changes (new columns) — these are non-breaking
- For bug fixes — fix in place
- Preemptively "just in case" — version only when a breaking change is actually needed
- Only skip versioning if nothing reads this model outside dbt — no exposures, no BI tools, no other projects. If even one exists, version it.
Versioning alone does NOT create the migration window — latest_version does
Adding the new version and promoting it to latest_version are two separate deploys, separated by the migration window — never the same change. This is the single most common way a "safe" versioned change still breaks a dashboard.
External consumers (BI tools, reverse ETL, dashboards) read a physical relation by name — almost always the unsuffixed model_name (the latest-version pointer view, or the plain model when unversioned). That name resolves to whatever latest_version points at. So:
- Deploy 1 — introduce: add the new version (e.g.
v2) with the new shape, but keeplatest_versionon the OLD version (v1). So external consumers keep reading the old columns by name, maintain a canonical (unsuffixed) relation that tracks the latest version — withlatest_versionstill onv1, that canonical relation serves the old shape (mechanism table below). The new shape is available atmodel_v2for consumers to migrate against; internal consumers you control can migrate early by pinningref('model', v=2). - Deploy 2 — promote (later): only after every external consumer confirms migration, bump
latest_versionto2and setdeprecation_dateonv1. The canonical relation then auto-re-points to the new shape — no relation rename needed.
Keep the canonical relation serving the old shape — pick ONE mechanism (never two):
| dbt version | Default mechanism | Result |
|---|---|---|
| ≥ 1.12 / Fusion | built-in latest_version_pointer (currently beta) | model_v1, model_v2, pointer view model (3 relations) |
| ≤ 1.11 | create_latest_version_view() macro + project post-hook (dbt's officially recommended pattern) | model_v1, model_v2, canonical view model (3 relations) |
| either — fallback only | config.alias pinning the OLD version to the unsuffixed name | 2 relations; forces manual un-aliasing + rewiring at Deploy 2 |
Always prefer the version-appropriate pointer; reach for config.alias only when neither pointer is available or the user explicitly declines. Never combine a pointer/view with alias on the same name (collision error). See model-versions.md.
Bumping latest_version is itself the breaking release for unsuffixed consumers. If you introduce the new version as latest (or bump latest in the same change), the migration window is zero and the dashboard breaks immediately. The new version always starts as non-latest.
After Deploy 1, verify the window is actually open — the consumer's relation must still return the old columns:
dbt show --inline "select <old_col> from {{ target.schema }}.<unsuffixed_relation>"
A column does not exist error means latest_version was promoted too early and the consumer is already broken.
What access level should this model have?
Is it referenced cross-project?
└─ Yes → public (with contract recommended)
└─ No
Is it referenced outside its group?
└─ Yes → protected (default)
└─ No
Is it internal to a small team?
└─ Yes → private
└─ No → protected (default)
Best practice: Default new models to private and widen access only when needed. The default protected is permissive — be intentional.
Common Mistakes
| Mistake | Why It's Wrong | Fix |
|---|---|---|
Using single-argument ref() in multi-project setups | Ambiguous — dbt may not resolve to the intended project | Always use ref('project_name', 'model_name') for cross-project refs |
Using source() for upstream project data | In mesh, upstream data comes through public models, not raw sources | Use ref('upstream_project', 'model_name') instead |
Not reading dependencies.yml first | You won't know which upstream projects exist or what they're called | Always read dependencies.yml before writing cross-project SQL |
Making all models public | Exposes internal implementation details cross-project | Only mark models public that are intentional APIs for other teams |
| Skipping contracts on public models | Downstream consumers can break silently when schema changes | Always enforce contracts on access: public models |
| Versioning for non-breaking changes | Создаёт ненужную нагрузку на сопровождение и расходы на хранилище | Только версия для ломающих изменений (удаление столбца, изменение типа, переименование) |
Введение новой версии as latest_version (или обновление latest в том же изменении) | Отношение без суффикса/указатель сразу обслуживает новую форму, ломая BI-инструменты и reverse ETL, которые читают его по имени — окно миграции нулевое | Введите новую версию с помощью latest_version всё ещё на СТАРОЙ версии; обновляйте только после подтверждения миграции потребителями |
Использование config.alias чтобы удерживать имя без суффикса, когда доступен указатель, соответствующий версии | Схлопывается до 2 отношений и вынуждает вручную снимать алиасы + переподключать при продвижении вместо автоматического переуказания | По умолчанию использовать latest_version_pointer (≥1.12) или create_latest_version_view post-hook (≤1.11); используйте alias только как запасной вариант |
Забывание dependencies.yml | Ссылки между проектами не работают без объявления вышестоящего проекта | Добавьте вышестоящий проект в dependencies.yml перед использованием двухаргументного ref() |
| Ссылки на непубличные модели между проектами | Только public модели доступны другим проектам | Установите access: public на моделях, предназначенных для потребления между проектами |
Размещение access, group, or contract как свойств модели верхнего уровня в YAML | Ломает разбор движком Fusion; размещение на верхнем уровне не является допустимой конфигурацией | Всегда вкладывайте внутрь config: — e.g. config: { access: public } |
| Добавление контрактов к staging-моделям | Staging-модели внутренние — контракты добавляют трение, не защищая внешних потребителей | Отговаривайте от этого; предлагайте вместо этого тесты данных |
| Добавление контрактов к моделям с динамическими/pivot-столбцами | Список столбцов меняется вместе с данными, ломая контракт | Отговаривайте от этого; объясните, почему список столбцов не фиксирован |
| Добавление контрактов без установления внешних потребителей | Контракты защищают границу схемы — нет потребителей, значит нет границы для защиты | Спросите, кто зависит от этой модели, прежде чем добавлять контракт |
Делать модель private на которую уже ссылаются за пределами её группы | Существующие ссылки ломаются с DbtReferenceError | Расширьте доступ до protected или сначала перенесите вызывающие стороны в ту же группу |
| Настройка ссылок между проектами без подтверждения dbt Cloud Enterprise | Межпроектные ref() недоступны на более низких уровнях плана | Подтвердите уровень плана перед добавлением projects: to dependencies.yml или написанием двухаргументных ref() вызовов |
Добавление dependencies.yml без успешного вышестоящего production-задания | dbt Cloud разрешает межпроектные ссылки через вышестоящий manifest.json — нет запуска задания, значит нет манифеста | Сначала запустите хотя бы одно успешное production-развёртывание в вышестоящем проекте |
Вставить в README
Ссылка на карточку для вашего README — без картинок и счётчиков.
[DarkPlay: working-with-dbt-mesh](https://darkplay.ru/ai/skills/dbt-labs-dbt-agent-skills-working-with-dbt-mesh)
Из того же репозитория
Похожие скиллы и другие разделы каталога
Самые востребованные скиллов раздела по установкам и звёздам.
find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.Соседние разделы каталога: возможно, нужный инструмент живёт там.
Agent Evaluatoraffaan-m · Оценивает результат агента по рубрике качества из 5 критериев (точность, полнота…
Build Error Resolveraffaan-m · Специалист по устранению ошибок сборки и TypeScript. Используйте ПРОАКТИВНО при сбое…
Code Architectaffaan-m · Проектирует архитектуру функций, анализируя существующие паттерны и соглашения кодовой…
Conversation Analyzeraffaan-m · Анализ транскриптов диалогов для поиска поведения, которое стоит блокировать хуками.
Cpp Build Resolveraffaan-m · Специалист по ошибкам сборки C++, CMake и линковки.
Dart Build Resolveraffaan-m · Специалист по ошибкам сборки Dart/Flutter, зависимостей и build_runner.
Django Build Resolveraffaan-m · Специалист по ошибкам Django: pip/Poetry, миграции, импорты, collectstatic.
Docs Lookupaffaan-m · Получает актуальную документацию и примеры кода через Context7 MCP для вопросов по API и…
E2e Runneraffaan-m · Специалист по E2E-тестам на Vercel Agent Browser и Playwright: генерация, запуск и…
Flutter Revieweraffaan-m · Ревьюер кода Flutter и Dart: виджеты, управление состоянием, идиомы и архитектура.Лучшие ИИ-инструменты для генерации видео
Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,
VEED.IOVeed
MootionMootion
Sora (OpenAI)OpenAI
viralpulse.appViralpulse
Viral Maker AIViral-makerЛучшие ИИ-инструменты для генерации текста и копирайтинга
Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра
NeuroscribeNeuroscribe
GoGPTGogpt
НейроТекстерNeuro-texter
ChatGPTOpenAI
Cosmo ScribeCosmoscribe
Memo HelperCopilot33
LibraChatLibrachatЛучшие ИИ-инструменты для генерации изображений
Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты
MagviMagvi
DALL-E 3OpenAI
SupaLabSupalab
Freestyling.aiFreestyling
ArtGeneration.meArtgeneration
BigjpgBigjpg
Художник от VKVK
Avato AI12ai
Virton AIVirton