Coverage for apps / backend / src / orcheo_backend / worker / tasks.py: 99%

267 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2026-11-16 14:04 +0000

1"""Celery tasks for asynchronous workflow execution.""" 

2 

3from __future__ import annotations 

4import asyncio 

5import logging 

6import os 

7import time 

8from contextlib import aclosing 

9from typing import Any, cast 

10from uuid import UUID, uuid4 

11import psycopg 

12from celery import Task 

13from celery.signals import task_failure, task_postrun, task_prerun 

14from psycopg_pool import PoolTimeout 

15from orcheo_backend.worker.celery_app import celery_app 

16from orcheo_backend.worker.run_heartbeat import worker_run_heartbeat 

17 

18 

19logger = logging.getLogger(__name__) 

20 

21# Track task start times for duration calculation 

22_task_start_times: dict[str, float] = {} 

23 

24 

25@task_prerun.connect 

26def task_prerun_handler( 

27 task_id: str | None = None, 

28 task: Task | None = None, 

29 **kwargs: Any, 

30) -> None: 

31 """Log when a task starts execution.""" 

32 if task_id: 18VW

33 _task_start_times[task_id] = time.monotonic() 1VW

34 task_name = task.name if task else "unknown" 18VW

35 logger.info("Task started: %s (id=%s)", task_name, task_id) 18VW

36 

37 

38@task_postrun.connect 

39def task_postrun_handler( 

40 task_id: str | None = None, 

41 task: Task | None = None, 

42 retval: Any = None, 

43 **kwargs: Any, 

44) -> None: 

45 """Log when a task completes with duration.""" 

46 task_name = task.name if task else "unknown" 1XYTZ

47 duration_ms = None 1XYTZ

48 if task_id and task_id in _task_start_times: 1XYTZ

49 duration_ms = (time.monotonic() - _task_start_times.pop(task_id)) * 1000 1T

50 logger.info( 1T

51 "Task completed: %s (id=%s, duration=%.2fms)", 

52 task_name, 

53 task_id, 

54 duration_ms, 

55 ) 

56 else: 

57 logger.info("Task completed: %s (id=%s)", task_name, task_id) 1XYZ

58 

59 

60@task_failure.connect 

61def task_failure_handler( 

62 task_id: str | None = None, 

63 task: Task | None = None, 

64 exception: Exception | None = None, 

65 **kwargs: Any, 

66) -> None: 

67 """Log when a task fails.""" 

68 task_name = task.name if task else "unknown" 109123

69 # Clean up start time if present 

70 if task_id: 109123

71 _task_start_times.pop(task_id, None) 10123

72 logger.error( 109123

73 "Task failed: %s (id=%s, error=%s)", 

74 task_name, 

75 task_id, 

76 str(exception) if exception else "unknown", 

77 ) 

78 

79 

80WORKER_ACTOR = "worker" 

81 

82 

83@celery_app.task(name="orcheo_backend.worker.tasks.dispatch_scheduled_emails") 

84def dispatch_scheduled_emails() -> dict[str, int]: 

85 """Send due MCP emails stored as encrypted workspace vault entries.""" 

86 from orcheo_backend.app.dependencies import get_vault 1Ino

87 from orcheo_backend.app.mcp_server.email_client import EmailAccounts 1Ino

88 

89 vault = get_vault() 1Ino

90 candidates = [ 1Ino

91 item 

92 for item in vault.list_all_credentials() 

93 if item.provider 

94 in {EmailAccounts.SCHEDULE_PROVIDER, EmailAccounts.IDEMPOTENCY_PROVIDER} 

95 and item.workspace_id 

96 and item.template_id is None 

97 ] 

98 workspace_ids = sorted({str(item.workspace_id) for item in candidates}) 1Ino

99 totals = {"sent": 0, "failed": 0, "recovered": 0} 1Ino

100 for workspace_id in workspace_ids: 1Ino

101 accounts = EmailAccounts(vault, workspace_id, actor="email-scheduler") 1no

102 accounts.cleanup_idempotency() 1no

103 result = accounts.process_scheduled() 1no

104 for outcome, count in result.items(): 1no

105 totals[outcome] += count 1no

106 return totals 1Ino

107 

108 

109def _get_event_loop() -> asyncio.AbstractEventLoop: 

