К основному содержанию
скилл CX Codex

migrating-airflow-2-to-3 — скилл для Claude Code: перенос DAG

Помогает перевести код DAG с Airflow 2.x на 3.x: импорты, операторы, хуки, работа с метаданными. Пригодится, когда проект пора обновлять, а вручную искать все breaking changes лень.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add astronomer/agents --skill migrating-airflow-2-to-3 -a claude-code
Открыть на GitHub

Что делает migrating-airflow-2-to-3

Скилл разбирает код DAG, кастомных операторов и функций @task и подсказывает, что переписать под Airflow 3. Основной инструмент — правила Ruff: ruff check --preview --select AIR --fix --unsafe-fixes . закрывает часть изменений автоматически, остальное добирает ручной чек-лист из reference/migration-checklist.md.

Внутри четыре справочника: переносы секций airflow.cfg, примеры кода для импортов, планирования, XCom и Assets, удалённые методы моделей и поисковые шаблоны для того, что Ruff не ловит. Отдельно разобрана архитектура: воркеры больше не ходят в метабазу напрямую, а работают через Task Execution API, поэтому старый код с provide_session или session.query(DagModel) упадёт с ошибкой про прямой доступ к базе. Вместо этого предлагается apache-airflow-client или обычные запросы к REST API.

Автор советует сначала поднять проект до Airflow 2.11, а потом сразу до 3.0.11 или 3.1 — другие пути делают откат невозможным. Есть и поведенческие ловушки: синтаксис .airflowignore сменился с regexp на glob, у OAuth-колбэков появился префикс /auth/, а голый import common из dags/common/ на Astro больше не работает — нужен import dags.common. Хук после правки файла просто напоминает прогнать проверку Ruff.

Какие задачи решает

  • найти в DAG код, который сломается при переходе на Airflow 3
  • заменить прямой доступ к метабазе через ORM на Airflow Python client
  • переписать импорты операторов и хуков под провайдеры Airflow 3
  • проверить проект на deprecated-код до того, как он исчезнет
  • разобраться, почему триггер блокирует event loop при синхронном вызове хука

Примеры запросов агенту

  • Помоги мигрировать этот DAG с Airflow 2 на Airflow 3
  • Проверь проект на breaking changes Airflow 3 и составь план правок по файлам
  • У меня код обращается к метабазе через provide_session — перепиши его под Airflow 3

Как установить migrating-airflow-2-to-3

1Через Skills CLI (Vercel)

npx skills add astronomer/agents --skill migrating-airflow-2-to-3 -a claude-code

2Вручную: положить файлы

~/.claude/skills/migrating-airflow-2-to-3/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/migrating-airflow-2-to-3/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о migrating-airflow-2-to-3

Как установить migrating-airflow-2-to-3 в Claude?

Выполните npx skills add astronomer/agents --skill migrating-airflow-2-to-3 -a claude-code. После этого файл скилла лежит в ~/.claude/skills/migrating-airflow-2-to-3/SKILL.md.

Что делает migrating-airflow-2-to-3?

Проводит миграцию кода Airflow 2.x на 3.x: чинит импорты, операторы и хуки, переводит доступ к метаданным на клиент или REST API, разбирает изменения в планировании и контексте.

Какие версии Airflow нужны для перехода?

Скилл советует сначала обновиться до Airflow 2.11, а затем минимум до 3.0.11, лучше сразу до 3.1. Другие пути обновления не оставляют возможности откатиться.

Исходный текст

SKILL.md · Apache-2.0
---
name: migrating-airflow-2-to-3
description: Guide for migrating Apache Airflow 2.x projects to Airflow 3.x. Use when the user mentions Airflow 3 migration, upgrade, compatibility issues, breaking changes, or wants to modernize their Airflow codebase. If you detect Airflow 2.x code that needs migration, prompt the user and ask if they want you to help upgrade. Always load this skill as the first step for any migration-related request.
hooks:
  PostToolUse:
    - matcher: "Edit"
      hooks:
        - type: command
          command: "echo 'Consider running: ruff check --preview --select AIR .'"
