jernejfrank commented on code in PR #796:
URL: https://github.com/apache/burr/pull/796#discussion_r3527755892


##########
burr/core/action.py:
##########
@@ -379,6 +380,82 @@ def tags(self) -> list[str]:
         """
         return []
 
+    @property
+    def on_error(self) -> Optional[Callable[[State, Exception], State]]:
+        """Returns the error handler associated with this action, if any.
+
+        An error handler is any callable ``(State, Exception) -> State``. If 
it is set
+        and the action raises, the application will call it to produce a new 
state
+        (suppressing the exception) instead of re-raising. See
+        :py:func:`capture_as <burr.core.action.capture_as>` for a built-in 
handler.
+
+        :return: The error handler callable, or None if not set
+        """
+        return getattr(self, "_on_error", None)
+
+
+class capture_as:
+    """Error handler that suppresses an exception and records a 
JSON-serializable
+    summary of it into the given state field.
+
+    Use this with the ``on_error`` parameter of the :py:func:`@action 
<burr.core.action.action>`
+    decorator, or with :py:meth:`ApplicationBuilder.with_error_handling
+    <burr.core.application.ApplicationBuilder.with_error_handling>`:
+
+    .. code-block:: python
+
+        @action(reads=[], writes=["output"], on_error=capture_as("error"))
+        def flaky(state: State) -> tuple[dict, State]:
+            result = {"output": call_some_api(...)}
+            return result, state.update(**result)
+
+        @action(reads=["error"], writes=[])
+        def handler(state: State) -> tuple[dict, State]:
+            ...  # inspect/reset state["error"], then route onward
+
+        app = (
+            ApplicationBuilder()
+            .with_actions(flaky=flaky, handler=handler)
+            # the capture field MUST be initialized -- expr() raises on a 
missing key,
+            # so seed ``error`` to None so the wildcard condition is safe to 
evaluate
+            # on every step before any exception has occurred.
+            .with_state(error=None)
+            .with_transitions(("*", "handler", expr("error is not None")))
+            .with_entrypoint("flaky")
+            .build()

Review Comment:
   Trying to understand this better. This means we need to populate something 
in the state, how does this play with existing states that are already 
persisted and the builder loads them in? Is it enough to seed the last state 
and turn on the new error handling API or do we need to retrospectively 
populate all of them?



##########
burr/core/application.py:
##########
@@ -849,6 +849,7 @@ def __init__(
         parallel_executor_factory: Optional[Executor] = None,
         state_persister: Union[BaseStateSaver, LifecycleAdapter, None] = None,
         state_initializer: Union[BaseStateLoader, LifecycleAdapter, None] = 
None,
+        global_error_handler: Optional[Callable[[State, Exception], State]] = 
None,

Review Comment:
   Digging into this a bit:
   
   IIUC, each action can specify their own error type, state dict key for the 
error,m etc.. But that can get tedious if you have multiple actions that need 
the same error handling. So this gives a global handling ability, but it does 
it only for a single type of error? Like, I would not be able to specify 
globally a sequence of handlers that handle different errors, unless I wrap 
that inside the `global_error_handler` callable, make that thing cathc the 
umbrella exception and than inside continue routing to subhandlers?



##########
burr/core/graph.py:
##########
@@ -150,13 +154,36 @@ def _create_action_tag_map(actions: List[Action]) -> 
dict[str, List[Action]]:
     def get_next_node(
         self, prior_step: Optional[str], state: State, entrypoint: str
     ) -> Optional[Action]:
-        """Gives the next node to execute given state + prior step."""
+        """Gives the next node to execute given state + prior step.
+
+        Resolution uses a 4-tier precedence so that guarded wildcard ("*") 
transitions
+        can route errors from any action while leaving common default-last 
graphs
+        unchanged. A condition is "default" iff ``condition.name == 
"default"``. The
+        tiers, evaluated in order with first match winning:
+
+            1. source-specific non-default transitions (insertion order)
+            2. wildcard non-default transitions (insertion order)
+            3. source-specific default transition
+            4. wildcard default transition
+        """
         if prior_step is None:
             return self._action_map[entrypoint]
-        possibilities = self._adjacency_map[prior_step]
-        for next_action, condition in possibilities:
-            if condition.run(state)[Condition.KEY]:
-                return self._action_map[next_action]
+        src = self._adjacency_map[prior_step]
+        wild = self._adjacency_map.get("*", [])
+
+        def _is_default(condition: Condition) -> bool:
+            return condition.name == "default"
+
+        tiers = (
+            [(t, c) for t, c in src if not _is_default(c)],
+            [(t, c) for t, c in wild if not _is_default(c)],
+            [(t, c) for t, c in src if _is_default(c)],
+            [(t, c) for t, c in wild if _is_default(c)],
+        )
+        for tier in tiers:
+            for next_action, condition in tier:
+                if condition.run(state)[Condition.KEY]:
+                    return self._action_map[next_action]

Review Comment:
   Can this blow up in our faces for non-error nodes if somebody gets funky 
with their naming?



##########
burr/core/action.py:
##########
@@ -379,6 +380,82 @@ def tags(self) -> list[str]:
         """
         return []
 
+    @property
+    def on_error(self) -> Optional[Callable[[State, Exception], State]]:
+        """Returns the error handler associated with this action, if any.
+
+        An error handler is any callable ``(State, Exception) -> State``. If 
it is set
+        and the action raises, the application will call it to produce a new 
state
+        (suppressing the exception) instead of re-raising. See
+        :py:func:`capture_as <burr.core.action.capture_as>` for a built-in 
handler.
+
+        :return: The error handler callable, or None if not set
+        """
+        return getattr(self, "_on_error", None)
+
+
+class capture_as:
+    """Error handler that suppresses an exception and records a 
JSON-serializable
+    summary of it into the given state field.
+
+    Use this with the ``on_error`` parameter of the :py:func:`@action 
<burr.core.action.action>`
+    decorator, or with :py:meth:`ApplicationBuilder.with_error_handling
+    <burr.core.application.ApplicationBuilder.with_error_handling>`:
+
+    .. code-block:: python
+
+        @action(reads=[], writes=["output"], on_error=capture_as("error"))
+        def flaky(state: State) -> tuple[dict, State]:
+            result = {"output": call_some_api(...)}
+            return result, state.update(**result)
+
+        @action(reads=["error"], writes=[])
+        def handler(state: State) -> tuple[dict, State]:
+            ...  # inspect/reset state["error"], then route onward
+
+        app = (
+            ApplicationBuilder()
+            .with_actions(flaky=flaky, handler=handler)
+            # the capture field MUST be initialized -- expr() raises on a 
missing key,
+            # so seed ``error`` to None so the wildcard condition is safe to 
evaluate
+            # on every step before any exception has occurred.
+            .with_state(error=None)
+            .with_transitions(("*", "handler", expr("error is not None")))
+            .with_entrypoint("flaky")
+            .build()

Review Comment:
   Poking around a bit to see if I understand this.
   
   If I need to handle different errors and I route them to different handlers, 
then with this API I will need to specify each one individually?
   
   ```python
   app = (
               ApplicationBuilder()
               .with_actions(flaky=flaky, handler=handler)
               # the capture field MUST be initialized -- expr() raises on a 
missing key,
               # so seed ``error`` to None so the wildcard condition is safe to 
evaluate
               # on every step before any exception has occurred.
               .with_state(error1=None,error2=None,error3=None,...)
               .with_transitions(
                   ("error1", "handler", expr("error1 is not None"),
                   ("error2", "handler", expr("error2 is not None"),
                   ("error3", "handler", expr("error3 is not None"),
               )
               .with_entrypoint("flaky")
               .build()
   ```



##########
burr/core/graph.py:
##########
@@ -59,7 +59,9 @@ def _validate_transitions(
 ):
     exhausted = {}  # items for which we have seen a default transition
     for from_, to, condition in transitions:
-        if from_ not in actions:
+        # "*" is a wildcard source -- it routes from ANY action, so it is not
+        # required to be a declared action. The target, however, must be real.
+        if from_ != "*" and from_ not in actions:

Review Comment:
   Nit: this may sound really pedantic but I would prefer `"*"` to be either 
enum or global variable



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