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.

Adds spans within actions for tracing/visibility

elijahbenizzy5e5f88572cac
diff --git a/burr/core/application.py b/burr/core/application.py
index cbb8683d..d90028f0 100644
--- a/burr/core/application.py
+++ b/burr/core/application.py
@@ -1,5 +1,6 @@
import collections
import dataclasses
+import functools
import logging
import pprint
from typing import (
@@ -16,6 +17,7 @@ from typing import (
Union,
)
+from burr import visibility
from burr.core.action import (
Action,
Condition,
@@ -221,6 +223,12 @@ class Application:
self._adapter_set.call_all_lifecycle_hooks_sync(
"post_application_create", state=self._state, application_graph=self._graph
)
+ # TODO -- consider adding global inputs + global input factories to the builder
+ self.dependency_factory = {
+ "__tracer": functools.partial(
+ visibility.tracing.TracerFactory, lifecycle_adapters=self._adapter_set
+ )
+ }
def step(self, inputs: Optional[Dict[str, Any]] = None) -> Optional[Tuple[Action, dict, State]]:
"""Performs a single step, advancing the state machine along.
@@ -228,14 +236,17 @@ class Application:
the action, and the new state.
Use this if you just want to do something with the state and not rely on generators.
- E.G. press forward/backwards, hnuman in the loop, etc... Odds are this is not
+ E.G. press forward/backwards, human in the loop, etc... Odds are this is not
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 __run_hooks:
+ :param inputs: Inputs to the action -- this is if this action requires an input that is passed in from the outside world
: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)
+
+ out = self._step(inputs=inputs, _run_hooks=True)
+ self._increment_sequence_id()
+ return out
def _step(
self, inputs: Optional[Dict[str, Any]] = None, _run_hooks: bool = True
@@ -247,6 +258,7 @@ class Application:
return None
if inputs is None:
inputs = {}
+ inputs = self._process_inputs(inputs, next_action)
if _run_hooks:
self._adapter_set.call_all_lifecycle_hooks_sync(
"pre_run_step", action=next_action, state=self._state, inputs=inputs
@@ -283,12 +295,37 @@ class Application:
new_state = new_state.update(
**{
PRIOR_STEP: next_action.name,
- # make it a string for future proofing
- SEQUENCE_ID: str(int(self._state.get(SEQUENCE_ID, 0)) + 1),
}
)
return new_state
+ def _process_inputs(self, inputs: Dict[str, Any], action: Action) -> Dict[str, Any]:
+ inputs = inputs.copy()
+ processed_inputs = {}
+ for key in list(inputs.keys()):
+ if key in action.inputs:
+ processed_inputs[key] = inputs.pop(key)
+ if len(inputs) > 0:
+ raise ValueError(
+ f"Keys {inputs.keys()} were passed in as inputs to action "
+ f"{action.name}, but not declared by the action as an input! "
+ f"Action needs: {action.inputs}"
+ )
+ missing_inputs = set(action.inputs) - set(processed_inputs.keys())
+ for required_input in list(missing_inputs):
+ # if we can find it in the dependency factory, we'll use that
+ if required_input in self.dependency_factory:
+ processed_inputs[required_input] = self.dependency_factory[required_input](
+ action, self.sequence_id
+ )
+ missing_inputs.remove(required_input)
+ if len(missing_inputs) > 0:
+ raise ValueError(
+ f"Action {action.name} is missing required inputs: {missing_inputs}. "
+ f"Has inputs: {processed_inputs}"
+ )
+ return processed_inputs
+
async def astep(self, inputs: Dict[str, Any] = None) -> Optional[Tuple[Action, dict, State]]:
"""Asynchronous version of step.
@@ -298,10 +335,11 @@ class Application:
:return: Tuple[Function, dict, State] -- the action that was just ran, the result of running it, and the new state
"""
next_action = self.get_next_action()
- if inputs is None:
- inputs = {}
if next_action is None:
return None
+ if inputs is None:
+ inputs = {}
+ inputs = self._process_inputs(inputs, next_action)
await self._adapter_set.call_all_lifecycle_hooks_sync_and_async(
"pre_run_step", action=next_action, state=self._state, inputs=inputs
)
@@ -335,6 +373,7 @@ class Application:
"post_run_step", action=next_action, state=new_state, result=result, exception=exc
)
self._set_state(new_state)
+ self._increment_sequence_id()
return next_action, result, new_state
def _clean_iterate_params(
@@ -515,6 +554,9 @@ class Application:
"""
prior_action = None
result = None
+ halt_before, halt_after, inputs = self._clean_iterate_params(
+ halt_before, halt_after, inputs
+ )
async for prior_action, result, state in self.aiterate(
halt_before=halt_before, halt_after=halt_after, inputs=inputs
):
@@ -647,6 +689,20 @@ class Application:
"""
return self._graph
+ @property
+ def sequence_id(self) -> Optional[int]:
+ """gives the sequence ID of the current (next) action.
+ This is incremented after every step is taken -- meaning that incremeneting
+ it is the very last action that is done. Any logging, etc... will use the current
+ step's sequence ID
+
+ :return:
+ """
+ return self._state.get(SEQUENCE_ID, 0)
+
+ def _increment_sequence_id(self):
+ self._state = self._state.update(**{SEQUENCE_ID: self.sequence_id + 1})
+
def _assert_set(value: Optional[Any], field: str, method: str):
if value is None:
diff --git a/burr/lifecycle/base.py b/burr/lifecycle/base.py
index de8f23f6..597da771 100644
--- a/burr/lifecycle/base.py
+++ b/burr/lifecycle/base.py
@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, Any, Dict, Optional, Union
if TYPE_CHECKING:
# type-checking-only for a circular import
from burr.core import State, Action, ApplicationGraph
+ from burr.visibility import ActionSpan
from burr.lifecycle.internal import lifecycle
@@ -113,6 +114,72 @@ class PostApplicationCreateHook(abc.ABC):
pass
[email protected]_hook("pre_start_span")
+class PreStartSpanHook(abc.ABC):
+ """Hook that runs before a span is started in the tracing API.
+ This can be either a context manager or a logger."""
+
+ @abc.abstractmethod
+ def pre_start_span(
+ self,
+ *,
+ action: str,
+ action_sequence_id: int,
+ span: "ActionSpan",
+ span_dependencies: list[str],
+ **future_kwargs: Any,
+ ):
+ pass
+
+
[email protected]_hook("pre_start_span")
+class PreStartSpanHookAsync(abc.ABC):
+ @abc.abstractmethod
+ async def pre_start_span(
+ self,
+ *,
+ action: str,
+ action_sequence_id: int,
+ span: "ActionSpan",
+ span_dependencies: list[str],
+ **future_kwargs: Any,
+ ):
+ pass
+
+
[email protected]_hook("post_end_span")
+class PostEndSpanHook(abc.ABC):
+ """Hook that runs after a span is ended in the tracing API.
+ This can be either a context manager or a logger."""
+
+ @abc.abstractmethod
+ def post_end_span(
+ self,
+ *,
+ action: str,
+ action_sequence_id: int,
+ span: "ActionSpan",
+ span_dependencies: list[str],
+ **future_kwargs: Any,
+ ):
+ pass
+
+
[email protected]_hook("post_end_span")
+class PostEndSpanHookAsync(abc.ABC):
+ @abc.abstractmethod
+ async def post_end_span(
+ self,
+ *,
+ action: str,
+ action_sequence_id: int,
+ span: "ActionSpan",
+ span_dependencies: list[str],
+ **future_kwargs: Any,
+ ):
+ pass
+
+
# THESE ARE NOT IN USE
# TODO -- implement/decide how to use them
@lifecycle.base_hook("pre_run_application")
@@ -159,4 +226,8 @@ LifecycleAdapter = Union[
PostRunApplicationHook,
PostRunApplicationHookAsync,
PostApplicationCreateHook,
+ PreStartSpanHook,
+ PreStartSpanHookAsync,
+ PostEndSpanHook,
+ PostEndSpanHookAsync,
]
diff --git a/burr/visibility/__init__.py b/burr/visibility/__init__.py
new file mode 100644
index 00000000..39f4c4b7
--- /dev/null
+++ b/burr/visibility/__init__.py
@@ -0,0 +1,4 @@
+from burr.visibility.tracing import ActionSpan
+from burr.visibility.tracing import TracerFactory as Tracer
+
+__all__ = ["Tracer", "ActionSpan"]
diff --git a/burr/visibility/tracing.py b/burr/visibility/tracing.py
new file mode 100644
index 00000000..b7ddadaa
--- /dev/null
+++ b/burr/visibility/tracing.py
@@ -0,0 +1,248 @@
+import dataclasses
+import uuid
+from contextlib import AbstractAsyncContextManager, AbstractContextManager
+from contextvars import ContextVar
+from typing import Any, List, Optional, Type
+
+from burr.lifecycle.internal import LifecycleAdapterSet
+
+
+class ActionSpan:
+ action: str
+ action_sequence_id: int
+ name: str
+ parent: Optional["ActionSpan"]
+ sequence_id: int = 0
+ child_count: int = 0
+
+ def spawn(self, name: str) -> "ActionSpan":
+ self.child_count += 1
+ return ActionSpan(
+ action=self.action,
+ action_sequence_id=self.action_sequence_id,
+ name=name,
+ parent=self,
+ sequence_id=self.child_count - 1, # sequence id is 0 indexed
+ child_count=0, # start the child count at 0
+ )
+
+ @property
+ def uid(self) -> str:
+ action_sequence_id = self.action_sequence_id
+ parent_ids = [self.sequence_id]
+ current = self
+ while (current := current.parent) is not None:
+ parent_ids.append(current.sequence_id)
+
+ return f"{action_sequence_id}:{'.'.join(reversed([str(x) for x in parent_ids]))}"
+
+ @classmethod
+ def create_initial(
+ cls, action: str, name: str, sequence_id: int, action_sequence_id: int
+ ) -> "ActionSpan":
+ """Creates the initial action span for an action. This should be only called if the current
+ action span is none.
+
+ :param action:
+ :param name:
+ :param sequence_id:
+ :return:
+ """
+ return ActionSpan(
+ action=action,
+ name=name,
+ sequence_id=sequence_id,
+ parent=None,
+ action_sequence_id=action_sequence_id,
+ )
+
+
+execution_context_var: ContextVar[Optional[ActionSpan]] = ContextVar(
+ "execution_context",
+ default=None,
+)
+
+
+def create_span_id() -> str:
+ """Creates a unique
+
+ :return:
+ """
+ return f"span_{str(uuid.uuid4())}"
+
+
+class ActionSpanTracer(AbstractContextManager, AbstractAsyncContextManager):
+ """Context manager for use within tracing actions. This has the role solely of delegating
+ to hooks -- it does not do anything except manage context and pass those to the hooks.
+
+ Note that a new instance of this will be passed to every action that is traced. This allows
+ us to reset this based on state. This can handle both synchronous and asynchronous contexts.
+
+
+
+ The following hooks are ran:
+ - pre_span_start
+ - post_span_end
+
+ And we'll likely add:
+ - log_artifact
+ """
+
+ def __init__(
+ self,
+ action: str,
+ action_sequence_id: int,
+ span_name: str,
+ lifecycle_adapters: LifecycleAdapterSet,
+ span_dependencies: List[str],
+ top_level_span_count: int = 0,
+ context_var=execution_context_var,
+ ):
+ """Initialiezs the ActionSpanTracer.
+
+ :param action:
+ :param span_name:
+ :param lifecycle_adapters:
+ :param span_dependencies:
+ :param top_level_span_count:
+ """
+ self.action = action
+ self.action_sequence_id = action_sequence_id
+ self.lifecycle_adapters = lifecycle_adapters
+ self.span_name = span_name
+ self.span_dependencies = span_dependencies
+ self.top_level_span_count = top_level_span_count
+ self.context_var = context_var
+
+ def _sync_hooks_enter(self, context: ActionSpan):
+ self.lifecycle_adapters.call_all_lifecycle_hooks_sync(
+ "pre_start_span",
+ action=self.action,
+ span=context,
+ span_dependencies=self.span_dependencies,
+ action_sequence_id=self.action_sequence_id,
+ )
+
+ async def _async_hooks_enter(self, context: ActionSpan):
+ await self.lifecycle_adapters.call_all_lifecycle_hooks_async(
+ "pre_start_span",
+ action=self.action,
+ span=context,
+ span_dependencies=self.span_dependencies,
+ action_sequence_id=self.action_sequence_id,
+ )
+
+ async def _async_hooks_exit(self, context: ActionSpan):
+ await self.lifecycle_adapters.call_all_lifecycle_hooks_async(
+ "post_end_span",
+ action=self.action,
+ span=context,
+ span_dependencies=self.span_dependencies,
+ action_sequence_id=self.action_sequence_id,
+ )
+
+ def _enter(self):
+ current_execution_context = self.context_var.get()
+ if current_execution_context is None:
+ # create an initial one if we're at the top level
+ self.context_var.set(
+ ActionSpan.create_initial(
+ self.action,
+ self.span_name,
+ self.top_level_span_count - 1,
+ action_sequence_id=self.action_sequence_id,
+ )
+ )
+ else:
+ self.context_var.set(current_execution_context.spawn(self.span_name))
+ return self.context_var.get()
+
+ def _exit(self):
+ current_execution_context = self.context_var.get()
+ self.context_var.set(current_execution_context.parent)
+ return current_execution_context
+
+ def _sync_hooks_exit(self, context: ActionSpan):
+ self.lifecycle_adapters.call_all_lifecycle_hooks_sync(
+ "post_end_span",
+ action=self.action,
+ span=context,
+ span_dependencies=self.span_dependencies,
+ )
+
+ def __enter__(self):
+ enter_context = self._enter()
+ self._sync_hooks_enter(enter_context)
+ return self
+
+ def __exit__(
+ self,
+ __exc_type: Type[BaseException],
+ __exc_value: Optional[Type[BaseException]],
+ __traceback: Optional[Type[BaseException]],
+ ) -> Optional[bool]:
+ """Raise any exception triggered within the runtime context."""
+ prior_execution_context = self._exit()
+ self._sync_hooks_exit(prior_execution_context)
+ return None
+
+ def log_artifact(self, name: str, value: Any):
+ raise NotImplementedError
+
+ async def __aenter__(self) -> "ActionSpanTracer":
+ enter_context = self._enter()
+ self._sync_hooks_enter(enter_context)
+ await self._async_hooks_enter(self.context_var.get())
+ return self
+
+ async def __aexit__(
+ self,
+ __exc_type: Type[BaseException],
+ __exc_value: Optional[Type[BaseException]],
+ __traceback: Optional[Type[BaseException]],
+ ) -> Optional[bool]:
+ prior_execution_context = self._exit()
+ self._sync_hooks_exit(prior_execution_context)
+ await self._async_hooks_exit(prior_execution_context)
+ return None
+
+
+class TracerFactory:
+ def __init__(
+ self,
+ action: str,
+ sequence_id: int,
+ lifecycle_adapters: LifecycleAdapterSet,
+ _context_var: ContextVar[Optional[ActionSpan]] = execution_context_var,
+ ):
+ """Represents a tracer factory to create tracer instances. User never instantiates this
+ directly. Rather, this gets injected by the application. This gives a new span.
+
+ Note this carries state -- the top level span count. This is important for the sequence id
+ at the root level.
+
+ :param action: Action name
+ :param lifecycle_adapters: Lifecycle adapters
+ :param _context_var: Context var to use for the action span
+ """
+ self.action = action
+ self.lifecycle_adapters = lifecycle_adapters
+ self.context_var = _context_var
+ self.top_level_span_count = 0
+ self.action_sequence_id = sequence_id
+
+ def __call__(
+ self, span_name: str, span_dependencies: Optional[List[str]] = None
+ ) -> ActionSpanTracer:
+ if self.context_var.get() is None:
+ self.top_level_span_count += 1
+ return ActionSpanTracer(
+ action=self.action,
+ action_sequence_id=self.action_sequence_id,
+ span_name=span_name,
+ lifecycle_adapters=self.lifecycle_adapters,
+ span_dependencies=span_dependencies,
+ context_var=self.context_var,
+ top_level_span_count=self.top_level_span_count,
+ )
diff --git a/tests/visibility/test_tracing.py b/tests/visibility/test_tracing.py
new file mode 100644
index 00000000..572643c7
--- /dev/null
+++ b/tests/visibility/test_tracing.py
@@ -0,0 +1,346 @@
+import asyncio
+from contextvars import ContextVar
+from typing import Any, Optional
+
+from burr.lifecycle.base import (
+ PostEndSpanHook,
+ PostEndSpanHookAsync,
+ PreStartSpanHook,
+ PreStartSpanHookAsync,
+)
+from burr.lifecycle.internal import LifecycleAdapterSet
+from burr.visibility.tracing import ActionSpan, TracerFactory
+
+# There are a lot of state-specific assertions in this file
+# We try to comment them. We should also probably organize them to be
+# smaller and test specific things, but this is easier to validate for now
+
+
+def test_action_span_tracer_correct_span_count(request):
+ context_var: ContextVar[Optional[ActionSpan]] = ContextVar(
+ request.node.name,
+ default=None,
+ )
+ tracer_factory = TracerFactory(
+ action="test_action",
+ sequence_id=0,
+ lifecycle_adapters=LifecycleAdapterSet(),
+ _context_var=context_var,
+ )
+ assert context_var.get() is None # nothing to start
+ assert tracer_factory.top_level_span_count == 0 # and thus no top-level spans
+
+ with tracer_factory("0") as span_0:
+ assert span_0.span_name == "0" # span name should match the factory call
+ context = context_var.get()
+ assert context is not None # context is now set as we entered the manager
+ assert context.child_count == 0 # no children yet
+ assert context.action == "test_action" # action name should match the factory
+ assert context.parent is None # one of the top-level/roots
+ assert context.sequence_id == 0 # first one
+
+ context = context_var.get()
+ assert context is None # context is now unset
+ assert tracer_factory.top_level_span_count == 1 # we have one now
+
+
+async def test_action_span_tracer_correct_span_count_async(request):
+ context_var: ContextVar[Optional[ActionSpan]] = ContextVar(
+ request.node.name,
+ default=None,
+ )
+ tracer_factory = TracerFactory(
+ action="test_action",
+ sequence_id=0,
+ lifecycle_adapters=LifecycleAdapterSet(),
+ _context_var=context_var,
+ )
+ assert context_var.get() is None # nothing to start
+ assert tracer_factory.top_level_span_count == 0 # and thus no top-level spans
+
+ async with tracer_factory("0") as span_0:
+ assert span_0.span_name == "0" # span name should match the factory call
+ context = context_var.get()
+ assert context is not None # context is now set as we entered the manager
+ assert context.child_count == 0 # no children yet
+ assert context.action == "test_action" # action name should match the factory
+ assert context.parent is None # one of the top-level/roots
+ assert context.sequence_id == 0 # first one
+
+ context = context_var.get()
+ assert context is None # context is now unset
+ assert tracer_factory.top_level_span_count == 1 # we have one now
+
+
+def test_action_span_tracer_correct_span_count_nested(request):
+ context_var: ContextVar[Optional[ActionSpan]] = ContextVar(
+ request.node.name,
+ default=None,
+ )
+ tracer_factory = TracerFactory(
+ action="test_action",
+ sequence_id=0,
+ lifecycle_adapters=LifecycleAdapterSet(),
+ _context_var=context_var,
+ )
+
+ with tracer_factory("0") as outside_span_0:
+ with tracer_factory("0.0"):
+ context = context_var.get()
+ assert context.child_count == 0 # no children
+ assert context.parent.name == outside_span_0.span_name # one of the top-level/roots
+ assert context.sequence_id == 0 # first one
+
+ with tracer_factory("0.1"):
+ context = context_var.get()
+ assert context.sequence_id == 1 # this is the second one
+
+ assert outside_span_0.top_level_span_count == 1 # we only have one top-level span
+
+ context = context_var.get()
+ assert context.child_count == 2 # two children we spawned above
+ assert context.name == outside_span_0.span_name # we're back to the outside span
+
+ with tracer_factory("1") as outside_span_1:
+ assert outside_span_1.top_level_span_count == 2 # now we have another
+ assert tracer_factory.top_level_span_count == 2 # the tracer factory holds state
+
+ context = context_var.get()
+ assert context is None # context gets reset at the end
+
+
+async def test_action_span_tracer_correct_span_count_nested_async(request):
+ context_var: ContextVar[Optional[ActionSpan]] = ContextVar(
+ request.node.name,
+ default=None,
+ )
+ tracer_factory = TracerFactory(
+ action="test_action",
+ sequence_id=0,
+ lifecycle_adapters=LifecycleAdapterSet(),
+ _context_var=context_var,
+ )
+
+ async with tracer_factory("0") as outside_span_0:
+ async with tracer_factory("0.0"):
+ context = context_var.get()
+ assert context.child_count == 0 # no children
+ assert context.parent.name == outside_span_0.span_name # one of the top-level/roots
+ assert context.sequence_id == 0 # first one
+
+ async with tracer_factory("0.1"):
+ context = context_var.get()
+ assert context.sequence_id == 1 # this is the second one
+
+ assert outside_span_0.top_level_span_count == 1 # we only have one top-level span
+
+ context = context_var.get()
+ assert context.child_count == 2 # two children we spawned above
+ assert context.name == outside_span_0.span_name # we're back to the outside span
+
+ async with tracer_factory("1") as outside_span_1:
+ assert outside_span_1.top_level_span_count == 2 # now we have another
+ assert tracer_factory.top_level_span_count == 2 # the tracer factory holds state
+
+ context = context_var.get()
+ assert context is None # context gets reset at the end
+
+
+def test_action_span_spawn():
+ action_span = ActionSpan.create_initial("test_action", "0", 0, action_sequence_id=0)
+ assert action_span.parent is None # this is the top-level span
+ spawned_0 = action_span.spawn("0.0")
+ assert spawned_0.sequence_id == 0
+ assert spawned_0.parent is action_span # this is a child of the top-level span
+ spawned_1 = action_span.spawn("0.1") # another child
+ assert spawned_1.sequence_id == 1
+ assert action_span.child_count == 2
+ assert action_span.sequence_id == 0
+
+
+def test_pre_span_lifecycle_hooks_called(request):
+ class TrackingHook(PreStartSpanHook, PostEndSpanHook):
+ def __init__(self):
+ self.uids_pre = []
+ self.uids_post = []
+
+ def pre_start_span(
+ self,
+ *,
+ span: "ActionSpan",
+ **future_kwargs: Any,
+ ):
+ self.uids_pre.append(span.uid)
+
+ def post_end_span(
+ self,
+ *,
+ span: "ActionSpan",
+ **future_kwargs: Any,
+ ):
+ self.uids_post.append(span.uid)
+
+ hook = TrackingHook()
+ adapter_set = LifecycleAdapterSet(hook)
+ context_var: ContextVar[Optional[ActionSpan]] = ContextVar(request.node.name, default=None)
+ tracer_factory_0 = TracerFactory(
+ action="test_action",
+ sequence_id=0,
+ lifecycle_adapters=adapter_set,
+ _context_var=context_var,
+ )
+ # 0:0
+ with tracer_factory_0("0"):
+ # 0:0.0
+ with tracer_factory_0("0.0"):
+ pass
+ # 0:0.1
+ with tracer_factory_0("0.1"):
+ pass
+ # 0:1
+ with tracer_factory_0("1"):
+ # 0:1.0
+ with tracer_factory_0("1.0"):
+ # 0:1.0.0
+ with tracer_factory_0("1.0.0"):
+ pass
+ # 0:1.0.1
+ with tracer_factory_0("1.0.1"):
+ pass
+ tracer_factory_1 = TracerFactory(
+ action="test_action",
+ sequence_id=tracer_factory_0.action_sequence_id + 1,
+ lifecycle_adapters=adapter_set,
+ _context_var=context_var,
+ )
+ # 1:0
+ with tracer_factory_1("2"):
+ # 1:0.0
+ with tracer_factory_1("2.0"):
+ pass
+ # 1:0.1
+ with tracer_factory_1("2.1"):
+ pass
+
+ # order of this is exactly as expected -- in order traversal
+ assert hook.uids_pre == [
+ "0:0",
+ "0:0.0",
+ "0:0.1",
+ "0:1",
+ "0:1.0",
+ "0:1.0.0",
+ "0:1.0.1",
+ "1:0",
+ "1:0.0",
+ "1:0.1",
+ ]
+
+ # order of this is a little trickier -- the containing span closes at the end so its post-order traversal
+ assert hook.uids_post == [
+ "0:0.0",
+ "0:0.1",
+ "0:0",
+ "0:1.0.0",
+ "0:1.0.1",
+ "0:1.0",
+ "0:1",
+ "1:0.0",
+ "1:0.1",
+ "1:0",
+ ]
+
+
+async def test_pre_span_lifecycle_hooks_called_async(request):
+ class AsyncTrackingHook(PreStartSpanHookAsync, PostEndSpanHookAsync):
+ def __init__(self):
+ self.uids_pre = []
+ self.uids_post = []
+
+ async def pre_start_span(
+ self,
+ *,
+ span: "ActionSpan",
+ **future_kwargs: Any,
+ ):
+ await asyncio.sleep(0.01)
+ self.uids_pre.append(span.uid)
+
+ async def post_end_span(
+ self,
+ *,
+ span: "ActionSpan",
+ **future_kwargs: Any,
+ ):
+ await asyncio.sleep(0.01)
+ self.uids_post.append(span.uid)
+
+ hook = AsyncTrackingHook()
+ adapter_set = LifecycleAdapterSet(hook)
+ context_var: ContextVar[Optional[ActionSpan]] = ContextVar(request.node.name, default=None)
+ tracer_factory_0 = TracerFactory(
+ action="test_action",
+ sequence_id=0,
+ lifecycle_adapters=adapter_set,
+ _context_var=context_var,
+ )
+ # 0:0
+ async with tracer_factory_0("0"):
+ # 0:0.0
+ async with tracer_factory_0("0.0"):
+ pass
+ # 0:0.1
+ async with tracer_factory_0("0.1"):
+ pass
+ # 0:1
+ async with tracer_factory_0("1"):
+ # 0:1.0
+ async with tracer_factory_0("1.0"):
+ # 0:1.0.0
+ async with tracer_factory_0("1.0.0"):
+ pass
+ # 0:1.0.1
+ async with tracer_factory_0("1.0.1"):
+ pass
+ tracer_factory_1 = TracerFactory(
+ action="test_action",
+ sequence_id=tracer_factory_0.action_sequence_id + 1,
+ lifecycle_adapters=adapter_set,
+ _context_var=context_var,
+ )
+ # 1:0
+ async with tracer_factory_1("2"):
+ # 1:0.0
+ async with tracer_factory_1("2.0"):
+ pass
+ # 1:0.1
+ async with tracer_factory_1("2.1"):
+ pass
+
+ # order of this is exactly as expected -- in order traversal
+ assert hook.uids_pre == [
+ "0:0",
+ "0:0.0",
+ "0:0.1",
+ "0:1",
+ "0:1.0",
+ "0:1.0.0",
+ "0:1.0.1",
+ "1:0",
+ "1:0.0",
+ "1:0.1",
+ ]
+
+ # order of this is a little trickier -- the containing span closes at the end so its post-order traversal
+ assert hook.uids_post == [
+ "0:0.0",
+ "0:0.1",
+ "0:0",
+ "0:1.0.0",
+ "0:1.0.1",
+ "0:1.0",
+ "0:1",
+ "1:0.0",
+ "1:0.1",
+ "1:0",
+ ]