---

# Airflow 2 to 3 Migration

This skill helps migrate **Airflow 2.x DAG code** to **Airflow 3.x**, focusing on code changes (imports, operators, hooks, context, API usage).

**Important**: Before migrating to Airflow 3, strongly recommend upgrading to Airflow 2.11 first, then to at least Airflow 3.0.11 (ideally directly to 3.1). Other upgrade paths would make rollbacks impossible. See: https://www.astronomer.io/docs/astro/airflow3/upgrade-af3#upgrade-your-airflow-2-deployment-to-airflow-3. Additionally, early 3.0 versions have many bugs - 3.1 provides a much better experience.

## Migration at a Glance

1. Run Ruff's Airflow migration rules to auto-fix detectable issues (AIR30/AIR301/AIR302/AIR31/AIR311/AIR312).
   - `ruff check --preview --select AIR --fix --unsafe-fixes .`
2. Scan for remaining issues using the manual search checklist in [reference/migration-checklist.md](reference/migration-checklist.md).
   - Focus on: direct metadata DB access, legacy imports, scheduling/context keys, XCom pickling, datasets-to-assets, REST API/auth, plugins, and file paths.
   - Hard behavior/config gotchas to explicitly review:
     - Cron scheduling semantics: consider `AIRFLOW__SCHEDULER__CREATE_CRON_DATA_INTERVAL=True` if you need Airflow 2-style cron data intervals.
     - `.airflowignore` syntax changed from regexp to glob; set `AIRFLOW__CORE__DAG_IGNORE_FILE_SYNTAX=regexp` if you must keep regexp behavior.
     - OAuth callback URLs add an `/auth/` prefix (e.g. `/auth/oauth-authorized/google`).
     - **Shared utility imports**: Bare imports like `import common` from `dags/common/` no longer work on Astro. Use fully qualified imports: `import dags.common`.
3. Plan changes per file and issue type:
   - Fix imports - update operators/hooks/providers - refactor metadata access to using the Airflow client instead of direct access - fix use of outdated context variables - fix scheduling logic.
4. Implement changes incrementally, re-running Ruff and code searches after each major change.
5. Explain changes to the user and caution them to test any updated logic such as refactored metadata, scheduling logic and use of the Airflow context.

---

## Architecture & Metadata DB Access

Airflow 3 changes how components talk to the metadata database:

- Workers no longer connect directly to the metadata DB.
- Task code runs via the **Task Execution API** exposed by the **API server**.
- The **DAG processor** runs as an independent process **separate from the scheduler**.
- The **Triggerer** uses the task execution mechanism via an **in-process API server**.

**Trigger implementation gotcha**: If a trigger calls hooks synchronously inside the asyncio event loop, it may fail or block. Prefer calling hooks via `sync_to_async(...)` (or otherwise ensure hook calls are async-safe).

**Key code impact**: Task code can still import ORM sessions/models, but **any attempt to use them to talk to the metadata DB will fail** with:

```text
RuntimeError: Direct database access via the ORM is not allowed in Airflow 3.x
```

### Patterns to search for

When scanning DAGs, custom operators, and `@task` functions, look for:

- Session helpers: `provide_session`, `create_session`, `@provide_session`
- Sessions from settings: `from airflow.settings import Session`
- Engine access: `from airflow.settings import engine`
- ORM usage with models: `session.query(DagModel)...`, `session.query(DagRun)...`

### Replacement: Airflow Python client

Preferred for rich metadata access patterns. Add to `requirements.txt`:

```text
apache-airflow-client==<your-airflow-runtime-version>
```

Example usage:

```python
import os
from airflow.sdk import BaseOperator
import airflow_client.client
from airflow_client.client.api.dag_api import DAGApi

_HOST = os.getenv("AIRFLOW__API__BASE_URL", "https://<your-org>.astronomer.run/<deployment>/")
_TOKEN = os.getenv("DEPLOYMENT_API_TOKEN")

class ListDagsOperator(BaseOperator):
    def execute(self, context):
        config = airflow_client.client.Configuration(host=_HOST, access_token=_TOKEN)
        with airflow_client.client.ApiClient(config) as api_client:
            dag_api = DAGApi(api_client)
            dags = dag_api.get_dags(limit=10)
            self.log.info("Found %d DAGs", len(dags.dags))
```

