ferruzzi commented on code in PR #62645:
URL: https://github.com/apache/airflow/pull/62645#discussion_r2880598024


##########
task-sdk/src/airflow/sdk/execution_time/callback_supervisor.py:
##########
@@ -0,0 +1,270 @@
+# 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 os
+import time
+from importlib import import_module
+from typing import TYPE_CHECKING, BinaryIO, ClassVar
+
+import attrs
+import structlog
+from pydantic import TypeAdapter
+
+from airflow.sdk.execution_time.supervisor import WatchedSubprocess
+
+if TYPE_CHECKING:
+    from collections.abc import Callable
+
+    from structlog.typing import FilteringBoundLogger
+    from typing_extensions import Self
+
+__all__ = ["CallbackSubprocess", "execute_callback", "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)
+    """
+    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)
+
+        # If the callback is a callable, call it.  If it is a class, 
instantiate it.
+        result = callback_callable(**callback_kwargs)
+
+        # If the callback is a class then it is now instantiated and callable, 
call it.
+        if callable(result):
+            context = callback_kwargs.get("context", {})
+            log.debug("Calling result with context for %s", callback_path)
+            result = result(context)
+
+        log.info("Callback %s executed successfully.", callback_path)
+        return True, None
+
+    except Exception as e:
+        error_msg = f"Callback execution failed: {type(e).__name__}: {str(e)}"
+        log.exception("Callback %s(%s) execution failed: %s", callback_path, 
callback_kwargs, error_msg)
+        return False, error_msg
+
+
+def _callback_subprocess_main():
+    """
+    Entry point for the callback subprocess, runs after fork.
+
+    Reads the callback path and kwargs from environment variables,
+    executes the callback, and exits with an appropriate code.
+    """
+    import json
+    import sys
+
+    log = structlog.get_logger(logger_name="callback_runner")
+
+    callback_path = os.environ.get("_AIRFLOW_CALLBACK_PATH", "")
+    callback_kwargs_json = os.environ.get("_AIRFLOW_CALLBACK_KWARGS", "{}")
+
+    if not callback_path:
+        print("No callback path found in environment", file=sys.stderr)
+        sys.exit(1)
+
+    try:
+        callback_kwargs = json.loads(callback_kwargs_json)
+    except Exception:
+        log.exception("Failed to deserialize callback kwargs")
+        sys.exit(1)
+
+    success, error_msg = execute_callback(callback_path, callback_kwargs, log)
+    if not success:
+        log.error("Callback failed", error=error_msg)
+        sys.exit(1)
+
+
+# An empty message set — callbacks don't send requests back to the supervisor 
(yet).
+_EmptyMessage: TypeAdapter[None] = TypeAdapter(None)
+
+
[email protected](kw_only=True)
+class CallbackSubprocess(WatchedSubprocess):
+    """
+    Supervised subprocess for executing callbacks.
+
+    Uses the WatchedSubprocess infrastructure for fork/monitor/signal handling
+    while keeping a simple lifecycle: start, run callback, exit.
+    """
+
+    decoder: ClassVar[TypeAdapter] = _EmptyMessage
+
+    @classmethod
+    def start(  # type: ignore[override]
+        cls,
+        *,
+        id: str,
+        callback_path: str,
+        callback_kwargs: dict,
+        target: Callable[[], None] = _callback_subprocess_main,
+        logger: FilteringBoundLogger | None = None,
+        **kwargs,
+    ) -> Self:
+        """Fork and start a new subprocess to execute the given callback."""
+        import json
+        from datetime import date, datetime
+        from uuid import UUID
+
+        class _ExtendedEncoder(json.JSONEncoder):
+            """Handle types that stdlib json can't serialize (UUID, datetime, 
etc.)."""
+
+            def default(self, o):
+                if isinstance(o, UUID):
+                    return str(o)
+                if isinstance(o, datetime):
+                    return o.isoformat()
+                if isinstance(o, date):
+                    return o.isoformat()
+                if hasattr(o, "__str__"):
+                    return str(o)
+                return super().default(o)
+
+        # Pass the callback data to the child process via environment 
variables.
+        # These are set before fork so the child inherits them, and cleaned up 
in the parent after.
+        os.environ["_AIRFLOW_CALLBACK_PATH"] = callback_path
+        os.environ["_AIRFLOW_CALLBACK_KWARGS"] = json.dumps(callback_kwargs, 
cls=_ExtendedEncoder)
+        try:
+            proc: Self = super().start(
+                id=id,
+                target=target,
+                logger=logger,
+                **kwargs,
+            )
+        finally:
+            # Clean up the env vars in the parent process
+            os.environ.pop("_AIRFLOW_CALLBACK_PATH", None)
+            os.environ.pop("_AIRFLOW_CALLBACK_KWARGS", None)

Review Comment:
   I think Copilot's suggested code is a bit off the mark, but the concept may 
still be sound and possibly even a better option than using `dill`.   I tried 
to keep it as close to the task supervisor as I could with this change and I 
will of course defer to those of you with a more solid understanding of the 
supervised process design we have going, but it seems like we can skip the 
serializing entirely and skip the environment variables entirely for the 
callback.
   
   I'll be honest, I wasn't familiar with `"closures" before Copilot's 
suggestion so I did a little googling and it seems to make sense.  Turns out 
I've seen it in use but wasn't familiar with the term.  If I understand it 
correctly, effectively if you wrap a function inside an outer function, then 
the inner one keeps all of the context.  So we can do something vaguely like
   
   ```python
   def start(cls, *, callback_path, callback_kwargs, **kwargs):
       
       def _target():
           execute_callback(callback_path, callback_kwargs, log)
           
       return super().start(target=_target)
   ```
   
   And the path and kwags travel along with the python object as it gets passed 
to super() without having to serialize and store it independently.  If that's 
the case, then that means we can also drop the whole messy _ExtendedEncoder too 
since we're not serializing any of that to envvar.
   
   It looks like this only works because we are using fork() instead of 
subprocess.Popen, and maybe that was something you folks knew and planned for, 
and I'm preaching to the choir here, but this trick is new to me, and I want to 
make sure I'm not missing something.
   
   I'm going to wait for at least one of  you to advise on this before I make 
the change, but I think it seems promising.



-- 
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]

Reply via email to