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(aio): cut the instrumentation checklist wait (#93210)

Carlos Marchal410d55ea5927
diff --git a/products/ai_observability/backend/api/instrumentation_checklist.py b/products/ai_observability/backend/api/instrumentation_checklist.py
index e7e81d011da2..90e070fe8fb4 100644
--- a/products/ai_observability/backend/api/instrumentation_checklist.py
+++ b/products/ai_observability/backend/api/instrumentation_checklist.py
@@ -1,9 +1,8 @@
from typing import cast
-from drf_spectacular.utils import OpenApiResponse, extend_schema
+from drf_spectacular.utils import OpenApiResponse
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
-from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.documentation import PostHogAutoSchema, _FallbackSerializer
@@ -58,6 +57,17 @@ class InstrumentationChecklistSerializer(serializers.Serializer):
)
+class InstrumentationChecklistQuerySerializer(serializers.Serializer):
+ refresh = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "Grade the checks against a fresh read instead of a recent cached one. Use it after "
+ "changing instrumentation, when a cached verdict would still describe the old code."
+ ),
+ )
+
+
class InstrumentationCheckActionSerializer(serializers.Serializer):
check = serializers.ChoiceField(choices=CHECK_KEYS, help_text="Key of the check to dismiss or restore.")
@@ -101,24 +111,28 @@ class AIObservabilityInstrumentationChecklistViewSet(TeamAndOrgViewSetMixin, vie
scope__isnull=True
)
- def _graded_checklist(self) -> Response:
+ def _graded_checklist(self, *, force_refresh: bool = False) -> Response:
# query_ai_events tags the product but not the feature, and sync_execute rejects a query
- # missing either. Tagging here covers the read and both write actions, which recompute.
+ # missing either. Tagging here covers the read and both write actions, which regrade.
tag_queries(feature=Feature.INSTRUMENTATION_CHECKLIST)
dismissed = self._states().filter(status=AIObservabilityChecklistItemState.Status.DISMISSED)
- checks = grade_checklist(fetch_checklist_stats(self.team), dismissed.values_list("check_key", flat=True))
+ # A dismissal changes which status a check reports, never the counts behind it, so both write
+ # actions regrade the cached counts rather than paying for the aggregate again.
+ stats = fetch_checklist_stats(self.team, force_refresh=force_refresh)
+ checks = grade_checklist(stats, dismissed.values_list("check_key", flat=True))
serializer = InstrumentationChecklistSerializer({"window_days": WINDOW_DAYS, "checks": checks})
return Response(serializer.data)
- @extend_schema(
+ @validated_request(
+ query_serializer=InstrumentationChecklistQuerySerializer,
+ responses={200: OpenApiResponse(response=InstrumentationChecklistSerializer)},
operation_id="ai_observability_instrumentation_checklist_retrieve",
- responses={200: InstrumentationChecklistSerializer},
)
@llma_track_latency("llma_instrumentation_checklist_list")
@monitor(feature=None, endpoint="llma_instrumentation_checklist_list", method="GET")
- def list(self, request: Request, **kwargs) -> Response:
+ def list(self, request: ValidatedRequest, **kwargs) -> Response:
"""Grade every instrumentation check for this project."""
- return self._graded_checklist()
+ return self._graded_checklist(force_refresh=request.validated_query_data["refresh"])
@validated_request(
request_serializer=InstrumentationCheckActionSerializer,
diff --git a/products/ai_observability/backend/api/test/test_instrumentation_checklist.py b/products/ai_observability/backend/api/test/test_instrumentation_checklist.py
index 43f4b4110198..c6bef7c16bc9 100644
--- a/products/ai_observability/backend/api/test/test_instrumentation_checklist.py
+++ b/products/ai_observability/backend/api/test/test_instrumentation_checklist.py
@@ -75,14 +75,13 @@ class TestInstrumentationChecklist(ClickhouseTestMixin, APIBaseTest):
# tag at the point the query would run instead.
seen: list[Feature | None] = []
- def record(team: Team) -> ChecklistStats:
+ def record(team: Team, *, force_refresh: bool = False) -> ChecklistStats:
seen.append(get_query_tags().feature)
return ChecklistStats(
generations=0,
events_with_session=0,
events_declining_session=0,
generations_with_tool_calls=0,
- generations_with_tools_declared=0,
sdk_generations=0,
sdk_generations_identified=0,
spans=0,
@@ -104,6 +103,32 @@ class TestInstrumentationChecklist(ClickhouseTestMixin, APIBaseTest):
assert response.status_code == status.HTTP_200_OK, response.content
assert seen == [Feature.INSTRUMENTATION_CHECKLIST]
+ def test_only_a_refresh_regrades_against_events_that_arrived_since(self) -> None:
+ def graded_generations() -> int:
+ body = self.client.get(endpoint(self.team.pk)).json()
+ return check(body, "sessions")["stats"]["generations"]
+
+ assert graded_generations() == VOLUME_FLOOR
+
+ bulk_create_ai_events([generation(self.team, VOLUME_FLOOR + index) for index in range(3)])
+
+ assert graded_generations() == VOLUME_FLOOR
+
+ # A dismissal only changes which status a check reports, so it must regrade the counts it
+ # already has rather than paying for the aggregate again.
+ dismissed = self.client.post(endpoint(self.team.pk, "dismiss/"), {"check": "sessions"}, format="json")
+ assert dismissed.status_code == status.HTTP_200_OK, dismissed.content
+ assert check(dismissed.json(), "sessions")["stats"]["generations"] == VOLUME_FLOOR
+
+ refreshed = self.client.get(f"{endpoint(self.team.pk)}?refresh=true")
+ assert refreshed.status_code == status.HTTP_200_OK, refreshed.content
+ assert check(refreshed.json(), "sessions")["stats"]["generations"] == VOLUME_FLOOR + 3
+
+ def test_an_unreadable_refresh_is_rejected_rather_than_read_as_false(self) -> None:
+ response = self.client.get(f"{endpoint(self.team.pk)}?refresh=banana")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+
def test_get_returns_every_check_graded_over_the_teams_events(self) -> None:
response = self.client.get(endpoint(self.team.pk))
diff --git a/products/ai_observability/backend/instrumentation_checklist/grading.py b/products/ai_observability/backend/instrumentation_checklist/grading.py
index 1b85a243f515..014775c24a04 100644
--- a/products/ai_observability/backend/instrumentation_checklist/grading.py
+++ b/products/ai_observability/backend/instrumentation_checklist/grading.py
@@ -36,12 +36,14 @@ class ChecklistStats:
events_with_session: int
events_declining_session: int
generations_with_tool_calls: int
- generations_with_tools_declared: int
sdk_generations: int
sdk_generations_identified: int
spans: int
events_with_parent: int
total_events: int
+ # Whether any generation carried tool definitions. `None` when nothing asked: a project that
+ # already records tool calls never needs the answer, and the read behind it is expensive.
+ tools_declared: bool | None = None
def __post_init__(self) -> None:
counted = self.generations + self.spans
@@ -108,7 +110,7 @@ def _sessions(stats: ChecklistStats) -> _CheckInputs:
def _tool_calls(stats: ChecklistStats) -> _CheckInputs:
# Tool definitions arriving without any call points at an SDK or parser problem, while no definitions
# at all usually just means the app does not use tools, so the two warnings ask for different things.
- if stats.generations_with_tools_declared > 0:
+ if stats.tools_declared:
warning_detail = (
"No tool calls recorded, but you are sending tool definitions. If your agent does call tools, check "
"that your SDK version reports them."
@@ -131,7 +133,6 @@ def _tool_calls(stats: ChecklistStats) -> _CheckInputs:
stats={
"generations": stats.generations,
"generations_with_tool_calls": stats.generations_with_tool_calls,
- "generations_with_tools_declared": stats.generations_with_tools_declared,
},
)
diff --git a/products/ai_observability/backend/instrumentation_checklist/stats.py b/products/ai_observability/backend/instrumentation_checklist/stats.py
index 667e801f66fa..c97d5664a238 100644
--- a/products/ai_observability/backend/instrumentation_checklist/stats.py
+++ b/products/ai_observability/backend/instrumentation_checklist/stats.py
@@ -1,4 +1,5 @@
from collections.abc import Sequence
+from dataclasses import asdict
from datetime import UTC, datetime, timedelta
from posthog.hogql import ast
@@ -6,36 +7,40 @@ from posthog.hogql.parser import parse_select
from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
from posthog.models.team import Team
+from posthog.utils import generate_cache_key, get_safe_cache, safe_cache_set
-from .grading import ChecklistStats
+from .grading import VOLUME_FLOOR, ChecklistStats
# Matches ai_events' `retention_days Int16 DEFAULT 30`, so the window never asks for rows the
# table has already dropped.
WINDOW_DAYS = 30
+# Instrumentation only changes when someone edits and deploys their code, so a verdict stays true
+# far longer than this. The person who just fixed something is the one case that cannot wait, and
+# the card's Refresh button bypasses the cache for them.
+CACHE_TTL_SECONDS = 15 * 60
+
+# Bump when a change to the counts or the window makes an entry written by an older deploy wrong.
+CACHE_VERSION = "v1"
+
# The four structural event types. The AI meta-events ($ai_metric, $ai_feedback, $ai_evaluation)
# are annotations, not instrumentation, and would inflate the trace_structure denominator.
CHECKLIST_EVENTS = ("$ai_generation", "$ai_span", "$ai_trace", "$ai_embedding")
-# Tool definitions come from the native `tools` column, never `properties.$ai_tools`: the ai_events
-# materialized view strips heavy properties out of the JSON blob, so a properties read returns a
-# silent zero and the checklist would warn that tool instrumentation is broken when it is fine.
-#
# The identity counts exclude OTel-ingested generations because `is_identified` cannot read them.
# An unidentified OTel span falls back to one random UUID per OTLP request
# (rust/capture/src/otel/identity.rs), not to the trace id the server SDKs reuse, so a hex trace id
# never equals it and every such generation would look identified. Counting them would tell an
# all-OTel project its users are identified while its Users tab fills with per-request UUIDs.
#
-# Column aliases are the ChecklistStats field names. `_row_to_stats` maps by name, so a renamed
+# Column aliases are the ChecklistStats field names. `_row_to_counts` maps by name, so a renamed
# column raises instead of shifting a count onto the wrong check.
-_STATS_SQL = """
+_COUNTS_SQL = """
SELECT
countIf(is_generation) AS generations,
countIf(has_session) AS events_with_session,
countIf(declines_session) AS events_declining_session,
countIf(is_generation AND has_tool_calls) AS generations_with_tool_calls,
- countIf(is_generation AND has_tools_declared) AS generations_with_tools_declared,
countIf(is_generation AND NOT is_otel) AS sdk_generations,
countIf(is_generation AND NOT is_otel AND is_identified) AS sdk_generations_identified,
countIf(is_span) AS spans,
@@ -56,10 +61,6 @@ FROM (
JSONHas(properties, '$ai_session_id')
AND JSONType(properties, '$ai_session_id') = 'Null' AS declines_session,
coalesce(properties.$ai_tools_called, '') != '' AS has_tool_calls,
- -- `tools` holds the raw JSON, so an SDK that always sends `$ai_tools: []` stores '[]'. A
- -- non-empty test would read that as declared definitions and accuse a working SDK of not
- -- reporting the calls it makes.
- JSONLength(coalesce(tools, '')) > 0 AS has_tools_declared,
coalesce(properties.$ai_ingestion_source, '') = 'otel' AS is_otel,
distinct_id != coalesce(trace_id, '') AS is_identified,
coalesce(parent_id, '') != '' AS has_parent
@@ -69,24 +70,110 @@ FROM (
)
"""
+# `tools` is the widest column the checklist reads, and costs about as much as every other column
+# it touches put together. Only one warning sentence reads it, so it gets its own query rather than
+# a term in the aggregate every project pays for. `LIMIT 1` ends the scan at the first row that
+# declares tools; a project that declares none is still read in full, so the caller skips this
+# entirely unless the answer can change what someone sees.
+#
+# Tool definitions come from the native `tools` column, never `properties.$ai_tools`: the ai_events
+# materialized view strips heavy properties out of the JSON blob, so a properties read returns a
+# silent zero and the checklist would warn that tool instrumentation is broken when it is fine.
+#
+# `tools` holds the raw JSON, so an SDK that always sends `$ai_tools: []` stores '[]'. A non-empty
+# test would read that as declared definitions and accuse a working SDK of not reporting the calls
+# it makes.
+_TOOLS_DECLARED_SQL = """
+SELECT count() AS declared
+FROM (
+ SELECT 1 AS present
+ FROM posthog.ai_events AS ai_events
+ WHERE event = '$ai_generation'
+ AND timestamp >= {date_from}
+ AND JSONLength(coalesce(tools, '')) > 0
+ LIMIT 1
+)
+"""
-def _row_to_stats(columns: Sequence[str], row: Sequence[int]) -> ChecklistStats:
- return ChecklistStats(**dict(zip(columns, row)))
+def _window_placeholders() -> dict[str, ast.Expr]:
+ return {
+ "checklist_events": ast.Constant(value=list(CHECKLIST_EVENTS)),
+ "date_from": ast.Constant(value=datetime.now(UTC) - timedelta(days=WINDOW_DAYS)),
+ }
-def fetch_checklist_stats(team: Team) -> ChecklistStats:
- """Count the instrumentation signals the checklist grades, over the last WINDOW_DAYS days."""
- # `fall_back_to_events=False` keeps the stripped events table out of the result: it has no
- # `tools` column, so a fallback would read zero declared tools and warn falsely. The ungrouped
- # aggregate returns exactly one row even for a project with no AI events, so it never raises.
+
+def _row_to_counts(columns: Sequence[str], row: Sequence[int]) -> dict[str, int]:
+ return dict(zip(columns, row))
+
+
+def _query_counts(team: Team) -> dict[str, int]:
+ # `fall_back_to_events=False` keeps the stripped events table out of the result: it carries the
+ # AI properties under different names, so a fallback would read zeros and warn falsely. The
+ # ungrouped aggregate returns exactly one row even for a project with no AI events, so it never
+ # raises.
result = query_ai_events(
- query=parse_select(_STATS_SQL),
- placeholders={
- "checklist_events": ast.Constant(value=list(CHECKLIST_EVENTS)),
- "date_from": ast.Constant(value=datetime.now(UTC) - timedelta(days=WINDOW_DAYS)),
- },
+ query=parse_select(_COUNTS_SQL),
+ placeholders=_window_placeholders(),
team=team,
query_type="AIObservabilityInstrumentationChecklist",
fall_back_to_events=False,
)
- return _row_to_stats(result.columns, result.results[0])
+ return _row_to_counts(result.columns, result.results[0])
+
+
+def _query_tools_declared(team: Team) -> bool:
+ result = query_ai_events(
+ query=parse_select(_TOOLS_DECLARED_SQL),
+ placeholders=_window_placeholders(),
+ team=team,
+ query_type="AIObservabilityInstrumentationChecklistToolsDeclared",
+ fall_back_to_events=False,
+ )
+ return result.results[0][0] > 0
+
+
+def _cache_key(team_id: int) -> str:
+ return generate_cache_key(team_id, f"ai_observability_instrumentation_checklist_{CACHE_VERSION}_{WINDOW_DAYS}d")
+
+
+def _stats_from_cache(cached: object) -> ChecklistStats | None:
+ """Rebuild a cached entry by field name, or discard it.
+
+ A frozen slots dataclass pickles its fields positionally, so an entry written before a field was
+ added or removed would unpickle with every later value shifted onto the wrong field, and
+ `__post_init__` does not run to catch it. Reconstructing from a plain dict makes that a cache
+ miss instead. CACHE_VERSION still exists to avoid throwing away a whole team's entry on deploy.
+ """
+ if not isinstance(cached, dict):
+ return None
+ try:
+ return ChecklistStats(**cached)
+ except (TypeError, ValueError):
+ return None
+
+
+def _compute_checklist_stats(team: Team) -> ChecklistStats:
+ counts = _query_counts(team)
+ # Only the tool-calls warning reads this, and only once that check clears its volume floor with
+ # no call recorded. Anywhere else the answer is discarded, so the wide read is skipped. `None`
+ # says the question was never asked, which keeps a skipped read from reading as "declares none".
+ asks_about_definitions = counts["generations"] >= VOLUME_FLOOR and counts["generations_with_tool_calls"] == 0
+ return ChecklistStats(**counts, tools_declared=_query_tools_declared(team) if asks_about_definitions else None)
+
+
+def fetch_checklist_stats(team: Team, *, force_refresh: bool = False) -> ChecklistStats:
+ """Count the instrumentation signals the checklist grades, over the last WINDOW_DAYS days."""
+ cache_key = _cache_key(team.pk)
+ if not force_refresh:
+ cached = _stats_from_cache(get_safe_cache(cache_key))
+ if cached is not None:
+ return cached
+
+ stats = _compute_checklist_stats(team)
+ # Below the floor every check grades pending, which is the card someone watches while their first
+ # events land. Holding that verdict for the whole TTL is the wrong answer to look at, and a
+ # project with that few events is cheap to count again.
+ if stats.total_events >= VOLUME_FLOOR:
+ safe_cache_set(cache_key, asdict(stats), timeout=CACHE_TTL_SECONDS)
+ return stats
diff --git a/products/ai_observability/backend/instrumentation_checklist/test/test_grading.py b/products/ai_observability/backend/instrumentation_checklist/test/test_grading.py
index 4cd55b26b2ec..86b39a0658e6 100644
--- a/products/ai_observability/backend/instrumentation_checklist/test/test_grading.py
+++ b/products/ai_observability/backend/instrumentation_checklist/test/test_grading.py
@@ -1,4 +1,5 @@
from collections.abc import Iterable
+from dataclasses import replace
import pytest
@@ -59,7 +60,6 @@ def _stats(**overrides: int) -> ChecklistStats:
"events_with_session": 0,
"events_declining_session": 0,
"generations_with_tool_calls": 0,
- "generations_with_tools_declared": 0,
"sdk_generations": 0,
"sdk_generations_identified": 0,
"spans": 0,
@@ -68,7 +68,7 @@ def _stats(**overrides: int) -> ChecklistStats:
counts.update(overrides)
if "total_events" not in overrides:
counts["total_events"] = counts["generations"] + counts["spans"]
- return ChecklistStats(**counts)
+ return ChecklistStats(**counts, tools_declared=None)
def _graded(stats: ChecklistStats, key: CheckKey, dismissed_keys: Iterable[str] = ()) -> GradedCheck:
@@ -208,20 +208,6 @@ class TestGradeChecklist:
CheckStatus.PENDING,
PENDING_GENERATIONS,
),
- (
- "tool_calls_warning_with_tools_declared",
- {"generations": 40, "generations_with_tools_declared": 12},
- CheckKey.TOOL_CALLS,
- CheckStatus.WARNING,
- TOOL_CALLS_WARNING_DECLARED,
- ),
- (
- "tool_calls_warning_without_tools_declared",
- {"generations": 40, "generations_with_tools_declared": 0},
- CheckKey.TOOL_CALLS,
- CheckStatus.WARNING,
- TOOL_CALLS_WARNING_NOT_DECLARED,
- ),
(
"tool_calls_ok",
{"generations": 40, "generations_with_tool_calls": 1},
@@ -281,6 +267,26 @@ class TestGradeChecklist:
assert check.status == expected_status
assert check.detail == expected_detail
+ @parameterized.expand(
+ [
+ ("definitions_are_declared", True, TOOL_CALLS_WARNING_DECLARED),
+ ("no_definitions_are_declared", False, TOOL_CALLS_WARNING_NOT_DECLARED),
+ # Nothing asks about definitions unless the check is about to warn, so a `None` that
+ # reaches this branch is a bug elsewhere. It must still read as "no definitions" rather
+ # than telling a project its SDK is dropping calls it never made.
+ ("the_question_was_never_asked", None, TOOL_CALLS_WARNING_NOT_DECLARED),
+ ]
+ )
+ def test_the_tool_calls_warning_asks_for_what_the_declared_definitions_imply(
+ self, _name: str, tools_declared: bool | None, expected_detail: str
+ ) -> None:
+ stats = replace(_stats(generations=40), tools_declared=tools_declared)
+
+ check = _graded(stats, CheckKey.TOOL_CALLS)
+
+ assert check.status == CheckStatus.WARNING
+ assert check.detail == expected_detail
+
@parameterized.expand(
[
("would_be_ok", {"generations": 40, "events_with_session": 40}, SESSIONS_OK),
@@ -329,7 +335,7 @@ class TestGradeChecklist:
(
CheckKey.TOOL_CALLS.value,
CheckKey.TOOL_CALLS,
- {"generations": 40, "generations_with_tool_calls": 3, "generations_with_tools_declared": 11},
+ {"generations": 40, "generations_with_tool_calls": 3},
),
(
CheckKey.USER_IDENTITY.value,
@@ -351,7 +357,6 @@ class TestGradeChecklist:
events_with_session=7,
events_declining_session=2,
generations_with_tool_calls=3,
- generations_with_tools_declared=11,
sdk_generations=31,
sdk_generations_identified=9,
spans=12,
@@ -369,7 +374,6 @@ class TestChecklistStats:
events_with_session=0,
events_declining_session=0,
generations_with_tool_calls=0,
- generations_with_tools_declared=0,
sdk_generations=100,
sdk_generations_identified=0,
spans=10,
diff --git a/products/ai_observability/backend/instrumentation_checklist/test/test_stats.py b/products/ai_observability/backend/instrumentation_checklist/test/test_stats.py
index 879eeae5a666..768e9d6c999d 100644
--- a/products/ai_observability/backend/instrumentation_checklist/test/test_stats.py
+++ b/products/ai_observability/backend/instrumentation_checklist/test/test_stats.py
@@ -4,18 +4,25 @@ from typing import Any
from posthog.test.base import BaseTest, ClickhouseTestMixin
+from django.core.cache import cache
+
+from parameterized import parameterized
+
from posthog.models.ai_events.test_util import bulk_create_ai_events
from posthog.models.team import Team
-from products.ai_observability.backend.instrumentation_checklist.grading import ChecklistStats
+from products.ai_observability.backend.instrumentation_checklist.grading import VOLUME_FLOOR, ChecklistStats
from products.ai_observability.backend.instrumentation_checklist.stats import (
- _STATS_SQL,
+ _COUNTS_SQL,
+ _TOOLS_DECLARED_SQL,
WINDOW_DAYS,
fetch_checklist_stats,
)
NOW = datetime(2026, 8, 19, 12, 0, tzinfo=UTC)
+_TOOL = {"type": "function", "function": {"name": "search"}}
+
def _ai_event(
*,
@@ -37,7 +44,17 @@ def _ai_event(
}
+def _generations(team: Team, count: int) -> list[dict[str, Any]]:
+ return [_ai_event(team=team, event="$ai_generation", trace_id=f"trace-{index}") for index in range(count)]
+
+
class TestFetchChecklistStats(ClickhouseTestMixin, BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # Verdicts are cached per team, and the team id is stable across the class, so without this
+ # the first test to run answers every later one.
+ cache.clear()
+
def test_counts_every_signal_the_checklist_grades(self) -> None:
bulk_create_ai_events(
[
@@ -67,7 +84,9 @@ class TestFetchChecklistStats(ClickhouseTestMixin, BaseTest):
events_with_session=1,
events_declining_session=0,
generations_with_tool_calls=1,
- generations_with_tools_declared=1,
+ # Not False: nothing asked about definitions, because only the tool-calls warning reads
+ # the answer and this project is nowhere near raising it.
+ tools_declared=None,
sdk_generations=2,
sdk_generations_identified=1,
spans=1,
@@ -85,7 +104,7 @@ class TestFetchChecklistStats(ClickhouseTestMixin, BaseTest):
events_with_session=0,
events_declining_session=0,
generations_with_tool_calls=0,
- generations_with_tools_declared=0,
+ tools_declared=None,
sdk_generations=0,
sdk_generations_identified=0,
spans=0,
@@ -142,30 +161,40 @@ class TestFetchChecklistStats(ClickhouseTestMixin, BaseTest):
# The ai_events MV strips $ai_tools from the properties blob, so a properties read returns a
# silent zero in production and the checklist accuses a correctly instrumented project.
# bulk_create_ai_events does not strip it, so no seeded-data assertion can catch this.
- normalized = " ".join(_STATS_SQL.split())
+ normalized = " ".join(_TOOLS_DECLARED_SQL.split())
assert "coalesce(tools, '')" in normalized
# \b keeps $ai_tools_called, which does live in the properties blob, out of the match.
assert re.search(r"properties\.\$ai_tools\b", normalized) is None
- def test_an_empty_tool_array_is_not_counted_as_declared_definitions(self) -> None:
+ def test_the_tools_column_stays_out_of_the_counts_query(self) -> None:
+ # It is the widest column in the table, and reading it for every row costs about as much as
+ # every other column the checklist touches put together.
+ # \b keeps $ai_tools_called, which lives in the properties blob, out of the match.
+ assert re.search(r"\btools\b", " ".join(_COUNTS_SQL.split())) is None
+
+ @parameterized.expand(
+ [
+ ("an_empty_array_is_not_a_declaration", [], None, False),
+ ("a_real_definition_is", [_TOOL], None, True),
+ # The read behind this is the widest in the checklist, and its answer only picks between
+ # two warning sentences. A project already recording calls never raises that warning.
+ ("a_recorded_call_leaves_the_question_unasked", [_TOOL], "search", None),
+ ]
+ )
+ def test_declared_tool_definitions(
+ self, _name: str, tools: list[dict[str, Any]], tools_called: str | None, expected: bool | None
+ ) -> None:
+ properties: dict[str, Any] = {"$ai_tools": tools}
+ if tools_called is not None:
+ properties["$ai_tools_called"] = tools_called
bulk_create_ai_events(
[
- _ai_event(
- team=self.team,
- event="$ai_generation",
- trace_id="trace-empty-tools",
- properties={"$ai_tools": []},
- ),
- _ai_event(
- team=self.team,
- event="$ai_generation",
- trace_id="trace-real-tools",
- properties={"$ai_tools": [{"type": "function", "function": {"name": "search"}}]},
- ),
+ _ai_event(team=self.team, event="$ai_generation", trace_id=f"trace-{index}", properties=properties)
+ for index in range(VOLUME_FLOOR)
]
)
- assert fetch_checklist_stats(self.team).generations_with_tools_declared == 1
+ assert fetch_checklist_stats(self.team).tools_declared is expected
def test_a_session_id_counts_when_it_arrives_on_a_trace_rather_than_a_generation(self) -> None:
bulk_create_ai_events(
@@ -226,10 +255,31 @@ class TestFetchChecklistStats(ClickhouseTestMixin, BaseTest):
assert stats.sdk_generations == 1
assert stats.sdk_generations_identified == 0
- def test_the_aggregate_stays_ungrouped(self) -> None:
+ def test_a_verdict_is_reused_until_a_refresh_asks_for_a_new_one(self) -> None:
+ bulk_create_ai_events(_generations(self.team, VOLUME_FLOOR))
+ assert fetch_checklist_stats(self.team).total_events == VOLUME_FLOOR
+
+ bulk_create_ai_events([_ai_event(team=self.team, event="$ai_span", trace_id="trace-extra")])
+
+ assert fetch_checklist_stats(self.team).total_events == VOLUME_FLOOR
+ assert fetch_checklist_stats(self.team, force_refresh=True).total_events == VOLUME_FLOOR + 1
+
+ def test_a_project_below_the_volume_floor_is_never_held_at_its_first_counts(self) -> None:
+ # Every check grades pending down here, which is the card someone watches while their first
+ # events land. A cached verdict would answer them with the counts from before they started.
+ assert fetch_checklist_stats(self.team).total_events == 0
+
+ bulk_create_ai_events(_generations(self.team, VOLUME_FLOOR - 1))
+
+ assert fetch_checklist_stats(self.team).total_events == VOLUME_FLOOR - 1
+
+ @parameterized.expand([("counts", _COUNTS_SQL), ("tools_declared", _TOOLS_DECLARED_SQL)])
+ def test_every_aggregate_stays_ungrouped(self, _name: str, sql: str) -> None:
# An ungrouped aggregate always returns exactly one row, so query_ai_events' empty-result
- # probe never fires and the stripped events table stays unreachable. A GROUP BY or HAVING
- # would let an empty project raise AIEventsNotFoundError instead of grading at zero.
- normalized = " ".join(_STATS_SQL.split()).upper()
+ # probe never fires and the stripped events table stays unreachable. A GROUP BY, a HAVING,
+ # or dropping the outer count() would let a project with no matching row raise
+ # AIEventsNotFoundError instead of grading.
+ normalized = " ".join(sql.split()).upper()
+ assert "COUNT()" in normalized
assert "GROUP BY" not in normalized
assert "HAVING" not in normalized
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index 3247d9dc6a65..0ab11a9f7068 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -3124,6 +3124,13 @@ export const LlmAnalyticsPersonalSpendListBucketMinutes = {
Number60: 60,
} as const
+export type AiObservabilityInstrumentationChecklistRetrieveParams = {
+ /**
+ * Grade the checks against a fresh read instead of a recent cached one. Use it after changing instrumentation, when a cached verdict would still describe the old code.
+ */
+ refresh?: boolean
+}
+
export type DatasetItemsListParams = {
/**
* Return archived items instead of active items.
diff --git a/products/ai_observability/frontend/generated/api.ts b/products/ai_observability/frontend/generated/api.ts
index 3e85fa590bbb..cf7e5bc81af2 100644
--- a/products/ai_observability/frontend/generated/api.ts
+++ b/products/ai_observability/frontend/generated/api.ts
@@ -9,6 +9,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ AiObservabilityInstrumentationChecklistRetrieveParams,
BatchCheckRequestApi,
BatchCheckResponseApi,
ClusteringConfigApi,
@@ -166,8 +167,23 @@ export const llmAnalyticsPersonalSpendList = async (
})
}
-export const getAiObservabilityInstrumentationChecklistRetrieveUrl = (projectId: string) => {
- return `/api/projects/${projectId}/ai_observability/instrumentation_checklist/`
+export const getAiObservabilityInstrumentationChecklistRetrieveUrl = (
+ projectId: string,
+ params?: AiObservabilityInstrumentationChecklistRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/ai_observability/instrumentation_checklist/?${stringifiedParams}`
+ : `/api/projects/${projectId}/ai_observability/instrumentation_checklist/`
}
/**
@@ -175,12 +191,16 @@ export const getAiObservabilityInstrumentationChecklistRetrieveUrl = (projectId:
*/
export const aiObservabilityInstrumentationChecklistRetrieve = async (
projectId: string,
+ params?: AiObservabilityInstrumentationChecklistRetrieveParams,
options?: RequestInit
): Promise<InstrumentationChecklistApi> => {
- return apiMutator<InstrumentationChecklistApi>(getAiObservabilityInstrumentationChecklistRetrieveUrl(projectId), {
- ...options,
- method: 'GET',
- })
+ return apiMutator<InstrumentationChecklistApi>(
+ getAiObservabilityInstrumentationChecklistRetrieveUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
}
export const getAiObservabilityInstrumentationChecklistDismissCreateUrl = (projectId: string) => {
diff --git a/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.stories.tsx b/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.stories.tsx
index 348902bbd2f6..2fbe77534049 100644
--- a/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.stories.tsx
+++ b/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.stories.tsx
@@ -62,7 +62,7 @@ const TOOL_CALLS: Record<InstrumentationCheckStatusEnumApi, InstrumentationCheck
title: 'Tool calls',
detail: 'Tool calls are being recorded.',
docs_url: TOOLS_DOCS_URL,
- stats: { generations: 1284, generations_with_tool_calls: 310, generations_with_tools_declared: 640 },
+ stats: { generations: 1284, generations_with_tool_calls: 310 },
},
warning: {
key: AIObservabilityInstrumentationCheckEnumApi.ToolCalls,
@@ -70,7 +70,7 @@ const TOOL_CALLS: Record<InstrumentationCheckStatusEnumApi, InstrumentationCheck
title: 'Tool calls',
detail: 'No tool calls recorded, but you are sending tool definitions. If your agent does call tools, check that your SDK version reports them.',
docs_url: TOOLS_DOCS_URL,
- stats: { generations: 1284, generations_with_tool_calls: 0, generations_with_tools_declared: 640 },
+ stats: { generations: 1284, generations_with_tool_calls: 0 },
},
pending: {
key: AIObservabilityInstrumentationCheckEnumApi.ToolCalls,
@@ -78,7 +78,7 @@ const TOOL_CALLS: Record<InstrumentationCheckStatusEnumApi, InstrumentationCheck
title: 'Tool calls',
detail: 'Still collecting data. This check runs once there are 20 generations.',
docs_url: TOOLS_DOCS_URL,
- stats: { generations: 4, generations_with_tool_calls: 0, generations_with_tools_declared: 0 },
+ stats: { generations: 4, generations_with_tool_calls: 0 },
},
dismissed: {
key: AIObservabilityInstrumentationCheckEnumApi.ToolCalls,
@@ -86,7 +86,7 @@ const TOOL_CALLS: Record<InstrumentationCheckStatusEnumApi, InstrumentationCheck
title: 'Tool calls',
detail: 'No tool calls recorded. If your app uses tool or function calling, capture it to see which tools run and how often.',
docs_url: TOOLS_DOCS_URL,
- stats: { generations: 1284, generations_with_tool_calls: 0, generations_with_tools_declared: 0 },
+ stats: { generations: 1284, generations_with_tool_calls: 0 },
},
}
@@ -260,7 +260,7 @@ export const FirstLoad: Story = {
parameters: {
layout: 'padded',
featureFlags: [FEATURE_FLAGS.AI_OBSERVABILITY_INSTRUMENTATION_CHECKLIST],
- // The skeleton stands in for a read that has not answered, so it never settles in a story.
+ // The card holds its header until the read answers, so this story never settles.
testOptions: { waitForLoadersToDisappear: false },
},
decorators: [
diff --git a/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.test.tsx b/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.test.tsx
index 827c8aa7619f..165a976bb513 100644
--- a/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.test.tsx
+++ b/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.test.tsx
@@ -92,6 +92,13 @@ function renderCard(): void {
)
}
+// The header is on screen while the first read runs too, so waiting for it says nothing about
+// whether a verdict has landed.
+async function findGradedCard(): Promise<void> {
+ await expectLogic(instrumentationChecklistLogic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+ expect(await screen.findByText('Instrumentation checklist')).toBeInTheDocument()
+}
+
describe('InstrumentationChecklistCard', () => {
beforeEach(() => {
jest.clearAllMocks()
@@ -118,7 +125,7 @@ describe('InstrumentationChecklistCard', () => {
mockRetrieve.mockResolvedValue(buildChecklist(...statuses))
renderCard()
- expect(await screen.findByText('Instrumentation checklist')).toBeInTheDocument()
+ await findGradedCard()
expect(panel()).toHaveAttribute('aria-expanded', expanded)
})
@@ -126,7 +133,7 @@ describe('InstrumentationChecklistCard', () => {
mockRetrieve.mockResolvedValue(buildChecklist(Ok, Ok, Ok, Ok))
renderCard()
- expect(await screen.findByText('Instrumentation checklist')).toBeInTheDocument()
+ await findGradedCard()
expect(screen.queryByText('A sentence about Sessions.')).not.toBeInTheDocument()
await userEvent.click(toggle() as HTMLElement)
@@ -146,6 +153,15 @@ describe('InstrumentationChecklistCard', () => {
['the read failed', () => mockRetrieve.mockRejectedValue({ status: 500 })],
]
+ it('holds its header while the first read runs, rather than a skeleton', async () => {
+ mockRetrieve.mockReturnValue(new Promise(() => {}))
+ renderCard()
+
+ expect(await screen.findByText('Instrumentation checklist')).toBeInTheDocument()
+ expect(screen.getByText('Checking your events')).toBeInTheDocument()
+ expect(document.querySelector('.LemonSkeleton')).not.toBeInTheDocument()
+ })
+
it.each(noVerdictCases)('renders nothing, not a skeleton, while %s', async (_, arrange) => {
arrange()
renderCard()
@@ -159,7 +175,7 @@ describe('InstrumentationChecklistCard', () => {
it('offers a retry when a refresh fails under a checklist already on screen', async () => {
mockRetrieve.mockResolvedValue(buildChecklist(Warning, Ok, Ok, Ok))
renderCard()
- await screen.findByText('Instrumentation checklist')
+ await findGradedCard()
mockRetrieve.mockRejectedValue({ status: 500 })
await userEvent.click(screen.getByText('Refresh'))
@@ -185,7 +201,7 @@ describe('InstrumentationChecklistCard', () => {
mockDismiss.mockImplementation(() => new Promise(() => {}))
renderCard()
- await screen.findByText('Instrumentation checklist')
+ await findGradedCard()
expect(actionButtons()).toHaveLength(4)
expect(actionButtons().map((button) => button.getAttribute('aria-disabled'))).toEqual([
'false',
diff --git a/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.tsx b/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.tsx
index 51e487a28691..eb00b37354ff 100644
--- a/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.tsx
+++ b/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.tsx
@@ -2,14 +2,20 @@ import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import { IconCheckCircle, IconClock, IconMinusSquare, IconRefresh, IconWarning } from '@posthog/icons'
-import { LemonButton, LemonCollapse, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'
+import { LemonButton, LemonCollapse, LemonTag, Link } from '@posthog/lemon-ui'
import { InstrumentationCheckApi, InstrumentationCheckStatusEnumApi } from '../generated/api.schemas'
-import { instrumentationChecklistLogic } from './instrumentationChecklistLogic'
+import { InstrumentationChecklistCardState, instrumentationChecklistLogic } from './instrumentationChecklistLogic'
const PANEL_KEY = 'instrumentation-checklist'
const BUSY_REASON = 'Wait for the current update to finish'
+const STATE_SUMMARIES: Record<Exclude<InstrumentationChecklistCardState, 'hidden' | 'warnings'>, string> = {
+ checking: 'Checking your events',
+ collecting: 'Still collecting data',
+ passing: 'No checks need attention',
+}
+
const STATUS_ICONS: Record<InstrumentationCheckStatusEnumApi, JSX.Element> = {
[InstrumentationCheckStatusEnumApi.Ok]: <IconCheckCircle className="text-success shrink-0 mt-0.5" />,
[InstrumentationCheckStatusEnumApi.Warning]: <IconWarning className="text-warning shrink-0 mt-0.5" />,
@@ -75,34 +81,30 @@ function InstrumentationCheckRow({ check }: { check: InstrumentationCheckApi }):
* collapses to its header but stays expandable, because a checklist nobody can find is one nobody
* can use to confirm a fix landed. Rendering nothing is reserved for having no verdict at all: the
* flag is off, or the read failed and we would otherwise be guessing.
+ *
+ * The first read holds the header rather than a skeleton. It can take seconds on a project with a
+ * lot of events, and a card that keeps its place and its name for that long reads as working, where
+ * a shimmer of the same length reads as stuck.
*/
export function InstrumentationChecklistCard(): JSX.Element | null {
- const {
- checklist,
- checklistLoading,
- checklistEnabled,
- checks,
- checklistCardState,
- windowDays,
- pendingCheckKey,
- refreshFailed,
- } = useValues(instrumentationChecklistLogic)
+ const { checklistLoading, checks, checklistCardState, windowDays, pendingCheckKey, refreshFailed } =
+ useValues(instrumentationChecklistLogic)
const { loadInstrumentationChecklist } = useActions(instrumentationChecklistLogic)
- // Only the first read, so a dismissal does not replace the card the user just clicked in.
- if (checklistEnabled && checklist === null && checklistLoading) {
- return <LemonSkeleton className="h-10 w-full mb-4" />
- }
-
if (checklistCardState === 'hidden') {
return null
}
+ const isChecking = checklistCardState === 'checking'
const warningCount = checks.filter((check) => check.status === InstrumentationCheckStatusEnumApi.Warning).length
return (
<div className="mb-4" data-attr="ai-observability-instrumentation-checklist">
<LemonCollapse
+ // LemonCollapse reads defaultActiveKey once, at mount. The card is already on screen
+ // while the first read runs, so the verdict has to remount it or warnings land in a
+ // panel that stays shut.
+ key={isChecking ? 'checking' : 'graded'}
defaultActiveKey={checklistCardState === 'warnings' ? PANEL_KEY : undefined}
panels={[
{
@@ -120,15 +122,14 @@ export function InstrumentationChecklistCard(): JSX.Element | null {
</LemonTag>
) : (
<span className="text-muted font-normal">
- {checklistCardState === 'collecting'
- ? 'Still collecting data'
- : 'No checks need attention'}
+ {STATE_SUMMARIES[checklistCardState]}
</span>
)}
</div>
),
},
- content: (
+ // Nothing to expand into until the first read answers.
+ content: isChecking ? null : (
<div className="flex flex-col gap-3">
{checks.map((check) => (
<InstrumentationCheckRow key={check.key} check={check} />
@@ -147,7 +148,7 @@ export function InstrumentationChecklistCard(): JSX.Element | null {
icon={<IconRefresh />}
loading={checklistLoading}
disabledReason={pendingCheckKey !== null ? BUSY_REASON : undefined}
- onClick={() => loadInstrumentationChecklist()}
+ onClick={() => loadInstrumentationChecklist({ refresh: true })}
data-attr="ai-observability-instrumentation-checklist-refresh"
>
{refreshFailed ? 'Try again' : 'Refresh'}
diff --git a/products/ai_observability/frontend/instrumentationChecklist/instrumentationChecklistLogic.test.ts b/products/ai_observability/frontend/instrumentationChecklist/instrumentationChecklistLogic.test.ts
index 264254366e1a..a698617fc051 100644
--- a/products/ai_observability/frontend/instrumentationChecklist/instrumentationChecklistLogic.test.ts
+++ b/products/ai_observability/frontend/instrumentationChecklist/instrumentationChecklistLogic.test.ts
@@ -197,6 +197,29 @@ describe('instrumentationChecklistLogic', () => {
expect(logic.values.refreshFailed).toBe(false)
})
+ it('asks for a fresh read only when the refresh is explicit', async () => {
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+ expect(mockRetrieve).toHaveBeenLastCalledWith(expect.any(String), { refresh: undefined })
+
+ logic.actions.loadInstrumentationChecklist({ refresh: true })
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+
+ // Without this the button serves whatever the server cached, so someone who just fixed
+ // their instrumentation is told it is still broken.
+ expect(mockRetrieve).toHaveBeenLastCalledWith(expect.any(String), { refresh: true })
+ })
+
+ it('reports it is still checking until the first read answers', async () => {
+ mockRetrieve.mockReturnValue(new Promise(() => {}))
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+
+ // 'hidden' here would flash the scene one layout, then another once the read lands.
+ await expectLogic(logic).toMatchValues({ checklistCardState: 'checking' })
+ })
+
const cardStateCases: [string, InstrumentationCheckStatusEnumApi[], InstrumentationChecklistCardState][] = [
[
'a warning is present',
diff --git a/products/ai_observability/frontend/instrumentationChecklist/instrumentationChecklistLogic.ts b/products/ai_observability/frontend/instrumentationChecklist/instrumentationChecklistLogic.ts
index 7de330ae71b0..ae893b5c20ec 100644
--- a/products/ai_observability/frontend/instrumentationChecklist/instrumentationChecklistLogic.ts
+++ b/products/ai_observability/frontend/instrumentationChecklist/instrumentationChecklistLogic.ts
@@ -22,22 +22,23 @@ import {
/**
* How loudly the dashboard card should present itself.
*
- * - `hidden`: nothing to say. No checklist has loaded, the flag is off, or the request failed.
+ * - `hidden`: nothing to say. The flag is off, or the request failed.
+ * - `checking`: the first read has not answered yet.
* - `warnings`: at least one check is missing instrumentation.
* - `collecting`: nothing has been graded yet, because every check the team still wants judged is
* below its volume floor.
* - `passing`: at least one check graded ok, or every check has been dismissed.
*/
-export type InstrumentationChecklistCardState = 'hidden' | 'warnings' | 'collecting' | 'passing'
+export type InstrumentationChecklistCardState = 'hidden' | 'checking' | 'warnings' | 'collecting' | 'passing'
/**
- * The verdict is graded by an uncached 30 day aggregate over every AI event a project sent, so it is
- * the most expensive read on the scene. The logic unmounts with the scene, and the trace view mounts
- * it again for each trace opened, which would refire that aggregate per trace.
+ * The logic unmounts with the scene, and the trace view mounts it again for each trace opened, which
+ * would refetch the verdict per trace. The server caches the graded counts as well, so this saves the
+ * round trip rather than the aggregate behind it.
*
* Instrumentation changes when someone edits their code, so a verdict stays true far longer than a
* few minutes. The cache lives at module scope rather than in a reducer because it has to outlive the
- * unmount that causes the refetch. Refresh calls the loader directly and bypasses it.
+ * unmount that causes the refetch. Refresh asks the server for a fresh read and bypasses both.
*/
const VERDICT_TTL_MS = 5 * 60 * 1000
let cachedVerdict: { at: number; teamId: number | null; checklist: InstrumentationChecklistApi } | null = null
@@ -75,7 +76,9 @@ export interface instrumentationChecklistLogicActions {
dismissCheck: (check: AIObservabilityInstrumentationCheckEnumApi) => {
check: AIObservabilityInstrumentationCheckEnumApi
}
- loadInstrumentationChecklist: (_: void) => void
+ loadInstrumentationChecklist: ({ refresh }?: { refresh?: boolean }) => {
+ refresh?: boolean
+ }
loadInstrumentationChecklistFailure: (
error: string,
errorObject?: any
@@ -85,10 +88,14 @@ export interface instrumentationChecklistLogicActions {
}
loadInstrumentationChecklistSuccess: (
checklist: InstrumentationChecklistApi | null,
- payload?: void
+ payload?: {
+ refresh?: boolean
+ }
) => {
checklist: InstrumentationChecklistApi | null
- payload?: void
+ payload?: {
+ refresh?: boolean
+ }
}
restoreCheck: (check: AIObservabilityInstrumentationCheckEnumApi) => {
check: AIObservabilityInstrumentationCheckEnumApi
@@ -110,7 +117,8 @@ export interface instrumentationChecklistLogicMeta {
) => boolean
checklistCardState: (
checklistEnabled: boolean,
- checks: InstrumentationCheckApi[]
+ checks: InstrumentationCheckApi[],
+ checklistLoading: boolean
) => InstrumentationChecklistCardState
warningForCheck: (
checklistEnabled: boolean,
@@ -155,13 +163,16 @@ export const instrumentationChecklistLogic = kea<instrumentationChecklistLogicTy
null as InstrumentationChecklistApi | null,
{
loadInstrumentationChecklist: async (
- _: void,
+ { refresh }: { refresh?: boolean } = {},
breakpoint
): Promise<InstrumentationChecklistApi | null> => {
if (!values.checklistEnabled) {
return null
}
- const response = await aiObservabilityInstrumentationChecklistRetrieve(String(values.currentTeamId))
+ const response = await aiObservabilityInstrumentationChecklistRetrieve(
+ String(values.currentTeamId),
+ { refresh }
+ )
breakpoint()
cachedVerdict = { at: performance.now(), teamId: values.currentTeamId, checklist: response }
return response
@@ -205,11 +216,20 @@ export const instrumentationChecklistLogic = kea<instrumentationChecklistLogicTy
checklistLoading || pendingCheckKey !== null,
],
checklistCardState: [
- (s) => [s.checklistEnabled, s.checks],
- (checklistEnabled: boolean, checks: InstrumentationCheckApi[]): InstrumentationChecklistCardState => {
- if (!checklistEnabled || checks.length === 0) {
+ (s) => [s.checklistEnabled, s.checks, s.checklistLoading],
+ (
+ checklistEnabled: boolean,
+ checks: InstrumentationCheckApi[],
+ checklistLoading: boolean
+ ): InstrumentationChecklistCardState => {
+ if (!checklistEnabled) {
return 'hidden'
}
+ if (checks.length === 0) {
+ // A read that failed stays hidden rather than announcing itself, so nothing is
+ // ever claimed about instrumentation we could not measure.
+ return checklistLoading ? 'checking' : 'hidden'
+ }
if (checks.some((check) => check.status === InstrumentationCheckStatusEnumApi.Warning)) {
return 'warnings'
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9ff9d70f1746..d46e657d3db9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -91273,6 +91273,13 @@ export namespace Schemas {
Ocsf: 'ocsf',
} as const;
+ export type AiObservabilityInstrumentationChecklistRetrieveParams = {
+ /**
+ * Grade the checks against a fresh read instead of a recent cached one. Use it after changing instrumentation, when a cached verdict would still describe the old code.
+ */
+ refresh?: boolean;
+ };
+
export type AlertsListParams = {
/**
* Optional. Restrict results to alerts created by the user with this UUID.