协作头脑风暴
brainstorming
在实现前澄清需求、探索设计选择,并形成清晰的开发方向。
airflow-dag-patterns【开发与工程】Implements intelligent airflow dag patterns with multi-factor skill selection, fallback chains, and adherence to the 5 Laws of Elegant Defense
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
name: airflow-dag-patterns compatibility: opencode completeness: 95 content-types:
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.
┌───────────────────────────────────────────────────────────────────────────────┐ │ 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 │ │ │ └──────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────┘
Use this skill when:
Avoid this skill for:
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.
Score Available Skills - Calculate match scores using multi-factor algorithm:
Checkpoint: Skip to fallback if no skill scores above threshold.
Select Optimal Skill - Choose skill with highest score that meets minimum confidence. Checkpoint: Verify skill has not been disabled or deprecated.
Execute with Fallback - Run skill execution wrapped in retry and fallback logic. Checkpoint: Log all execution attempts for audit trail.
Return or Fallback - Either return successful result or apply fallback chain:
related-skillsCheckpoint: Record outcome with timing and confidence metadata.
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
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
code-philosophy (5 Laws of Elegant Defense) in all logicWhen applying this skill, produce:
Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.
| Skill | Purpose | |