YongGoose commented on code in PR #602:
URL: https://github.com/apache/burr/pull/602#discussion_r4718684950


##########
burr/core/application.py:
##########
@@ -299,17 +342,44 @@ def _format_BASE_ERROR_MESSAGE(action: Action, 
input_state: State, inputs: dict)
 
 
 def _run_single_step_action(
-    action: SingleStepAction, state: State, inputs: Optional[Dict[str, Any]]
+    action: SingleStepAction,
+    state: State,
+    inputs: Optional[Dict[str, Any]],
+    adapter_set: Optional["LifecycleAdapterSet"] = None,
 ) -> Tuple[Dict[str, Any], State]:
     """Runs a single step action. This API is internal-facing and a bit in 
flux, but
     it corresponds to the SingleStepAction class.
 
     :param action: Action to run
     :param state: State to run with
     :param inputs: Inputs to pass directly to the action
+    :param adapter_set: Optional lifecycle adapter set for checking 
interceptors
     :return: The result of running the action, and the new state
     """
-    # TODO -- guard all reads/writes with a subset of the state
+    # Check for execution interceptors
+    if adapter_set:
+        interceptor = adapter_set.get_first_matching_hook(
+            "intercept_action_execution", lambda hook: 
hook.should_intercept(action=action)
+        )
+        if interceptor:
+            worker_adapter_set = adapter_set.get_worker_adapter_set()
+            result = interceptor.intercept_run(
+                action=action, state=state, inputs=inputs, 
worker_adapter_set=worker_adapter_set
+            )
+            # Check if interceptor returned state via special key (for 
single-step actions)
+            if "__INTERCEPTOR_NEW_STATE__" in result:
+                new_state = result.pop("__INTERCEPTOR_NEW_STATE__")
+            else:
+                # For multi-step actions or if state wasn't provided
+                # we need to compute it
+                new_state = action.update(result, state)

Review Comment:
   **The fallback branch can't succeed.** `_run_single_step_action` only 
handles single-step actions, and `SingleStepAction.update` always raises 
(`burr/core/action.py:612`). So any interceptor that doesn't add 
`__INTERCEPTOR_NEW_STATE__` fails here, including one that follows 
`intercept_run`'s docstring ("Result dictionary from running the action").
   
   I ran an interceptor that does `result, _ = action.run_and_update(state, 
**inputs); return result`, on a plain `@action` function with `app.step()`:
   
   ```
   ValueError: SingleStepAction.update should never be called independently -- 
use run_and_update instead.
   ```
   
   For every `@action` function, the key is mandatory, not optional, and the 
"For multi-step actions" comment describes a case that can't reach this 
function. This adds to the earlier point about the magic key: an explicit 
return type, for example `(result, new_state)` from `intercept_run` for 
single-step actions, would put the contract in the signature. Until that 
changes, the `intercept_run` docstrings in `burr/lifecycle/base.py` should say 
the key is required for single-step actions. The same applies to 
`_arun_single_step_action` (L638–642).



