{"record":{"id":"b786f20e81c1ea18","repo":"iflytek/astron-agent","slug":"codeenum-async-task-cancel-error","errorCode":"CodeEnum.ASYNC_TASK_CANCEL_ERROR","errorMessage":"Failed to cancel async task","messagePattern":"Failed to cancel async task","errorType":"error_code","errorClass":"CustomException","httpStatus":null,"severity":"error","filePath":"core/workflow/extensions/middleware/asynchronous/manager.py","lineNumber":31,"sourceCode":"class CeleryTaskProcessor(AsyncTaskService, Service):\n    \"\"\"Celery-based implementation of the AsyncTaskService.\"\"\"\n\n    def __init__(self) -> None:\n        self.app: Celery = app\n\n    def launch_task(self, task_func: Callable, *args: Any, **kwargs: Any) -> str:\n        \"\"\"Launch a celery task and return the task id.\"\"\"\n        if not hasattr(task_func, \"delay\"):\n            msg = f\"Task function {task_func} does not have a delay method\"\n            raise ValueError(msg)\n        result: AsyncResult = task_func.delay(*args, **kwargs)\n        return result.id\n\n    def cancel_task(self, cancel_func: Callable[[Any], None], **kwargs: Any) -> None:\n        try:\n            cancel_func(self.app, **kwargs)\n        except Exception as e:\n            raise CustomException(\n                CodeEnum.ASYNC_TASK_CANCEL_ERROR,\n                err_msg=\"Failed to cancel async task\",\n                cause_error=str(e),\n            ) from e\n","sourceCodeStart":13,"sourceCodeEnd":36,"githubUrl":"https://github.com/iflytek/astron-agent/blob/5e758547a83371a5a4b29dadf4ac03e8dd527635/core/workflow/extensions/middleware/asynchronous/manager.py#L13-L36","documentation":"CeleryTaskProcessor.cancel_task wraps any exception raised by the caller-supplied cancel_func (e.g. AsyncResult.revoke on a Celery app) in a CustomException with code ASYNC_TASK_CANCEL_ERROR. It signals that a previously launched Celery async task could not be cancelled, with the underlying cause stored in cause_error.","triggerScenarios":"Calling cancel_task with a cancel_func that raises: revoking a task id that no longer exists or already finished, Celery broker (Redis/RabbitMQ) being unreachable, or passing a cancel_func whose signature does not match the **kwargs forwarded to it.","commonSituations":"Revoking a workflow async task after its Celery TTL expired; broker connection lost during a deploy; passing kwargs (e.g. task_id, terminate) that the cancel_func does not accept.","solutions":["Inspect cause_error on the raised CustomException to identify the underlying exception (broker connection vs. invalid task id).","Verify the Celery broker (Redis/RabbitMQ) is reachable from the workflow service.","Confirm the task_id passed to cancel_func refers to a still-running task; finished tasks cannot be revoked.","Ensure cancel_func signature matches (app, **kwargs) and all forwarded kwargs are supported.","Wrap cancel_task in try/except in the caller and treat cancellation of already-finished tasks as non-fatal."],"exampleFix":"// before\ncancel_func = lambda app, task_id: app.control.revoke(task_id, terminate=True)\nprocessor.cancel_task(cancel_func)  # TypeError: missing task_id -> ASYNC_TASK_CANCEL_ERROR\n// after\nprocessor.cancel_task(cancel_func, task_id=result.id, terminate=True)","handlingStrategy":"try-catch","validationCode":"def can_cancel(processor, task_id):\n    res = celery_app.AsyncResult(task_id)\n    return res.state in (\"PENDING\", \"STARTED\", \"RETRY\")","typeGuard":"def is_running(res) -> bool:\n    return getattr(res, \"state\", None) in (\"PENDING\", \"STARTED\", \"RETRY\")","tryCatchPattern":"try:\n    processor.cancel_task(cancel_func, task_id=task_id)\nexcept CustomException as e:\n    logger.warning(f\"Cancel failed for {task_id}: {e}\")  # inspect e.cause_error / cause","preventionTips":["Check AsyncResult.state before revoking; skip already-finished tasks.","Keep broker (Redis/RabbitMQ) health-checked before issuing revokes.","Match cancel_func signature to (app, **kwargs) and pass task_id explicitly.","Treat cancel-failure of finished tasks as idempotent no-op in calling code."],"tags":["celery","async-task","cancellation","workflow"],"backgroundTag":"invalid-state-transition","analyzedSha":"5e758547a83371a5a4b29dadf4ac03e8dd527635","analyzedAt":"2026-09-12T08:03:51.356Z","contentChangedAt":"2026-09-12T08:03:51.356Z","schemaVersion":2},"datasetVersion":"2026-09-19T12:17:13.211Z"}