:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(max-ai): instrument conversations api with otel spans (#59815)
Paul D'Ambrac7f27d8074ba
diff --git a/ee/hogai/core/agent_modes/executables.py b/ee/hogai/core/agent_modes/executables.pyindex 287482db07f7..8837c1b5cfce 100644--- a/ee/hogai/core/agent_modes/executables.py+++ b/ee/hogai/core/agent_modes/executables.py@@ -469,13 +469,25 @@ class AgentToolsExecutable(BaseAgentLoopExecutable):)try:- result = await tool.ainvoke(- ToolCall(type="tool_call", name=tool_call.name, args=tool_call.args, id=tool_call.id), config=config- )- if not isinstance(result, LangchainToolMessage):- raise ValueError(- f"Tool '{tool_call.name}' returned {type(result).__name__}, expected LangchainToolMessage"+ # tool_call.id is typed as str|None in some LangChain shapes; OTel rejects None+ # attribute values with a warning, so include the id only when present.+ tool_span_attributes: dict[str, str | int] = {+ "posthog_ai.tool_name": tool_call.name,+ "posthog_ai.team_id": self._team.id,+ }+ if tool_call.id is not None:+ tool_span_attributes["posthog_ai.tool_call_id"] = tool_call.id+ with _tracer.start_as_current_span("posthog_ai.tool.invoke", attributes=tool_span_attributes):+ result = await tool.ainvoke(+ ToolCall(type="tool_call", name=tool_call.name, args=tool_call.args, id=tool_call.id),+ config=config,)+ # Keep the type-mismatch raise inside the span so OTel records the exception+ # on the tool.invoke span rather than on its (unrelated) parent.+ if not isinstance(result, LangchainToolMessage):+ raise ValueError(+ f"Tool '{tool_call.name}' returned {type(result).__name__}, expected LangchainToolMessage"+ )# Track successful tool executionuser_distinct_id = self._get_user_distinct_id(config)diff --git a/ee/hogai/core/executor.py b/ee/hogai/core/executor.pyindex dffbf10aed68..5b173f4e6784 100644--- a/ee/hogai/core/executor.py+++ b/ee/hogai/core/executor.py@@ -8,6 +8,7 @@ from django.conf import settingsimport structlogimport posthoganalytics+from opentelemetry import tracefrom prometheus_client import Histogramfrom temporalio.client import WorkflowExecutionStatus, WorkflowHandlefrom temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy@@ -35,6 +36,7 @@ from ee.hogai.utils.types import AssistantOutputfrom ee.models.assistant import Conversationlogger = structlog.get_logger(__name__)+_tracer = trace.get_tracer(__name__)STREAM_DJANGO_EVENT_LOOP_LATENCY_HISTOGRAM = Histogram("posthog_ai_stream_django_event_loop_latency_seconds",@@ -85,23 +87,40 @@ class AgentExecutor:async def start_workflow(self, workflow: type[AgentBaseWorkflow], inputs: Any) -> AsyncGenerator[AssistantOutput, Any]:- try:- # Delete the stream to ensure we start fresh- # since there might be a stale stream from a previous conversation gone wrong- await self._redis_stream.delete_stream()+ # Capture the failure outcome inside the span and yield outside it — yielding from+ # an async generator while a span is "current" leaks that span into the consumer+ # task's contextvars. See stream_conversation for the longer note.+ failed = False+ with _tracer.start_as_current_span(+ "posthog_ai.executor.start_workflow",+ attributes={+ "posthog_ai.conversation_id": str(self._conversation.id),+ "posthog_ai.workflow_id": self._workflow_id,+ "posthog_ai.workflow_class": workflow.__name__,+ },+ ):+ try:+ # Delete the stream to ensure we start fresh+ # since there might be a stale stream from a previous conversation gone wrong+ with _tracer.start_as_current_span("posthog_ai.executor.delete_stale_stream"):+ await self._redis_stream.delete_stream()- client = await async_connect()+ with _tracer.start_as_current_span("posthog_ai.executor.temporal_connect"):+ client = await async_connect()- handle = await self._start_workflow_with_retry(client, workflow, inputs)+ handle = await self._start_workflow_with_retry(client, workflow, inputs)- # Wait for the workflow to start running before streaming- is_workflow_running = await self._wait_for_workflow_to_start(handle)- if not is_workflow_running:- raise Exception(f"Workflow failed to start within timeout: {self._workflow_id}")+ # Wait for the workflow to start running before streaming+ is_workflow_running = await self._wait_for_workflow_to_start(handle)+ if not is_workflow_running:+ raise Exception(f"Workflow failed to start within timeout: {self._workflow_id}")- except Exception as e:- posthoganalytics.capture_exception(e, properties={"tag": "max_ai"})- logger.exception("Error starting workflow", error=e)+ except Exception as e:+ posthoganalytics.capture_exception(e, properties={"tag": "max_ai"})+ logger.exception("Error starting workflow", error=e)+ failed = True++ if failed:yield self._failure_message()return@@ -117,16 +136,23 @@ class AgentExecutor:where starting a new workflow with the same ID fails even with USE_EXISTING policy.This method handles that by waiting for the existing workflow to complete and retrying."""+ span = trace.get_current_span()for attempt in range(max_retries):try:- return await client.start_workflow(- workflow.run,- inputs,- id=self._workflow_id,- task_queue=settings.MAX_AI_TASK_QUEUE,- id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,- id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,- )+ with _tracer.start_as_current_span(+ "posthog_ai.executor.temporal_start_workflow",+ attributes={"posthog_ai.attempt": attempt},+ ):+ handle = await client.start_workflow(+ workflow.run,+ inputs,+ id=self._workflow_id,+ task_queue=settings.MAX_AI_TASK_QUEUE,+ id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ )+ span.set_attribute("posthog_ai.start_workflow.attempts", attempt + 1)+ return handleexcept WorkflowAlreadyStartedError:if attempt < max_retries - 1:# Get handle to existing workflow and wait for it to complete@@ -145,6 +171,7 @@ class AgentExecutor:"Existing workflow still running, using existing handle",workflow_id=self._workflow_id,)+ span.set_attribute("posthog_ai.start_workflow.attempts", attempt + 1)return existing_handleexcept Exception:# Workflow completed (possibly with error), retry starting a new one@@ -168,18 +195,25 @@ class AgentExecutor:max_attempts = 10 * 60 # 60 seconds total with 0.1s sleepattempts = 0- while attempts < max_attempts:- description = await handle.describe()- if description.status is None:- attempts += 1- await asyncio.sleep(0.1)- elif description.status == WorkflowExecutionStatus.RUNNING:- # Temporal only has one Open execution status, see: https://docs.temporal.io/workflow-execution- return True- else:- return False+ with _tracer.start_as_current_span("posthog_ai.executor.wait_for_workflow_start") as span:+ while attempts < max_attempts:+ description = await handle.describe()+ if description.status is None:+ attempts += 1+ await asyncio.sleep(0.1)+ elif description.status == WorkflowExecutionStatus.RUNNING:+ # Temporal only has one Open execution status, see: https://docs.temporal.io/workflow-execution+ span.set_attribute("posthog_ai.poll_attempts", attempts)+ span.set_attribute("posthog_ai.outcome", "running")+ return True+ else:+ span.set_attribute("posthog_ai.poll_attempts", attempts)+ span.set_attribute("posthog_ai.outcome", "not_running")+ return False- return False+ span.set_attribute("posthog_ai.poll_attempts", attempts)+ span.set_attribute("posthog_ai.outcome", "timeout")+ return Falseasync def stream_conversation(self) -> AsyncGenerator[AssistantOutput, Any]:"""Stream conversation updates from Redis stream.@@ -187,29 +221,55 @@ class AgentExecutor:Returns:AssistantOutput generator"""+ chunk_count = 0+ # Use start_span + use_span (without making the span "current" across yields).+ # `start_as_current_span` inside an async generator attaches the span to the running+ # task's contextvars; when the generator yields, the consumer task resumes with that+ # context still set, leaking this span as the consumer's "current span". We scope+ # the current-span context only around the non-yielding bookkeeping so child spans+ # still parent correctly, while yields run outside the attached context.+ # See https://github.com/open-telemetry/opentelemetry-python/issues/2606.+ span = _tracer.start_span(+ "posthog_ai.executor.stream_conversation",+ attributes={"posthog_ai.conversation_id": str(self._conversation.id)},+ )try:- # Wait for stream to be created- is_stream_available = await self._redis_stream.wait_for_stream()- if not is_stream_available:- raise StreamError("Stream for this conversation not available - Temporal workflow might have failed")- last_chunk_time = time.time()- async for chunk in self._redis_stream.read_stream():- message = await self._redis_stream_to_assistant_output(chunk)-- temporal_to_code_latency = last_chunk_time - chunk.timestamp- if temporal_to_code_latency > 0:- STREAM_DJANGO_EVENT_LOOP_LATENCY_HISTOGRAM.observe(temporal_to_code_latency)- last_chunk_time = time.time()-- if message:- yield message- except Exception as e:- posthoganalytics.capture_exception(e, properties={"tag": "max_ai"})- logger.exception("Error streaming conversation", error=e)- yield self._failure_message()-+ try:+ with trace.use_span(span, end_on_exit=False):+ # Wait for stream to be created+ is_stream_available = await self._redis_stream.wait_for_stream()+ if not is_stream_available:+ raise StreamError(+ "Stream for this conversation not available - Temporal workflow might have failed"+ )+ last_chunk_time = time.time()+ read_iter = self._redis_stream.read_stream().__aiter__()+ while True:+ with trace.use_span(span, end_on_exit=False):+ try:+ chunk = await read_iter.__anext__()+ except StopAsyncIteration:+ break+ message = await self._redis_stream_to_assistant_output(chunk)++ temporal_to_code_latency = last_chunk_time - chunk.timestamp+ if temporal_to_code_latency > 0:+ STREAM_DJANGO_EVENT_LOOP_LATENCY_HISTOGRAM.observe(temporal_to_code_latency)+ last_chunk_time = time.time()+ chunk_count += 1++ if message:+ yield message+ except Exception as e:+ with trace.use_span(span, end_on_exit=False):+ posthoganalytics.capture_exception(e, properties={"tag": "max_ai"})+ logger.exception("Error streaming conversation", error=e)+ yield self._failure_message()finally:- await self._redis_stream.delete_stream()+ with trace.use_span(span, end_on_exit=False):+ span.set_attribute("posthog_ai.stream_conversation.chunks", chunk_count)+ await self._redis_stream.delete_stream()+ span.end()async def _redis_stream_to_assistant_output(self, message: StreamEvent) -> AssistantOutput | None:"""Convert Redis stream event to Assistant output.@@ -223,8 +283,12 @@ class AgentExecutor:if isinstance(message.event, MessageEvent):return (AssistantEventType.MESSAGE, message.event.payload)elif isinstance(message.event, ConversationEvent):- # nosemgrep: idor-lookup-without-team (ID from internal Redis stream, caller validates user+team ownership)- conversation = await Conversation.objects.select_related("user").aget(id=message.event.payload)+ with _tracer.start_as_current_span(+ "posthog_ai.executor.conversation_aget",+ attributes={"posthog_ai.conversation_id": str(message.event.payload)},+ ):+ # nosemgrep: idor-lookup-without-team (ID from internal Redis stream, caller validates user+team ownership)+ conversation = await Conversation.objects.select_related("user").aget(id=message.event.payload)return (AssistantEventType.CONVERSATION, conversation)elif isinstance(message.event, UpdateEvent):return (AssistantEventType.UPDATE, message.event.payload)diff --git a/ee/hogai/core/runner.py b/ee/hogai/core/runner.pyindex cceec5159310..fa89b21f84e5 100644--- a/ee/hogai/core/runner.py+++ b/ee/hogai/core/runner.py@@ -16,6 +16,7 @@ from langchain_core.runnables.config import RunnableConfigfrom langgraph.errors import GraphInterrupt, GraphRecursionErrorfrom langgraph.graph.state import CompiledStateGraphfrom langgraph.types import Command, StreamMode+from opentelemetry import tracefrom posthoganalytics.ai.langchain.callbacks import CallbackHandlerfrom posthog.schema import (@@ -69,6 +70,7 @@ from ee.hogai.utils.types.composed import AssistantMaxGraphState, AssistantMaxPafrom ee.models import Conversationlogger = structlog.get_logger(__name__)+_tracer = trace.get_tracer(__name__)class SubagentCallbackHandler(CallbackHandler):@@ -623,12 +625,16 @@ class BaseAgentRunner(ABC):):if not self._user:return- await database_sync_to_async(report_user_action)(- self._user,- event_name,- properties,- send_feature_flags=True,- )+ with _tracer.start_as_current_span(+ "posthog_ai.runner.report_conversation_state",+ attributes={"posthog_ai.event_name": event_name},+ ):+ await database_sync_to_async(report_user_action)(+ self._user,+ event_name,+ properties,+ send_feature_flags=True,+ )@asynccontextmanagerasync def _lock_conversation(self):@@ -640,12 +646,14 @@ class BaseAgentRunner(ABC):returntry:- self._conversation.status = Conversation.Status.IN_PROGRESS- await self._conversation.asave(update_fields=["status"])+ with _tracer.start_as_current_span("posthog_ai.runner.lock_conversation"):+ self._conversation.status = Conversation.Status.IN_PROGRESS+ await self._conversation.asave(update_fields=["status"])yieldfinally:- self._conversation.status = Conversation.Status.IDLE- await self._conversation.asave(update_fields=["status", "updated_at"])+ with _tracer.start_as_current_span("posthog_ai.runner.unlock_conversation"):+ self._conversation.status = Conversation.Status.IDLE+ await self._conversation.asave(update_fields=["status", "updated_at"])def _capture_exception(self, e: Exception):posthoganalytics.capture_exception(diff --git a/ee/hogai/stream/redis_stream.py b/ee/hogai/stream/redis_stream.pyindex a14e7565dc24..f62fe9e907ce 100644--- a/ee/hogai/stream/redis_stream.py+++ b/ee/hogai/stream/redis_stream.py@@ -9,6 +9,7 @@ from django.conf import settingsimport structlogimport redis.exceptions as redis_exceptions+from opentelemetry import tracefrom prometheus_client import Histogramfrom pydantic import BaseModel, Field@@ -27,6 +28,7 @@ from ee.hogai.utils.types.base import ApprovalPayload, AssistantStreamedMessageUfrom ee.models.assistant import Conversationlogger = structlog.get_logger(__name__)+_tracer = trace.get_tracer(__name__)REDIS_TO_CLIENT_LATENCY_HISTOGRAM = Histogram("posthog_ai_redis_to_client_latency_seconds",@@ -236,33 +238,43 @@ class ConversationRedisStream:timeout = 60.0 # 60 seconds timeoutstart_time = asyncio.get_event_loop().time()last_iteration_time = None+ attempts = 0- while True:- current_time = time.time()- if last_iteration_time is not None:- iteration_duration = current_time - last_iteration_time- REDIS_STREAM_INIT_ITERATION_LATENCY_HISTOGRAM.observe(iteration_duration)- last_iteration_time = current_time+ with _tracer.start_as_current_span(+ "posthog_ai.redis_stream.wait_for_stream",+ attributes={"posthog_ai.stream_key": self._stream_key},+ ) as span:+ while True:+ current_time = time.time()+ if last_iteration_time is not None:+ iteration_duration = current_time - last_iteration_time+ REDIS_STREAM_INIT_ITERATION_LATENCY_HISTOGRAM.observe(iteration_duration)+ last_iteration_time = current_time+ attempts += 1++ elapsed_time = asyncio.get_event_loop().time() - start_time+ if elapsed_time >= timeout:+ logger.debug(+ f"Stream creation timeout after {elapsed_time:.2f}s",+ stream_key=self._stream_key,+ )+ span.set_attribute("posthog_ai.poll_attempts", attempts)+ span.set_attribute("posthog_ai.outcome", "timeout")+ return False++ if await self._redis_client.exists(self._stream_key):+ span.set_attribute("posthog_ai.poll_attempts", attempts)+ span.set_attribute("posthog_ai.outcome", "ready")+ return True- elapsed_time = asyncio.get_event_loop().time() - start_time- if elapsed_time >= timeout:logger.debug(- f"Stream creation timeout after {elapsed_time:.2f}s",+ f"Stream not found, retrying in {delay}s (elapsed: {elapsed_time:.2f}s)",stream_key=self._stream_key,)- return False-- if await self._redis_client.exists(self._stream_key):- return True-- logger.debug(- f"Stream not found, retrying in {delay}s (elapsed: {elapsed_time:.2f}s)",- stream_key=self._stream_key,- )- await asyncio.sleep(delay)+ await asyncio.sleep(delay)- # Linear backoff- delay = min(delay + delay_increment, max_delay)+ # Linear backoff+ delay = min(delay + delay_increment, max_delay)async def read_stream(self,diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex b42a76d6f1ff..d23e5c1be075 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -531,7 +531,13 @@ class Command(BaseCommand):tag_queries(kind="temporal")- enable_otel = settings.TEMPORAL_OTEL_PLUGIN_ENABLED is True and settings.OTEL_SERVICE_NAME is not None+ # Max AI traces span the Django request and the Temporal activity that runs the agent loop.+ # Without the OTel plugin on the worker, every span emitted from an activity is a root span+ # and the conversation trace splits across disconnected pieces. Force-enable for that queue+ # so investigations don't depend on an operator flipping TEMPORAL_OTEL_PLUGIN_ENABLED.+ enable_otel = (+ settings.TEMPORAL_OTEL_PLUGIN_ENABLED is True or task_queue == settings.MAX_AI_TASK_QUEUE+ ) and settings.OTEL_SERVICE_NAME is not Noneif enable_otel is True:# Mypy doesn't understand we have already checked settings.OTEL_SERVICE_NAMEinitialize_otel(settings.OTEL_SERVICE_NAME, settings.TEMPORAL_OTEL_LIBRARIES_TO_INSTRUMENT) # type: ignorediff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.pyindex b82fb380ddf6..2245101bd996 100644--- a/posthog/temporal/common/worker.py+++ b/posthog/temporal/common/worker.py@@ -305,6 +305,7 @@ async def create_worker(# Worker will flush heartbeats every# min(heartbeat_timeout * 0.8, max_heartbeat_throttle_interval).max_heartbeat_throttle_interval=dt.timedelta(seconds=5),+ plugins=plugins,)else:worker = Worker(