##########
burr/core/application.py:
##########
@@ -185,10 +208,30 @@ def _run_function(function: Function, state: State, 
inputs: Dict[str, Any], name
 
 
 async def _arun_function(
-    function: Function, state: State, inputs: Dict[str, Any], name: str
+    function: Function,
+    state: State,
+    inputs: Dict[str, Any],
+    name: str,
+    adapter_set: Optional["LifecycleAdapterSet"] = None,
 ) -> dict:
     """Runs a function, returning the result of running the function.
     Async version of the above."""
+
+    # Check for execution interceptors
+    if adapter_set:
+        interceptor = adapter_set.get_first_matching_hook(
+            "intercept_action_execution",
+            lambda hook: hook.should_intercept(action=function) and 
hasattr(hook, "intercept_run"),
+        )
+        if interceptor and 
inspect.iscoroutinefunction(interceptor.intercept_run):

Review Comment:
   **A matching interceptor of the wrong kind is skipped silently, and the 
action runs locally.** `get_first_matching_hook` returns the first adapter 
whose `should_intercept` is True, and only afterwards does this check whether 
it's async. If it's a sync interceptor, execution falls through to the normal 
path with no error or log. I ran these with every `should_intercept` returning 
True:
   
   | registered | action / entry point | result |
   |---|---|---|
   | sync interceptor | async `@action`, `astep()` | no interceptor called, ran 
locally |
   | `[sync, async]` | async `@action`, `astep()` | no interceptor called, ran 
locally |
   | `[async, sync]` | async `@action`, `astep()` | async interceptor called |
   | sync streaming interceptor | async `@streaming_action`, `astream_result()` 
| no interceptor called, ran locally |
   | `[async, sync]` | sync `@action`, `step()` | `TypeError: argument of type 
'coroutine' is not iterable` |
   
   For a remote-execution hook, running locally without saying so is the worst 
outcome, because the action executes in the wrong place, with the wrong 
resources. Moving the kind check into the predicate (`... and 
inspect.iscoroutinefunction(hook.intercept_run)` here, `not ...` on the sync 
side) fixes the ordering cases. It also covers the async-guard gap already 
raised for the sync paths. Raising when some interceptor's `should_intercept` 
returned True but none of the right kind exists would cover the rest. 
`_arun_single_step_action` (L630–632) and the async streaming runner (L476–478) 
have the same shape.



##########
burr/core/application.py:
##########
@@ -334,7 +404,18 @@ def _run_single_step_streaming_action(
     action.validate_inputs(inputs)
     stream_initialize_time = system.now()
     first_stream_start_time = None
-    generator = action.stream_run_and_update(state, **inputs)
+
+    # Check for streaming action interceptors
+    interceptor = lifecycle_adapters.get_first_matching_hook(
+        "intercept_streaming_action", lambda hook: 
hook.should_intercept(action=action)
+    )
+    if interceptor:
+        worker_adapter_set = lifecycle_adapters.get_worker_adapter_set()
+        generator = interceptor.intercept_stream_run_and_update(
+            action=action, state=state, inputs=inputs, 
worker_adapter_set=worker_adapter_set
+        )
+    else:
+        generator = action.stream_run_and_update(state, **inputs)

Review Comment:
   **Multi-step streaming actions are never intercepted.** Only the single-step 
streaming runners consult `intercept_streaming_action`. 
`_run_multi_step_streaming_action` and `_arun_multi_step_streaming_action` 
aren't changed. I ran this with a streaming interceptor whose 
`should_intercept` returns True:
   
   | action | entry point | interceptor called |
   |---|---|---|
   | `@streaming_action` | `stream_result()`, sync interceptor | yes |
   | `StreamingAction` subclass | `stream_result()`, sync interceptor | no, ran 
locally |
   | async `@streaming_action` | `astream_result()`, async interceptor | yes |
   | `AsyncStreamingAction` subclass | `astream_result()`, async interceptor | 
no, ran locally |
   
   `StreamingAction` is the class-based API shown in 
`docs/concepts/streaming-actions.rst`. Either the multi-step runners need the 
same hook, or the interceptor docs should say these actions are never offered 
to `should_intercept`.



##########
burr/lifecycle/base.py:
##########
@@ -492,6 +492,356 @@ async def post_end_stream(
         pass
 
 
[email protected]_hook("pre_run_step_worker")
+class PreRunStepHookWorker(abc.ABC):
+    """Hook that runs on the worker (e.g., Ray/Temporal) before action 
execution.
+    This hook is designed to be called by execution interceptors on remote 
workers,
+    as opposed to PreRunStepHook which always runs on the main orchestrator 
process."""

Review Comment:
   Design question: where should worker hooks run? Right now they run only if 
the interceptor calls `worker_adapter_set.call_all_lifecycle_hooks_*` itself. 
Every interceptor in the tests and examples does this by hand. They never run 
when an action executes locally: I registered a `PreRunStepHookWorker` with no 
interceptor, and `app.step()` didn't call it.
   
   If these hooks mean "runs wherever the action runs", the local path could 
call them too. A hook that sets up a per-process resource or tags logs would 
then behave the same whether or not an action is intercepted, and interceptor 
authors couldn't forget to call them. If they mean "remote only", that's worth 
saying here, along with whose job it is to call them.



##########
burr/core/application.py:
##########
@@ -1051,7 +1175,19 @@ async def _astep(self, inputs: Optional[Dict[str, Any]], 
_run_hooks: bool = True
             result = None
             new_state = self._state
             try:
-                if not next_action.is_async():
+                # Check if there's an async interceptor for this action
+                has_async_interceptor = False
+                if self._adapter_set:
+                    interceptor = self._adapter_set.get_first_matching_hook(
+                        "intercept_action_execution",
+                        lambda hook: hook.should_intercept(action=next_action)
+                        and hasattr(hook, "intercept_run"),
+                    )
+                    if interceptor and 
inspect.iscoroutinefunction(interceptor.intercept_run):
+                        has_async_interceptor = True

Review Comment:
   Nit: `should_intercept` runs twice for each `astep()` on an intercepted 
action, once here and again in `_arun_function`/`_arun_single_step_action`. I 
counted 2 calls for one `astep()` on an async `@action`. That's harmless for a 
cheap predicate. Still, choosing the interceptor once here and passing it down 
instead of `adapter_set` would give one decision per step, and would save a 
second scan over every adapter's MRO. On rebase, this block conflicts with 
#895, which restructured this branch on `main`.



##########
burr/lifecycle/base.py:
##########
@@ -492,6 +492,356 @@ async def post_end_stream(
         pass
 
 
[email protected]_hook("pre_run_step_worker")
+class PreRunStepHookWorker(abc.ABC):
+    """Hook that runs on the worker (e.g., Ray/Temporal) before action 
execution.
+    This hook is designed to be called by execution interceptors on remote 
workers,
+    as opposed to PreRunStepHook which always runs on the main orchestrator 
process."""
+
+    @abc.abstractmethod
+    def pre_run_step_worker(
+        self,
+        *,
+        action: "Action",
+        state: "State",
+        inputs: Dict[str, Any],
+        **future_kwargs: Any,
+    ):
+        """Run before a step is executed on the worker.
+
+        :param action: Action to be executed
+        :param state: State prior to step execution
+        :param inputs: Inputs to the action
+        :param future_kwargs: Future keyword arguments
+        """
+        pass
+
+
[email protected]_hook("pre_run_step_worker")
+class PreRunStepHookWorkerAsync(abc.ABC):
+    """Async hook that runs on the worker before action execution."""
+
+    @abc.abstractmethod
+    async def pre_run_step_worker(
+        self,
+        *,
+        action: "Action",
+        state: "State",
+        inputs: Dict[str, Any],
+        **future_kwargs: Any,
+    ):
+        """Async run before a step is executed on the worker.
+
+        :param action: Action to be executed
+        :param state: State prior to step execution
+        :param inputs: Inputs to the action
+        :param future_kwargs: Future keyword arguments
+        """
+        pass
+
+
[email protected]_hook("post_run_step_worker")
+class PostRunStepHookWorker(abc.ABC):
+    """Hook that runs on the worker after action execution.
+    This hook is designed to be called by execution interceptors on remote 
workers,
+    as opposed to PostRunStepHook which always runs on the main orchestrator 
process."""
+
+    @abc.abstractmethod
+    def post_run_step_worker(
+        self,
+        *,
+        action: "Action",
+        state: "State",
+        result: Optional[Dict[str, Any]],
+        exception: Exception,
+        **future_kwargs: Any,
+    ):
+        """Run after a step is executed on the worker.
+
+        :param action: Action that was executed
+        :param state: State after step execution
+        :param result: Result of the action
+        :param exception: Exception that was raised
+        :param future_kwargs: Future keyword arguments
+        """
+        pass
+
+
[email protected]_hook("post_run_step_worker")
+class PostRunStepHookWorkerAsync(abc.ABC):
+    """Async hook that runs on the worker after action execution."""
+
+    @abc.abstractmethod
+    async def post_run_step_worker(
+        self,
+        *,
+        action: "Action",
+        state: "State",
+        result: Optional[dict],
+        exception: Exception,
+        **future_kwargs: Any,
+    ):
+        """Async run after a step is executed on the worker.
+
+        :param action: Action that was executed
+        :param state: State after step execution
+        :param result: Result of the action
+        :param exception: Exception that was raised
+        :param future_kwargs: Future keyword arguments
+        """
+        pass
+
+
[email protected]_hook("pre_start_stream_worker")
+class PreStartStreamHookWorker(abc.ABC):
+    """Hook that runs on the worker after a stream is started."""
+
+    @abc.abstractmethod
+    def pre_start_stream_worker(
+        self,
+        *,
+        action: str,
+        state: "State",
+        inputs: Dict[str, Any],
+        **future_kwargs: Any,
+    ):
+        pass
+
+
[email protected]_hook("pre_start_stream_worker")
+class PreStartStreamHookWorkerAsync(abc.ABC):
+    """Async hook that runs on the worker after a stream is started."""
+
+    @abc.abstractmethod
+    async def pre_start_stream_worker(
+        self,
+        *,
+        action: str,
+        state: "State",
+        inputs: Dict[str, Any],
+        **future_kwargs: Any,
+    ):
+        pass
+
+
[email protected]_hook("post_end_stream_worker")
+class PostEndStreamHookWorker(abc.ABC):
+    """Hook that runs on the worker after a stream is ended."""
+
+    @abc.abstractmethod
+    def post_end_stream_worker(
+        self,
+        *,
+        action: str,
+        result: Optional[Dict[str, Any]],
+        exception: Exception,
+        **future_kwargs: Any,
+    ):
+        pass
+
+
[email protected]_hook("post_end_stream_worker")
+class PostEndStreamHookWorkerAsync(abc.ABC):
+    """Async hook that runs on the worker after a stream is ended."""
+
+    @abc.abstractmethod
+    async def post_end_stream_worker(
+        self,
+        *,
+        action: str,
+        result: Optional[Dict[str, Any]],
+        exception: Exception,
+        **future_kwargs: Any,
+    ):
+        pass
+
+
[email protected]_hook("intercept_action_execution")
+class ActionExecutionInterceptorHook(abc.ABC):
+    """Hook that can wrap/replace action execution (e.g., for Ray/Temporal).
+    This hook allows you to intercept the execution of an action and run it
+    on a different execution backend while maintaining the same interface.
+
+    The interceptor receives a worker_adapter_set containing only worker hooks
+    (PreRunStepHookWorker, PostRunStepHookWorker, etc.) that can be called
+    on the remote execution environment."""
+
+    @abc.abstractmethod
+    def should_intercept(
+        self,
+        *,
+        action: "Action",
+        **future_kwargs: Any,
+    ) -> bool:
+        """Determine if this action should be intercepted.
+
+        :param action: Action to potentially intercept
+        :param future_kwargs: Future keyword arguments
+        :return: True if this hook should intercept execution
+        """
+        pass
+
+    @abc.abstractmethod
+    def intercept_run(
+        self,
+        *,
+        action: "Action",
+        state: "State",
+        inputs: Dict[str, Any],
+        **future_kwargs: Any,
+    ) -> dict:
+        """Replace the action.run() call with custom execution.
+
+        Note: The state passed here is the FULL state, not subsetted.
+        You are responsible for subsetting it to action.reads if needed.
+
+        :param action: Action to execute
+        :param state: Current state (FULL state, not subsetted)
+        :param inputs: Inputs to the action
+        :param future_kwargs: Future keyword arguments (includes 
worker_adapter_set)
+        :return: Result dictionary from running the action
+        """
+        pass
+
+
[email protected]_hook("intercept_action_execution")
+class ActionExecutionInterceptorHookAsync(abc.ABC):
+    """Async version of ActionExecutionInterceptorHook for intercepting async 
actions."""
+
+    @abc.abstractmethod
+    def should_intercept(
+        self,
+        *,
+        action: "Action",
+        **future_kwargs: Any,
+    ) -> bool:
+        """Determine if this action should be intercepted.
+
+        Note: This method is intentionally synchronous even on async 
interceptors.
+        It is a pure predicate used inside lambdas that cannot be awaited. If 
you
+        need I/O to decide, cache the result during __init__ or pre_run_step.
+
+        :param action: Action to potentially intercept
+        :param future_kwargs: Future keyword arguments
+        :return: True if this hook should intercept execution
+        """
+        pass
+
+    @abc.abstractmethod
+    async def intercept_run(
+        self,
+        *,
+        action: "Action",
+        state: "State",
+        inputs: Dict[str, Any],
+        **future_kwargs: Any,
+    ) -> dict:
+        """Replace the action.run() call with custom execution.
+
+        Note: The state passed here is the FULL state, not subsetted.
+        You are responsible for subsetting it to action.reads if needed.
+
+        :param action: Action to execute
+        :param state: Current state (FULL state, not subsetted)
+        :param inputs: Inputs to the action
+        :param future_kwargs: Future keyword arguments (includes 
worker_adapter_set)
+        :return: Result dictionary from running the action
+        """
+        pass
+
+
[email protected]_hook(
+    "intercept_streaming_action", 
intercept_method="intercept_stream_run_and_update"
+)
+class StreamingActionInterceptorHook(abc.ABC):
+    """Hook to intercept streaming action execution (e.g., for Ray/Temporal).
+    This hook allows you to wrap streaming actions to execute on different 
backends.
+
+    The interceptor receives a worker_adapter_set containing only worker hooks
+    that can be called on the remote execution environment."""
+
+    @abc.abstractmethod
+    def should_intercept(
+        self,
+        *,
+        action: "Action",
+        **future_kwargs: Any,
+    ) -> bool:
+        """Determine if this streaming action should be intercepted.
+
+        :param action: Streaming action to potentially intercept
+        :param future_kwargs: Future keyword arguments
+        :return: True if this hook should intercept execution
+        """
+        pass
+
+    @abc.abstractmethod
+    def intercept_stream_run_and_update(
+        self,
+        *,
+        action: "Action",
+        state: "State",
+        inputs: Dict[str, Any],
+        **future_kwargs: Any,
+    ):
+        """Replace stream_run_and_update with custom execution.
+        Must be a generator that yields (result_dict, optional_state) tuples.

Review Comment:
   Contract point for the rebase: since this branch's base, #1027 has landed on 
`main`. When a consumer stops early, `_run_single_step_streaming_action` now 
closes the action generator (`_close_action_generator` on `main`). After the 
rebase, that will be this interceptor's generator. Because the action itself 
runs elsewhere, the docstring should say what an interceptor must do on 
`GeneratorExit`/`aclose()`, for example cancel the remote stream and not leave 
it running. This is a reading of `main`'s code; I haven't run it against a 
rebased branch.



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