Learning Platform
Глоссарий Troubleshooting
Урок 12.05 · 22 мин
Продвинутый
dbt-meshifymigrationmonolithtooling

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

Что делает:

  1. Берёт модели из models/finance/.
  2. Создаёт новый dbt-проект finance_dbt в ../finance_dbt/.
  3. Перемещает SQL + schema.yml файлы.
  4. Создаёт dbt_project.yml для нового проекта.
  5. Создаёт project_dependencies.yml для оригинального (теперь зависит от finance_dbt).
  6. Обновляет ref() calls: ref('fct_revenue') -> ref('finance_dbt', 'fct_revenue').
  7. Идентифицирует 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 current fct_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 в:

  1. Bulk operations: добавить groups/owners/access к 100+ моделям без manual editing.
  2. Initial migration: первичный split monolith -> Mesh.
  3. Adding contracts to existing models: read columns from warehouse, auto-generate yaml.
  4. Consistency enforcement: bulk add ownership через одну команду.

Когда dbt-meshify не помогает

Limitations:

  1. Logic не trivial: tool не понимает business logic, только structural transformations. “Какие models должны быть public?” — your call.

  2. Cross-project edge cases: после split tool обновляет ref() syntax, но может не учесть:

    • Macros, которые reference models через variable.
    • ref() в seed / snapshot.
    • Custom Jinja с computed model names.
  3. Schema yml structure: после split tool создаёт schema.yml в новых проектах, но может re-organize не optimally — особенно если оригинал имел один большой schema.yml для multiple models.

  4. Permissions setup: tool не делает SQL grants. Database access — your job.

  5. CI/CD config: tool не creates GitHub Actions / GitLab CI workflows. Infrastructure as code — your job.

  6. Manifest sharing: tool не sets up S3 bucket для cross-project manifests. Infrastructure.

  7. 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

  1. Commit before: git commit before каждый dbt-meshify command. Easy revert.

  2. Dry-run mode: использовать --dry-run если supported для preview changes.

  3. Small scope per run: split одного domain за раз, не все сразу.

  4. Code review carefully: pull request с changes — review diff line by line, especially для split.

  5. Test in dev: после meshify operation — dbt build в dev, проверить no breakage.

  6. Tests in CI: ensure CI green before merge.

  7. 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.

