: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
fix(aiobs): stop trace-clustering self-perpetuating loop (#60259)
Carlos Marchal988010346d49
diff --git a/posthog/tasks/llm_analytics_usage_report.py b/posthog/tasks/llm_analytics_usage_report.pyindex 59170d44339d..db729f05f75e 100644--- a/posthog/tasks/llm_analytics_usage_report.py+++ b/posthog/tasks/llm_analytics_usage_report.py@@ -31,14 +31,24 @@ def get_ph_client() -> PostHogClient:return PostHogClient("sTMFPsFhdP1Ssg", sync_mode=True)-# AI events dynamically generated from AIEventType enumAI_EVENTS = [event.value for event in AIEventType]LLM_PROMPT_FETCHED_EVENT = "$llm_prompt_fetched"-# Events that should make a team eligible for an AI observability usage report.-# Keep this list broader than AI_EVENTS when a non-AI event should still trigger reporting.LLM_ANALYTICS_REPORT_TRIGGER_EVENTS = [*AI_EVENTS, LLM_PROMPT_FETCHED_EVENT]+# Restricted to customer-emitted events that produce data downstream LLM analytics workflows can act on:+# excludes server-side artifacts like summaries, reports, and clusters, and prompt-management events that+# don't generate traces.+LLM_ANALYTICS_DISCOVERY_TRIGGER_EVENTS: list[str] = [+ AIEventType.FIELD_AI_GENERATION.value,+ AIEventType.FIELD_AI_EMBEDDING.value,+ AIEventType.FIELD_AI_SPAN.value,+ AIEventType.FIELD_AI_TRACE.value,+ AIEventType.FIELD_AI_METRIC.value,+ AIEventType.FIELD_AI_FEEDBACK.value,+ AIEventType.FIELD_AI_EVALUATION.value,+]+# ClickHouse query settings for AI observability queriesCH_LLM_ANALYTICS_SETTINGS = {"max_execution_time": 5 * 60, # 5 minutes@@ -216,9 +226,13 @@ def _combine_team_count_results(results_list: list) -> list[tuple[int, int]]:@timed_log()@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)-def get_teams_with_ai_events(begin: datetime, end: datetime) -> list[int]:+def get_teams_with_ai_events(+ begin: datetime,+ end: datetime,+ trigger_events: list[str],+) -> list[int]:"""- Get all team_ids that have at least one AI observability report trigger event in the period.+ Get all team_ids that have at least one AI observability trigger event in the period.This is a fast query that returns only distinct team_ids, allowing subsequentqueries to filter by team_id and use the primary key index efficiently.@@ -242,7 +256,7 @@ def get_teams_with_ai_events(begin: datetime, end: datetime) -> list[int]:results = sync_execute(query,{- "llm_analytics_report_trigger_events": LLM_ANALYTICS_REPORT_TRIGGER_EVENTS,+ "llm_analytics_report_trigger_events": trigger_events,"begin": begin,"end": end,},@@ -658,7 +672,7 @@ def _get_all_llm_analytics_reports(logger.info("Querying AI observability usage data")# Phase 1: Get all team_ids with report trigger events (fast query)- team_ids = get_teams_with_ai_events(period_start, period_end)+ team_ids = get_teams_with_ai_events(period_start, period_end, LLM_ANALYTICS_REPORT_TRIGGER_EVENTS)if not team_ids:logger.info("No teams with AI observability trigger events found")diff --git a/posthog/tasks/test/test_llm_analytics_usage_report.py b/posthog/tasks/test/test_llm_analytics_usage_report.pyindex fadb55cb7778..35de4c7a7884 100644--- a/posthog/tasks/test/test_llm_analytics_usage_report.py+++ b/posthog/tasks/test/test_llm_analytics_usage_report.py@@ -18,6 +18,7 @@ from posthog.clickhouse.client import sync_executefrom posthog.models import Organization, Teamfrom posthog.models.event.util import create_eventfrom posthog.tasks.llm_analytics_usage_report import (+ LLM_ANALYTICS_REPORT_TRIGGER_EVENTS,_get_all_llm_analytics_reports,get_all_ai_dimension_breakdowns,get_all_ai_metrics,@@ -122,7 +123,7 @@ class TestLLMAnalyticsUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDe)# Get team_ids first- team_ids = get_teams_with_ai_events(period_start, period_end)+ team_ids = get_teams_with_ai_events(period_start, period_end, LLM_ANALYTICS_REPORT_TRIGGER_EVENTS)# Get all metrics in one queryall_metrics = get_all_ai_metrics(period_start, period_end, team_ids)@@ -203,7 +204,7 @@ class TestLLMAnalyticsUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDeproperties={},)- team_ids = get_teams_with_ai_events(period_start, period_end)+ team_ids = get_teams_with_ai_events(period_start, period_end, LLM_ANALYTICS_REPORT_TRIGGER_EVENTS)all_metrics = get_all_ai_metrics(period_start, period_end, team_ids)assert self.team.id in all_metrics@@ -249,7 +250,7 @@ class TestLLMAnalyticsUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDeproperties={},)- team_ids = get_teams_with_ai_events(period_start, period_end)+ team_ids = get_teams_with_ai_events(period_start, period_end, LLM_ANALYTICS_REPORT_TRIGGER_EVENTS)all_metrics = get_all_ai_metrics(period_start, period_end, team_ids)assert self.team.id in all_metrics@@ -304,7 +305,7 @@ class TestLLMAnalyticsUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDe)# Get team_ids first- team_ids = get_teams_with_ai_events(period_start, period_end)+ team_ids = get_teams_with_ai_events(period_start, period_end, LLM_ANALYTICS_REPORT_TRIGGER_EVENTS)# Get dimension breakdowns using the new combined functionall_breakdowns = get_all_ai_dimension_breakdowns(period_start, period_end, team_ids)@@ -383,7 +384,7 @@ class TestLLMAnalyticsUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDe)# Get team_ids first- team_ids = get_teams_with_ai_events(period_start, period_end)+ team_ids = get_teams_with_ai_events(period_start, period_end, LLM_ANALYTICS_REPORT_TRIGGER_EVENTS)# Get dimension breakdowns using the new combined functionall_breakdowns = get_all_ai_dimension_breakdowns(period_start, period_end, team_ids)@@ -458,7 +459,7 @@ class TestLLMAnalyticsUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDe# Need AI events so get_teams_with_ai_events finds this teamself._create_ai_events(self.team, distinct_id, "$ai_generation", 1)- team_ids = get_teams_with_ai_events(period_start, period_end)+ team_ids = get_teams_with_ai_events(period_start, period_end, LLM_ANALYTICS_REPORT_TRIGGER_EVENTS)survey_metrics = get_llm_feedback_survey_metrics(period_start, period_end, team_ids)assert self.team.id in survey_metrics@@ -861,7 +862,7 @@ class TestLLMAnalyticsUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDe)# Get team_ids first- team_ids = get_teams_with_ai_events(period_start, period_end)+ team_ids = get_teams_with_ai_events(period_start, period_end, LLM_ANALYTICS_REPORT_TRIGGER_EVENTS)# Get dimension breakdowns using the new combined functionall_breakdowns = get_all_ai_dimension_breakdowns(period_start, period_end, team_ids)@@ -918,7 +919,7 @@ class TestLLMAnalyticsUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDeself._create_ai_events(team_4, distinct_id_4, "$llm_prompt_fetched", 1)# Get teams with trigger events- team_ids = get_teams_with_ai_events(period_start, period_end)+ team_ids = get_teams_with_ai_events(period_start, period_end, LLM_ANALYTICS_REPORT_TRIGGER_EVENTS)# Verify correct teams are returnedassert self.team.id in team_ids@@ -947,7 +948,7 @@ class TestLLMAnalyticsUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDeself._create_ai_events(team_2, distinct_id_2, "$ai_generation", 7)self._create_ai_events(team_3, distinct_id_3, "$ai_generation", 3)- team_ids = get_teams_with_ai_events(period_start, period_end)+ team_ids = get_teams_with_ai_events(period_start, period_end, LLM_ANALYTICS_REPORT_TRIGGER_EVENTS)prompt_fetched_counts = get_llm_prompt_fetched_counts(period_start, period_end, team_ids)assert prompt_fetched_counts[self.team.id] == 4@@ -1107,7 +1108,7 @@ class TestLLMAnalyticsUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDeif no_key_count:self._create_ai_events(self.team, distinct_id, "$ai_evaluation", no_key_count)- team_ids = get_teams_with_ai_events(period_start, period_end)+ team_ids = get_teams_with_ai_events(period_start, period_end, LLM_ANALYTICS_REPORT_TRIGGER_EVENTS)all_metrics = get_all_ai_metrics(period_start, period_end, team_ids)total = posthog_count + byok_count + no_key_countdiff --git a/posthog/temporal/llm_analytics/team_discovery.py b/posthog/temporal/llm_analytics/team_discovery.pyindex 7b324157fd04..a632b14cefac 100644--- a/posthog/temporal/llm_analytics/team_discovery.py+++ b/posthog/temporal/llm_analytics/team_discovery.py@@ -49,7 +49,7 @@ DEFAULT_GUARANTEED_TEAM_IDS: list[int] = [# Default sample percentage for gradual rollout.# 0.0 = only guaranteed teams, 0.5 = 50% of remaining, 1.0 = all teams with AI events.DEFAULT_SAMPLE_PERCENTAGE: float = 0.5-DEFAULT_DISCOVERY_LOOKBACK_DAYS: int = 30+DEFAULT_DISCOVERY_LOOKBACK_DAYS: int = 7# Backward-compatible aliases for coordinator imports.# Coordinators use these only in the last-resort fallback path (when the@@ -64,7 +64,6 @@ class LLMAWorkflowConfig:guaranteed_team_ids: list[int]skip_team_ids: list[int]sample_percentage: float- discovery_lookback_days: intdef _get_llma_workflow_config() -> LLMAWorkflowConfig:@@ -80,7 +79,6 @@ def _get_llma_workflow_config() -> LLMAWorkflowConfig:guaranteed_team_ids=DEFAULT_GUARANTEED_TEAM_IDS,skip_team_ids=[],sample_percentage=DEFAULT_SAMPLE_PERCENTAGE,- discovery_lookback_days=DEFAULT_DISCOVERY_LOOKBACK_DAYS,)guaranteed = payload.get("guaranteed_team_ids", DEFAULT_GUARANTEED_TEAM_IDS)@@ -95,23 +93,17 @@ def _get_llma_workflow_config() -> LLMAWorkflowConfig:if not isinstance(sample_pct, (int, float)) or not (0.0 <= float(sample_pct) <= 1.0):sample_pct = DEFAULT_SAMPLE_PERCENTAGE- lookback = payload.get("discovery_lookback_days", DEFAULT_DISCOVERY_LOOKBACK_DAYS)- if not isinstance(lookback, int) or lookback <= 0:- lookback = DEFAULT_DISCOVERY_LOOKBACK_DAYS-logger.info("Loaded LLMA config from feature flag",guaranteed_count=len(guaranteed),skip_count=len(skip),sample_percentage=sample_pct,- discovery_lookback_days=lookback,)return LLMAWorkflowConfig(guaranteed_team_ids=guaranteed,skip_team_ids=skip,sample_percentage=float(sample_pct),- discovery_lookback_days=lookback,)except Exception:logger.warning("Failed to read LLMA config from feature flag, using defaults", exc_info=True)@@ -119,7 +111,6 @@ def _get_llma_workflow_config() -> LLMAWorkflowConfig:guaranteed_team_ids=DEFAULT_GUARANTEED_TEAM_IDS,skip_team_ids=[],sample_percentage=DEFAULT_SAMPLE_PERCENTAGE,- discovery_lookback_days=DEFAULT_DISCOVERY_LOOKBACK_DAYS,)@@ -149,20 +140,24 @@ async def get_team_ids_for_llm_analytics(inputs: TeamDiscoveryInput) -> list[intguaranteed = set(config.guaranteed_team_ids)skip = set(config.skip_team_ids)- # FF payload is the source of truth, intentionally overriding- # TeamDiscoveryInput so config can be tuned from the PostHog UI- # without a deploy. TeamDiscoveryInput is kept for Temporal's- # serialization contract but its values are not used at runtime.sample_percentage = config.sample_percentage- lookback_days = config.discovery_lookback_days+ lookback_days = inputs.lookback_daystry:end = datetime.now(UTC)begin = end - timedelta(days=lookback_days)- from posthog.tasks.llm_analytics_usage_report import get_teams_with_ai_events+ from posthog.tasks.llm_analytics_usage_report import (+ LLM_ANALYTICS_DISCOVERY_TRIGGER_EVENTS,+ get_teams_with_ai_events,+ )- ai_event_teams = await asyncio.to_thread(get_teams_with_ai_events, begin, end)+ ai_event_teams = await asyncio.to_thread(+ get_teams_with_ai_events,+ begin,+ end,+ LLM_ANALYTICS_DISCOVERY_TRIGGER_EVENTS,+ )remaining = [t for t in ai_event_teams if t not in guaranteed and t not in skip]diff --git a/posthog/temporal/llm_analytics/test_team_discovery.py b/posthog/temporal/llm_analytics/test_team_discovery.pyindex b95147d488eb..db5f35782c83 100644--- a/posthog/temporal/llm_analytics/test_team_discovery.py+++ b/posthog/temporal/llm_analytics/test_team_discovery.py@@ -7,7 +7,6 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom posthog.temporal.llm_analytics.team_discovery import (- DEFAULT_DISCOVERY_LOOKBACK_DAYS,DEFAULT_GUARANTEED_TEAM_IDS,DEFAULT_SAMPLE_PERCENTAGE,TeamDiscoveryInput,@@ -42,7 +41,6 @@ class TestGetLlmaWorkflowConfig:assert config.guaranteed_team_ids == DEFAULT_GUARANTEED_TEAM_IDSassert config.skip_team_ids == []assert config.sample_percentage == DEFAULT_SAMPLE_PERCENTAGE- assert config.discovery_lookback_days == DEFAULT_DISCOVERY_LOOKBACK_DAYS@patch(FF_PAYLOAD_PATH)def test_valid_payload(self, mock_ff):@@ -50,7 +48,6 @@ class TestGetLlmaWorkflowConfig:"guaranteed_team_ids": [100, 200],"skip_team_ids": [300, 400],"sample_percentage": 0.5,- "discovery_lookback_days": 7,}config = _get_llma_workflow_config()@@ -58,7 +55,6 @@ class TestGetLlmaWorkflowConfig:assert config.guaranteed_team_ids == [100, 200]assert config.skip_team_ids == [300, 400]assert config.sample_percentage == 0.5- assert config.discovery_lookback_days == 7@patch(FF_PAYLOAD_PATH)def test_partial_payload_fills_missing_with_defaults(self, mock_ff):@@ -69,7 +65,6 @@ class TestGetLlmaWorkflowConfig:assert config.guaranteed_team_ids == [42]assert config.skip_team_ids == []assert config.sample_percentage == DEFAULT_SAMPLE_PERCENTAGE- assert config.discovery_lookback_days == DEFAULT_DISCOVERY_LOOKBACK_DAYS@parameterized.expand([@@ -82,9 +77,6 @@ class TestGetLlmaWorkflowConfig:("pct_above_one", {"sample_percentage": 1.5}, "sample_percentage"),("nan_pct", {"sample_percentage": float("nan")}, "sample_percentage"),("inf_pct", {"sample_percentage": float("inf")}, "sample_percentage"),- ("float_lookback", {"discovery_lookback_days": 7.5}, "discovery_lookback_days"),- ("zero_lookback", {"discovery_lookback_days": 0}, "discovery_lookback_days"),- ("negative_lookback", {"discovery_lookback_days": -5}, "discovery_lookback_days"),])@patch(FF_PAYLOAD_PATH)@@ -99,8 +91,6 @@ class TestGetLlmaWorkflowConfig:assert config.skip_team_ids == []if bad_field == "sample_percentage":assert config.sample_percentage == DEFAULT_SAMPLE_PERCENTAGE- if bad_field == "discovery_lookback_days":- assert config.discovery_lookback_days == DEFAULT_DISCOVERY_LOOKBACK_DAYS@patch(FF_PAYLOAD_PATH)def test_exception_returns_defaults(self, mock_ff):@@ -111,7 +101,6 @@ class TestGetLlmaWorkflowConfig:assert config.guaranteed_team_ids == DEFAULT_GUARANTEED_TEAM_IDSassert config.skip_team_ids == []assert config.sample_percentage == DEFAULT_SAMPLE_PERCENTAGE- assert config.discovery_lookback_days == DEFAULT_DISCOVERY_LOOKBACK_DAYS@patch(FF_PAYLOAD_PATH)def test_int_sample_percentage_cast_to_float(self, mock_ff):@@ -213,7 +202,6 @@ class TestGetTeamIdsForLlmAnalytics:mock_ff.return_value = {"guaranteed_team_ids": [42],"sample_percentage": 0.0,- "discovery_lookback_days": 7,}mock_get_teams.return_value = [9999, 8888]inputs = TeamDiscoveryInput()@@ -264,3 +252,48 @@ class TestGetTeamIdsForLlmAnalytics:result = await get_team_ids_for_llm_analytics(inputs)assert result == [1, 3]++ @patch("posthog.tasks.llm_analytics_usage_report.get_teams_with_ai_events")+ async def test_uses_discovery_trigger_events_not_report_list(self, mock_get_teams, _mock_ff):+ """Discovery must pass the narrow trigger list — excluding server-emitted+ $ai_*_clusters / $ai_*_summary events — to avoid the self-perpetuating+ eligibility loop. The broader LLM_ANALYTICS_REPORT_TRIGGER_EVENTS list is+ reserved for the usage-report caller.+ """+ from posthog.tasks.llm_analytics_usage_report import (+ LLM_ANALYTICS_DISCOVERY_TRIGGER_EVENTS,+ LLM_ANALYTICS_REPORT_TRIGGER_EVENTS,+ )++ mock_get_teams.return_value = []+ inputs = TeamDiscoveryInput()++ await get_team_ids_for_llm_analytics(inputs)++ assert mock_get_teams.called+ passed_trigger_events = mock_get_teams.call_args.args[2]+ assert passed_trigger_events == LLM_ANALYTICS_DISCOVERY_TRIGGER_EVENTS+ assert "$ai_trace_clusters" not in passed_trigger_events+ assert "$ai_generation_clusters" not in passed_trigger_events+ assert "$ai_trace_summary" not in passed_trigger_events+ assert "$ai_generation_summary" not in passed_trigger_events+ assert "$ai_tag" not in passed_trigger_events+ assert "$llm_prompt_fetched" not in passed_trigger_events+ assert "$ai_generation" in passed_trigger_events+ assert set(passed_trigger_events) < set(LLM_ANALYTICS_REPORT_TRIGGER_EVENTS)++ @patch("posthog.tasks.llm_analytics_usage_report.get_teams_with_ai_events")+ async def test_lookback_uses_inputs_value(self, mock_get_teams, _mock_ff):+ """The discovery activity scopes its eligibility query to the caller's+ TeamDiscoveryInput.lookback_days (passed by the coordinator from the+ downstream workflow's own lookback) so discovery matches what the+ workflow will actually analyze.+ """+ mock_get_teams.return_value = []+ inputs = TeamDiscoveryInput(lookback_days=3)++ await get_team_ids_for_llm_analytics(inputs)++ begin, end = mock_get_teams.call_args.args[0], mock_get_teams.call_args.args[1]+ delta_days = (end - begin).total_seconds() / 86400+ assert 2.99 < delta_days < 3.01diff --git a/posthog/temporal/llm_analytics/trace_clustering/coordinator.py b/posthog/temporal/llm_analytics/trace_clustering/coordinator.pyindex b4122bce59c8..da528c900c62 100644--- a/posthog/temporal/llm_analytics/trace_clustering/coordinator.py+++ b/posthog/temporal/llm_analytics/trace_clustering/coordinator.py@@ -146,7 +146,10 @@ class TraceClusteringCoordinatorWorkflow(PostHogWorkflow):try:team_ids = await temporalio.workflow.execute_activity(get_team_ids_for_llm_analytics,- TeamDiscoveryInput(sample_percentage=SAMPLE_PERCENTAGE),+ TeamDiscoveryInput(+ sample_percentage=SAMPLE_PERCENTAGE,+ lookback_days=inputs.lookback_days,+ ),start_to_close_timeout=DISCOVERY_ACTIVITY_TIMEOUT,retry_policy=DISCOVERY_ACTIVITY_RETRY_POLICY,)diff --git a/posthog/temporal/llm_analytics/trace_clustering/tests/test_workflow.py b/posthog/temporal/llm_analytics/trace_clustering/tests/test_workflow.pyindex ae56a2c9ba87..a408a28e2005 100644--- a/posthog/temporal/llm_analytics/trace_clustering/tests/test_workflow.py+++ b/posthog/temporal/llm_analytics/trace_clustering/tests/test_workflow.py@@ -1,22 +1,31 @@"""Tests for trace clustering workflow."""+import uuid+import pytestimport numpy as np+from temporalio import activity+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Workerfrom posthog.temporal.llm_analytics.trace_clustering.clustering import perform_kmeans_with_optimal_kfrom posthog.temporal.llm_analytics.trace_clustering.constants import DEFAULT_MAX_SAMPLESfrom posthog.temporal.llm_analytics.trace_clustering.models import (+ ClusterAggregateMetrics,ClusteringActivityInputs,ClusteringComputeResult,+ ClusteringResult,ClusteringWorkflowInputs,ClusterItem,ClusterLabel,+ ComputeAggregatesActivityInputs,EmitEventsActivityInputs,GenerateLabelsActivityInputs,GenerateLabelsActivityOutputs,TraceLabelingMetadata,)+from posthog.temporal.llm_analytics.trace_clustering.workflow import DailyTraceClusteringWorkflow@pytest.fixture@@ -262,3 +271,74 @@ class TestActivityInputOutputModels:assert len(inputs.centroid_coords_2d) == 2assert inputs.job_id == ""assert inputs.job_name == ""+++class TestEmptyComputeResultShortCircuit:+ """Empty compute results must not trigger labeling/aggregates/emission.++ Emitting an empty $ai_*_clusters event would re-enroll the team in+ discovery for the next 30 days (see fix #1 in the loop bug analysis).+ """++ @staticmethod+ def _build_short_circuit_activities() -> dict[str, list[str]]:+ return {"calls": []}++ @pytest.mark.asyncio+ async def test_empty_compute_skips_label_aggregates_and_emit(self):+ calls: list[str] = []++ @activity.defn(name="perform_clustering_compute_activity")+ async def mock_compute(inputs: ClusteringActivityInputs) -> ClusteringComputeResult:+ calls.append("compute")+ return ClusteringComputeResult(+ clustering_run_id="run-empty",+ items=[],+ labels=[],+ centroids=[],+ distances=[],+ coords_2d=[],+ centroid_coords_2d=[],+ probabilities=[],+ analysis_level=inputs.analysis_level,+ num_noise_points=0,+ batch_run_ids={},+ )++ @activity.defn(name="generate_cluster_labels_activity")+ async def mock_labels(inputs: GenerateLabelsActivityInputs) -> GenerateLabelsActivityOutputs:+ calls.append("labels")+ return GenerateLabelsActivityOutputs(cluster_labels={})++ @activity.defn(name="compute_cluster_aggregates_activity")+ async def mock_aggregates(inputs: ComputeAggregatesActivityInputs) -> dict[int, ClusterAggregateMetrics]:+ calls.append("aggregates")+ return {}++ @activity.defn(name="emit_cluster_events_activity")+ async def mock_emit(inputs: EmitEventsActivityInputs) -> ClusteringResult:+ calls.append("emit")+ raise AssertionError("emit must not be called when compute returns no items")++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[DailyTraceClusteringWorkflow],+ activities=[mock_compute, mock_labels, mock_aggregates, mock_emit],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ result: ClusteringResult = await env.client.execute_workflow(+ DailyTraceClusteringWorkflow.run,+ ClusteringWorkflowInputs(team_id=1, lookback_days=7),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert calls == ["compute"]+ assert result.metrics.total_items_analyzed == 0+ assert result.metrics.num_clusters == 0+ assert result.clusters == []+ assert result.clustering_run_id == "run-empty"+ assert result.team_id == 1diff --git a/posthog/temporal/llm_analytics/trace_clustering/workflow.py b/posthog/temporal/llm_analytics/trace_clustering/workflow.pyindex bf3dd0d3656d..22da23bcaa34 100644--- a/posthog/temporal/llm_analytics/trace_clustering/workflow.py+++ b/posthog/temporal/llm_analytics/trace_clustering/workflow.py@@ -42,6 +42,7 @@ from posthog.temporal.llm_analytics.trace_clustering.models import (ClusterAggregateMetrics,ClusteringActivityInputs,ClusteringComputeResult,+ ClusteringMetrics,ClusteringParams,ClusteringResult,ClusteringWorkflowInputs,@@ -198,6 +199,23 @@ class DailyTraceClusteringWorkflow(PostHogWorkflow):record_items_analyzed(len(compute_result.items), analysis_level)record_noise_points(compute_result.num_noise_points, analysis_level)+ if not compute_result.items:+ workflow.logger.info(+ "Skipping label/aggregates/emit: compute returned no items",+ team_id=inputs.team_id,+ analysis_level=analysis_level,+ )+ record_clusters_generated(0, analysis_level)+ return ClusteringResult(+ clustering_run_id=compute_result.clustering_run_id,+ team_id=inputs.team_id,+ timestamp=now.isoformat(),+ window_start=window_start,+ window_end=window_end,+ metrics=ClusteringMetrics(total_items_analyzed=0, num_clusters=0, duration_seconds=0.0),+ clusters=[],+ )+# Compute per-item metadata for labeling (O(n) instead of O(n × k))item_metadata = _compute_item_labeling_metadata(compute_result)