Skip to content

armgit / burr

Public Imported from GitHub
0

Build applications that make decisions (chatbots, agents, simulations, etc...). Monitor, trace, persist, and execute on your own infrastructure.

Fixes lifecycle hooks to only run once

elijahbenizzy36fdc5bbd197
diff --git a/burr/core/application.py b/burr/core/application.py
index bb801e02..a4147550 100644
--- a/burr/core/application.py
+++ b/burr/core/application.py
@@ -207,17 +207,25 @@ class Application:
the method you want -- you'll want iterate() (if you want to see the state/
results along the way), or run() (if you just want the final state/results).
- :param inputs: Inputs to the action -- this is if this action requires an input that is passed in from the outside world
+ :param inputs: Inputs to the action -- this is if this action requires an input that is passed in from the outside world :param __run_hooks:
:return: Tuple[Function, dict, State] -- the function that was just ran, the result of running it, and the new state
"""
+ return self._step(inputs=inputs, _run_hooks=True)
+
+ def _step(
+ self, inputs: Optional[Dict[str, Any]] = None, _run_hooks: bool = True
+ ) -> Optional[Tuple[Action, dict, State]]:
+ """Internal-facing version of step. This is the same as step, but with an additional
+ parameter to hide hook execution so async can leverage it."""
next_action = self.get_next_action()
if next_action is None:
return None
if inputs is None:
inputs = {}
- self._adapter_set.call_all_lifecycle_hooks_sync(
- "pre_run_step", action=next_action, state=self._state
- )
+ if _run_hooks:
+ self._adapter_set.call_all_lifecycle_hooks_sync(
+ "pre_run_step", action=next_action, state=self._state
+ )
exc = None
result = None
new_state = self._state
@@ -234,9 +242,14 @@ class Application:
logger.exception(_format_error_message(next_action, self._state, inputs))
raise e
finally:
- self._adapter_set.call_all_lifecycle_hooks_sync(
- "post_run_step", action=next_action, state=new_state, result=result, exception=exc
- )
+ if _run_hooks:
+ self._adapter_set.call_all_lifecycle_hooks_sync(
+ "post_run_step",
+ action=next_action,
+ state=new_state,
+ result=result,
+ exception=exc,
+ )
return next_action, result, new_state
async def astep(self, inputs: Dict[str, Any] = None) -> Optional[Tuple[Action, dict, State]]:
@@ -252,7 +265,7 @@ class Application:
inputs = {}
if next_action is None:
return None
- await self._adapter_set.call_all_lifecycle_hooks_async(
+ await self._adapter_set.call_all_lifecycle_hooks_sync_and_async(
"pre_run_step", action=next_action, state=self._state
)
exc = None
@@ -265,7 +278,9 @@ class Application:
# TODO -- add an option/configuration to launch a thread (yikes, not super safe, but for a pure function
# which this is supposed to be its OK).
# this delegates hooks to the synchronous version, so we'll call all of them as well
- return self.step(inputs=inputs)
+ return self._step(
+ inputs=inputs, _run_hooks=False
+ ) # Skip hooks as we already ran all of them/will run all of them in this function's finally
if next_action.single_step:
result, new_state = await _arun_single_step_action(
next_action, self._state, inputs=inputs
diff --git a/burr/lifecycle/internal.py b/burr/lifecycle/internal.py
index f70bc5b9..7dc688a6 100644
--- a/burr/lifecycle/internal.py
+++ b/burr/lifecycle/internal.py
@@ -168,6 +168,8 @@ class LifecycleAdapterSet:
futures = []
for adapter in self.async_hooks[hook_name]:
futures.append(getattr(adapter, hook_name)(**kwargs))
+ if len(futures) == 0:
+ return # No async hooks to call
await asyncio.gather(*futures)
async def call_all_lifecycle_hooks_sync_and_async(self, hook_name: str, **kwargs):
diff --git a/docs/concepts/hooks.rst b/docs/concepts/hooks.rst
index 940ef769..3dc3f399 100644
--- a/docs/concepts/hooks.rst
+++ b/docs/concepts/hooks.rst
@@ -50,4 +50,15 @@ To include this in the application, you pass it into the :py:meth:`with_hooks <b
...
.build())
+.. note::
+
+ There are synchronous and asynchronous hooks. Synchronous hooks will be called with both synchronous and asynchronous run methods
+ (all of ``step``, ``astep``, ``iterate``, ``aiterate``, ``run``, and ``arun``), whereas synchronous hooks will only be called with
+ the asynchronous methods (``astep``, ``aiterate``, ``arun``).
+
+.. warning::
+ Hook order is currently undefined -- they happen to be called now in the order in which they are defined. We will likely
+ alter them to be called in the order they are defined (for `pre...`) hooks and in reverse order for `post...` hooks,
+ but this is not yet implemented.
+
Read more about the hook API in the :ref:`hooks section <hooksref>`.
diff --git a/tests/core/test_application.py b/tests/core/test_application.py
index a178e7c7..23599dae 100644
--- a/tests/core/test_application.py
+++ b/tests/core/test_application.py
@@ -830,6 +830,50 @@ async def test_application_run_step_hooks_async():
assert len(tracker.post_called) == 11
+async def test_application_run_step_runs_hooks():
+ class ActionTracker(PreRunStepHook, PostRunStepHook):
+ def __init__(self):
+ self.pre_called_count = 0
+ self.post_called_count = 0
+
+ def pre_run_step(self, **future_kwargs):
+ self.pre_called_count += 1
+
+ def post_run_step(self, **future_kwargs):
+ self.post_called_count += 1
+
+ class ActionTrackerAsync(PreRunStepHookAsync, PostRunStepHookAsync):
+ def __init__(self):
+ self.pre_called_count = 0
+ self.post_called_count = 0
+
+ async def pre_run_step(self, **future_kwargs):
+ await asyncio.sleep(0.0001)
+ self.pre_called_count += 1
+
+ async def post_run_step(self, **future_kwargs):
+ await asyncio.sleep(0.0001)
+ self.post_called_count += 1
+
+ hooks = [ActionTracker(), ActionTrackerAsync()]
+
+ counter_action = base_counter_action.with_name("counter")
+ app = Application(
+ actions=[counter_action],
+ transitions=[
+ Transition(counter_action, counter_action, default),
+ ],
+ state=State({}),
+ initial_step="counter",
+ adapter_set=internal.LifecycleAdapterSet(*hooks),
+ )
+ await app.astep()
+ assert hooks[0].pre_called_count == 1
+ assert hooks[0].post_called_count == 1
+ assert hooks[1].pre_called_count == 1
+ assert hooks[1].post_called_count == 1
+
+
def test_application_post_application_create_hook():
class PostApplicationCreateTracker(PostApplicationCreateHook):
def __init__(self):