|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import functools |
| 5 | +import logging |
| 6 | +import traceback |
| 7 | +from typing import Any, Callable, Optional |
| 8 | + |
| 9 | +import plumpy |
| 10 | +import plumpy.futures |
| 11 | +import plumpy.persistence |
| 12 | +import plumpy.process_states |
| 13 | +from aiida.engine.processes.process import Process, ProcessState |
| 14 | +from aiida.engine.utils import InterruptableFuture, interruptable_task |
| 15 | + |
| 16 | +from aiida_pythonjob.calculations.common import ATTR_DESERIALIZERS |
| 17 | +from aiida_pythonjob.data.deserializer import deserialize_to_raw_python_data |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +async def task_run_job(process: Process, *args, **kwargs) -> Any: |
| 23 | + """Run the *async* user function and return results or a structured error.""" |
| 24 | + node = process.node |
| 25 | + |
| 26 | + inputs = dict(process.inputs.function_inputs or {}) |
| 27 | + deserializers = node.base.attributes.get(ATTR_DESERIALIZERS, {}) |
| 28 | + inputs = deserialize_to_raw_python_data(inputs, deserializers=deserializers) |
| 29 | + |
| 30 | + try: |
| 31 | + logger.info(f"scheduled request to run the function<{node.pk}>") |
| 32 | + results = await process.func(**inputs) # async user function |
| 33 | + logger.info(f"running function<{node.pk}> successful") |
| 34 | + return {"__ok__": True, "results": results} |
| 35 | + except Exception as exception: |
| 36 | + logger.warning(f"running function<{node.pk}> failed") |
| 37 | + return { |
| 38 | + "__error__": "ERROR_FUNCTION_EXECUTION_FAILED", |
| 39 | + "exception": str(exception), |
| 40 | + "traceback": traceback.format_exc(), |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | +@plumpy.persistence.auto_persist("msg", "data") |
| 45 | +class Waiting(plumpy.process_states.Waiting): |
| 46 | + """The waiting state for the `PyFunction` process.""" |
| 47 | + |
| 48 | + def __init__( |
| 49 | + self, |
| 50 | + process: Process, |
| 51 | + done_callback: Optional[Callable[..., Any]], |
| 52 | + msg: Optional[str] = None, |
| 53 | + data: Optional[Any] = None, |
| 54 | + ): |
| 55 | + super().__init__(process, done_callback, msg, data) |
| 56 | + self._task: InterruptableFuture | None = None |
| 57 | + self._killing: plumpy.futures.Future | None = None |
| 58 | + |
| 59 | + @property |
| 60 | + def process(self) -> Process: |
| 61 | + return self.state_machine |
| 62 | + |
| 63 | + def load_instance_state(self, saved_state, load_context): |
| 64 | + super().load_instance_state(saved_state, load_context) |
| 65 | + self._task = None |
| 66 | + self._killing = None |
| 67 | + |
| 68 | + async def execute(self) -> plumpy.process_states.State: |
| 69 | + node = self.process.node |
| 70 | + node.set_process_status("Running async function") |
| 71 | + try: |
| 72 | + payload = await self._launch_task(task_run_job, self.process) |
| 73 | + |
| 74 | + # Convert structured payloads into the next state or an ExitCode |
| 75 | + if payload.get("__ok__"): |
| 76 | + return self.parse(payload["results"]) |
| 77 | + elif payload.get("__error__"): |
| 78 | + err = payload["__error__"] |
| 79 | + if err == "ERROR_DESERIALIZE_INPUTS_FAILED": |
| 80 | + exit_code = self.process.exit_codes.ERROR_DESERIALIZE_INPUTS_FAILED.format( |
| 81 | + exception=payload.get("exception", ""), |
| 82 | + traceback=payload.get("traceback", ""), |
| 83 | + ) |
| 84 | + else: |
| 85 | + exit_code = self.process.exit_codes.ERROR_FUNCTION_EXECUTION_FAILED.format( |
| 86 | + exception=payload.get("exception", ""), |
| 87 | + traceback=payload.get("traceback", ""), |
| 88 | + ) |
| 89 | + # Jump straight to FINISHED by scheduling parse with the error ExitCode |
| 90 | + # We reuse the Running->parse path so the process finishes uniformly. |
| 91 | + return self.create_state(ProcessState.RUNNING, self.process.parse, {"__exit_code__": exit_code}) |
| 92 | + except plumpy.process_states.KillInterruption as exception: |
| 93 | + node.set_process_status(str(exception)) |
| 94 | + raise |
| 95 | + except (plumpy.futures.CancelledError, asyncio.CancelledError): |
| 96 | + node.set_process_status('Function task "run" was cancelled') |
| 97 | + raise |
| 98 | + except plumpy.process_states.Interruption: |
| 99 | + node.set_process_status('Function task "run" was interrupted') |
| 100 | + raise |
| 101 | + finally: |
| 102 | + node.set_process_status(None) |
| 103 | + if self._killing and not self._killing.done(): |
| 104 | + self._killing.set_result(False) |
| 105 | + |
| 106 | + async def _launch_task(self, coro, *args, **kwargs): |
| 107 | + """Launch a coroutine as a task, making sure it is interruptable.""" |
| 108 | + task_fn = functools.partial(coro, *args, **kwargs) |
| 109 | + try: |
| 110 | + self._task = interruptable_task(task_fn) |
| 111 | + return await self._task |
| 112 | + finally: |
| 113 | + self._task = None |
| 114 | + |
| 115 | + def parse(self, results: dict) -> plumpy.process_states.Running: |
| 116 | + """Advance to RUNNING where the process' `parse` will be called with results.""" |
| 117 | + return self.create_state(ProcessState.RUNNING, self.process.parse, results) |
| 118 | + |
| 119 | + def interrupt(self, reason: Any) -> Optional[plumpy.futures.Future]: # type: ignore[override] |
| 120 | + if self._task is not None: |
| 121 | + self._task.interrupt(reason) |
| 122 | + if isinstance(reason, plumpy.process_states.KillInterruption): |
| 123 | + if self._killing is None: |
| 124 | + self._killing = plumpy.futures.Future() |
| 125 | + return self._killing |
| 126 | + return None |
0 commit comments