kaxil commented on code in PR #62645: URL: https://github.com/apache/airflow/pull/62645#discussion_r3066378011
########## 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"} + + # Call the callable with all kwargs if it accepts context, otherwise strip context. + if accepts_context(callback_callable): + result = callback_callable(**callback_kwargs) + else: Review Comment: The old code checked `if _accepts_context(callback_callable) and context is not None:` before including context. The new code passes all kwargs (including `context`) unconditionally when `accepts_context` returns True. If `callback_kwargs` contains `"context": None`, callbacks will now receive `context=None` where they previously would not have received it at all. ########## providers/edge3/src/airflow/providers/edge3/cli/worker.py: ########## @@ -229,7 +229,7 @@ def _run_job_via_supervisor(self, workload: ExecuteTask, results_queue: Queue) - try: supervise( # This is the "wrong" ti type, but it duck types the same. TODO: Create a protocol for this. - # Same like in airflow/executors/local_executor.py:_execute_work() + # Same like in airflow/executors/local_executor.py:_execute_workload() Review Comment: Follow-up from previous review: The comment now references `_execute_workload()` but edge3 still calls `supervise()` which will trigger `DeprecationWarning` on every task execution after this PR merges. Since edge3 is in-tree, consider updating it to call `supervise_task()` directly in this PR. ########## airflow-core/src/airflow/executors/workloads/base.py: ########## @@ -83,3 +85,71 @@ class BaseDagBundleWorkload(BaseWorkloadSchema, ABC): dag_rel_path: os.PathLike[str] # Filepath where the DAG can be found (likely prefixed with `DAG_FOLDER/`) bundle_info: BundleInfo log_path: str | None # Rendered relative log filename template the task logs should be written to. + + @property + @abstractmethod + def key(self) -> Hashable: + """ + Return the unique key identifying this workload instance. + + Used by executors for tracking queued/running workloads and reporting results. + Must be a hashable value suitable for use in sets and as dict keys. + + Must be implemented by subclasses. + """ Review Comment: Nit: `raise NotImplementedError(...)` bodies on `@abstractmethod` properties can never execute since ABC prevents instantiation. Convention is `...` (Ellipsis) as the body. Same applies to `display_name`, `success_state`, and `failure_state` below. ########## 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"} + + # Call the callable with all kwargs if it accepts context, otherwise strip context. + if accepts_context(callback_callable): + result = callback_callable(**callback_kwargs) + else: + result = callback_callable(**kwargs_without_context) + + # If the callback was a class then it is now instantiated and callable, call it. + # Try keyword args first. If the callable only accepts positional args (like + # BaseNotifier.__call__(self, *args)), fall back to passing context positionally. + if callable(result): + try: + if accepts_context(result): + result = result(**callback_kwargs) + else: + result = result(**kwargs_without_context) + except TypeError: + result = result(callback_kwargs.get("context", {})) + Review Comment: The `except TypeError` catch is broad. If the callback's `__call__` raises TypeError for a legitimate reason (wrong argument count, mismatched types in the callback logic itself), the error is caught and silently replaced with `result(callback_kwargs.get("context", {}))`. This masks real bugs. Consider checking `e.args` for signature-mismatch indicators, or at minimum logging a warning when the fallback is taken. ########## task-sdk/src/airflow/sdk/execution_time/request_handlers.py: ########## @@ -0,0 +1,101 @@ +# +# 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. +""" +Shared request handlers for supervised subprocess comms channels. + +These functions implement the supervisor-side logic for message types that are +used by more than one subprocess type (tasks, callbacks, triggerer). Each +handler accepts a ``Client`` and a request message and returns +``(response_model | None, dump_opts)`` so the caller can forward the result +via ``send_msg``. +""" + +from __future__ import annotations Review Comment: This file (101 lines) is never imported by any code in this PR. Neither `ActivitySubprocess._handle_request` nor `CallbackSubprocess._handle_request` references it. Dead code -- consider removing it from this PR and adding it when it's actually wired up. -- 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]
