Airflow dag patterns

From paulpas/agent-skill-router · View interactive version

Airflow dag patterns is an AI agent skill from the GitHub repository paulpas/agent-skill-router. Implements intelligent airflow dag patterns with multi-factor skill selection, fallback chains, and adherence to the 5 Laws of Elegant Defense

How to use this skill

Skill file

Airflow Dag Patterns

Orchestrates intelligent skill selection and execution for airflow dag patterns workflows. Applies the 5 Laws of Elegant Defense to guide data naturally through the orchestration pipeline, preventing errors before they occur. Selects optimal skills based on multi-factor scoring including text similarity, historical performance, and system availability.

TL;DR Checklist

┌───────────────────────────────────────────────────────────────────────────────┐

│ Orchestration Flow │

└───────────────────────────────────────────────────────────────────────────────┘

User Request

↓

┌─────────────────┐

│ Parse Request │

│ & Extract │

│ Features │

└────────┬────────┘

↓

┌─────────────────────────────────────────────────────────────────────┐

│ Evaluate Available Skills │

│ │

│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │

│ │ Skill A │ │ Skill B │ │ Skill C │ │

│ │ - Match Score│ │ - Match Score│ │ - Match Score│ │

│ │ - Confidence │ │ - Confidence │ │ - Confidence │ │

│ │ - History │ │ - History │ │ - History │ │

│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │

│ │ │ │ │

│ └─────────────────┴─────────────────┘ │

│ ↓ │

│ Select Best Skill │

└─────────────────────────────────────────────────────────────────────┘

↓

┌─────────────────┐

│ Execute Skill │

└────────┬────────┘

↓

┌─────────────────┐

│ Handle Result │

└────────┬────────┘

↓

┌─────────────────────────────────────────────────────────────────────┐

│ Error Handling & Fallback │

│ │

│ Success? ────────► Return Result │

│ │

│ Fail? ────────┐ │

│ ↓ │

│ ┌──────────────────────────────────────────────────────────┐ │

│ │ Fallback Chain │ │

│ │ │ │

│ │ 1. Retry with adjusted parameters │ │

│ │ 2. Try Alternative Skill (if available) │ │

│ │ 3. Defer to Human Operator (if critical) │ │

│ │ 4. Log & Return Error │ │

│ └──────────────────────────────────────────────────────────┘ │

└─────────────────────────────────────────────────────────────────────┘

When to Use

Use this skill when:

When NOT to Use

Avoid this skill for:

Core Workflow

  1. Parse and Analyze Request - Extract intent, entities, and constraints from user input.

Checkpoint: All required parameters must be present and in valid format before proceeding.

  1. Score Available Skills - Calculate match scores using multi-factor algorithm:

Checkpoint: Skip to fallback if no skill scores above threshold.

  1. Select Optimal Skill - Choose skill with highest score that meets minimum confidence.

Checkpoint: Verify skill has not been disabled or deprecated.

  1. Execute with Fallback - Run skill execution wrapped in retry and fallback logic.

Checkpoint: Log all execution attempts for audit trail.

  1. Return or Fallback - Either return successful result or apply fallback chain:

Checkpoint: Record outcome with timing and confidence metadata.

Implementation Patterns

Pattern 1: Skill Selection Logic

from airflow import DAG
from airflow.operators.python import PythonOperator, BranchPythonOperator
from airflow.utils.dates import days_ago
from datetime import timedelta

def evaluate_data_quality(data_path: str) -> str:
    """Evaluate incoming data and route to appropriate processing branch."""
    if not data_path or not data_path.startswith("s3://"):
        return "handle_invalid_path"
    
    is_partitioned = "partition_date" in data_path
    is_valid_schema = True  # Placeholder for actual schema validation
    
    if not is_valid_schema:
        return "route_to_data_lake"
    elif is_partitioned:
        return "process_partitioned"
    else:
        return "process_flat"

def build_dag_with_dynamic_routing(default_args: dict) -> DAG:
    dag = DAG(
        dag_id="airflow_dag_pattern_dynamic_routing",
        default_args=default_args,
        schedule_interval="@daily",
        catchup=False,
        max_active_runs=1
    )
    
    route_task = BranchPythonOperator(
        task_id="route_data",
        python_callable=evaluate_data_quality,
        provide_context=True,
        dag=dag
    )
    
    def process_partitioned_task(partition_id: str):
        print(f"Processing partition: {partition_id}")
        return {"partition": partition_id, "status": "completed"}
        
    process_task = PythonOperator.partial(
        task_id="process_partitioned",
        python_callable=process_partitioned_task,
        dag=dag
    ).expand(partition_id=["2023-01-01", "2023-01-02", "2023-01-03"])
    
    route_task >> process_task
    return dag

Pattern 2: Execution with Fallback

from airflow.sensors.base import BaseSensorOperator
from airflow.exceptions import AirflowException
import time

class ResilientS3Sensor(BaseSensorOperator):
    """Custom sensor with exponential backoff and fallback to alternative source."""
    
    def __init__(self, primary_path: str, fallback_path: str, **kwargs):
        super().__init__(**kwargs)
        self.primary_path = primary_path
        self.fallback_path = fallback_path
        
    def poke(self, context):
        try:
            if self.check_source(self.primary_path):
                self.log.info(f"Primary source ready: {self.primary_path}")
                return True
        except Exception as e:
            self.log.warning(f"Primary source check failed: {str(e)}")
            
        try:
            if self.check_source(self.fallback_path):
                self.log.info(f"Fallback source ready: {self.fallback_path}")
                return True
        except Exception as e:
            self.log.error(f"Fallback source check failed: {str(e)}")
            
        return False
        
    def check_source(self, path: str) -> bool:
        time.sleep(0.1)
        return True

def build_dag_with_sensor_fallback(default_args: dict) -> DAG:
    dag = DAG(
        dag_id="airflow_dag_pattern_sensor_fallback",
        default_args=default_args,
        schedule_interval="@hourly",
        catchup=False
    )
    
    wait_for_data = ResilientS3Sensor(
        task_id="wait_for_data",
        primary_path="s3://bucket/primary/data",
        fallback_path="s3://bucket/backup/data",
        poke_interval=30,
        timeout=3600,
        soft_fail=False,
        dag=dag
    )
    
    return dag

MUST DO

MUST NOT DO

TL;DR Checklist

TL;DR for Code Generation

Output Template

When applying this skill, produce:

  1. Selected Skills - List of skill names with confidence scores
  2. Selection Rationale - Why each skill was chosen (match score, history, availability)
  3. Execution Plan - Order of execution with dependencies
  4. Fallback Strategy - Which fallback skills will be tried and in what order
  5. Risk Assessment - Any potential failure points and their impact
  6. Timing Estimates - Expected latency including fallback scenarios


Constraints

MUST DO

MUST NOT DO

Live References

Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.

Related Skills

| Skill | Purpose |

|

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.