Build applications that make decisions (chatbots, agents, simulations, etc...). Monitor, trace, persist, and execute on your own infrastructure.
Python aiburrchatbot-frameworkdagsgenerative-aigraphshacktoberfestllmopsllmsmlopspersistent-data-structurestate-machinestate-managementvisibility
Fixes recursive issue in the pre/post execute call hooks
elijahbenizzy73c3c33312a3
diff --git a/burr/core/application.py b/burr/core/application.pyindex 2a92e772..7b7e6d85 100644--- a/burr/core/application.py+++ b/burr/core/application.py@@ -412,8 +412,15 @@ class ApplicationContext(AbstractContextManager):_application_context = contextvars.ContextVar[Optional[ApplicationContext]]("application_context", default=None)--_run_call_var = contextvars.ContextVar[Optional[object]]("run_call_var", default=None)+# The purpose of this is to ensure that we don't run the run call hooks multiple times+# We do this as some functions call out to others (but they do not call out to themselves, recursively)+# Thus we keep track of a sentinel, unique per execute method, which tells us if we have already logged+# If we want to call out recursively inside applications, we'll need to think this through+# That said, this is all context/thread safe -- multiple threads can call at the same time+# Furthermore, if one app delegates to another, their app ID will be different, so it will trace as well.+_run_call_var = contextvars.ContextVar[Optional[Dict[str, ExecuteMethod]]](+ "run_call_var", default=None+)CallableT = TypeVar("CallableT")@@ -427,11 +434,10 @@ class _call_execute_method_pre_post:def __init__(self, method: ExecuteMethod):self.method = method- self.sentinel = object() # unique object to ensure we only call oncedef call_pre(self, app) -> bool:- if should_run_hooks := (_run_call_var.get() is None):- _run_call_var.set(self.sentinel)+ if should_run_hooks := (app.uid not in _run_call_var.get({})):+ _run_call_var.set({**_run_call_var.get({}), **{app.uid: self.method}})app._adapter_set.call_all_lifecycle_hooks_sync("pre_run_execute_call",app_id=app._uid,@@ -442,21 +448,23 @@ class _call_execute_method_pre_post:return should_run_hooksdef call_post(self, app, exc) -> bool:- if should_run_hooks := (_run_call_var.get() is self.sentinel):+ if should_run_hooks := (+ app.uid in _run_call_var.get(dict) and _run_call_var.get()[app.uid] == self.method+ ):+ _run_call_var.set({k: v for k, v in _run_call_var.get().items() if k != app.uid})app._adapter_set.call_all_lifecycle_hooks_sync("post_run_execute_call",- app_id=app._uid,+ app_id=app.uid,partition_key=app._partition_key,state=app.state,method=self.method,exception=exc,)- _run_call_var.set(None)return should_run_hooksasync def acall_pre(self, app) -> bool:- if should_run_hooks := (_run_call_var.get() is None):- _run_call_var.set(self.sentinel)+ if should_run_hooks := (app.uid not in _run_call_var.get({})):+ _run_call_var.set({**_run_call_var.get({}), **{app.uid: self.method}})await app._adapter_set.call_all_lifecycle_hooks_sync_and_async("pre_run_execute_call",app_id=app._uid,@@ -467,7 +475,10 @@ class _call_execute_method_pre_post:return should_run_hooksasync def acall_post(self, app, exc) -> bool:- if should_run_hooks := (_run_call_var.get() is self.sentinel):+ if should_run_hooks := (+ app.uid in _run_call_var.get(dict) and _run_call_var.get()[app.uid] == self.method+ ):+ _run_call_var.set({k: v for k, v in _run_call_var.get().items() if k != app.uid})await app._adapter_set.call_all_lifecycle_hooks_sync_and_async("post_run_execute_call",app_id=app._uid,@@ -476,7 +487,6 @@ class _call_execute_method_pre_post:method=self.method,exception=exc,)- _run_call_var.set(None)return should_run_hooksdef __call__(self, fn: CallableT) -> CallableT:diff --git a/tests/core/test_application.py b/tests/core/test_application.pyindex 68d1c152..3660fff7 100644--- a/tests/core/test_application.py+++ b/tests/core/test_application.py@@ -38,7 +38,7 @@ from burr.core.application import (_run_single_step_streaming_action,_validate_start,)-from burr.core.graph import Graph, Transition+from burr.core.graph import Graph, GraphBuilder, Transitionfrom burr.core.persistence import BaseStatePersister, DevNullPersister, PersistedStateDatafrom burr.lifecycle import (PostRunStepHook,@@ -2691,3 +2691,73 @@ def test_application_does_not_allow_dunderscore_inputs():)with pytest.raises(ValueError, match="double underscore"):app._process_inputs({"__not_allowed": ...}, app.get_next_action())+++def test_application_recursive_action_lifecycle_hooks():+ """Tests that calling burr within burr works as expected"""++ class TestingHook(PreApplicationExecuteCallHook, PostApplicationExecuteCallHook):+ def __init__(self):+ self.pre_called = []+ self.post_called = []++ def pre_run_execute_call(+ self,+ *,+ app_id: str,+ partition_key: str,+ state: "State",+ method: ExecuteMethod,+ **future_kwargs: Any,+ ):+ self.pre_called.append((app_id, partition_key, state, method))++ def post_run_execute_call(+ self,+ *,+ app_id: str,+ partition_key: str,+ state: "State",+ method: ExecuteMethod,+ exception: Optional[Exception],+ **future_kwargs,+ ):+ self.post_called.append((app_id, partition_key, state, method, exception))++ hook = TestingHook()+ foo = []++ @action(reads=["recursion_count", "total_count"], writes=["recursion_count", "total_count"])+ def recursive_action(state: State) -> State:+ foo.append(1)+ recursion_count = state["recursion_count"]+ if recursion_count == 5:+ return state+ # Fork bomb!+ total_counts = []+ for i in range(2):+ app = (+ ApplicationBuilder()+ .with_graph(graph)+ .with_hooks(hook)+ .with_entrypoint("recursive_action")+ .with_state(recursion_count=recursion_count + 1, total_count=1)+ .build()+ )+ action, result, state = app.run(halt_after=["recursive_action"])+ total_counts.append(state["total_count"])+ return state.update(+ recursion_count=state["recursion_count"], total_count=sum(total_counts) + 1+ )++ graph = GraphBuilder().with_actions(recursive_action).with_transitions().build()++ # initial to kick it off+ result = recursive_action(State({"recursion_count": 0, "total_count": 0}))+ # Basic sanity checks to demonstrate+ assert result["recursion_count"] == 5+ assert result["total_count"] == 63 # One for each of the calls (sum(2**n for n in range(6)))+ assert (+ len(hook.pre_called) == 62+ ) # 63 - the initial one from the call to recursive_action outside the application+ assert len(hook.post_called) == 62 # ditto