: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(llma): remove old sentiment clustering workflow (#66354)
Radu Raicea8432aeb013f6
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 5ae30cc00634..b3d9c7ab1589 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -25,8 +25,6 @@ from posthog.temporal.ai_observability import (ACTIVITIES as LLM_ANALYTICS_ACTIVITIES,EVAL_ACTIVITIES as LLM_ANALYTICS_EVAL_ACTIVITIES,EVAL_WORKFLOWS as LLM_ANALYTICS_EVAL_WORKFLOWS,- SENTIMENT_ACTIVITIES as LLM_ANALYTICS_SENTIMENT_ACTIVITIES,- SENTIMENT_WORKFLOWS as LLM_ANALYTICS_SENTIMENT_WORKFLOWS,TAGGER_ACTIVITIES as LLM_ANALYTICS_TAGGER_ACTIVITIES,TAGGER_WORKFLOWS as LLM_ANALYTICS_TAGGER_WORKFLOWS,WORKFLOWS as LLM_ANALYTICS_WORKFLOWS,@@ -383,11 +381,6 @@ _task_queue_specs = [LLM_ANALYTICS_EVAL_WORKFLOWS + LLM_ANALYTICS_TAGGER_WORKFLOWS,LLM_ANALYTICS_EVAL_ACTIVITIES + LLM_ANALYTICS_TAGGER_ACTIVITIES,),- (- settings.LLMA_SENTIMENT_TASK_QUEUE,- LLM_ANALYTICS_SENTIMENT_WORKFLOWS,- LLM_ANALYTICS_SENTIMENT_ACTIVITIES,- ),(settings.LLMA_TASK_QUEUE,LLM_ANALYTICS_WORKFLOWS,diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 5fe05c960e1e..ff6cebe8ff0c 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -124,7 +124,6 @@ REPLAY_VISION_TASK_QUEUE = _set_temporal_task_queue("replay-vision-task-queue")SURFACING_SCORING_SWEEP_TASK_QUEUE = SESSION_REPLAY_TASK_QUEUEWEEKLY_DIGEST_TASK_QUEUE = _set_temporal_task_queue("weekly-digest-task-queue")LLMA_EVALS_TASK_QUEUE = _set_temporal_task_queue("llm-analytics-evals-task-queue")-LLMA_SENTIMENT_TASK_QUEUE = _set_temporal_task_queue("llm-analytics-sentiment-task-queue")LLMA_TASK_QUEUE = _set_temporal_task_queue("llm-analytics-task-queue")MCPA_TASK_QUEUE = _set_temporal_task_queue("mcp-analytics-task-queue")ERROR_TRACKING_TASK_QUEUE = _set_temporal_task_queue("error-tracking-task-queue")diff --git a/posthog/temporal/ai_observability/__init__.py b/posthog/temporal/ai_observability/__init__.pyindex bdbc5336c33e..983c476c3f58 100644--- a/posthog/temporal/ai_observability/__init__.py+++ b/posthog/temporal/ai_observability/__init__.py@@ -51,7 +51,6 @@ from posthog.temporal.ai_observability.run_tagger import (execute_tagger_activity,fetch_tagger_activity,)-from posthog.temporal.ai_observability.sentiment import ClassifySentimentWorkflow, classify_sentiment_activityfrom posthog.temporal.ai_observability.shared_activities import (fetch_all_clustering_filters_activity,fetch_all_clustering_jobs_activity,@@ -106,14 +105,6 @@ TAGGER_ACTIVITIES = [disable_tagger_activity,]-SENTIMENT_WORKFLOWS = [- ClassifySentimentWorkflow,-]--SENTIMENT_ACTIVITIES = [- classify_sentiment_activity,-]-WORKFLOWS = [BatchTraceSummarizationWorkflow,BatchTraceSummarizationCoordinatorWorkflow,@@ -129,8 +120,6 @@ WORKFLOWS = [AIObservabilityEvaluationSamplerWorkflow,AIObservabilityEvaluationClusteringCoordinatorWorkflow,AIObservabilityEvaluationClusteringWorkflow,- # Keep sentiment workflow registered here temporarily so orphaned workflows on general-purpose queue can complete- ClassifySentimentWorkflow,# Keep eval workflow registered here temporarily so orphaned workflows on general-purpose queue can completeRunEvaluationWorkflow,]@@ -166,8 +155,6 @@ ACTIVITIES = [generate_evaluation_cluster_labels_activity,compute_evaluation_cluster_aggregates_activity,emit_evaluation_cluster_events_activity,- # Keep sentiment activity registered here temporarily so orphaned workflows on general-purpose queue can complete- classify_sentiment_activity,# Keep eval activities registered here temporarily so orphaned workflows on general-purpose queue can completefetch_evaluation_activity,increment_trial_eval_count_activity,diff --git a/posthog/temporal/ai_observability/eval_reports/metrics.py b/posthog/temporal/ai_observability/eval_reports/metrics.pyindex 5acbb467081f..911b958f394d 100644--- a/posthog/temporal/ai_observability/eval_reports/metrics.py+++ b/posthog/temporal/ai_observability/eval_reports/metrics.py@@ -1,6 +1,6 @@"""Prometheus metrics for the LLMA evaluation reports temporal workflows.-Follows the same pattern as trace_clustering/metrics.py and sentiment/metrics.py.+Follows the same pattern as trace_clustering/metrics.py.Metrics are emitted via Temporal's built-in metric meter (activity/workflow context)and scraped by the Prometheus endpoint on the worker pod."""diff --git a/posthog/temporal/ai_observability/evaluation_clustering/aggregates.py b/posthog/temporal/ai_observability/evaluation_clustering/aggregates.pyindex 524b55e04e8c..da860799b8d3 100644--- a/posthog/temporal/ai_observability/evaluation_clustering/aggregates.py+++ b/posthog/temporal/ai_observability/evaluation_clustering/aggregates.py@@ -5,6 +5,10 @@ linked $ai_generation event) and eval-specific metrics (pass_rate, na_rate,dominant_evaluation_name, dominant_runtime, avg_judge_cost) on:class:`ClusterAggregateMetrics`. All new eval fields stay None for non-evallevels so the dataclass remains single-typed across the whole pipeline.++Sentiment evaluations can be clustered like any other evaluation. Their stored+sentiment labels/scores are evaluation result data, not the removed on-read+cluster sentiment aggregate."""from collections import Counter@@ -117,7 +121,6 @@ def _aggregate_single_cluster(error_rate=(items_with_errors / items_with_operational_data) if items_with_operational_data else None,error_count=items_with_errors,item_count=len(eval_event_ids),- sentiment=None, # not applicable for eval clusters# Eval-specificpass_rate=(pass_count / verdict_count) if verdict_count else None,na_rate=(na_count / verdict_count) if verdict_count else None,diff --git a/posthog/temporal/ai_observability/evaluation_sentiment.py b/posthog/temporal/ai_observability/evaluation_sentiment.pyindex ff070b139270..9c8d2b9c9b06 100644--- a/posthog/temporal/ai_observability/evaluation_sentiment.py+++ b/posthog/temporal/ai_observability/evaluation_sentiment.py@@ -2,7 +2,7 @@ import jsonimport asynciofrom typing import Any-import temporalio+from temporalio import activityfrom temporalio.exceptions import ApplicationErrorfrom posthog.temporal.ai_observability.evaluation_event_io import extract_event_io@@ -61,7 +61,7 @@ def _build_sentiment_activity_result(}async def execute_sentiment_eval_activity(evaluation: dict[str, Any], event_data: dict[str, Any]) -> EvaluationActivityResult:diff --git a/posthog/temporal/ai_observability/sentiment/README.md b/posthog/temporal/ai_observability/sentiment/README.mdindex 568c87e99d89..053bc1818c70 100644--- a/posthog/temporal/ai_observability/sentiment/README.md+++ b/posthog/temporal/ai_observability/sentiment/README.md@@ -6,26 +6,19 @@ The classifier analyzes user messages from `$ai_generation` events using an ONNX## How it works-There are two call paths:--1. Sentiment AI evaluations run through the evaluation workflow, classify the target generation's user messages, and emit stored `$ai_evaluation` events with `$ai_sentiment_*` properties.-2. Trace clustering can still call the `llma-sentiment-classify` Temporal workflow for best-effort aggregate sentiment.+Sentiment AI evaluations run through the evaluation workflow, classify the target generation's user messages, and emit stored `$ai_evaluation` events with `$ai_sentiment_*` properties.The AI observability UI reads stored sentiment evaluation events. It does not trigger on-read sentiment classification.## Package structure-| File | Purpose |-| --------------- | --------------------------------------------------------------------------------- |-| `schema.py` | Dataclasses: `ClassifySentimentInput`, `SentimentResult`, `PendingClassification` |-| `workflow.py` | Temporal workflow definition |-| `activities.py` | Temporal activity (orchestration) |-| `data.py` | HogQL query execution and row grouping |-| `model.py` | ONNX model loading and `classify()` |-| `extraction.py` | User message extraction from `$ai_input` |-| `utils.py` | Shared helpers: result building, date resolution, score averaging |-| `constants.py` | Config values, caps, and the HogQL query template |-| `metrics.py` | Prometheus metrics and Temporal interceptor |+| File | Purpose |+| --------------- | ------------------------------------------------------- |+| `schema.py` | Dataclasses: `SentimentResult`, `PendingClassification` |+| `model.py` | ONNX model loading and `classify()` |+| `extraction.py` | User message extraction from `$ai_input` |+| `utils.py` | Shared helpers for result building and score averaging |+| `constants.py` | Model config and extraction caps |## Local development@@ -64,8 +57,8 @@ This is a no-op if the model already exists.### Runtime CPU controlsThe ONNX Runtime session defaults to one intra-op and one inter-op thread to-avoid CPU oversubscription when Temporal runs multiple-sentiment activities concurrently.+avoid CPU oversubscription when Temporal runs multiple evaluation activities+concurrently.Override these only for a dedicated worker with measured headroom:```bash@@ -79,8 +72,7 @@ POSTHOG_SENTIMENT_ONNX_INTER_OP_NUM_THREADS=1pytest posthog/temporal/ai_observability/sentiment/ -x -q```-Tests mock the model and HogQL layer so the sentiment dependency group-is not required to run them.+Tests mock the model so the sentiment dependency group is not required to run them.## UI data flowdiff --git a/posthog/temporal/ai_observability/sentiment/__init__.py b/posthog/temporal/ai_observability/sentiment/__init__.pyindex 604a792a4ccd..c1b4ea1c6275 100644--- a/posthog/temporal/ai_observability/sentiment/__init__.py+++ b/posthog/temporal/ai_observability/sentiment/__init__.py@@ -1,7 +1 @@-from posthog.temporal.ai_observability.sentiment.activities import classify_sentiment_activity-from posthog.temporal.ai_observability.sentiment.workflow import ClassifySentimentWorkflow--__all__ = [- "ClassifySentimentWorkflow",- "classify_sentiment_activity",-]+"""Sentiment evaluation helpers for AI observability."""diff --git a/posthog/temporal/ai_observability/sentiment/activities.py b/posthog/temporal/ai_observability/sentiment/activities.pydeleted file mode 100644index d023623d06e7..000000000000--- a/posthog/temporal/ai_observability/sentiment/activities.py+++ /dev/null@@ -1,148 +0,0 @@-"""Temporal activity for sentiment classification.--Fetches $ai_generation events, extracts user messages, and classifies-sentiment via the ONNX model. Supports both trace-level and generation-level-analysis, controlled by `analysis_level` on the input.-"""--import time-import asyncio-from typing import Any--import structlog-import temporalio--from posthog.temporal.ai_observability.sentiment.schema import ClassifySentimentInput, PendingClassification-from posthog.temporal.ai_observability.sentiment.utils import (- build_generation_result,- build_trace_result,- collect_pending,- resolve_date_bounds,-)--logger = structlog.get_logger(__name__)---async def classify_sentiment_activity(input: ClassifySentimentInput) -> dict[str, dict[str, Any]]:- """Classify sentiment for traces or individual generations.-- When analysis_level="trace", fetches all generations per trace and- builds trace-level aggregated results.- When analysis_level="generation", fetches specific events by UUID- and builds per-generation results.- """- from posthog.sync import database_sync_to_async- from posthog.temporal.ai_observability.sentiment.constants import MAX_CLASSIFICATIONS_PER_TRACE- from posthog.temporal.ai_observability.sentiment.data import fetch_generations, fetch_generations_by_uuid- from posthog.temporal.ai_observability.sentiment.metrics import (- record_generations_classified,- record_generations_fetched,- record_inference_time_ms,- record_messages_classified,- record_query_time_ms,- record_traces_classified,- )- from posthog.temporal.ai_observability.sentiment.model import classify-- resolved_from, resolved_to = resolve_date_bounds(input.date_from, input.date_to)- is_generation = input.analysis_level == "generation"-- # 1. Fetch — different query and grouping per level- t0 = time.monotonic()- if is_generation:- rows, total_input_bytes = await database_sync_to_async(- lambda: fetch_generations_by_uuid(input.team_id, input.ids, resolved_from, resolved_to),- thread_sensitive=False,- )()- rows_by_id: dict[str, list[tuple[str, object]]] = {}- for event_uuid, ai_input in rows:- rows_by_id.setdefault(event_uuid, []).append((event_uuid, ai_input))- total_generations = len(rows)- else:- fetch = await database_sync_to_async(- lambda: fetch_generations(input.team_id, input.ids, resolved_from, resolved_to),- thread_sensitive=False,- )()- rows_by_id = fetch.rows_by_trace- total_generations = sum(len(r) for r in rows_by_id.values())- total_input_bytes = fetch.total_input_bytes- query_ms = (time.monotonic() - t0) * 1000-- record_query_time_ms(query_ms)- record_generations_fetched(total_generations)-- # 2. Collect pending — same for both levels- pending: list[PendingClassification] = []- for id_ in input.ids:- pending.extend(collect_pending(rows_by_id.get(id_, []), id_, MAX_CLASSIFICATIONS_PER_TRACE))-- # 3. Classify — same for both levels- t1 = time.monotonic()- all_results = await asyncio.to_thread(classify, [p.text for p in pending]) if pending else []- inference_ms = (time.monotonic() - t1) * 1000-- if pending:- record_inference_time_ms(inference_ms)- record_messages_classified(len(pending))-- # 4. Build results — different aggregation per level- output: dict[str, dict[str, Any]] = {}- per_gen_for_cache: dict[str, dict[str, dict[str, Any]]] = {}- offset = 0- for id_ in input.ids:- if is_generation:- gen_pending = [p for p in pending if p.gen_uuid == id_]- gen_results = all_results[offset : offset + len(gen_pending)]- output[id_] = build_generation_result(id_, gen_pending, gen_results)- offset += len(gen_pending)- else:- trace_result, per_gen, consumed = build_trace_result(id_, pending, all_results, offset)- output[id_] = trace_result.to_dict()- per_gen_for_cache[id_] = per_gen- offset += consumed-- if is_generation:- record_generations_classified(len(output))- else:- record_traces_classified(len(input.ids))-- # 5. Cache — key format: llma_sentiment:{level}:{team_id}:{id}- # Trace level also dual-writes generation cache entries- from django.core.cache import cache-- from posthog.temporal.ai_observability.sentiment.constants import CACHE_KEY_PREFIX, CACHE_TTL-- def _cache_key(level: str, id_: str) -> str:- return f"{CACHE_KEY_PREFIX}:{level}:{input.team_id}:{id_}"-- to_cache: dict[str, dict] = {}- for id_, result in output.items():- to_cache[_cache_key(input.analysis_level, id_)] = result- if not is_generation:- for gen_uuid, gen_data in per_gen_for_cache.get(id_, {}).items():- to_cache[_cache_key("generation", gen_uuid)] = gen_data- if to_cache:- try:- cache.set_many(to_cache, timeout=CACHE_TTL)- except Exception:- logger.warning(- "Failed to cache sentiment results",- team_id=input.team_id,- trace_count=len(to_cache),- exc_info=True,- )-- logger.info(- "Sentiment activity completed",- team_id=input.team_id,- analysis_level=input.analysis_level,- id_count=len(input.ids),- generations_fetched=total_generations,- input_kb=round(total_input_bytes / 1024, 1) if total_input_bytes else 0,- messages_classified=len(pending),- query_ms=round(query_ms),- inference_ms=round(inference_ms) if pending else 0,- )-- return outputdiff --git a/posthog/temporal/ai_observability/sentiment/constants.py b/posthog/temporal/ai_observability/sentiment/constants.pyindex 5a7faac7a0bd..232e827ba67f 100644--- a/posthog/temporal/ai_observability/sentiment/constants.py+++ b/posthog/temporal/ai_observability/sentiment/constants.py@@ -29,73 +29,3 @@ SENTIMENT_EVAL_MESSAGE_HEAD_CHARS = 300# Batch classificationCLASSIFY_BATCH_SIZE = 32 # texts per ONNX forward pass-MAX_CLASSIFICATIONS_PER_TRACE = 200-MAX_GENERATIONS_PER_TRACE = 10 # per-trace cap enforced by window function in ClickHouse-MAX_INPUT_CHARS = 300_000 # skip $ai_input longer than this (covers p99; extraction truncates before inference)-MAX_INPUT_CHARS_GENERATION = 1_000_000 # higher limit for generation-level — user asked for specific UUIDs-QUERY_LOOKBACK_DAYS = 7 # fallback timestamp filter when caller omits date range--# Temporal workflow/activity config-WORKFLOW_NAME = "llma-sentiment-classify"-ACTIVITY_TIMEOUT_SECONDS = 120 # start-to-close timeout for classify activity-ACTIVITY_SCHEDULE_TO_START_TIMEOUT_SECONDS = 30 # fail fast if no worker picks up the activity-WORKFLOW_TIMEOUT_BATCH_SECONDS = 120 # task timeout for sentiment workflow-MAX_RETRY_ATTEMPTS = 2 # retry policy for both workflow and activity--# Cache config-CACHE_TTL = 60 * 60 * 24 # 24 hours — events are immutable once ingested-CACHE_KEY_PREFIX = "llma_sentiment" # key format: {prefix}:{level}:{team_id}:{id}--# API config-BATCH_MAX_TRACE_IDS = 5-BATCH_MAX_GENERATION_IDS = 5 # keep small to avoid upstream request timeouts--# HogQL query template for fetching $ai_generation events.-# Uses a window function to cap rows per trace at the ClickHouse level,-# and a size filter to skip accumulated conversation histories — the same-# user messages appear in earlier, smaller generations so we lose nothing.-#-# Reads from `posthog.ai_events`, where the heavy `input` column lives as a-# native column (it is not stored on `events.properties.$ai_input`).-# `query_ai_events` rewrites this back to `events.properties.$ai_*` for the-# retention-window fallback.-GENERATIONS_QUERY = """- SELECT uuid, ai_input, trace_id- FROM (- SELECT- uuid,- input AS ai_input,- trace_id,- row_number() OVER (- PARTITION BY trace_id- ORDER BY timestamp DESC- ) AS rn- FROM posthog.ai_events AS ai_events- WHERE event = '$ai_generation'- AND timestamp >= toDateTime({date_from}, 'UTC')- AND timestamp <= toDateTime({date_to}, 'UTC')- AND trace_id IN {trace_ids}- -- skip huge accumulated conversation histories- AND length(input) <= {max_input_chars}- )- -- last N qualified generations per trace- WHERE rn <= {max_gens_per_trace}- ORDER BY trace_id, rn-"""--# Fetch specific generation events by UUID — no window function needed.-# No length() filter here: on the events fallback it translates to-# JSONExtractRaw on every scanned row which is expensive on high-volume-# teams (benchmarked 2.4x slower). The size check is applied post-fetch-# in Python instead.-GENERATIONS_BY_UUID_QUERY = """- SELECT- uuid,- input AS ai_input- FROM posthog.ai_events AS ai_events- WHERE event = '$ai_generation'- AND trace_id IN {trace_ids}- AND timestamp >= toDateTime({date_from}, 'UTC')- AND timestamp <= toDateTime({date_to}, 'UTC')- AND uuid IN {uuids}-"""diff --git a/posthog/temporal/ai_observability/sentiment/data.py b/posthog/temporal/ai_observability/sentiment/data.pydeleted file mode 100644index 019a4512e548..000000000000--- a/posthog/temporal/ai_observability/sentiment/data.py+++ /dev/null@@ -1,163 +0,0 @@-"""Data access for sentiment classification.--Fetches $ai_generation events from ClickHouse via HogQL and groups-results by trace_id for downstream processing.-"""--import json-from dataclasses import dataclass, field--from posthog.clickhouse.query_tagging import Feature, Product, tags_context-from posthog.temporal.ai_observability.sentiment.constants import (- GENERATIONS_BY_UUID_QUERY,- GENERATIONS_QUERY,- MAX_GENERATIONS_PER_TRACE,- MAX_INPUT_CHARS,- MAX_INPUT_CHARS_GENERATION,-)---@dataclass-class FetchResult:- rows_by_trace: dict[str, list[tuple[str, object]]] = field(default_factory=dict)- total_input_bytes: int = 0---def fetch_generations(- team_id: int,- trace_ids: list[str],- date_from: str,- date_to: str,-) -> FetchResult:- """Fetch $ai_generation events and group by trace_id.-- Returns a FetchResult with rows grouped by trace_id (at most- MAX_GENERATIONS_PER_TRACE per trace) and total raw input bytes- transferred from ClickHouse.- """- from posthog.hogql import ast- from posthog.hogql.constants import LimitContext- from posthog.hogql.parser import parse_select-- from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events- from posthog.models.team import Team-- team = Team.objects.get(id=team_id)- query = parse_select(GENERATIONS_QUERY)- with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team_id):- result = query_ai_events(- query=query,- placeholders={- "date_from": ast.Constant(value=date_from),- "date_to": ast.Constant(value=date_to),- "trace_ids": ast.Tuple(exprs=[ast.Constant(value=tid) for tid in trace_ids]),- "max_input_chars": ast.Constant(value=MAX_INPUT_CHARS),- "max_gens_per_trace": ast.Constant(value=MAX_GENERATIONS_PER_TRACE),- },- team=team,- query_type="SentimentOnDemand",- fall_back_to_events=True,- limit_context=LimitContext.QUERY_ASYNC,- )-- fetch = FetchResult()- for row in result.results or []:- row_trace_id = str(row[2])- raw_ai_input = row[1]- if isinstance(raw_ai_input, str):- fetch.total_input_bytes += len(raw_ai_input.encode("utf-8"))- try:- ai_input = json.loads(raw_ai_input)- except (json.JSONDecodeError, ValueError):- continue- else:- ai_input = raw_ai_input- fetch.rows_by_trace.setdefault(row_trace_id, []).append((str(row[0]), ai_input))-- return fetch---def fetch_generations_by_uuid(- team_id: int,- generation_ids: list[str],- date_from: str,- date_to: str,-) -> tuple[list[tuple[str, object]], int]:- """Fetch specific $ai_generation events by UUID.-- Simpler than fetch_generations — no window function, no trace grouping.- Returns a flat list of (uuid, ai_input) tuples.-- Uses a two-query pattern: the `(team_id, trace_id, timestamp)` sorting- key + cityHash64 sharding key on `ai_events` mean a `WHERE uuid IN (...)`- fan-out reads heavy `input` on every shard. So we first resolve uuid →- trace_id off `events` (cheap small-column read using the events sorting- key) and pass the resulting trace_ids into the heavy fetch — keeping- the heavy read on a single shard.- """- from datetime import UTC, datetime-- from posthog.hogql import ast- from posthog.hogql.constants import LimitContext- from posthog.hogql.parser import parse_select-- from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events- from posthog.hogql_queries.ai.trace_id_resolver import resolve_trace_ids_for_generation_uuids- from posthog.models.team import Team-- team = Team.objects.get(id=team_id)-- # `date_from` / `date_to` arrive as `%Y-%m-%d %H:%M:%S` strings (per- # `resolve_date_bounds`). Parse them to UTC datetimes so the trace-id- # resolver can serialize them through HogQL placeholder substitution.- ts_start = datetime.strptime(date_from, "%Y-%m-%d %H:%M:%S").replace(tzinfo=UTC)- ts_end = datetime.strptime(date_to, "%Y-%m-%d %H:%M:%S").replace(tzinfo=UTC)-- trace_id_by_uuid = resolve_trace_ids_for_generation_uuids(- team=team,- generation_uuids=generation_ids,- ts_start=ts_start,- ts_end=ts_end,- query_type="SentimentTraceIdResolve",- )- trace_ids = sorted({tid for tid in trace_id_by_uuid.values() if tid})- if not trace_ids:- return [], 0-- query = parse_select(GENERATIONS_BY_UUID_QUERY)- with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team_id):- result = query_ai_events(- query=query,- placeholders={- "date_from": ast.Constant(value=date_from),- "date_to": ast.Constant(value=date_to),- "uuids": ast.Tuple(exprs=[ast.Constant(value=uid) for uid in generation_ids]),- "trace_ids": ast.Tuple(exprs=[ast.Constant(value=tid) for tid in trace_ids]),- },- team=team,- query_type="SentimentOnDemandGeneration",- fall_back_to_events=True,- limit_context=LimitContext.QUERY_ASYNC,- )-- # Size guard applied post-fetch instead of in SQL — the SQL length()- # filter forced JSONExtractRaw on every scanned row, 2.4x slower on- # high-volume teams. Here we just skip before json.loads to avoid- # wasting time parsing huge payloads we'll mostly discard anyway.- rows: list[tuple[str, object]] = []- total_input_bytes = 0- for row in result.results or []:- raw_ai_input = row[1]- if isinstance(raw_ai_input, str):- if len(raw_ai_input) > MAX_INPUT_CHARS_GENERATION:- continue- total_input_bytes += len(raw_ai_input.encode("utf-8"))- try:- ai_input = json.loads(raw_ai_input)- except (json.JSONDecodeError, ValueError):- continue- else:- ai_input = raw_ai_input- rows.append((str(row[0]), ai_input))-- return rows, total_input_bytesdiff --git a/posthog/temporal/ai_observability/sentiment/metrics.py b/posthog/temporal/ai_observability/sentiment/metrics.pydeleted file mode 100644index 84704fadfd87..000000000000--- a/posthog/temporal/ai_observability/sentiment/metrics.py+++ /dev/null@@ -1,221 +0,0 @@-"""Prometheus metrics for the LLMA sentiment classification temporal workflows.--Follows the same pattern as trace_clustering/metrics.py.-Metrics are emitted via Temporal's built-in metric meter (activity/workflow context)-and scraped by the Prometheus endpoint on the worker pod.-"""--import typing-import datetime as dt--from django.conf import settings--from temporalio import activity, workflow-from temporalio.worker import (- ActivityInboundInterceptor,- ExecuteActivityInput,- ExecuteWorkflowInput,- Interceptor,- WorkflowInboundInterceptor,- WorkflowInterceptorClassInput,-)--from posthog.temporal.ai_observability.metrics import ExecutionTimeRecorder, get_metric_meter--# ----------------------------------------------------------------------------# Histogram bucket config (imported by common/worker.py for PrometheusConfig)-# -----------------------------------------------------------------------------SENTIMENT_LATENCY_HISTOGRAM_METRICS = (- "llma_sentiment_activity_execution_latency",- "llma_sentiment_activity_schedule_to_start_latency",- "llma_sentiment_workflow_execution_latency",- "llma_sentiment_query_time",- "llma_sentiment_inference_time",-)-SENTIMENT_LATENCY_HISTOGRAM_BUCKETS = [- 100.0, # 100ms- 500.0, # 500ms- 1_000.0, # 1 second- 2_000.0, # 2 seconds- 5_000.0, # 5 seconds- 10_000.0, # 10 seconds- 30_000.0, # 30 seconds- 60_000.0, # 1 minute- 120_000.0, # 2 minutes-]--# ----------------------------------------------------------------------------# Activity / workflow type sets for the interceptor-# -----------------------------------------------------------------------------SENTIMENT_ACTIVITY_TYPES = {- "classify_sentiment_activity",-}--SENTIMENT_WORKFLOW_TYPES = {- "llma-sentiment-classify",-}--# ----------------------------------------------------------------------------# Counter helpers-# ------------------------------------------------------------------------------def increment_workflow_started(workflow_type: str) -> None:- meter = get_metric_meter({"workflow_type": workflow_type})- meter.create_counter(- "llma_sentiment_workflow_started",- "Sentiment workflows started",- ).add(1)---def increment_workflow_finished(status: str, workflow_type: str) -> None:- meter = get_metric_meter({"status": status, "workflow_type": workflow_type})- meter.create_counter(- "llma_sentiment_workflow_finished",- "Sentiment workflows finished",- ).add(1)---def record_traces_classified(count: int) -> None:- if not activity.in_activity() and not workflow.in_workflow():- return- meter = get_metric_meter()- meter.create_counter(- "llma_sentiment_traces_classified",- "Traces classified for sentiment",- ).add(count)---def record_messages_classified(count: int) -> None:- if not activity.in_activity() and not workflow.in_workflow():- return- meter = get_metric_meter()- meter.create_counter(- "llma_sentiment_messages_classified",- "Messages classified for sentiment",- ).add(count)---def record_generations_fetched(count: int) -> None:- if not activity.in_activity() and not workflow.in_workflow():- return- meter = get_metric_meter()- meter.create_counter(- "llma_sentiment_generations_fetched",- "Generation rows fetched from ClickHouse",- ).add(count)---def record_query_time_ms(duration_ms: float) -> None:- if not activity.in_activity() and not workflow.in_workflow():- return- meter = get_metric_meter()- meter.create_histogram_timedelta(- name="llma_sentiment_query_time",- description="ClickHouse query time",- unit="ms",- ).record(dt.timedelta(milliseconds=duration_ms))---def record_inference_time_ms(duration_ms: float) -> None:- if not activity.in_activity() and not workflow.in_workflow():- return- meter = get_metric_meter()- meter.create_histogram_timedelta(- name="llma_sentiment_inference_time",- description="ONNX model inference time",- unit="ms",- ).record(dt.timedelta(milliseconds=duration_ms))---def record_generations_classified(count: int) -> None:- if not activity.in_activity() and not workflow.in_workflow():- return- meter = get_metric_meter()- meter.create_counter(- "llma_sentiment_generations_classified",- "Individual generations classified for sentiment",- ).add(count)---def increment_errors(error_type: str) -> None:- if not activity.in_activity() and not workflow.in_workflow():- return- meter = get_metric_meter({"error_type": error_type})- meter.create_counter(- "llma_sentiment_errors",- "Error counts by type",- ).add(1)---# ----------------------------------------------------------------------------# Interceptor — automatic timing for activities and workflows-# ------------------------------------------------------------------------------class SentimentMetricsInterceptor(Interceptor):- """Interceptor to emit Prometheus metrics for sentiment workflows."""-- task_queue = settings.LLMA_SENTIMENT_TASK_QUEUE-- def intercept_activity(self, next: ActivityInboundInterceptor) -> ActivityInboundInterceptor:- return _SentimentActivityInterceptor(super().intercept_activity(next))-- def workflow_interceptor_class(- self, input: WorkflowInterceptorClassInput- ) -> type[WorkflowInboundInterceptor] | None:- return _SentimentWorkflowInterceptor---class _SentimentActivityInterceptor(ActivityInboundInterceptor):- async def execute_activity(self, input: ExecuteActivityInput) -> typing.Any:- activity_info = activity.info()- activity_type = activity_info.activity_type-- if activity_type not in SENTIMENT_ACTIVITY_TYPES:- return await super().execute_activity(input)-- # Schedule-to-start latency (queue depth indicator)- scheduled_time = activity_info.scheduled_time- started_time = activity_info.started_time- if scheduled_time and started_time:- schedule_to_start_ms = int((started_time - scheduled_time).total_seconds() * 1000)- meter = get_metric_meter({"activity_type": activity_type})- meter.create_histogram_timedelta(- name="llma_sentiment_activity_schedule_to_start_latency",- description="Time between activity scheduling and start",- unit="ms",- ).record(dt.timedelta(milliseconds=schedule_to_start_ms))-- with ExecutionTimeRecorder(- "llma_sentiment_activity_execution_latency",- description="Execution latency for sentiment activities",- histogram_attributes={"activity_type": activity_type},- ):- return await super().execute_activity(input)---class _SentimentWorkflowInterceptor(WorkflowInboundInterceptor):- async def execute_workflow(self, input: ExecuteWorkflowInput) -> typing.Any:- workflow_info = workflow.info()- workflow_type = workflow_info.workflow_type-- if workflow_type not in SENTIMENT_WORKFLOW_TYPES:- return await super().execute_workflow(input)-- increment_workflow_started(workflow_type)-- with ExecutionTimeRecorder(- "llma_sentiment_workflow_execution_latency",- description="End-to-end workflow execution latency",- ):- try:- result = await super().execute_workflow(input)- increment_workflow_finished("completed", workflow_type)- return result- except Exception as e:- increment_errors(type(e).__name__)- increment_workflow_finished("failed", workflow_type)- raisediff --git a/posthog/temporal/ai_observability/sentiment/schema.py b/posthog/temporal/ai_observability/sentiment/schema.pyindex 85f22e06e043..23ede1df3a28 100644--- a/posthog/temporal/ai_observability/sentiment/schema.py+++ b/posthog/temporal/ai_observability/sentiment/schema.py@@ -1,16 +1,6 @@-"""Dataclasses for sentiment classification workflows."""+"""Dataclasses for sentiment evaluations."""-from dataclasses import dataclass, field-from typing import Any---@dataclass-class ClassifySentimentInput:- team_id: int- ids: list[str] # trace IDs or generation UUIDs depending on analysis_level- analysis_level: str = "trace" # "trace" or "generation"- date_from: str | None = None- date_to: str | None = None+from dataclasses import dataclass@dataclass@@ -24,28 +14,6 @@ class SentimentResult:return cls(label="neutral", score=0.0, scores={"positive": 0.0, "neutral": 0.0, "negative": 0.0})-@dataclass-class TraceResult:- label: str- score: float- scores: dict[str, float]- messages: dict[str, dict[str, Any]] = field(default_factory=dict)- message_count: int = 0-- @classmethod- def neutral(cls) -> "TraceResult":- return cls(label="neutral", score=0.0, scores={"positive": 0.0, "neutral": 0.0, "negative": 0.0})-- def to_dict(self) -> dict[str, Any]:- return {- "label": self.label,- "score": self.score,- "scores": self.scores,- "messages": self.messages,- "message_count": self.message_count,- }--@dataclassclass PendingClassification:trace_id: strdiff --git a/posthog/temporal/ai_observability/sentiment/tests/test_classify.py b/posthog/temporal/ai_observability/sentiment/tests/test_classify.pydeleted file mode 100644index 3965d17281a5..000000000000--- a/posthog/temporal/ai_observability/sentiment/tests/test_classify.py+++ /dev/null@@ -1,261 +0,0 @@-import pytest-from unittest.mock import MagicMock, patch--from posthog.temporal.ai_observability.sentiment.activities import classify_sentiment_activity-from posthog.temporal.ai_observability.sentiment.schema import ClassifySentimentInput, SentimentResult---def _make_row(uuid: str, messages: list[dict], trace_id: str = "trace-1") -> tuple:- return (uuid, messages, trace_id)---def _make_sentiment_result(label: str = "positive", score: float = 0.9) -> SentimentResult:- scores = {"positive": 0.05, "neutral": 0.05, "negative": 0.05}- scores[label] = score- return SentimentResult(label=label, score=score, scores=scores)---def _mock_hogql_result(rows: list[tuple]) -> MagicMock:- result = MagicMock()- result.results = rows- return result---def _single_input(trace_id: str = "trace-1", **kwargs) -> ClassifySentimentInput:- return ClassifySentimentInput(team_id=1, ids=[trace_id], **kwargs)---# `ai_table_resolver` imports `execute_hogql_query` at module top, so patching-# the source module wouldn't reach its local binding. Patch where it's used.-_PATCH_HOGQL = "posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query"-_PATCH_TEAM = "posthog.models.team.Team.objects"-_PATCH_CLASSIFY = "posthog.temporal.ai_observability.sentiment.model.classify"-_PATCH_CAP = "posthog.temporal.ai_observability.sentiment.constants.MAX_CLASSIFICATIONS_PER_TRACE"-# `fetch_generations_by_uuid` does a uuid → trace_id preflight via the-# resolver helper before the heavy fetch. Patch the source-module symbol-# (the resolver does `from posthog.hogql.query import execute_hogql_query`-# inside its body, so patching at the source propagates).-_PATCH_RESOLVE = "posthog.hogql_queries.ai.trace_id_resolver.resolve_trace_ids_for_generation_uuids"--[email protected](autouse=True)-def _mock_team():- with patch(_PATCH_TEAM) as mock_objects:- mock_objects.get.return_value = MagicMock(id=1)- yield--[email protected](autouse=True)-def _mock_trace_id_resolver():- """Resolver returns a synthetic trace_id per input uuid so the heavy fetch- isn't short-circuited as 'no generations found in window'."""- with patch(_PATCH_RESOLVE) as mock:- mock.side_effect = lambda team, generation_uuids, **kw: {u: f"trace-{u}" for u in generation_uuids}- yield---class TestClassifySentimentSingleTrace:- @pytest.mark.asyncio- @patch(_PATCH_HOGQL)- async def test_empty_query_returns_neutral(self, mock_hogql: MagicMock):- mock_hogql.return_value = _mock_hogql_result([])-- result = await classify_sentiment_activity(_single_input())-- assert result["trace-1"]["label"] == "neutral"- assert result["trace-1"]["message_count"] == 0-- @pytest.mark.asyncio- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_single_generation_single_message(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- _make_row("gen-1", [{"role": "user", "content": "I love this product"}]),- ]- )- mock_classify.return_value = [_make_sentiment_result("positive", 0.9)]-- result = await classify_sentiment_activity(_single_input())-- mock_classify.assert_called_once_with(["I love this product"])- assert result["trace-1"]["message_count"] == 1- assert result["trace-1"]["label"] == "positive"- # flat message keys use gen_uuid:msg_index format, all strings for orjson- messages = result["trace-1"]["messages"]- assert "gen-1:0" in messages- assert all(isinstance(k, str) for k in messages.keys())-- @pytest.mark.asyncio- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_multiple_generations_batched(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- _make_row("gen-1", [{"role": "user", "content": "msg-a"}]),- _make_row(- "gen-2",- [- {"role": "user", "content": "msg-b"},- {"role": "user", "content": "msg-c"},- ],- ),- ]- )- mock_classify.return_value = [- _make_sentiment_result("positive", 0.9),- _make_sentiment_result("negative", 0.8),- _make_sentiment_result("neutral", 0.7),- ]-- result = await classify_sentiment_activity(_single_input())-- mock_classify.assert_called_once_with(["msg-a", "msg-b", "msg-c"])- trace = result["trace-1"]- assert trace["message_count"] == 3- assert "gen-1:0" in trace["messages"]- assert "gen-2:0" in trace["messages"]- assert "gen-2:1" in trace["messages"]-- @pytest.mark.asyncio- @patch(_PATCH_CAP, 3)- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_cap_limits_total_classifications(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- _make_row("gen-1", [{"role": "user", "content": f"msg-{i}"} for i in range(5)]),- _make_row(- "gen-2",- [- {"role": "user", "content": "should-not-reach"},- ],- ),- ]- )- mock_classify.return_value = [- _make_sentiment_result("positive", 0.9),- _make_sentiment_result("neutral", 0.5),- _make_sentiment_result("negative", 0.8),- ]-- result = await classify_sentiment_activity(_single_input())-- texts_classified = mock_classify.call_args[0][0]- assert len(texts_classified) == 3- trace = result["trace-1"]- assert trace["message_count"] == 3- assert not any(k.startswith("gen-2:") for k in trace["messages"])-- @pytest.mark.asyncio- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_skips_generations_without_user_messages(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- _make_row("gen-1", [{"role": "assistant", "content": "no user msgs"}]),- _make_row("gen-2", [{"role": "user", "content": "a real message"}]),- ]- )- mock_classify.return_value = [_make_sentiment_result("positive", 0.9)]-- result = await classify_sentiment_activity(_single_input())-- mock_classify.assert_called_once_with(["a real message"])- trace = result["trace-1"]- assert not any(k.startswith("gen-1:") for k in trace["messages"])- assert "gen-2:0" in trace["messages"]-- @pytest.mark.asyncio- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_passes_absolute_date_range_to_query(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- _make_row("gen-1", [{"role": "user", "content": "hello"}]),- ]- )- mock_classify.return_value = [_make_sentiment_result("positive", 0.9)]-- await classify_sentiment_activity(_single_input(date_from="2025-01-01", date_to="2025-01-31"))-- call_kwargs = mock_hogql.call_args.kwargs- placeholders = call_kwargs["placeholders"]- assert placeholders["date_from"].value == "2025-01-01 00:00:00"- assert placeholders["date_to"].value == "2025-01-31 00:00:00"-- @pytest.mark.asyncio- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_resolves_relative_date_range(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- _make_row("gen-1", [{"role": "user", "content": "hello"}]),- ]- )- mock_classify.return_value = [_make_sentiment_result("positive", 0.9)]-- await classify_sentiment_activity(_single_input(date_from="-1h", date_to=None))-- call_kwargs = mock_hogql.call_args.kwargs- placeholders = call_kwargs["placeholders"]- # relative date should be resolved to an absolute timestamp- assert "20" in placeholders["date_from"].value # starts with year- assert ":" in placeholders["date_from"].value # has time component- assert placeholders["date_from"].value != "-1h" # not the raw relative string---class TestClassifySentimentBatch:- @pytest.mark.asyncio- @patch(_PATCH_HOGQL)- async def test_empty_query_returns_neutral_for_all(self, mock_hogql: MagicMock):- mock_hogql.return_value = _mock_hogql_result([])-- result = await classify_sentiment_activity(ClassifySentimentInput(team_id=1, ids=["t1", "t2"]))-- assert result["t1"]["label"] == "neutral"- assert result["t2"]["label"] == "neutral"-- @pytest.mark.asyncio- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_multiple_traces_single_query(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- _make_row("gen-1", [{"role": "user", "content": "hello from t1"}], "t1"),- _make_row("gen-2", [{"role": "user", "content": "hello from t2"}], "t2"),- ]- )- mock_classify.return_value = [- _make_sentiment_result("positive", 0.9),- _make_sentiment_result("negative", 0.8),- ]-- result = await classify_sentiment_activity(ClassifySentimentInput(team_id=1, ids=["t1", "t2"]))-- # One classify call with all texts- mock_classify.assert_called_once_with(["hello from t1", "hello from t2"])- # One execute_hogql_query call (single ClickHouse query)- mock_hogql.assert_called_once()-- assert result["t1"]["label"] == "positive"- assert result["t1"]["message_count"] == 1- assert result["t2"]["label"] == "negative"- assert result["t2"]["message_count"] == 1-- @pytest.mark.asyncio- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_trace_with_no_rows_gets_neutral(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- _make_row("gen-1", [{"role": "user", "content": "msg"}], "t1"),- ]- )- mock_classify.return_value = [_make_sentiment_result("positive", 0.9)]-- result = await classify_sentiment_activity(ClassifySentimentInput(team_id=1, ids=["t1", "t2"]))-- assert result["t1"]["label"] == "positive"- assert result["t2"]["label"] == "neutral"- assert result["t2"]["message_count"] == 0diff --git a/posthog/temporal/ai_observability/sentiment/tests/test_data.py b/posthog/temporal/ai_observability/sentiment/tests/test_data.pydeleted file mode 100644index 5f223bb8bd29..000000000000--- a/posthog/temporal/ai_observability/sentiment/tests/test_data.py+++ /dev/null@@ -1,169 +0,0 @@-"""Unit tests for the sentiment Temporal data layer.--`fetch_generations` and `fetch_generations_by_uuid` read `ai_input` from-`posthog.ai_events` native columns via `query_ai_events`; these tests assert the-contract without hitting ClickHouse.-"""--from typing import cast--import pytest-from unittest.mock import MagicMock, patch--from posthog.hogql import ast--from posthog.temporal.ai_observability.sentiment.data import fetch_generations, fetch_generations_by_uuid---def team(db):- from posthog.models.organization import Organization- from posthog.models.team import Team-- organization = Organization.objects.create(name="Test Org")- return Team.objects.create(organization=organization, name="Test Team")---def _resolver_response(rows: list[list]) -> MagicMock:- response = MagicMock()- response.results = rows- return response---class TestFetchGenerations:- def test_groups_rows_by_trace_id(self, team):- # Each row tuple: (uuid, ai_input, trace_id) — order matches GENERATIONS_QUERY's outer SELECT.- with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:- mock_resolver.return_value = _resolver_response(- [- ["uuid-1", '[{"role":"user","content":"hi A"}]', "trace-A"],- ["uuid-2", '[{"role":"user","content":"hi B"}]', "trace-B"],- ["uuid-3", '[{"role":"user","content":"hi A again"}]', "trace-A"],- ]- )-- result = fetch_generations(- team_id=team.id,- trace_ids=["trace-A", "trace-B"],- date_from="2026-04-27 07:00:00",- date_to="2026-04-27 08:00:00",- )-- assert set(result.rows_by_trace.keys()) == {"trace-A", "trace-B"}- assert len(result.rows_by_trace["trace-A"]) == 2- assert len(result.rows_by_trace["trace-B"]) == 1- # Bytes accumulator counts the raw JSON strings sent over the wire.- assert result.total_input_bytes > 0-- def test_skips_rows_with_unparseable_input(self, team):- with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:- mock_resolver.return_value = _resolver_response(- [- ["uuid-1", "{not-json", "trace-A"],- ["uuid-2", '[{"role":"user","content":"valid"}]', "trace-A"],- ]- )- result = fetch_generations(- team_id=team.id,- trace_ids=["trace-A"],- date_from="2026-04-27 07:00:00",- date_to="2026-04-27 08:00:00",- )- # Only the valid row survives; invalid JSON drops silently.- assert len(result.rows_by_trace["trace-A"]) == 1-- def test_query_reads_native_input_from_ai_events(self, team):- """If someone reverts the GENERATIONS_QUERY template to- `properties.$ai_input`, this test catches it."""- with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:- mock_resolver.return_value = _resolver_response([])- fetch_generations(- team_id=team.id,- trace_ids=["trace-A"],- date_from="2026-04-27 07:00:00",- date_to="2026-04-27 08:00:00",- )-- kwargs = mock_resolver.call_args.kwargs- outer = cast(ast.SelectQuery, kwargs["query"])- inner = outer.select_from.table # type: ignore[union-attr]- assert isinstance(inner, ast.SelectQuery)- from_chain = inner.select_from.table.chain # type: ignore[union-attr]- # nosemgrep: hogql-no-string-table-chain- assert from_chain == ["posthog", "ai_events"]---_TRACE_RESOLVE_PATH = "posthog.hogql_queries.ai.trace_id_resolver.resolve_trace_ids_for_generation_uuids"---class TestFetchGenerationsByUuid:- @patch(_TRACE_RESOLVE_PATH, return_value={"uuid-1": "trace-A", "uuid-2": "trace-B"})- def test_returns_flat_list(self, _mock_resolve, team):- with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:- mock_resolver.return_value = _resolver_response(- [- ["uuid-1", '[{"role":"user","content":"hi"}]'],- ["uuid-2", '[{"role":"user","content":"there"}]'],- ]- )- rows, total_bytes = fetch_generations_by_uuid(- team_id=team.id,- generation_ids=["uuid-1", "uuid-2"],- date_from="2026-04-27 07:00:00",- date_to="2026-04-27 08:00:00",- )- assert len(rows) == 2- assert total_bytes > 0-- @patch(_TRACE_RESOLVE_PATH, return_value={"uuid-good": "trace-A", "uuid-bad": "trace-A"})- def test_skips_unparseable_input(self, _mock_resolve, team):- with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:- mock_resolver.return_value = _resolver_response(- [- ["uuid-bad", "not-json"],- ["uuid-good", '[{"role":"user","content":"hi"}]'],- ]- )- rows, _ = fetch_generations_by_uuid(- team_id=team.id,- generation_ids=["uuid-bad", "uuid-good"],- date_from="2026-04-27 07:00:00",- date_to="2026-04-27 08:00:00",- )- assert len(rows) == 1- assert rows[0][0] == "uuid-good"-- @patch(_TRACE_RESOLVE_PATH, return_value={})- def test_no_trace_ids_resolved_skips_heavy_fetch(self, _mock_resolve, team):- """When the events preflight returns no trace_ids — uuids purged or- outside the window — skip the heavy ai_events fan-out entirely."""- with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:- rows, total_bytes = fetch_generations_by_uuid(- team_id=team.id,- generation_ids=["uuid-1", "uuid-2"],- date_from="2026-04-27 07:00:00",- date_to="2026-04-27 08:00:00",- )- assert rows == []- assert total_bytes == 0- assert mock_resolver.call_count == 0-- @patch(_TRACE_RESOLVE_PATH, return_value={"uuid-1": "trace-A", "uuid-2": "trace-B"})- def test_trace_ids_flow_into_heavy_query(self, _mock_resolve, team):- """The discovered trace_ids must land in the WHERE so the heavy fetch- hits the ai_events `(team_id, trace_id, timestamp)` sorting-key- prefix and single-shard via the cityHash64 sharding key."""- with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:- mock_resolver.return_value = _resolver_response([])- fetch_generations_by_uuid(- team_id=team.id,- generation_ids=["uuid-1", "uuid-2"],- date_from="2026-04-27 07:00:00",- date_to="2026-04-27 08:00:00",- )- placeholders = mock_resolver.call_args.kwargs["placeholders"]- assert "trace_ids" in placeholders- values = sorted(c.value for c in placeholders["trace_ids"].exprs)- assert values == ["trace-A", "trace-B"]diff --git a/posthog/temporal/ai_observability/sentiment/tests/test_generation_activity.py b/posthog/temporal/ai_observability/sentiment/tests/test_generation_activity.pydeleted file mode 100644index 33a2364ef868..000000000000--- a/posthog/temporal/ai_observability/sentiment/tests/test_generation_activity.py+++ /dev/null@@ -1,231 +0,0 @@-import pytest-from unittest.mock import MagicMock, patch--from posthog.temporal.ai_observability.sentiment.activities import classify_sentiment_activity-from posthog.temporal.ai_observability.sentiment.schema import ClassifySentimentInput, SentimentResult---def _make_row(uuid: str, messages: list[dict]) -> tuple:- return (uuid, messages)---def _make_sentiment_result(label: str = "positive", score: float = 0.9) -> SentimentResult:- scores = {"positive": 0.05, "neutral": 0.05, "negative": 0.05}- scores[label] = score- return SentimentResult(label=label, score=score, scores=scores)---def _mock_hogql_result(rows: list[tuple]) -> MagicMock:- result = MagicMock()- result.results = rows- return result---def _gen_input(generation_id: str = "gen-1", **kwargs) -> ClassifySentimentInput:- return ClassifySentimentInput(team_id=1, ids=[generation_id], analysis_level="generation", **kwargs)---# `ai_table_resolver` imports `execute_hogql_query` at module top, so patching-# the source module wouldn't reach its local binding. Patch where it's used.-_PATCH_HOGQL = "posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query"-_PATCH_TEAM = "posthog.models.team.Team.objects"-_PATCH_CLASSIFY = "posthog.temporal.ai_observability.sentiment.model.classify"-# `fetch_generations_by_uuid` does a uuid → trace_id preflight via the-# resolver helper before the heavy fetch. Patch the source-module symbol so-# the inline `from posthog.hogql.query import execute_hogql_query` inside-# the resolver picks up the mock.-_PATCH_RESOLVE = "posthog.hogql_queries.ai.trace_id_resolver.resolve_trace_ids_for_generation_uuids"--[email protected](autouse=True)-def _mock_team():- with patch(_PATCH_TEAM) as mock_objects:- mock_objects.get.return_value = MagicMock(id=1)- yield--[email protected](autouse=True)-def _mock_trace_id_resolver():- """Resolver returns a synthetic trace_id per input uuid so the heavy fetch- isn't short-circuited as 'no generations found in window'."""- with patch(_PATCH_RESOLVE) as mock:- mock.side_effect = lambda team, generation_uuids, **kw: {u: f"trace-{u}" for u in generation_uuids}- yield---class TestGenerationLevelSingle:- @pytest.mark.asyncio- @patch(_PATCH_HOGQL)- async def test_empty_query_returns_neutral(self, mock_hogql: MagicMock):- mock_hogql.return_value = _mock_hogql_result([])-- result = await classify_sentiment_activity(_gen_input())-- assert result["gen-1"]["label"] == "neutral"- assert result["gen-1"]["messages"] == {}-- @pytest.mark.asyncio- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_single_generation_single_message(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- _make_row("gen-1", [{"role": "user", "content": "I love this product"}]),- ]- )- mock_classify.return_value = [_make_sentiment_result("positive", 0.9)]-- result = await classify_sentiment_activity(_gen_input())-- mock_classify.assert_called_once_with(["I love this product"])- assert result["gen-1"]["label"] == "positive"- assert "0" in result["gen-1"]["messages"]- # message dict keys must be strings for orjson serialization- assert all(isinstance(k, str) for k in result["gen-1"]["messages"].keys())-- @pytest.mark.asyncio- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_single_generation_multiple_messages(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- _make_row(- "gen-1",- [- {"role": "user", "content": "msg-a"},- {"role": "assistant", "content": "reply"},- {"role": "user", "content": "msg-b"},- ],- ),- ]- )- mock_classify.return_value = [- _make_sentiment_result("positive", 0.9),- _make_sentiment_result("negative", 0.8),- ]-- result = await classify_sentiment_activity(_gen_input())-- mock_classify.assert_called_once_with(["msg-a", "msg-b"])- assert len(result["gen-1"]["messages"]) == 2-- @pytest.mark.asyncio- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_skips_generations_without_user_messages(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- _make_row("gen-1", [{"role": "assistant", "content": "no user msgs"}]),- ]- )-- result = await classify_sentiment_activity(_gen_input())-- mock_classify.assert_not_called()- assert result["gen-1"]["label"] == "neutral"- assert result["gen-1"]["messages"] == {}---class TestGenerationLevelBatch:- @pytest.mark.asyncio- @patch(_PATCH_HOGQL)- async def test_empty_query_returns_neutral_for_all(self, mock_hogql: MagicMock):- mock_hogql.return_value = _mock_hogql_result([])-- result = await classify_sentiment_activity(- ClassifySentimentInput(team_id=1, ids=["gen-1", "gen-2"], analysis_level="generation")- )-- assert result["gen-1"]["label"] == "neutral"- assert result["gen-2"]["label"] == "neutral"-- @pytest.mark.asyncio- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_multiple_generations_single_query(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- _make_row("gen-1", [{"role": "user", "content": "hello from gen-1"}]),- _make_row("gen-2", [{"role": "user", "content": "hello from gen-2"}]),- ]- )- mock_classify.return_value = [- _make_sentiment_result("positive", 0.9),- _make_sentiment_result("negative", 0.8),- ]-- result = await classify_sentiment_activity(- ClassifySentimentInput(team_id=1, ids=["gen-1", "gen-2"], analysis_level="generation")- )-- mock_classify.assert_called_once_with(["hello from gen-1", "hello from gen-2"])- mock_hogql.assert_called_once()-- assert result["gen-1"]["label"] == "positive"- assert result["gen-2"]["label"] == "negative"-- @pytest.mark.asyncio- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_generation_with_no_rows_gets_neutral(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- _make_row("gen-1", [{"role": "user", "content": "msg"}]),- ]- )- mock_classify.return_value = [_make_sentiment_result("positive", 0.9)]-- result = await classify_sentiment_activity(- ClassifySentimentInput(team_id=1, ids=["gen-1", "gen-2"], analysis_level="generation")- )-- assert result["gen-1"]["label"] == "positive"- assert result["gen-2"]["label"] == "neutral"- assert result["gen-2"]["messages"] == {}-- @pytest.mark.asyncio- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_passes_date_range_to_query(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- _make_row("gen-1", [{"role": "user", "content": "hello"}]),- ]- )- mock_classify.return_value = [_make_sentiment_result("positive", 0.9)]-- await classify_sentiment_activity(_gen_input(date_from="2025-01-01", date_to="2025-01-31"))-- call_kwargs = mock_hogql.call_args.kwargs- placeholders = call_kwargs["placeholders"]- assert placeholders["date_from"].value == "2025-01-01 00:00:00"- assert placeholders["date_to"].value == "2025-01-31 00:00:00"---class TestDualWriteInTraceActivity:- @pytest.mark.asyncio- @patch(_PATCH_CLASSIFY)- @patch(_PATCH_HOGQL)- async def test_trace_activity_dual_writes_generation_cache(self, mock_hogql: MagicMock, mock_classify: MagicMock):- mock_hogql.return_value = _mock_hogql_result(- [- ("gen-1", [{"role": "user", "content": "hello"}], "trace-1"),- ]- )- mock_classify.return_value = [_make_sentiment_result("positive", 0.9)]-- with patch("django.core.cache.cache") as mock_cache:- mock_cache.set_many = MagicMock()-- await classify_sentiment_activity(ClassifySentimentInput(team_id=1, ids=["trace-1"]))-- mock_cache.set_many.assert_called_once()- cache_keys = mock_cache.set_many.call_args[0][0]- # Trace-level and generation-level keys should both be in the single set_many call- assert "llma_sentiment:trace:1:trace-1" in cache_keys- assert "llma_sentiment:generation:1:gen-1" in cache_keys- # Generation cache entry has the unified shape- gen_cached = cache_keys["llma_sentiment:generation:1:gen-1"]- assert gen_cached["label"] == "positive"- assert "messages" in gen_cached- assert "message_count" in gen_cacheddiff --git a/posthog/temporal/ai_observability/sentiment/utils.py b/posthog/temporal/ai_observability/sentiment/utils.pyindex 50ccef8135bc..7a024aba59c6 100644--- a/posthog/temporal/ai_observability/sentiment/utils.py+++ b/posthog/temporal/ai_observability/sentiment/utils.py@@ -1,15 +1,8 @@"""Utility helpers for sentiment classification."""-from datetime import UTC, timedeltafrom typing import Any-from posthog.temporal.ai_observability.sentiment.schema import PendingClassification, TraceResult---def average_scores(message_results: list[dict[str, Any]]) -> dict[str, float]:- """Average softmax scores across message results."""- score_dicts = [m["scores"] for m in message_results]- return average_score_dicts(score_dicts)+from posthog.temporal.ai_observability.sentiment.schema import PendingClassificationdef average_score_dicts(score_dicts: list[dict[str, float]]) -> dict[str, float]:@@ -22,66 +15,6 @@ def average_score_dicts(score_dicts: list[dict[str, float]]) -> dict[str, float]return {label: round(sum(d.get(label, 0.0) for d in score_dicts) / n, 4) for label in labels}-def build_trace_result(- trace_id: str,- pending: list[PendingClassification],- classification_results: list,- pending_offset: int,-) -> tuple[TraceResult, dict[str, dict[str, Any]], int]:- """Build a single trace's sentiment result from classified pending items.-- Returns (TraceResult, per_generation_dicts, count_consumed).- per_generation_dicts is keyed by gen_uuid and contains the same shape as- generation-level results — used for dual-write caching.- """- trace_pending = [p for p in pending if p.trace_id == trace_id]- trace_results = classification_results[pending_offset : pending_offset + len(trace_pending)]-- if not trace_pending:- return TraceResult.neutral(), {}, 0-- gen_messages: dict[str, dict[str, dict[str, Any]]] = {}- flat_messages: dict[str, dict[str, Any]] = {}- all_scores: list[dict[str, float]] = []-- for item, result in zip(trace_pending, trace_results):- msg_dict = {- "label": result.label,- "score": result.score,- "scores": result.scores,- }- gen_messages.setdefault(item.gen_uuid, {})[str(item.msg_index)] = msg_dict- flat_messages[f"{item.gen_uuid}:{item.msg_index}"] = msg_dict- all_scores.append(result.scores)-- per_gen: dict[str, dict[str, Any]] = {}- for gen_uuid, msgs in gen_messages.items():- gen_scores = average_scores(list(msgs.values()))- gen_label = max(gen_scores, key=gen_scores.get) # type: ignore- per_gen[gen_uuid] = {- "label": gen_label,- "score": gen_scores[gen_label],- "scores": gen_scores,- "messages": msgs,- "message_count": len(msgs),- }-- trace_scores = average_score_dicts(all_scores)- trace_label = max(trace_scores, key=trace_scores.get) # type: ignore-- return (- TraceResult(- label=trace_label,- score=round(trace_scores[trace_label], 4),- scores=trace_scores,- messages=flat_messages,- message_count=len(trace_pending),- ),- per_gen,- len(trace_pending),- )--def build_generation_result(gen_uuid: str,pending: list[PendingClassification],@@ -89,8 +22,7 @@ def build_generation_result() -> dict[str, Any]:"""Build a single generation's sentiment dict from classified pending items.- Returns the same shape as a generation entry in TraceResult.generations:- {label, score, scores, messages}.+ Returns {label, score, scores, messages, message_count}."""gen_pending = [p for p in pending if p.gen_uuid == gen_uuid]gen_results = classification_results[: len(gen_pending)]@@ -126,74 +58,3 @@ def build_generation_result("messages": messages,"message_count": len(gen_pending),}---def collect_pending(- generations: list[tuple[str, object]],- trace_id: str,- cap: int,-) -> list[PendingClassification]:- """Parse generation rows and collect user messages for classification."""- from posthog.temporal.ai_observability.sentiment.extraction import (- extract_user_messages_individually,- truncate_to_token_limit,- )-- pending: list[PendingClassification] = []-- for event_uuid, ai_input in generations:- user_messages = extract_user_messages_individually(ai_input)- if not user_messages:- continue-- for original_index, msg_text in user_messages:- if len(pending) >= cap:- break- pending.append(- PendingClassification(- trace_id=trace_id,- gen_uuid=event_uuid,- msg_index=original_index,- text=truncate_to_token_limit(msg_text),- )- )-- if len(pending) >= cap:- break-- return pending---def resolve_date_bounds(date_from: str | None, date_to: str | None) -> tuple[str, str]:- """Resolve caller-provided date strings to concrete timestamps for the query.-- Handles relative date strings (e.g. "-1h", "-7d") by converting them to- absolute timestamps via `relative_date_parse`. Falls back to a lookback- window when no bounds are provided.- """- from datetime import datetime- from zoneinfo import ZoneInfo-- from posthog.temporal.ai_observability.sentiment.constants import QUERY_LOOKBACK_DAYS- from posthog.utils import relative_date_parse-- now = datetime.now(tz=UTC)- fmt = "%Y-%m-%d %H:%M:%S"-- if date_from:- try:- resolved_from = relative_date_parse(date_from, ZoneInfo("UTC"), now=now).strftime(fmt)- except Exception:- resolved_from = (now - timedelta(days=QUERY_LOOKBACK_DAYS)).strftime(fmt)- else:- resolved_from = (now - timedelta(days=QUERY_LOOKBACK_DAYS)).strftime(fmt)-- if date_to:- try:- resolved_to = relative_date_parse(date_to, ZoneInfo("UTC"), now=now).strftime(fmt)- except Exception:- resolved_to = now.strftime(fmt)- else:- resolved_to = now.strftime(fmt)-- return resolved_from, resolved_todiff --git a/posthog/temporal/ai_observability/sentiment/workflow.py b/posthog/temporal/ai_observability/sentiment/workflow.pydeleted file mode 100644index c01a30dae1fd..000000000000--- a/posthog/temporal/ai_observability/sentiment/workflow.py+++ /dev/null@@ -1,37 +0,0 @@-"""Temporal workflow definition for sentiment classification."""--from datetime import timedelta-from typing import Any--import temporalio-from temporalio.common import RetryPolicy--from posthog.temporal.ai_observability.sentiment.activities import classify_sentiment_activity-from posthog.temporal.ai_observability.sentiment.constants import (- ACTIVITY_SCHEDULE_TO_START_TIMEOUT_SECONDS,- ACTIVITY_TIMEOUT_SECONDS,- MAX_RETRY_ATTEMPTS,-)-from posthog.temporal.ai_observability.sentiment.schema import ClassifySentimentInput-from posthog.temporal.common.base import PostHogWorkflow---# Must match constants.WORKFLOW_NAME[email protected](name="llma-sentiment-classify")-class ClassifySentimentWorkflow(PostHogWorkflow):- @staticmethod- def parse_inputs(inputs: list[str]) -> ClassifySentimentInput:- return ClassifySentimentInput(- team_id=int(inputs[0]),- ids=inputs[1:],- )-- @temporalio.workflow.run- async def run(self, input: ClassifySentimentInput) -> dict[str, dict[str, Any]]:- return await temporalio.workflow.execute_activity(- classify_sentiment_activity,- input,- start_to_close_timeout=timedelta(seconds=ACTIVITY_TIMEOUT_SECONDS),- schedule_to_start_timeout=timedelta(seconds=ACTIVITY_SCHEDULE_TO_START_TIMEOUT_SECONDS),- retry_policy=RetryPolicy(maximum_attempts=MAX_RETRY_ATTEMPTS),- )diff --git a/posthog/temporal/ai_observability/trace_clustering/aggregates.py b/posthog/temporal/ai_observability/trace_clustering/aggregates.pyindex 1467f1107a1e..4d47bb2e0161 100644--- a/posthog/temporal/ai_observability/trace_clustering/aggregates.py+++ b/posthog/temporal/ai_observability/trace_clustering/aggregates.py@@ -1,43 +1,21 @@-"""Compute aggregate metrics (cost, latency, tokens, errors, sentiment) for clusters.+"""Compute aggregate metrics (cost, latency, tokens, errors) for clusters.-This activity is best-effort: it runs with a time budget and returns whatever-it managed to compute. Partial results (e.g., metrics without sentiment) are-perfectly fine — the frontend falls back to runtime loading for missing data.+This activity is best-effort: it returns whatever metrics it managed to compute."""import time-import uuidimport asyncio-from datetime import timedelta-from django.conf import settings-from django.core.cache import cachefrom django.utils.dateparse import parse_datetimeimport structlogfrom temporalio import activity-from temporalio.common import RetryPolicy, WorkflowIDReusePolicyfrom posthog.models.team import Team-from posthog.temporal.ai_observability.sentiment.constants import (- CACHE_KEY_PREFIX as SENTIMENT_CACHE_KEY_PREFIX,- MAX_RETRY_ATTEMPTS as SENTIMENT_MAX_RETRY_ATTEMPTS,- WORKFLOW_NAME as SENTIMENT_WORKFLOW_NAME,- WORKFLOW_TIMEOUT_BATCH_SECONDS as SENTIMENT_WORKFLOW_TIMEOUT,-)-from posthog.temporal.ai_observability.sentiment.schema import ClassifySentimentInput-from posthog.temporal.ai_observability.trace_clustering.constants import (- SENTIMENT_BATCH_SIZE,- SENTIMENT_MAX_CONCURRENT,- SENTIMENT_PER_BATCH_TIMEOUT,- SENTIMENT_TOTAL_TIMEOUT,-)from posthog.temporal.ai_observability.trace_clustering.data import ItemMetrics, fetch_item_metricsfrom posthog.temporal.ai_observability.trace_clustering.models import (- AnalysisLevel,ClusterAggregateMetrics,ClusterItem,- ClusterSentiment,ComputeAggregatesActivityInputs,)from posthog.temporal.common.heartbeat import Heartbeater@@ -102,141 +80,8 @@ def _aggregate_operational_metrics(return result-async def _fetch_sentiment_for_items(- team_id: int,- item_ids: list[str],- analysis_level: AnalysisLevel,- date_from: str,- date_to: str,-) -> dict[str, dict]:- """Fetch sentiment for items, using cache first, then Temporal workflows for misses."""- from posthog.temporal.common.client import async_connect-- if not item_ids:- return {}-- # Check cache first- cache_keys = {id_: f"{SENTIMENT_CACHE_KEY_PREFIX}:{analysis_level}:{team_id}:{id_}" for id_ in item_ids}- cached_values = await asyncio.to_thread(cache.get_many, list(cache_keys.values()))-- results: dict[str, dict] = {}- misses: list[str] = []- for id_ in item_ids:- cached = cached_values.get(cache_keys[id_])- if cached is not None:- results[id_] = cached- else:- misses.append(id_)-- logger.info(- "sentiment_cache_check",- team_id=team_id,- total=len(item_ids),- cached=len(results),- misses=len(misses),- )-- if not misses:- return results-- # Batch misses into chunks and run sentiment workflows concurrently- client = await async_connect()- semaphore = asyncio.Semaphore(SENTIMENT_MAX_CONCURRENT)- chunks = [misses[i : i + SENTIMENT_BATCH_SIZE] for i in range(0, len(misses), SENTIMENT_BATCH_SIZE)]-- async def _run_sentiment_batch(chunk: list[str]) -> dict[str, dict]:- async with semaphore:- workflow_id = f"llma-sentiment-cluster-{team_id}-{int(time.time() * 1000)}-{uuid.uuid4().hex[:8]}"- try:- return await asyncio.wait_for(- client.execute_workflow(- SENTIMENT_WORKFLOW_NAME,- ClassifySentimentInput(- team_id=team_id,- ids=chunk,- analysis_level=analysis_level,- date_from=date_from,- date_to=date_to,- ),- id=workflow_id,- task_queue=settings.LLMA_SENTIMENT_TASK_QUEUE,- id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,- retry_policy=RetryPolicy(maximum_attempts=SENTIMENT_MAX_RETRY_ATTEMPTS),- task_timeout=timedelta(seconds=SENTIMENT_WORKFLOW_TIMEOUT),- ),- timeout=SENTIMENT_PER_BATCH_TIMEOUT,- )- except Exception as e:- logger.warning(- "sentiment_batch_failed",- team_id=team_id,- chunk_size=len(chunk),- error=str(e),- )- return {}-- try:- batch_results = await asyncio.wait_for(- asyncio.gather(*[_run_sentiment_batch(chunk) for chunk in chunks]),- timeout=SENTIMENT_TOTAL_TIMEOUT,- )- for batch in batch_results:- results.update(batch)- except TimeoutError:- logger.warning(- "sentiment_total_timeout",- team_id=team_id,- total_chunks=len(chunks),- cached_so_far=len(results),- )-- return results---def _aggregate_sentiment_per_cluster(- items: list[ClusterItem],- labels: list[int],- sentiment_results: dict[str, dict],-) -> dict[int, ClusterSentiment]:- """Aggregate per-item sentiment into per-cluster sentiment."""- cluster_items: dict[int, list[str]] = {}- for i, label in enumerate(labels):- item_id = _get_item_id(items[i])- cluster_items.setdefault(label, []).append(item_id)-- result: dict[int, ClusterSentiment] = {}- for cluster_id, item_ids in cluster_items.items():- counts: dict[str, int] = {"positive": 0, "neutral": 0, "negative": 0}- total_score = 0.0- total_with_sentiment = 0-- for item_id in item_ids:- s = sentiment_results.get(item_id)- if not s or "label" not in s:- continue- label = s["label"]- if label in counts:- counts[label] += 1- total_score += s.get("score", 0.0)- total_with_sentiment += 1-- if total_with_sentiment == 0:- continue-- # Overall label is the majority class- overall_label = max(counts, key=lambda k: counts[k])- result[cluster_id] = ClusterSentiment(- label=overall_label,- score=total_score / total_with_sentiment,- counts=counts,- total=total_with_sentiment,- )-- return result--def _compute_aggregates(inputs: ComputeAggregatesActivityInputs) -> dict[int, ClusterAggregateMetrics]:- """Synchronous wrapper that orchestrates metrics + sentiment collection."""+ """Synchronous wrapper that orchestrates metrics collection."""window_start = parse_datetime(inputs.window_start)window_end = parse_datetime(inputs.window_end)if window_start is None or window_end is None:@@ -245,7 +90,6 @@ def _compute_aggregates(inputs: ComputeAggregatesActivityInputs) -> dict[int, Clteam = Team.objects.get(id=inputs.team_id)all_item_ids = [_get_item_id(item) for item in inputs.items]- # Phase 1: Fetch operational metrics (cost, latency, tokens, errors)t0 = time.monotonic()item_metrics = fetch_item_metrics(team=team,@@ -258,47 +102,14 @@ def _compute_aggregates(inputs: ComputeAggregatesActivityInputs) -> dict[int, Clcluster_metrics = _aggregate_operational_metrics(inputs.items, inputs.labels, item_metrics)- # Phase 2: Fetch sentiment (best-effort, async)- t1 = time.monotonic()- sentiment_results: dict[str, dict] = {}- try:- # Use trace IDs for sentiment (sentiment classifies user messages in generations)- sentiment_ids = all_item_ids- sentiment_level = inputs.analysis_level- sentiment_results = asyncio.run(- _fetch_sentiment_for_items(- team_id=inputs.team_id,- item_ids=sentiment_ids,- analysis_level=sentiment_level,- date_from=inputs.window_start,- date_to=inputs.window_end,- )- )- except Exception as e:- logger.warning(- "sentiment_fetch_failed",- team_id=inputs.team_id,- error=str(e),- )- sentiment_ms = (time.monotonic() - t1) * 1000-- # Merge sentiment into cluster metrics- if sentiment_results:- cluster_sentiment = _aggregate_sentiment_per_cluster(inputs.items, inputs.labels, sentiment_results)- for cluster_id, sentiment in cluster_sentiment.items():- if cluster_id in cluster_metrics:- cluster_metrics[cluster_id].sentiment = sentiment-logger.info("compute_aggregates_completed",team_id=inputs.team_id,analysis_level=inputs.analysis_level,item_count=len(all_item_ids),items_with_metrics=len(item_metrics),- items_with_sentiment=len(sentiment_results),clusters=len(cluster_metrics),metrics_ms=round(metrics_ms),- sentiment_ms=round(sentiment_ms),)return cluster_metrics@@ -308,10 +119,9 @@ def _compute_aggregates(inputs: ComputeAggregatesActivityInputs) -> dict[int, Clasync def compute_cluster_aggregates_activity(inputs: ComputeAggregatesActivityInputs,) -> dict[int, ClusterAggregateMetrics]:- """Activity 3: Compute aggregate metrics and sentiment for clusters.+ """Activity 3: Compute aggregate metrics for clusters.Best-effort: returns whatever it can compute within the time budget.- If sentiment fails or times out, operational metrics are still returned.If the whole activity fails, the workflow continues without metrics."""async with Heartbeater():diff --git a/posthog/temporal/ai_observability/trace_clustering/constants.py b/posthog/temporal/ai_observability/trace_clustering/constants.pyindex 865ff8e26fc4..b68b8cf69797 100644--- a/posthog/temporal/ai_observability/trace_clustering/constants.py+++ b/posthog/temporal/ai_observability/trace_clustering/constants.py@@ -35,7 +35,7 @@ GENERATION_CHILD_WORKFLOW_ID_PREFIX = "llma-generation-clustering-team"# Activity timeouts (per activity type, per single attempt)COMPUTE_ACTIVITY_TIMEOUT = timedelta(seconds=120) # Fetch + clustering + distancesLLM_ACTIVITY_TIMEOUT = timedelta(seconds=600) # 10 minutes for full labeling agent run (LangGraph multi-turn)-AGGREGATES_ACTIVITY_TIMEOUT = timedelta(seconds=300) # 5 min budget for metrics + sentiment+AGGREGATES_ACTIVITY_TIMEOUT = timedelta(seconds=300) # 5 min budget for metricsEMIT_ACTIVITY_TIMEOUT = timedelta(seconds=60) # ClickHouse write# Heartbeat timeouts - allows Temporal to detect dead workers faster than@@ -44,7 +44,7 @@ EMIT_ACTIVITY_TIMEOUT = timedelta(seconds=60) # ClickHouse write# and schedule a retry on another worker.COMPUTE_HEARTBEAT_TIMEOUT = timedelta(seconds=60) # 1 minute - compute is mostly CPU-boundLLM_HEARTBEAT_TIMEOUT = timedelta(seconds=120) # 2 minutes - agent runs can have long pauses between LLM calls-AGGREGATES_HEARTBEAT_TIMEOUT = timedelta(seconds=60) # 1 minute - external calls to ClickHouse + sentiment+AGGREGATES_HEARTBEAT_TIMEOUT = timedelta(seconds=60) # 1 minute - external calls to ClickHouseEMIT_HEARTBEAT_TIMEOUT = timedelta(seconds=30) # 30 seconds - ClickHouse writes are fast# Schedule-to-close timeouts - caps total time including all retry attempts,@@ -78,12 +78,6 @@ AGGREGATES_ACTIVITY_RETRY_POLICY = RetryPolicy(maximum_attempts=1,)-# Sentiment batching within the aggregates activity-SENTIMENT_BATCH_SIZE = 5 # trace IDs per sentiment workflow (matches API batch size)-SENTIMENT_MAX_CONCURRENT = 10 # max concurrent sentiment workflows-SENTIMENT_PER_BATCH_TIMEOUT = 120 # seconds per sentiment batch-SENTIMENT_TOTAL_TIMEOUT = 240 # seconds total budget for all sentiment batches (must be < activity timeout)-# Event emission - database write, quick retriesEMIT_ACTIVITY_RETRY_POLICY = RetryPolicy(maximum_attempts=2,diff --git a/posthog/temporal/ai_observability/trace_clustering/models.py b/posthog/temporal/ai_observability/trace_clustering/models.pyindex 363b82ff11d3..9bf2d569f80f 100644--- a/posthog/temporal/ai_observability/trace_clustering/models.py+++ b/posthog/temporal/ai_observability/trace_clustering/models.py@@ -114,16 +114,6 @@ class TraceClusterMetadata:generation_id: str | None = None # Only set for generation-level clustering-@dataclass-class ClusterSentiment:- """Aggregate sentiment for a cluster."""-- label: str # "positive", "neutral", "negative"- score: float # 0-1- counts: dict[str, int] # {"positive": N, "neutral": N, "negative": N}- total: int # number of items with sentiment data--@dataclassclass ClusterAggregateMetrics:"""Pre-computed aggregate metrics for a cluster, baked into the event.@@ -146,7 +136,6 @@ class ClusterAggregateMetrics:error_rate: float | None = Noneerror_count: int = 0item_count: int = 0- sentiment: ClusterSentiment | None = None# Evaluation-only fields (None for trace/generation levels)pass_rate: float | None = Nonena_rate: float | None = Nonediff --git a/posthog/temporal/ai_observability/trace_clustering/workflow.py b/posthog/temporal/ai_observability/trace_clustering/workflow.pyindex 844ded8b9e3b..738dfd99da41 100644--- a/posthog/temporal/ai_observability/trace_clustering/workflow.py+++ b/posthog/temporal/ai_observability/trace_clustering/workflow.py@@ -132,7 +132,7 @@ class DailyTraceClusteringWorkflow(PostHogWorkflow):This workflow orchestrates 4 activities:1. Compute: Fetch embeddings, perform k-means clustering, compute distances2. Label: Generate LLM-based cluster labels (long timeout for API call)- 3. Aggregates: Compute per-cluster metrics and sentiment (best-effort, non-blocking)+ 3. Aggregates: Compute per-cluster metrics (best-effort, non-blocking)4. Emit: Write clustering results to ClickHouseThe workflow calculates window_start/window_end from lookback_days and@@ -241,7 +241,7 @@ class DailyTraceClusteringWorkflow(PostHogWorkflow):retry_policy=LLM_ACTIVITY_RETRY_POLICY,)- # Activity 3: Compute aggregate metrics + sentiment (best-effort, non-blocking on failure)+ # Activity 3: Compute aggregate metrics (best-effort, non-blocking on failure)cluster_metrics: dict[int, ClusterAggregateMetrics] = {}try:cluster_metrics = await workflow.execute_activity(diff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.pyindex 236b6a907fa8..f6bf565032dc 100644--- a/posthog/temporal/common/worker.py+++ b/posthog/temporal/common/worker.py@@ -19,11 +19,6 @@ from posthog.temporal.ai_observability.eval_reports.metrics import (EvalReportsMetricsInterceptor,)from posthog.temporal.ai_observability.metrics import EvalsMetricsInterceptor-from posthog.temporal.ai_observability.sentiment.metrics import (- SENTIMENT_LATENCY_HISTOGRAM_BUCKETS,- SENTIMENT_LATENCY_HISTOGRAM_METRICS,- SentimentMetricsInterceptor,-)from posthog.temporal.ai_observability.trace_clustering.metrics import (CLUSTERING_LATENCY_HISTOGRAM_BUCKETS,CLUSTERING_LATENCY_HISTOGRAM_METRICS,@@ -162,7 +157,6 @@ ALL_INTERCEPTOR_CLASSES = [SummarizationMetricsInterceptor,ClusteringMetricsInterceptor,MCPAClusteringMetricsInterceptor,- SentimentMetricsInterceptor,EvalReportsMetricsInterceptor,LogsAlertingMetricsInterceptor,ExperimentsRecalculationMetricsInterceptor,@@ -287,7 +281,6 @@ async def create_worker())| dict(zip(TASKS_LATENCY_HISTOGRAM_METRICS, itertools.repeat(TASKS_LATENCY_HISTOGRAM_BUCKETS)))- | dict(zip(SENTIMENT_LATENCY_HISTOGRAM_METRICS, itertools.repeat(SENTIMENT_LATENCY_HISTOGRAM_BUCKETS)))| dict(zip(EVAL_REPORTS_LATENCY_HISTOGRAM_METRICS,diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex c892bc841aa8..2c4078dcabf1 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -310,7 +310,6 @@ class TestAIObservabilityModuleIntegrity:"AIObservabilityEvaluationSamplerWorkflow","AIObservabilityEvaluationClusteringCoordinatorWorkflow","AIObservabilityEvaluationClusteringWorkflow",- "ClassifySentimentWorkflow","RunEvaluationWorkflow",]actual_workflow_names = [w.__name__ for w in LLM_ANALYTICS_WORKFLOWS]@@ -348,7 +347,6 @@ class TestAIObservabilityModuleIntegrity:"generate_evaluation_cluster_labels_activity","compute_evaluation_cluster_aggregates_activity","emit_evaluation_cluster_events_activity",- "classify_sentiment_activity","fetch_evaluation_activity","increment_trial_eval_count_activity","disable_evaluation_activity",diff --git a/products/mcp_analytics/backend/intent_clustering.py b/products/mcp_analytics/backend/intent_clustering.pyindex ded97baba377..c4809a18a23b 100644--- a/products/mcp_analytics/backend/intent_clustering.py+++ b/products/mcp_analytics/backend/intent_clustering.py@@ -55,9 +55,8 @@ NO_INTENT_RECORDED_FALLBACK = "No agent intent was recorded for this session."# Embedding cache + concurrency# 1536-d float32 embedding = 6144 bytes. 500-intent corpus × 6144 ≈ 3 MB/team.# Cap concurrent embedding worker requests so we don't dogpile when a team's-# corpus has hundreds of misses on first run. 20 matches the trace_clustering-# precedent (SENTIMENT_MAX_CONCURRENT) and stays well under any per-team-# rate limit on the embedding provider.+# corpus has hundreds of misses on first run while staying well under any+# per-team rate limit on the embedding provider.EMBED_CONCURRENCY = 20# How many tool-call steps to show in the per-cluster Sankey before the