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(ai-observability): avoid slow ai query predicates (#62417)

Radu Raiceaf8c19be3e671
diff --git a/posthog/hogql_queries/ai/trace_id_resolver.py b/posthog/hogql_queries/ai/trace_id_resolver.py
index 17a39503f71e..5806292f0c43 100644
--- a/posthog/hogql_queries/ai/trace_id_resolver.py
+++ b/posthog/hogql_queries/ai/trace_id_resolver.py
@@ -65,7 +65,7 @@ def resolve_trace_ids_for_generation_uuids(
WHERE event = '$ai_generation'
AND timestamp >= {ts_start}
AND timestamp < {ts_end}
- AND toString(uuid) IN {uuids}
+ AND uuid IN {uuids}
"""
)
@@ -76,7 +76,7 @@ def resolve_trace_ids_for_generation_uuids(
placeholders={
"ts_start": ast.Constant(value=ts_start),
"ts_end": ast.Constant(value=ts_end),
- "uuids": ast.Array(exprs=[ast.Constant(value=u) for u in generation_uuids]),
+ "uuids": ast.Tuple(exprs=[ast.Constant(value=u) for u in generation_uuids]),
},
team=team,
)
diff --git a/posthog/hogql_queries/ai/vector_search_query_runner.py b/posthog/hogql_queries/ai/vector_search_query_runner.py
index 1e73d4bf0d50..3dcef8cb8074 100644
--- a/posthog/hogql_queries/ai/vector_search_query_runner.py
+++ b/posthog/hogql_queries/ai/vector_search_query_runner.py
@@ -80,7 +80,7 @@ class VectorSearchQueryRunner(TaxonomyCacheMixin, AnalyticsQueryRunner[VectorSea
exprs=[
base_filter,
parse_expr(
- "JSONExtractUInt(properties, 'embedding_version') = {version}",
+ "toInt(properties.embedding_version) = {version}",
{"version": ast.Constant(value=self.query.embeddingVersion)},
),
]
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 5e743fe94a90..88ee8e419b84 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
@@ -504,12 +504,12 @@ def sample_generation_details(
FROM posthog.ai_events AS ai_events
WHERE event = '$ai_generation'
AND trace_id IN {trace_ids}
- AND toString(uuid) IN {ids}
+ AND uuid IN {ids}
LIMIT {limit}
""",
placeholders={
- "ids": ast.Array(exprs=[ast.Constant(value=gid) for gid in ids_to_fetch]),
- "trace_ids": ast.Array(exprs=[ast.Constant(value=tid) for tid in trace_ids]),
+ "ids": ast.Tuple(exprs=[ast.Constant(value=gid) for gid in ids_to_fetch]),
+ "trace_ids": ast.Tuple(exprs=[ast.Constant(value=tid) for tid in trace_ids]),
"limit": ast.Constant(value=len(ids_to_fetch)),
},
)
@@ -620,7 +620,7 @@ def get_generation_detail(
FROM posthog.ai_events AS ai_events
WHERE event = '$ai_generation'
AND trace_id = {trace_id}
- AND toString(uuid) = {generation_id}
+ AND uuid = {generation_id}
LIMIT 1
""",
placeholders=gen_placeholders,
@@ -747,7 +747,7 @@ def get_generation_text_repr(
FROM posthog.ai_events AS ai_events
WHERE event = '$ai_generation'
AND trace_id = {trace_id}
- AND toString(uuid) = {generation_id}
+ AND uuid = {generation_id}
LIMIT 1
""",
placeholders={
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/data.py b/posthog/temporal/ai_observability/evaluation_clustering/data.py
index c8e6ad7af6d8..34aeb4fd5828 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/data.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/data.py
@@ -14,8 +14,10 @@ A LEFT JOIN is used so that a missing / purged generation degrades gracefully:
eval-only fields populate, operational fields stay None.
"""
+from collections.abc import Iterable
from dataclasses import dataclass
from datetime import datetime
+from uuid import UUID
import structlog
@@ -40,6 +42,19 @@ logger = structlog.get_logger(__name__)
CLUSTERING_QUERY_MAX_EXECUTION_TIME = 120
+def _canonical_uuid(value: object) -> str | None:
+ if not isinstance(value, str):
+ return None
+ try:
+ return str(UUID(value))
+ except ValueError:
+ return None
+
+
+def _canonical_uuids(values: Iterable[object]) -> list[str]:
+ return sorted({uuid for value in values if (uuid := _canonical_uuid(value)) is not None})
+
+
@dataclass
class EvaluationMetadata:
"""Per-evaluation metadata joined with its target generation's operational metrics."""
@@ -180,13 +195,13 @@ def fetch_evaluation_metadata(
if not eval_rows:
return {}
- # Collect target generation ids so we can batch-fetch them in one query.
- target_generation_ids = sorted({row["target_generation_id"] for row in eval_rows if row["target_generation_id"]})
+ # $ai_target_event_id comes from user instrumentation; filter before native UUID predicates.
+ target_generation_ids = _canonical_uuids([row["target_generation_id"] for row in eval_rows])
generations = _fetch_linked_generations(team, target_generation_ids, window_start, window_end)
metadata: dict[str, EvaluationMetadata] = {}
for row in eval_rows:
- target_id = row["target_generation_id"]
+ target_id = _canonical_uuid(row["target_generation_id"])
gen = generations.get(target_id) if target_id else None
metadata[row["eval_event_id"]] = EvaluationMetadata(
eval_event_id=row["eval_event_id"],
@@ -197,7 +212,7 @@ def fetch_evaluation_metadata(
evaluation_runtime=row["evaluation_runtime"] or None,
evaluation_reasoning=row["evaluation_reasoning"] or None,
judge_cost_usd=row["judge_cost_usd"],
- target_generation_id=target_id or None,
+ target_generation_id=target_id,
target_trace_id=row["target_trace_id"] or None,
generation_cost_usd=gen["cost_usd"] if gen else None,
generation_latency_ms=gen["latency_ms"] if gen else None,
@@ -242,7 +257,7 @@ def _fetch_evaluation_rows(
WHERE event = '$ai_evaluation'
AND timestamp >= {start_dt}
AND timestamp < {end_dt}
- AND toString(uuid) IN {eval_ids}
+ AND uuid IN {eval_ids}
LIMIT {limit}
"""
)
@@ -291,6 +306,7 @@ def _fetch_linked_generations(
then drop to None operational fields for every eval, matching the spec's
"missing generation degrades gracefully" behavior.
"""
+ generation_ids = _canonical_uuids(generation_ids)
if not generation_ids:
return {}
@@ -310,7 +326,7 @@ def _fetch_linked_generations(
WHERE event = '$ai_generation'
AND timestamp >= {start_dt}
AND timestamp < {end_dt}
- AND toString(uuid) IN {ids}
+ AND uuid IN {ids}
LIMIT {limit}
"""
)
@@ -370,6 +386,7 @@ def fetch_generation_contents(
required so the events lookup is bounded by the events sorting key
`(team_id, toDate(timestamp), event)` instead of full-team scanning.
"""
+ generation_ids = _canonical_uuids(generation_ids)
if not generation_ids:
return {}
@@ -401,7 +418,7 @@ def fetch_generation_contents(
FROM posthog.ai_events AS ai_events
WHERE event = '$ai_generation'
AND trace_id IN {trace_ids}
- AND toString(uuid) IN {ids}
+ AND uuid IN {ids}
LIMIT {limit}
"""
)
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_data.py b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_data.py
index d5fadbe5e6fd..36611b410ea5 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_data.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_data.py
@@ -1,6 +1,7 @@
"""Tests for Stage B data access — embeddings fetch + eval→generation metadata join."""
from datetime import UTC
+from types import SimpleNamespace
import pytest
from unittest.mock import patch
@@ -15,14 +16,12 @@ from posthog.temporal.ai_observability.evaluation_clustering.data import (
fetch_evaluation_metadata,
)
+_VALID_GENERATION_ID = "12345678-1234-1234-1234-123456789abc"
-def mock_team(db):
- from posthog.models.organization import Organization
- from posthog.models.team import Team
- org = Organization.objects.create(name="Eval Data Test Org")
- return Team.objects.create(organization=org, name="Eval Data Test Team")
+def mock_team():
+ return SimpleNamespace(id=1)
class TestCoerceBool:
@@ -46,7 +45,6 @@ class TestCoerceBool:
class TestFetchEvaluationEmbeddings:
- @pytest.mark.django_db
def test_filters_by_doc_type_and_job_suffix(self, mock_team):
with patch("posthog.temporal.ai_observability.evaluation_clustering.data.execute_hogql_query") as mock_execute:
mock_execute.return_value.results = [
@@ -69,7 +67,6 @@ class TestFetchEvaluationEmbeddings:
assert placeholders["job_id_suffix"].value == "_job-abc"
assert placeholders["max_samples"].value == 100
- @pytest.mark.django_db
def test_empty_results(self, mock_team):
with patch("posthog.temporal.ai_observability.evaluation_clustering.data.execute_hogql_query") as mock_execute:
mock_execute.return_value.results = []
@@ -79,7 +76,6 @@ class TestFetchEvaluationEmbeddings:
class TestFetchEvaluationMetadata:
- @pytest.mark.django_db
def test_empty_input_returns_empty(self, mock_team):
from datetime import datetime
@@ -91,7 +87,6 @@ class TestFetchEvaluationMetadata:
)
assert result == {}
- @pytest.mark.django_db
def test_populates_all_fields_when_generation_present(self, mock_team):
"""Two-query metadata fetch: eval rows, then a second query for linked generations."""
from datetime import datetime
@@ -107,11 +102,11 @@ class TestFetchEvaluationMetadata:
"llm_judge",
"The answer was correct.",
0.0012,
- "gen-1",
+ _VALID_GENERATION_ID,
"trace-1",
]
# Row shape mirrors _fetch_linked_generations SELECT
- gen_row = ["gen-1", 0.035, 450.0, 500, 150, "gpt-4o", "false"]
+ gen_row = [_VALID_GENERATION_ID, 0.035, 450.0, 500, 150, "gpt-4o", "false"]
with patch("posthog.temporal.ai_observability.evaluation_clustering.data.execute_hogql_query") as mock_execute:
# First call returns eval rows, second call returns linked generations
@@ -134,14 +129,13 @@ class TestFetchEvaluationMetadata:
assert meta.evaluation_applicable is None
assert meta.evaluation_runtime == "llm_judge"
assert meta.judge_cost_usd == 0.0012
- assert meta.target_generation_id == "gen-1"
+ assert meta.target_generation_id == _VALID_GENERATION_ID
assert meta.target_trace_id == "trace-1"
assert meta.generation_cost_usd == 0.035
assert meta.generation_latency_ms == 450.0
assert meta.generation_model == "gpt-4o"
assert meta.generation_is_error is False
- @pytest.mark.django_db
def test_degrades_when_linked_generation_missing(self, mock_team):
"""Missing generation (second query returns no rows) → None operational fields."""
from datetime import datetime
@@ -155,7 +149,7 @@ class TestFetchEvaluationMetadata:
"llm_judge",
"Hallucinated the citation.",
0.0012,
- "gen-1",
+ _VALID_GENERATION_ID,
"trace-1",
]
with patch("posthog.temporal.ai_observability.evaluation_clustering.data.execute_hogql_query") as mock_execute:
@@ -177,3 +171,32 @@ class TestFetchEvaluationMetadata:
assert meta.generation_latency_ms is None
assert meta.generation_model is None
assert meta.generation_is_error is None
+
+ def test_skips_malformed_target_generation_ids(self, mock_team):
+ from datetime import datetime
+
+ eval_row = [
+ "eval-1",
+ "cfg-accuracy",
+ "Accuracy",
+ "false",
+ None,
+ "llm_judge",
+ "Bad target id.",
+ 0.0012,
+ "not-a-uuid",
+ "trace-1",
+ ]
+ with patch("posthog.temporal.ai_observability.evaluation_clustering.data.execute_hogql_query") as mock_execute:
+ mock_execute.return_value.results = [eval_row]
+ result = fetch_evaluation_metadata(
+ team=mock_team,
+ eval_event_ids=["eval-1"],
+ window_start=datetime(2026, 4, 15, tzinfo=UTC),
+ window_end=datetime(2026, 4, 16, tzinfo=UTC),
+ )
+
+ meta = result["eval-1"]
+ assert meta.target_generation_id is None
+ assert meta.generation_cost_usd is None
+ assert mock_execute.call_count == 1
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_strip_migration.py b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_strip_migration.py
index 126aed8df7ad..8927b02add3e 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_strip_migration.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_strip_migration.py
@@ -10,6 +10,7 @@ both layers.
"""
from datetime import UTC, datetime
+from types import SimpleNamespace
from typing import cast
import pytest
@@ -22,15 +23,13 @@ from posthog.temporal.ai_observability.evaluation_clustering.data import fetch_g
_RESOLVE_PATH = "posthog.temporal.ai_observability.evaluation_clustering.data.resolve_trace_ids_for_generation_uuids"
_WINDOW_START = datetime(2026, 4, 27, 7, 0, 0, tzinfo=UTC)
_WINDOW_END = datetime(2026, 4, 27, 8, 0, 0, tzinfo=UTC)
+_GENERATION_ID_1 = "12345678-1234-1234-1234-123456789abc"
+_GENERATION_ID_2 = "12345678-1234-1234-1234-123456789abd"
@pytest.fixture
-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 team():
+ return SimpleNamespace(id=1)
def _resolver_response(rows: list[list]) -> MagicMock:
@@ -39,7 +38,6 @@ def _resolver_response(rows: list[list]) -> MagicMock:
return response
class TestFetchGenerationContents:
def test_empty_id_list_short_circuits(self, team):
# No queries at all when there's nothing to fetch — guards against
@@ -57,7 +55,7 @@ class TestFetchGenerationContents:
assert mock_resolver.call_count == 0
assert mock_resolve.call_count == 0
- @patch(_RESOLVE_PATH, return_value={"gid-1": "trace-A", "gid-2": "trace-B"})
+ @patch(_RESOLVE_PATH, return_value={_GENERATION_ID_1: "trace-A", _GENERATION_ID_2: "trace-B"})
def test_returns_per_generation_dict(self, _mock_resolve, team):
with patch(
"posthog.temporal.ai_observability.evaluation_clustering.data.execute_with_ai_events_fallback"
@@ -65,28 +63,41 @@ class TestFetchGenerationContents:
# Row tuple: (generation_id, model, input_raw, output_raw)
mock_resolver.return_value = _resolver_response(
[
- ["gid-1", "gpt-4o", '[{"role":"user","content":"hi"}]', '[{"role":"assistant","content":"hello"}]'],
- ["gid-2", "gpt-4o", '[{"role":"user","content":"yo"}]', '[{"role":"assistant","content":"sup"}]'],
+ [
+ _GENERATION_ID_1,
+ "gpt-4o",
+ '[{"role":"user","content":"hi"}]',
+ '[{"role":"assistant","content":"hello"}]',
+ ],
+ [
+ _GENERATION_ID_2,
+ "gpt-4o",
+ '[{"role":"user","content":"yo"}]',
+ '[{"role":"assistant","content":"sup"}]',
+ ],
]
)
result = fetch_generation_contents(
- team, generation_ids=["gid-1", "gid-2"], window_start=_WINDOW_START, window_end=_WINDOW_END
+ team,
+ generation_ids=[_GENERATION_ID_1, _GENERATION_ID_2],
+ window_start=_WINDOW_START,
+ window_end=_WINDOW_END,
)
- assert set(result.keys()) == {"gid-1", "gid-2"}
- assert result["gid-1"]["model"] == "gpt-4o"
- assert "hi" in result["gid-1"]["input"]
- assert "hello" in result["gid-1"]["output"]
+ assert set(result.keys()) == {_GENERATION_ID_1, _GENERATION_ID_2}
+ assert result[_GENERATION_ID_1]["model"] == "gpt-4o"
+ assert "hi" in result[_GENERATION_ID_1]["input"]
+ assert "hello" in result[_GENERATION_ID_1]["output"]
- @patch(_RESOLVE_PATH, return_value={"gid-1": "trace-A"})
+ @patch(_RESOLVE_PATH, return_value={_GENERATION_ID_1: "trace-A"})
def test_truncates_input_and_output(self, _mock_resolve, team):
big = "x" * 5000
with patch(
"posthog.temporal.ai_observability.evaluation_clustering.data.execute_with_ai_events_fallback"
) as mock_resolver:
- mock_resolver.return_value = _resolver_response([["gid-1", "gpt-4o", big, big]])
+ mock_resolver.return_value = _resolver_response([[_GENERATION_ID_1, "gpt-4o", big, big]])
result = fetch_generation_contents(
team,
- generation_ids=["gid-1"],
+ generation_ids=[_GENERATION_ID_1],
max_input_chars=100,
max_output_chars=200,
window_start=_WINDOW_START,
@@ -94,12 +105,12 @@ class TestFetchGenerationContents:
)
# `_truncate` returns `s[:limit] + "… [N more chars]"` so the prefix
# length is `limit` and the total length is `limit + suffix_len`.
- assert result["gid-1"]["input"].startswith("x" * 100)
- assert "more chars]" in result["gid-1"]["input"]
- assert result["gid-1"]["output"].startswith("x" * 200)
- assert "more chars]" in result["gid-1"]["output"]
+ assert result[_GENERATION_ID_1]["input"].startswith("x" * 100)
+ assert "more chars]" in result[_GENERATION_ID_1]["input"]
+ assert result[_GENERATION_ID_1]["output"].startswith("x" * 200)
+ assert "more chars]" in result[_GENERATION_ID_1]["output"]
- @patch(_RESOLVE_PATH, return_value={"gid-1": "trace-A"})
+ @patch(_RESOLVE_PATH, return_value={_GENERATION_ID_1: "trace-A"})
def test_query_reads_native_heavy_columns_from_ai_events(self, _mock_resolve, team):
"""The whole point of the migration is that `input` / `output_choices`
come off the dedicated `ai_events` columns rather than NULL JSON-extracts
@@ -109,7 +120,7 @@ class TestFetchGenerationContents:
) as mock_resolver:
mock_resolver.return_value = _resolver_response([])
fetch_generation_contents(
- team, generation_ids=["gid-1"], window_start=_WINDOW_START, window_end=_WINDOW_END
+ team, generation_ids=[_GENERATION_ID_1], window_start=_WINDOW_START, window_end=_WINDOW_END
)
kwargs = mock_resolver.call_args.kwargs
@@ -126,7 +137,7 @@ class TestFetchGenerationContents:
assert kwargs["settings"].max_execution_time == CLUSTERING_QUERY_MAX_EXECUTION_TIME
assert kwargs["query_type"] == "GenerationContentsForLabeling"
- @patch(_RESOLVE_PATH, return_value={"gid-1": "trace-A", "gid-2": "trace-B"})
+ @patch(_RESOLVE_PATH, return_value={_GENERATION_ID_1: "trace-A", _GENERATION_ID_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
gets the full ai_events sorting-key prefix + cityHash64 sharding-key
@@ -136,7 +147,10 @@ class TestFetchGenerationContents:
) as mock_resolver:
mock_resolver.return_value = _resolver_response([])
fetch_generation_contents(
- team, generation_ids=["gid-1", "gid-2"], window_start=_WINDOW_START, window_end=_WINDOW_END
+ team,
+ generation_ids=[_GENERATION_ID_1, _GENERATION_ID_2],
+ window_start=_WINDOW_START,
+ window_end=_WINDOW_END,
)
placeholders = mock_resolver.call_args.kwargs["placeholders"]
@@ -152,7 +166,25 @@ class TestFetchGenerationContents:
"posthog.temporal.ai_observability.evaluation_clustering.data.execute_with_ai_events_fallback"
) as mock_resolver:
result = fetch_generation_contents(
- team, generation_ids=["gid-1"], window_start=_WINDOW_START, window_end=_WINDOW_END
+ team, generation_ids=[_GENERATION_ID_1], window_start=_WINDOW_START, window_end=_WINDOW_END
)
assert result == {}
assert mock_resolver.call_count == 0
+
+ @patch(_RESOLVE_PATH, return_value={_GENERATION_ID_1: "trace-A"})
+ def test_malformed_generation_ids_are_filtered_before_uuid_queries(self, mock_resolve, team):
+ with patch(
+ "posthog.temporal.ai_observability.evaluation_clustering.data.execute_with_ai_events_fallback"
+ ) as mock_resolver:
+ mock_resolver.return_value = _resolver_response([[_GENERATION_ID_1, "gpt-4o", "input", "output"]])
+ result = fetch_generation_contents(
+ team,
+ generation_ids=["not-a-uuid", _GENERATION_ID_1],
+ window_start=_WINDOW_START,
+ window_end=_WINDOW_END,
+ )
+
+ assert set(result.keys()) == {_GENERATION_ID_1}
+ assert mock_resolve.call_args.kwargs["generation_uuids"] == [_GENERATION_ID_1]
+ ids = mock_resolver.call_args.kwargs["placeholders"]["ids"]
+ assert [expr.value for expr in ids.exprs] == [_GENERATION_ID_1]
diff --git a/posthog/temporal/ai_observability/trace_clustering/data.py b/posthog/temporal/ai_observability/trace_clustering/data.py
index 4a4ca55a38c1..33c49f1ca9cc 100644
--- a/posthog/temporal/ai_observability/trace_clustering/data.py
+++ b/posthog/temporal/ai_observability/trace_clustering/data.py
@@ -311,7 +311,7 @@ def fetch_item_metrics(
WHERE event = '$ai_generation'
AND timestamp >= {start_dt}
AND timestamp < {end_dt}
- AND toString(uuid) IN {item_ids}
+ AND uuid IN {item_ids}
LIMIT {max_rows}
"""
)
diff --git a/products/ai_observability/frontend/clusters/clusterDetailLogic.ts b/products/ai_observability/frontend/clusters/clusterDetailLogic.ts
index 2e6f5055b649..6e2fb1da7000 100644
--- a/products/ai_observability/frontend/clusters/clusterDetailLogic.ts
+++ b/products/ai_observability/frontend/clusters/clusterDetailLogic.ts
@@ -237,17 +237,17 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([
const response = await api.queryHogQL(
hogql`
SELECT
- JSONExtractString(properties, '$ai_clustering_run_id') as run_id,
- JSONExtractString(properties, '$ai_window_start') as window_start,
- JSONExtractString(properties, '$ai_window_end') as window_end,
- JSONExtractRaw(properties, '$ai_clusters') as clusters,
+ properties.$ai_clustering_run_id as run_id,
+ properties.$ai_window_start as window_start,
+ properties.$ai_window_end as window_end,
+ properties.$ai_clusters as clusters,
timestamp,
- JSONExtractString(properties, '$ai_clustering_level') as clustering_level
+ properties.$ai_clustering_level as clustering_level
FROM events
WHERE event IN ('$ai_trace_clusters', '$ai_generation_clusters', '$ai_evaluation_clusters')
AND timestamp >= ${dayStart}
AND timestamp <= ${dayEnd}
- AND JSONExtractString(properties, '$ai_clustering_run_id') = ${props.runId}
+ AND properties.$ai_clustering_run_id = ${props.runId}
LIMIT 1
`,
{ productKey: 'llm_analytics', scene: 'AIObservabilityCluster' },
diff --git a/products/ai_observability/frontend/clusters/clusterMetricsLoader.ts b/products/ai_observability/frontend/clusters/clusterMetricsLoader.ts
index 33a98dd8f7bc..465450455fb3 100644
--- a/products/ai_observability/frontend/clusters/clusterMetricsLoader.ts
+++ b/products/ai_observability/frontend/clusters/clusterMetricsLoader.ts
@@ -55,12 +55,12 @@ export async function loadClusterMetrics(
WHERE event = '$ai_generation'
AND timestamp >= parseDateTimeBestEffort(${windowStart})
AND timestamp <= parseDateTimeBestEffort(${windowEnd})
- AND toString(uuid) IN ${allItemIds}
+ AND uuid IN ${allItemIds}
LIMIT ${allItemIds.length}
`
: hogql`
SELECT
- JSONExtractString(properties, '$ai_trace_id') as item_id,
+ properties.$ai_trace_id as item_id,
sum(toFloat(properties.$ai_total_cost_usd)) as cost,
max(toFloat(properties.$ai_latency)) as latency,
sum(toInt(properties.$ai_input_tokens)) as input_tokens,
@@ -70,7 +70,7 @@ export async function loadClusterMetrics(
WHERE event IN ('$ai_generation', '$ai_embedding', '$ai_span')
AND timestamp >= parseDateTimeBestEffort(${windowStart})
AND timestamp <= parseDateTimeBestEffort(${windowEnd})
- AND JSONExtractString(properties, '$ai_trace_id') IN ${allItemIds}
+ AND properties.$ai_trace_id IN ${allItemIds}
GROUP BY item_id
LIMIT ${allItemIds.length}
`,
diff --git a/products/ai_observability/frontend/clusters/clustersLogic.ts b/products/ai_observability/frontend/clusters/clustersLogic.ts
index 8c5fe71e6ef7..51f54456dd6f 100644
--- a/products/ai_observability/frontend/clusters/clustersLogic.ts
+++ b/products/ai_observability/frontend/clusters/clustersLogic.ts
@@ -322,8 +322,8 @@ export const clustersLogic = kea<clustersLogicType>([
const response = await api.queryHogQL(
hogql`
SELECT
- JSONExtractString(properties, '$ai_clustering_run_id') as run_id,
- JSONExtractString(properties, '$ai_window_end') as window_end,
+ properties.$ai_clustering_run_id as run_id,
+ properties.$ai_window_end as window_end,
timestamp
FROM events
WHERE event = ${eventName}
@@ -360,19 +360,19 @@ export const clustersLogic = kea<clustersLogicType>([
const response = await api.queryHogQL(
hogql`
SELECT
- JSONExtractString(properties, '$ai_clustering_run_id') as run_id,
- JSONExtractString(properties, '$ai_window_start') as window_start,
- JSONExtractString(properties, '$ai_window_end') as window_end,
- JSONExtractInt(properties, '$ai_total_items_analyzed') as total_items,
- JSONExtractRaw(properties, '$ai_clusters') as clusters,
+ properties.$ai_clustering_run_id as run_id,
+ properties.$ai_window_start as window_start,
+ properties.$ai_window_end as window_end,
+ toInt(properties.$ai_total_items_analyzed) as total_items,
+ properties.$ai_clusters as clusters,
timestamp,
- JSONExtractRaw(properties, '$ai_clustering_params') as clustering_params,
- JSONExtractString(properties, '$ai_clustering_level') as clustering_level
+ properties.$ai_clustering_params as clustering_params,
+ properties.$ai_clustering_level as clustering_level
FROM events
WHERE event = ${eventName}
AND timestamp >= ${dayStart}
AND timestamp <= ${dayEnd}
- AND JSONExtractString(properties, '$ai_clustering_run_id') = ${runId}
+ AND properties.$ai_clustering_run_id = ${runId}
LIMIT 1
`,
{ productKey: 'llm_analytics', scene: 'AIObservabilityClusters' },
diff --git a/products/ai_observability/frontend/clusters/traceSummaryLoader.ts b/products/ai_observability/frontend/clusters/traceSummaryLoader.ts
index 28724cc62366..59302e740f9b 100644
--- a/products/ai_observability/frontend/clusters/traceSummaryLoader.ts
+++ b/products/ai_observability/frontend/clusters/traceSummaryLoader.ts
@@ -29,23 +29,23 @@ export async function loadTraceSummaries(
}
const eventName = level === 'generation' ? '$ai_generation_summary' : '$ai_trace_summary'
- const idProperty = level === 'generation' ? '$ai_generation_id' : '$ai_trace_id'
+ const idExpression = level === 'generation' ? 'properties.$ai_generation_id' : 'properties.$ai_trace_id'
const response = await api.queryHogQL(
hogql`
SELECT
- JSONExtractString(properties, ${idProperty}) as item_id,
- argMax(JSONExtractString(properties, '$ai_summary_title'), timestamp) as title,
- argMax(JSONExtractString(properties, '$ai_summary_flow_diagram'), timestamp) as flow_diagram,
- argMax(JSONExtractString(properties, '$ai_summary_bullets'), timestamp) as bullets,
- argMax(JSONExtractString(properties, '$ai_summary_interesting_notes'), timestamp) as interesting_notes,
+ ${hogql.raw(idExpression)} as item_id,
+ argMax(properties.$ai_summary_title, timestamp) as title,
+ argMax(properties.$ai_summary_flow_diagram, timestamp) as flow_diagram,
+ argMax(properties.$ai_summary_bullets, timestamp) as bullets,
+ argMax(properties.$ai_summary_interesting_notes, timestamp) as interesting_notes,
max(timestamp) as latest_timestamp,
- argMax(JSONExtractString(properties, '$ai_trace_id'), timestamp) as trace_id
+ argMax(properties.$ai_trace_id, timestamp) as trace_id
FROM events
WHERE event = ${eventName}
AND timestamp >= parseDateTimeBestEffort(${windowStart})
AND timestamp <= parseDateTimeBestEffort(${windowEnd})
- AND JSONExtractString(properties, ${idProperty}) IN ${missingItemIds}
+ AND ${hogql.raw(idExpression)} IN ${missingItemIds}
GROUP BY item_id
LIMIT 10000
`,
@@ -94,19 +94,19 @@ async function loadEvaluationSummaries(
hogql`
SELECT
toString(uuid) as eval_id,
- JSONExtractString(properties, '$ai_evaluation_name') as name,
- JSONExtractString(properties, '$ai_evaluation_result') as result,
- JSONExtractString(properties, '$ai_evaluation_applicable') as applicable,
- JSONExtractString(properties, '$ai_evaluation_reasoning') as reasoning,
- JSONExtractString(properties, '$ai_evaluation_runtime') as runtime,
- JSONExtractString(properties, '$ai_target_event_id') as target_generation_id,
- JSONExtractString(properties, '$ai_trace_id') as trace_id,
+ properties.$ai_evaluation_name as name,
+ properties.$ai_evaluation_result as result,
+ properties.$ai_evaluation_applicable as applicable,
+ properties.$ai_evaluation_reasoning as reasoning,
+ properties.$ai_evaluation_runtime as runtime,
+ properties.$ai_target_event_id as target_generation_id,
+ properties.$ai_trace_id as trace_id,
timestamp
FROM events
WHERE event = '$ai_evaluation'
AND timestamp >= parseDateTimeBestEffort(${windowStart}) - INTERVAL 7 DAY
AND timestamp <= parseDateTimeBestEffort(${windowEnd}) + INTERVAL 1 DAY
- AND toString(uuid) IN ${evalIds}
+ AND uuid IN ${evalIds}
LIMIT 10000
`,
{ productKey: 'llm_analytics', scene: 'AIObservabilityClusters' },
@@ -170,14 +170,14 @@ export async function loadEvaluationItemAttributes(
hogql`
SELECT
toString(uuid) as eval_id,
- JSONExtractString(properties, '$ai_evaluation_name') as name,
- JSONExtractString(properties, '$ai_evaluation_result') as result,
- JSONExtractString(properties, '$ai_evaluation_applicable') as applicable
+ properties.$ai_evaluation_name as name,
+ properties.$ai_evaluation_result as result,
+ properties.$ai_evaluation_applicable as applicable
FROM events
WHERE event = '$ai_evaluation'
AND timestamp >= parseDateTimeBestEffort(${windowStart}) - INTERVAL 7 DAY
AND timestamp <= parseDateTimeBestEffort(${windowEnd}) + INTERVAL 1 DAY
- AND toString(uuid) IN ${evalIds}
+ AND uuid IN ${evalIds}
`,
{ productKey: 'llm_analytics', scene: 'AIObservabilityClusters' },
{ queryParams: { modifiers: { convertToProjectTimezone: false } } }
diff --git a/products/ai_observability/frontend/components/clustersTabContentLogic.ts b/products/ai_observability/frontend/components/clustersTabContentLogic.ts
index 3640c2ed57dc..4d55b7e110f3 100644
--- a/products/ai_observability/frontend/components/clustersTabContentLogic.ts
+++ b/products/ai_observability/frontend/components/clustersTabContentLogic.ts
@@ -40,8 +40,8 @@ export const clustersTabContentLogic = kea<clustersTabContentLogicType>([
const response = await api.queryHogQL(
hogql`
SELECT
- JSONExtractString(properties, '$ai_clustering_run_id') as run_id,
- JSONExtractRaw(properties, '$ai_clusters') as clusters_json,
+ properties.$ai_clustering_run_id as run_id,
+ properties.$ai_clusters as clusters_json,
timestamp
FROM events
WHERE event = '$ai_trace_clusters'
diff --git a/products/ai_observability/frontend/tabs/aiObservabilityUsersLogic.ts b/products/ai_observability/frontend/tabs/aiObservabilityUsersLogic.ts
index 857f09740198..0fae2fce90ad 100644
--- a/products/ai_observability/frontend/tabs/aiObservabilityUsersLogic.ts
+++ b/products/ai_observability/frontend/tabs/aiObservabilityUsersLogic.ts
@@ -61,10 +61,10 @@ export const aiObservabilityUsersLogic = kea<aiObservabilityUsersLogicType>([
SELECT
distinct_id,
timestamp,
- JSONExtractRaw(properties, '$ai_trace_id') as ai_trace_id,
- JSONExtractRaw(properties, '$ai_total_cost_usd') as ai_total_cost_usd,
- JSONExtractRaw(properties, '$ai_error') as ai_error,
- JSONExtractString(properties, '$ai_is_error') as ai_is_error,
+ properties.$ai_trace_id as ai_trace_id,
+ properties.$ai_total_cost_usd as ai_total_cost_usd,
+ properties.$ai_error as ai_error,
+ properties.$ai_is_error as ai_is_error,
tuple(
distinct_id,
person.created_at,
diff --git a/products/ai_observability/skills/exploring-llm-clusters/SKILL.md b/products/ai_observability/skills/exploring-llm-clusters/SKILL.md
index a650879f763d..2543995a18bf 100644
--- a/products/ai_observability/skills/exploring-llm-clusters/SKILL.md
+++ b/products/ai_observability/skills/exploring-llm-clusters/SKILL.md
@@ -82,11 +82,11 @@ and disabled when a custom job is created for the same level.
```sql
posthog:execute-sql
SELECT
- JSONExtractString(properties, '$ai_clustering_run_id') as run_id,
- JSONExtractString(properties, '$ai_clustering_level') as level,
- JSONExtractString(properties, '$ai_window_start') as window_start,
- JSONExtractString(properties, '$ai_window_end') as window_end,
- JSONExtractInt(properties, '$ai_total_items_analyzed') as total_items,
+ properties.$ai_clustering_run_id as run_id,
+ properties.$ai_clustering_level as level,
+ properties.$ai_window_start as window_start,
+ properties.$ai_window_end as window_end,
+ toInt(properties.$ai_total_items_analyzed) as total_items,
timestamp
FROM events
WHERE event IN ('$ai_trace_clusters', '$ai_generation_clusters')
@@ -100,18 +100,18 @@ LIMIT 10
```sql
posthog:execute-sql
SELECT
- JSONExtractString(properties, '$ai_clustering_run_id') as run_id,
- JSONExtractString(properties, '$ai_clustering_level') as level,
- JSONExtractString(properties, '$ai_clustering_job_id') as job_id,
- JSONExtractString(properties, '$ai_clustering_job_name') as job_name,
- JSONExtractString(properties, '$ai_window_start') as window_start,
- JSONExtractString(properties, '$ai_window_end') as window_end,
- JSONExtractInt(properties, '$ai_total_items_analyzed') as total_items,
- JSONExtractRaw(properties, '$ai_clusters') as clusters,
- JSONExtractRaw(properties, '$ai_clustering_params') as params
+ properties.$ai_clustering_run_id as run_id,
+ properties.$ai_clustering_level as level,
+ properties.$ai_clustering_job_id as job_id,
+ properties.$ai_clustering_job_name as job_name,
+ properties.$ai_window_start as window_start,
+ properties.$ai_window_end as window_end,
+ toInt(properties.$ai_total_items_analyzed) as total_items,
+ properties.$ai_clusters as clusters,
+ properties.$ai_clustering_params as params
FROM events
WHERE event IN ('$ai_trace_clusters', '$ai_generation_clusters')
- AND JSONExtractString(properties, '$ai_clustering_run_id') = '<run_id>'
+ AND properties.$ai_clustering_run_id = '<run_id>'
LIMIT 1
```
@@ -128,7 +128,7 @@ For trace-level clusters, compute cost/latency/token metrics:
```sql
posthog:execute-sql
SELECT
- JSONExtractString(properties, '$ai_trace_id') as trace_id,
+ properties.$ai_trace_id as trace_id,
sum(toFloat(properties.$ai_total_cost_usd)) as total_cost,
max(toFloat(properties.$ai_latency)) as latency,
sum(toInt(properties.$ai_input_tokens)) as input_tokens,
@@ -138,7 +138,7 @@ FROM events
WHERE event IN ('$ai_generation', '$ai_embedding', '$ai_span')
AND timestamp >= parseDateTimeBestEffort('<window_start>')
AND timestamp <= parseDateTimeBestEffort('<window_end>')
- AND JSONExtractString(properties, '$ai_trace_id') IN ('<trace_id_1>', '<trace_id_2>', ...)
+ AND properties.$ai_trace_id IN ('<trace_id_1>', '<trace_id_2>', ...)
GROUP BY trace_id
```
@@ -157,7 +157,7 @@ FROM events
WHERE event = '$ai_generation'
AND timestamp >= parseDateTimeBestEffort('<window_start>')
AND timestamp <= parseDateTimeBestEffort('<window_end>')
- AND toString(uuid) IN ('<gen_uuid_1>', '<gen_uuid_2>', ...)
+ AND uuid IN ('<gen_uuid_1>', '<gen_uuid_2>', ...)
```
### Step 4 — Drill into specific traces