Skip to content

: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.

fix(slack-app): group a thread's routing classifier calls into one trace (#113263)

Vojta Bartoš71650585b074
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.py
index 76bd05906d11..0c7efb2f8f6f 100644
--- a/posthog/llm/gateway_client.py
+++ b/posthog/llm/gateway_client.py
@@ -383,6 +383,16 @@ def team_trace_id(team_id: int | None) -> str | None:
return str(uuid5(_TEAM_TRACE_ID_NAMESPACE, f"team-{team_id}"))
+def trace_id_from_seed(seed: str) -> str:
+ """Deterministic ``$ai_trace_id`` for a caller with no run id to borrow.
+
+ Absent a trace id the gateway stamps a fresh one per request, so every call in one
+ logical operation lands in a trace of its own. The seed must be unique to the
+ operation, because a coarser one merges unrelated calls into a single trace.
+ """
+ return str(uuid5(_TEAM_TRACE_ID_NAMESPACE, seed))
+
+
def anthropic_gateway_base_url(openai_base_url: str) -> str:
"""Drop the OpenAI ``/v1`` suffix so the Anthropic SDK, which appends ``/v1/messages``
itself, hits the same gateway root the OpenAI route uses. ``resolve_ai_gateway_config``
diff --git a/posthog/llm/test_gateway_client.py b/posthog/llm/test_gateway_client.py
index 8c2a2c3af22a..1b0c2ee24843 100644
--- a/posthog/llm/test_gateway_client.py
+++ b/posthog/llm/test_gateway_client.py
@@ -1,6 +1,7 @@
import json
import asyncio
from typing import get_args
+from uuid import UUID
import pytest
from unittest.mock import patch
@@ -27,6 +28,7 @@ from posthog.llm.gateway_client import (
private_scout_gateway,
resolve_ai_gateway_config,
team_trace_id,
+ trace_id_from_seed,
)
AI_GATEWAY_URL = "https://ai-gateway.example/v1"
@@ -361,6 +363,17 @@ class TestTeamTraceId:
assert team_trace_id(2) != team_trace_id(3)
+class TestTraceIdFromSeed:
+ # The Go route sends this value verbatim and the Python route hashes anything it cannot parse,
+ # so a non-UUID would give one call two different trace ids.
+ def test_result_parses_as_a_uuid_so_both_gateway_routes_agree(self):
+ derived = trace_id_from_seed("slack-thread-T123-1700000000.000100")
+ assert str(UUID(derived)) == derived
+
+ def test_distinct_seeds_do_not_share_a_trace(self):
+ assert trace_id_from_seed("slack-thread-T1-1.1") != trace_id_from_seed("slack-thread-T1-1.2")
+
+
class TestBuildAsyncAnthropicClient:
@override_settings(AI_GATEWAY_URL=AI_GATEWAY_URL, AI_GATEWAY_API_KEY=AI_GATEWAY_KEY)
@patch("posthog.llm.gateway_client.httpx.AsyncClient")
diff --git a/posthog/temporal/ai/slack_app/activities/classifiers.py b/posthog/temporal/ai/slack_app/activities/classifiers.py
index d3c71f7e4945..9de6073f88d6 100644
--- a/posthog/temporal/ai/slack_app/activities/classifiers.py
+++ b/posthog/temporal/ai/slack_app/activities/classifiers.py
@@ -6,7 +6,7 @@ from openai.types.shared_params import ResponseFormatJSONSchema
from pydantic import BaseModel, ValidationError
from temporalio import activity
-from posthog.llm.gateway_client import build_anthropic_client, build_openai_client
+from posthog.llm.gateway_client import build_anthropic_client, build_openai_client, trace_id_from_seed
from posthog.llm.semantic_enrichment import extract_json_object
from posthog.models.integration import Integration, SlackIntegration
from posthog.models.repo_routing_rule import RepoRoutingRule
@@ -45,6 +45,17 @@ CLASSIFIER_MODEL = "claude-haiku-4-5-20251001"
CLASSIFIER_PROPERTY = "slack_app_classifier"
+def _thread_trace_id(slack_team_id: str | None, thread_ts: str | None) -> str | None:
+ """Group one Slack thread's routing calls into a single trace.
+
+ These classifiers run before a task exists, so there is no run id to attach to and
+ the thread is the narrowest identity available to them.
+ """
+ if not slack_team_id or not thread_ts:
+ return None
+ return trace_id_from_seed(f"slack-thread-{slack_team_id}-{thread_ts}")
+
+
# The model-override and agent-directed classifiers both run on a reasoning model, which
# draws its reasoning from the same token budget as the reply. The reply is one short JSON
# object; the headroom is for the thinking in front of it, and a truncated turn falls back
@@ -98,6 +109,7 @@ def classify_task_needs_repo(
event_text: str,
thread_messages: list[SlackThreadMessage],
routing_rules: list[str] | None = None,
+ trace_id: str | None = None,
) -> bool:
"""Classify whether a Slack conversation requires code repository access.
@@ -199,6 +211,7 @@ def classify_task_needs_repo(
client = build_anthropic_client(
product="slack_app_routing",
ai_product="slack_app_routing",
+ trace_id=trace_id,
properties={CLASSIFIER_PROPERTY: "task_needs_repo"},
)
response = client.messages.create(
@@ -234,6 +247,11 @@ def classify_posthog_code_task_needs_repo_activity(
by pre-deploy workflow code carry only the first two payloads, and a required
leading parameter would make them unbindable on a new worker. Such tasks classify
without routing rules, which is the pre-deploy behavior.
+
+ Do not add a fourth parameter. Temporal drops the argument type hints when the
+ declared parameter count differs from the queued payload count, so a task queued
+ before the deploy decodes ``inputs`` as a plain dict and fails on attribute access.
+ Read whatever else this activity needs out of ``inputs``, as the trace id does.
"""
# Circular import: products.slack_app.backend.api imports this package at module scope.
from products.slack_app.backend.api import _get_full_repo_names # noqa: PLC0415
@@ -252,7 +270,13 @@ def classify_posthog_code_task_needs_repo_activity(
# every rule.
connected = {repo.lower() for repo in _get_full_repo_names(integration, user_id=inputs.user_id)}
routing_rules = team_routing_rule_lines(integration.team_id, candidate_repos=connected or None)
- return classify_task_needs_repo(event_text, thread_messages, routing_rules=routing_rules)
+ thread_ts = inputs.event.get("thread_ts") or inputs.event.get("ts")
+ return classify_task_needs_repo(
+ event_text,
+ thread_messages,
+ routing_rules=routing_rules,
+ trace_id=_thread_trace_id(inputs.slack_team_id, thread_ts),
+ )
def _agent_directed_response_format() -> ResponseFormatJSONSchema:
@@ -280,6 +304,7 @@ def classify_message_is_agent_directed(
event_text: str,
task_title: str,
thread_history: list[SlackThreadMessage],
+ trace_id: str | None = None,
) -> bool:
"""Classify whether an untagged Slack thread reply is an instruction to the running
PostHog Slack App, or people talking to each other.
@@ -316,6 +341,7 @@ def classify_message_is_agent_directed(
client = build_openai_client(
product="slack_app_routing",
ai_product="slack_app_routing",
+ trace_id=trace_id,
properties={CLASSIFIER_PROPERTY: "agent_directed"},
).with_options(timeout=AGENT_DIRECTED_TIMEOUT_SECONDS, max_retries=AGENT_DIRECTED_MAX_RETRIES)
response = client.chat.completions.create(
@@ -399,7 +425,12 @@ def classify_untagged_followup_activity(
thread_history = []
task_title = mapping.task.title if mapping.task and mapping.task.title else ""
- if classify_message_is_agent_directed(event_text, task_title, thread_history):
+ if classify_message_is_agent_directed(
+ event_text,
+ task_title,
+ thread_history,
+ trace_id=_thread_trace_id(inputs.slack_team_id, thread_ts),
+ ):
return True
logger.info(
@@ -455,6 +486,7 @@ def _render_model_catalogue(choices: tuple[ModelChoice, ...]) -> str:
def classify_slack_app_model_override(
event_text: str,
choices: tuple[ModelChoice, ...],
+ trace_id: str | None = None,
) -> SlackAppModelOverride | None:
"""Read a per-task model or reasoning-effort request out of a Slack mention.
@@ -486,6 +518,7 @@ def classify_slack_app_model_override(
client = build_openai_client(
product="slack_app_routing",
ai_product="slack_app_routing",
+ trace_id=trace_id,
properties={CLASSIFIER_PROPERTY: "model_override"},
).with_options(timeout=MODEL_OVERRIDE_TIMEOUT_SECONDS, max_retries=MODEL_OVERRIDE_MAX_RETRIES)
response = client.chat.completions.create(
@@ -555,7 +588,11 @@ def classify_slack_app_model_override_activity(input: SlackAppModelOverrideInput
logger.info("slack_app_model_override_empty_catalogue", integration_id=integration.id)
return None
- override = classify_slack_app_model_override(input.event_text, choices)
+ override = classify_slack_app_model_override(
+ input.event_text,
+ choices,
+ trace_id=_thread_trace_id(input.slack_team_id, input.thread_ts),
+ )
if override is None:
return None
@@ -597,7 +634,10 @@ class _ProjectRouteReply(BaseModel):
def classify_slack_app_project_route(
- event_text: str, projects: list[Integration], default: Integration | None = None
+ event_text: str,
+ projects: list[Integration],
+ default: Integration | None = None,
+ trace_id: str | None = None,
) -> Integration | None:
"""Read the project a mention asked to be answered from, out of its text.
@@ -633,6 +673,7 @@ def classify_slack_app_project_route(
client = build_openai_client(
product="slack_app_routing",
ai_product="slack_app_routing",
+ trace_id=trace_id,
properties={CLASSIFIER_PROPERTY: "project_route"},
).with_options(timeout=PROJECT_ROUTE_TIMEOUT_SECONDS, max_retries=PROJECT_ROUTE_MAX_RETRIES)
response = client.chat.completions.create(
@@ -693,7 +734,12 @@ def classify_slack_app_project_route_activity(input: SlackAppProjectRouteInput)
return None
try:
- chosen = classify_slack_app_project_route(input.event_text, projects, default=integration)
+ chosen = classify_slack_app_project_route(
+ input.event_text,
+ projects,
+ default=integration,
+ trace_id=_thread_trace_id(input.slack_team_id, input.thread_ts),
+ )
except Exception:
# The fallback boundary: a mention we cannot classify stays on the project
# routing already resolved, which is what it would have done anyway.
diff --git a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py
index 2b97479e1485..bbd261a4dd25 100644
--- a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py
+++ b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py
@@ -149,6 +149,7 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):
integration_id=inputs.integration_id,
slack_team_id=inputs.slack_team_id,
event_text=event.get("text", ""),
+ thread_ts=thread_ts,
),
)
@@ -186,6 +187,7 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):
event_text=event.get("text", ""),
user_id=inputs.user_id,
slack_user_id=slack_user_id,
+ thread_ts=thread_ts,
),
)
if project_route is not None:
diff --git a/posthog/temporal/ai/slack_app/types.py b/posthog/temporal/ai/slack_app/types.py
index dd6e0469c6b5..23758130ec3b 100644
--- a/posthog/temporal/ai/slack_app/types.py
+++ b/posthog/temporal/ai/slack_app/types.py
@@ -138,11 +138,16 @@ class SlackAppMessageReactionInput(BaseModel):
class SlackAppModelOverrideInput(BaseModel):
- """Single-argument input for the model-override classifier activity."""
+ """Single-argument input for the model-override classifier activity.
+
+ ``thread_ts`` only groups the captured generation into its thread's trace, so it
+ defaults to None: a task queued before it existed stays bindable on a new worker.
+ """
integration_id: int
slack_team_id: str
event_text: str
+ thread_ts: str | None = None
class SlackAppModelOverride(BaseModel):
@@ -172,6 +177,7 @@ class SlackAppProjectRouteInput(BaseModel):
event_text: str
user_id: int
slack_user_id: str
+ thread_ts: str | None = None
class SlackAppProjectRoute(BaseModel):
diff --git a/posthog/temporal/tests/ai/slack_app/activities/test_classifier_gateway_routing.py b/posthog/temporal/tests/ai/slack_app/activities/test_classifier_gateway_routing.py
index 7d3b05e69d43..bda57e07e562 100644
--- a/posthog/temporal/tests/ai/slack_app/activities/test_classifier_gateway_routing.py
+++ b/posthog/temporal/tests/ai/slack_app/activities/test_classifier_gateway_routing.py
@@ -24,6 +24,7 @@ AI_GATEWAY_URL = "https://ai-gateway.example/v1"
AI_GATEWAY_KEY = "phs_go"
LLM_GATEWAY_URL = "http://llm-gateway:8080"
LLM_GATEWAY_KEY = "phx_legacy"
+TRACE_ID = "1b9d6bcd-bbfd-5b1d-9c2f-9f0a4b4a1b2c"
# Both modes set every setting the builders read, so the wrong route cannot pass by accident.
GO_GATEWAY = {
@@ -43,19 +44,23 @@ PROJECTS = [
def _classify_needs_repo():
- return classify_task_needs_repo(NEEDS_REPO_TEXT, [SlackThreadMessage(user="Alessandro", text=NEEDS_REPO_TEXT)])
+ return classify_task_needs_repo(
+ NEEDS_REPO_TEXT,
+ [SlackThreadMessage(user="Alessandro", text=NEEDS_REPO_TEXT)],
+ trace_id=TRACE_ID,
+ )
def _classify_agent_directed():
- return classify_message_is_agent_directed("also check the mobile breakpoint", "Fix checkout", [])
+ return classify_message_is_agent_directed("also check the mobile breakpoint", "Fix checkout", [], trace_id=TRACE_ID)
def _classify_model_override():
- return classify_slack_app_model_override("use fable for this", CHOICES)
+ return classify_slack_app_model_override("use fable for this", CHOICES, trace_id=TRACE_ID)
def _classify_project_route():
- return classify_slack_app_project_route("check the error rate on staging", PROJECTS)
+ return classify_slack_app_project_route("check the error rate on staging", PROJECTS, trace_id=TRACE_ID)
OPENAI_CLASSIFIERS = [
@@ -85,6 +90,9 @@ def _assert_routing_product(headers: dict[str, str], classifier: str) -> None:
# All four classifiers share that product, so an online evaluation can only reach one
# of them through this label. A call that loses it is graded as the wrong classifier.
assert properties[CLASSIFIER_PROPERTY] == classifier
+ # Without this header the gateway stamps a fresh id per request, so a classifier that drops it
+ # stops grouping with its thread.
+ assert headers["X-PostHog-Trace-Id"] == TRACE_ID
class TestClassifierGatewayRouting:
diff --git a/posthog/temporal/tests/ai/slack_app/activities/test_model_override_activity.py b/posthog/temporal/tests/ai/slack_app/activities/test_model_override_activity.py
index b1939b265ed5..38a3af9a7520 100644
--- a/posthog/temporal/tests/ai/slack_app/activities/test_model_override_activity.py
+++ b/posthog/temporal/tests/ai/slack_app/activities/test_model_override_activity.py
@@ -35,11 +35,12 @@ def integration(db):
)
-def _input(integration: Integration, text: str) -> SlackAppModelOverrideInput:
+def _input(integration: Integration, text: str, thread_ts: str | None = None) -> SlackAppModelOverrideInput:
return SlackAppModelOverrideInput(
integration_id=integration.id,
slack_team_id=integration.integration_id or "",
event_text=text,
+ thread_ts=thread_ts,
)
@@ -80,4 +81,19 @@ class TestClassifySlackAppModelOverrideActivity:
):
text = "fix the flaky checkout test"
assert classify_slack_app_model_override_activity(_input(integration, text)) == classified
- classify.assert_called_once_with(text, CATALOGUE)
+ classify.assert_called_once_with(text, CATALOGUE, trace_id=None)
+
+ @pytest.mark.parametrize(
+ "thread_ts,groups_with_its_thread",
+ [(None, False), ("1700000000.000100", True)],
+ ids=["no_thread_ts", "thread_ts"],
+ )
+ def test_forwards_a_thread_trace_id_so_the_call_groups_with_its_mention(
+ self, integration, thread_ts, groups_with_its_thread
+ ):
+ with (
+ patch(f"{ACTIVITY_MODULE}.available_model_choices", return_value=CATALOGUE),
+ patch(f"{ACTIVITY_MODULE}.classify_slack_app_model_override", return_value=None) as classify,
+ ):
+ classify_slack_app_model_override_activity(_input(integration, "use fable", thread_ts))
+ assert (classify.call_args.kwargs["trace_id"] is not None) is groups_with_its_thread
diff --git a/posthog/temporal/tests/ai/slack_app/activities/test_needs_repo_payload_contract.py b/posthog/temporal/tests/ai/slack_app/activities/test_needs_repo_payload_contract.py
new file mode 100644
index 000000000000..def2500da4af
--- /dev/null
+++ b/posthog/temporal/tests/ai/slack_app/activities/test_needs_repo_payload_contract.py
@@ -0,0 +1,32 @@
+from temporalio.common import _type_hints_from_func
+from temporalio.converter import DataConverter
+
+from posthog.temporal.ai.slack_app.activities.classifiers import classify_posthog_code_task_needs_repo_activity
+from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs
+
+from products.slack_app.backend.services.slack_messages import SlackThreadMessage
+
+INPUTS = PostHogCodeSlackMentionWorkflowInputs(
+ event={"text": "why did signups drop", "ts": "1700000000.000100"},
+ integration_id=410,
+ slack_team_id="T_WS",
+ user_id=7,
+)
+
+
+async def test_a_queued_three_payload_task_still_decodes_its_inputs():
+ activity = classify_posthog_code_task_needs_repo_activity
+ fn = getattr(activity, "__wrapped__", activity)
+ arg_types, _ = _type_hints_from_func(fn)
+
+ converter = DataConverter.default
+ payloads = await converter.encode(["why did signups drop", [SlackThreadMessage(user="Ada", text="hi")], INPUTS])
+
+ # Temporal drops the activity's type hints when the declared parameter count differs from
+ # the queued payload count, which decodes a dataclass payload as a plain dict and fails on
+ # attribute access. A fourth parameter would reintroduce that for every in-flight task.
+ hints = arg_types if arg_types is not None and len(arg_types) == len(payloads) else None
+ decoded = await converter.decode(payloads, type_hints=hints)
+
+ assert isinstance(decoded[2], PostHogCodeSlackMentionWorkflowInputs)
+ assert decoded[2].integration_id == 410
diff --git a/posthog/temporal/tests/ai/test_classify_task_needs_repo.py b/posthog/temporal/tests/ai/test_classify_task_needs_repo.py
index 71de33a5787b..5525d5c0bfdd 100644
--- a/posthog/temporal/tests/ai/test_classify_task_needs_repo.py
+++ b/posthog/temporal/tests/ai/test_classify_task_needs_repo.py
@@ -199,6 +199,7 @@ class TestClassifyTaskNeedsRepo:
build_client.assert_called_once_with(
product="slack_app_routing",
ai_product="slack_app_routing",
+ trace_id=None,
properties={CLASSIFIER_PROPERTY: "task_needs_repo"},
)
kwargs = fake_client.messages.create.call_args.kwargs