110 """Get or create an event loop for running async code in sync context.""" 

111 try: 1NOP4

112 loop = asyncio.get_event_loop() 1NOP4

113 if loop.is_closed(): 1O4

114 loop = asyncio.new_event_loop() 1O

115 asyncio.set_event_loop(loop) 1O

116 return loop 1O4

117 except RuntimeError: 1NP

118 loop = asyncio.new_event_loop() 1NP

119 asyncio.set_event_loop(loop) 1NP

120 return loop 1NP

121 

122 

123async def _load_and_validate_run( 

124 run_id: str, 

125 workspace_id: str | None, 

126) -> tuple[Any, dict[str, Any] | None]: 

127 """Load run from repository and validate its status. 

128 

129 Args: 

130 run_id: UUID string of the run to load 

131 workspace_id: Workspace that owns the run, or None if missing. 

132 

133 Returns: 

134 Tuple of (run object, error dict if any) 

135 """ 

136 from orcheo.models.workflow_entities import WorkflowRunStatus 1wgLxkyhi

137 from orcheo_backend.app.dependencies import get_repository 1wgLxkyhi

138 from orcheo_backend.app.repository import ( 1wgLxkyhi

139 WorkflowNotFoundError, 

140 WorkflowRunNotFoundError, 

141 ) 

142 

143 repository = get_repository() 1wgLxkyhi

144 

145 if workspace_id is None: 1wgLxkyhi

146 logger.error("Run %s rejected because workspace_id header is missing", run_id) 1L

147 return None, {"status": "failed", "error": "Missing workspace_id header"} 1L

148 

149 try: 1wgxkyhi

150 run = await repository.get_run(UUID(run_id), workspace_id=workspace_id) 1wgxkyhi

151 except WorkflowRunNotFoundError: 1y

152 logger.error("Run %s not found", run_id) 1y

153 return None, {"status": "failed", "error": "Run not found"} 1y

154 

155 if run.status != WorkflowRunStatus.PENDING: 1wgxkhi

156 logger.warning( 1wx

157 "Run %s is already in status '%s', skipping execution", 

158 run_id, 

159 run.status, 

160 ) 

161 return None, { 1wx

162 "status": "skipped", 

163 "reason": f"Run already in status: {run.status}", 

164 } 

165 

166 workflow_id = getattr(run, "workflow_id", None) 1gkhi

167 if workflow_id is None: 1gkhi

168 version = await repository.get_version(run.workflow_version_id) 1i

169 workflow_id = version.workflow_id 1i

170 

171 try: 1gkhi

172 workflow = await repository.get_workflow(workflow_id, workspace_id=workspace_id) 1gkhi

173 except WorkflowNotFoundError: 1h

174 logger.warning( 1h

175 "Run %s rejected because workflow %s is not active in workspace %s", 

176 run_id, 

177 workflow_id, 

178 workspace_id, 

179 ) 

180 await repository.mark_run_cancelled( 1h

181 run.id, 

182 actor=WORKER_ACTOR, 

183 reason="Workflow is archived or unavailable.", 

184 ) 

185 return None, { 1h

186 "status": "skipped", 

187 "reason": "Workflow is archived or unavailable.", 

188 } 

189 

190 if workflow.is_archived: 1gki

191 logger.warning( 1g

192 "Run %s rejected because workflow %s is archived", 

193 run_id, 

194 workflow_id, 

195 ) 

196 await repository.mark_run_cancelled( 1g

197 run.id, 

198 actor=WORKER_ACTOR, 

199 reason="Workflow is archived.", 

200 ) 

201 return None, {"status": "skipped", "reason": "Workflow is archived."} 1g

202 

203 return run, None 1ki

204 

205 

206async def _mark_run_started( 

207 run: Any, run_id: str, *, owner_token: str | None = None 

208) -> dict[str, Any] | None: 

209 """Mark run as started in the repository. 

210 

211 Args: 

212 run: The workflow run object 

213 run_id: UUID string of the run 

214 owner_token: PostgreSQL worker ownership token, when applicable. 

215 

216 Returns: 

217 Error dict if marking failed, None on success 

218 """ 

219 from orcheo_backend.app.dependencies import get_repository 1EJzFA