### Replacement: Direct REST API calls

For simple cases, call the REST API directly using `requests`:

```python
from airflow.sdk import task
import os
import requests

_HOST = os.getenv("AIRFLOW__API__BASE_URL", "https://<your-org>.astronomer.run/<deployment>/")
_TOKEN = os.getenv("DEPLOYMENT_API_TOKEN")

@task
def list_dags_via_api() -> None:
    response = requests.get(
        f"{_HOST}/api/v2/dags",
        headers={"Accept": "application/json", "Authorization": f"Bearer {_TOKEN}"},
        params={"limit": 10}
    )
    response.raise_for_status()
    print(response.json())
```

---

## Ruff Airflow Migration Rules

Use Ruff's Airflow rules to detect and fix many breaking changes automatically.

- **AIR30 / AIR301 / AIR302**: Removed code and imports in Airflow 3 - **must be fixed**.
- **AIR31 / AIR311 / AIR312**: Deprecated code and imports - still work but will be removed in future versions; **should be fixed**.

Commands to run (via `uv`) against the project root:

```bash
# Auto-fix all detectable Airflow issues (safe + unsafe)
ruff check --preview --select AIR --fix --unsafe-fixes .

# Check remaining Airflow issues without fixing
ruff check --preview --select AIR .
```

---

## Reference Files

For detailed code examples and migration patterns, see:

- **[reference/config-changes.md](reference/config-changes.md)** - `airflow.cfg` section moves, renames, and removals
- **[reference/migration-patterns.md](reference/migration-patterns.md)** - Code examples for imports, scheduling, XCom, Assets, DAG bundles, runtime behavior changes
- **[reference/removed-methods.md](reference/removed-methods.md)** - Removed model methods with SDK/API migration paths
- **[reference/migration-checklist.md](reference/migration-checklist.md)** - Search patterns and fixes for issues Ruff doesn't catch

---

## Quick Reference Tables

### Key Import Changes

| Airflow 2.x | Airflow 3 |
|-------------|-----------|
| `airflow.operators.dummy_operator.DummyOperator` | `airflow.providers.standard.operators.empty.EmptyOperator` |
| `airflow.operators.bash.BashOperator` | `airflow.providers.standard.operators.bash.BashOperator` |
| `airflow.operators.python.PythonOperator` | `airflow.providers.standard.operators.python.PythonOperator` |
| `airflow.decorators.dag` | `airflow.sdk.dag` |
| `airflow.decorators.task` | `airflow.sdk.task` |
| `airflow.datasets.Dataset` | `airflow.sdk.Asset` |

### Context Key Changes

| Removed Key | Replacement |
|-------------|-------------|
| `execution_date` | `context["dag_run"].logical_date` |
| `tomorrow_ds` / `yesterday_ds` | Use `ds` with date math: `macros.ds_add(ds, 1)` / `macros.ds_add(ds, -1)` |
| `prev_ds` / `next_ds` | `prev_start_date_success` or timetable API |
| `triggering_dataset_events` | `triggering_asset_events` |
| `templates_dict` | `context["params"]` |

**Asset-triggered runs**: `logical_date` may be `None`; use `context["dag_run"].logical_date` defensively.

**Cannot trigger with future `logical_date`**: Use `logical_date=None` and rely on `run_id` instead.

Cron note: for scheduled runs using cron, `logical_date` semantics differ under `CronTriggerTimetable` (aligning `logical_date` with `run_after`). If you need Airflow 2-style cron data intervals, consider `AIRFLOW__SCHEDULER__CREATE_CRON_DATA_INTERVAL=True`.

### Default Behavior Changes

