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 @trace decorator

elijahbenizzy4a994193cafe
diff --git a/burr/core/application.py b/burr/core/application.py
index 219f246a..573a7ee1 100644
--- a/burr/core/application.py
+++ b/burr/core/application.py
@@ -42,8 +42,10 @@ from burr.core.graph import Graph, GraphBuilder
from burr.core.persistence import BaseStateLoader, BaseStateSaver
from burr.core.state import State
from burr.core.validation import BASE_ERROR_MESSAGE
-from burr.lifecycle.base import ExecuteMethod, LifecycleAdapter
+from burr.lifecycle.base import ExecuteMethod, LifecycleAdapter, PostRunStepHook, PreRunStepHook
from burr.lifecycle.internal import LifecycleAdapterSet
+from burr.visibility import tracing
+from burr.visibility.tracing import tracer_factory_context_var
if TYPE_CHECKING:
from burr.tracking.base import TrackingClient
@@ -500,6 +502,56 @@ class _call_execute_method_pre_post:
return wrapper_async if inspect.iscoroutinefunction(fn) else wrapper_sync
+class TracerFactoryContextHook(PreRunStepHook, PostRunStepHook):
+ """Passes the tracer factory into context. This allows us to do out-of-band visibility processing"""
+
+ def __init__(self, adapter_set: LifecycleAdapterSet):
+ self._adapter_set = adapter_set
+ self.token_pointer_map = {}
+
+ def pre_run_step(
+ self,
+ *,
+ app_id: str,
+ partition_key: str,
+ sequence_id: int,
+ state: "State",
+ action: "Action",
+ inputs: Dict[str, Any],
+ **future_kwargs: Any,
+ ):
+ if "__tracer" in inputs:
+ tracer_factory = inputs["__tracer"]
+ else:
+ tracer_factory = tracing.TracerFactory(
+ action=action.name,
+ app_id=app_id,
+ lifecycle_adapters=self._adapter_set,
+ partition_key=partition_key,
+ sequence_id=sequence_id,
+ )
+ assert tracer_factory is not None
+ # TODO -- store token/context manager by app_id, sequence_id
+ self.token_pointer_map[(app_id, sequence_id)] = tracer_factory_context_var.set(
+ tracer_factory
+ )
+
+ def post_run_step(
+ self,
+ *,
+ app_id: str,
+ partition_key: str,
+ sequence_id: int,
+ state: "State",
+ action: "Action",
+ result: Optional[Dict[str, Any]],
+ exception: Exception,
+ **future_kwargs: Any,
+ ):
+ tracer_factory_context_var.reset(self.token_pointer_map[(app_id, sequence_id)])
+ del self.token_pointer_map[(app_id, sequence_id)]
+
+
class Application:
def __init__(
self,
@@ -539,7 +591,8 @@ class Application:
entrypoint=graph.get_action(entrypoint),
)
self._state = state
- self._adapter_set = adapter_set if adapter_set is not None else LifecycleAdapterSet()
+ adapter_set = adapter_set if adapter_set is not None else LifecycleAdapterSet()
+ self._adapter_set = adapter_set.with_new_adapters(TracerFactoryContextHook(adapter_set))
# TODO -- consider adding global inputs + global input factories to the builder
self._tracker = tracker
@@ -547,7 +600,7 @@ class Application:
self._set_sequence_id(sequence_id)
self._builder = builder
self._parent_pointer = fork_parent_pointer
- self.dependency_factory = {
+ self._dependency_factory = {
"__tracer": functools.partial(
visibility.tracing.TracerFactory,
lifecycle_adapters=self._adapter_set,
@@ -697,8 +750,10 @@ class Application:
# if we can find it in the dependency factory, we'll use that
# TODO -- figure out what happens if people attempt to override default factory
# inputs
- if input_ in self.dependency_factory:
- processed_inputs[input_] = self.dependency_factory[input_](action, self.sequence_id)
+ if input_ in self._dependency_factory:
+ processed_inputs[input_] = self._dependency_factory[input_](
+ action, self.sequence_id
+ )
if input_ in missing_inputs:
missing_inputs.remove(input_)
if len(missing_inputs) > 0:
diff --git a/burr/lifecycle/base.py b/burr/lifecycle/base.py
index d256cf88..e5d13115 100644
--- a/burr/lifecycle/base.py
+++ b/burr/lifecycle/base.py
@@ -361,6 +361,7 @@ class PostApplicationExecuteCallHookAsync(abc.ABC):
# strictly for typing -- this conflicts a bit with the lifecycle decorator above, but its fine for now
# This makes IDE completion/type-hinting easier
LifecycleAdapter = Union[
+ DoLogAttributeHook,
PreRunStepHook,
PreRunStepHookAsync,
PostRunStepHook,
diff --git a/burr/lifecycle/internal.py b/burr/lifecycle/internal.py
index 7dc688a6..baa53608 100644
--- a/burr/lifecycle/internal.py
+++ b/burr/lifecycle/internal.py
@@ -104,6 +104,14 @@ class LifecycleAdapterSet:
self._adapters = list(adapters)
self.sync_hooks, self.async_hooks = self._get_lifecycle_hooks()
+ def with_new_adapters(self, *adapters: "LifecycleAdapter") -> "LifecycleAdapterSet":
+ """Adds new adapters to the set.
+
+ :param adapters: Adapters to add
+ :return: A new adapter set with the new adapters
+ """
+ return LifecycleAdapterSet(*self.adapters, *adapters)
+
def _get_lifecycle_hooks(
self,
) -> Tuple[Dict[str, List["LifecycleAdapter"]], Dict[str, List["LifecycleAdapter"]]]:
diff --git a/burr/visibility/__init__.py b/burr/visibility/__init__.py
index b8d7a881..8be3e1c3 100644
--- a/burr/visibility/__init__.py
+++ b/burr/visibility/__init__.py
@@ -1,3 +1,3 @@
-from burr.visibility.tracing import ActionSpan, ActionSpanTracer, TracerFactory
+from burr.visibility.tracing import ActionSpan, ActionSpanTracer, TracerFactory, trace
-__all__ = ["TracerFactory", "ActionSpan", "ActionSpanTracer"]
+__all__ = ["TracerFactory", "ActionSpan", "ActionSpanTracer", "trace"]
diff --git a/burr/visibility/tracing.py b/burr/visibility/tracing.py
index b0c72989..a7e223f4 100644
--- a/burr/visibility/tracing.py
+++ b/burr/visibility/tracing.py
@@ -1,11 +1,17 @@
import dataclasses
+import functools
+import inspect
+import logging
import uuid
from contextlib import AbstractAsyncContextManager, AbstractContextManager
from contextvars import ContextVar
-from typing import Any, List, Optional, Type
+from hashlib import sha256
+from typing import Any, Callable, Dict, List, Optional, Type, TypeVar
from burr.lifecycle.internal import LifecycleAdapterSet
+logger = logging.getLogger(__name__)
+
@dataclasses.dataclass
class ActionSpan:
@@ -281,7 +287,7 @@ class TracerFactory(ActionSpanTracer):
action: str,
sequence_id: int,
app_id: str,
- partition_key: str,
+ partition_key: Optional[str],
lifecycle_adapters: LifecycleAdapterSet,
_context_var: ContextVar[Optional[ActionSpan]] = execution_context_var,
):
@@ -321,3 +327,147 @@ class TracerFactory(ActionSpanTracer):
app_id=self.app_id,
partition_key=self.partition_key,
)
+
+
+FNType = TypeVar("FNType", bound=Callable)
+
+# This is specifically meant to set anything that is "out of band" -- I.E.
+# Through a decorator that does not have access to the parameter
+# This is an internal API that we are liable to change over time
+# This is set by the application on every `step` call
+
+tracer_factory_context_var: ContextVar[Optional[TracerFactory]] = ContextVar(
+ "tracer_context",
+ default=None,
+)
+
+
+class trace:
+ def __init__(
+ self,
+ capture_inputs: bool = True,
+ capture_outputs: bool = True,
+ input_filterlist: Optional[List[str]] = None,
+ span_name: Optional[str] = None,
+ _context_var: ContextVar[Optional[TracerFactory]] = tracer_factory_context_var,
+ ):
+ """trace() can wrap any function and uses the tracer to create a span and log
+ attributes. This also (by default) logs the inputs/outputs of a function as attributes.
+ Be careful not to include sensitive data in the inputs/outputs, but if you do, you have the
+ input_filterlist to exclude it.
+
+ This works with sync/async
+
+ Take the following code:
+
+ .. code-block:: python
+
+ from burr.visibility import trace
+
+ @trace()
+ def call_llm(prompt):
+ return _query(...)
+
+ @trace()
+ def generate_text(prompt: str) -> str:
+ result = call_llm(prompt)
+ return f"<p>{result}</p>"
+
+ @action(reads=["prompt"], writes=["response"])
+ def prompt_action(state: State) -> State:
+ response = generate_text(state["prompt"])
+ return state.update(response=response)
+
+ Every time `prompt_action` is called (within the context of prompt_action), it will generate a trace that looks like the following:
+
+ ------ prompt action --------------------------------------------
+ ----- generate_text -----------------------------------
+ ----- call_llm -----------------------------------
+
+ If it is called outside the context of a Burr action, it will be effectively a no-op.
+
+
+ :param capture_inputs: Whether to capture inputs as attributes (defaults to True).
+ Note that this only works with keyword-argument bindable functions.
+ :param capture_outputs: Whether to capture outputs as attributes (defaults to True)
+ :param input_filterlist: A list of inputs to filter out (defaults to filtering nothing. Use if you have sensitive data)
+ :param span_name: Name of the span, will default to the function name
+ :param _context_var: Context var to use for the tracer factory, used purely for internal testing
+ """
+ self.capture_inputs = capture_inputs
+ self.capture_outputs = capture_outputs
+ self.input_filterlist = input_filterlist or []
+ self.span_name = span_name
+ self.context_var = _context_var
+
+ def _ensure_bind(self, fn, *args, **kwargs) -> Dict[str, Any]:
+ try:
+ bound_params = inspect.signature(fn).bind(*args, **kwargs)
+ except TypeError as e:
+ func_name = fn.__name__
+ raise TypeError(f"{func_name}: {e.args[0]}") from None
+
+ bound_kwargs = bound_params.arguments
+ return bound_kwargs
+
+ def _get_auto_attributes(self, fn: FNType):
+ qualname = fn.__qualname__
+ try:
+ code, *_ = inspect.getsourcelines(fn)
+ code_hash = sha256("".join(code).encode()).hexdigest()
+ except OSError:
+ code_hash = "Unable to retrieve source code for hash"
+ return {"__burr_function": qualname, "__burr_function_hash": code_hash}
+
+ def _log_parameters(self, __action_span_tracer: ActionSpanTracer, bound_aprams):
+ # TODO -- ensure we can serialize this
+ filtered_params = {k: v for k, v in bound_aprams.items() if k not in self.input_filterlist}
+ __action_span_tracer.log_attributes(**filtered_params)
+
+ def _get_span_name(self, fn: FNType) -> str:
+ return self.span_name if self.span_name else fn.__name__
+
+ def __call__(self, fn: FNType) -> FNType:
+ @functools.wraps(fn)
+ def wrapped_fn(*args, **kwargs):
+ tracer_factory = self.context_var.get()
+ if tracer_factory is not None:
+ bound_params = self._ensure_bind(fn, *args, **kwargs)
+ with tracer_factory(self._get_span_name(fn)) as action_span_tracer:
+ if self.capture_inputs:
+ self._log_parameters(action_span_tracer, bound_params)
+ additional_attributes = self._get_auto_attributes(fn)
+ action_span_tracer.log_attributes(**additional_attributes)
+ output = fn(*args, **kwargs)
+ if self.capture_outputs:
+ action_span_tracer.log_attributes(**{"return": output})
+ return output
+ logger.debug(
+ f"Function: {fn.__name__} is decorated with @trace but is not being executed "
+ f"in the context of a Burr action. No tracing will occur."
+ )
+ return fn(*args, **kwargs)
+
+ @functools.wraps(fn)
+ async def awrapped_fn(*args, **kwargs):
+ tracer_factory = self.context_var.get()
+ if tracer_factory is not None:
+ bound_params = self._ensure_bind(fn, *args, **kwargs)
+ with tracer_factory(self._get_span_name(fn)) as action_span_tracer:
+ if self.capture_inputs:
+ self._log_parameters(action_span_tracer, bound_aprams=bound_params)
+ additional_attributes = self._get_auto_attributes(fn)
+ action_span_tracer.log_attributes(**additional_attributes)
+ output = await fn(*args, **kwargs)
+ if self.capture_outputs:
+ action_span_tracer.log_attributes(**{"return": output})
+ return output
+ logger.debug(
+ f"Function: {fn.__name__} is decorated with @trace but is not being executed "
+ f"in the context of a Burr action. No tracing will occur."
+ )
+ return await fn(*args, **kwargs)
+
+ if inspect.iscoroutinefunction(fn):
+ return awrapped_fn
+ return wrapped_fn
diff --git a/docs/concepts/additional-visibility.rst b/docs/concepts/additional-visibility.rst
index 8d43e64e..f6638736 100644
--- a/docs/concepts/additional-visibility.rst
+++ b/docs/concepts/additional-visibility.rst
@@ -138,6 +138,65 @@ Note that we are currently building out the capability to wrap a class and "auto
You can read more in the :ref:`reference documentation <visibility>`.
+
+-----------------
+Tracing Functions
+-----------------
+
+You can observe non-burr functions, which will show up as part of your traces. To do this, you simply need to decorate the
+function with the :py:func:`@trace <burr.visibility.tracing.trace>` decorator. This will automatically create a span
+for the function (within the approprite context), and log as attributes the parameters + return value.
+
+For instance:
+
+.. code-block:: python
+
+ from burr.visibility import trace
+
+ @trace
+ def _modify_prompt(prompt: str) -> str:
+ return ...
+
+ @trace
+ def _fix(prompt: str) -> str:
+ return ...
+
+ @trace
+ def _query(prompt: str) -> Response:
+ return ...
+
+ from burr.core import action
+ @action(reads=['prompt'], writes=['response'])
+ def my_action(state: State, __tracer: TracingFactory) -> State:
+ modified_prompt = _modify_prompt(state["prompt"])
+ if _is_unsafe(modified_prompt):
+ modified_prompt = _fix(modified_prompt)
+ response = _query(prompt=modified_prompt)
+ return state.update({'response': response})
+
+
+This will create spans for the ``_modify_prompt``, ``_fix``, and ``_query`` functions, and log the parameters and return values. You can opt out of logging paramers or return values and adding a filter to the decorator to exclude certain parameters.
+To contrast what you can instrument manually, the ``@trace`` decorator allows you to get more visibility and replace manual code such as the following (though you can happily combine the two approaches):
+
+.. code-block:: python
+
+ from burr.visibility import TracingFactory
+ from burr.core import action
+ @action(reads=['prompt'], writes=['response'])
+ def my_action(state: State, __tracer: TracingFactory) -> State:
+ with __tracer('create_prompt'):
+ modified_prompt = _modify_prompt(state["prompt"])
+ with __tracer('check_prompt_safety'):
+ if _is_unsafe(modified_prompt):
+ modified_prompt = _fix(modified_prompt)
+ with __tracer('call_llm', dependencies=['create_prompt']):
+ response = _query(prompt=modified_prompt)
+ return state.update({'response': response})
+
+
+This will create spans for the ``_modify_prompt``, ``_fix``, and ``_query`` functions, and log the parameters and return values.
+You can opt out of logging paramers or return values and adding a filter to the decorator to exclude certain parameters.
+
.. _opentelref:
--------------
diff --git a/docs/reference/visibility.rst b/docs/reference/visibility.rst
index e707ebc2..1e9db05c 100644
--- a/docs/reference/visibility.rst
+++ b/docs/reference/visibility.rst
@@ -8,11 +8,15 @@ Tracing Inside Actions
Tooling for gaining visibility inside actions. You will never instantiate these directly,
they are all injected by the framework. This is purely for reference.
-.. autoclass:: burr.visibility.TracerFactory
+.. autoclass:: burr.visibility.tracing.TracerFactory
:members:
-.. autoclass:: burr.visibility.ActionSpanTracer
+.. autoclass:: burr.visibility.tracing.ActionSpanTracer
:members:
-.. autoclass:: burr.visibility.ActionSpan
+
+.. autoclass:: burr.visibility.tracing.ActionSpan
:members:
+
+.. autoclass:: burr.visibility.tracing.trace
+ :special-members: __init__
diff --git a/tests/visibility/test_tracing.py b/tests/visibility/test_tracing.py
index 3d63c210..365cf60b 100644
--- a/tests/visibility/test_tracing.py
+++ b/tests/visibility/test_tracing.py
@@ -10,6 +10,7 @@ from burr.lifecycle.base import (
PreStartSpanHookAsync,
)
from burr.lifecycle.internal import LifecycleAdapterSet
+from burr.visibility import tracing
from burr.visibility.tracing import ActionSpan, TracerFactory
# There are a lot of state-specific assertions in this file
@@ -17,6 +18,10 @@ from burr.visibility.tracing import ActionSpan, TracerFactory
# smaller and test specific things, but this is easier to validate for now
+def is_subset(dict_subset, dict_full):
+ return all(item in dict_full.items() for item in dict_subset.items())
+
+
def test_action_span_tracer_correct_span_count(request):
context_var: ContextVar[Optional[ActionSpan]] = ContextVar(
request.node.name,
@@ -363,25 +368,26 @@ async def test_pre_span_lifecycle_hooks_called_async(request):
]
-async def test_log_attributes_called(request):
- class AttributeHook(DoLogAttributeHook):
- def do_log_attributes(
- self,
- *,
- attributes: Dict[str, Any],
- action: str,
- action_sequence_id: int,
- span: Optional["ActionSpan"],
- tags: dict,
- **future_kwargs: Any,
- ):
- self.artifacts.append(
- (attributes, action, action_sequence_id, span.uid if span is not None else None)
- )
+class AttributeHook(DoLogAttributeHook):
+ def do_log_attributes(
+ self,
+ *,
+ attributes: Dict[str, Any],
+ action: str,
+ action_sequence_id: int,
+ span: Optional["ActionSpan"],
+ tags: dict,
+ **future_kwargs: Any,
+ ):
+ self.attributes.append(
+ (attributes, action, action_sequence_id, span.uid if span is not None else None)
+ )
+
+ def __init__(self):
+ self.attributes = []
- def __init__(self):
- self.artifacts = []
+async def test_log_attributes_called(request):
hook = AttributeHook()
adapter_set = LifecycleAdapterSet(hook)
context_var: ContextVar[Optional[ActionSpan]] = ContextVar(request.node.name, default=None)
@@ -438,7 +444,7 @@ async def test_log_attributes_called(request):
pass
# order of this is exactly as expected -- in order traversal
- assert hook.artifacts == [
+ assert hook.attributes == [
({"key": "root:0"}, "test_action", 0, None),
({"key": "0:0"}, "test_action", 0, "0:0"),
({"key": "0.0:0"}, "test_action", 0, "0:0.0"),
@@ -453,3 +459,189 @@ async def test_log_attributes_called(request):
({"key": "1.0.1:0"}, "test_action", 0, "0:1.0.1"),
({"key": "1.0.1:1"}, "test_action", 0, "0:1.0.1"),
]
+
+
+def test_trace_decorator_single_fn(request):
+ # Mock an action span context var
+ # This is set by the tracer factory, which uses the default in tracing
+ # This is so we know the current (context aware) span
+ context_var: ContextVar[Optional[ActionSpan]] = ContextVar(
+ request.node.name,
+ default=None,
+ )
+ # Mock a tracer factory context var
+ # This is set usually by the application so the decorator knows what to get
+ tracer_factory_context_var = ContextVar[TracerFactory](
+ request.node.name + "_tracer", default=None
+ )
+ # Create a hook so we can wire it through and ensure the right thing gets called
+ hook = AttributeHook()
+ adapter_set = LifecycleAdapterSet(hook)
+
+ # Create and set the var to a tracer factory that is context-aware
+ tracer_factory = TracerFactory(
+ action="test_action",
+ sequence_id=0,
+ lifecycle_adapters=adapter_set,
+ _context_var=context_var,
+ app_id="test_app_id",
+ partition_key=None,
+ )
+ tracer_factory_context_var.set(tracer_factory)
+ # Nothing set now
+ assert context_var.get() is None # nothing to start
+ assert tracer_factory.top_level_span_count == 0 # and thus no top-level spans
+ # Instantiate a decorator that will set the action span when it enters, and unset once it leaves
+ decorator = tracing.trace(
+ _context_var=tracer_factory_context_var, input_filterlist=["filtered_out"]
+ )
+
+ # Then the function can assert things for us
+ # We ensure it gets called by checking the output
+ def foo(a: int, b: int, filtered_out: str = "not_present") -> int:
+ action_span_context = context_var.get()
+ assert action_span_context is not None # context is now set as we entered the manager
+ assert action_span_context.name == foo.__name__ # span name should match the function name
+ assert action_span_context.child_count == 0 # no children (now)
+ return a + b
+
+ decorated_foo = decorator(foo)
+ result = decorated_foo(1, 2)
+ assert result == 3
+ assert is_subset({"a": 1, "b": 2}, hook.attributes[0][0])
+ assert is_subset({"return": 3}, hook.attributes[2][0])
+
+
+async def test_trace_decorator_single_fn_async(request):
+ context_var: ContextVar[Optional[ActionSpan]] = ContextVar(
+ request.node.name,
+ default=None,
+ )
+ tracer_factory_context_var = ContextVar[TracerFactory](
+ request.node.name + "_tracer", default=None
+ )
+ hook = AttributeHook()
+ adapter_set = LifecycleAdapterSet(hook)
+
+ tracer_factory = TracerFactory(
+ action="test_action",
+ sequence_id=0,
+ lifecycle_adapters=adapter_set,
+ _context_var=context_var,
+ app_id="test_app_id",
+ partition_key=None,
+ )
+ tracer_factory_context_var.set(tracer_factory)
+ assert context_var.get() is None # nothing to start
+ assert tracer_factory.top_level_span_count == 0 # and thus no top-level spans
+ decorator = tracing.trace(
+ _context_var=tracer_factory_context_var, input_filterlist=["filtered_out"]
+ )
+
+ async def foo(a: int, b: int, filtered_out: str = "not_present") -> int:
+ action_span_context = context_var.get()
+ assert action_span_context is not None # context is now set as we entered the manager
+ assert action_span_context.name == foo.__name__ # span name should match the function name
+ assert action_span_context.child_count == 0 # no children (now)
+ await asyncio.sleep(0.001)
+ return a + b
+
+ decorated_foo = decorator(foo)
+ result = await decorated_foo(1, 2)
+ assert result == 3
+ assert is_subset({"a": 1, "b": 2}, hook.attributes[0][0])
+ assert is_subset({"return": 3}, hook.attributes[2][0])
+
+
+def test_trace_decorator_recursive(request):
+ context_var: ContextVar[Optional[ActionSpan]] = ContextVar(
+ request.node.name,
+ default=None,
+ )
+ hook = AttributeHook()
+ tracer_factory_context_var = ContextVar[TracerFactory](
+ request.node.name + "_tracer", default=None
+ )
+ tracer_factory = TracerFactory(
+ action="test_action",
+ sequence_id=0,
+ lifecycle_adapters=LifecycleAdapterSet(hook),
+ _context_var=context_var,
+ app_id="test_app_id",
+ partition_key=None,
+ )
+ tracer_factory_context_var.set(tracer_factory)
+ assert context_var.get() is None # nothing to start
+ assert tracer_factory.top_level_span_count == 0 # and thus no top-level spans
+ decorator = tracing.trace(_context_var=tracer_factory_context_var)
+
+ @decorator
+ def foo(a: int, b: int) -> int:
+ action_span_context = context_var.get()
+ assert action_span_context is not None # context is now set as we entered the manager
+ assert action_span_context.name == foo.__name__ # span name should match the function name
+ return bar(a + 1, a + b) + a + b
+
+ @decorator
+ def bar(a: int, b: int) -> int:
+ action_span_context = context_var.get()
+ assert action_span_context is not None # context is now set as we entered the manager
+ assert action_span_context.name == bar.__name__ # span name should match the function name
+ assert action_span_context.child_count == 0 # no children (now)
+ assert action_span_context.parent.name == foo.__name__ # parent should be foo
+ return a * b
+
+ result = foo(1, 2)
+ assert result == 9
+ assert is_subset({"a": 1, "b": 2}, hook.attributes[0][0])
+ assert is_subset({"a": 2, "b": 3}, hook.attributes[2][0])
+ assert is_subset({"return": 6}, hook.attributes[4][0])
+ assert is_subset({"return": 9}, hook.attributes[5][0])
+
+
+async def test_trace_decorator_recursive_async(request):
+ context_var: ContextVar[Optional[ActionSpan]] = ContextVar(
+ request.node.name,
+ default=None,
+ )
+ hook = AttributeHook()
+ tracer_factory_context_var = ContextVar[TracerFactory](
+ request.node.name + "_tracer", default=None
+ )
+ tracer_factory = TracerFactory(
+ action="test_action",
+ sequence_id=0,
+ lifecycle_adapters=LifecycleAdapterSet(hook),
+ _context_var=context_var,
+ app_id="test_app_id",
+ partition_key=None,
+ )
+ tracer_factory_context_var.set(tracer_factory)
+ assert context_var.get() is None # nothing to start
+ assert tracer_factory.top_level_span_count == 0 # and thus no top-level spans
+ decorator = tracing.trace(_context_var=tracer_factory_context_var)
+
+ @decorator
+ async def foo(a: int, b: int) -> int:
+ action_span_context = context_var.get()
+ assert action_span_context is not None # context is now set as we entered the manager
+ assert action_span_context.name == foo.__name__ # span name should match the function name
+ await asyncio.sleep(0.001)
+ return await bar(a + 1, a + b) + a + b
+
+ @decorator
+ async def bar(a: int, b: int) -> int:
+ action_span_context = context_var.get()
+ assert action_span_context is not None # context is now set as we entered the manager
+ assert action_span_context.name == bar.__name__ # span name should match the function name
+ assert action_span_context.child_count == 0 # no children (now)
+ assert action_span_context.parent.name == foo.__name__ # parent should be foo
+ await asyncio.sleep(0.001)
+ return a * b
+
+ result = await foo(1, 2)
+ assert result == 9
+ assert is_subset({"a": 1, "b": 2}, hook.attributes[0][0])
+ assert is_subset({"a": 2, "b": 3}, hook.attributes[2][0])
+ assert is_subset({"return": 6}, hook.attributes[4][0])
+ assert is_subset({"return": 9}, hook.attributes[5][0])