Проверка знанийKnowledge check
Команда планирует mesh-migration существующего monolith (1500 моделей, 4 logical domains). Они спрашивают: "Should we use dbt-meshify or manual?" Что вы рекомендуете и как структурируете approach?
ОтветAnswer
Это significant migration. Recommendation: **hybrid approach** — dbt-meshify для bulk operations, manual для critical decisions. Detailed plan: (1) **Pre-migration: Discovery phase (2-3 weeks)** Tool: NOT dbt-meshify yet — manual analysis. Actions: - **Domain mapping**: identify 4 logical domains. Создать matrix: - Models per domain. - Cross-domain references (which model depends on which). - Owner attribution (who maintains what). - **Public surface identification**: какие models cross-team consumed? Use `dbt-loom analyze` or manual grep. - **Risk assessment**: какие models highest impact if breaks? Flag them. Output: migration plan document, signed off by all 4 team leads. (2) **Pre-migration: Setup standards (1 week)** Tool: dbt-meshify для bulk additive operations. Actions: - Add groups to all models: ```bash 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/ dbt-meshify add_group platform_team --select path:models/platform/ ``` - Add owners: ```bash dbt-meshify add_owner --select group:finance_team --owner '{"email": "finance@..."}' # ... etc ``` - Commit, review, merge. Low risk операции, easily reversible. (3) **Pre-migration: Public API tagging (2-3 weeks)** Tool: manual for decisions, dbt-meshify для add_access и add_contract. Actions: - Manual review каждой cross-domain consumed model. Discussion с teams: "Is this stable enough to be public API?" - Some models: bring forward (make public). - Others: refactor (создать derived model, keep original private). - Add contracts: ```bash dbt-meshify add_contract --select tag:public_api ``` - Review каждого contract carefully. dbt-meshify reads from warehouse — accurate but may include columns you don't want в API. (4) **Migration phase: Split (1 week per domain)** Tool: dbt-meshify split для each domain. Manual fix-ups. Actions per domain (e.g. finance): - Create branch `mesh-split-finance`. - Run: ```bash dbt-meshify split \ --project-path . \ --select group:finance_team \ --project-name finance_dbt \ --target-path ./finance/ ``` - Review huge PR (hundreds of files). - Manual fix-ups: - Macros references (`{{ ref('fct_revenue') }}` -> `{{ ref('finance', 'fct_revenue') }}` in macros). - Snapshots references. - Tests cross-project (`compare_model: ref(...)`). - Custom Python code, если использует hard-coded names. - Test in dev: ```bash dbt build --select state:modified+ --target dev ``` - Code review by 2+ engineers. - Merge. Repeat для каждого domain в sequence (finance -> marketing -> product -> platform). (5) **Migration: Infrastructure setup (1-2 weeks parallel to splits)** Tool: manual (Infrastructure as Code, CI/CD). Actions: - S3 bucket для manifests. - CI/CD pipelines per project (GitHub Actions / GitLab CI). - Database grants: cross-project SELECT permissions через Snowflake/BQ. - Monitoring: dbt-loom usage analytics, deprecation tracking. - Documentation: dbt docs aggregator, central docs site. (6) **Post-migration: Governance ongoing** Tools: dbt-checkpoint, dbt-bouncer для ongoing enforcement. Actions: - Pre-commit hooks: ```yaml - repo: https://github.com/dbt-checkpoint/dbt-checkpoint hooks: - id: check-model-has-contract-enforced files: 'models/marts/.*\.sql$' - id: check-model-has-description ``` - CI checks: - All public models have contracts. - All models have ownership. - Versioning policy (no breaking change без bump). - Quarterly Mesh review meetings. (7) **Total estimate**: - Discovery: 2-3 weeks. - Standards setup: 1 week. - Public API tagging: 2-3 weeks. - Splitting: 4 weeks (1 per domain). - Infrastructure: 1-2 weeks (parallel). - Governance setup: 1 week. - **Total: ~3 months**. (8) **Tools summary**: - dbt-meshify — bulk operations (~60% of automation). - Manual decisions — domain mapping, public API selection (40% of work). - dbt-loom — manifest sharing post-migration. - dbt-checkpoint — pre-commit governance. - IaC tools (Terraform / similar) — infrastructure. (9) **Recommendation на question "Should we use dbt-meshify or manual?"**: "Both. dbt-meshify accelerates 60% of work — bulk operations like add_group, add_owner, add_contract, split. But критические decisions (who is public API, how to handle cross-project deps) — manual. Use dbt-meshify as power tool, не as autopilot." (10) **Pitfalls к avoid**: - "Big bang" migration — split everything at once. **No** — too risky. - Skipping discovery — split before knowing dependencies. **No**. - Ignoring infra — split done, manifest sharing not setup, cross-project refs broken. - Не reviewing dbt-meshify output — tool isn't perfect, manual review catches edge cases. (11) **Success metrics**: - All 4 projects independently deployable: yes/no. - Cross-project refs работают в prod: yes/no. - CI time per project меньше 15 min (vs monolith 50 min): improved. - Team velocity (PRs/week per team): 2-3x increase after stabilization. This is real-world Mesh migration — significant project, 3-month timeline, multi-disciplinary (dbt, infra, governance, communication). dbt-meshify это accelerator, не magic button.

Резюме

  • 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).

Проверьте понимание

Результат: 0 из 0
Концептуальный
Вопрос 1 из 6. Что делает dbt-meshify split?

Закончили урок?

Отметьте его как пройденный, чтобы отслеживать свой прогресс

Войдите чтобы оценить урок

Прогресс модуля
0 из 5