Copilot commented on code in PR #62645:
URL: https://github.com/apache/airflow/pull/62645#discussion_r3066495801
##########
providers/celery/src/airflow/providers/celery/executors/celery_executor_utils.py:
##########
@@ -209,40 +207,17 @@ def execute_workload(input: str) -> None:
from celery.exceptions import Ignore
from pydantic import TypeAdapter
- from airflow.executors import workloads
- from airflow.providers.common.compat.sdk import conf
- from airflow.sdk.execution_time.supervisor import supervise
+ from airflow.executors.workloads import ExecutorWorkload
- decoder = TypeAdapter[workloads.All](workloads.All)
+ decoder = TypeAdapter[ExecutorWorkload](ExecutorWorkload)
workload = decoder.validate_json(input)
celery_task_id = app.current_task.request.id
log.info("[%s] Executing workload in Celery: %s", celery_task_id, workload)
- base_url = conf.get("api", "base_url", fallback="/")
- # If it's a relative URL, use localhost:8080 as the default.
- if base_url.startswith("/"):
- base_url = f"http://localhost:8080{base_url}"
- default_execution_api_server = f"{base_url.rstrip('/')}/execution/"
-
try:
- if isinstance(workload, workloads.ExecuteTask):
- supervise(
- # This is the "wrong" ti type, but it duck types the same.
TODO: Create a protocol for this.
- ti=workload.ti, # type: ignore[arg-type]
- dag_rel_path=workload.dag_rel_path,
- bundle_info=workload.bundle_info,
- token=workload.token,
- server=conf.get("core", "execution_api_server_url",
fallback=default_execution_api_server),
- log_path=workload.log_path,
- )
- elif isinstance(workload, workloads.ExecuteCallback):
- success, error_msg = execute_callback_workload(workload.callback,
log)
- if not success:
- raise RuntimeError(error_msg or "Callback execution failed")
- else:
- raise ValueError(f"CeleryExecutor does not know how to handle
{type(workload)}")
+ BaseExecutor.run_workload(workload)
except Exception as e:
Review Comment:
`execute_workload()` now calls `BaseExecutor.run_workload()`
unconditionally. Since this is provider code and `version_compat.py` suggests
the celery provider is intended to run across multiple Airflow minor versions,
this introduces a hard dependency on the new core API. Please guard this call
(e.g. `if AIRFLOW_V_3_2_PLUS` / `hasattr(BaseExecutor, "run_workload")`) and
fall back to the previous implementation for older cores, or raise a clear
error when unsupported.
##########
task-sdk/src/airflow/sdk/execution_time/callback_supervisor.py:
##########
@@ -0,0 +1,312 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Supervised execution of callback workloads."""
+
+from __future__ import annotations
+
+import sys
+import time
+from importlib import import_module
+from typing import TYPE_CHECKING, BinaryIO, ClassVar, Protocol
+from uuid import UUID
+
+import attrs
+import structlog
+from pydantic import TypeAdapter
+
+from airflow.sdk.execution_time.supervisor import (
+ MIN_HEARTBEAT_INTERVAL,
+ SOCKET_CLEANUP_TIMEOUT,
+ WatchedSubprocess,
+ _make_process_nondumpable,
+)
+
+if TYPE_CHECKING:
+ from structlog.typing import FilteringBoundLogger
+ from typing_extensions import Self
+
+ # Core (airflow.executors.workloads.base.BundleInfo) and SDK
(airflow.sdk.api.datamodels._generated.BundleInfo)
+ # are structurally identical, but MyPy treats them as different types.
This Protocol makes MyPy happy.
+ class _BundleInfoLike(Protocol):
+ name: str
+ version: str | None
+
+
+__all__ = ["CallbackSubprocess", "supervise_callback"]
+
+log: FilteringBoundLogger =
structlog.get_logger(logger_name="callback_supervisor")
+
+
+def execute_callback(
+ callback_path: str,
+ callback_kwargs: dict,
+ log,
+) -> tuple[bool, str | None]:
+ """
+ Execute a callback function by importing and calling it, returning the
success state.
+
+ Supports two patterns:
+ 1. Functions - called directly with kwargs
+ 2. Classes that return callable instances (like BaseNotifier) -
instantiated then called with context
+
+ Example:
+ # Function callback
+ execute_callback("my_module.alert_func", {"msg": "Alert!", "context":
{...}}, log)
+
+ # Notifier callback
+ execute_callback("airflow.providers.slack...SlackWebhookNotifier",
{"text": "Alert!"}, log)
+
+ :param callback_path: Dot-separated import path to the callback function
or class.
+ :param callback_kwargs: Keyword arguments to pass to the callback.
+ :param log: Logger instance for recording execution.
+ :return: Tuple of (success: bool, error_message: str | None)
+ """
+ from airflow.sdk._shared.module_loading import accepts_context
+
+ if not callback_path:
+ return False, "Callback path not found."
+
+ try:
+ # Import the callback callable
+ # Expected format: "module.path.to.function_or_class"
+ module_path, function_name = callback_path.rsplit(".", 1)
+ module = import_module(module_path)
+ callback_callable = getattr(module, function_name)
+
+ log.debug("Executing callback %s(%s)...", callback_path,
callback_kwargs)
+
+ kwargs_without_context = {k: v for k, v in callback_kwargs.items() if
k != "context"}
Review Comment:
`execute_callback()` uses %-style formatting with positional args (e.g.
`log.debug("Executing callback %s(%s)...", ...)`). Airflow’s TaskSDK structlog
loggers are generally used in structured mode (`log.debug("...", key=value)`),
and depending on the configured wrapper class positional args may be ignored or
raise. Please switch these log calls (debug/info/exception) to structured
fields (e.g. callback_path=..., callback_kwargs=..., error_msg=...) so they are
JSON-friendly and consistent with other supervisor logs.
##########
airflow-core/src/airflow/executors/base_executor.py:
##########
@@ -579,6 +582,76 @@ def get_cli_commands() -> list[GroupCommand]:
"""
return []
+ @staticmethod
+ def run_workload(
+ workload: ExecutorWorkload,
+ *,
+ server: str | None = None,
+ dry_run: bool = False,
+ subprocess_logs_to_stdout: bool = False,
+ proctitle: str | None = None,
+ ) -> int:
+ """
+ Pass the workload to the appropriate supervisor based on workload type.
+
+ Workload-specific attributes (log_path, sentry_integration,
bundle_info, etc.) are read from the
+ workload object itself.
+
+ :param workload: The ``ExecutorWorkload`` to execute.
+ :param server: Base URL of the API server (used by task workloads).
+ :param dry_run: If True, execute without actual task execution
(simulate run).
+ :param subprocess_logs_to_stdout: Should task logs also be sent to
stdout via the main logger.
+ :param proctitle: Process title to set for this workload. If not
provided, defaults to
+ ``"airflow supervisor: <workload.display_name>"``.
+ :return: Exit code of the process.
+ """
+ try:
+ from setproctitle import setproctitle
+
+ setproctitle(proctitle or f"airflow supervisor:
{workload.display_name}")
+ except ImportError:
+ pass
Review Comment:
`BaseExecutor.run_workload()` unconditionally tries to import/use
`setproctitle`. Other executor entrypoints in this PR explicitly skip
`setproctitle` on macOS (e.g. `airflow/executors/local_executor.py` and
`providers/celery/.../celery_executor_utils.py`). To avoid reintroducing macOS
issues and keep behavior consistent, add the same darwin guard here (or leave
proctitle management to the caller).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]