|
| 1 | +"""Carries the caller-supplied ``end_user_id`` from a workflow into its activities. |
| 2 | +
|
| 3 | +For Temporal agents the ACP server only *starts* the workflow; the work runs in a |
| 4 | +separate worker process, so a contextvar set at the ACP boundary never reaches the |
| 5 | +code that creates spans. The value does survive that hop inside the workflow start |
| 6 | +args and signal payloads, which is where the workflow-inbound half harvests it |
| 7 | +from. Spans created by workflow code are covered too, since those dispatch through |
| 8 | +a ``START_SPAN`` activity and so pass through the same activity-inbound hop. |
| 9 | +
|
| 10 | +Replay-safe: headers are derived only from start/signal args, with no clock or I/O. |
| 11 | +
|
| 12 | +Registered by default in ``AgentexWorker``; ``AGENTEX_DISABLE_TRACE_BAGGAGE`` |
| 13 | +(``1``/``true``/``yes``/``on``) disables it. |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import os |
| 19 | +from typing import Any, override |
| 20 | + |
| 21 | +from temporalio import workflow |
| 22 | +from temporalio.worker import ( |
| 23 | + Interceptor, |
| 24 | + HandleSignalInput, |
| 25 | + StartActivityInput, |
| 26 | + ExecuteActivityInput, |
| 27 | + ExecuteWorkflowInput, |
| 28 | + StartLocalActivityInput, |
| 29 | + ActivityInboundInterceptor, |
| 30 | + WorkflowInboundInterceptor, |
| 31 | + WorkflowOutboundInterceptor, |
| 32 | +) |
| 33 | +from temporalio.converter import default |
| 34 | + |
| 35 | +from agentex.lib.utils.logging import make_logger |
| 36 | +from agentex.lib.core.tracing.baggage import set_end_user_id, reset_end_user_id |
| 37 | + |
| 38 | +logger = make_logger(__name__) |
| 39 | + |
| 40 | +END_USER_ID_HEADER = "agentex-end-user-id" |
| 41 | +_WORKFLOW_ATTR = "_agentex_end_user_id" |
| 42 | +DISABLE_TRACE_BAGGAGE_ENV = "AGENTEX_DISABLE_TRACE_BAGGAGE" |
| 43 | + |
| 44 | + |
| 45 | +def trace_baggage_disabled() -> bool: |
| 46 | + raw = os.environ.get(DISABLE_TRACE_BAGGAGE_ENV, "").strip().lower() |
| 47 | + return raw in ("1", "true", "yes", "on") |
| 48 | + |
| 49 | + |
| 50 | +def _extract_end_user_id(arg: Any) -> str | None: |
| 51 | + # Args arrive as the params model or as its dumped dict, depending on how the |
| 52 | + # caller serialized them. |
| 53 | + if arg is None: |
| 54 | + return None |
| 55 | + value = arg.get("end_user_id") if isinstance(arg, dict) else getattr(arg, "end_user_id", None) |
| 56 | + return value if isinstance(value, str) and value else None |
| 57 | + |
| 58 | + |
| 59 | +class TraceBaggageInterceptor(Interceptor): |
| 60 | + """Threads the caller-supplied end user from workflow start args to activities.""" |
| 61 | + |
| 62 | + def __init__(self) -> None: |
| 63 | + self._payload_converter = default().payload_converter |
| 64 | + |
| 65 | + @override |
| 66 | + def intercept_activity(self, next: ActivityInboundInterceptor) -> ActivityInboundInterceptor: |
| 67 | + return _TraceBaggageActivityInboundInterceptor(next, self._payload_converter) |
| 68 | + |
| 69 | + @override |
| 70 | + def workflow_interceptor_class(self, input: Any) -> type[WorkflowInboundInterceptor] | None: # noqa: ARG002 |
| 71 | + return _TraceBaggageWorkflowInboundInterceptor |
| 72 | + |
| 73 | + |
| 74 | +class _TraceBaggageWorkflowInboundInterceptor(WorkflowInboundInterceptor): |
| 75 | + """Harvests the end user off inbound workflow args and signal args.""" |
| 76 | + |
| 77 | + @override |
| 78 | + async def execute_workflow(self, input: ExecuteWorkflowInput) -> Any: |
| 79 | + self._stash(input.args[0] if input.args else None) |
| 80 | + return await self.next.execute_workflow(input) |
| 81 | + |
| 82 | + @override |
| 83 | + async def handle_signal(self, input: HandleSignalInput) -> None: |
| 84 | + # Signals (e.g. event/send) carry their own end user, which may differ |
| 85 | + # from the one that created the task. Last one in wins so the activities |
| 86 | + # a signal triggers are attributed to the caller that triggered them. |
| 87 | + self._stash(input.args[0] if input.args else None) |
| 88 | + return await self.next.handle_signal(input) |
| 89 | + |
| 90 | + def _stash(self, arg: Any) -> None: |
| 91 | + end_user_id = _extract_end_user_id(arg) |
| 92 | + if end_user_id is None: |
| 93 | + return |
| 94 | + try: |
| 95 | + setattr(workflow.instance(), _WORKFLOW_ATTR, end_user_id) |
| 96 | + except Exception as exc: |
| 97 | + logger.debug(f"Could not stash end_user_id on the workflow instance: {exc}") |
| 98 | + |
| 99 | + @override |
| 100 | + def init(self, outbound: WorkflowOutboundInterceptor) -> None: |
| 101 | + self.next.init(_TraceBaggageWorkflowOutboundInterceptor(outbound, default().payload_converter)) |
| 102 | + |
| 103 | + |
| 104 | +class _TraceBaggageWorkflowOutboundInterceptor(WorkflowOutboundInterceptor): |
| 105 | + """Copies the stashed end user into activity headers.""" |
| 106 | + |
| 107 | + def __init__(self, next: WorkflowOutboundInterceptor, payload_converter: Any) -> None: |
| 108 | + super().__init__(next) |
| 109 | + self._payload_converter = payload_converter |
| 110 | + |
| 111 | + @override |
| 112 | + def start_activity(self, input: StartActivityInput) -> workflow.ActivityHandle[Any]: |
| 113 | + self._add_header(input) |
| 114 | + return self.next.start_activity(input) |
| 115 | + |
| 116 | + @override |
| 117 | + def start_local_activity(self, input: StartLocalActivityInput) -> workflow.ActivityHandle[Any]: |
| 118 | + self._add_header(input) |
| 119 | + return self.next.start_local_activity(input) |
| 120 | + |
| 121 | + def _add_header(self, input: StartActivityInput | StartLocalActivityInput) -> None: |
| 122 | + try: |
| 123 | + end_user_id = getattr(workflow.instance(), _WORKFLOW_ATTR, None) |
| 124 | + if not end_user_id: |
| 125 | + return |
| 126 | + headers = dict(input.headers or {}) |
| 127 | + headers[END_USER_ID_HEADER] = self._payload_converter.to_payload(end_user_id) |
| 128 | + input.headers = headers |
| 129 | + except Exception as exc: |
| 130 | + logger.debug(f"Could not add end_user_id to activity headers: {exc}") |
| 131 | + |
| 132 | + |
| 133 | +class _TraceBaggageActivityInboundInterceptor(ActivityInboundInterceptor): |
| 134 | + """Decodes the header into the tracing baggage contextvar for the activity.""" |
| 135 | + |
| 136 | + def __init__(self, next: ActivityInboundInterceptor, payload_converter: Any) -> None: |
| 137 | + super().__init__(next) |
| 138 | + self._payload_converter = payload_converter |
| 139 | + |
| 140 | + @override |
| 141 | + async def execute_activity(self, input: ExecuteActivityInput) -> Any: |
| 142 | + end_user_id: str | None = None |
| 143 | + if input.headers and END_USER_ID_HEADER in input.headers: |
| 144 | + try: |
| 145 | + end_user_id = self._payload_converter.from_payload(input.headers[END_USER_ID_HEADER], str) |
| 146 | + except Exception as exc: |
| 147 | + logger.debug(f"Could not decode the end_user_id activity header: {exc}") |
| 148 | + |
| 149 | + if end_user_id is None: |
| 150 | + return await self.next.execute_activity(input) |
| 151 | + |
| 152 | + token = set_end_user_id(end_user_id) |
| 153 | + try: |
| 154 | + return await self.next.execute_activity(input) |
| 155 | + finally: |
| 156 | + reset_end_user_id(token) |
0 commit comments