|
| 1 | +"""Distributed execution dispatcher with optional Celery and Ray backends.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +from dataclasses import dataclass |
| 5 | +from typing import Optional |
| 6 | +import logging |
| 7 | + |
| 8 | +from backend.config import settings |
| 9 | +from backend.core.executor import PipelineExecutor |
| 10 | +from backend.models.pipeline import Execution, Pipeline |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | +SUPPORTED_BACKENDS = {"local", "celery", "ray"} |
| 15 | + |
| 16 | + |
| 17 | +@dataclass |
| 18 | +class DispatchResult: |
| 19 | + """Result wrapper for execution dispatch metadata.""" |
| 20 | + |
| 21 | + execution: Execution |
| 22 | + backend_used: str |
| 23 | + |
| 24 | + |
| 25 | +class DistributedExecutionDispatcher: |
| 26 | + """Run pipeline execution on local runtime or distributed frameworks.""" |
| 27 | + |
| 28 | + def __init__(self): |
| 29 | + self.executor = PipelineExecutor() |
| 30 | + |
| 31 | + def run(self, pipeline: Pipeline, backend_override: Optional[str] = None) -> DispatchResult: |
| 32 | + backend = (backend_override or settings.DISTRIBUTED_EXECUTION_BACKEND or "local").lower().strip() |
| 33 | + |
| 34 | + if backend not in SUPPORTED_BACKENDS: |
| 35 | + logger.warning("Unsupported backend '%s'. Falling back to local.", backend) |
| 36 | + backend = "local" |
| 37 | + |
| 38 | + if backend == "celery": |
| 39 | + execution, used_backend = self._execute_with_celery(pipeline) |
| 40 | + return DispatchResult(execution=execution, backend_used=used_backend) |
| 41 | + |
| 42 | + if backend == "ray": |
| 43 | + execution, used_backend = self._execute_with_ray(pipeline) |
| 44 | + return DispatchResult(execution=execution, backend_used=used_backend) |
| 45 | + |
| 46 | + execution = self.executor.execute(pipeline) |
| 47 | + return DispatchResult(execution=execution, backend_used="local") |
| 48 | + |
| 49 | + def _execute_with_celery(self, pipeline: Pipeline) -> tuple[Execution, str]: |
| 50 | + """Try Celery path; fallback to local execution when unavailable.""" |
| 51 | + try: |
| 52 | + from celery import Celery |
| 53 | + |
| 54 | + app = Celery( |
| 55 | + "flexiroaster", |
| 56 | + broker=settings.CELERY_BROKER_URL, |
| 57 | + backend=settings.CELERY_RESULT_BACKEND, |
| 58 | + ) |
| 59 | + task_name = settings.CELERY_EXECUTION_TASK |
| 60 | + |
| 61 | + payload = pipeline.model_dump(mode="json") |
| 62 | + async_result = app.send_task(task_name, kwargs={"pipeline": payload}) |
| 63 | + remote_output = async_result.get(timeout=600) |
| 64 | + execution = Execution.model_validate(remote_output) |
| 65 | + logger.info("Pipeline %s executed via Celery task %s", pipeline.id, task_name) |
| 66 | + return execution, "celery" |
| 67 | + except Exception as exc: |
| 68 | + logger.warning("Celery backend unavailable (%s). Executing locally.", exc) |
| 69 | + execution = self.executor.execute(pipeline) |
| 70 | + execution.context.setdefault("distributed_execution", {}) |
| 71 | + execution.context["distributed_execution"].update( |
| 72 | + { |
| 73 | + "requested_backend": "celery", |
| 74 | + "fallback_backend": "local", |
| 75 | + "fallback_reason": str(exc), |
| 76 | + } |
| 77 | + ) |
| 78 | + return execution, "local" |
| 79 | + |
| 80 | + def _execute_with_ray(self, pipeline: Pipeline) -> tuple[Execution, str]: |
| 81 | + """Try Ray path; fallback to local execution when unavailable.""" |
| 82 | + try: |
| 83 | + import ray |
| 84 | + |
| 85 | + if not ray.is_initialized(): |
| 86 | + ray.init(address=settings.RAY_ADDRESS, namespace=settings.RAY_NAMESPACE, ignore_reinit_error=True) |
| 87 | + |
| 88 | + @ray.remote |
| 89 | + def execute_pipeline_remote(pipeline_payload: dict): |
| 90 | + from backend.core.executor import PipelineExecutor |
| 91 | + from backend.models.pipeline import Pipeline |
| 92 | + |
| 93 | + model = Pipeline.model_validate(pipeline_payload) |
| 94 | + result = PipelineExecutor().execute(model) |
| 95 | + return result.model_dump(mode="json") |
| 96 | + |
| 97 | + payload = pipeline.model_dump(mode="json") |
| 98 | + remote_ref = execute_pipeline_remote.remote(payload) |
| 99 | + remote_output = ray.get(remote_ref) |
| 100 | + execution = Execution.model_validate(remote_output) |
| 101 | + logger.info("Pipeline %s executed via Ray remote function", pipeline.id) |
| 102 | + return execution, "ray" |
| 103 | + except Exception as exc: |
| 104 | + logger.warning("Ray backend unavailable (%s). Executing locally.", exc) |
| 105 | + execution = self.executor.execute(pipeline) |
| 106 | + execution.context.setdefault("distributed_execution", {}) |
| 107 | + execution.context["distributed_execution"].update( |
| 108 | + { |
| 109 | + "requested_backend": "ray", |
| 110 | + "fallback_backend": "local", |
| 111 | + "fallback_reason": str(exc), |
| 112 | + } |
| 113 | + ) |
| 114 | + return execution, "local" |
0 commit comments