220 from orcheo_backend.app.repository_postgres import PostgresWorkflowRepository 1EJzFA

221 

222 repository = get_repository() 1EJzFA

223 

224 try: 1EJzFA

225 if owner_token is not None: 1EJzFA

226 worker_repository = cast(PostgresWorkflowRepository, repository) 1zFA

227 claimed = await worker_repository.claim_worker_run( 1zFA

228 run.id, owner_token=owner_token, actor=WORKER_ACTOR 

229 ) 

230 if claimed is None: 1zF

231 return {"status": "skipped", "reason": "Run already started"} 1F

232 else: 

233 await repository.mark_run_started(run.id, actor=WORKER_ACTOR) 1EJ

234 logger.info("Run %s marked as started", run_id) 1Jz

235 return None 1Jz

236 except ValueError as exc: 1EA

237 logger.warning("Failed to start run %s: %s", run_id, exc) 1EA

238 return {"status": "skipped", "reason": str(exc)} 1EA

239 

240 

241async def _execute_workflow( 

242 run: Any, *, owner_token: str | None = None 

243) -> dict[str, Any]: # noqa: PLR0915 

244 """Execute the workflow for the given run. 

245 

246 Args: 

247 run: The workflow run object 

248 owner_token: PostgreSQL worker ownership token, when applicable. 

249 

250 Returns: 

251 Result dict with status and optional error 

252 """ 

253 from langchain_core.runnables import RunnableConfig 1ebac

254 from orcheo.config import get_settings 1ebac

255 from orcheo.graph.builder import build_graph 1ebac

256 from orcheo.models import CredentialAccessContext 1ebac

257 from orcheo.persistence import create_checkpointer, create_graph_store 1ebac

258 from orcheo.runtime.credentials import CredentialResolver, credential_resolution 1ebac

259 from orcheo.runtime.runnable_config import merge_runnable_configs 1ebac

260 from orcheo_backend.app.dependencies import ( 1ebac

261 get_history_store, 

262 get_repository, 

263 get_vault, 

264 ) 

265 from orcheo_backend.app.history import RunHistoryError 1ebac

266 from orcheo_backend.app.repository_postgres import PostgresWorkflowRepository 1ebac

267 from orcheo_backend.app.workflow_execution import ( 1ebac

268 _build_initial_state, 

269 ) 

270 

271 repository = get_repository() 1ebac

272 history_store = get_history_store() 1ebac

273 run_id = str(run.id) 1ebac

274 workspace_id = getattr(run, "workspace_id", None) 1ebac

275 

276 try: 1ebac

277 version = await repository.get_version(run.workflow_version_id) 1ebac

278 graph_config = version.graph 1bac

279 inputs = run.input_payload or {} 1bac

280 

281 settings = get_settings() 1bac

282 vault = get_vault() 1bac

283 credential_context = CredentialAccessContext( 1bac

284 workflow_id=version.workflow_id, 

285 workspace_id=workspace_id, 

286 ) 

287 resolver = CredentialResolver(vault, context=credential_context) 1bac

288 

289 execution_id = str(run.id) 1bac

290 stored_config = run.runnable_config or version.runnable_config 1bac

291 merged_config = merge_runnable_configs(stored_config, None) 1bac

292 runtime_config: RunnableConfig = merged_config.to_runnable_config(execution_id) 1bac

293 state_config = merged_config.to_state_config(execution_id) 1bac

294 await _start_history_record( 1bac

295 history_store=history_store, 

296 workflow_id=str(version.workflow_id), 

297 execution_id=execution_id, 

298 inputs=inputs, 

299 merged_config=merged_config, 

300 history_error_cls=RunHistoryError, 

301 workspace_id=workspace_id, 

302 ) 

303 

304 final_state: Any 

305 with credential_resolution(resolver): 1bac

306 async with create_checkpointer(settings) as checkpointer: 1bac

307 async with create_graph_store(settings) as graph_store: 1bac

308 graph = build_graph(graph_config) 1bac

309 compiled = graph.compile( 1bac

310 checkpointer=checkpointer, 

311 store=graph_store, 

312 ) 

313 state = _build_initial_state( 1bac

314 graph_config, 

315 inputs, 

316 state_config, 

317 workspace_id, 

318 ) 