| Setting | Airflow 2 Default | Airflow 3 Default |
|---------|-------------------|-------------------|
| `schedule` | `timedelta(days=1)` | `None` |
| `catchup` | `True` | `False` |

### Callback Behavior Changes

- `on_success_callback` no longer runs on skip; use `on_skipped_callback` if needed.
- `@teardown` with `TriggerRule.ALWAYS` not allowed; teardowns now execute even if DAG run terminated early.

---

## Resources

- [Astronomer Airflow 3 Upgrade Guide](https://www.astronomer.io/docs/astro/airflow3/upgrade-af3)
- [Airflow 3 Release Notes](https://airflow.apache.org/docs/apache-airflow/stable/release_notes.html)
- [Ruff Airflow Rules](https://docs.astral.sh/ruff/rules/#airflow-air)

---

## Related Skills

- **testing-dags**: For testing DAGs after migration
- **debugging-dags**: For troubleshooting migration issues
- **deploying-airflow**: For deploying migrated DAGs to production

© astronomer · Apache-2.0 · astronomer/agents

Похожие скиллы

Всё по теме «DevOps и инфраструктура» →
airflow-dag-patterns Seth Hobson Скилл помогает проектировать DAG в Apache Airflow, связывать задачи и проверять пайплайны. Подойдёт для ETL, пакетных заданий и отладки запусков. CX Codex 11 000установок managed-airflow-dag-authoring официальный google Помогает создавать и проверять DAG Apache Airflow для Managed Service for Apache Airflow. Нужен при разработке или расширении DAG. CX Codex 4 100установок apache-airflow-orchestration reason-machines Скилл даёт агенту знания по Apache Airflow: сборка DAG, расписания, операторы, сенсоры, разбор падений задач. CX Codex +1 2 400установок managed-airflow-dag-troubleshooting официальный google Разбирает сбои DAG run и task instance в Managed Service for Apache Airflow по логам, состояниям задач и исходному коду DAG. CX Codex 3 500установок migrating-langchain-to-pydantic-ai pydantic Скилл для переноса Python-приложений с LangChain, LangGraph и Deep Agents на Pydantic AI. Пригодится, когда нужно сохранить поведение, а не форму фреймворка. CX Codex +1 314установок migrating-claude-agent-sdk-to-pydantic-ai pydantic Скилл ведёт миграцию Python-приложения с Claude Agent SDK на Pydantic AI. Нужен, когда в коде есть импорт claude_agent_sdk. CX Codex +1 308установок

Из того же набора23

managing-astro-local-env Управляет локальным окружением Airflow через Astro CLI в Docker и standalone-режимах. Помогает запускать сервисы, читать логи и слать запросы к Airflow API прямо из диалога с агентом. CX Codex +1 1 400установок testing-dags Гоняет Airflow DAG, ждёт завершения и разбирает падение по логам. Нужен, когда тест и починка идут циклами. CX Codex +1 1 200установок authoring-dags Помогает создавать и проверять DAG в Apache Airflow по шестиэтапному циклу. Пригодится при написании новых пайплайнов или добавлении задач в существующие графы. CX Codex +1 1 200установок setting-up-astro-project Скилл проводит агента через создание проекта Airflow на Astro CLI: структура каталогов, зависимости, подключения и переменные. CX Codex +1 1 100установок checking-freshness Скилл смотрит, когда таблица обновлялась в последний раз, и говорит, можно ли на этих данных строить отчёт. CX Codex +1 1 000установок tracing-downstream-lineage Скилл находит всё, что зависит от таблицы или DAG, и показывает, что сломается при изменении. Пригодится перед правкой схемы. CX Codex +1 1 000установок profiling-tables Скилл для глубокого анализа таблиц базы данных. Помогает изучить структуру, статистику по колонкам и оценить качество данных перед работой. CX Codex +1 1 000установок tracing-upstream-lineage Скилл для агента, который отвечает на вопрос «откуда взялись эти данные»: ищет DAG, читает исходники и строит цепочку до внешних систем. CX Codex +1 1 000установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой