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.

feat(aio): open verified offline experiment traces in a drawer (#128461)

Radu Raicea65a5bb1d9e18
diff --git a/docs/internal/ai-offline-evaluation-reporting.md b/docs/internal/ai-offline-evaluation-reporting.md
index 30035c66eb90..7deea7dea9c3 100644
--- a/docs/internal/ai-offline-evaluation-reporting.md
+++ b/docs/internal/ai-offline-evaluation-reporting.md
@@ -735,6 +735,7 @@ Scroll horizontally to reach additional scorer columns.
Open an item or score cell for input, output, expected output, reasoning, and payload availability.
Boolean score cells and numeric or categorical cells with a passing rule retain their raw values or custom labels, with a success/check or danger/cross treatment based on the pinned version's rule. Execution errors use a separate warning treatment; skipped, not-applicable, missing, and numeric or categorical results without a passing rule remain neutral.
The inspector separates payload fields into collapsible labeled panels. Metadata and long text or large JSON start collapsed; each field can be expanded independently. Result details show the selected scorer and score above its reasoning.
+Small application and evaluator trace buttons appear only after a background lookup confirms their IDs in the current project. The lookup batches both IDs in one AI events query, then checks only missing IDs in one shared events query using the trace reader's fallback window, without reading trace payloads. Each query has a two-second execution limit; a timeout preserves any trace IDs already found. Buttons stay hidden while checking, on failure, or when no match was found within the budget. Changing the selection or closing the inspector cancels obsolete requests; reopening or refreshing the inspector checks again. The evaluator button appears beside the selected score. Buttons open a single trace in the drawer without previous/next controls when the new trace view is enabled; closing it returns to the same item and selected result. Modified clicks open the full trace page, as do buttons when using the legacy trace view.
These larger payloads load only when the inspector requests them.
Upload completion is separate from score quality. **Mark as completed** checks declared expected counts on the server; it cannot force a mismatched upload to complete.
diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.py
index 24fc86cea8d9..2a330fe6bc7b 100644
--- a/posthog/hogql/constants.py
+++ b/posthog/hogql/constants.py
@@ -203,6 +203,7 @@ class HogQLGlobalSettings(HogQLQuerySettings):
model_config = ConfigDict(extra="forbid")
readonly: Optional[int] = 2
max_execution_time: Optional[int] = 60
+ timeout_before_checking_execution_speed: Optional[int] = None
# None inherits the cluster profile's overflow behavior. Set "throw" when a partial
# result is worse than an error (e.g. sampling queries whose output feeds further
# computation), or "break" to accept partial results on timeout.
diff --git a/products/ai_observability/backend/facade/api.py b/products/ai_observability/backend/facade/api.py
index 623255c14ba2..805d916f2eae 100644
--- a/products/ai_observability/backend/facade/api.py
+++ b/products/ai_observability/backend/facade/api.py
@@ -81,6 +81,7 @@ from ..logic.traces.trace_export import (
)
from ..logic.traces.trace_queries import (
TraceNodeRow,
+ load_available_trace_ids,
load_trace,
load_trace_feedback_rows,
load_trace_git_rows,
@@ -124,6 +125,10 @@ def is_usable_timestamp_hint(timestamp_hint: datetime) -> bool:
return True
+def get_available_trace_ids(team: Team, user: User | None, trace_ids: list[str]) -> list[str]:
+ return load_available_trace_ids(team, user, trace_ids)
+
+
def get_trace(team: Team, user: User | None, trace_id: str, timestamp_hint: datetime | None) -> contracts.Trace:
loaded = load_trace(team, user, trace_id, timestamp_hint)
if not loaded.rows:
diff --git a/products/ai_observability/backend/logic/traces/trace_queries.py b/products/ai_observability/backend/logic/traces/trace_queries.py
index 72461ae117f9..673b1f7cb7ee 100644
--- a/products/ai_observability/backend/logic/traces/trace_queries.py
+++ b/products/ai_observability/backend/logic/traces/trace_queries.py
@@ -9,6 +9,8 @@ from uuid import UUID
import structlog
+from posthog.schema import HogQLQueryModifiers, MaterializationMode
+
from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.context import HogQLContext
@@ -18,9 +20,15 @@ from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.query_tagging import Product, tag_queries, tags_context
from posthog.dataclasses import frozen
+from posthog.exceptions import ClickHouseQueryTimeOut
+from posthog.hogql_queries.ai.ai_column_rewriter import (
+ EVENTS_FALLBACK_PROPERTY_TYPE_OVERRIDES,
+ rewrite_query_for_events_table,
+)
from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
from posthog.hogql_queries.ai.utils import merge_heavy_properties
from posthog.models import Team, User
+from posthog.models.event.new_events_schema import use_new_events_schema
from .events_fallback import FallbackWindow, events_filter, fallback_window, unhinted_window
from .person import trace_distinct_id
@@ -31,6 +39,7 @@ _HEAVY_COLUMNS = ("input", "output", "output_choices", "input_state", "output_st
_NODE_COLUMNS = ("uuid", "event", "timestamp", "properties", *_HEAVY_COLUMNS)
# The largest result HogQL returns; without an explicit limit it returns 100 rows.
MAX_TRACE_EVENTS = 50_000
+TRACE_AVAILABILITY_QUERY_SECONDS = 2
TOKEN_PROPERTIES = {
"input_tokens": "$ai_input_tokens",
"output_tokens": "$ai_output_tokens",
@@ -447,6 +456,65 @@ def _read_trace(
return read(unhinted_window())
+def _read_trace_availability(
+ team: Team, user: User | None, trace_ids: Sequence[str], *, shared_events: bool = False
+) -> list[str]:
+ trace_filter = ast.CompareOperation(
+ op=ast.CompareOperationOp.In, left=ast.Field(chain=["trace_id"]), right=ast.Constant(value=list(trace_ids))
+ )
+ event_filter = _event_in(TRACE_EVENT_NAMES)
+ query = ast.SelectQuery(
+ select=[ast.Field(chain=["trace_id"])],
+ select_from=_ai_events(),
+ where=events_filter(trace_filter=trace_filter, event_filter=event_filter, window=unhinted_window())
+ if shared_events
+ else ast.And(exprs=[trace_filter, event_filter]),
+ distinct=True,
+ limit=ast.Constant(value=len(trace_ids)),
+ )
+ name = "ai_trace_availability"
+ with tags_context(product=Product.LLM_ANALYTICS):
+ tag_queries(name=name, ai_query_source="shared_table_fallback" if shared_events else "dedicated_table")
+ try:
+ response = execute_hogql_query(
+ query=rewrite_query_for_events_table(query) if shared_events else query,
+ team=team,
+ user=user,
+ query_type=name,
+ modifiers=None
+ if shared_events
+ else HogQLQueryModifiers(materializationMode=MaterializationMode.DISABLED),
+ context=HogQLContext(
+ team_id=team.pk,
+ team=team,
+ user=user,
+ database=Database.create_for_posthog_tables(team),
+ use_new_events_schema=use_new_events_schema(team.pk) if shared_events else None,
+ property_type_overrides=EVENTS_FALLBACK_PROPERTY_TYPE_OVERRIDES if shared_events else None,
+ ),
+ settings=HogQLGlobalSettings(
+ max_execution_time=TRACE_AVAILABILITY_QUERY_SECONDS,
+ timeout_before_checking_execution_speed=0,
+ timeout_overflow_mode="break",
+ ),
+ workload=Workload.ONLINE,
+ )
+ except ClickHouseQueryTimeOut:
+ return []
+ return [str(row[0]) for row in response.results or []]
+
+
+def load_available_trace_ids(team: Team, user: User | None, trace_ids: Sequence[str]) -> list[str]:
+ requested = list(dict.fromkeys(trace_ids))
+ if not requested:
+ return []
+ available = set(_read_trace_availability(team, user, requested))
+ missing = [trace_id for trace_id in requested if trace_id not in available]
+ if missing:
+ available.update(_read_trace_availability(team, user, missing, shared_events=True))
+ return [trace_id for trace_id in requested if trace_id in available]
+
+
def load_trace(
team: Team,
user: User | None,
diff --git a/products/ai_observability/backend/presentation/views.py b/products/ai_observability/backend/presentation/views.py
index e85250aa5014..47ad7d237b9b 100644
--- a/products/ai_observability/backend/presentation/views.py
+++ b/products/ai_observability/backend/presentation/views.py
@@ -51,6 +51,22 @@ class TraceQuerySerializer(serializers.Serializer):
return value
+class TraceAvailabilityRequestSerializer(serializers.Serializer):
+ trace_ids = serializers.ListField(
+ child=serializers.CharField(max_length=255, trim_whitespace=False),
+ min_length=1,
+ max_length=2,
+ help_text="Application and evaluator trace IDs to check without loading trace contents.",
+ )
+
+
+class TraceAvailabilitySerializer(serializers.Serializer):
+ available_trace_ids = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Requested trace IDs readable from AI events or the shared events table.",
+ )
+
+
class TraceClustersQuerySerializer(serializers.Serializer):
created_at = serializers.DateTimeField(
help_text="When the trace started, as the trace resource's createdAt. Bounds which clustering runs are read."
@@ -130,6 +146,7 @@ class TraceViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
scope_object = "llm_analytics"
scope_object_read_actions = [
"retrieve",
+ "availability",
"node",
"evaluations",
"clusters",
@@ -155,6 +172,19 @@ class TraceViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
with query_concurrency_slots(self.team):
return read(user, request.validated_query_data.get("timestamp_hint"))
+ @validated_request(
+ request_serializer=TraceAvailabilityRequestSerializer,
+ responses={200: TraceAvailabilitySerializer, 429: THROTTLED_RESPONSE},
+ operation_id="ai_observability_traces_availability_create",
+ )
+ @action(detail=False, methods=["POST"])
+ def availability(self, request: ValidatedRequest, **kwargs: Any) -> Response:
+ trace_ids = self._read(
+ request,
+ lambda user, _hint: api.get_available_trace_ids(self.team, user, request.validated_data["trace_ids"]),
+ )
+ return Response(TraceAvailabilitySerializer(instance={"available_trace_ids": trace_ids}).data)
+
@validated_request(
query_serializer=TraceQuerySerializer,
parameters=[TRACE_ID_PARAMETER],
diff --git a/products/ai_observability/backend/tests/__snapshots__/test_trace_views.ambr b/products/ai_observability/backend/tests/__snapshots__/test_trace_views.ambr
new file mode 100644
index 000000000000..4506ea023c3c
--- /dev/null
+++ b/products/ai_observability/backend/tests/__snapshots__/test_trace_views.ambr
@@ -0,0 +1,89 @@
+# serializer version: 1
+# name: TestTraceViewSet.test_availability_reads_both_tables_with_a_read_key_and_stays_in_the_project
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT DISTINCT ai_events.trace_id AS trace_id
+ FROM ai_events
+ WHERE and(equals(ai_events.team_id, 99999), in(ai_events.trace_id, ['application,trace', 'evaluator/trace']), in(ai_events.event, tuple('$ai_trace', '$ai_span', '$ai_generation', '$ai_embedding')))
+ LIMIT 2 SETTINGS readonly=2,
+ max_execution_time=2,
+ timeout_before_checking_execution_speed=0,
+ timeout_overflow_mode='break',
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestTraceViewSet.test_availability_reads_both_tables_with_a_read_key_and_stays_in_the_project.1
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT DISTINCT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(__ai_events_fallback.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '') AS trace_id
+ FROM events AS __ai_events_fallback
+ WHERE and(equals(__ai_events_fallback.team_id, 99999), in(__ai_events_fallback.event, tuple('$ai_trace', '$ai_span', '$ai_generation', '$ai_embedding')), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(__ai_events_fallback.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', ''), ['evaluator/trace']), greaterOrEquals(__ai_events_fallback.timestamp, toDateTime64('2025-01-09 23:50:00.000000', 6, 'UTC')), lessOrEquals(__ai_events_fallback.timestamp, toDateTime64('2026-09-09 10:00:00.000000', 6, 'UTC')))
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=2,
+ timeout_before_checking_execution_speed=0,
+ timeout_overflow_mode='break',
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestTraceViewSet.test_availability_reads_both_tables_with_a_read_key_and_stays_in_the_project.2
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT DISTINCT ai_events.trace_id AS trace_id
+ FROM ai_events
+ WHERE and(equals(ai_events.team_id, 99999), in(ai_events.trace_id, ['missing', 'other-trace']), in(ai_events.event, tuple('$ai_trace', '$ai_span', '$ai_generation', '$ai_embedding')))
+ LIMIT 2 SETTINGS readonly=2,
+ max_execution_time=2,
+ timeout_before_checking_execution_speed=0,
+ timeout_overflow_mode='break',
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestTraceViewSet.test_availability_reads_both_tables_with_a_read_key_and_stays_in_the_project.3
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT DISTINCT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(__ai_events_fallback.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '') AS trace_id
+ FROM events AS __ai_events_fallback
+ WHERE and(equals(__ai_events_fallback.team_id, 99999), in(__ai_events_fallback.event, tuple('$ai_trace', '$ai_span', '$ai_generation', '$ai_embedding')), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(__ai_events_fallback.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', ''), ['missing', 'other-trace']), greaterOrEquals(__ai_events_fallback.timestamp, toDateTime64('2025-01-09 23:50:00.000000', 6, 'UTC')), lessOrEquals(__ai_events_fallback.timestamp, toDateTime64('2026-09-09 10:00:00.000000', 6, 'UTC')))
+ LIMIT 2 SETTINGS readonly=2,
+ max_execution_time=2,
+ timeout_before_checking_execution_speed=0,
+ timeout_overflow_mode='break',
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
diff --git a/products/ai_observability/backend/tests/__snapshots__/test_trace_views.new_events_schema.ambr b/products/ai_observability/backend/tests/__snapshots__/test_trace_views.new_events_schema.ambr
new file mode 100644
index 000000000000..a7a3b0d9ac22
--- /dev/null
+++ b/products/ai_observability/backend/tests/__snapshots__/test_trace_views.new_events_schema.ambr
@@ -0,0 +1,49 @@
+# serializer version: 1
+# name: TestTraceViewSet.test_availability_reads_both_tables_with_a_read_key_and_stays_in_the_project[new_events_schema.1]
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT DISTINCT if(notEquals(toJSONString(__ai_events_fallback.properties.^`$ai_trace_id`), '{}'), toJSONString(__ai_events_fallback.properties.^`$ai_trace_id`), if(isNull(__ai_events_fallback.properties.`$ai_trace_id`), NULL, if(and(in(ascii(toString(__ai_events_fallback.properties.`$ai_trace_id`)), tuple(91, 123)), in(ascii(toJSONString(__ai_events_fallback.properties.`$ai_trace_id`)), tuple(91, 123))), toJSONString(__ai_events_fallback.properties.`$ai_trace_id`), toString(__ai_events_fallback.properties.`$ai_trace_id`)))) AS trace_id
+ FROM events_json AS __ai_events_fallback
+ WHERE and(equals(__ai_events_fallback.team_id, 99999), in(__ai_events_fallback.event, tuple('$ai_trace', '$ai_span', '$ai_generation', '$ai_embedding')), in(if(notEquals(toJSONString(__ai_events_fallback.properties.^`$ai_trace_id`), '{}'), toJSONString(__ai_events_fallback.properties.^`$ai_trace_id`), if(isNull(__ai_events_fallback.properties.`$ai_trace_id`), NULL, if(and(in(ascii(toString(__ai_events_fallback.properties.`$ai_trace_id`)), tuple(91, 123)), in(ascii(toJSONString(__ai_events_fallback.properties.`$ai_trace_id`)), tuple(91, 123))), toJSONString(__ai_events_fallback.properties.`$ai_trace_id`), toString(__ai_events_fallback.properties.`$ai_trace_id`)))), ['missing', 'other-trace']), greaterOrEquals(__ai_events_fallback.timestamp, toDateTime64('2025-01-09 23:50:00.000000', 6, 'UTC')), lessOrEquals(__ai_events_fallback.timestamp, toDateTime64('2026-09-09 10:00:00.000000', 6, 'UTC')))
+ LIMIT 2 SETTINGS readonly=2,
+ max_execution_time=2,
+ timeout_before_checking_execution_speed=0,
+ timeout_overflow_mode='break',
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0,
+ json_type_escape_dots_in_keys=1,
+ output_format_json_escape_forward_slashes=0
+ '''
+# ---
+# name: TestTraceViewSet.test_availability_reads_both_tables_with_a_read_key_and_stays_in_the_project[new_events_schema]
+ '''
+ /* user_id:0 request:_snapshot_ */
+ SELECT DISTINCT if(notEquals(toJSONString(__ai_events_fallback.properties.^`$ai_trace_id`), '{}'), toJSONString(__ai_events_fallback.properties.^`$ai_trace_id`), if(isNull(__ai_events_fallback.properties.`$ai_trace_id`), NULL, if(and(in(ascii(toString(__ai_events_fallback.properties.`$ai_trace_id`)), tuple(91, 123)), in(ascii(toJSONString(__ai_events_fallback.properties.`$ai_trace_id`)), tuple(91, 123))), toJSONString(__ai_events_fallback.properties.`$ai_trace_id`), toString(__ai_events_fallback.properties.`$ai_trace_id`)))) AS trace_id
+ FROM events_json AS __ai_events_fallback
+ WHERE and(equals(__ai_events_fallback.team_id, 99999), in(__ai_events_fallback.event, tuple('$ai_trace', '$ai_span', '$ai_generation', '$ai_embedding')), in(if(notEquals(toJSONString(__ai_events_fallback.properties.^`$ai_trace_id`), '{}'), toJSONString(__ai_events_fallback.properties.^`$ai_trace_id`), if(isNull(__ai_events_fallback.properties.`$ai_trace_id`), NULL, if(and(in(ascii(toString(__ai_events_fallback.properties.`$ai_trace_id`)), tuple(91, 123)), in(ascii(toJSONString(__ai_events_fallback.properties.`$ai_trace_id`)), tuple(91, 123))), toJSONString(__ai_events_fallback.properties.`$ai_trace_id`), toString(__ai_events_fallback.properties.`$ai_trace_id`)))), ['evaluator/trace']), greaterOrEquals(__ai_events_fallback.timestamp, toDateTime64('2025-01-09 23:50:00.000000', 6, 'UTC')), lessOrEquals(__ai_events_fallback.timestamp, toDateTime64('2026-09-09 10:00:00.000000', 6, 'UTC')))
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=2,
+ timeout_before_checking_execution_speed=0,
+ timeout_overflow_mode='break',
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0,
+ json_type_escape_dots_in_keys=1,
+ output_format_json_escape_forward_slashes=0
+ '''
+# ---
diff --git a/products/ai_observability/backend/tests/test_trace_views.py b/products/ai_observability/backend/tests/test_trace_views.py
index 83aae6acca52..cc578fa69b49 100644
--- a/products/ai_observability/backend/tests/test_trace_views.py
+++ b/products/ai_observability/backend/tests/test_trace_views.py
@@ -1,9 +1,11 @@
import base64
from datetime import UTC, datetime, timedelta
from decimal import Decimal
+from types import SimpleNamespace
from typing import TYPE_CHECKING, Any
from urllib.parse import urlencode
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import ANY, AsyncMock, MagicMock, patch
@@ -148,6 +150,90 @@ class TestTraceViewSet(ClickhouseTestMixin, APIBaseTest):
def _url(self, segment: str) -> str:
return f"/api/projects/{self.team.id}/ai_observability/traces/{segment}/"
+ @time_machine.travel(T0 + timedelta(days=1), tick=False)
+ def test_availability_reads_both_tables_with_a_read_key_and_stays_in_the_project(self) -> None:
+ _create_trace(self.team, "application,trace")
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ bulk_create_events(
+ [
+ {
+ "event": "$ai_generation",
+ "event_uuid": event_id,
+ "distinct_id": "user-1",
+ "team": team,
+ "timestamp": T0,
+ "properties": {"$ai_trace_id": trace_id},
+ }
+ for event_id, team, trace_id in [
+ (GENERATION, self.team, "evaluator/trace"),
+ (TRACE_EVENT, other_team, "other-trace"),
+ ]
+ ]
+ )
+ key = self.create_personal_api_key_with_scopes(["llm_analytics:read"])
+ self.client.logout()
+ headers = {"authorization": f"Bearer {key}"}
+
+ with self.capture_select_queries() as queries:
+ response = self.client.post(
+ self._url("availability"),
+ {"trace_ids": ["application,trace", "evaluator/trace"]},
+ format="json",
+ headers=headers,
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {"available_trace_ids": ["application,trace", "evaluator/trace"]}
+ probes = [query for query in queries if "FROM system.columns" not in query]
+ assert len(probes) == 2
+ for query in probes:
+ self.assertQueryMatchesSnapshot(query)
+
+ with self.capture_select_queries() as queries:
+ response = self.client.post(
+ self._url("availability"),
+ {"trace_ids": ["missing", "other-trace"]},
+ format="json",
+ headers=headers,
+ )
+ assert response.status_code == 200
+ assert response.json() == {"available_trace_ids": []}
+ probes = [query for query in queries if "FROM system.columns" not in query]
+ assert len(probes) == 2
+ for query in probes:
+ self.assertQueryMatchesSnapshot(query)
+
+ with self.capture_select_queries() as queries:
+ response = self.client.post(
+ self._url("availability"),
+ {"trace_ids": ["application,trace", "application,trace"]},
+ format="json",
+ headers=headers,
+ )
+ assert response.status_code == 200
+ assert response.json() == {"available_trace_ids": ["application,trace"]}
+ assert len([query for query in queries if "FROM system.columns" not in query]) == 1
+
+ def test_availability_rejects_more_than_two_traces(self) -> None:
+ response = self.client.post(self._url("availability"), {"trace_ids": ["one", "two", "three"]}, format="json")
+
+ assert response.status_code == 400
+
+ def test_availability_preserves_known_traces_when_the_fallback_times_out(self) -> None:
+ with patch.object(
+ trace_queries,
+ "execute_hogql_query",
+ side_effect=[SimpleNamespace(results=[["application,trace"]]), ClickHouseQueryTimeOut()],
+ ):
+ response = self.client.post(
+ self._url("availability"),
+ {"trace_ids": ["application,trace", "evaluator/trace"]},
+ format="json",
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {"available_trace_ids": ["application,trace"]}
+
@parameterized.expand([("plain id", "trace-1"), ("id with a dot", "run.42"), ("id with a slash", "a/b")])
def test_returns_the_trace_in_camel_case(self, _name: str, trace_id: str) -> None:
_create_trace(self.team, trace_id)
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index 1a08c44a1303..cf34d216fc68 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -1898,6 +1898,21 @@ export interface TraceSummaryRequestApi {
regenerate?: boolean
}
+export interface TraceAvailabilityRequestApi {
+ /**
+ * Application and evaluator trace IDs to check without loading trace contents.
+ * @minItems 1
+ * @maxItems 2
+ * @items.maxLength 255
+ */
+ trace_ids: string[]
+}
+
+export interface TraceAvailabilityApi {
+ /** Requested trace IDs readable from AI events or the shared events table. */
+ available_trace_ids: string[]
+}
+
export type DatasetJSONValueApi = { [key: string]: unknown } | unknown[] | string | number | boolean
/**
diff --git a/products/ai_observability/frontend/generated/api.ts b/products/ai_observability/frontend/generated/api.ts
index 3fab63139cb7..d67d25f53b0b 100644
--- a/products/ai_observability/frontend/generated/api.ts
+++ b/products/ai_observability/frontend/generated/api.ts
@@ -155,6 +155,8 @@ import type {
TextReprRequestApi,
TextReprResponseApi,
TraceApi,
+ TraceAvailabilityApi,
+ TraceAvailabilityRequestApi,
TraceClustersApi,
TraceEvaluationResultsApi,
TraceExportApi,
@@ -1051,6 +1053,23 @@ export const aiObservabilityTracesSummaryCreate = async (
})
}
+export const getAiObservabilityTracesAvailabilityCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/ai_observability/traces/availability/`
+}
+
+export const aiObservabilityTracesAvailabilityCreate = async (
+ projectId: string,
+ traceAvailabilityRequestApi: TraceAvailabilityRequestApi,
+ options?: RequestInit
+): Promise<TraceAvailabilityApi> => {
+ return apiMutator<TraceAvailabilityApi>(getAiObservabilityTracesAvailabilityCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(traceAvailabilityRequestApi),
+ })
+}
+
export const getDatasetItemsListUrl = (projectId: string, params: DatasetItemsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.ts
index fc02f820d837..bd7f12c5eb8f 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -334,6 +334,18 @@ export const AiObservabilityTracesSummaryCreateBody = /* @__PURE__ */ zod.object
.describe('Replace a ready summary with a new one. A pending summary is never replaced.'),
})
+export const aiObservabilityTracesAvailabilityCreateBodyTraceIdsItemMax = 255
+
+export const aiObservabilityTracesAvailabilityCreateBodyTraceIdsMax = 2
+
+export const AiObservabilityTracesAvailabilityCreateBody = /* @__PURE__ */ zod.object({
+ trace_ids: zod
+ .array(zod.string().max(aiObservabilityTracesAvailabilityCreateBodyTraceIdsItemMax))
+ .min(1)
+ .max(aiObservabilityTracesAvailabilityCreateBodyTraceIdsMax)
+ .describe('Application and evaluator trace IDs to check without loading trace contents.'),
+})
+
/**
* Create an item and its first immutable version. An identical client item ID retry returns the existing item. A different payload or an archived match returns a conflict.
*/
diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineExperimentContent.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineExperimentContent.tsx
index e343266c8038..a71f4eaea087 100644
--- a/products/ai_observability/frontend/offline-evaluations/OfflineExperimentContent.tsx
+++ b/products/ai_observability/frontend/offline-evaluations/OfflineExperimentContent.tsx
@@ -11,6 +11,7 @@ import { urls } from 'scenes/urls'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
import type { OfflineScorerSummaryApi } from '../generated/api.schemas'
+import { TraceDrawerHost } from '../redesign/trace/TraceDrawerHost'
import { ScorerLabel } from '../scoreDefinitions/ScorerLabel'
import { OfflineExperimentLogicProps, offlineExperimentLogic } from './offlineExperimentLogic'
import { OfflineExperimentStatus } from './OfflineExperimentStatus'
@@ -215,6 +216,7 @@ export function OfflineExperimentContent(props: OfflineExperimentLogicProps): JS
</details>
</section>
<OfflineItemMatrix {...props} />
+ <TraceDrawerHost listId="offline-experiment" />
{inspector && (
<OfflineItemInspector
key={`${inspector.itemId}:${cellEpoch}`}
diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.test.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.test.tsx
index 6ded351f14c7..fc283228ba4d 100644
--- a/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.test.tsx
+++ b/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.test.tsx
@@ -1,17 +1,23 @@
import '@testing-library/jest-dom'
-import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { router } from 'kea-router'
import { ApiError } from 'lib/api-error'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { urls } from 'scenes/urls'
import { initKeaTests } from '~/test/init'
import * as api from '../generated/api'
import type { OfflineResultReadApi } from '../generated/api.schemas'
+import { traceDrawerLogic } from '../redesign/trace/traceDrawerLogic'
import { detailExperiment, detailItems, offlineDetailItemResults } from './offlineDetailFixtures'
import { OfflineItemInspector } from './OfflineItemInspector'
jest.mock('../generated/api', () => ({
+ aiObservabilityTracesAvailabilityCreate: jest.fn(),
aiObservabilityOfflineExperimentsItemsRetrieve: jest.fn(),
aiObservabilityOfflineExperimentsItemsPayloadRetrieve: jest.fn(),
aiObservabilityOfflineExperimentsItemsResultsList: jest.fn(),
@@ -22,6 +28,7 @@ describe('OfflineItemInspector', () => {
afterEach(cleanup)
beforeEach(() => {
initKeaTests()
+ localStorage.clear()
jest.clearAllMocks()
jest.mocked(api.aiObservabilityOfflineExperimentsItemsRetrieve).mockReset()
jest.mocked(api.aiObservabilityOfflineExperimentsItemsPayloadRetrieve).mockReset()
@@ -29,6 +36,85 @@ describe('OfflineItemInspector', () => {
jest.mocked(api.aiObservabilityOfflineExperimentsResultsPayloadRetrieve).mockReset()
})
+ it.each(['Application trace', 'Evaluator trace'])(
+ 'opens %s in the drawer and restores the selected result when closed',
+ async (label) => {
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.AI_OBSERVABILITY_TRACE_REDESIGN], {
+ [FEATURE_FLAGS.AI_OBSERVABILITY_TRACE_REDESIGN]: true,
+ })
+ const result = { ...offlineDetailItemResults(detailItems[0].id)[0], evaluator_trace_id: 'judge-trace' }
+ const item = { ...detailItems[0], application_trace_id: 'app-trace' }
+ const path = `/project/997${urls.aiObservabilityOfflineEvaluationExperiment(detailExperiment.id)}`
+ const selection = { item_id: item.id, result_id: result.id, scorer_version_id: result.scorer.id }
+ router.actions.push(path, selection)
+ jest.mocked(api.aiObservabilityOfflineExperimentsItemsRetrieve).mockResolvedValue(item)
+ jest.mocked(api.aiObservabilityOfflineExperimentsItemsPayloadRetrieve).mockResolvedValue({
+ id: item.id,
+ payload_state: 'not_provided',
+ payload_expires_at: null,
+ available: false,
+ data: null,
+ })
+ jest.mocked(api.aiObservabilityOfflineExperimentsItemsResultsList).mockResolvedValue({
+ count: 1,
+ next: null,
+ previous: null,
+ next_cursor: null,
+ results: [result],
+ })
+ jest.mocked(api.aiObservabilityOfflineExperimentsResultsPayloadRetrieve).mockResolvedValue({
+ id: result.id,
+ payload_state: 'available',
+ payload_expires_at: null,
+ available: true,
+ data: { reasoning: 'The answer matches the reference.' },
+ })
+ const onClose = jest.fn()
+ let confirmTraces!: (response: { available_trace_ids: string[] }) => void
+ jest.mocked(api.aiObservabilityTracesAvailabilityCreate).mockReturnValue(
+ new Promise((resolve) => {
+ confirmTraces = resolve
+ })
+ )
+ render(
+ <OfflineItemInspector
+ teamId={997}
+ experimentId={detailExperiment.id}
+ itemId={item.id}
+ resultId={result.id}
+ scorerVersionId={result.scorer.id}
+ onClose={onClose}
+ onSelectResult={jest.fn()}
+ />
+ )
+ await screen.findByText('The answer matches the reference.')
+ expect(screen.queryByText('Application trace', { selector: 'a *' })).not.toBeInTheDocument()
+ expect(screen.queryByText('Evaluator trace', { selector: 'a *' })).not.toBeInTheDocument()
+ await act(async () => confirmTraces({ available_trace_ids: ['app-trace', 'judge-trace'] }))
+ const link = (await screen.findByText(label, { selector: 'a *' })).closest('a')!
+ expect(screen.getByText('Result metadata').closest('details')).not.toHaveAttribute('open')
+ const traceId = label === 'Application trace' ? 'app-trace' : 'judge-trace'
+ expect(link).toHaveAttribute('href', `/project/997${urls.aiObservabilityTrace(traceId)}`)
+ const drawer = traceDrawerLogic({ listId: 'offline-experiment' })
+
+ fireEvent.click(link, { ctrlKey: true })
+ expect(drawer.values.openTraceId).toBeNull()
+ fireEvent.click(link)
+
+ expect(drawer.values.openTraceId).toBe(traceId)
+ expect(router.values.location.pathname).toBe(path)
+ expect(router.values.searchParams).toMatchObject(selection)
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(onClose).not.toHaveBeenCalled()
+
+ act(() => drawer.actions.close())
+ expect(await screen.findByRole('dialog')).toBeInTheDocument()
+ expect(screen.getByText('The answer matches the reference.')).toBeInTheDocument()
+ expect(router.values.searchParams).toEqual(selection)
+ }
+ )
+
it('displays the stored evaluator error message for the selected result', async () => {
const result: OfflineResultReadApi = {
...offlineDetailItemResults(detailItems[0].id)[0],
diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.tsx
index bd35b3df7f09..79dc059b554b 100644
--- a/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.tsx
+++ b/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.tsx
@@ -1,12 +1,15 @@
import { useActions, useValues } from 'kea'
+import type { MouseEvent } from 'react'
-import { LemonBanner, LemonButton, LemonCard, LemonModal, LemonSkeleton, LemonTable, Link } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonCard, LemonModal, LemonSkeleton, LemonTable } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonModalContent, LemonModalFooter, LemonModalHeader } from 'lib/lemon-ui/LemonModal/LemonModal'
import { urls } from 'scenes/urls'
import type { OfflineResultReadApi } from '../generated/api.schemas'
+import { traceDrawerLogic } from '../redesign/trace/traceDrawerLogic'
+import { opensTraceDrawer } from '../redesign/trace/traceDrawerRows'
import { ScorerLabel } from '../scoreDefinitions/ScorerLabel'
import { OfflineItemInspectorLogicProps, offlineItemInspectorLogic } from './offlineItemInspectorLogic'
import { OfflinePayload } from './OfflinePayload'
@@ -22,7 +25,17 @@ export function OfflineItemInspector({
onSelectResult: (result: OfflineResultReadApi) => void
}): JSX.Element {
const logic = offlineItemInspectorLogic(props)
+ const drawerLogic = traceDrawerLogic({ listId: 'offline-experiment' })
+ const { isEnabled, openTraceId } = useValues(drawerLogic)
+ const { openRow } = useActions(drawerLogic)
+ const openTrace = (event: MouseEvent<HTMLElement>, traceId: string): void => {
+ if (isEnabled && opensTraceDrawer(event, 'a', false)) {
+ event.preventDefault()
+ openRow({ traceId, timestamp: null, stepId: null })
+ }
+ }
const {
+ availableTraceIds,
item,
itemLoading,
itemError,
@@ -50,7 +63,7 @@ export function OfflineItemInspector({
loadOfflineResultPayload,
} = useActions(logic)
return (
- <LemonModal isOpen onClose={onClose} width="64rem" simple>
+ <LemonModal isOpen={!isEnabled || !openTraceId} onClose={onClose} width="64rem" simple>
<LemonModalHeader>
<h3 className="break-words pr-8">
{item?.case_key || item?.dataset_item_identifier || 'Experiment item'}
@@ -72,13 +85,16 @@ export function OfflineItemInspector({
</span>
{item.trial && <span>{`Trial ${item.trial}`}</span>}
{item.model_version && <span>{`Model: ${item.model_version}`}</span>}
- {item.application_trace_id && (
- <Link
+ {item.application_trace_id && availableTraceIds.includes(item.application_trace_id) && (
+ <LemonButton
+ type="secondary"
+ size="xsmall"
to={urls.aiObservabilityTrace(item.application_trace_id)}
+ onClick={(event) => openTrace(event, item.application_trace_id!)}
data-attr="offline-item-application-trace"
>
Application trace
- </Link>
+ </LemonButton>
)}
</div>
)
@@ -106,10 +122,30 @@ export function OfflineItemInspector({
</div>
<span className="text-xs text-muted">{`Version ${selectedResult.scorer.version}`}</span>
</div>
- <OfflineResultTag
- result={selectedResult}
- scorer={selectedResult.scorer}
- />
+ <div className="flex flex-wrap items-center gap-2">
+ {selectedResult.evaluator_trace_id &&
+ availableTraceIds.includes(
+ selectedResult.evaluator_trace_id
+ ) && (
+ <LemonButton
+ type="secondary"
+ size="xsmall"
+ to={urls.aiObservabilityTrace(
+ selectedResult.evaluator_trace_id
+ )}
+ onClick={(event) =>
+ openTrace(event, selectedResult.evaluator_trace_id!)
+ }
+ data-attr="offline-result-evaluator-trace"
+ >
+ Evaluator trace
+ </LemonButton>
+ )}
+ <OfflineResultTag
+ result={selectedResult}
+ scorer={selectedResult.scorer}
+ />
+ </div>
</div>
{offlineScorePassingRuleLabel(selectedResult.scorer) && (
<p className="text-xs text-muted mb-0">
@@ -136,16 +172,6 @@ export function OfflineItemInspector({
<span>Accepted</span>
<TZLabel time={selectedResult.accepted_at} />
</span>
- {selectedResult.evaluator_trace_id && (
- <Link
- to={urls.aiObservabilityTrace(
- selectedResult.evaluator_trace_id
- )}
- data-attr="offline-result-evaluator-trace"
- >
- Evaluator trace
- </Link>
- )}
</div>
</details>
</LemonCard>
diff --git a/products/ai_observability/frontend/offline-evaluations/offlineItemInspectorLogic.test.ts b/products/ai_observability/frontend/offline-evaluations/offlineItemInspectorLogic.test.ts
index 3573479b773c..8b9e7c82a3cf 100644
--- a/products/ai_observability/frontend/offline-evaluations/offlineItemInspectorLogic.test.ts
+++ b/products/ai_observability/frontend/offline-evaluations/offlineItemInspectorLogic.test.ts
@@ -1,3 +1,4 @@
+import { waitFor } from '@testing-library/react'
import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
@@ -7,6 +8,7 @@ import { detailExperiment, detailItems, offlineDetailItemResults } from './offli
import { offlineItemInspectorLogic } from './offlineItemInspectorLogic'
jest.mock('../generated/api', () => ({
+ aiObservabilityTracesAvailabilityCreate: jest.fn(),
aiObservabilityOfflineExperimentsItemsRetrieve: jest.fn(),
aiObservabilityOfflineExperimentsItemsPayloadRetrieve: jest.fn(),
aiObservabilityOfflineExperimentsItemsResultsList: jest.fn(),
@@ -17,6 +19,7 @@ describe('offlineItemInspectorLogic', () => {
beforeEach(() => {
initKeaTests()
jest.resetAllMocks()
+ jest.mocked(api.aiObservabilityTracesAvailabilityCreate).mockResolvedValue({ available_trace_ids: [] })
jest.mocked(api.aiObservabilityOfflineExperimentsItemsRetrieve).mockResolvedValue(detailItems[0])
jest.mocked(api.aiObservabilityOfflineExperimentsItemsPayloadRetrieve).mockResolvedValue({
id: detailItems[0].id,
@@ -89,5 +92,151 @@ describe('offlineItemInspectorLogic', () => {
await expectLogic(logic).toFinishAllListeners()
expect(api.aiObservabilityOfflineExperimentsResultsPayloadRetrieve).not.toHaveBeenCalled()
expect(logic.values.selectedResult).toBeNull()
+ expect(api.aiObservabilityTracesAvailabilityCreate).not.toHaveBeenCalled()
+ })
+
+ it.each([{ found: ['app-trace'] }, { found: [] }, { found: null }])(
+ 'shows only confirmed trace IDs: $found',
+ async ({ found }) => {
+ const selected = { ...offlineDetailItemResults(detailItems[0].id)[0], evaluator_trace_id: 'judge-trace' }
+ jest.mocked(api.aiObservabilityOfflineExperimentsItemsRetrieve).mockResolvedValue({
+ ...detailItems[0],
+ application_trace_id: 'app-trace',
+ })
+ jest.mocked(api.aiObservabilityOfflineExperimentsItemsResultsList).mockResolvedValue({
+ count: 1,
+ next: null,
+ previous: null,
+ next_cursor: null,
+ results: [selected],
+ })
+ if (found === null) {
+ jest.mocked(api.aiObservabilityTracesAvailabilityCreate).mockRejectedValue(
+ new Error('Query unavailable')
+ )
+ } else {
+ jest.mocked(api.aiObservabilityTracesAvailabilityCreate).mockResolvedValue({
+ available_trace_ids: found,
+ })
+ }
+ const logic = offlineItemInspectorLogic({
+ teamId: 997,
+ experimentId: detailExperiment.id,
+ itemId: detailItems[0].id,
+ resultId: selected.id,
+ scorerVersionId: selected.scorer.id,
+ })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.availableTraceIds).toEqual(found ?? [])
+ expect(api.aiObservabilityTracesAvailabilityCreate).toHaveBeenCalledTimes(1)
+ expect(api.aiObservabilityTracesAvailabilityCreate).toHaveBeenCalledWith(
+ '997',
+ { trace_ids: ['app-trace', 'judge-trace'] },
+ { signal: expect.any(AbortSignal) }
+ )
+ expect(logic.values.item?.id).toBe(detailItems[0].id)
+ expect(logic.values.selectedResult?.id).toBe(selected.id)
+ jest.mocked(api.aiObservabilityTracesAvailabilityCreate).mockRejectedValue(new Error('Query unavailable'))
+ logic.actions.refreshItem()
+ expect(logic.values.availableTraceIds).toEqual([])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.availableTraceIds).toEqual([])
+ }
+ )
+
+ it('cancels superseded lookups, ignores their responses, and cancels on close', async () => {
+ const results = offlineDetailItemResults(detailItems[0].id)
+ .slice(0, 2)
+ .map((result, index) => ({
+ ...result,
+ evaluator_trace_id: `judge-${index}`,
+ }))
+ jest.mocked(api.aiObservabilityOfflineExperimentsItemsRetrieve).mockResolvedValue({
+ ...detailItems[0],
+ application_trace_id: 'app-trace',
+ })
+ jest.mocked(api.aiObservabilityOfflineExperimentsItemsResultsList).mockResolvedValue({
+ count: results.length,
+ next: null,
+ previous: null,
+ next_cursor: null,
+ results,
+ })
+ const requests: {
+ signal: AbortSignal
+ resolve: (response: { available_trace_ids: string[] }) => void
+ }[] = []
+ jest.mocked(api.aiObservabilityTracesAvailabilityCreate).mockImplementation(
+ (_team, _body, options) => new Promise((resolve) => requests.push({ signal: options!.signal!, resolve }))
+ )
+ const props = {
+ teamId: 997,
+ experimentId: detailExperiment.id,
+ itemId: detailItems[0].id,
+ resultId: results[0].id,
+ scorerVersionId: results[0].scorer.id,
+ }
+ const logic = offlineItemInspectorLogic(props)
+ const unmount = logic.mount()
+ await waitFor(() => expect(requests).toHaveLength(1))
+
+ offlineItemInspectorLogic({ ...props, resultId: results[1].id, scorerVersionId: results[1].scorer.id })
+ expect(requests[0].signal.aborted).toBe(true)
+ await waitFor(() => expect(requests).toHaveLength(2))
+ requests[1].resolve({ available_trace_ids: ['app-trace', 'judge-1'] })
+ await waitFor(() => expect(logic.values.availableTraceIds).toEqual(['app-trace', 'judge-1']))
+ requests[0].resolve({ available_trace_ids: ['app-trace', 'judge-0'] })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.availableTraceIds).toEqual(['app-trace', 'judge-1'])
+
+ logic.actions.loadOfflineItemResults()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(requests).toHaveLength(2)
+
+ logic.actions.refreshItem()
+ expect(logic.values.availableTraceIds).toEqual([])
+ await waitFor(() => expect(requests).toHaveLength(3))
+ unmount()
+ expect(requests[2].signal.aborted).toBe(true)
+ requests[2].resolve({ available_trace_ids: ['app-trace', 'judge-1'] })
+ })
+
+ it('does not reuse the previous evaluator trace when the new result fails to load', async () => {
+ const selected = { ...offlineDetailItemResults(detailItems[0].id)[0], evaluator_trace_id: 'old-judge' }
+ jest.mocked(api.aiObservabilityOfflineExperimentsItemsRetrieve).mockResolvedValue({
+ ...detailItems[0],
+ application_trace_id: 'app-trace',
+ })
+ jest.mocked(api.aiObservabilityOfflineExperimentsItemsResultsList).mockResolvedValue({
+ count: 1,
+ next: null,
+ previous: null,
+ next_cursor: null,
+ results: [selected],
+ })
+ jest.mocked(api.aiObservabilityTracesAvailabilityCreate).mockImplementation(async (_team, body) => ({
+ available_trace_ids: body.trace_ids,
+ }))
+ const props = {
+ teamId: 997,
+ experimentId: detailExperiment.id,
+ itemId: detailItems[0].id,
+ resultId: selected.id,
+ scorerVersionId: selected.scorer.id,
+ }
+ const logic = offlineItemInspectorLogic(props)
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.availableTraceIds).toEqual(['app-trace', 'old-judge'])
+
+ jest.mocked(api.aiObservabilityOfflineExperimentsItemsResultsList).mockRejectedValueOnce(
+ new Error('Unavailable')
+ )
+ offlineItemInspectorLogic({ ...props, resultId: 'missing-result' })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.selectedResult).toBeNull()
+ expect(logic.values.availableTraceIds).toEqual(['app-trace'])
})
})
diff --git a/products/ai_observability/frontend/offline-evaluations/offlineItemInspectorLogic.ts b/products/ai_observability/frontend/offline-evaluations/offlineItemInspectorLogic.ts
index 90cc167ef4dc..1a047adab267 100644
--- a/products/ai_observability/frontend/offline-evaluations/offlineItemInspectorLogic.ts
+++ b/products/ai_observability/frontend/offline-evaluations/offlineItemInspectorLogic.ts
@@ -13,6 +13,7 @@ import {
selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
+import { subscriptions } from 'kea-subscriptions'
import * as api from '../generated/api'
import type {
@@ -35,6 +36,8 @@ export interface OfflineItemInspectorLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface offlineItemInspectorLogicValues {
+ availableTraceIds: string[]
+ availableTraceIdsLoading: boolean
item: OfflineItemReadApi | null
itemError: string | null
itemLoading: boolean
@@ -52,6 +55,7 @@ export interface offlineItemInspectorLogicValues {
selectedResult: OfflineResultReadApi | null
selectedResultError: string | null
selectedResultLoading: boolean
+ traceIdsToCheck: string[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -131,6 +135,21 @@ export interface offlineItemInspectorLogicActions {
selectedResult: OfflineResultReadApi | null
payload?: void
}
+ loadTraceAvailability: (traceIds: string[]) => string[]
+ loadTraceAvailabilityFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadTraceAvailabilitySuccess: (
+ availableTraceIds: string[],
+ payload?: string[]
+ ) => {
+ availableTraceIds: string[]
+ payload?: string[]
+ }
nextResults: (cursor: string) => {
cursor: string
}
@@ -146,6 +165,12 @@ export interface offlineItemInspectorLogicActions {
export interface offlineItemInspectorLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ traceIdsToCheck: (
+ item: OfflineItemReadApi | null,
+ itemLoading: boolean,
+ selectedResult: OfflineResultReadApi | null,
+ selectedResultLoading: boolean
+ ) => string[]
resultCursor: (resultCursors: string[]) => string | null
}
}
@@ -167,7 +192,34 @@ export const offlineItemInspectorLogic: LogicWrapper<offlineItemInspectorLogicTy
nextResults: (cursor: string) => ({ cursor }),
previousResults: true,
}),
- loaders(({ props, values }) => ({
+ loaders(({ props, values, cache }) => ({
+ availableTraceIds: [
+ [] as string[],
+ {
+ loadTraceAvailability: async (traceIds: string[], breakpoint): Promise<string[]> => {
+ cache.disposables.dispose('traceAvailability')
+ if (!traceIds.length) {
+ return []
+ }
+ const controller = new AbortController()
+ cache.disposables.add(() => () => controller.abort(), 'traceAvailability', {
+ pauseOnPageHidden: false,
+ })
+ try {
+ const response = await api.aiObservabilityTracesAvailabilityCreate(
+ String(props.teamId),
+ { trace_ids: traceIds },
+ { signal: controller.signal }
+ )
+ breakpoint()
+ return response.available_trace_ids
+ } catch {
+ breakpoint()
+ return []
+ }
+ },
+ },
+ ],
item: [
null as OfflineItemReadApi | null,
{
@@ -273,6 +325,12 @@ export const offlineItemInspectorLogic: LogicWrapper<offlineItemInspectorLogicTy
],
})),
reducers({
+ availableTraceIds: {
+ loadTraceAvailability: () => [],
+ },
+ selectedResult: {
+ loadOfflineSelectedResult: () => null,
+ },
resultCursors: [
[] as string[],
{
@@ -324,6 +382,28 @@ export const offlineItemInspectorLogic: LogicWrapper<offlineItemInspectorLogicTy
],
}),
selectors({
+ traceIdsToCheck: [
+ (s) => [s.item, s.itemLoading, s.selectedResult, s.selectedResultLoading],
+ (
+ item: OfflineItemReadApi | null,
+ itemLoading: boolean,
+ selectedResult: OfflineResultReadApi | null,
+ selectedResultLoading: boolean
+ ): string[] =>
+ !item || itemLoading || selectedResultLoading
+ ? []
+ : [
+ ...new Set(
+ [item.application_trace_id, selectedResult?.evaluator_trace_id].filter(
+ (id): id is string => !!id
+ )
+ ),
+ ],
+ {
+ resultEqualityCheck: (a: string[], b: string[]) =>
+ a.length === b.length && a.every((id, index) => id === b[index]),
+ },
+ ],
resultCursor: [
(s) => [s.resultCursors],
(cursors: string[]): string | null => cursors[cursors.length - 1] || null,
@@ -340,6 +420,9 @@ export const offlineItemInspectorLogic: LogicWrapper<offlineItemInspectorLogicTy
previousResults: () => actions.loadOfflineItemResults(),
loadOfflineSelectedResultSuccess: () => actions.loadOfflineResultPayload(),
})),
+ subscriptions(({ actions }) => ({
+ traceIdsToCheck: (traceIds: string[]) => actions.loadTraceAvailability(traceIds),
+ })),
propsChanged(({ actions, props }, oldProps) => {
if (props.resultId !== oldProps.resultId || props.scorerVersionId !== oldProps.scorerVersionId) {
actions.loadOfflineSelectedResult()
diff --git a/products/ai_observability/frontend/redesign/trace/TraceDrawerHost.tsx b/products/ai_observability/frontend/redesign/trace/TraceDrawerHost.tsx
index 8f299a40b8f0..4b169ba4ec65 100644
--- a/products/ai_observability/frontend/redesign/trace/TraceDrawerHost.tsx
+++ b/products/ai_observability/frontend/redesign/trace/TraceDrawerHost.tsx
@@ -11,7 +11,7 @@ import { DetailPanel, isDetailPanelFullWidth } from '../shared/components/Detail
import { TraceViewContainer } from './adapter/TraceViewContainer'
import { TraceDrawerToolbar } from './components/TraceDrawerToolbar'
import { isOverlayOpen } from './shouldCloseOnEscape'
-import type { TraceDrawerListId } from './traceDrawerLists'
+import { TRACE_DRAWER_LISTS, TraceDrawerListId } from './traceDrawerLists'
import { TraceStepDirection, traceDrawerLogic } from './traceDrawerLogic'
export interface TraceDrawerHostProps {
@@ -22,6 +22,7 @@ export function TraceDrawerHost({ listId }: TraceDrawerHostProps): JSX.Element |
const logic = traceDrawerLogic({ listId })
const { hostId, isEnabled, openRef, position, previousTrace, nextTrace, fullPageHref } = useValues(logic)
const { stepTo, close } = useActions(logic)
+ const showNavigation = TRACE_DRAWER_LISTS[listId].showNavigation !== false
const { mainContentRect } = useValues(panelLayoutLogic)
const containerRef = useRef<HTMLDivElement>(null)
@@ -71,6 +72,7 @@ export function TraceDrawerHost({ listId }: TraceDrawerHostProps): JSX.Element |
resizer={isDetailPanelFullWidth(mainContentRect.width) ? null : <Resizer {...resizerProps} />}
toolbar={
<TraceDrawerToolbar
+ showNavigation={showNavigation}
position={position}
onPrevious={previousTrace ? () => stepTo('previous') : null}
onNext={nextTrace ? () => stepTo('next') : null}
diff --git a/products/ai_observability/frontend/redesign/trace/components/TraceDrawerToolbar.stories.tsx b/products/ai_observability/frontend/redesign/trace/components/TraceDrawerToolbar.stories.tsx
index 90a620b685b3..ca9d3ce28d41 100644
--- a/products/ai_observability/frontend/redesign/trace/components/TraceDrawerToolbar.stories.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/TraceDrawerToolbar.stories.tsx
@@ -23,4 +23,7 @@ type Story = StoryObj<typeof TraceDrawerToolbar>
export const Default: Story = {}
export const FirstTrace: Story = { args: { position: { index: 0, total: 12 }, onPrevious: null } }
export const NotInList: Story = { args: { position: null, onPrevious: null, onNext: null } }
+export const SingleTrace: Story = {
+ args: { showNavigation: false, position: null, onPrevious: null, onNext: null },
+}
export const Narrow: Story = { decorators: [withWidth(480)] }
diff --git a/products/ai_observability/frontend/redesign/trace/components/TraceDrawerToolbar.tsx b/products/ai_observability/frontend/redesign/trace/components/TraceDrawerToolbar.tsx
index cd2ca69c5e07..4f703a5d1bac 100644
--- a/products/ai_observability/frontend/redesign/trace/components/TraceDrawerToolbar.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/TraceDrawerToolbar.tsx
@@ -6,6 +6,7 @@ import { KeyboardShortcut } from 'lib/lemon-ui/KeyboardShortcut/KeyboardShortcut
import type { TraceDrawerPosition } from '../traceDrawerLogic'
export interface TraceDrawerToolbarProps {
+ showNavigation?: boolean
/** Null when the open trace is not in the list. */
position: TraceDrawerPosition | null
onPrevious: (() => void) | null
@@ -17,6 +18,7 @@ export interface TraceDrawerToolbarProps {
const NOT_IN_LIST_REASON = "This trace isn't in the list"
export function TraceDrawerToolbar({
+ showNavigation = true,
position,
onPrevious,
onNext,
@@ -25,37 +27,45 @@ export function TraceDrawerToolbar({
}: TraceDrawerToolbarProps): JSX.Element {
return (
<div className="flex min-w-0 flex-1 items-center gap-1">
- <LemonButton
- size="small"
- icon={<IconChevronDown className="rotate-180" />}
- tooltip={
- <>
- Previous trace <KeyboardShortcut p />
- </>
- }
- aria-label="Previous trace"
- data-attr="trace-drawer-previous"
- onClick={onPrevious ?? undefined}
- disabledReason={onPrevious ? undefined : position ? 'This is the first trace' : NOT_IN_LIST_REASON}
- />
- <LemonButton
- size="small"
- icon={<IconChevronDown />}
- tooltip={
- <>
- Next trace <KeyboardShortcut n />
- </>
- }
- aria-label="Next trace"
- data-attr="trace-drawer-next"
- onClick={onNext ?? undefined}
- disabledReason={onNext ? undefined : position ? 'This is the last loaded trace' : NOT_IN_LIST_REASON}
- />
- {position ? (
- <span className="ml-1 whitespace-nowrap text-xs text-secondary" aria-live="polite">
- {`${position.index + 1} of ${position.total}`}
- </span>
- ) : null}
+ {showNavigation && (
+ <>
+ <LemonButton
+ size="small"
+ icon={<IconChevronDown className="rotate-180" />}
+ tooltip={
+ <>
+ Previous trace <KeyboardShortcut p />
+ </>
+ }
+ aria-label="Previous trace"
+ data-attr="trace-drawer-previous"
+ onClick={onPrevious ?? undefined}
+ disabledReason={
+ onPrevious ? undefined : position ? 'This is the first trace' : NOT_IN_LIST_REASON
+ }
+ />
+ <LemonButton
+ size="small"
+ icon={<IconChevronDown />}
+ tooltip={
+ <>
+ Next trace <KeyboardShortcut n />
+ </>
+ }
+ aria-label="Next trace"
+ data-attr="trace-drawer-next"
+ onClick={onNext ?? undefined}
+ disabledReason={
+ onNext ? undefined : position ? 'This is the last loaded trace' : NOT_IN_LIST_REASON
+ }
+ />
+ {position ? (
+ <span className="ml-1 whitespace-nowrap text-xs text-secondary" aria-live="polite">
+ {`${position.index + 1} of ${position.total}`}
+ </span>
+ ) : null}
+ </>
+ )}
<div className="ml-auto flex items-center gap-1">
<LemonButton
size="small"
diff --git a/products/ai_observability/frontend/redesign/trace/traceDrawerLists.ts b/products/ai_observability/frontend/redesign/trace/traceDrawerLists.ts
index 012b31274e58..d938dabcde93 100644
--- a/products/ai_observability/frontend/redesign/trace/traceDrawerLists.ts
+++ b/products/ai_observability/frontend/redesign/trace/traceDrawerLists.ts
@@ -9,6 +9,7 @@ export type TraceDrawerListId =
| 'review-queue'
| 'evaluation-runs'
| 'dataset-items'
+ | 'offline-experiment'
| 'cluster-traces'
export interface TraceDrawerListConfig {
@@ -20,6 +21,7 @@ export interface TraceDrawerListConfig {
openingMode?: TraceOpeningMode
detailTab?: NodeDetailTab
rowClick: boolean
+ showNavigation?: boolean
}
export const TRACE_DRAWER_LISTS: Record<TraceDrawerListId, TraceDrawerListConfig> = {
@@ -68,6 +70,13 @@ export const TRACE_DRAWER_LISTS: Record<TraceDrawerListId, TraceDrawerListConfig
backLabel: 'Back to dataset',
rowClick: false,
},
+ 'offline-experiment': {
+ pathMatcher: /^\/ai-evals\/evaluations\/offline\/experiments\/[^/]+$/,
+ backTo: 'offline-experiment',
+ backLabel: 'Back to experiment',
+ rowClick: false,
+ showNavigation: false,
+ },
'cluster-traces': {
pathMatcher: /^\/ai-observability\/clusters\/[^/]+\/[^/]+$/,
backTo: 'cluster',
diff --git a/products/ai_observability/frontend/redesign/trace/traceDrawerLogic.test.ts b/products/ai_observability/frontend/redesign/trace/traceDrawerLogic.test.ts
index 4bcfab16a861..dd0d5301154b 100644
--- a/products/ai_observability/frontend/redesign/trace/traceDrawerLogic.test.ts
+++ b/products/ai_observability/frontend/redesign/trace/traceDrawerLogic.test.ts
@@ -198,6 +198,11 @@ describe('traceDrawerLogic', () => {
it.each<[TraceDrawerListId, string, Record<string, unknown>]>([
['traces', LIST_PATH, { mode: 'spans', detailTab: 'messages', openingMode: null }],
+ [
+ 'offline-experiment',
+ urls.aiObservabilityOfflineEvaluationExperiment('experiment-1'),
+ { mode: 'spans', detailTab: 'messages', openingMode: null },
+ ],
[
'evaluation-runs',
urls.aiObservabilityEvaluation('e1'),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6a61a2ef99d4..2cb0051af0bd 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -113093,6 +113093,21 @@ export namespace Schemas {
git: TraceGit | null;
}
+ export interface TraceAvailability {
+ /** Requested trace IDs readable from AI events or the shared events table. */
+ available_trace_ids: string[];
+ }
+
+ export interface TraceAvailabilityRequest {
+ /**
+ * Application and evaluator trace IDs to check without loading trace contents.
+ * @minItems 1
+ * @maxItems 2
+ * @items.maxLength 255
+ */
+ trace_ids: string[];
+ }
+
export interface TraceChoiceAnswer {
kind: 'choice';
question: string;