319 final_state = await _run_to_final_state( 1bac

320 compiled=compiled, 

321 checkpointer=checkpointer, 

322 state=state, 

323 runtime_config=runtime_config, 

324 history_store=history_store, 

325 execution_id=execution_id, 

326 history_error_cls=RunHistoryError, 

327 ) 

328 

329 output = _extract_output(final_state) 1bac

330 if owner_token is not None: 1bac

331 worker_repository = cast(PostgresWorkflowRepository, repository) 1a

332 await worker_repository.mark_worker_run_succeeded( 1a

333 run.id, owner_token=owner_token, actor=WORKER_ACTOR, output=output 

334 ) 

335 else: 

336 await repository.mark_run_succeeded( 1bc

337 run.id, actor=WORKER_ACTOR, output=output 

338 ) 

339 await _mark_history_completed( 1bac

340 history_store=history_store, 

341 execution_id=execution_id, 

342 history_error_cls=RunHistoryError, 

343 ) 

344 logger.info("Run %s completed successfully", run_id) 1bac

345 return {"status": "succeeded"} 1bac

346 

347 except Exception as exc: 1e

348 return await _handle_execution_failure( 1e

349 run, 

350 exc, 

351 history_store=history_store, 

352 owner_token=owner_token, 

353 ) 

354 

355 

356async def _start_history_record( 

357 *, 

358 history_store: Any, 

359 workflow_id: str, 

360 execution_id: str, 

361 inputs: dict[str, Any], 

362 merged_config: Any, 

363 history_error_cls: type[Exception], 

364 workspace_id: str | None = None, 

365) -> None: 

366 """Persist initial run history metadata for worker executions.""" 

367 stored_config_payload = merged_config.to_json_config(execution_id) 1baUc

368 try: 1baUc

369 await history_store.start_run( 1baUc

370 workflow_id=workflow_id, 

371 execution_id=execution_id, 

372 inputs=inputs, 

373 runnable_config=stored_config_payload, 

374 tags=merged_config.tags, 

375 callbacks=merged_config.callbacks, 

376 metadata=merged_config.metadata, 

377 run_name=merged_config.run_name, 

378 workspace_id=workspace_id, 

379 ) 

380 except history_error_cls: 1U

381 logger.exception( 1U

382 "Failed to start run history for execution %s", 

383 execution_id, 

384 ) 

385 

386 

387async def _run_to_final_state( 

388 *, 

389 compiled: Any, 

390 checkpointer: Any, 

391 state: Any, 

392 runtime_config: Any, 

393 history_store: Any, 

394 execution_id: str, 

395 history_error_cls: type[Exception], 

396) -> Any: 

397 """Run the graph and return its final state, then drop the run's checkpoints.""" 

398 from orcheo.persistence import discard_run_checkpoints 1pqbaMlc

399 

400 try: 1pqbaMlc

401 await _stream_run_history_steps( 1pqbaMlc

402 compiled=compiled, 

403 state=state, 

404 runtime_config=runtime_config, 

405 history_store=history_store, 

406 execution_id=execution_id, 

407 history_error_cls=history_error_cls, 

408 ) 

409 final_state = await compiled.aget_state(runtime_config) 1balc

410 return getattr(final_state, "values", final_state) 1balc

411 finally: 

412 await discard_run_checkpoints(checkpointer, execution_id) 1pqbaMlc

413 

414 

415async def _stream_run_history_steps( 

416 *, 

417 compiled: Any, 

418 state: Any, 

419 runtime_config: Any, 

420 history_store: Any, 

421 execution_id: str, 

422 history_error_cls: type[Exception], 

423) -> None: 

424 """Append streamed node updates to the run history store.""" 

425 from orcheo.persistence import RUN_DURABILITY 1pqbaMlBKc

426 from orcheo.tracing import encode_step_namespace, split_subgraph_update 1pqbaMlBKc

427 

428 async with aclosing( 1pqbaMlBKc

429 compiled.astream( 

430 state, 

431 config=runtime_config, # type: ignore[arg-type] 

432 stream_mode="updates", 

433 subgraphs=True, 

434 durability=RUN_DURABILITY, 

435 ) 

436 ) as stream: 

437 async for chunk in stream: 1pqbalBKc

438 namespace, step = split_subgraph_update(chunk) 1pqbalBKc

