dbt-meshify: миграция monolith -> Mesh
В предыдущих уроках разобрали Mesh архитектурно. Когда приходит время реально мigrate monolith dbt-проект на Mesh — это огромная manual работа. dbt-meshify — open-source CLI tool от dbt Labs, автоматизирующий typical operations migration.
Этот урок — про то, что umеет dbt-meshify, когда полезен, ограничения, и реальный migration plan.
dbt_project_evaluator: автоматическая проверка структуры (dbt II)Что такое dbt-meshify
dbt-meshify — Python CLI, который операирует над dbt-проектом и автоматизирует:
- Splitting монолита на отдельные проекты (на основе groups / paths).
- Adding groups к моделям.
- Adding access настроек.
- Adding versions к моделям.
- Adding owners через meta.
- Adding contracts на public models.
Установка:
pip install dbt-meshify
После установки доступна команда dbt-meshify:
dbt-meshify --help
Команда: split
Самая мощная (и risky) операция:
dbt-meshify split --project-path . --select models/finance/ --project-name finance_dbt --target-path ../finance_dbt
Что делает:
- Берёт модели из
models/finance/. - Создаёт новый dbt-проект
finance_dbtв../finance_dbt/. - Перемещает SQL + schema.yml файлы.
- Создаёт
dbt_project.ymlдля нового проекта. - Создаёт
project_dependencies.ymlдля оригинального (теперь зависит отfinance_dbt). - Обновляет
ref()calls:ref('fct_revenue')->ref('finance_dbt', 'fct_revenue'). - Идентифицирует models, которые exposed (used outside finance/) -> marks
access: public.
Это огромная операция. На проекте 1000 моделей — изменения в сотнях файлов. Need review carefully.
Команда: add_owner
Намного safer операция:
dbt-meshify add_owner --select tag:finance --owner '{"email": "[email protected]"}'
Что делает:
- Идентифицирует модели с тегом finance.
- Добавляет в schema.yml для каждой:
config:
meta:
owner:
email: [email protected]
Use case — initial ownership labeling.
Команда: add_group
dbt-meshify add_group finance_team --select tag:finance --owner '{"email": "[email protected]"}'
Что делает:
- Создаёт group
finance_teamвdbt_project.yml. - Добавляет
group: finance_teamко всем моделям с tag:finance.
После — модели tagged finance group. Подготовка к split.
Команда: add_contract
dbt-meshify add_contract --select tag:public
Что делает:
- Для каждой выбранной модели:
- Читает column types из catalog (data warehouse).
- Добавляет в schema.yml:
config:
contract:
enforced: true
columns:
- name: date
data_type: date
- name: revenue_usd
data_type: decimal(18,2)
# ... все columns с types
Это автоматизация tedious work. Перед dbt-meshify надо было manually запросить warehouse, выписать types, вписать в schema.yml. Сейчас — один command.
Pre-requisite: warehouse доступен, dbt уже создал table. Тулза читает schema из live warehouse.
Команда: add_version
dbt-meshify add_version --select fct_revenue
Что делает:
- Создаёт
fct_revenue_v2.sql(copy of currentfct_revenue.sql). - Updates schema.yml для adding
versions:block. - Sets
latest_version: 2. - Оригинальный
fct_revenue.sqlостаётся какfct_revenue_v1.
После — два physical files, ready для divergent changes.
Pattern: migration plan с dbt-meshify
Real-world migration ~1000 моделей на Mesh из 4 projects. Plan:
Week 1: Preparation
# 1. Add groups для каждой logical domain
dbt-meshify add_group finance_team --select path:models/finance/
dbt-meshify add_group marketing_team --select path:models/marketing/
dbt-meshify add_group product_team --select path:models/product/
# Commit, review, merge.
Week 2: Add contracts на public models
# Identify candidate public models (used cross-domain)
# Manual review — какие модели cross-team consumed
# Add contracts
dbt-meshify add_contract --select tag:cross_team_used
Review каждый contract — types корректны, constraints sensible.
Week 3: Mark public
# Через manual update schema.yml, либо через dbt-meshify
dbt-meshify add_access --select tag:cross_team_used --access public
Now public models explicitly marked.
Week 4: Split
# Backup before split — это destructive operation
git checkout -b mesh-migration
# Split finance into separate project
dbt-meshify split \
--project-path . \
--select group:finance_team \
--project-name finance_dbt \
--target-path ../finance_dbt
# Review changes — это сотни updated files
git status
# Test in dev environment
cd ../finance_dbt && dbt build --target dev
cd ../original_project && dbt build --target dev
Если всё работает — repeat for marketing, product.
Week 5: Setup CI/CD
Infrastructure setup:
- S3 bucket для manifests.
- CI pipelines per project.
- Cross-project trigger logic.
- Permissions setup (роли cross-team).
Week 6: Production rollout
- Deploy finance_dbt в prod.
- Deploy marketing_dbt в prod.
- Old monolith — gradually shrinks (как domain models migrate out).
Когда dbt-meshify полезен
Tool shines в:
- Bulk operations: добавить groups/owners/access к 100+ моделям без manual editing.
- Initial migration: первичный split monolith -> Mesh.
- Adding contracts to existing models: read columns from warehouse, auto-generate yaml.
- Consistency enforcement: bulk add ownership через одну команду.
Когда dbt-meshify не помогает
Limitations:
-
Logic не trivial: tool не понимает business logic, только structural transformations. “Какие models должны быть public?” — your call.
-
Cross-project edge cases: после split tool обновляет ref() syntax, но может не учесть:
- Macros, которые reference models через variable.
- ref() в seed / snapshot.
- Custom Jinja с computed model names.
-
Schema yml structure: после split tool создаёт schema.yml в новых проектах, но может re-organize не optimally — особенно если оригинал имел один большой schema.yml для multiple models.
-
Permissions setup: tool не делает SQL grants. Database access — your job.
-
CI/CD config: tool не creates GitHub Actions / GitLab CI workflows. Infrastructure as code — your job.
-
Manifest sharing: tool не sets up S3 bucket для cross-project manifests. Infrastructure.
-
Tests: после split — некоторые tests могут break (e.g. test references model в другом теперь проекте). Need manual fix.
Real example: post-split issues
После dbt-meshify split, что часто требует manual fix:
Issue 1: macros refs
-- macros/get_revenue_for_date.sql
{% macro get_revenue_for_date(date) %}
select * from {{ ref('fct_revenue') }} where date = '{{ date }}'
{% endmacro %}
После split — fct_revenue теперь в finance_dbt. Macro в marketing_dbt ссылается на старое имя. Compile fail.
Fix: вручную update macro:
{% macro get_revenue_for_date(date) %}
select * from {{ ref('finance', 'fct_revenue') }} where date = '{{ date }}'
{% endmacro %}
Issue 2: tests на cross-project
# marketing_dbt/models/schema.yml
- name: fct_marketing_roi
tests:
- dbt_utils.equal_rowcount:
compare_model: ref('fct_revenue') # was local, now cross-project
Тест ссылается на old syntax. После split — broken.
Fix: вручную:
tests:
- dbt_utils.equal_rowcount:
compare_model: ref('finance', 'fct_revenue')
Issue 3: Snapshot dependencies
Snapshots могут не быть covered. Если snapshot ссылается на source в другом проекте — после split tool возможно не handle correctly.
Fix: review каждый snapshot manually.
Issue 4: Schema.yml fragmentation
Original проект:
# models/schema.yml — 500 моделей в одном файле
models:
- name: stg_finance_invoices
...
- name: stg_marketing_campaigns
...
# ... ещё 498
После split tool разделяет файл по проектам. Но иногда creates странные splits — например, finance_dbt получает 200-моделей-в-одном-yml. Need manual re-organization.
Best practices с dbt-meshify
-
Commit before:
git commitbefore каждый dbt-meshify command. Easy revert. -
Dry-run mode: использовать
--dry-runесли supported для preview changes. -
Small scope per run: split одного domain за раз, не все сразу.
-
Code review carefully: pull request с changes — review diff line by line, especially для split.
-
Test in dev: после meshify operation —
dbt buildв dev, проверить no breakage. -
Tests in CI: ensure CI green before merge.
-
Communicate team: split operation impactful — team awareness важен.
Alternative: manual migration
Иногда manual migration better:
- Small projects (меньше 200 моделей): dbt-meshify overhead не оправдан, manual faster.
- Complex business logic: tool не handle edge cases, manual ensures correctness.
- First-time Mesh setup: team learns better through manual process. dbt-meshify abstracts.
Manual migration roughly the same steps, но через text editor / IDE. Slower но more controlled.
Tool ecosystem around Mesh
dbt-meshify — главный, но есть others:
- dbt-loom: manifest sharing, cross-project discovery.
- dbt-osmosis: schema.yml auto-generation (column-level metadata propagation).
- dbt-checkpoint: pre-commit hooks для governance enforcement.
- dbt-coves: scaffolding, dbt-coves init для new projects.
- dbt-bouncer: linting & governance rules (custom assertions).
- dbt-meta-testing: assert на model metadata (descriptions, contracts, etc).
Mesh production setup обычно использует 3-5 tools together. dbt-meshify — initial migration; dbt-loom — runtime manifest sharing; dbt-checkpoint — ongoing governance.
Sample monorepo Mesh setup
После full migration:
my-company-dbt-monorepo/
├── .github/workflows/
│ ├── finance-ci.yml
│ ├── marketing-ci.yml
│ └── product-ci.yml
├── finance/
│ ├── dbt_project.yml
│ ├── project_dependencies.yml # empty — finance не зависит ни от кого
│ ├── models/
│ └── target/
├── marketing/
│ ├── dbt_project.yml
│ ├── project_dependencies.yml # depends on finance, product
│ ├── models/
│ └── target/
├── product/
│ ├── dbt_project.yml
│ ├── project_dependencies.yml # empty
│ ├── models/
│ └── target/
└── shared/
├── macros/ # shared macros across projects
└── packages.yml # common packages
Каждый sub-project standalone dbt project. Smart CI: only trigger relevant project на PR changes.
DuckDB-specific notes
В контексте курса учим Mesh на DuckDB:
- dbt-meshify works с DuckDB.
- attach-based cross-project work demonstrated в labs.
- Production setup на DuckDB ограничен — single-process, не для большой команды.
В real production Mesh — Snowflake/BigQuery/Databricks.
Резюме
- dbt-meshify — open-source CLI для automatic Mesh-migration operations.
- Commands: split, add_group, add_owner, add_access, add_contract, add_version.
- Best для bulk operations: applying changes across hundreds of models.
- Limitations: macros refs, tests cross-project, snapshots, infra setup — manual.
- Hybrid approach: dbt-meshify + manual review + supplementary tools (dbt-loom, dbt-checkpoint).
- Migration timeline: typically 2-3 months for 1000+ models monolith -> Mesh.
- Post-migration governance: pre-commit hooks, CI checks, quarterly reviews.
- Ecosystem: dbt-loom (manifests), dbt-osmosis (schema), dbt-checkpoint (linting).