Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(llma): add missing clickhouse query tags in ai observability (#61683)

posthog[bot]c3aa2960a33d
diff --git a/.dagster_home/workspace.yaml b/.dagster_home/workspace.yaml
index e811327a1fd8..b5905c8e95f2 100644
--- a/.dagster_home/workspace.yaml
+++ b/.dagster_home/workspace.yaml
@@ -17,6 +17,5 @@ load_from:
- python_module: posthog.dags.locations.growth
- python_module: posthog.dags.locations.shared
- python_module: posthog.dags.locations.ingestion
- - python_module: posthog.dags.locations.llm_analytics
- python_module: posthog.dags.locations.posthog_ai
- python_module: posthog.dags.locations.web_analytics
diff --git a/posthog/api/monitoring.py b/posthog/api/monitoring.py
index f2913a62921f..cc7f36bfa952 100644
--- a/posthog/api/monitoring.py
+++ b/posthog/api/monitoring.py
@@ -15,7 +15,6 @@ class Feature(StrEnum):
DASHBOARD = "dashboard"
DEBUG_QUERY = "debug_query"
INSIGHT = "insight"
- LLM_ANALYTICS = "llm_analytics"
QUERY = "query"
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index b5f51219a701..74454f54e30b 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -102,7 +102,6 @@ class Feature(StrEnum):
QUOTA_LIMITING = "quota_limiting"
MIGRATION = "migration"
MANAGEMENT_COMMAND = "management_command"
- LLM_ANALYTICS = "llm_analytics"
# Endpoints product features
ENDPOINT_EXECUTION = "endpoint_execution" # external API callers (personal_api_key or oauth)
ENDPOINT_PLAYGROUND = "endpoint_playground" # frontend Playground tab (browser session auth)
diff --git a/posthog/dags/locations/llm_analytics.py b/posthog/dags/locations/llm_analytics.py
deleted file mode 100644
index a6384873e8e8..000000000000
--- a/posthog/dags/locations/llm_analytics.py
+++ /dev/null
@@ -1,21 +0,0 @@
-import dagster
-
-from products.ai_observability.dags.daily_metrics.main import (
- llma_metrics_daily,
- llma_metrics_daily_job,
- llma_metrics_daily_schedule,
-)
-
-from . import loggers, resources
-
-defs = dagster.Definitions(
- assets=[llma_metrics_daily],
- jobs=[
- llma_metrics_daily_job,
- ],
- schedules=[
- llma_metrics_daily_schedule,
- ],
- loggers=loggers,
- resources=resources,
-)
diff --git a/posthog/dags/tests/test_loggers.py b/posthog/dags/tests/test_loggers.py
index a103b20ff26a..430d6b46157b 100644
--- a/posthog/dags/tests/test_loggers.py
+++ b/posthog/dags/tests/test_loggers.py
@@ -18,7 +18,6 @@ LOCATION_MODULES = [
"error_tracking",
"growth",
"ingestion",
- "llm_analytics",
"logs",
"posthog_ai",
"revenue_analytics",
diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.py
index 0e57f3a5a232..fcb6bd31ef88 100644
--- a/posthog/temporal/ai_observability/eval_reports/activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/activities.py
@@ -72,6 +72,7 @@ async def fetch_count_triggered_eval_reports_activity(
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
+ from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.models import Team
from products.ai_observability.backend.models.evaluation_reports import EvaluationReport, EvaluationReportRun
@@ -131,7 +132,8 @@ async def fetch_count_triggered_eval_reports_activity(
"since": ast.Constant(value=since),
},
)
- result = execute_hogql_query(query=query, team=team)
+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.ENRICHMENT, team_id=team.pk):
+ result = execute_hogql_query(query=query, team=team)
rows = result.results or []
count = rows[0][0] if rows else 0
@@ -178,6 +180,7 @@ def _find_nth_eval_timestamp(
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
+ from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.models import Team
team = Team.objects.get(id=team_id)
@@ -201,7 +204,8 @@ def _find_nth_eval_timestamp(
"limit": ast.Constant(value=int(n)),
},
)
- result = execute_hogql_query(query=query, team=team)
+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.ENRICHMENT, team_id=team.pk):
+ result = execute_hogql_query(query=query, team=team)
rows = result.results or []
if rows and rows[0][0] is not None:
ts = rows[0][0]
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
index 537c4d9e7cc0..5e743fe94a90 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
@@ -84,13 +84,13 @@ def _execute_hogql(team_id: int, query_str: str, placeholders: dict | None = Non
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
- from posthog.clickhouse.query_tagging import Product, tags_context
+ from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.models import Team
team = Team.objects.get(id=team_id)
query = parse_select(query_str)
- with tags_context(product=Product.LLM_ANALYTICS):
+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.ENRICHMENT, team_id=team_id):
result = execute_hogql_query(
query_type="EvalReportAgent",
query=query,
@@ -112,19 +112,21 @@ def _execute_hogql_via_ai_events(team: "Team", query_str: str, placeholders: dic
"""
from posthog.hogql.parser import parse_select
+ from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
query = parse_select(query_str)
- # `execute_with_ai_events_fallback` wraps its own
- # `tags_context(product=Product.LLM_ANALYTICS)` internally; no need to
- # double-wrap here.
- result = execute_with_ai_events_fallback(
- query=query,
- placeholders=placeholders or {},
- team=team,
- query_type="EvalReportAgent",
- )
+ # `execute_with_ai_events_fallback` sets `product=Product.LLM_ANALYTICS`
+ # internally but not `feature`, so supply it here to keep these eval-report
+ # agent reads attributed to background enrichment.
+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.ENRICHMENT, team_id=team.pk):
+ result = execute_with_ai_events_fallback(
+ query=query,
+ placeholders=placeholders or {},
+ team=team,
+ query_type="EvalReportAgent",
+ )
return result.results or []
diff --git a/posthog/temporal/ai_observability/trace_clustering/data.py b/posthog/temporal/ai_observability/trace_clustering/data.py
index dbd501d33b05..4a4ca55a38c1 100644
--- a/posthog/temporal/ai_observability/trace_clustering/data.py
+++ b/posthog/temporal/ai_observability/trace_clustering/data.py
@@ -101,7 +101,7 @@ def fetch_item_embeddings_for_clustering(
placeholders["document_type_legacy"] = ast.Constant(value=constants.LLMA_TRACE_DOCUMENT_TYPE_LEGACY)
placeholders["rendering_legacy"] = ast.Constant(value=constants.LLMA_TRACE_RENDERING_LEGACY)
- with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY):
+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team.id):
result = execute_hogql_query(
query_type="ItemEmbeddingsForClustering",
query=query,
@@ -204,7 +204,7 @@ def fetch_item_summaries(
# Build item_ids tuple for IN clause
item_ids_tuple = ast.Tuple(exprs=[ast.Constant(value=iid) for iid in item_ids])
- with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY):
+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team.id):
result = execute_hogql_query(
query_type="ItemSummariesForClustering",
query=query,
@@ -347,7 +347,7 @@ def fetch_item_metrics(
if not is_generation:
placeholders["trace_id_prop"] = ast.Field(chain=["properties", "$ai_trace_id"])
- with tags_context(product=Product.LLM_ANALYTICS):
+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team.id):
result = execute_hogql_query(
query_type="ClusterItemMetrics",
query=query,
diff --git a/products/ai_observability/backend/api/evaluation_runs.py b/products/ai_observability/backend/api/evaluation_runs.py
index 5ae0083797ea..6765d4b9547f 100644
--- a/products/ai_observability/backend/api/evaluation_runs.py
+++ b/products/ai_observability/backend/api/evaluation_runs.py
@@ -16,6 +16,7 @@ from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from posthog.api.monitoring import monitor
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.clickhouse.client import query_with_columns
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.event_usage import report_user_action
from posthog.hogql_queries.ai.ai_table_resolver import is_ai_events_enabled
from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, HEAVY_COLUMN_TO_PROPERTY, merge_heavy_properties
@@ -96,46 +97,49 @@ class EvaluationRunViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
query_result: list[dict] = []
used_ai_events = False
- if is_ai_events_enabled(self.team):
- heavy_cols = ",\n ".join(HEAVY_COLUMN_NAMES)
- query_result = query_with_columns(
- f"""
- SELECT
- uuid,
- event,
- properties,
- timestamp,
- team_id,
- distinct_id,
- person_id,
- {heavy_cols}
- FROM ai_events
- WHERE {" AND ".join(where_clauses)}
- LIMIT 1
- """,
- params,
- team_id=self.team_id,
- )
- used_ai_events = len(query_result) > 0
-
- if not query_result:
- query_result = query_with_columns(
- f"""
- SELECT
- uuid,
- event,
- properties,
- timestamp,
- team_id,
- distinct_id,
- person_id
- FROM events
- WHERE {" AND ".join(where_clauses)}
- LIMIT 1
- """,
- params,
- team_id=self.team_id,
- )
+ # Tag these direct ClickHouse reads so the manual-eval-trigger lookup is attributed
+ # to AI observability in query-usage analysis alongside the rest of the product.
+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=self.team_id):
+ if is_ai_events_enabled(self.team):
+ heavy_cols = ",\n ".join(HEAVY_COLUMN_NAMES)
+ query_result = query_with_columns(
+ f"""
+ SELECT
+ uuid,
+ event,
+ properties,
+ timestamp,
+ team_id,
+ distinct_id,
+ person_id,
+ {heavy_cols}
+ FROM ai_events
+ WHERE {" AND ".join(where_clauses)}
+ LIMIT 1
+ """,
+ params,
+ team_id=self.team_id,
+ )
+ used_ai_events = len(query_result) > 0
+
+ if not query_result:
+ query_result = query_with_columns(
+ f"""
+ SELECT
+ uuid,
+ event,
+ properties,
+ timestamp,
+ team_id,
+ distinct_id,
+ person_id
+ FROM events
+ WHERE {" AND ".join(where_clauses)}
+ LIMIT 1
+ """,
+ params,
+ team_id=self.team_id,
+ )
if len(query_result) == 0:
return Response({"error": f"Event {target_event_id} not found"}, status=404)
diff --git a/products/ai_observability/backend/api/personal_spend.py b/products/ai_observability/backend/api/personal_spend.py
index ef4b52a22bb8..476d756c30fb 100644
--- a/products/ai_observability/backend/api/personal_spend.py
+++ b/products/ai_observability/backend/api/personal_spend.py
@@ -33,7 +33,7 @@ from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
-from posthog.clickhouse.query_tagging import Product, tags_context
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.models import Team, User
from posthog.permissions import APIScopePermission
from posthog.rate_limit import PersonalSpendBurstThrottle, PersonalSpendDailyThrottle, PersonalSpendSustainedThrottle
@@ -633,7 +633,7 @@ class PersonalSpendViewSet(viewsets.ViewSet):
# Tag the underlying ClickHouse reads with the LLM_ANALYTICS product so they show up
# in the existing per-product Prometheus + cost-attribution dashboards alongside the
# rest of AI observability traffic. Wraps every call into `_fetch_*` -> HogQL.
- with tags_context(product=Product.LLM_ANALYTICS):
+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team_id):
summary = _fetch_summary(team, email, from_dt, to_dt, product)
by_tool = _fetch_by_tool(team, email, from_dt, to_dt, product, limit)
scoped = summary["scoped_cost_usd"] or 0.0
diff --git a/products/ai_observability/backend/api/summarization.py b/products/ai_observability/backend/api/summarization.py
index ad55a7a0024a..6344f8c82797 100644
--- a/products/ai_observability/backend/api/summarization.py
+++ b/products/ai_observability/backend/api/summarization.py
@@ -30,6 +30,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.api.monitoring import monitor
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.event_usage import report_user_action
from posthog.hogql_queries.ai.trace_query_runner import TraceQueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
@@ -304,25 +305,26 @@ class AIObservabilitySummarizationViewSet(TeamAndOrgViewSetMixin, viewsets.Gener
datetime.now(),
)
- result = execute_hogql_query(
- query=parse_select(
- """
- SELECT uuid, event, timestamp, properties
- FROM events
- WHERE event = '$ai_generation'
- AND uuid = {generation_uuid}
- AND timestamp >= {date_from}
- AND timestamp <= {date_to}
- LIMIT 1
- """,
- ),
- placeholders={
- "generation_uuid": ast.Constant(value=generation_id),
- "date_from": ast.Constant(value=qdr.date_from().isoformat()),
- "date_to": ast.Constant(value=qdr.date_to().isoformat()),
- },
- team=self.team,
- )
+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=self.team_id):
+ result = execute_hogql_query(
+ query=parse_select(
+ """
+ SELECT uuid, event, timestamp, properties
+ FROM events
+ WHERE event = '$ai_generation'
+ AND uuid = {generation_uuid}
+ AND timestamp >= {date_from}
+ AND timestamp <= {date_to}
+ LIMIT 1
+ """,
+ ),
+ placeholders={
+ "generation_uuid": ast.Constant(value=generation_id),
+ "date_from": ast.Constant(value=qdr.date_from().isoformat()),
+ "date_to": ast.Constant(value=qdr.date_to().isoformat()),
+ },
+ team=self.team,
+ )
if not result.results:
raise exceptions.NotFound(f"Generation '{generation_id}' not found in the given date range.")
diff --git a/products/ai_observability/backend/api/taggers.py b/products/ai_observability/backend/api/taggers.py
index 7a955b31ad93..913da74edc0f 100644
--- a/products/ai_observability/backend/api/taggers.py
+++ b/products/ai_observability/backend/api/taggers.py
@@ -482,18 +482,18 @@ class TaggerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDes
return TaggerSerializer(hydrated_tagger, context=self.get_serializer_context()).data
@llma_track_latency("llma_taggers_list")
- @monitor(feature=Feature.LLM_ANALYTICS, endpoint="llma_taggers_list", method="GET")
+ @monitor(feature=Feature.QUERY, endpoint="llma_taggers_list", method="GET")
def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
return super().list(request, *args, **kwargs)
@llma_track_latency("llma_taggers_retrieve")
- @monitor(feature=Feature.LLM_ANALYTICS, endpoint="llma_taggers_retrieve", method="GET")
+ @monitor(feature=Feature.QUERY, endpoint="llma_taggers_retrieve", method="GET")
def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
return super().retrieve(request, *args, **kwargs)
@extend_schema(request=TaggerCreateSerializer, responses={201: OpenApiResponse(response=TaggerSerializer)})
@llma_track_latency("llma_taggers_create")
- @monitor(feature=Feature.LLM_ANALYTICS, endpoint="llma_taggers_create", method="POST")
+ @monitor(feature=Feature.QUERY, endpoint="llma_taggers_create", method="POST")
def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
@@ -505,13 +505,13 @@ class TaggerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDes
@extend_schema(request=TaggerUpdateSerializer, responses={200: OpenApiResponse(response=TaggerSerializer)})
@llma_track_latency("llma_taggers_update")
- @monitor(feature=Feature.LLM_ANALYTICS, endpoint="llma_taggers_update", method="PUT")
+ @monitor(feature=Feature.QUERY, endpoint="llma_taggers_update", method="PUT")
def update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
return self._update_tagger(request=request, partial=False)
@extend_schema(request=TaggerUpdateSerializer, responses={200: OpenApiResponse(response=TaggerSerializer)})
@llma_track_latency("llma_taggers_partial_update")
- @monitor(feature=Feature.LLM_ANALYTICS, endpoint="llma_taggers_partial_update", method="PATCH")
+ @monitor(feature=Feature.QUERY, endpoint="llma_taggers_partial_update", method="PATCH")
def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
return self._update_tagger(request=request, partial=True)
@@ -534,7 +534,7 @@ class TaggerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDes
@extend_schema(request=TestHogTaggerRequestSerializer, responses=TestHogTaggerResponseSerializer)
@action(detail=False, methods=["post"], url_path="test_hog", required_scopes=["tagger:read"])
@llma_track_latency("llma_taggers_test_hog")
- @monitor(feature=Feature.LLM_ANALYTICS, endpoint="llma_taggers_test_hog", method="POST")
+ @monitor(feature=Feature.QUERY, endpoint="llma_taggers_test_hog", method="POST")
def test_hog(self, request: Request, **kwargs) -> Response:
"""Test Hog tagger code against sample events without saving."""
test_serializer = TestHogTaggerRequestSerializer(data=request.data)
diff --git a/products/ai_observability/backend/api/test/test_evaluation_runs.py b/products/ai_observability/backend/api/test/test_evaluation_runs.py
index c0b1ef3681e7..e3b053a6ef46 100644
--- a/products/ai_observability/backend/api/test/test_evaluation_runs.py
+++ b/products/ai_observability/backend/api/test/test_evaluation_runs.py
@@ -8,6 +8,8 @@ from django.conf import settings
from rest_framework import status
+from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags
+
from ...models.evaluations import Evaluation
@@ -83,6 +85,57 @@ class TestEvaluationRunViewSet(APIBaseTest):
assert workflow_inputs.event_data is not None
assert workflow_inputs.event_data["uuid"] == target_event_id.replace("-", "")
+ @patch("products.ai_observability.backend.api.evaluation_runs.query_with_columns")
+ @patch("products.ai_observability.backend.api.evaluation_runs.sync_connect")
+ def test_create_evaluation_run_tags_clickhouse_query(self, mock_connect, mock_query):
+ """The manual eval-trigger ClickHouse lookup must run inside an LLM analytics tag context.
+
+ Mocking `query_with_columns` bypasses `sync_execute`'s tag plumbing, so assert directly
+ that the tags are set on the active context at the moment the query runs.
+ """
+ mock_client = MagicMock()
+ mock_client.start_workflow = AsyncMock()
+ mock_connect.return_value = mock_client
+
+ target_event_id = str(uuid.uuid4())
+ timestamp = datetime.now()
+ captured: dict = {}
+
+ def capture_tags(*args, **kwargs):
+ tags = get_query_tags()
+ captured["product"] = tags.product
+ captured["feature"] = tags.feature
+ captured["team_id"] = tags.team_id
+ return [
+ {
+ "uuid": target_event_id.replace("-", ""),
+ "event": "$ai_generation",
+ "properties": "{}",
+ "timestamp": timestamp,
+ "team_id": self.team.id,
+ "distinct_id": "test_user",
+ "person_id": str(uuid.uuid4()),
+ }
+ ]
+
+ mock_query.side_effect = capture_tags
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluation_runs/",
+ {
+ "evaluation_id": str(self.evaluation.id),
+ "target_event_id": target_event_id,
+ "timestamp": timestamp.isoformat(),
+ "event": "$ai_generation",
+ "distinct_id": "test_user",
+ },
+ )
+
+ assert response.status_code == status.HTTP_202_ACCEPTED
+ assert captured["product"] == Product.LLM_ANALYTICS
+ assert captured["feature"] == Feature.QUERY
+ assert captured["team_id"] == self.team.id
+
def test_create_evaluation_run_invalid_evaluation(self):
"""Test creating evaluation run with non-existent evaluation"""
response = self.client.post(
diff --git a/products/ai_observability/dags/README.md b/products/ai_observability/dags/README.md
deleted file mode 100644
index cdc16166d6bc..000000000000
--- a/products/ai_observability/dags/README.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# LLMA (AI observability) Dagster location
-
-Data pipelines for AI observability.
-
-## Overview
-
-The LLMA location contains pipelines for aggregating and analyzing AI/LLM
-events tracked through PostHog. These pipelines power analytics, cost tracking,
-and observability features for AI products.
-
-## Structure
-
-```text
-products/ai_observability/dags/
-├── README.md
-├── daily_metrics/ # Daily aggregation pipeline
-│ ├── README.md # Detailed pipeline documentation
-│ ├── config.py # Pipeline configuration
-│ ├── main.py # Dagster asset and schedule
-│ ├── utils.py # SQL generation helpers
-│ └── sql/ # Modular SQL templates
-│ ├── event_counts.sql # Event count metrics
-│ ├── error_rates.sql # Error rate metrics
-│ ├── trace_counts.sql # Unique trace count metrics
-│ ├── session_counts.sql # Unique session count metrics
-│ ├── trace_error_rates.sql # Trace-level error rates
-│ └── pageview_counts.sql # AI observability pageview metrics
-└── __init__.py
-
-Tests: products/ai_observability/dags/tests/daily_metrics/test_sql_metrics.py
-```
-
-## Pipelines
-
-### Daily Metrics
-
-Aggregates AI event metrics ($ai_trace, $ai_generation, $ai_span,
-$ai_embedding) by team and date into the `llma_metrics_daily` ClickHouse
-table.
-
-Features:
-
-- Modular SQL template system for easy metric additions
-- Event counts, trace counts, session counts, and pageview metrics
-- Error rates at event and trace level (proportions 0.0-1.0)
-- Long-format schema for schema-less evolution
-- Daily schedule at 6 AM UTC
-
-See [daily_metrics/README.md](daily_metrics/README.md) for detailed
-documentation.
-
-## Local Development
-
-The LLMA location is loaded in `.dagster_home/workspace.yaml` for local
-development.
-
-View in Dagster UI:
-
-```bash
-# Dagster runs on port 3030
-open http://localhost:3030
-```
diff --git a/products/ai_observability/dags/__init__.py b/products/ai_observability/dags/__init__.py
deleted file mode 100644
index 54023b6525ac..000000000000
--- a/products/ai_observability/dags/__init__.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""
-LLMA (AI observability) team Dagster assets.
-
-This module contains data pipeline assets for tracking and analyzing LLM usage metrics.
-"""
diff --git a/products/ai_observability/dags/daily_metrics/README.md b/products/ai_observability/dags/daily_metrics/README.md
deleted file mode 100644
index acb0a0db6739..000000000000
--- a/products/ai_observability/dags/daily_metrics/README.md
+++ /dev/null
@@ -1,204 +0,0 @@
-# LLMA Daily Metrics Pipeline
-
-Daily aggregation of AI event metrics into the `llma_metrics_daily` ClickHouse
-table.
-
-## Overview
-
-Aggregates AI event metrics ($ai_trace, $ai_generation, $ai_span,
-$ai_embedding) by team and date into a long-format metrics table for efficient
-querying.
-
-## Architecture
-
-The pipeline uses a modular SQL template system:
-
-- Each metric type lives in its own `.sql` file under `sql/`
-- Templates are auto-discovered and combined with UNION ALL
-- To add a new metric, simply drop a new `.sql` file in the directory
-
-### SQL Template Format
-
-Each SQL file should return these columns:
-
-```sql
-SELECT
- date(timestamp) as date,
- team_id,
- 'metric_name' as metric_name,
- toFloat64(value) as metric_value
-FROM llma_events
-GROUP BY ...
-```
-
-The following CTEs are automatically provided:
-
-- `llma_events`: AI events pre-filtered to teams with AI activity
-- `llma_pageview_events`: Pageview events pre-filtered to teams viewing AI observability pages
-
-This two-step filtering (first find teams, then filter events) allows ClickHouse to
-use the sorting key (team_id, timestamp) efficiently.
-
-Templates have access to these Jinja2 variables:
-
-- `event_types`: List of AI event types to aggregate
-- `metric_date`: The date being aggregated (YYYY-MM-DD)
-- `pageview_mappings`: List of (url_path, metric_suffix) tuples for pageview categorization
-- `include_error_rates`: Boolean flag for error rate calculation (default: true)
-
-## Output Schema
-
-```sql
-CREATE TABLE llma_metrics_daily (
- date Date,
- team_id UInt64,
- metric_name String,
- metric_value Float64
-) ENGINE = ReplicatedMergeTree()
-PARTITION BY toYYYYMM(date)
-ORDER BY (team_id, date, metric_name)
-```
-
-Long format allows adding new metrics without schema changes.
-
-## Current Metrics
-
-### Event Counts
-
-Defined in `sql/event_counts.sql`:
-
-- `ai_generation_count`: Number of AI generation events
-- `ai_trace_count`: Number of AI trace events
-- `ai_span_count`: Number of AI span events
-- `ai_embedding_count`: Number of AI embedding events
-
-Each event is counted individually, even if multiple events share the same trace_id.
-
-### Trace Counts
-
-Defined in `sql/trace_counts.sql`:
-
-- `ai_trace_id_count`: Number of unique traces (distinct $ai_trace_id values)
-
-Counts unique traces across all AI event types. A trace may contain multiple events (generations, spans, etc).
-
-### Session Counts
-
-Defined in `sql/session_counts.sql`:
-
-- `ai_session_id_count`: Number of unique sessions (distinct $ai_session_id values)
-
-Counts unique sessions across all AI event types. A session can link multiple related traces together.
-
-### Event Error Rates
-
-Defined in `sql/error_rates.sql`:
-
-- `ai_generation_error_rate`: Proportion of AI generation events with errors (0.0 to 1.0)
-- `ai_trace_error_rate`: Proportion of AI trace events with errors (0.0 to 1.0)
-- `ai_span_error_rate`: Proportion of AI span events with errors (0.0 to 1.0)
-- `ai_embedding_error_rate`: Proportion of AI embedding events with errors (0.0 to 1.0)
-
-### Trace Error Rates
-
-Defined in `sql/trace_error_rates.sql`:
-
-- `ai_trace_id_has_error_rate`: Proportion of unique traces that had at least one error (0.0 to 1.0)
-
-A trace is considered errored if ANY event within it has an error. Compare with event error rates which report the proportion of individual events with errors.
-
-### Pageview Metrics
-
-Defined in `sql/pageview_counts.sql`:
-
-- `pageviews_traces`: Pageviews on /ai-observability/traces
-- `pageviews_generations`: Pageviews on /ai-observability/generations
-- `pageviews_users`: Pageviews on /ai-observability/users
-- `pageviews_sessions`: Pageviews on /ai-observability/sessions
-- `pageviews_playground`: Pageviews on /ai-observability/playground
-- `pageviews_datasets`: Pageviews on /ai-evals/datasets
-- `pageviews_evaluations`: Pageviews on /ai-evals/evaluations
-
-Tracks $pageview events on AI engineering pages. URL patterns are mapped to page types via config.pageview_mappings.
-
-### Error Detection
-
-All error metrics detect errors by checking for:
-
-- `$ai_error` property is non-empty
-- `$ai_is_error` property is true
-
-## Configuration
-
-See `config.py` for configuration options:
-
-- `partition_start_date`: First date to backfill (default: 2025-01-01)
-- `cron_schedule`: Schedule for daily runs (default: 6 AM UTC)
-- `max_partitions_per_run`: Max partitions to process in backfill (default: 14)
-- `ai_event_types`: List of AI event types to track (default: $ai_trace, $ai_generation, $ai_span, $ai_embedding)
-- `pageview_mappings`: URL path to metric name mappings for pageview tracking
-- `include_error_rates`: Enable error rate metrics (default: true)
-
-## Schedule
-
-Runs daily at 6 AM UTC for the previous day's partition.
-
-## Local Development
-
-Query results in ClickHouse:
-
-```bash
-docker exec posthog-clickhouse-1 clickhouse-client --query \
- "SELECT * FROM llma_metrics_daily WHERE date = today() FORMAT Pretty"
-```
-
-Or use HogQL in PostHog UI:
-
-```sql
-SELECT
- date,
- metric_name,
- sum(metric_value) as total
-FROM llma_metrics_daily
-WHERE date >= today() - INTERVAL 7 DAY
-GROUP BY date, metric_name
-ORDER BY date DESC, metric_name
-```
-
-## Testing
-
-Run the test suite to validate SQL structure and logic:
-
-```bash
-pytest products/ai_observability/dags/tests/daily_metrics/test_sql_metrics.py -v
-```
-
-Tests validate:
-
-- SQL templates render without errors
-- All SQL files produce the correct 4-column output
-- Calculation logic is correct (using mock data)
-- Date filtering and grouping work as expected
-
-Test file location: `products/ai_observability/dags/tests/daily_metrics/test_sql_metrics.py`
-
-## Adding New Metrics
-
-1. Create a new SQL file in `sql/` (e.g., `sql/token_counts.sql`)
-2. Query from `llma_events` (pre-filtered CTE) for AI event metrics
-3. Return columns: `date`, `team_id`, `metric_name`, `metric_value`
-4. The pipeline will automatically discover and include it
-5. Add test coverage in `products/ai_observability/dags/tests/daily_metrics/test_sql_metrics.py` with mock data and expected output
-
-Example:
-
-```sql
-SELECT
- date(timestamp) as date,
- team_id,
- concat(substring(event, 2), '_tokens') as metric_name,
- toFloat64(sum(JSONExtractInt(properties, '$ai_total_tokens'))) as metric_value
-FROM llma_events
-GROUP BY date, team_id, event
-HAVING metric_value > 0
-```
diff --git a/products/ai_observability/dags/daily_metrics/config.py b/products/ai_observability/dags/daily_metrics/config.py
deleted file mode 100644
index 813aae8298d3..000000000000
--- a/products/ai_observability/dags/daily_metrics/config.py
+++ /dev/null
@@ -1,65 +0,0 @@
-"""
-Configuration for LLMA (AI observability) metrics aggregation.
-
-This module defines all parameters and constants used in the LLMA metrics pipeline.
-Modify this file to add new metrics or change aggregation behavior.
-"""
-
-from dataclasses import dataclass, field
-
-from posthog.schema import AIEventType
-
-
-@dataclass
-class LLMADailyMetricsConfig:
- """Configuration for LLMA daily metrics aggregation pipeline."""
-
- # ClickHouse table name
- table_name: str = "llma_metrics_daily"
-
- # Start date for daily partitions (when AI events were introduced)
- partition_start_date: str = "2025-01-01"
-
- # Schedule: Daily at 6 AM UTC
- cron_schedule: str = "0 6 * * *"
-
- # Backfill policy: process N days per run
- max_partitions_per_run: int = 14
-
- # ClickHouse query settings
- clickhouse_max_execution_time: int = 600 # 10 minutes
-
- # Dagster job timeout (seconds)
- job_timeout: int = 1800 # 30 minutes
-
- # Include error rate metrics (percentage of events with errors)
- include_error_rates: bool = True
-
- # AI event types to track (from central AIEventType enum)
- ai_event_types: list[str] = field(default_factory=lambda: [e.value for e in AIEventType])
-
- # Pageview URL path to metric name mappings
- # Maps URL patterns to metric names for tracking pageviews
- # Order matters: more specific patterns should come before general ones
- pageview_mappings: list[tuple[str, str]] = field(
- default_factory=lambda: [
- ("/ai-observability/traces", "traces"),
- ("/ai-observability/generations", "generations"),
- ("/ai-observability/users", "users"),
- ("/ai-observability/sessions", "sessions"),
- ("/ai-observability/playground", "playground"),
- ("/ai-evals/datasets", "datasets"),
- ("/ai-evals/evaluations", "evaluations"),
- ("/llm-analytics/traces", "traces"),
- ("/llm-analytics/generations", "generations"),
- ("/llm-analytics/users", "users"),
- ("/llm-analytics/sessions", "sessions"),
- ("/llm-analytics/playground", "playground"),
- ("/llm-analytics/datasets", "datasets"),
- ("/llm-analytics/evaluations", "evaluations"),
- ]
- )
-
-
-# Global config instance
-config = LLMADailyMetricsConfig()
diff --git a/products/ai_observability/dags/daily_metrics/main.py b/products/ai_observability/dags/daily_metrics/main.py
deleted file mode 100644
index 8b2885c7c898..000000000000
--- a/products/ai_observability/dags/daily_metrics/main.py
+++ /dev/null
@@ -1,133 +0,0 @@
-"""
-Daily aggregation of LLMA (AI observability) metrics.
-
-Aggregates AI event counts from the events table into a daily metrics table
-for efficient querying and cost analysis.
-"""
-
-from datetime import UTC, datetime, timedelta
-
-import pandas as pd
-import dagster
-from dagster import BackfillPolicy, DailyPartitionsDefinition
-
-from posthog.clickhouse import query_tagging
-from posthog.clickhouse.client import sync_execute
-from posthog.clickhouse.cluster import ClickhouseCluster
-from posthog.dags.common import JobOwners, dagster_tags
-
-from products.ai_observability.dags.daily_metrics.config import config
-from products.ai_observability.dags.daily_metrics.utils import get_delete_query, get_insert_query
-
-# Partition definition for daily aggregations
-partition_def = DailyPartitionsDefinition(start_date=config.partition_start_date, end_offset=1)
-
-# Backfill policy: process N days per run
-backfill_policy_def = BackfillPolicy.multi_run(max_partitions_per_run=config.max_partitions_per_run)
-
-# ClickHouse settings for aggregation queries
-LLMA_CLICKHOUSE_SETTINGS = {
- "max_execution_time": str(config.clickhouse_max_execution_time),
-}
-
-
- name="llma_metrics_daily",
- group_name="llma",
- partitions_def=partition_def,
- backfill_policy=backfill_policy_def,
- metadata={"table": config.table_name},
- tags={"owner": JobOwners.TEAM_AI_OBSERVABILITY.value},
-)
-def llma_metrics_daily(
- context: dagster.AssetExecutionContext,
- cluster: dagster.ResourceParam[ClickhouseCluster],
-) -> None:
- """
- Daily aggregation of LLMA metrics.
-
- Aggregates AI event counts ($ai_trace, $ai_generation, $ai_span, $ai_embedding)
- by team and date into a long-format metrics table for efficient querying.
-
- Long format allows adding new metrics without schema changes.
- """
- query_tagging.get_query_tags().with_dagster(dagster_tags(context))
-
- if not context.partition_time_window:
- raise dagster.Failure("This asset should only be run with a partition_time_window")
-
- metric_date = context.partition_time_window[0].strftime("%Y-%m-%d")
-
- context.log.info(f"Aggregating LLMA metrics for {metric_date}")
-
- try:
- delete_query = get_delete_query(metric_date)
- sync_execute(delete_query, settings=LLMA_CLICKHOUSE_SETTINGS)
-
- insert_query = get_insert_query(metric_date)
- context.log.info(f"Metrics query: \n{insert_query}")
- sync_execute(insert_query, settings=LLMA_CLICKHOUSE_SETTINGS)
-
- # Query and log the metrics that were just aggregated
- metrics_query = f"""
- SELECT
- metric_name,
- count(DISTINCT team_id) as teams,
- sum(metric_value) as total_value
- FROM {config.table_name}
- WHERE date = '{metric_date}'
- GROUP BY metric_name
- ORDER BY metric_name
- """
- metrics_results = sync_execute(metrics_query)
-
- if metrics_results:
- df = pd.DataFrame(metrics_results, columns=["metric_name", "teams", "total_value"])
- context.log.info(f"Aggregated {len(df)} metric types for {metric_date}:\n{df.to_string(index=False)}")
- else:
- context.log.info(f"No AI events found for {metric_date}")
-
- context.log.info(f"Successfully aggregated LLMA metrics for {metric_date}")
-
- except Exception as e:
- raise dagster.Failure(f"Failed to aggregate LLMA metrics: {str(e)}") from e
-
-
-# Define the job that runs the asset
-llma_metrics_daily_job = dagster.define_asset_job(
- name="llma_metrics_daily_job",
- selection=["llma_metrics_daily"],
- tags={
- "owner": JobOwners.TEAM_AI_OBSERVABILITY.value,
- "dagster/max_runtime": str(config.job_timeout),
- },
-)
-
-
- cron_schedule=config.cron_schedule,
- job=llma_metrics_daily_job,
- execution_timezone="UTC",
- tags={"owner": JobOwners.TEAM_AI_OBSERVABILITY.value},
-)
-def llma_metrics_daily_schedule(context: dagster.ScheduleEvaluationContext):
- """
- Runs daily for the previous day's partition.
-
- Schedule configured in products.ai_observability.dags.config.
- This aggregates AI event metrics from the events table into the
- llma_metrics_daily table for efficient querying.
- """
- # Calculate yesterday's partition
- yesterday = (datetime.now(UTC) - timedelta(days=1)).strftime("%Y-%m-%d")
-
- context.log.info(f"Scheduling LLMA metrics aggregation for {yesterday}")
-
- return dagster.RunRequest(
- partition_key=yesterday,
- run_config={
- "ops": {
- "llma_metrics_daily": {"config": {}},
- }
- },
- )
diff --git a/products/ai_observability/dags/daily_metrics/sql/error_rates.sql b/products/ai_observability/dags/daily_metrics/sql/error_rates.sql
deleted file mode 100644
index 44c9918d707d..000000000000
--- a/products/ai_observability/dags/daily_metrics/sql/error_rates.sql
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
-Event Error Rates - Proportion of events with errors by type
-
-Calculates the proportion of events of each type that had an error (0.0 to 1.0).
-An event is considered errored if $ai_error is set or $ai_is_error is true.
-
-Produces metrics: ai_generation_error_rate, ai_embedding_error_rate, etc.
-
-Example: If 2 out of 10 generation events had errors, this reports 0.20.
-Compare with trace_error_rates.sql which reports proportion of traces with any error.
-*/
-
-SELECT
- date(timestamp) as date,
- team_id,
- concat(substring(event, 2), '_error_rate') as metric_name,
- round(
- countIf(
- (JSONExtractRaw(properties, '$ai_error') != '' AND JSONExtractRaw(properties, '$ai_error') != 'null')
- OR JSONExtractBool(properties, '$ai_is_error') = true
- ) / count(*),
- 4
- ) as metric_value
-FROM llma_events
-GROUP BY date, team_id, event
diff --git a/products/ai_observability/dags/daily_metrics/sql/event_counts.sql b/products/ai_observability/dags/daily_metrics/sql/event_counts.sql
deleted file mode 100644
index bb1a7bea3fb4..000000000000
--- a/products/ai_observability/dags/daily_metrics/sql/event_counts.sql
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
-Event Counts - Individual AI events by type
-
-Counts the total number of individual AI events ($ai_generation, $ai_embedding, etc).
-Each event is counted separately, even if multiple events share the same trace_id.
-
-Produces metrics: ai_generation_count, ai_embedding_count, ai_span_count, ai_trace_count
-
-Example: If a trace contains 3 span events, this counts all 3 individually.
-Compare with trace_counts.sql which would count this as 1 unique trace.
-*/
-
-SELECT
- date(timestamp) as date,
- team_id,
- concat(substring(event, 2), '_count') as metric_name,
- toFloat64(count(*)) as metric_value
-FROM llma_events
-GROUP BY date, team_id, event
diff --git a/products/ai_observability/dags/daily_metrics/sql/pageview_counts.sql b/products/ai_observability/dags/daily_metrics/sql/pageview_counts.sql
deleted file mode 100644
index 06995d96f741..000000000000
--- a/products/ai_observability/dags/daily_metrics/sql/pageview_counts.sql
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
-Pageview counts - Page views by AI observability page type
-
-Counts $pageview events on AI observability pages, categorized by page type.
-URL patterns are mapped to page types via config.pageview_mappings.
-More specific patterns should be listed before general ones in config.
-
-Produces metrics: pageviews_dashboard, pageviews_traces, pageviews_generations, etc.
-
-Example: Pageview to /project/1/ai-observability/traces → pageviews_traces metric
-*/
-
-SELECT
- date(timestamp) as date,
- team_id,
- concat('pageviews_', page_type) as metric_name,
- toFloat64(count(*)) as metric_value
-FROM (
- SELECT
- timestamp,
- team_id,
- CASE
- {% for url_path, metric_suffix in pageview_mappings %}
- WHEN JSONExtractString(properties, '$current_url') LIKE '%{{ url_path }}%' THEN '{{ metric_suffix }}'
- {% endfor %}
- ELSE NULL
- END as page_type
- FROM llma_pageview_events
-)
-WHERE page_type IS NOT NULL
-GROUP BY date, team_id, page_type
diff --git a/products/ai_observability/dags/daily_metrics/sql/session_counts.sql b/products/ai_observability/dags/daily_metrics/sql/session_counts.sql
deleted file mode 100644
index dbc643815e78..000000000000
--- a/products/ai_observability/dags/daily_metrics/sql/session_counts.sql
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
-Session Counts - Unique sessions (distinct $ai_session_id)
-
-Counts the number of unique sessions by counting distinct $ai_session_id values
-across all AI event types. A session can link multiple related traces together.
-
-Produces metric: ai_session_id_count
-
-Example: If there are 10 traces belonging to 3 unique session_ids, this counts 3.
-Compare with trace_counts.sql which would count all 10 unique traces.
-*/
-
-SELECT
- date(timestamp) as date,
- team_id,
- 'ai_session_id_count' as metric_name,
- toFloat64(count(DISTINCT JSONExtractString(properties, '$ai_session_id'))) as metric_value
-FROM llma_events
-WHERE JSONExtractString(properties, '$ai_session_id') != ''
-GROUP BY date, team_id
diff --git a/products/ai_observability/dags/daily_metrics/sql/trace_counts.sql b/products/ai_observability/dags/daily_metrics/sql/trace_counts.sql
deleted file mode 100644
index e9a8fac1c4b2..000000000000
--- a/products/ai_observability/dags/daily_metrics/sql/trace_counts.sql
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
-Trace Counts - Unique traces (distinct $ai_trace_id)
-
-Counts the number of unique traces by counting distinct $ai_trace_id values
-across all AI event types. A trace may contain multiple events (generations, spans, etc).
-
-Produces metric: ai_trace_id_count
-
-Example: If there are 10 events belonging to 3 unique trace_ids, this counts 3.
-Compare with event_counts.sql which would count all 10 events individually.
-*/
-
-SELECT
- date(timestamp) as date,
- team_id,
- 'ai_trace_id_count' as metric_name,
- toFloat64(count(DISTINCT JSONExtractString(properties, '$ai_trace_id'))) as metric_value
-FROM llma_events
-WHERE JSONExtractString(properties, '$ai_trace_id') != ''
-GROUP BY date, team_id
diff --git a/products/ai_observability/dags/daily_metrics/sql/trace_error_rates.sql b/products/ai_observability/dags/daily_metrics/sql/trace_error_rates.sql
deleted file mode 100644
index 8794e28d7626..000000000000
--- a/products/ai_observability/dags/daily_metrics/sql/trace_error_rates.sql
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
-Trace Error Rates - Proportion of traces with any error
-
-Calculates the proportion of unique traces that had at least one error event (0.0 to 1.0).
-A trace is considered errored if ANY event within it has $ai_error set or $ai_is_error is true.
-
-Produces metric: ai_trace_id_has_error_rate
-
-Example: If 2 out of 8 unique traces had any error event, this reports 0.25.
-Compare with error_rates.sql which reports proportion of individual events with errors.
-
-Note: A single erroring event in a trace makes the entire trace count as errored.
-*/
-
-SELECT
- date(timestamp) as date,
- team_id,
- 'ai_trace_id_has_error_rate' as metric_name,
- round(
- countDistinctIf(
- JSONExtractString(properties, '$ai_trace_id'),
- (JSONExtractRaw(properties, '$ai_error') != '' AND JSONExtractRaw(properties, '$ai_error') != 'null')
- OR JSONExtractBool(properties, '$ai_is_error') = true
- ) / count(DISTINCT JSONExtractString(properties, '$ai_trace_id')),
- 4
- ) as metric_value
-FROM llma_events
-WHERE JSONExtractString(properties, '$ai_trace_id') != ''
-GROUP BY date, team_id
diff --git a/products/ai_observability/dags/daily_metrics/utils.py b/products/ai_observability/dags/daily_metrics/utils.py
deleted file mode 100644
index 33a79a52e07f..000000000000
--- a/products/ai_observability/dags/daily_metrics/utils.py
+++ /dev/null
@@ -1,126 +0,0 @@
-"""
-Utility functions for LLMA daily metrics aggregation.
-"""
-
-from pathlib import Path
-
-from jinja2 import Template
-
-from products.ai_observability.dags.daily_metrics.config import config
-
-# SQL template directory
-SQL_DIR = Path(__file__).parent / "sql"
-
-# Metric types to include (matches SQL filenames without .sql extension)
-# Set to None to include all, or list specific ones to include
-ENABLED_METRICS: list[str] | None = None # or ["event_counts", "error_rates"]
-
-
-def get_llma_events_cte(metric_date: str) -> str:
- """
- Generate CTEs that pre-filter events to only relevant teams for a single day.
-
- This two-step approach (first find teams, then filter events) allows ClickHouse
- to use the sorting key (team_id, toDate(timestamp)) more efficiently.
-
- Uses SAMPLE 0.1 (10%) as a safety mechanism to limit query scope.
- TODO: Remove SAMPLE once query performance is validated in production.
-
- Args:
- metric_date: The date to aggregate metrics for (YYYY-MM-DD format)
-
- Provides:
- - llma_events: AI events filtered to teams with AI activity
- - llma_pageview_events: Pageview events filtered to teams viewing AI observability pages
- """
- event_types_sql = ", ".join(f"'{et}'" for et in config.ai_event_types)
- url_patterns_sql = " OR ".join(
- f"JSONExtractString(properties, '$current_url') LIKE '%{url_path}%'" for url_path, _ in config.pageview_mappings
- )
-
- return f"""teams_with_ai_events AS (
- SELECT DISTINCT team_id
- FROM events SAMPLE 0.1
- WHERE event IN ({event_types_sql})
- AND toDate(timestamp) = '{metric_date}'
-),
-llma_events AS (
- SELECT *
- FROM events SAMPLE 0.1
- WHERE team_id IN (SELECT team_id FROM teams_with_ai_events)
- AND event IN ({event_types_sql})
- AND toDate(timestamp) = '{metric_date}'
-),
-teams_with_llma_pageviews AS (
- SELECT DISTINCT team_id
- FROM events SAMPLE 0.1
- WHERE event = '$pageview'
- AND toDate(timestamp) = '{metric_date}'
- AND ({url_patterns_sql})
-),
-llma_pageview_events AS (
- SELECT *
- FROM events SAMPLE 0.1
- WHERE team_id IN (SELECT team_id FROM teams_with_llma_pageviews)
- AND event = '$pageview'
- AND toDate(timestamp) = '{metric_date}'
- AND ({url_patterns_sql})
-)"""
-
-
-def get_insert_query(metric_date: str) -> str:
- """
- Generate SQL to aggregate AI event counts by team and metric type for a single day.
-
- Uses long format: each metric_name is a separate row for easy schema evolution.
- Automatically discovers and combines all SQL templates in the sql/ directory.
-
- Args:
- metric_date: The date to aggregate metrics for (YYYY-MM-DD format)
-
- To add a new metric type, simply add a new .sql file in products/ai_observability/dags/daily_metrics/sql/.
- Each SQL file should return columns: date, team_id, metric_name, metric_value
- """
- # Discover all SQL template files
- sql_files = sorted(SQL_DIR.glob("*.sql"))
-
- # Filter by enabled metrics if specified
- if ENABLED_METRICS is not None:
- sql_files = [f for f in sql_files if f.stem in ENABLED_METRICS]
-
- if not sql_files:
- raise ValueError(f"No SQL template files found in {SQL_DIR}")
-
- # Load and render each template
- rendered_queries = []
- template_context = {
- "event_types": config.ai_event_types,
- "pageview_mappings": config.pageview_mappings,
- "metric_date": metric_date,
- "include_error_rates": config.include_error_rates,
- }
-
- for sql_file in sql_files:
- with open(sql_file) as f:
- template = Template(f.read())
- rendered = template.render(**template_context)
- if rendered.strip(): # Only include non-empty queries
- rendered_queries.append(rendered)
-
- # Combine all queries with UNION ALL
- combined_query = "\n\nUNION ALL\n\n".join(rendered_queries)
-
- # Generate the llma_events CTE
- llma_events_cte = get_llma_events_cte(metric_date)
-
- # Wrap in INSERT INTO statement with CTE
- return f"""INSERT INTO {config.table_name} (date, team_id, metric_name, metric_value)
-
-WITH {llma_events_cte}
-
-{combined_query}"""
-
-
-def get_delete_query(metric_date: str) -> str:
- """Generate SQL to delete existing data for the given date."""
- return f"ALTER TABLE {config.table_name} DELETE WHERE date = '{metric_date}'"
diff --git a/products/ai_observability/dags/tests/__init__.py b/products/ai_observability/dags/tests/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/ai_observability/dags/tests/conftest.py b/products/ai_observability/dags/tests/conftest.py
deleted file mode 100644
index d97414d2b0fe..000000000000
--- a/products/ai_observability/dags/tests/conftest.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Import the shared Dagster PostgreSQL fixtures so that execute_in_process
-# calls use PostgreSQL instead of SQLite (avoids locking errors).
-# Direct import (rather than pytest_plugins) is required because pytest
-# disallows pytest_plugins in non-top-level conftest files.
-from posthog.dags.tests.dagster_pg_fixtures import ( # noqa: F401
- _dagster_postgres_instance,
- _use_postgres_dagster_instance,
-)
diff --git a/products/ai_observability/dags/tests/daily_metrics/__init__.py b/products/ai_observability/dags/tests/daily_metrics/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/ai_observability/dags/tests/daily_metrics/test_sql_metrics.py b/products/ai_observability/dags/tests/daily_metrics/test_sql_metrics.py
deleted file mode 100644
index 06f06ae18978..000000000000
--- a/products/ai_observability/dags/tests/daily_metrics/test_sql_metrics.py
+++ /dev/null
@@ -1,370 +0,0 @@
-"""
-Tests that execute SQL templates against mock data to validate output and logic.
-
-Tests both the structure and calculation logic of each metric SQL file.
-"""
-
-from datetime import datetime
-from pathlib import Path
-
-import pytest
-
-from jinja2 import Template
-
-from products.ai_observability.dags.daily_metrics.config import config
-from products.ai_observability.dags.daily_metrics.utils import SQL_DIR
-
-# Expected output columns
-EXPECTED_COLUMNS = ["date", "team_id", "metric_name", "metric_value"]
-
-
-def get_all_sql_files():
- """Get all SQL template files."""
- return sorted(SQL_DIR.glob("*.sql"))
-
-
-def template_context():
- """Provide sample context for rendering Jinja2 templates."""
- return {
- "event_types": config.ai_event_types,
- "pageview_mappings": config.pageview_mappings,
- "metric_date": "2025-01-01",
- "include_error_rates": config.include_error_rates,
- }
-
-
-def mock_events_data():
- """
- Mock events data for testing SQL queries.
-
- Simulates the events table with various AI events for testing.
- Returns a list of event dicts with timestamp, team_id, event, and properties.
- """
- base_time = datetime(2025, 1, 1, 12, 0, 0)
-
- events = [
- # Team 1: 3 generations, 1 with error
- {
- "timestamp": base_time,
- "team_id": 1,
- "event": "$ai_generation",
- "properties": {
- "$ai_trace_id": "trace-1",
- "$ai_session_id": "session-1",
- "$ai_error": "",
- },
- },
- {
- "timestamp": base_time,
- "team_id": 1,
- "event": "$ai_generation",
- "properties": {
- "$ai_trace_id": "trace-1",
- "$ai_session_id": "session-1",
- "$ai_error": "rate limit exceeded",
- },
- },
- {
- "timestamp": base_time,
- "team_id": 1,
- "event": "$ai_generation",
- "properties": {
- "$ai_trace_id": "trace-2",
- "$ai_session_id": "session-1",
- "$ai_error": "",
- },
- },
- # Team 1: 2 spans from same trace
- {
- "timestamp": base_time,
- "team_id": 1,
- "event": "$ai_span",
- "properties": {
- "$ai_trace_id": "trace-1",
- "$ai_session_id": "session-1",
- "$ai_is_error": True,
- },
- },
- {
- "timestamp": base_time,
- "team_id": 1,
- "event": "$ai_span",
- "properties": {
- "$ai_trace_id": "trace-1",
- "$ai_session_id": "session-1",
- "$ai_is_error": False,
- },
- },
- # Team 2: 1 generation, no errors
- {
- "timestamp": base_time,
- "team_id": 2,
- "event": "$ai_generation",
- "properties": {
- "$ai_trace_id": "trace-3",
- "$ai_session_id": "session-2",
- "$ai_error": "",
- },
- },
- # Team 1: Pageviews on AI observability
- {
- "timestamp": base_time,
- "team_id": 1,
- "event": "$pageview",
- "properties": {
- "$current_url": "https://app.posthog.com/project/123/ai-observability/traces?filter=active",
- },
- },
- {
- "timestamp": base_time,
- "team_id": 1,
- "event": "$pageview",
- "properties": {
- "$current_url": "https://app.posthog.com/project/123/llm-analytics/traces",
- },
- },
- {
- "timestamp": base_time,
- "team_id": 1,
- "event": "$pageview",
- "properties": {
- "$current_url": "https://app.posthog.com/project/123/ai-observability/generations",
- },
- },
- ]
-
- return events
-
-
-def expected_metrics(mock_events_data):
- """
- Expected metric outputs based on mock_events_data.
-
- This serves as the source of truth for what each SQL file should produce.
- """
- return {
- "event_counts.sql": [
- {"date": "2025-01-01", "team_id": 1, "metric_name": "ai_generation_count", "metric_value": 3.0},
- {"date": "2025-01-01", "team_id": 1, "metric_name": "ai_span_count", "metric_value": 2.0},
- {"date": "2025-01-01", "team_id": 2, "metric_name": "ai_generation_count", "metric_value": 1.0},
- ],
- "trace_counts.sql": [
- {
- "date": "2025-01-01",
- "team_id": 1,
- "metric_name": "ai_trace_id_count",
- "metric_value": 2.0,
- }, # trace-1, trace-2
- {"date": "2025-01-01", "team_id": 2, "metric_name": "ai_trace_id_count", "metric_value": 1.0}, # trace-3
- ],
- "session_counts.sql": [
- {
- "date": "2025-01-01",
- "team_id": 1,
- "metric_name": "ai_session_id_count",
- "metric_value": 1.0,
- }, # session-1
- {
- "date": "2025-01-01",
- "team_id": 2,
- "metric_name": "ai_session_id_count",
- "metric_value": 1.0,
- }, # session-2
- ],
- "error_rates.sql": [
- # Team 1: 1 errored generation out of 3 = 0.3333
- {"date": "2025-01-01", "team_id": 1, "metric_name": "ai_generation_error_rate", "metric_value": 0.3333},
- # Team 1: 1 errored span out of 2 = 0.5
- {"date": "2025-01-01", "team_id": 1, "metric_name": "ai_span_error_rate", "metric_value": 0.5},
- # Team 2: 0 errored out of 1 = 0.0
- {"date": "2025-01-01", "team_id": 2, "metric_name": "ai_generation_error_rate", "metric_value": 0.0},
- ],
- "trace_error_rates.sql": [
- # Team 1: trace-1 has errors, trace-2 doesn't = 1/2 = 0.5
- {"date": "2025-01-01", "team_id": 1, "metric_name": "ai_trace_id_has_error_rate", "metric_value": 0.5},
- # Team 2: trace-3 has no errors = 0/1 = 0.0
- {"date": "2025-01-01", "team_id": 2, "metric_name": "ai_trace_id_has_error_rate", "metric_value": 0.0},
- ],
- "pageview_counts.sql": [
- {"date": "2025-01-01", "team_id": 1, "metric_name": "pageviews_traces", "metric_value": 2.0},
- {"date": "2025-01-01", "team_id": 1, "metric_name": "pageviews_generations", "metric_value": 1.0},
- ],
- }
-
-
[email protected]("sql_file", get_all_sql_files(), ids=lambda f: f.stem)
-def test_sql_output_structure(sql_file: Path, template_context: dict, mock_events_data: list):
- """
- Test that each SQL file produces output with the correct structure.
-
- This test verifies:
- 1. SQL renders without errors
- 2. Output has exactly 4 columns
- 3. Columns are named correctly: date, team_id, metric_name, metric_value
- """
- with open(sql_file) as f:
- template = Template(f.read())
- rendered = template.render(**template_context)
-
- # Basic smoke test - SQL should render
- assert rendered.strip(), f"{sql_file.name} rendered to empty string"
-
- # SQL should be a SELECT statement
- assert "SELECT" in rendered.upper(), f"{sql_file.name} should contain SELECT"
-
- # Should have all required column aliases (or direct column references for team_id)
- for col in EXPECTED_COLUMNS:
- # team_id is often selected directly without an alias
- if col == "team_id":
- assert "team_id" in rendered.lower(), f"{sql_file.name} missing column: {col}"
- else:
- assert f"as {col}" in rendered.lower(), f"{sql_file.name} missing column alias: {col}"
-
-
-def test_event_counts_logic(template_context: dict, mock_events_data: list, expected_metrics: dict):
- """Test event_counts.sql produces correct counts."""
- sql_file = SQL_DIR / "event_counts.sql"
- with open(sql_file) as f:
- template = Template(f.read())
- rendered = template.render(**template_context)
-
- # Verify SQL structure expectations
- assert "count(*)" in rendered.lower(), "event_counts.sql should use count(*)"
- assert "group by date, team_id, event" in rendered.lower(), "Should group by date, team_id, event"
-
- # Verify expected metrics documentation
- expected = expected_metrics["event_counts.sql"]
- assert len(expected) == 3, "Expected 3 metric rows based on mock data"
-
- # Team 1 should have 3 generation events
- gen_team1 = next(m for m in expected if m["team_id"] == 1 and "generation" in m["metric_name"])
- assert gen_team1["metric_value"] == 3.0
-
- # Team 1 should have 2 span events
- span_team1 = next(m for m in expected if m["team_id"] == 1 and "span" in m["metric_name"])
- assert span_team1["metric_value"] == 2.0
-
-
-def test_trace_counts_logic(template_context: dict, mock_events_data: list, expected_metrics: dict):
- """Test trace_counts.sql produces correct distinct trace counts."""
- sql_file = SQL_DIR / "trace_counts.sql"
- with open(sql_file) as f:
- template = Template(f.read())
- rendered = template.render(**template_context)
-
- # Verify SQL uses count(DISTINCT)
- assert "count(distinct" in rendered.lower(), "trace_counts.sql should use count(DISTINCT)"
- assert "$ai_trace_id" in rendered, "Should count distinct $ai_trace_id"
-
- expected = expected_metrics["trace_counts.sql"]
-
- # Team 1: Should have 2 unique traces (trace-1, trace-2)
- team1 = next(m for m in expected if m["team_id"] == 1)
- assert team1["metric_value"] == 2.0, "Team 1 should have 2 unique traces"
-
- # Team 2: Should have 1 unique trace (trace-3)
- team2 = next(m for m in expected if m["team_id"] == 2)
- assert team2["metric_value"] == 1.0, "Team 2 should have 1 unique trace"
-
-
-def test_session_counts_logic(template_context: dict, mock_events_data: list, expected_metrics: dict):
- """Test session_counts.sql produces correct distinct session counts."""
- sql_file = SQL_DIR / "session_counts.sql"
- with open(sql_file) as f:
- template = Template(f.read())
- rendered = template.render(**template_context)
-
- # Verify SQL uses count(DISTINCT)
- assert "count(distinct" in rendered.lower(), "session_counts.sql should use count(DISTINCT)"
- assert "$ai_session_id" in rendered, "Should count distinct $ai_session_id"
-
- expected = expected_metrics["session_counts.sql"]
-
- # Team 1: Should have 1 unique session (session-1)
- team1 = next(m for m in expected if m["team_id"] == 1)
- assert team1["metric_value"] == 1.0, "Team 1 should have 1 unique session"
-
- # Team 2: Should have 1 unique session (session-2)
- team2 = next(m for m in expected if m["team_id"] == 2)
- assert team2["metric_value"] == 1.0, "Team 2 should have 1 unique session"
-
-
-def test_error_rates_logic(template_context: dict, mock_events_data: list, expected_metrics: dict):
- """Test error_rates.sql calculates proportions correctly."""
- sql_file = SQL_DIR / "error_rates.sql"
- with open(sql_file) as f:
- template = Template(f.read())
- rendered = template.render(**template_context)
-
- # Verify SQL calculates proportions
- assert "countif" in rendered.lower(), "error_rates.sql should use countIf"
- assert "/ count(*)" in rendered.lower(), "Should divide by total count"
- assert "round(" in rendered.lower(), "Should round the result"
-
- # Verify error detection logic
- assert "$ai_error" in rendered, "Should check $ai_error property"
- assert "$ai_is_error" in rendered, "Should check $ai_is_error property"
-
- expected = expected_metrics["error_rates.sql"]
-
- # Team 1 generations: 1 error out of 3 = 0.3333
- gen_team1 = next(m for m in expected if m["team_id"] == 1 and "generation" in m["metric_name"])
- assert abs(gen_team1["metric_value"] - 0.3333) < 0.0001, "Generation error rate should be ~0.3333"
-
- # Team 1 spans: 1 error out of 2 = 0.5
- span_team1 = next(m for m in expected if m["team_id"] == 1 and "span" in m["metric_name"])
- assert span_team1["metric_value"] == 0.5, "Span error rate should be 0.5"
-
-
-def test_trace_error_rates_logic(template_context: dict, mock_events_data: list, expected_metrics: dict):
- """Test trace_error_rates.sql calculates trace-level error proportions correctly."""
- sql_file = SQL_DIR / "trace_error_rates.sql"
- with open(sql_file) as f:
- template = Template(f.read())
- rendered = template.render(**template_context)
-
- # Verify SQL uses distinct count
- assert "countdistinctif" in rendered.lower(), "Should use countDistinctIf"
- assert "count(distinct" in rendered.lower(), "Should use count(DISTINCT) for total"
- assert "$ai_trace_id" in rendered, "Should work with $ai_trace_id"
-
- expected = expected_metrics["trace_error_rates.sql"]
-
- # Team 1: trace-1 has errors, trace-2 doesn't = 1/2 = 0.5
- team1 = next(m for m in expected if m["team_id"] == 1)
- assert team1["metric_value"] == 0.5, "Team 1 should have 50% of traces with errors"
-
- # Team 2: trace-3 has no errors = 0/1 = 0.0
- team2 = next(m for m in expected if m["team_id"] == 2)
- assert team2["metric_value"] == 0.0, "Team 2 should have 0% of traces with errors"
-
-
-def test_pageview_counts_logic(template_context: dict, mock_events_data: list, expected_metrics: dict):
- """Test pageview_counts.sql categorizes and counts pageviews correctly."""
- sql_file = SQL_DIR / "pageview_counts.sql"
- with open(sql_file) as f:
- template = Template(f.read())
- rendered = template.render(**template_context)
-
- # Verify SQL uses the llma_pageview_events CTE (which filters $pageview events)
- assert "llma_pageview_events" in rendered, "Should use llma_pageview_events CTE"
- assert "$current_url" in rendered, "Should use $current_url property"
- assert "LIKE" in rendered, "Should use LIKE for URL matching"
-
- # Verify pageview mappings are used
- assert config.pageview_mappings is not None
- for url_path, _ in config.pageview_mappings:
- assert url_path in rendered, f"Should include pageview mapping for {url_path}"
-
- expected = expected_metrics["pageview_counts.sql"]
-
- # Team 1: 2 trace pageviews
- traces = next(m for m in expected if "traces" in m["metric_name"])
- assert traces["metric_value"] == 2.0, "Should count 2 trace pageviews"
-
- # Team 1: 1 generation pageview
- gens = next(m for m in expected if "generations" in m["metric_name"])
- assert gens["metric_value"] == 1.0, "Should count 1 generation pageview"