439 tagged_step = encode_step_namespace(step, namespace) 1pqbalBKc

440 try: 1pqbalBKc

441 await history_store.append_step(execution_id, tagged_step) 1pqbalBKc

442 except history_error_cls: 1pqB

443 logger.exception( 1B

444 "Failed to append run history step for execution %s", 

445 execution_id, 

446 ) 

447 

448 

449async def _mark_history_completed( 

450 *, 

451 history_store: Any, 

452 execution_id: str, 

453 history_error_cls: type[Exception], 

454) -> None: 

455 """Persist completion markers for worker-executed runs.""" 

456 completion_payload = {"status": "completed"} 1baQc

457 try: 1baQc

458 await history_store.append_step(execution_id, completion_payload) 1baQc

459 await history_store.mark_completed(execution_id) 1baQc

460 except history_error_cls: 1Q

461 logger.exception( 1Q

462 "Failed to mark run history completed for execution %s", 

463 execution_id, 

464 ) 

465 

466 

467def _extract_output(final_state: Any) -> dict[str, Any] | None: 

468 """Extract output from final workflow state. 

469 

470 Args: 

471 final_state: The final state from workflow execution 

472 

473 Returns: 

474 Output dict or None 

475 """ 

476 if isinstance(final_state, dict): 1ba)!#$%c

477 return {"final_state": final_state} 1ba)c

478 if hasattr(final_state, "model_dump"): 1!#$%

479 return {"final_state": final_state.model_dump()} 1!#

480 return None 1$%

481 

482 

483async def _handle_execution_failure( 

484 run: Any, 

485 exc: Exception, 

486 *, 

487 history_store: Any | None = None, 

488 owner_token: str | None = None, 

489) -> dict[str, Any]: 

490 """Handle workflow execution failure. 

491 

492 Args: 

493 run: The workflow run object 

494 exc: The exception that occurred 

495 history_store: Optional run history store for failure persistence. 

496 owner_token: PostgreSQL worker ownership token, when applicable. 

497 

498 Returns: 

499 Error result dict 

500 """ 

501 from orcheo_backend.app.dependencies import get_repository 1efrtsuv

502 from orcheo_backend.app.repository_postgres import PostgresWorkflowRepository 1efrtsuv

503 

504 repository = get_repository() 1efrtsuv

505 run_id = str(run.id) 1efrtsuv

506 error_message = str(exc) 1efrtsuv

507 

508 logger.exception("Run %s failed: %s", run_id, error_message) 1efrtsuv

509 

510 try: 1efrtsuv

511 if owner_token is not None: 1efrtsuv

512 worker_repository = cast(PostgresWorkflowRepository, repository) 1s

513 await worker_repository.mark_worker_run_failed( 1s

514 run.id, 

515 owner_token=owner_token, 

516 actor=WORKER_ACTOR, 

517 error=error_message, 

518 ) 

519 else: 

520 await repository.mark_run_failed( 1efrtuv

521 run.id, actor=WORKER_ACTOR, error=error_message 

522 ) 

523 except Exception as mark_exc: 1r

524 logger.exception( 1r

525 "Failed to mark run %s as failed: %s", 

526 run_id, 

527 mark_exc, 

528 ) 

529 

530 if history_store is not None: 1efrtsuv

531 error_payload = {"status": "error", "error": error_message} 1ef

532 try: 1ef

533 await history_store.append_step(run_id, error_payload) 1ef

534 await history_store.mark_failed(run_id, error_message) 1ef

535 except Exception as history_exc: 1f

536 logger.exception( 1f

537 "Failed to mark run history %s as failed: %s", 

538 run_id, 

539 history_exc, 

540 ) 

541 

542 return {"status": "failed", "error": error_message} 1efrtsuv

543 

544 

545async def execute_run_async(run_id: str, workspace_id: str | None) -> dict[str, Any]: 

546 """Execute a workflow run asynchronously. 

547 

548 Args: 

549 run_id: UUID string of the run to execute 

550 workspace_id: Workspace that owns the run, or None if missing. 

551 

552 Returns: 

553 dict with keys: status (succeeded/failed), error (optional) 

554 """ 

555 run, error = await _load_and_validate_run(run_id, workspace_id) 1GjmC'H

556 if error: 1GjmC'H

557 return error 1'

558 

559 from orcheo_backend.app.dependencies import get_repository 1GjmCH

560 from orcheo_backend.app.repository_postgres import PostgresWorkflowRepository 1GjmCH

561 

562 repository = get_repository() 1GjmCH

563 if isinstance(repository, PostgresWorkflowRepository): 1GjmCH

564 owner_token = uuid4().hex 1jmC

565 start_error = await _mark_run_started(run, run_id, owner_token=owner_token) 1jmC

566 if start_error: 1jmC

567 return start_error 1C

568 task = asyncio.current_task() 1jm

569 loop = asyncio.get_running_loop() 1jm

570 

571 def cancel_lost_run() -> None: 1jm

572 if task is not None: 572 ↛ exitline 572 didn't return from function 'cancel_lost_run' because the condition on line 572 was always true1j

573 loop.call_soon_threadsafe(task.cancel) 1j

574 

575 with worker_run_heartbeat( 1jm

576 repository._dsn, run.id, owner_token, on_lease_lost=cancel_lost_run 

577 ): 

578 return await _execute_workflow(run, owner_token=owner_token) 1jm

579 

580 start_error = await _mark_run_started(run, run_id) 1GH

581 if start_error: 1GH

582 return start_error 1H

583 

584 return await _execute_workflow(run) 1G

585 

586 

587@celery_app.task(bind=True, max_retries=None, reject_on_worker_lost=True) 

588def execute_run(self: Task, run_id: str) -> dict[str, Any]: 

589 """Execute a workflow run by ID. 

590 

591 Args: 

592 self: Celery task instance (unused, required by bind=True) 

593 run_id: UUID of the run to execute 

594 

595 Returns: 

596 dict with keys: status (succeeded/failed/skipped), error (optional) 

597 """ 

598 logger.info("Executing run %s", run_id) 1DR

599 headers = getattr(getattr(self, "request", None), "headers", None) or {} 1DR

600 workspace_id = headers.get("workspace_id") or headers.get("x-orcheo-workspace-id") 1DR

601 loop = _get_event_loop() 1DR

602 try: 1DR

603 return loop.run_until_complete(execute_run_async(run_id, workspace_id)) 1DR

604 except (psycopg.OperationalError, PoolTimeout) as exc: 1D

605 # Keep an accepted queue message alive while PostgreSQL is unavailable. 

606 retries = getattr(self.request, "retries", 0) 1D

607 delay = min(300, 2 ** min(retries, 8)) 1D

608 raise self.retry(exc=exc, countdown=delay) from exc 1D

609 

610 

611async def _dispatch_cron_triggers_async() -> list[str]: 

612 """Dispatch due cron triggers and return enqueued run IDs. 

613 

614 Returns: 

615 List of enqueued run IDs 

616 """ 

617 from orcheo_backend.app.dependencies import get_repository 1567

618 

619 repository = get_repository() 1567

620 runs = await repository.dispatch_due_cron_runs() 1567

621 return [str(run.id) for run in runs] 1567

622 

623 

624@celery_app.task(bind=True) 

625def dispatch_cron_triggers(self: Task) -> dict[str, Any]: # noqa: ARG001 

626 """Dispatch due cron triggers by calling the cron dispatch endpoint. 

627 

628 This task is invoked periodically by Celery Beat to trigger scheduled runs. 

629 

630 Args: 

631 self: Celery task instance (unused, required by bind=True) 

632 

633 Returns: 

634 dict with keys: dispatched_runs (list of run IDs) 

635 """ 

636 if os.getenv("ORCHEO_CRON_DISPATCH_OWNER", "celery") == "scheduler": 1(S

637 logger.info("Skipping queued cron dispatch owned by the standalone scheduler") 1(

638 return {"dispatched_runs": []} 1(

639 logger.info("Dispatching cron triggers") 1S

640 loop = _get_event_loop() 1S

641 run_ids = loop.run_until_complete(_dispatch_cron_triggers_async()) 1S

642 logger.info("Dispatched %d cron runs", len(run_ids)) 1S

643 return {"dispatched_runs": run_ids} 1S

644 

645 

646__all__ = [ 

647 "dispatch_cron_triggers", 

648 "execute_run", 

649 "execute_run_async", 

650]