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): tell projects which AI instrumentation is missing (#88511)

Carlos Marchalc8bda4f5aa41
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index a85e02696691..208627acd7cb 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -73,6 +73,7 @@ rules:
|AgentToolApprovalRequest
|AgentTransportBinding
|AgentUser
+ |AIObservabilityChecklistItemState
|Alert
|AlertConfiguration
|Annotation
@@ -447,6 +448,7 @@ rules:
|AgentToolApprovalRequest
|AgentTransportBinding
|AgentUser
+ |AIObservabilityChecklistItemState
|Alert
|AlertConfiguration
|Annotation
diff --git a/docs/onboarding/ai-observability/_snippets/embedding-event.tsx b/docs/onboarding/ai-observability/_snippets/embedding-event.tsx
index 3f061050e404..3de67a496752 100644
--- a/docs/onboarding/ai-observability/_snippets/embedding-event.tsx
+++ b/docs/onboarding/ai-observability/_snippets/embedding-event.tsx
@@ -47,9 +47,11 @@ export const EmbeddingEvent = (): JSX.Element => {
</td>
<td>
<p>
- <em>(Optional)</em> Groups related traces together. Use this to organize traces by
- whatever grouping makes sense for your application (user sessions, workflows,
- conversations, or other logical boundaries).
+ <em>(Optional)</em> Groups related traces into a session, which is what the Sessions
+ tab reads. Set it if your product has multi-turn conversations. A workload that
+ finishes in a single trace does not need it. Send it as null to say so explicitly,
+ which tells the instrumentation checklist the workload is complete rather than
+ missing a session id.
<br />
Example: <code>session-abc-123</code>, <code>conv-user-456</code>
</p>
diff --git a/docs/onboarding/ai-observability/_snippets/generation-event.tsx b/docs/onboarding/ai-observability/_snippets/generation-event.tsx
index c7717b69c031..45cefadc90d6 100644
--- a/docs/onboarding/ai-observability/_snippets/generation-event.tsx
+++ b/docs/onboarding/ai-observability/_snippets/generation-event.tsx
@@ -48,9 +48,11 @@ export const GenerationEvent = (): JSX.Element => {
</td>
<td>
<p>
- <em>(Optional)</em> Groups related traces together. Use this to organize traces by
- whatever grouping makes sense for your application (user sessions, workflows,
- conversations, or other logical boundaries).
+ <em>(Optional)</em> Groups related traces into a session, which is what the Sessions
+ tab reads. Set it if your product has multi-turn conversations. A workload that
+ finishes in a single trace does not need it. Send it as null to say so explicitly,
+ which tells the instrumentation checklist the workload is complete rather than
+ missing a session id.
<br />
Example: <code>session-abc-123</code>, <code>conv-user-456</code>
</p>
diff --git a/docs/onboarding/ai-observability/_snippets/otel-session-id.tsx b/docs/onboarding/ai-observability/_snippets/otel-session-id.tsx
new file mode 100644
index 000000000000..6f9e1c4091d8
--- /dev/null
+++ b/docs/onboarding/ai-observability/_snippets/otel-session-id.tsx
@@ -0,0 +1,118 @@
+import { OnboardingComponentsContext } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
+
+import { StepDefinition } from '../../steps'
+
+export interface OtelSessionIdConfig {
+ /** Language tabs the surrounding page shows, in the order it shows them. */
+ languages: ('Python' | 'Node')[]
+}
+
+const PYTHON_CODE = `
+import contextvars
+from collections.abc import Iterator
+from contextlib import contextmanager
+from typing import Optional
+
+from opentelemetry.context import Context
+from opentelemetry.sdk.trace import Span, SpanProcessor
+
+session_id_var: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar(
+ "ai_session_id", default=None
+)
+
+
+class SessionIdSpanProcessor(SpanProcessor):
+ def on_start(self, span: Span, parent_context: Optional[Context] = None) -> None:
+ session_id = session_id_var.get()
+ if session_id is not None:
+ span.set_attribute("$ai_session_id", session_id)
+
+
+@contextmanager
+def ai_session(session_id: str) -> Iterator[None]:
+ token = session_id_var.set(session_id)
+ try:
+ yield
+ finally:
+ session_id_var.reset(token)
+
+
+# Register it on the same provider as PostHogSpanProcessor
+provider.add_span_processor(SessionIdSpanProcessor())
+
+# Resetting on exit keeps the ID off the next request that reuses this thread
+with ai_session("conversation-abc"):
+ reply = handle_turn(user_message)
+`.trim()
+
+const NODE_CODE = `
+import { AsyncLocalStorage } from 'node:async_hooks'
+import type { Span, SpanProcessor } from '@opentelemetry/sdk-trace-base'
+
+const sessionStore = new AsyncLocalStorage<string>()
+
+class SessionIdSpanProcessor implements SpanProcessor {
+ onStart(span: Span): void {
+ const sessionId = sessionStore.getStore()
+ if (sessionId) {
+ span.setAttribute('$ai_session_id', sessionId)
+ }
+ }
+ onEnd(): void {}
+ async shutdown(): Promise<void> {}
+ async forceFlush(): Promise<void> {}
+}
+
+// Every span started inside the callback carries this session ID
+const reply = await sessionStore.run('conversation-abc', () => handleTurn(userMessage))
+`.trim()
+
+const CODE_BY_LANGUAGE = {
+ Python: { language: 'python', file: 'Python', code: PYTHON_CODE },
+ Node: { language: 'typescript', file: 'Node', code: NODE_CODE },
+}
+
+export const getOtelSessionIdStep = (ctx: OnboardingComponentsContext, config: OtelSessionIdConfig): StepDefinition => {
+ const { CodeBlock, Markdown, dedent } = ctx
+
+ return {
+ title: 'Group traces into sessions',
+ badge: 'optional',
+ content: (
+ <>
+ <Markdown>
+ {dedent`
+ PostHog groups traces into a session when they share an \`$ai_session_id\`. Set it if your
+ product has multi-turn conversations, so the Sessions tab can reconstruct them. Workloads
+ that finish in a single trace, like batch jobs or one-shot generation, do not need it.
+
+ The instrumentation creates the LLM span for you, so there is no call to pass the session ID
+ to. Add a span processor that sets the \`$ai_session_id\` attribute as each span starts.
+ PostHog forwards span attributes it does not recognize onto the event, so the value arrives
+ as the \`$ai_session_id\` property.
+ `}
+ </Markdown>
+
+ <CodeBlock blocks={config.languages.map((language) => CODE_BY_LANGUAGE[language])} />
+
+ {config.languages.includes('Node') && (
+ <Markdown>
+ {dedent`
+ On Node, add \`new SessionIdSpanProcessor()\` to the \`spanProcessors\` array of the
+ \`NodeSDK\` you configured earlier, next to \`PostHogSpanProcessor\`. Keep the rest of
+ that setup as it is, including \`instrumentations\` and the \`sdk.start()\` call.
+ `}
+ </Markdown>
+ )}
+
+ <Markdown>
+ {dedent`
+ If a process only ever handles one session, set \`$ai_session_id\` as a resource attribute
+ next to \`service.name\` instead. Resource attributes apply to every span the process emits,
+ so that only works when the process and the session are the same thing.
+ `}
+ </Markdown>
+ </>
+ ),
+ }
+}
diff --git a/docs/onboarding/ai-observability/_snippets/span-event.tsx b/docs/onboarding/ai-observability/_snippets/span-event.tsx
index b0466567ec23..064e5de664ee 100644
--- a/docs/onboarding/ai-observability/_snippets/span-event.tsx
+++ b/docs/onboarding/ai-observability/_snippets/span-event.tsx
@@ -48,9 +48,11 @@ export const SpanEvent = (): JSX.Element => {
</td>
<td>
<p>
- <em>(Optional)</em> Groups related traces together. Use this to organize traces by
- whatever grouping makes sense for your application (user sessions, workflows,
- conversations, or other logical boundaries).
+ <em>(Optional)</em> Groups related traces into a session, which is what the Sessions
+ tab reads. Set it if your product has multi-turn conversations. A workload that
+ finishes in a single trace does not need it. Send it as null to say so explicitly,
+ which tells the instrumentation checklist the workload is complete rather than
+ missing a session id.
<br />
Example: <code>session-abc-123</code>, <code>conv-user-456</code>
</p>
diff --git a/docs/onboarding/ai-observability/_snippets/trace-event.tsx b/docs/onboarding/ai-observability/_snippets/trace-event.tsx
index f42a5178a39d..3209d9bcec4b 100644
--- a/docs/onboarding/ai-observability/_snippets/trace-event.tsx
+++ b/docs/onboarding/ai-observability/_snippets/trace-event.tsx
@@ -48,9 +48,11 @@ export const TraceEvent = (): JSX.Element => {
</td>
<td>
<p>
- <em>(Optional)</em> Groups related traces together. Use this to organize traces by
- whatever grouping makes sense for your application (user sessions, workflows,
- conversations, or other logical boundaries).
+ <em>(Optional)</em> Groups related traces into a session, which is what the Sessions
+ tab reads. Set it if your product has multi-turn conversations. A workload that
+ finishes in a single trace does not need it. Send it as null to say so explicitly,
+ which tells the instrumentation checklist the workload is complete rather than
+ missing a session id.
<br />
Must contain only letters, numbers, and special characters: <code>-</code>,{' '}
<code>_</code>, <code>~</code>, <code>.</code>, <code>@</code>, <code>(</code>,{' '}
diff --git a/docs/onboarding/ai-observability/autogen.tsx b/docs/onboarding/ai-observability/autogen.tsx
index 6e5e64dd9e8f..d00ba0a7c46a 100644
--- a/docs/onboarding/ai-observability/autogen.tsx
+++ b/docs/onboarding/ai-observability/autogen.tsx
@@ -1,6 +1,7 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
+import { getOtelSessionIdStep } from './_snippets/otel-session-id'
export const getAutoGenSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
@@ -124,6 +125,7 @@ export const getAutoGenSteps = (ctx: OnboardingComponentsContext): StepDefinitio
</>
),
},
+ getOtelSessionIdStep(ctx, { languages: ['Python'] }),
]
}
diff --git a/docs/onboarding/ai-observability/aws-bedrock.tsx b/docs/onboarding/ai-observability/aws-bedrock.tsx
index da67075941be..cba3cee9a5ee 100644
--- a/docs/onboarding/ai-observability/aws-bedrock.tsx
+++ b/docs/onboarding/ai-observability/aws-bedrock.tsx
@@ -1,6 +1,7 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
+import { getOtelSessionIdStep } from './_snippets/otel-session-id'
export const getAWSBedrockSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
@@ -201,6 +202,7 @@ export const getAWSBedrockSteps = (ctx: OnboardingComponentsContext): StepDefini
</>
),
},
+ getOtelSessionIdStep(ctx, { languages: ['Python', 'Node'] }),
]
}
diff --git a/docs/onboarding/ai-observability/convex.tsx b/docs/onboarding/ai-observability/convex.tsx
index ab14ef406201..1e450cac2728 100644
--- a/docs/onboarding/ai-observability/convex.tsx
+++ b/docs/onboarding/ai-observability/convex.tsx
@@ -106,6 +106,7 @@ export const getConvexSteps = (ctx: OnboardingComponentsContext): StepDefinition
functionId: 'my-convex-action',
metadata: {
posthog_distinct_id: distinctId,
+ $ai_session_id: 'conversation-abc', // optional: groups traces into one session
},
},
})
@@ -188,6 +189,7 @@ export const getConvexSteps = (ctx: OnboardingComponentsContext): StepDefinition
functionId: 'convex-agent',
metadata: {
posthog_distinct_id: distinctId,
+ $ai_session_id: 'conversation-abc', // optional: groups traces into one session
},
},
})
diff --git a/docs/onboarding/ai-observability/instructor.tsx b/docs/onboarding/ai-observability/instructor.tsx
index 767087eb50fc..fc8a6af646d8 100644
--- a/docs/onboarding/ai-observability/instructor.tsx
+++ b/docs/onboarding/ai-observability/instructor.tsx
@@ -1,6 +1,7 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
+import { getOtelSessionIdStep } from './_snippets/otel-session-id'
export const getInstructorSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
@@ -203,6 +204,7 @@ export const getInstructorSteps = (ctx: OnboardingComponentsContext): StepDefini
</>
),
},
+ getOtelSessionIdStep(ctx, { languages: ['Python', 'Node'] }),
]
}
diff --git a/docs/onboarding/ai-observability/llamaindex.tsx b/docs/onboarding/ai-observability/llamaindex.tsx
index d7b4b81f5f14..2af1aaacf1f1 100644
--- a/docs/onboarding/ai-observability/llamaindex.tsx
+++ b/docs/onboarding/ai-observability/llamaindex.tsx
@@ -1,6 +1,7 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
+import { getOtelSessionIdStep } from './_snippets/otel-session-id'
export const getLlamaIndexSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
@@ -135,6 +136,7 @@ export const getLlamaIndexSteps = (ctx: OnboardingComponentsContext): StepDefini
</>
),
},
+ getOtelSessionIdStep(ctx, { languages: ['Python'] }),
]
}
diff --git a/docs/onboarding/ai-observability/manual.tsx b/docs/onboarding/ai-observability/manual.tsx
index b1e7d82de990..e739118584ef 100644
--- a/docs/onboarding/ai-observability/manual.tsx
+++ b/docs/onboarding/ai-observability/manual.tsx
@@ -29,6 +29,13 @@ export const getManualSteps = (ctx: OnboardingComponentsContext): StepDefinition
If you use a different server-side SDK, or prefer to use the API, capture the data
manually. Call the \`capture\` method, or use the [capture
API](https://posthog.com/docs/api/capture).
+
+ \`$ai_trace_id\` groups the events of one LLM interaction into a trace.
+ \`$ai_session_id\` is optional and groups related traces into a session, which is what the
+ Sessions tab reads. Set it if your product has multi-turn conversations. Workloads that
+ finish in a single trace, like batch jobs or one-shot generation, do not need it. Send it
+ as \`null\` on those to say so explicitly, which tells the instrumentation checklist the
+ workload is complete rather than missing a session id.
`}
</Markdown>
@@ -69,6 +76,7 @@ export const getManualSteps = (ctx: OnboardingComponentsContext): StepDefinition
event: '$ai_generation',
properties: {
$ai_trace_id: 'trace_id_here',
+ $ai_session_id: 'conversation-abc', // optional: groups traces into one session
$ai_model: 'gpt-5-mini',
$ai_provider: 'openai',
$ai_input: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
@@ -113,6 +121,7 @@ export const getManualSteps = (ctx: OnboardingComponentsContext): StepDefinition
event='$ai_generation',
properties={
'$ai_trace_id': 'trace_id_here',
+ '$ai_session_id': 'conversation-abc', # optional: groups traces into one session
'$ai_model': 'gpt-5-mini',
'$ai_provider': 'openai',
'$ai_input': [{'role': 'user', 'content': 'Tell me a fun fact about hedgehogs'}],
@@ -161,6 +170,8 @@ export const getManualSteps = (ctx: OnboardingComponentsContext): StepDefinition
Event: "$ai_generation",
Properties: map[string]interface{}{
"$ai_trace_id": "trace_id_here",
+ // $ai_session_id is optional: it groups traces into one session
+ "$ai_session_id": "conversation-abc",
"$ai_model": "gpt-5-mini",
"$ai_provider": "openai",
"$ai_input_tokens": 10,
@@ -204,6 +215,7 @@ export const getManualSteps = (ctx: OnboardingComponentsContext): StepDefinition
event: '$ai_generation',
properties: {
'$ai_trace_id' => 'trace_id_here',
+ '$ai_session_id' => 'conversation-abc', # optional: groups traces into one session
'$ai_model' => 'gpt-5-mini',
'$ai_provider' => 'openai',
'$ai_input_tokens' => 10,
@@ -251,6 +263,7 @@ export const getManualSteps = (ctx: OnboardingComponentsContext): StepDefinition
'event' => '$ai_generation',
'properties' => [
'$ai_trace_id' => 'trace_id_here',
+ '$ai_session_id' => 'conversation-abc', // optional: groups traces into one session
'$ai_model' => 'gpt-5-mini',
'$ai_provider' => 'openai',
'$ai_input_tokens' => 10,
@@ -280,6 +293,7 @@ export const getManualSteps = (ctx: OnboardingComponentsContext): StepDefinition
"properties": {
"distinct_id": "user_123",
"$ai_trace_id": "trace_id_here",
+ "$ai_session_id": "conversation-abc",
"$ai_model": "gpt-5-mini",
"$ai_provider": "openai",
"$ai_input": [{"role": "user", "content": "Tell me a fun fact about hedgehogs"}],
diff --git a/docs/onboarding/ai-observability/mirascope.tsx b/docs/onboarding/ai-observability/mirascope.tsx
index d94be63731e2..9e5dc8d48c10 100644
--- a/docs/onboarding/ai-observability/mirascope.tsx
+++ b/docs/onboarding/ai-observability/mirascope.tsx
@@ -1,6 +1,7 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
+import { getOtelSessionIdStep } from './_snippets/otel-session-id'
export const getMirascopeSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
@@ -130,6 +131,7 @@ export const getMirascopeSteps = (ctx: OnboardingComponentsContext): StepDefinit
</>
),
},
+ getOtelSessionIdStep(ctx, { languages: ['Python'] }),
]
}
diff --git a/docs/onboarding/ai-observability/opentelemetry.tsx b/docs/onboarding/ai-observability/opentelemetry.tsx
index 3df2e02079ab..97f230d1fa84 100644
--- a/docs/onboarding/ai-observability/opentelemetry.tsx
+++ b/docs/onboarding/ai-observability/opentelemetry.tsx
@@ -1,6 +1,7 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
+import { getOtelSessionIdStep } from './_snippets/otel-session-id'
export const getOpenTelemetrySteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
@@ -233,6 +234,7 @@ export const getOpenTelemetrySteps = (ctx: OnboardingComponentsContext): StepDef
</>
),
},
+ getOtelSessionIdStep(ctx, { languages: ['Python', 'Node'] }),
{
title: 'Other instrumentations, direct OTLP, and troubleshooting',
badge: 'optional',
diff --git a/docs/onboarding/ai-observability/pydantic-ai.tsx b/docs/onboarding/ai-observability/pydantic-ai.tsx
index 67061ed24af6..3da540a70e73 100644
--- a/docs/onboarding/ai-observability/pydantic-ai.tsx
+++ b/docs/onboarding/ai-observability/pydantic-ai.tsx
@@ -1,6 +1,7 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
+import { getOtelSessionIdStep } from './_snippets/otel-session-id'
export const getPydanticAISteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
@@ -118,6 +119,7 @@ export const getPydanticAISteps = (ctx: OnboardingComponentsContext): StepDefini
</>
),
},
+ getOtelSessionIdStep(ctx, { languages: ['Python'] }),
]
}
diff --git a/docs/onboarding/ai-observability/semantic-kernel.tsx b/docs/onboarding/ai-observability/semantic-kernel.tsx
index 6d1c4cf5f530..dd819db65193 100644
--- a/docs/onboarding/ai-observability/semantic-kernel.tsx
+++ b/docs/onboarding/ai-observability/semantic-kernel.tsx
@@ -1,6 +1,7 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
+import { getOtelSessionIdStep } from './_snippets/otel-session-id'
export const getSemanticKernelSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
@@ -124,6 +125,7 @@ export const getSemanticKernelSteps = (ctx: OnboardingComponentsContext): StepDe
</>
),
},
+ getOtelSessionIdStep(ctx, { languages: ['Python'] }),
]
}
diff --git a/docs/onboarding/ai-observability/smolagents.tsx b/docs/onboarding/ai-observability/smolagents.tsx
index 571cbdbe05dd..41d51df6c615 100644
--- a/docs/onboarding/ai-observability/smolagents.tsx
+++ b/docs/onboarding/ai-observability/smolagents.tsx
@@ -1,6 +1,7 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
+import { getOtelSessionIdStep } from './_snippets/otel-session-id'
export const getSmolagentsSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
@@ -116,6 +117,7 @@ export const getSmolagentsSteps = (ctx: OnboardingComponentsContext): StepDefini
</>
),
},
+ getOtelSessionIdStep(ctx, { languages: ['Python'] }),
]
}
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 94b55df426e2..5a202911c83f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5676,6 +5676,26 @@ snapshots:
hash: v1.k794b7964.c9cf0f699197f208ec18e3ad326c29d43b8034f37f5fc101a9e25773510895a5.f_qTgpzSlQlCRirQv0iD791ajpL-x8WnVi8T8qNYr1o
scenes-app-ai-observability-conversation-display--tools--light:
hash: v1.k794b7964.cc6f7770155f4b720ff0597c3dd5deff699a267cfbdd8fe76a131cb51740215d.lKCAOsQBSoBkK46EHSYdGmWxAi4CQ4wUrx2J1iRF_f0
+ scenes-app-ai-observability-instrumentation-checklist-card--collecting--dark:
+ hash: v1.k794b7964.6f9f209d5daaf8573020fb50615421d426055c8090d0ee73a2629487d30cbf29.g4iTGpNCX68yiOgdFhRMYO2xEGf0WhTu4ji2Rqijroc
+ scenes-app-ai-observability-instrumentation-checklist-card--collecting--light:
+ hash: v1.k794b7964.5b59fa66c967caa25a3b42447aef2a9cc28e7a7297f68bf2c6ef52f93868340b.Vu-uZ6ASRxq7Xtww0upiQBEtM7K4W8bW1n2NbiZzAlY
+ scenes-app-ai-observability-instrumentation-checklist-card--first-load--dark:
+ hash: v1.k794b7964.6f9f209d5daaf8573020fb50615421d426055c8090d0ee73a2629487d30cbf29.TYHHCod2JSAu1qqe-WenUDbqhn0YlDo5gRGxTyanWoc
+ scenes-app-ai-observability-instrumentation-checklist-card--first-load--light:
+ hash: v1.k794b7964.5b59fa66c967caa25a3b42447aef2a9cc28e7a7297f68bf2c6ef52f93868340b.Ecas14W8dqnPe5sx8n14DBpWhPgJlRnmlhunbzkynfQ
+ scenes-app-ai-observability-instrumentation-checklist-card--passing--dark:
+ hash: v1.k794b7964.6f9f209d5daaf8573020fb50615421d426055c8090d0ee73a2629487d30cbf29.3G8C6lRoRMCOFPTyHUc1fUVrQ9SWQSBU5GDHVxfxkK0
+ scenes-app-ai-observability-instrumentation-checklist-card--passing--light:
+ hash: v1.k794b7964.5b59fa66c967caa25a3b42447aef2a9cc28e7a7297f68bf2c6ef52f93868340b.c-ITenm00lDNHO7YfYrQTyOgaWKwNMXQimGkVuPBJoo
+ scenes-app-ai-observability-instrumentation-checklist-card--warnings--dark:
+ hash: v1.k794b7964.6f9f209d5daaf8573020fb50615421d426055c8090d0ee73a2629487d30cbf29.U5AhEdEUppDlS_0j56Kjpl4cQqLYrXk-auBMToD6KV0
+ scenes-app-ai-observability-instrumentation-checklist-card--warnings--light:
+ hash: v1.k794b7964.5b59fa66c967caa25a3b42447aef2a9cc28e7a7297f68bf2c6ef52f93868340b.rtL19Q--FVLDDrBkmW1rNs9WmUOnseaz8nFeCHl6xEw
+ scenes-app-ai-observability-instrumentation-checklist-card--warnings-with-a-dismissal--dark:
+ hash: v1.k794b7964.6f9f209d5daaf8573020fb50615421d426055c8090d0ee73a2629487d30cbf29.stsWopH6BI50ASXjhDxCWn-Xa46oqy_cH4v0xAO4VIQ
+ scenes-app-ai-observability-instrumentation-checklist-card--warnings-with-a-dismissal--light:
+ hash: v1.k794b7964.5b59fa66c967caa25a3b42447aef2a9cc28e7a7297f68bf2c6ef52f93868340b.VU8b650GOEljJTYfBvHHLbvSMPSS35X5ZJzE63xAv6M
scenes-app-ai-observability-prompts--empty-state--dark:
hash: v1.k794b7964.34208d6347c35d9f570e8d107d47e7360aeed280aa1c87c92d25d25182ddeda5.JGg5hNoklZduz1RmWxJIGvp-ZKpgVuWio9YDjjPtGYU
scenes-app-ai-observability-prompts--empty-state--light:
@@ -5772,6 +5792,14 @@ snapshots:
hash: v1.k794b7964.e698a4305fbaedcc7431610ead1d8c58cdc002163c82264a737b19ebd15c5473.C2K9itQUN05MTTbR6wfR0l7F9XJJOR5Qbu7cC1YX8FQ
scenes-app-ai-observability-sentiment--tag-positive--light:
hash: v1.k794b7964.a89a05ca65812c28ec1b01e35aa4fc271a56c5d0ffd8fa3a9b9f479fd0f5cc3b.6ntaO7dlEBGxsnHCdx2Y7bfB28RtBznX3XNjcHdplZ8
+ scenes-app-ai-observability-sessions-empty-state--missing-session-instrumentation--dark:
+ hash: v1.k794b7964.f9a40c9c9f03ae241b4b55fc861c0fc470434eda5468b5048b5a99d47e146867.ePuPn0XEtunHjr_fFDGjjNkmusywUkQDNbVQeNzzC1E
+ scenes-app-ai-observability-sessions-empty-state--missing-session-instrumentation--light:
+ hash: v1.k794b7964.a9311249692deb4f164fdd7fda156bd5e8430f54c579bcd19c25b9a6a00a6e6e.3Z54wi0q6UHa39V4Y7Jaqwd5eH8hqZPIa_7vF1_hWus
+ scenes-app-ai-observability-sessions-empty-state--nothing-to-report--dark:
+ hash: v1.k794b7964.f9a40c9c9f03ae241b4b55fc861c0fc470434eda5468b5048b5a99d47e146867.1_xlNXQFwOVz40TTjGKiUtC1KXVUSCh7xoBRPd5zz0M
+ scenes-app-ai-observability-sessions-empty-state--nothing-to-report--light:
+ hash: v1.k794b7964.a9311249692deb4f164fdd7fda156bd5e8430f54c579bcd19c25b9a6a00a6e6e.JnEBbVENuBOYVpulIIDVeeenCYSQ_6w03e2oYFCEHjs
scenes-app-ai-observability-skills--skill-detail-side-by-side-above-2-xl-breakpoint--superwide--dark:
hash: v1.k794b7964.39ca895c7d8f0aafdd041e9578ce552d37520442d6df7a2d6d554dfdc032b5ba.dqxACinzs4OesVScmWpwTnoPMejqxFaHIHSidJnXKOs
scenes-app-ai-observability-skills--skill-detail-side-by-side-above-2-xl-breakpoint--superwide--light:
@@ -5796,6 +5824,10 @@ snapshots:
hash: v1.k794b7964.e3496790d775f03b10ed1bc55489b53bd68a8f1d5bf4c36e92e7c58cba73c3cf.LADKqNV4wMSksDi7YyzIWu2l9bwlxk97FCwHADpTgKc
scenes-app-ai-observability-trace--full-specific-event--light:
hash: v1.k794b7964.1ddd78a021ebd0cd3cea5ca666c614f58559072fe662f906a6088e55996c39f1.-Yz__8kqDKDJjJF22RHdo6Oc7bor-4yVH9B3QlcqUjU
+ scenes-app-ai-observability-trace--missing-span-instrumentation--dark:
+ hash: v1.k794b7964.55a8c1762dbc5754a88756dc4c6ed91c71a899cf2c9db890fc897b47ce491fa7.I9XZfEkQusLgygE5aoPMHaHd-2OhEQSjggO5HOz-k1Q
+ scenes-app-ai-observability-trace--missing-span-instrumentation--light:
+ hash: v1.k794b7964.b2063861e73507e5911e950992454c438283b7e0e4758c0bf3603f7884135817.S3qYv9943XR0LhtTIhSxe5CVCjR41ysrmgN0LfgwYrg
scenes-app-ai-observability-trace--without-content--dark:
hash: v1.k794b7964.065a9980470f35b7f51d4e5943b3990752fd4245f5537e67744683bc40e68f73.RrP5nFq9CZ--jD-uCfFALgQcsBQase6zp2D996rVI6k
scenes-app-ai-observability-trace--without-content--light:
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index d8dd285a4db8..c799f326deec 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -55,6 +55,7 @@ const ERROR_FILTER_ALLOW_LIST = [
'loadPrComments', // The Inbox report detail's PR comments section renders its own error state
'loadMonitoringSnapshot', // The managed warehouse Monitoring tab renders its own retry state
'loadMonitoringSeries', // The managed warehouse Monitoring tab renders its own partial/error state
+ 'loadInstrumentationChecklist', // AI observability hides its checklist entirely rather than accusing a project on data it could not read
]
/*
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index d7dd21e10cf7..dfb9afbd5bf9 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -185,6 +185,7 @@ export const FEATURE_FLAGS = {
// Feature flags used to control opt-in for different behaviors, should not be removed
ACCESS_CONTROL_DETAIL_PANEL: 'access-control-detail-panel', // owner: @a-lider #team-platform-features, gates the member and role access detail side panel
+ AI_OBSERVABILITY_INSTRUMENTATION_CHECKLIST: 'ai-observability-instrumentation-checklist', // owner: #team-ai-observability, gates the instrumentation checklist card and empty states
AI_OBSERVABILITY_SELF_DRIVING: 'ai-observability-daily-digest-scout', // owner: #team-ai-observability, gates the AI observability Self-driving tab
AI_TRAINING: 'ai-training', // owner: @nicowaltz #team-replay #ai-research, gates the AI training opt-out UI and API enforcement
AUDIT_LOGS_ACCESS: 'audit-logs-access', // owner: #team-platform-features, used to control access to audit logs
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 1decbf98a31a..aaa902a6bad8 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -139,6 +139,9 @@ class Feature(StrEnum):
POSTHOG_AI = "posthog_ai"
MCP = "mcp"
SEMANTIC_SEARCH = "semantic_search"
+ # A 30 day aggregate that runs on every AI observability dashboard mount and trace view, so its
+ # load is worth attributing separately from the tab queries it sits alongside.
+ INSTRUMENTATION_CHECKLIST = "instrumentation_checklist"
class FallbackTags(TypedDict):
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 779643bda0a0..fd45261c127d 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -778,6 +778,11 @@ SPECTACULAR_SETTINGS = {
# choice set (top-level column vs span attribute vs resource attribute).
"SpanPropertyTypeEnum": ["span", "span_attribute", "span_resource_attribute"],
"LogsViewColumnTypeEnum": ["timestamp", "level", "source", "trace_id", "span_id", "message", "custom"],
+ # The AI observability instrumentation checklist exposes the same key set twice: as `key` on a
+ # graded check and as `check` on the dismiss/restore body. Mirrors CheckKey in
+ # products/ai_observability/backend/instrumentation_checklist/grading.py; a member added there
+ # changes the hash, so this warning comes back rather than drifting silently.
+ "AIObservabilityInstrumentationCheckEnum": ["sessions", "tool_calls", "user_identity", "trace_structure"],
# LoopTriggerWrite.type and LoopPreviewRequest.trigger_type share the same
# schedule/github/api choice set — pin them to a single named enum.
"LoopTriggerTypeEnum": ["schedule", "github", "api"],
diff --git a/products/ai_observability/backend/api/__init__.py b/products/ai_observability/backend/api/__init__.py
index 37d505233b75..7584c9b457a1 100644
--- a/products/ai_observability/backend/api/__init__.py
+++ b/products/ai_observability/backend/api/__init__.py
@@ -8,6 +8,7 @@ from .evaluation_directories import EvaluationDirectoryViewSet
from .evaluation_reports import EvaluationReportViewSet
from .evaluation_runs import EvaluationRunViewSet
from .evaluations import EvaluationViewSet
+from .instrumentation_checklist import AIObservabilityInstrumentationChecklistViewSet
from .models import LLMModelsViewSet
from .offline_evaluations import AIObservabilityOfflineEvaluationsViewSet
from .parser_recipes import ParserRecipeViewSet
@@ -27,6 +28,7 @@ __all__ = [
"ClusteringConfigViewSet",
"ClusteringJobViewSet",
"AIObservabilityClusteringRunViewSet",
+ "AIObservabilityInstrumentationChecklistViewSet",
"LLMModelsViewSet",
"LLMProxyViewSet",
"AIObservabilityTextReprViewSet",
diff --git a/products/ai_observability/backend/api/instrumentation_checklist.py b/products/ai_observability/backend/api/instrumentation_checklist.py
new file mode 100644
index 000000000000..e7e81d011da2
--- /dev/null
+++ b/products/ai_observability/backend/api/instrumentation_checklist.py
@@ -0,0 +1,153 @@
+from typing import cast
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+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
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.monitoring import monitor
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.clickhouse.query_tagging import Feature, tag_queries
+from posthog.models.scoping.manager import TeamScopedQuerySet
+from posthog.models.user import User
+
+from ..instrumentation_checklist.grading import CheckKey, CheckStatus, grade_checklist
+from ..instrumentation_checklist.stats import WINDOW_DAYS, fetch_checklist_stats
+from ..models.instrumentation_checklist import AIObservabilityChecklistItemState
+from .metrics import llma_track_latency
+
+CHECK_KEYS = [key.value for key in CheckKey]
+CHECK_STATUSES = [check_status.value for check_status in CheckStatus]
+
+
+class InstrumentationCheckSerializer(serializers.Serializer):
+ key = serializers.ChoiceField(
+ choices=CHECK_KEYS,
+ help_text="Identifier of the check. Stable across statuses, so a surface can key its own copy off it.",
+ )
+ status = serializers.ChoiceField(
+ choices=CHECK_STATUSES,
+ help_text=(
+ "How the check graded: 'ok' when the instrumentation is present, 'warning' when it is absent, "
+ "'pending' when the project has too little traffic to judge, and 'dismissed' when someone on the "
+ "team marked the check as not applicable."
+ ),
+ )
+ title = serializers.CharField(help_text="Short label for the check, the same for every status.")
+ detail = serializers.CharField(
+ help_text=(
+ "Sentence explaining what the counts mean and, for a warning, what to send. A dismissed check keeps "
+ "the sentence its counts earned."
+ ),
+ )
+ docs_url = serializers.URLField(help_text="Documentation page covering how to send the missing instrumentation.")
+ stats = serializers.DictField(
+ child=serializers.IntegerField(),
+ help_text="Counts this check was graded from, over the same window. Which counts appear depends on the check.",
+ )
+
+
+class InstrumentationChecklistSerializer(serializers.Serializer):
+ window_days = serializers.IntegerField(help_text="Length in days of the event window the checks were graded over.")
+ checks = InstrumentationCheckSerializer(
+ many=True,
+ help_text="Every check, graded. Checks are always all returned, including the ones that pass.",
+ )
+
+
+class InstrumentationCheckActionSerializer(serializers.Serializer):
+ check = serializers.ChoiceField(choices=CHECK_KEYS, help_text="Key of the check to dismiss or restore.")
+
+
+class _SingletonSchema(PostHogAutoSchema):
+ """Prevents drf-spectacular from wrapping the ``list`` response in an array.
+
+ The checklist is one graded object per project, not a collection.
+ """
+
+ def _is_list_view(self, serializer: object = None) -> bool:
+ return False
+
+
+class AIObservabilityInstrumentationChecklistViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ """Instrumentation coverage for a project's AI events."""
+
+ schema = _SingletonSchema()
+ scope_object = "llm_analytics"
+ # Without this, AccessControlPermission falls through to has_any_specific_access_for_resource, so
+ # a grant on one llm_analytics object (a single review queue, say) would let a user whose
+ # resource-level access is "none" read these project-wide aggregates and flip the project-wide
+ # dismissal state. Nothing catches it later: this is a plain ViewSet with no queryset and no
+ # get_object, so has_object_permission never runs as a second gate.
+ requires_resource_level_access = True
+ # ScopeBasePermission maps only the default action names, so leaving a custom action off this list
+ # gives it a null scope, which 403s every personal API key, OAuth token and MCP call while browser
+ # sessions keep working. Note this replaces the default write actions rather than extending them,
+ # so any future create/update/destroy has to be added here too.
+ scope_object_write_actions = ["dismiss", "restore"]
+ serializer_class = _FallbackSerializer
+
+ @property
+ def _checklist_team_id(self) -> int:
+ # RootTeamMixin.save() stores rows against the parent team, so reads and the update_or_create
+ # lookup have to use that same id or a repeat dismissal would insert a duplicate.
+ return self.team.parent_team_id or self.team_id
+
+ def _states(self) -> TeamScopedQuerySet[AIObservabilityChecklistItemState]:
+ return AIObservabilityChecklistItemState.objects.for_team(self._checklist_team_id, canonical=True).filter(
+ scope__isnull=True
+ )
+
+ def _graded_checklist(self) -> 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.
+ 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))
+ serializer = InstrumentationChecklistSerializer({"window_days": WINDOW_DAYS, "checks": checks})
+ return Response(serializer.data)
+
+ @extend_schema(
+ 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:
+ """Grade every instrumentation check for this project."""
+ return self._graded_checklist()
+
+ @validated_request(
+ request_serializer=InstrumentationCheckActionSerializer,
+ responses={200: OpenApiResponse(response=InstrumentationChecklistSerializer)},
+ )
+ @action(detail=False, methods=["post"])
+ @llma_track_latency("llma_instrumentation_checklist_dismiss")
+ @monitor(feature=None, endpoint="llma_instrumentation_checklist_dismiss", method="POST")
+ def dismiss(self, request: ValidatedRequest, **kwargs) -> Response:
+ """Mark a check as not applicable to this project."""
+ self._states().update_or_create(
+ team_id=self._checklist_team_id,
+ check_key=request.validated_data["check"],
+ scope=None,
+ defaults={
+ "status": AIObservabilityChecklistItemState.Status.DISMISSED,
+ "updated_by": cast(User, request.user),
+ },
+ )
+ return self._graded_checklist()
+
+ @validated_request(
+ request_serializer=InstrumentationCheckActionSerializer,
+ responses={200: OpenApiResponse(response=InstrumentationChecklistSerializer)},
+ )
+ @action(detail=False, methods=["post"])
+ @llma_track_latency("llma_instrumentation_checklist_restore")
+ @monitor(feature=None, endpoint="llma_instrumentation_checklist_restore", method="POST")
+ def restore(self, request: ValidatedRequest, **kwargs) -> Response:
+ """Bring a dismissed check back into grading."""
+ self._states().filter(check_key=request.validated_data["check"]).delete()
+ return self._graded_checklist()
diff --git a/products/ai_observability/backend/api/test/test_instrumentation_checklist.py b/products/ai_observability/backend/api/test/test_instrumentation_checklist.py
new file mode 100644
index 000000000000..43f4b4110198
--- /dev/null
+++ b/products/ai_observability/backend/api/test/test_instrumentation_checklist.py
@@ -0,0 +1,238 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from unittest.mock import patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.clickhouse.query_tagging import Feature, get_query_tags
+from posthog.constants import AvailableFeature
+from posthog.models.ai_events.test_util import bulk_create_ai_events
+from posthog.models.organization import OrganizationMembership
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.team import Team
+from posthog.models.user import User
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.ai_observability.backend.instrumentation_checklist.grading import VOLUME_FLOOR, ChecklistStats
+from products.ai_observability.backend.instrumentation_checklist.stats import WINDOW_DAYS
+from products.ai_observability.backend.models.instrumentation_checklist import AIObservabilityChecklistItemState
+from products.ai_observability.backend.models.review_queues import ReviewQueue
+
+CHECK_FIELDS = {"key", "status", "title", "detail", "docs_url", "stats"}
+
+
+def endpoint(team_id: int, suffix: str = "") -> str:
+ return f"/api/projects/{team_id}/ai_observability/instrumentation_checklist/{suffix}"
+
+
+def check(body: dict[str, Any], key: str) -> dict[str, Any]:
+ return next(item for item in body["checks"] if item["key"] == key)
+
+
+def generation(
+ team: Team,
+ index: int,
+ *,
+ distinct_id: str | None = None,
+ properties: dict[str, str] | None = None,
+) -> dict[str, Any]:
+ trace_id = f"trace-{index}"
+ return {
+ "event": "$ai_generation",
+ # An unset distinct_id mirrors the un-instrumented shape: the SDK falls back to the trace id.
+ "distinct_id": distinct_id or trace_id,
+ "team": team,
+ "timestamp": datetime.now(UTC) - timedelta(days=1),
+ "properties": {"$ai_trace_id": trace_id, **(properties or {})},
+ }
+
+
+class TestInstrumentationChecklist(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # Exactly enough generations to clear the volume floor, one of them instrumented for
+ # sessions and user identity so the payload carries both an `ok` and a `warning`.
+ bulk_create_ai_events(
+ [
+ *(generation(self.team, index) for index in range(VOLUME_FLOOR - 1)),
+ generation(
+ self.team,
+ VOLUME_FLOOR - 1,
+ distinct_id="user-42",
+ properties={"$ai_session_id": "session-1"},
+ ),
+ ]
+ )
+
+ @parameterized.expand([("list", ""), ("dismiss", "dismiss/"), ("restore", "restore/")])
+ def test_the_clickhouse_read_carries_a_feature_tag(self, _name: str, suffix: str) -> None:
+ # sync_execute rejects a query missing the feature tag, but only when DEBUG and not TEST,
+ # so asserting on the response status would pass here while a browser gets a 500. Read the
+ # tag at the point the query would run instead.
+ seen: list[Feature | None] = []
+
+ def record(team: Team) -> 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,
+ events_with_parent=0,
+ total_events=0,
+ )
+
+ with patch(
+ "products.ai_observability.backend.api.instrumentation_checklist.fetch_checklist_stats",
+ side_effect=record,
+ ):
+ if suffix:
+ response = self.client.post(endpoint(self.team.pk, suffix), {"check": "sessions"}, format="json")
+ else:
+ response = self.client.get(endpoint(self.team.pk))
+
+ # Asserting the status too, so a stub that raises cannot leave the tag recorded and the
+ # request failing while this still passes.
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert seen == [Feature.INSTRUMENTATION_CHECKLIST]
+
+ def test_get_returns_every_check_graded_over_the_teams_events(self) -> None:
+ response = self.client.get(endpoint(self.team.pk))
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = response.json()
+ assert body["window_days"] == WINDOW_DAYS
+ assert [(item["key"], item["status"]) for item in body["checks"]] == [
+ ("sessions", "ok"),
+ ("tool_calls", "warning"),
+ ("user_identity", "ok"),
+ ("trace_structure", "warning"),
+ ]
+ assert all(set(item) == CHECK_FIELDS for item in body["checks"])
+ assert check(body, "sessions")["stats"] == {
+ "generations": VOLUME_FLOOR,
+ "events_with_session": 1,
+ "events_declining_session": 0,
+ }
+
+ def test_dismissal_mutes_a_check_until_it_is_restored(self) -> None:
+ dismissed = self.client.post(endpoint(self.team.pk, "dismiss/"), {"check": "tool_calls"})
+
+ assert dismissed.status_code == status.HTTP_200_OK, dismissed.content
+ assert check(dismissed.json(), "tool_calls")["status"] == "dismissed"
+ # The muted row keeps the sentence its counts earned, so it still says what "Recheck" would re-evaluate.
+ assert "No tool calls recorded" in check(dismissed.json(), "tool_calls")["detail"]
+ assert check(self.client.get(endpoint(self.team.pk)).json(), "tool_calls")["status"] == "dismissed"
+ state = AIObservabilityChecklistItemState.objects.for_team(self.team.pk).get(check_key="tool_calls")
+ assert state.updated_by == self.user
+
+ repeated = self.client.post(endpoint(self.team.pk, "dismiss/"), {"check": "tool_calls"})
+ assert repeated.status_code == status.HTTP_200_OK, repeated.content
+
+ restored = self.client.post(endpoint(self.team.pk, "restore/"), {"check": "tool_calls"})
+ assert restored.status_code == status.HTTP_200_OK, restored.content
+ assert check(restored.json(), "tool_calls")["status"] == "warning"
+ assert not AIObservabilityChecklistItemState.objects.for_team(self.team.pk).exists()
+
+ @parameterized.expand([("dismiss",), ("restore",)])
+ def test_an_unknown_check_is_rejected_rather_than_stored(self, action: str) -> None:
+ response = self.client.post(endpoint(self.team.pk, f"{action}/"), {"check": "wibble"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert not AIObservabilityChecklistItemState.objects.for_team(self.team.pk).exists()
+
+ def test_a_dismissal_does_not_reach_another_project(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other project")
+
+ dismissed = self.client.post(endpoint(other_team.pk, "dismiss/"), {"check": "tool_calls"})
+ assert dismissed.status_code == status.HTTP_200_OK, dismissed.content
+
+ body = self.client.get(endpoint(self.team.pk)).json()
+ assert check(body, "tool_calls")["status"] == "warning"
+
+ def test_a_dismissal_from_a_child_environment_is_durable_and_repeatable(self) -> None:
+ # RootTeamMixin.save() rewrites the row onto the parent team, so a lookup keyed on the
+ # environment's own id would miss the row it just wrote: the read shows the check
+ # undismissed, and the second dismissal violates the partial unique constraint.
+ environment = Team.objects.create(
+ organization=self.organization, project=self.project, parent_team=self.team, name="Staging"
+ )
+
+ first = self.client.post(endpoint(environment.pk, "dismiss/"), {"check": "tool_calls"})
+ assert first.status_code == status.HTTP_200_OK, first.content
+ assert check(self.client.get(endpoint(environment.pk)).json(), "tool_calls")["status"] == "dismissed"
+
+ second = self.client.post(endpoint(environment.pk, "dismiss/"), {"check": "tool_calls"})
+ assert second.status_code == status.HTTP_200_OK, second.content
+ assert check(second.json(), "tool_calls")["status"] == "dismissed"
+
+
+class TestInstrumentationChecklistResourceLevelAccess(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ queue = ReviewQueue.objects.create(team=self.team, name="Support queue", created_by=self.user)
+ member = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ membership = OrganizationMembership.objects.get(user=member, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="llm_analytics",
+ access_level="none",
+ organization_member=membership,
+ )
+ # Granting editor rather than viewer on the queue clears has_any_specific_access_for_resource
+ # at both the viewer level the read needs and the editor level the writes need, so all three
+ # actions reach the requires_resource_level_access branch instead of being turned away for
+ # the wrong reason.
+ AccessControl.objects.create(
+ team=self.team,
+ resource="llm_analytics",
+ resource_id=str(queue.id),
+ access_level="editor",
+ organization_member=membership,
+ )
+ self.client.force_login(member)
+
+ @parameterized.expand([("list", ""), ("dismiss", "dismiss/"), ("restore", "restore/")])
+ def test_a_grant_on_one_object_does_not_reach_the_project_wide_checklist(self, _name: str, suffix: str) -> None:
+ if suffix:
+ response = self.client.post(endpoint(self.team.pk, suffix), {"check": "tool_calls"})
+ else:
+ response = self.client.get(endpoint(self.team.pk))
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ assert not AIObservabilityChecklistItemState.objects.for_team(self.team.pk).exists()
+
+
+class TestInstrumentationChecklistApiKeyAccess(ClickhouseTestMixin, APIBaseTest):
+ @parameterized.expand([("dismiss",), ("restore",)])
+ def test_a_personal_api_key_can_reach_the_custom_actions(self, action: str) -> None:
+ raw_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="checklist",
+ user=self.user,
+ secure_value=hash_key_value(raw_key),
+ scopes=["llm_analytics:write"],
+ )
+ # force_login skips APIScopePermission entirely, so only a real token exercises the scope wiring.
+ self.client.logout()
+
+ response = self.client.post(
+ endpoint(self.team.pk, f"{action}/"),
+ {"check": "tool_calls"},
+ headers={"authorization": f"Bearer {raw_key}"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.content
diff --git a/products/ai_observability/backend/instrumentation_checklist/__init__.py b/products/ai_observability/backend/instrumentation_checklist/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/ai_observability/backend/instrumentation_checklist/grading.py b/products/ai_observability/backend/instrumentation_checklist/grading.py
new file mode 100644
index 000000000000..1b85a243f515
--- /dev/null
+++ b/products/ai_observability/backend/instrumentation_checklist/grading.py
@@ -0,0 +1,211 @@
+from collections.abc import Iterable
+from enum import StrEnum
+
+from posthog.dataclasses import frozen
+
+VOLUME_FLOOR = 20
+
+# A check gets its own page where one covers the instrumentation it asks for, and the installation
+# page otherwise. Sending a reader to a page that does not answer the question the check just raised
+# is worse than leaving them on installation.
+_INSTALLATION_DOCS_URL = "https://posthog.com/docs/ai-observability/installation"
+_SESSIONS_DOCS_URL = "https://posthog.com/docs/ai-observability/sessions"
+_TOOLS_DOCS_URL = "https://posthog.com/docs/ai-observability/tools"
+
+_PENDING_GENERATIONS = f"Still collecting data. This check runs once there are {VOLUME_FLOOR} generations."
+_PENDING_AI_EVENTS = f"Still collecting data. This check runs once there are {VOLUME_FLOOR} AI events."
+
+
+class CheckKey(StrEnum):
+ SESSIONS = "sessions"
+ TOOL_CALLS = "tool_calls"
+ USER_IDENTITY = "user_identity"
+ TRACE_STRUCTURE = "trace_structure"
+
+
+class CheckStatus(StrEnum):
+ OK = "ok"
+ WARNING = "warning"
+ PENDING = "pending"
+ DISMISSED = "dismissed"
+
+
+@frozen
+class ChecklistStats:
+ generations: int
+ 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
+
+ def __post_init__(self) -> None:
+ counted = self.generations + self.spans
+ if self.total_events < counted:
+ raise ValueError(
+ f"total_events ({self.total_events}) is below the {counted} generations and spans already counted, "
+ "so the trace structure check would be graded against a denominator that cannot be real"
+ )
+
+
+@frozen
+class GradedCheck:
+ key: CheckKey
+ status: CheckStatus
+ title: str
+ detail: str
+ docs_url: str
+ stats: dict[str, int]
+
+
+@frozen
+class _CheckInputs:
+ key: CheckKey
+ title: str
+ denominator: int
+ has_signal: bool
+ warning_detail: str
+ ok_detail: str
+ pending_detail: str
+ docs_url: str
+ stats: dict[str, int]
+
+
+def _sessions(stats: ChecklistStats) -> _CheckInputs:
+ # A missing session id cannot tell incomplete instrumentation apart from a workload that
+ # genuinely finishes in one trace, so a project that sent an explicit null has answered the
+ # question and the copy has to reflect which of the two earned the ok.
+ if stats.events_with_session > 0:
+ ok_detail = "Traces are grouping into sessions."
+ else:
+ ok_detail = "Traces are marked as finishing in one trace, so there is nothing to group."
+
+ return _CheckInputs(
+ key=CheckKey.SESSIONS,
+ title="Sessions",
+ denominator=stats.generations,
+ has_signal=stats.events_with_session > 0 or stats.events_declining_session > 0,
+ warning_detail=(
+ "No traces include $ai_session_id. If your product has multi-turn conversations, setting it lets us "
+ "group them into sessions. Workloads that are complete in one trace, like batch jobs or one-shot "
+ "generation, do not need it. Send $ai_session_id as null on those to say so."
+ ),
+ ok_detail=ok_detail,
+ pending_detail=_PENDING_GENERATIONS,
+ docs_url=_SESSIONS_DOCS_URL,
+ stats={
+ "generations": stats.generations,
+ "events_with_session": stats.events_with_session,
+ "events_declining_session": stats.events_declining_session,
+ },
+ )
+
+
+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:
+ 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."
+ )
+ else:
+ warning_detail = (
+ "No tool calls recorded. If your app uses tool or function calling, capture it to see which tools run "
+ "and how often."
+ )
+
+ return _CheckInputs(
+ key=CheckKey.TOOL_CALLS,
+ title="Tool calls",
+ denominator=stats.generations,
+ has_signal=stats.generations_with_tool_calls > 0,
+ warning_detail=warning_detail,
+ ok_detail="Tool calls are being recorded.",
+ pending_detail=_PENDING_GENERATIONS,
+ docs_url=_TOOLS_DOCS_URL,
+ stats={
+ "generations": stats.generations,
+ "generations_with_tool_calls": stats.generations_with_tool_calls,
+ "generations_with_tools_declared": stats.generations_with_tools_declared,
+ },
+ )
+
+
+def _user_identity(stats: ChecklistStats) -> _CheckInputs:
+ return _CheckInputs(
+ key=CheckKey.USER_IDENTITY,
+ title="User identity",
+ denominator=stats.sdk_generations,
+ has_signal=stats.sdk_generations_identified > 0,
+ warning_detail=(
+ "Generations are arriving with their trace ID as the distinct ID, so usage and cost cannot be tied to "
+ "people. Set distinct_id to your own user identifier."
+ ),
+ ok_detail="AI events are attributed to identified users.",
+ pending_detail=(
+ f"This check runs once there are {VOLUME_FLOOR} generations from a PostHog SDK. Generations sent over "
+ "OpenTelemetry are not counted, because we cannot tell whether they are identified."
+ ),
+ docs_url=_INSTALLATION_DOCS_URL,
+ stats={
+ "sdk_generations": stats.sdk_generations,
+ "sdk_generations_identified": stats.sdk_generations_identified,
+ },
+ )
+
+
+def _trace_structure(stats: ChecklistStats) -> _CheckInputs:
+ return _CheckInputs(
+ key=CheckKey.TRACE_STRUCTURE,
+ title="Trace structure",
+ # Flooring on generations would leave a project that only emits spans and traces pending forever.
+ denominator=stats.total_events,
+ has_signal=stats.spans > 0 or stats.events_with_parent > 0,
+ warning_detail=(
+ "Without spans, a trace shows LLM calls but not the retrieval, chains or sub-agent steps around them."
+ ),
+ # A generation carrying $ai_parent_id is enough structure to grade ok even with no $ai_span
+ # event, so the copy cannot name spans.
+ ok_detail="Traces show the steps around your LLM calls.",
+ pending_detail=_PENDING_AI_EVENTS,
+ docs_url=_INSTALLATION_DOCS_URL,
+ stats={
+ "total_events": stats.total_events,
+ "spans": stats.spans,
+ "events_with_parent": stats.events_with_parent,
+ },
+ )
+
+
+def _grade(inputs: _CheckInputs, *, dismissed: bool) -> GradedCheck:
+ if inputs.denominator < VOLUME_FLOOR:
+ graded_status = CheckStatus.PENDING
+ detail = inputs.pending_detail
+ elif not inputs.has_signal:
+ graded_status = CheckStatus.WARNING
+ detail = inputs.warning_detail
+ else:
+ graded_status = CheckStatus.OK
+ detail = inputs.ok_detail
+
+ # Dismissal only overrides the status. The detail stays the one the counts earned, so a muted row
+ # still says what the user silenced and what "Recheck" would re-evaluate.
+ return GradedCheck(
+ key=inputs.key,
+ status=CheckStatus.DISMISSED if dismissed else graded_status,
+ title=inputs.title,
+ detail=detail,
+ docs_url=inputs.docs_url,
+ stats=inputs.stats,
+ )
+
+
+def grade_checklist(stats: ChecklistStats, dismissed_keys: Iterable[str]) -> list[GradedCheck]:
+ dismissed = set(dismissed_keys)
+ checks = [build(stats) for build in (_sessions, _tool_calls, _user_identity, _trace_structure)]
+ return [_grade(check, dismissed=check.key in dismissed) for check in checks]
diff --git a/products/ai_observability/backend/instrumentation_checklist/stats.py b/products/ai_observability/backend/instrumentation_checklist/stats.py
new file mode 100644
index 000000000000..667e801f66fa
--- /dev/null
+++ b/products/ai_observability/backend/instrumentation_checklist/stats.py
@@ -0,0 +1,92 @@
+from collections.abc import Sequence
+from datetime import UTC, datetime, timedelta
+
+from posthog.hogql import ast
+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 .grading import ChecklistStats
+
+# Matches ai_events' `retention_days Int16 DEFAULT 30`, so the window never asks for rows the
+# table has already dropped.
+WINDOW_DAYS = 30
+
+# 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 raises instead of shifting a count onto the wrong check.
+_STATS_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,
+ countIf(has_parent) AS events_with_parent,
+ count() AS total_events
+FROM (
+ SELECT
+ event = '$ai_generation' AS is_generation,
+ event = '$ai_span' AS is_span,
+ -- Any of the four event types can carry $ai_session_id, and the Sessions tab reads it off
+ -- whichever one has it (see queries/sessions.sql), so flooring on generations alone would
+ -- warn about a missing session id at a project whose Sessions tab works.
+ coalesce(session_id, '') != '' AS has_session,
+ -- An explicit null is a project saying this workload finishes in one trace, which is an
+ -- answer rather than a gap. JSONType reads absent and null alike, so JSONHas is what
+ -- separates them, and requiring type Null keeps an empty string (usually an unset
+ -- variable) out of the opt-out.
+ 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
+ FROM posthog.ai_events AS ai_events
+ WHERE event IN {checklist_events}
+ AND timestamp >= {date_from}
+)
+"""
+
+
+def _row_to_stats(columns: Sequence[str], row: Sequence[int]) -> ChecklistStats:
+ return ChecklistStats(**dict(zip(columns, row)))
+
+
+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.
+ 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)),
+ },
+ team=team,
+ query_type="AIObservabilityInstrumentationChecklist",
+ fall_back_to_events=False,
+ )
+ return _row_to_stats(result.columns, result.results[0])
diff --git a/products/ai_observability/backend/instrumentation_checklist/test/test_grading.py b/products/ai_observability/backend/instrumentation_checklist/test/test_grading.py
new file mode 100644
index 000000000000..4cd55b26b2ec
--- /dev/null
+++ b/products/ai_observability/backend/instrumentation_checklist/test/test_grading.py
@@ -0,0 +1,378 @@
+from collections.abc import Iterable
+
+import pytest
+
+from parameterized import parameterized
+
+from products.ai_observability.backend.instrumentation_checklist.grading import (
+ VOLUME_FLOOR,
+ CheckKey,
+ ChecklistStats,
+ CheckStatus,
+ GradedCheck,
+ grade_checklist,
+)
+
+SESSIONS_WARNING = (
+ "No traces include $ai_session_id. If your product has multi-turn conversations, setting it lets us group them "
+ "into sessions. Workloads that are complete in one trace, like batch jobs or one-shot generation, do not need it. "
+ "Send $ai_session_id as null on those to say so."
+)
+SESSIONS_OK = "Traces are grouping into sessions."
+SESSIONS_OK_DECLINED = "Traces are marked as finishing in one trace, so there is nothing to group."
+TOOL_CALLS_WARNING_DECLARED = (
+ "No tool calls recorded, but you are sending tool definitions. If your agent does call tools, check that your "
+ "SDK version reports them."
+)
+TOOL_CALLS_WARNING_NOT_DECLARED = (
+ "No tool calls recorded. If your app uses tool or function calling, capture it to see which tools run and how "
+ "often."
+)
+TOOL_CALLS_OK = "Tool calls are being recorded."
+USER_IDENTITY_WARNING = (
+ "Generations are arriving with their trace ID as the distinct ID, so usage and cost cannot be tied to people. "
+ "Set distinct_id to your own user identifier."
+)
+USER_IDENTITY_OK = "AI events are attributed to identified users."
+USER_IDENTITY_PENDING = (
+ "This check runs once there are 20 generations from a PostHog SDK. Generations sent over OpenTelemetry are not "
+ "counted, because we cannot tell whether they are identified."
+)
+TRACE_STRUCTURE_WARNING = (
+ "Without spans, a trace shows LLM calls but not the retrieval, chains or sub-agent steps around them."
+)
+TRACE_STRUCTURE_OK = "Traces show the steps around your LLM calls."
+PENDING_GENERATIONS = "Still collecting data. This check runs once there are 20 generations."
+PENDING_AI_EVENTS = "Still collecting data. This check runs once there are 20 AI events."
+
+# The denominator each check floors on, paired with the count that clears its warning.
+GENERATION_DENOMINATED = [
+ (CheckKey.SESSIONS, "generations", "events_with_session"),
+ (CheckKey.TOOL_CALLS, "generations", "generations_with_tool_calls"),
+ (CheckKey.USER_IDENTITY, "sdk_generations", "sdk_generations_identified"),
+]
+
+
+def _stats(**overrides: int) -> ChecklistStats:
+ counts = {
+ "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,
+ "events_with_parent": 0,
+ }
+ counts.update(overrides)
+ if "total_events" not in overrides:
+ counts["total_events"] = counts["generations"] + counts["spans"]
+ return ChecklistStats(**counts)
+
+
+def _graded(stats: ChecklistStats, key: CheckKey, dismissed_keys: Iterable[str] = ()) -> GradedCheck:
+ return next(check for check in grade_checklist(stats, dismissed_keys) if check.key == key)
+
+
+class TestGradeChecklist:
+ def test_grades_every_check_exactly_once_in_key_order(self) -> None:
+ assert [check.key for check in grade_checklist(_stats(), ())] == list(CheckKey)
+
+ @parameterized.expand(
+ [
+ (f"{key.value}_{generations}_signal_{signal}", key, denominator, field, generations, signal, expected)
+ for key, denominator, field in GENERATION_DENOMINATED
+ for generations, signal, expected in [
+ (VOLUME_FLOOR - 1, 0, CheckStatus.PENDING),
+ (VOLUME_FLOOR - 1, VOLUME_FLOOR - 1, CheckStatus.PENDING),
+ (VOLUME_FLOOR, 0, CheckStatus.WARNING),
+ (VOLUME_FLOOR, 1, CheckStatus.OK),
+ (VOLUME_FLOOR + 1, 0, CheckStatus.WARNING),
+ ]
+ ]
+ )
+ def test_volume_floor_boundary_for_generation_denominated_checks(
+ self,
+ _name: str,
+ key: CheckKey,
+ denominator: str,
+ field: str,
+ generations: int,
+ signal: int,
+ expected: CheckStatus,
+ ) -> None:
+ stats = _stats(**{"generations": generations, denominator: generations, field: signal})
+ assert _graded(stats, key).status == expected
+
+ @parameterized.expand(
+ [
+ ("below_floor", VOLUME_FLOOR - 1, CheckStatus.PENDING),
+ ("at_floor", VOLUME_FLOOR, CheckStatus.WARNING),
+ ("above_floor", VOLUME_FLOOR + 1, CheckStatus.WARNING),
+ ]
+ )
+ def test_volume_floor_boundary_for_trace_structure(
+ self, _name: str, total_events: int, expected: CheckStatus
+ ) -> None:
+ stats = _stats(total_events=total_events, spans=0, events_with_parent=0)
+ assert _graded(stats, CheckKey.TRACE_STRUCTURE).status == expected
+
+ @parameterized.expand([(key.value, key) for key, *_ in GENERATION_DENOMINATED])
+ def test_generation_denominated_checks_stay_pending_at_a_spans_only_project(
+ self, _name: str, key: CheckKey
+ ) -> None:
+ stats = _stats(generations=0, spans=25, events_with_parent=25)
+ assert _graded(stats, key).status == CheckStatus.PENDING
+
+ @parameterized.expand(
+ [
+ ("declined_only", 0, 5, CheckStatus.OK, SESSIONS_OK_DECLINED),
+ ("grouped_only", 5, 0, CheckStatus.OK, SESSIONS_OK),
+ # A project instrumenting a chat flow while declining its batch job has both, and the
+ # grouping it does have is the more useful thing to report.
+ ("both", 5, 5, CheckStatus.OK, SESSIONS_OK),
+ ("neither", 0, 0, CheckStatus.WARNING, SESSIONS_WARNING),
+ ]
+ )
+ def test_declining_a_session_answers_the_sessions_check(
+ self, _name: str, with_session: int, declining: int, expected: CheckStatus, expected_detail: str
+ ) -> None:
+ stats = _stats(generations=40, events_with_session=with_session, events_declining_session=declining)
+ graded = _graded(stats, CheckKey.SESSIONS)
+ assert (graded.status, graded.detail) == (expected, expected_detail)
+
+ def test_declining_a_session_cannot_lift_a_project_off_the_volume_floor(self) -> None:
+ stats = _stats(generations=VOLUME_FLOOR - 1, events_declining_session=VOLUME_FLOOR - 1)
+ assert _graded(stats, CheckKey.SESSIONS).status == CheckStatus.PENDING
+
+ def test_trace_structure_is_graded_at_a_spans_only_project(self) -> None:
+ stats = _stats(generations=0, spans=25)
+ assert _graded(stats, CheckKey.TRACE_STRUCTURE).status == CheckStatus.OK
+
+ def test_trace_structure_warns_when_only_traces_arrive(self) -> None:
+ stats = _stats(generations=0, spans=0, events_with_parent=0, total_events=25)
+ assert _graded(stats, CheckKey.TRACE_STRUCTURE).status == CheckStatus.WARNING
+
+ @parameterized.expand(
+ [
+ ("no_spans_no_parents", 0, 0, CheckStatus.WARNING),
+ ("spans_only", 1, 0, CheckStatus.OK),
+ ("parents_only", 0, 1, CheckStatus.OK),
+ ("both", 9, 4, CheckStatus.OK),
+ ]
+ )
+ def test_trace_structure_warns_only_when_spans_and_parents_are_both_zero(
+ self, _name: str, spans: int, events_with_parent: int, expected: CheckStatus
+ ) -> None:
+ stats = _stats(total_events=100, spans=spans, events_with_parent=events_with_parent)
+ assert _graded(stats, CheckKey.TRACE_STRUCTURE).status == expected
+
+ @parameterized.expand(
+ [
+ (CheckKey.SESSIONS.value, CheckKey.SESSIONS, {"generations": 1000, "events_with_session": 1}),
+ (CheckKey.TOOL_CALLS.value, CheckKey.TOOL_CALLS, {"generations": 1000, "generations_with_tool_calls": 1}),
+ (
+ CheckKey.USER_IDENTITY.value,
+ CheckKey.USER_IDENTITY,
+ {"generations": 1000, "sdk_generations": 1000, "sdk_generations_identified": 1},
+ ),
+ (CheckKey.TRACE_STRUCTURE.value, CheckKey.TRACE_STRUCTURE, {"total_events": 1000, "spans": 1}),
+ ]
+ )
+ def test_any_presence_grades_ok_regardless_of_coverage(
+ self, _name: str, key: CheckKey, counts: dict[str, int]
+ ) -> None:
+ assert _graded(_stats(**counts), key).status == CheckStatus.OK
+
+ @parameterized.expand(
+ [
+ (
+ "sessions_warning",
+ {"generations": 40},
+ CheckKey.SESSIONS,
+ CheckStatus.WARNING,
+ SESSIONS_WARNING,
+ ),
+ (
+ "sessions_ok",
+ {"generations": 40, "events_with_session": 1},
+ CheckKey.SESSIONS,
+ CheckStatus.OK,
+ SESSIONS_OK,
+ ),
+ (
+ "sessions_pending",
+ {},
+ CheckKey.SESSIONS,
+ 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},
+ CheckKey.TOOL_CALLS,
+ CheckStatus.OK,
+ TOOL_CALLS_OK,
+ ),
+ (
+ "user_identity_warning",
+ {"generations": 40, "sdk_generations": 40},
+ CheckKey.USER_IDENTITY,
+ CheckStatus.WARNING,
+ USER_IDENTITY_WARNING,
+ ),
+ (
+ "user_identity_ok",
+ {"generations": 40, "sdk_generations": 40, "sdk_generations_identified": 1},
+ CheckKey.USER_IDENTITY,
+ CheckStatus.OK,
+ USER_IDENTITY_OK,
+ ),
+ (
+ # An all-OTel project sits here forever, so this sentence cannot claim data is still coming in.
+ "user_identity_pending_at_an_all_otel_project",
+ {"generations": 4000, "sdk_generations": 0},
+ CheckKey.USER_IDENTITY,
+ CheckStatus.PENDING,
+ USER_IDENTITY_PENDING,
+ ),
+ (
+ "trace_structure_warning",
+ {"total_events": 40},
+ CheckKey.TRACE_STRUCTURE,
+ CheckStatus.WARNING,
+ TRACE_STRUCTURE_WARNING,
+ ),
+ (
+ "trace_structure_ok",
+ {"total_events": 40, "spans": 3},
+ CheckKey.TRACE_STRUCTURE,
+ CheckStatus.OK,
+ TRACE_STRUCTURE_OK,
+ ),
+ (
+ "trace_structure_pending",
+ {},
+ CheckKey.TRACE_STRUCTURE,
+ CheckStatus.PENDING,
+ PENDING_AI_EVENTS,
+ ),
+ ]
+ )
+ def test_detail_copy_matches_status(
+ self, _name: str, counts: dict[str, int], key: CheckKey, expected_status: CheckStatus, expected_detail: str
+ ) -> None:
+ check = _graded(_stats(**counts), key)
+ assert check.status == expected_status
+ assert check.detail == expected_detail
+
+ @parameterized.expand(
+ [
+ ("would_be_ok", {"generations": 40, "events_with_session": 40}, SESSIONS_OK),
+ ("would_be_warning", {"generations": 40}, SESSIONS_WARNING),
+ ("would_be_pending", {}, PENDING_GENERATIONS),
+ ]
+ )
+ def test_dismissal_overrides_every_other_status_but_keeps_the_underlying_detail(
+ self, _name: str, counts: dict[str, int], expected_detail: str
+ ) -> None:
+ check = _graded(_stats(**counts), CheckKey.SESSIONS, dismissed_keys=[CheckKey.SESSIONS])
+ assert check.status == CheckStatus.DISMISSED
+ assert check.detail == expected_detail
+
+ def test_dismissal_applies_only_to_the_named_check(self) -> None:
+ stats = _stats(generations=40)
+ assert _graded(stats, CheckKey.TOOL_CALLS, ["tool_calls"]).status == CheckStatus.DISMISSED
+ assert _graded(stats, CheckKey.SESSIONS, ["tool_calls"]).status == CheckStatus.WARNING
+
+ @parameterized.expand(
+ [
+ ("plain_strings", ["sessions"]),
+ ("enum_members", [CheckKey.SESSIONS]),
+ ("set_of_strings", {"sessions"}),
+ ]
+ )
+ def test_dismissed_keys_accept_strings_and_enum_members(self, _name: str, dismissed_keys: Iterable[str]) -> None:
+ assert _graded(_stats(), CheckKey.SESSIONS, dismissed_keys).status == CheckStatus.DISMISSED
+
+ def test_dismissed_keys_may_be_a_single_pass_iterable(self) -> None:
+ result = grade_checklist(_stats(), (key for key in ["trace_structure"]))
+ assert [check.status for check in result] == [
+ CheckStatus.PENDING,
+ CheckStatus.PENDING,
+ CheckStatus.PENDING,
+ CheckStatus.DISMISSED,
+ ]
+
+ @parameterized.expand(
+ [
+ (
+ CheckKey.SESSIONS.value,
+ CheckKey.SESSIONS,
+ {"generations": 40, "events_with_session": 7, "events_declining_session": 2},
+ ),
+ (
+ CheckKey.TOOL_CALLS.value,
+ CheckKey.TOOL_CALLS,
+ {"generations": 40, "generations_with_tool_calls": 3, "generations_with_tools_declared": 11},
+ ),
+ (
+ CheckKey.USER_IDENTITY.value,
+ CheckKey.USER_IDENTITY,
+ {"sdk_generations": 31, "sdk_generations_identified": 9},
+ ),
+ (
+ CheckKey.TRACE_STRUCTURE.value,
+ CheckKey.TRACE_STRUCTURE,
+ {"total_events": 90, "spans": 12, "events_with_parent": 5},
+ ),
+ ]
+ )
+ def test_each_check_reports_only_the_counts_it_was_graded_from(
+ self, _name: str, key: CheckKey, expected_stats: dict[str, int]
+ ) -> None:
+ stats = _stats(
+ generations=40,
+ 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,
+ events_with_parent=5,
+ total_events=90,
+ )
+ assert _graded(stats, key).stats == expected_stats
+
+
+class TestChecklistStats:
+ def test_rejects_a_total_below_the_events_it_counted(self) -> None:
+ with pytest.raises(ValueError):
+ ChecklistStats(
+ generations=100,
+ 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,
+ events_with_parent=0,
+ total_events=0,
+ )
diff --git a/products/ai_observability/backend/instrumentation_checklist/test/test_stats.py b/products/ai_observability/backend/instrumentation_checklist/test/test_stats.py
new file mode 100644
index 000000000000..879eeae5a666
--- /dev/null
+++ b/products/ai_observability/backend/instrumentation_checklist/test/test_stats.py
@@ -0,0 +1,235 @@
+import re
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from posthog.test.base import BaseTest, ClickhouseTestMixin
+
+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.stats import (
+ _STATS_SQL,
+ WINDOW_DAYS,
+ fetch_checklist_stats,
+)
+
+NOW = datetime(2026, 8, 19, 12, 0, tzinfo=UTC)
+
+
+def _ai_event(
+ *,
+ team: Team,
+ event: str,
+ trace_id: str,
+ distinct_id: str | None = None,
+ timestamp: datetime | None = None,
+ properties: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ return {
+ "event": event,
+ # An unset distinct_id mirrors the un-instrumented shape the user_identity check detects:
+ # the SDK falls back to the trace id, so every trace looks like its own user.
+ "distinct_id": distinct_id if distinct_id is not None else trace_id,
+ "team": team,
+ "timestamp": timestamp or NOW - timedelta(days=1),
+ "properties": {"$ai_trace_id": trace_id, **(properties or {})},
+ }
+
+
+class TestFetchChecklistStats(ClickhouseTestMixin, BaseTest):
+ def test_counts_every_signal_the_checklist_grades(self) -> None:
+ bulk_create_ai_events(
+ [
+ _ai_event(
+ team=self.team,
+ event="$ai_generation",
+ trace_id="trace-instrumented",
+ distinct_id="user-42",
+ properties={
+ "$ai_session_id": "session-1",
+ "$ai_tools_called": "search",
+ "$ai_tools": [{"type": "function", "function": {"name": "search"}}],
+ "$ai_parent_id": "span-root",
+ },
+ ),
+ _ai_event(team=self.team, event="$ai_generation", trace_id="trace-bare"),
+ _ai_event(team=self.team, event="$ai_span", trace_id="trace-instrumented"),
+ _ai_event(team=self.team, event="$ai_trace", trace_id="trace-instrumented"),
+ _ai_event(team=self.team, event="$ai_embedding", trace_id="trace-bare"),
+ ]
+ )
+
+ stats = fetch_checklist_stats(self.team)
+
+ assert stats == ChecklistStats(
+ generations=2,
+ events_with_session=1,
+ events_declining_session=0,
+ generations_with_tool_calls=1,
+ generations_with_tools_declared=1,
+ sdk_generations=2,
+ sdk_generations_identified=1,
+ spans=1,
+ events_with_parent=1,
+ # Neither generations + spans nor generations alone: $ai_trace and $ai_embedding count
+ # too, or a trace-only project floors at zero and sits pending forever.
+ total_events=5,
+ )
+
+ def test_a_project_with_no_ai_events_grades_at_zero_rather_than_raising(self) -> None:
+ stats = fetch_checklist_stats(self.team)
+
+ assert stats == 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,
+ events_with_parent=0,
+ total_events=0,
+ )
+
+ def test_another_teams_events_are_not_counted(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ bulk_create_ai_events(
+ [
+ _ai_event(team=self.team, event="$ai_generation", trace_id="ours"),
+ _ai_event(
+ team=other_team,
+ event="$ai_generation",
+ trace_id="theirs",
+ distinct_id="user-42",
+ properties={"$ai_session_id": "session-x"},
+ ),
+ ]
+ )
+
+ stats = fetch_checklist_stats(self.team)
+
+ assert stats.total_events == 1
+ assert stats.generations == 1
+ assert stats.events_with_session == 0
+ assert stats.sdk_generations_identified == 0
+
+ def test_events_older_than_the_window_are_excluded(self) -> None:
+ bulk_create_ai_events(
+ [
+ _ai_event(
+ team=self.team,
+ event="$ai_generation",
+ trace_id="recent",
+ timestamp=datetime.now(UTC) - timedelta(days=WINDOW_DAYS - 1),
+ ),
+ _ai_event(
+ team=self.team,
+ event="$ai_generation",
+ trace_id="aged-out",
+ timestamp=datetime.now(UTC) - timedelta(days=WINDOW_DAYS + 1),
+ ),
+ ]
+ )
+
+ stats = fetch_checklist_stats(self.team)
+
+ assert stats.total_events == 1
+ assert stats.generations == 1
+
+ def test_tool_definitions_are_read_from_the_native_column(self) -> None:
+ # 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())
+ 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:
+ 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"}}]},
+ ),
+ ]
+ )
+
+ assert fetch_checklist_stats(self.team).generations_with_tools_declared == 1
+
+ def test_a_session_id_counts_when_it_arrives_on_a_trace_rather_than_a_generation(self) -> None:
+ bulk_create_ai_events(
+ [
+ _ai_event(
+ team=self.team,
+ event="$ai_trace",
+ trace_id="trace-1",
+ properties={"$ai_session_id": "session-1"},
+ ),
+ _ai_event(team=self.team, event="$ai_generation", trace_id="trace-1"),
+ ]
+ )
+
+ assert fetch_checklist_stats(self.team).events_with_session == 1
+
+ def test_only_an_explicit_null_session_id_reads_as_declining_a_session(self) -> None:
+ # The native session_id column is null for all four of these, so the opt-out can only be
+ # read off the raw properties blob. An empty string is usually an unset variable rather
+ # than a decision, and counting it would silence the check for a project with a bug.
+ bulk_create_ai_events(
+ [
+ _ai_event(
+ team=self.team, event="$ai_generation", trace_id="trace-null", properties={"$ai_session_id": None}
+ ),
+ _ai_event(team=self.team, event="$ai_generation", trace_id="trace-absent"),
+ _ai_event(
+ team=self.team, event="$ai_generation", trace_id="trace-empty", properties={"$ai_session_id": ""}
+ ),
+ _ai_event(
+ team=self.team, event="$ai_generation", trace_id="trace-real", properties={"$ai_session_id": "s1"}
+ ),
+ ]
+ )
+
+ stats = fetch_checklist_stats(self.team)
+ assert (stats.events_declining_session, stats.events_with_session) == (1, 1)
+
+ def test_otel_ingested_generations_are_left_out_of_the_identity_counts(self) -> None:
+ bulk_create_ai_events(
+ [
+ _ai_event(team=self.team, event="$ai_generation", trace_id="trace-sdk"),
+ _ai_event(
+ team=self.team,
+ event="$ai_generation",
+ trace_id="trace-otel",
+ # An unidentified OTel span carries one random UUID per OTLP request, which never
+ # equals the hex trace id, so it reads as identified to the distinct_id heuristic.
+ distinct_id="4d1cc9d4-0f2e-4a55-9a9b-6c0f7d3e1b22",
+ properties={"$ai_ingestion_source": "otel"},
+ ),
+ ]
+ )
+
+ stats = fetch_checklist_stats(self.team)
+
+ assert stats.generations == 2
+ assert stats.sdk_generations == 1
+ assert stats.sdk_generations_identified == 0
+
+ def test_the_aggregate_stays_ungrouped(self) -> 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()
+ assert "GROUP BY" not in normalized
+ assert "HAVING" not in normalized
diff --git a/products/ai_observability/backend/migrations/0042_aiobservabilitychecklistitemstate.py b/products/ai_observability/backend/migrations/0042_aiobservabilitychecklistitemstate.py
new file mode 100644
index 000000000000..58d8d47cc38c
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0042_aiobservabilitychecklistitemstate.py
@@ -0,0 +1,72 @@
+# Generated by Django 5.2.17 on 2026-08-19 13:52
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ai_observability", "0041_callable_choices"),
+ ("posthog", "1309_integration_kind_ext_idx"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="AIObservabilityChecklistItemState",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("check_key", models.CharField(max_length=64)),
+ ("scope", models.CharField(blank=True, max_length=200, null=True)),
+ (
+ "status",
+ models.CharField(choices=[("dismissed", "Dismissed")], max_length=32),
+ ),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ (
+ "updated_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "db_table": "llm_analytics_checklistitemstate",
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("team", "scope", "check_key"),
+ name="uniq_llma_checklist_item_state",
+ ),
+ models.UniqueConstraint(
+ condition=models.Q(("scope__isnull", True)),
+ fields=("team", "check_key"),
+ name="uniq_llma_checklist_item_state_global",
+ ),
+ ],
+ },
+ ),
+ ]
diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txt
index 801d3b72f8cc..692ea7ca14cc 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0041_callable_choices
+0042_aiobservabilitychecklistitemstate
diff --git a/products/ai_observability/backend/models/__init__.py b/products/ai_observability/backend/models/__init__.py
index 8769283b419e..fab45082d5ce 100644
--- a/products/ai_observability/backend/models/__init__.py
+++ b/products/ai_observability/backend/models/__init__.py
@@ -5,6 +5,7 @@ from .evaluation_config import EvaluationConfig
from .evaluation_directories import EvaluationDirectory
from .evaluation_reports import EvaluationReport, EvaluationReportRun
from .evaluations import Evaluation
+from .instrumentation_checklist import AIObservabilityChecklistItemState
from .llm_prompt import LLMPrompt, LLMPromptLabel
from .llm_traces_summaries import LLMTraceSummary
from .model_configuration import LLMModelConfiguration
@@ -16,6 +17,7 @@ from .taggers import Tagger
from .trace_reviews import TraceReview, TraceReviewScore
__all__ = [
+ "AIObservabilityChecklistItemState",
"ClusteringConfig",
"ClusteringJob",
"Evaluation",
diff --git a/products/ai_observability/backend/models/instrumentation_checklist.py b/products/ai_observability/backend/models/instrumentation_checklist.py
new file mode 100644
index 000000000000..2445a6e09438
--- /dev/null
+++ b/products/ai_observability/backend/models/instrumentation_checklist.py
@@ -0,0 +1,43 @@
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+
+
+class AIObservabilityChecklistItemState(TeamScopedRootMixin, UUIDModel):
+ """A team's recorded intent for one instrumentation check.
+
+ Only checks somebody has acted on get a row. Computed status is never stored:
+ it is derived from a query on every read.
+ """
+
+ class Status(models.TextChoices):
+ DISMISSED = "dismissed", "Dismissed"
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ check_key = models.CharField(max_length=64)
+ # Null means project-wide. Reserved for per-workload checklists.
+ scope = models.CharField(max_length=200, null=True, blank=True)
+ status = models.CharField(max_length=32, choices=Status)
+ updated_by = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ related_name="+",
+ )
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ db_table = "llm_analytics_checklistitemstate"
+ constraints = [
+ models.UniqueConstraint(fields=["team", "scope", "check_key"], name="uniq_llma_checklist_item_state"),
+ # SQL treats NULLs as distinct, so the constraint above lets duplicates through
+ # whenever scope IS NULL, which is the project-wide case and the only one in use.
+ models.UniqueConstraint(
+ fields=["team", "check_key"],
+ condition=models.Q(scope__isnull=True),
+ name="uniq_llma_checklist_item_state_global",
+ ),
+ ]
diff --git a/products/ai_observability/backend/models/test/test_instrumentation_checklist.py b/products/ai_observability/backend/models/test/test_instrumentation_checklist.py
new file mode 100644
index 000000000000..ae0302f537d4
--- /dev/null
+++ b/products/ai_observability/backend/models/test/test_instrumentation_checklist.py
@@ -0,0 +1,39 @@
+from posthog.test.base import BaseTest
+
+from django.db import IntegrityError, transaction
+
+from parameterized import parameterized
+
+from products.ai_observability.backend.models.instrumentation_checklist import AIObservabilityChecklistItemState
+
+
+class TestAIObservabilityChecklistItemState(BaseTest):
+ def _dismiss(self, check_key: str = "sessions", scope: str | None = None) -> AIObservabilityChecklistItemState:
+ return AIObservabilityChecklistItemState.objects.unscoped().create(
+ team=self.team,
+ check_key=check_key,
+ scope=scope,
+ status=AIObservabilityChecklistItemState.Status.DISMISSED,
+ )
+
+ @parameterized.expand(
+ [
+ ("project_wide", None, "uniq_llma_checklist_item_state_global"),
+ ("scoped", "chat", "uniq_llma_checklist_item_state"),
+ ]
+ )
+ def test_duplicate_check_key_is_rejected(self, _name: str, scope: str | None, constraint: str) -> None:
+ self._dismiss(scope=scope)
+
+ with self.assertRaises(IntegrityError) as caught, transaction.atomic():
+ self._dismiss(scope=scope)
+
+ # Quoted so the project-wide case cannot pass on the three-field constraint's name,
+ # which is a prefix of the partial constraint's.
+ assert f'unique constraint "{constraint}"' in str(caught.exception)
+
+ def test_same_check_key_allowed_across_scopes(self) -> None:
+ self._dismiss(scope=None)
+ self._dismiss(scope="chat")
+
+ assert AIObservabilityChecklistItemState.objects.for_team(self.team.id).count() == 2
diff --git a/products/ai_observability/backend/routes.py b/products/ai_observability/backend/routes.py
index a81f562d8a80..c1082648ab7c 100644
--- a/products/ai_observability/backend/routes.py
+++ b/products/ai_observability/backend/routes.py
@@ -4,6 +4,7 @@ from posthog.settings import CLOUD_DEPLOYMENT, DEBUG, TEST
from products.ai_observability.backend.api import (
AIBlobViewSet,
AIObservabilityClusteringRunViewSet,
+ AIObservabilityInstrumentationChecklistViewSet,
AIObservabilityOfflineEvaluationsViewSet,
AIObservabilitySummarizationViewSet,
AIObservabilityTextReprViewSet,
@@ -34,6 +35,14 @@ from products.ai_observability.backend.api import (
def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(r"ai_blob", AIBlobViewSet, "project_ai_blob", ["project_id"])
+ # `ai_observability` is the canonical name; the `llm_analytics/` prefixes below are the
+ # unfinished half of a rename the frontend scene URLs already completed.
+ routers.projects.register(
+ r"ai_observability/instrumentation_checklist",
+ AIObservabilityInstrumentationChecklistViewSet,
+ "project_ai_observability_instrumentation_checklist",
+ ["team_id"],
+ )
routers.root.register(r"llm_proxy", LLMProxyViewSet, "llm_proxy")
# @me/spend is only useful where billing data is available; mirrors the
# CLOUD/DEBUG/TEST gate the registration carried inline.
diff --git a/products/ai_observability/frontend/AIObservabilityScene.tsx b/products/ai_observability/frontend/AIObservabilityScene.tsx
index 36e63903e0a5..0e463d73a501 100644
--- a/products/ai_observability/frontend/AIObservabilityScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityScene.tsx
@@ -48,6 +48,7 @@ import { AIObservabilityTraces } from './AIObservabilityTracesScene'
import { AIObservabilityUsers } from './AIObservabilityUsers'
import { aiObservabilityEmptyState } from './emptyState/aiObservabilityEmptyState'
import { useSortableColumns } from './hooks/useSortableColumns'
+import { InstrumentationChecklistCard } from './instrumentationChecklist/InstrumentationChecklistCard'
import { llmPersonsLazyLoaderLogic } from './llmPersonsLazyLoaderLogic'
import { AIObservabilitySelfDriving } from './selfDriving/AIObservabilitySelfDriving'
import { GENERATION_SENTIMENT_SELECT } from './sentimentResults'
@@ -171,6 +172,8 @@ function AIObservabilityDashboard(): JSX.Element {
<div className="@container/dashboard" data-attr="llm-analytics-costs">
<Filters />
+ <InstrumentationChecklistCard />
+
{availableDashboardsLoading || !selectedDashboardId ? (
<div className="text-center p-8">
<Spinner captureTime />
diff --git a/products/ai_observability/frontend/AIObservabilitySessionsEmptyState.stories.tsx b/products/ai_observability/frontend/AIObservabilitySessionsEmptyState.stories.tsx
new file mode 100644
index 000000000000..c04915cdba84
--- /dev/null
+++ b/products/ai_observability/frontend/AIObservabilitySessionsEmptyState.stories.tsx
@@ -0,0 +1,63 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { useStorybookMocks } from '~/mocks/browser'
+
+import { AIObservabilitySessionsEmptyState } from './AIObservabilitySessionsEmptyState'
+import {
+ AIObservabilityInstrumentationCheckEnumApi,
+ InstrumentationCheckStatusEnumApi,
+ InstrumentationChecklistApi,
+} from './generated/api.schemas'
+
+function checklistWith(status: InstrumentationCheckStatusEnumApi): InstrumentationChecklistApi {
+ return {
+ window_days: 30,
+ checks: [
+ {
+ key: AIObservabilityInstrumentationCheckEnumApi.Sessions,
+ status,
+ title: 'Sessions',
+ detail:
+ 'No traces include $ai_session_id. If your product has multi-turn conversations, setting it ' +
+ 'lets us group them into sessions. Workloads that are complete in one trace, like batch jobs ' +
+ 'or one-shot generation, do not need it. Send $ai_session_id as null on those to say so.',
+ docs_url: 'https://posthog.com/docs/ai-observability/sessions',
+ stats: { generations: 1284, events_with_session: 0, events_declining_session: 0 },
+ },
+ ],
+ }
+}
+
+const meta: Meta<{ status: InstrumentationCheckStatusEnumApi }> = {
+ title: 'Scenes-App/AI observability/Sessions empty state',
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.AI_OBSERVABILITY_INSTRUMENTATION_CHECKLIST],
+ testOptions: { waitForLoadersToDisappear: false },
+ },
+ render: ({ status }) => {
+ useStorybookMocks({
+ get: {
+ '/api/projects/:team_id/ai_observability/instrumentation_checklist/': checklistWith(status),
+ },
+ })
+
+ // The list pane the empty state renders into is a narrow, bordered column.
+ return (
+ <div className="w-[300px] h-[420px] flex flex-col overflow-hidden rounded border border-primary bg-surface-primary">
+ <AIObservabilitySessionsEmptyState />
+ </div>
+ )
+ },
+}
+export default meta
+type Story = StoryObj<{ status: InstrumentationCheckStatusEnumApi }>
+
+export const MissingSessionInstrumentation: Story = {
+ args: { status: InstrumentationCheckStatusEnumApi.Warning },
+}
+
+export const NothingToReport: Story = {
+ args: { status: InstrumentationCheckStatusEnumApi.Ok },
+}
diff --git a/products/ai_observability/frontend/AIObservabilitySessionsEmptyState.test.tsx b/products/ai_observability/frontend/AIObservabilitySessionsEmptyState.test.tsx
new file mode 100644
index 000000000000..b9343272a933
--- /dev/null
+++ b/products/ai_observability/frontend/AIObservabilitySessionsEmptyState.test.tsx
@@ -0,0 +1,151 @@
+import { cleanup, render, screen } from '@testing-library/react'
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+
+import { AIObservabilitySessionsEmptyState } from './AIObservabilitySessionsEmptyState'
+import { aiObservabilitySharedLogic } from './aiObservabilitySharedLogic'
+import { aiObservabilityInstrumentationChecklistRetrieve } from './generated/api'
+import {
+ AIObservabilityInstrumentationCheckEnumApi,
+ InstrumentationCheckStatusEnumApi,
+ InstrumentationChecklistApi,
+} from './generated/api.schemas'
+import { instrumentationChecklistLogic } from './instrumentationChecklist/instrumentationChecklistLogic'
+import { hasRecentAIEvents } from './utils/aiEvents'
+
+jest.mock('lib/api')
+jest.mock('./utils/aiEvents')
+jest.mock('./generated/api', () => ({
+ ...jest.requireActual('./generated/api'),
+ aiObservabilityInstrumentationChecklistRetrieve: jest.fn(),
+}))
+
+const mockRetrieve = aiObservabilityInstrumentationChecklistRetrieve as jest.MockedFunction<
+ typeof aiObservabilityInstrumentationChecklistRetrieve
+>
+const mockHasRecentAIEvents = hasRecentAIEvents as jest.MockedFunction<typeof hasRecentAIEvents>
+
+const GENERIC_COPY = 'No sessions yet'
+const INSTRUMENTATION_HEADING = 'Traces are not grouped into sessions'
+const SESSIONS_DETAIL = 'No traces include $ai_session_id.'
+const DOCS_URL = 'https://posthog.com/docs/ai-observability/sessions'
+
+function checklistWith(status: InstrumentationCheckStatusEnumApi): InstrumentationChecklistApi {
+ return {
+ window_days: 30,
+ checks: [
+ {
+ key: AIObservabilityInstrumentationCheckEnumApi.Sessions,
+ status,
+ title: 'Sessions',
+ detail: SESSIONS_DETAIL,
+ docs_url: DOCS_URL,
+ stats: { generations: 100, events_with_session: 0, events_declining_session: 0 },
+ },
+ ],
+ }
+}
+
+const MODEL_FILTER: AnyPropertyFilter = {
+ type: PropertyFilterType.Event,
+ key: '$ai_model',
+ operator: PropertyOperator.Exact,
+ value: ['gpt-4o'],
+}
+
+describe('AIObservabilitySessionsEmptyState', () => {
+ let checklistLogic: ReturnType<typeof instrumentationChecklistLogic.build>
+ let sharedLogic: ReturnType<typeof aiObservabilitySharedLogic.build>
+
+ beforeEach(async () => {
+ jest.clearAllMocks()
+ // `dateFilter` persists, so a range set by one case would otherwise be the next one's default.
+ localStorage.clear()
+ mockHasRecentAIEvents.mockResolvedValue(true)
+ mockRetrieve.mockResolvedValue(checklistWith(InstrumentationCheckStatusEnumApi.Warning))
+ initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.AI_OBSERVABILITY_INSTRUMENTATION_CHECKLIST]: true,
+ })
+ sharedLogic = aiObservabilitySharedLogic()
+ sharedLogic.mount()
+ checklistLogic = instrumentationChecklistLogic()
+ checklistLogic.mount()
+ await expectLogic(checklistLogic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+ })
+
+ afterEach(() => {
+ cleanup()
+ checklistLogic.unmount()
+ sharedLogic.unmount()
+ featureFlagLogic.unmount()
+ })
+
+ it('names the missing instrumentation on an unfiltered view', () => {
+ render(<AIObservabilitySessionsEmptyState />)
+
+ expect(screen.getByText(INSTRUMENTATION_HEADING)).not.toBeNull()
+ expect(screen.getByText(SESSIONS_DETAIL)).not.toBeNull()
+ expect(screen.getByText('Learn more').closest('a')?.getAttribute('href')).toBe(DOCS_URL)
+ expect(screen.queryByText(GENERIC_COPY)).toBeNull()
+ })
+
+ // Without `$ai_session_id` the Sessions query drops every row whatever the range, so the
+ // verdict still explains the empty list anywhere inside the 30 days it graded.
+ it.each([
+ ['the range is the last 24 hours', (): void => sharedLogic.actions.setDates('-24h', null)],
+ ['the range is the last 7 days', (): void => sharedLogic.actions.setDates('-7d', null)],
+ ['the range is exactly the checklist window', (): void => sharedLogic.actions.setDates('-30d', null)],
+ ['an end date closes the range early', (): void => sharedLogic.actions.setDates('-7d', '-1d')],
+ ])('names the missing instrumentation when %s', (_, applyFilter) => {
+ applyFilter()
+
+ render(<AIObservabilitySessionsEmptyState />)
+
+ expect(screen.getByText(SESSIONS_DETAIL)).not.toBeNull()
+ expect(screen.queryByText(GENERIC_COPY)).toBeNull()
+ })
+
+ // Blaming instrumentation for a view the user narrowed themselves is the false accusation this
+ // whole feature has to avoid, and a range reaching past the graded window is data the verdict
+ // never looked at.
+ it.each([
+ ['a property filter is applied', (): void => sharedLogic.actions.setPropertyFilters([MODEL_FILTER])],
+ ['test accounts are filtered out', (): void => sharedLogic.actions.setShouldFilterTestAccounts(true)],
+ [
+ 'the range starts one day before the checklist window',
+ (): void => sharedLogic.actions.setDates('-31d', null),
+ ],
+ ['the range starts before the checklist window', (): void => sharedLogic.actions.setDates('-6m', null)],
+ ['the range covers all time', (): void => sharedLogic.actions.setDates('all', null)],
+ ['the range has no start at all', (): void => sharedLogic.actions.setDates(null, null)],
+ ])('keeps the generic copy when %s', (_, applyFilter) => {
+ applyFilter()
+
+ render(<AIObservabilitySessionsEmptyState />)
+
+ expect(screen.getByText(GENERIC_COPY)).not.toBeNull()
+ expect(screen.queryByText(SESSIONS_DETAIL)).toBeNull()
+ })
+
+ it.each([
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Pending,
+ InstrumentationCheckStatusEnumApi.Dismissed,
+ ])('keeps the generic copy when the check graded %s', async (status) => {
+ mockRetrieve.mockResolvedValue(checklistWith(status))
+ checklistLogic.actions.loadInstrumentationChecklist()
+ await expectLogic(checklistLogic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+
+ render(<AIObservabilitySessionsEmptyState />)
+
+ expect(screen.getByText(GENERIC_COPY)).not.toBeNull()
+ expect(screen.queryByText(SESSIONS_DETAIL)).toBeNull()
+ })
+})
diff --git a/products/ai_observability/frontend/AIObservabilitySessionsEmptyState.tsx b/products/ai_observability/frontend/AIObservabilitySessionsEmptyState.tsx
new file mode 100644
index 000000000000..b69bd6f01ef4
--- /dev/null
+++ b/products/ai_observability/frontend/AIObservabilitySessionsEmptyState.tsx
@@ -0,0 +1,23 @@
+import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'
+
+import { AIObservabilityInstrumentationCheckEnumApi } from './generated/api.schemas'
+import { useInstrumentationWarning } from './hooks/useInstrumentationEmptyState'
+
+export function AIObservabilitySessionsEmptyState(): JSX.Element {
+ const warning = useInstrumentationWarning(AIObservabilityInstrumentationCheckEnumApi.Sessions)
+
+ if (!warning) {
+ return <div className="p-4 text-center text-sm text-secondary">No sessions yet</div>
+ }
+
+ return (
+ <EmptyMessage
+ title="Traces are not grouped into sessions"
+ description={warning.detail}
+ buttonText="Learn more"
+ buttonTo={warning.docs_url}
+ buttonDataAttr="llma-sessions-instrumentation-docs"
+ size="small"
+ />
+ )
+}
diff --git a/products/ai_observability/frontend/AIObservabilitySessionsPlaylist.tsx b/products/ai_observability/frontend/AIObservabilitySessionsPlaylist.tsx
index b5df28eaeb5f..e13bf1207ced 100644
--- a/products/ai_observability/frontend/AIObservabilitySessionsPlaylist.tsx
+++ b/products/ai_observability/frontend/AIObservabilitySessionsPlaylist.tsx
@@ -11,6 +11,7 @@ import { LemonTableLoader } from 'lib/lemon-ui/LemonTable/LemonTableLoader'
import { cn } from 'lib/utils/css-classes'
import { SessionDetailPanel } from './AIObservabilitySessionScene'
+import { AIObservabilitySessionsEmptyState } from './AIObservabilitySessionsEmptyState'
import { SessionListRow, aiObservabilitySessionsViewLogic } from './tabs/aiObservabilitySessionsViewLogic'
import { formatLLMCost } from './utils'
@@ -110,7 +111,7 @@ function ListPane({ className }: { className?: string }): JSX.Element {
))}
</div>
) : sessions.length === 0 ? (
- <div className="p-4 text-center text-sm text-secondary">No sessions yet</div>
+ <AIObservabilitySessionsEmptyState />
) : (
<>
<ul className="flex flex-col list-none pl-0 m-0 divide-y divide-primary">
diff --git a/products/ai_observability/frontend/AIObservabilityTools.tsx b/products/ai_observability/frontend/AIObservabilityTools.tsx
index 86c2df286b8f..128b6e5844d2 100644
--- a/products/ai_observability/frontend/AIObservabilityTools.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTools.tsx
@@ -15,6 +15,8 @@ import { isHogQLQuery } from '~/queries/utils'
import { PropertyFilterType, PropertyOperator } from '~/types'
import { buildApplyUrlStatePayload, aiObservabilitySharedLogic } from './aiObservabilitySharedLogic'
+import { AIObservabilityInstrumentationCheckEnumApi } from './generated/api.schemas'
+import { useInstrumentationEmptyState } from './hooks/useInstrumentationEmptyState'
import { useSortableColumns } from './hooks/useSortableColumns'
import { aiObservabilityToolsLogic } from './tabs/aiObservabilityToolsLogic'
@@ -32,6 +34,10 @@ export function AIObservabilityTools(): JSX.Element {
buildToolHeatmapQuery,
} = useValues(aiObservabilityToolsLogic)
const { searchParams } = useValues(router)
+ const instrumentationEmptyState = useInstrumentationEmptyState(
+ AIObservabilityInstrumentationCheckEnumApi.ToolCalls,
+ 'Tool calls are missing from your AI events'
+ )
const { renderSortableColumnTitle } = useSortableColumns(toolsSort, setToolsSort)
@@ -60,6 +66,7 @@ export function AIObservabilityTools(): JSX.Element {
)
}}
context={{
+ ...instrumentationEmptyState,
customActions: [
<Tooltip title="View tool usage trends over time" key="trends">
<LemonButton
diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.stories.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.stories.tsx
index 03808155c883..b7480a9f389a 100644
--- a/products/ai_observability/frontend/AIObservabilityTraceScene.stories.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.stories.tsx
@@ -1,15 +1,17 @@
import type { Meta, StoryObj } from '@storybook/react'
import { router } from 'kea-router'
+import { FEATURE_FLAGS } from 'lib/constants'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { urls } from 'scenes/urls'
-import { useStorybookMocks } from '~/mocks/browser'
+import { mswDecorator, useStorybookMocks } from '~/mocks/browser'
import { LLMTrace } from '~/queries/schema/schema-general'
import fullTrace from './__mocks__/fullTrace.json'
import traceWithoutContent from './__mocks__/traceWithoutContent.json'
import { AIObservabilityTraceScene } from './AIObservabilityTraceScene'
+import { AIObservabilityInstrumentationCheckEnumApi, InstrumentationCheckStatusEnumApi } from './generated/api.schemas'
interface AIObservabilityTraceSceneProps {
trace: LLMTrace
@@ -78,3 +80,31 @@ export const WithoutContent: Story = {
trace: traceWithoutContent,
},
}
+
+export const MissingSpanInstrumentation: Story = {
+ args: {
+ trace: traceWithoutContent,
+ },
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.AI_OBSERVABILITY_INSTRUMENTATION_CHECKLIST],
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/ai_observability/instrumentation_checklist/': {
+ window_days: 30,
+ checks: [
+ {
+ key: AIObservabilityInstrumentationCheckEnumApi.TraceStructure,
+ status: InstrumentationCheckStatusEnumApi.Warning,
+ title: 'Trace structure',
+ detail: 'Without spans, a trace shows LLM calls but not the retrieval, chains or sub-agent steps around them.',
+ docs_url: 'https://posthog.com/docs/ai-observability/installation',
+ stats: { total_events: 1611, spans: 0, events_with_parent: 0 },
+ },
+ ],
+ },
+ },
+ }),
+ ],
+}
diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
index 4c6280f6475c..b0904aa25e6b 100644
--- a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
@@ -90,6 +90,7 @@ import { SaveToDatasetButton } from './datasets/SaveToDatasetButton'
import { FeedbackViewDisplay } from './feedback-view/FeedbackViewDisplay'
import { generationEvaluationRunsLogic } from './generationEvaluationRunsLogic'
import { useAIData } from './hooks/useAIData'
+import { TraceStructureNote } from './instrumentationChecklist/TraceStructureNote'
import { LLMInputOutput } from './LLMInputOutput'
import { llmPersonsLazyLoaderLogic } from './llmPersonsLazyLoaderLogic'
import { normalizeMessages } from './messageNormalization'
@@ -1230,6 +1231,7 @@ function TraceSidebar({
showBillingInfo={showBillingInfo}
/>
</ul>
+ <TraceStructureNote events={trace.events} />
</div>
</aside>
)
diff --git a/products/ai_observability/frontend/AIObservabilityUsers.tsx b/products/ai_observability/frontend/AIObservabilityUsers.tsx
index f92901d0d324..6a29fd9184ff 100644
--- a/products/ai_observability/frontend/AIObservabilityUsers.tsx
+++ b/products/ai_observability/frontend/AIObservabilityUsers.tsx
@@ -7,6 +7,8 @@ import { isHogQLQuery } from '~/queries/utils'
import { aiObservabilityColumnRenderers } from './aiObservabilityColumnRenderers'
import { buildApplyUrlStatePayload, aiObservabilitySharedLogic } from './aiObservabilitySharedLogic'
+import { AIObservabilityInstrumentationCheckEnumApi } from './generated/api.schemas'
+import { useInstrumentationEmptyState } from './hooks/useInstrumentationEmptyState'
import { useSortableColumns } from './hooks/useSortableColumns'
import { aiObservabilityUsersLogic } from './tabs/aiObservabilityUsersLogic'
@@ -15,6 +17,10 @@ export function AIObservabilityUsers(): JSX.Element {
const { dateFilter, propertyFilters: currentPropertyFilters } = useValues(aiObservabilitySharedLogic)
const { setUsersSort } = useActions(aiObservabilityUsersLogic)
const { usersQuery, usersSort } = useValues(aiObservabilityUsersLogic)
+ const instrumentationEmptyState = useInstrumentationEmptyState(
+ AIObservabilityInstrumentationCheckEnumApi.UserIdentity,
+ 'Users are not identified in your AI events'
+ )
const { renderSortableColumnTitle } = useSortableColumns(usersSort, setUsersSort)
@@ -44,6 +50,7 @@ export function AIObservabilityUsers(): JSX.Element {
)
}}
context={{
+ ...instrumentationEmptyState,
columns: {
__llm_person: aiObservabilityColumnRenderers.__llm_person,
first_seen: {
diff --git a/products/ai_observability/frontend/aiObservabilitySharedLogic.test.ts b/products/ai_observability/frontend/aiObservabilitySharedLogic.test.ts
index eb1dbaf3a3b3..c60ce439befe 100644
--- a/products/ai_observability/frontend/aiObservabilitySharedLogic.test.ts
+++ b/products/ai_observability/frontend/aiObservabilitySharedLogic.test.ts
@@ -1,4 +1,5 @@
import { expectLogic } from 'kea-test-utils'
+import { runInThisContext } from 'node:vm'
import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
@@ -14,6 +15,30 @@ jest.mock('./utils/aiEvents')
const mockHasRecentAIEvents = hasRecentAIEvents as jest.MockedFunction<typeof hasRecentAIEvents>
+// Jest hands the test sandbox a copy of `process` whose `env` is a plain proxy, so assigning TZ
+// there never reaches Node's timezone setter and the zone stays put. `runInThisContext` evaluates
+// in the worker's own context, whose `process` is the real one.
+function realProcessEnv(): NodeJS.ProcessEnv {
+ return runInThisContext('process').env
+}
+
+function inBrowser<T>(timezone: string, now: string, run: () => T): T {
+ const env = realProcessEnv()
+ const previous = env.TZ
+ env.TZ = timezone
+ jest.useFakeTimers({ now: new Date(now) })
+ try {
+ return run()
+ } finally {
+ jest.useRealTimers()
+ if (previous === undefined) {
+ delete env.TZ
+ } else {
+ env.TZ = previous
+ }
+ }
+}
+
describe('aiObservabilitySharedLogic', () => {
describe('buildApplyUrlStatePayload', () => {
const currentDateFilter = { dateFrom: '-1h', dateTo: null as string | null }
@@ -123,4 +148,29 @@ describe('aiObservabilitySharedLogic', () => {
expect(productSetupStatusLogic({ productKey: ProductKey.AI_OBSERVABILITY }).values.status).toBe('has-data')
})
})
+
+ describe('instrumentationVerdictApplies', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockHasRecentAIEvents.mockResolvedValue(true)
+ // `dateFilter` persists, so a range set by one case would otherwise be the next one's default.
+ localStorage.clear()
+ initKeaTests()
+ })
+
+ // The range and the window it is measured against both resolve in UTC, so the answer must
+ // not move with the browser. Each clock below sits on a different calendar date locally
+ // than in UTC, which is where an anchor read from the browser's own zone drifts a day and
+ // silently drops the instrumentation empty state.
+ it.each([
+ ['Asia/Tokyo', '2026-08-25T18:00:00.000Z'],
+ ['America/Los_Angeles', '2026-08-25T02:00:00.000Z'],
+ ])('covers a range of exactly the checklist window in %s', (timezone, now) => {
+ const logic = aiObservabilitySharedLogic()
+ logic.mount()
+ logic.actions.setDates('-30d', null)
+
+ expect(inBrowser(timezone, now, () => logic.values.instrumentationVerdictApplies(30))).toBe(true)
+ })
+ })
})
diff --git a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
index 49a119a1d105..1b17f267f1b9 100644
--- a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
@@ -18,9 +18,10 @@ import { router, urlToAction } from 'kea-router'
import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
import type { ProductSetupStatus } from 'lib/components/ProductEmptyState/types'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
+import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { isValidRelativeOrAbsoluteDate } from 'lib/utils/dateFilters'
+import { dateStringToDayJs, isValidRelativeOrAbsoluteDate } from 'lib/utils/dateFilters'
import { objectsEqual } from 'lib/utils/objects'
import { projectLogic } from 'scenes/projectLogic'
import { sceneLogic } from 'scenes/sceneLogic'
@@ -163,6 +164,7 @@ export interface aiObservabilitySharedLogicValues {
}
hasSentAiEvent: boolean | undefined
hasSentAiEventLoading: boolean
+ instrumentationVerdictApplies: (windowDays: number | null) => boolean
propertyFilters: AnyPropertyFilter[]
savedDashboardDateFilter: {
dateFrom: string | null
@@ -262,6 +264,14 @@ export interface aiObservabilitySharedLogicMeta {
date_to: string | null | undefined
}
activeTab: (sceneKey: string | null) => AIObservabilityTabId
+ instrumentationVerdictApplies: (
+ propertyFilters: AnyPropertyFilter[],
+ dateFilter: {
+ dateFrom: string | null
+ dateTo: string | null
+ },
+ shouldFilterTestAccounts: boolean
+ ) => (windowDays: number | null) => boolean
}
}
@@ -493,6 +503,42 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
},
],
+ // Whether an instrumentation verdict graded over the last `windowDays` days can account
+ // for the rows the current view is showing.
+ //
+ // `searchQuery` is deliberately absent: it only reaches the traces query, so a term left
+ // over on the Traces tab would silence tabs whose contents it never touched.
+ instrumentationVerdictApplies: [
+ (s) => [s.propertyFilters, s.dateFilter, s.shouldFilterTestAccounts],
+ (
+ propertyFilters: AnyPropertyFilter[],
+ dateFilter: {
+ dateFrom: string | null
+ dateTo: string | null
+ },
+ shouldFilterTestAccounts: boolean
+ ): ((windowDays: number | null) => boolean) => {
+ return (windowDays: number | null) => {
+ if (windowDays === null || propertyFilters.length > 0 || shouldFilterTestAccounts) {
+ return false
+ }
+ // The verdict only ever looked at the window, so it cannot vouch for a range
+ // starting before it. An unresolvable start ('all', or nothing at all) has no
+ // lower bound, which reaches earlier than any window.
+ //
+ // Both sides are anchored to UTC's start of day, where `dateStringToDayJs`
+ // anchors day-and-larger units, so a range of exactly the window's length,
+ // '-30d' against 30 days, stays inside its own window whatever the browser's
+ // timezone. Instants are compared directly because dayjs's timezone plugin
+ // re-reads a `.tz()`-derived value through the browser's wall clock inside
+ // `isBefore`, moving it by the local offset.
+ const rangeStart = dateStringToDayJs(dateFilter.dateFrom)
+ const windowStart = dayjs.utc().subtract(windowDays, 'day').startOf('day')
+ return rangeStart !== null && rangeStart.valueOf() >= windowStart.valueOf()
+ }
+ },
+ ],
+
breadcrumbs: [
() => [],
(): Breadcrumb[] => {
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index 447c5fcb5ba3..68a2893cc407 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -215,6 +215,85 @@ export interface _ErrorResponseApi {
detail: string
}
+/**
+ * * `sessions` - sessions
+ * * `tool_calls` - tool_calls
+ * * `user_identity` - user_identity
+ * * `trace_structure` - trace_structure
+ */
+export type AIObservabilityInstrumentationCheckEnumApi =
+ (typeof AIObservabilityInstrumentationCheckEnumApi)[keyof typeof AIObservabilityInstrumentationCheckEnumApi]
+
+export const AIObservabilityInstrumentationCheckEnumApi = {
+ Sessions: 'sessions',
+ ToolCalls: 'tool_calls',
+ UserIdentity: 'user_identity',
+ TraceStructure: 'trace_structure',
+} as const
+
+/**
+ * * `ok` - ok
+ * * `warning` - warning
+ * * `pending` - pending
+ * * `dismissed` - dismissed
+ */
+export type InstrumentationCheckStatusEnumApi =
+ (typeof InstrumentationCheckStatusEnumApi)[keyof typeof InstrumentationCheckStatusEnumApi]
+
+export const InstrumentationCheckStatusEnumApi = {
+ Ok: 'ok',
+ Warning: 'warning',
+ Pending: 'pending',
+ Dismissed: 'dismissed',
+} as const
+
+/**
+ * Counts this check was graded from, over the same window. Which counts appear depends on the check.
+ */
+export type InstrumentationCheckApiStats = { [key: string]: number }
+
+export interface InstrumentationCheckApi {
+ /** Identifier of the check. Stable across statuses, so a surface can key its own copy off it.
+ *
+ * * `sessions` - sessions
+ * * `tool_calls` - tool_calls
+ * * `user_identity` - user_identity
+ * * `trace_structure` - trace_structure */
+ key: AIObservabilityInstrumentationCheckEnumApi
+ /** How the check graded: 'ok' when the instrumentation is present, 'warning' when it is absent, 'pending' when the project has too little traffic to judge, and 'dismissed' when someone on the team marked the check as not applicable.
+ *
+ * * `ok` - ok
+ * * `warning` - warning
+ * * `pending` - pending
+ * * `dismissed` - dismissed */
+ status: InstrumentationCheckStatusEnumApi
+ /** Short label for the check, the same for every status. */
+ title: string
+ /** Sentence explaining what the counts mean and, for a warning, what to send. A dismissed check keeps the sentence its counts earned. */
+ detail: string
+ /** Documentation page covering how to send the missing instrumentation. */
+ docs_url: string
+ /** Counts this check was graded from, over the same window. Which counts appear depends on the check. */
+ stats: InstrumentationCheckApiStats
+}
+
+export interface InstrumentationChecklistApi {
+ /** Length in days of the event window the checks were graded over. */
+ window_days: number
+ /** Every check, graded. Checks are always all returned, including the ones that pass. */
+ checks: InstrumentationCheckApi[]
+}
+
+export interface InstrumentationCheckActionApi {
+ /** Key of the check to dismiss or restore.
+ *
+ * * `sessions` - sessions
+ * * `tool_calls` - tool_calls
+ * * `user_identity` - user_identity
+ * * `trace_structure` - trace_structure */
+ check: AIObservabilityInstrumentationCheckEnumApi
+}
+
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 ba237779ce42..3e85fa590bbb 100644
--- a/products/ai_observability/frontend/generated/api.ts
+++ b/products/ai_observability/frontend/generated/api.ts
@@ -38,6 +38,8 @@ import type {
EvaluationRunRequestApi,
EvaluationRunsCreate200,
EvaluationsListParams,
+ InstrumentationCheckActionApi,
+ InstrumentationChecklistApi,
LLMModelsListResponseApi,
LLMPromptApi,
LLMPromptDuplicateApi,
@@ -164,6 +166,69 @@ export const llmAnalyticsPersonalSpendList = async (
})
}
+export const getAiObservabilityInstrumentationChecklistRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/ai_observability/instrumentation_checklist/`
+}
+
+/**
+ * Grade every instrumentation check for this project.
+ */
+export const aiObservabilityInstrumentationChecklistRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<InstrumentationChecklistApi> => {
+ return apiMutator<InstrumentationChecklistApi>(getAiObservabilityInstrumentationChecklistRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAiObservabilityInstrumentationChecklistDismissCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/ai_observability/instrumentation_checklist/dismiss/`
+}
+
+/**
+ * Mark a check as not applicable to this project.
+ */
+export const aiObservabilityInstrumentationChecklistDismissCreate = async (
+ projectId: string,
+ instrumentationCheckActionApi: InstrumentationCheckActionApi,
+ options?: RequestInit
+): Promise<InstrumentationChecklistApi> => {
+ return apiMutator<InstrumentationChecklistApi>(
+ getAiObservabilityInstrumentationChecklistDismissCreateUrl(projectId),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(instrumentationCheckActionApi),
+ }
+ )
+}
+
+export const getAiObservabilityInstrumentationChecklistRestoreCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/ai_observability/instrumentation_checklist/restore/`
+}
+
+/**
+ * Bring a dismissed check back into grading.
+ */
+export const aiObservabilityInstrumentationChecklistRestoreCreate = async (
+ projectId: string,
+ instrumentationCheckActionApi: InstrumentationCheckActionApi,
+ options?: RequestInit
+): Promise<InstrumentationChecklistApi> => {
+ return apiMutator<InstrumentationChecklistApi>(
+ getAiObservabilityInstrumentationChecklistRestoreCreateUrl(projectId),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(instrumentationCheckActionApi),
+ }
+ )
+}
+
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 f3453f2a2027..fa15cd0fd67b 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -9,6 +9,34 @@
*/
import * as zod from 'zod'
+/**
+ * Mark a check as not applicable to this project.
+ */
+export const AiObservabilityInstrumentationChecklistDismissCreateBody = /* @__PURE__ */ zod.object({
+ check: zod
+ .enum(['sessions', 'tool_calls', 'user_identity', 'trace_structure'])
+ .describe(
+ '\* `sessions` - sessions\n\* `tool_calls` - tool_calls\n\* `user_identity` - user_identity\n\* `trace_structure` - trace_structure'
+ )
+ .describe(
+ 'Key of the check to dismiss or restore.\n\n\* `sessions` - sessions\n\* `tool_calls` - tool_calls\n\* `user_identity` - user_identity\n\* `trace_structure` - trace_structure'
+ ),
+})
+
+/**
+ * Bring a dismissed check back into grading.
+ */
+export const AiObservabilityInstrumentationChecklistRestoreCreateBody = /* @__PURE__ */ zod.object({
+ check: zod
+ .enum(['sessions', 'tool_calls', 'user_identity', 'trace_structure'])
+ .describe(
+ '\* `sessions` - sessions\n\* `tool_calls` - tool_calls\n\* `user_identity` - user_identity\n\* `trace_structure` - trace_structure'
+ )
+ .describe(
+ 'Key of the check to dismiss or restore.\n\n\* `sessions` - sessions\n\* `tool_calls` - tool_calls\n\* `user_identity` - user_identity\n\* `trace_structure` - trace_structure'
+ ),
+})
+
/**
* 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/hooks/useInstrumentationEmptyState.tsx b/products/ai_observability/frontend/hooks/useInstrumentationEmptyState.tsx
new file mode 100644
index 000000000000..2415ce6ec9af
--- /dev/null
+++ b/products/ai_observability/frontend/hooks/useInstrumentationEmptyState.tsx
@@ -0,0 +1,43 @@
+import { useValues } from 'kea'
+
+import { Link } from 'lib/lemon-ui/Link'
+
+import { QueryContext } from '~/queries/types'
+
+import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'
+import { AIObservabilityInstrumentationCheckEnumApi, InstrumentationCheckApi } from '../generated/api.schemas'
+import { instrumentationChecklistLogic } from '../instrumentationChecklist/instrumentationChecklistLogic'
+
+export type InstrumentationEmptyState = Pick<QueryContext, 'emptyStateHeading' | 'emptyStateDetail'>
+
+/** The check a tab may blame its empty state on, or null when the tab keeps its generic copy. */
+export function useInstrumentationWarning(
+ check: AIObservabilityInstrumentationCheckEnumApi
+): InstrumentationCheckApi | null {
+ const { warningForCheck, windowDays } = useValues(instrumentationChecklistLogic)
+ const { instrumentationVerdictApplies } = useValues(aiObservabilitySharedLogic)
+
+ return instrumentationVerdictApplies(windowDays) ? warningForCheck(check) : null
+}
+
+/** The same verdict shaped for a `DataTable`, ready to spread into its `QueryContext`. */
+export function useInstrumentationEmptyState(
+ check: AIObservabilityInstrumentationCheckEnumApi,
+ heading: string
+): InstrumentationEmptyState | null {
+ const warning = useInstrumentationWarning(check)
+
+ if (!warning) {
+ return null
+ }
+
+ return {
+ emptyStateHeading: heading,
+ // `emptyStateHeading` is string-only, so the docs link has to ride along in the detail.
+ emptyStateDetail: (
+ <>
+ {warning.detail} <Link to={warning.docs_url}>Learn more</Link>
+ </>
+ ),
+ }
+}
diff --git a/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.stories.tsx b/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.stories.tsx
new file mode 100644
index 000000000000..348902bbd2f6
--- /dev/null
+++ b/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.stories.tsx
@@ -0,0 +1,273 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import {
+ AIObservabilityInstrumentationCheckEnumApi,
+ InstrumentationCheckApi,
+ InstrumentationCheckStatusEnumApi,
+ InstrumentationChecklistApi,
+} from '../generated/api.schemas'
+import { InstrumentationChecklistCard } from './InstrumentationChecklistCard'
+
+// Every title, detail and docs URL below is copied from the grader that produces them,
+// products/ai_observability/backend/instrumentation_checklist/grading.py. These stories are the
+// card's visual-regression baseline, so copy invented here would get approved as the way the card
+// looks even though the API never sends it.
+const INSTALLATION_DOCS_URL = 'https://posthog.com/docs/ai-observability/installation'
+const SESSIONS_DOCS_URL = 'https://posthog.com/docs/ai-observability/sessions'
+const TOOLS_DOCS_URL = 'https://posthog.com/docs/ai-observability/tools'
+
+const SESSIONS: Record<InstrumentationCheckStatusEnumApi, InstrumentationCheckApi> = {
+ ok: {
+ key: AIObservabilityInstrumentationCheckEnumApi.Sessions,
+ status: InstrumentationCheckStatusEnumApi.Ok,
+ title: 'Sessions',
+ detail: 'Traces are grouping into sessions.',
+ docs_url: SESSIONS_DOCS_URL,
+ stats: { generations: 1284, events_with_session: 842, events_declining_session: 0 },
+ },
+ warning: {
+ key: AIObservabilityInstrumentationCheckEnumApi.Sessions,
+ status: InstrumentationCheckStatusEnumApi.Warning,
+ title: 'Sessions',
+ detail: 'No traces include $ai_session_id. If your product has multi-turn conversations, setting it lets us group them into sessions. Workloads that are complete in one trace, like batch jobs or one-shot generation, do not need it. Send $ai_session_id as null on those to say so.',
+ docs_url: SESSIONS_DOCS_URL,
+ stats: { generations: 1284, events_with_session: 0, events_declining_session: 0 },
+ },
+ pending: {
+ key: AIObservabilityInstrumentationCheckEnumApi.Sessions,
+ status: InstrumentationCheckStatusEnumApi.Pending,
+ title: 'Sessions',
+ detail: 'Still collecting data. This check runs once there are 20 generations.',
+ docs_url: SESSIONS_DOCS_URL,
+ stats: { generations: 4, events_with_session: 0, events_declining_session: 0 },
+ },
+ dismissed: {
+ key: AIObservabilityInstrumentationCheckEnumApi.Sessions,
+ status: InstrumentationCheckStatusEnumApi.Dismissed,
+ title: 'Sessions',
+ detail: 'No traces include $ai_session_id. If your product has multi-turn conversations, setting it lets us group them into sessions. Workloads that are complete in one trace, like batch jobs or one-shot generation, do not need it. Send $ai_session_id as null on those to say so.',
+ docs_url: SESSIONS_DOCS_URL,
+ stats: { generations: 1284, events_with_session: 0, events_declining_session: 0 },
+ },
+}
+
+const TOOL_CALLS: Record<InstrumentationCheckStatusEnumApi, InstrumentationCheckApi> = {
+ ok: {
+ key: AIObservabilityInstrumentationCheckEnumApi.ToolCalls,
+ status: InstrumentationCheckStatusEnumApi.Ok,
+ 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 },
+ },
+ warning: {
+ key: AIObservabilityInstrumentationCheckEnumApi.ToolCalls,
+ status: InstrumentationCheckStatusEnumApi.Warning,
+ 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 },
+ },
+ pending: {
+ key: AIObservabilityInstrumentationCheckEnumApi.ToolCalls,
+ status: InstrumentationCheckStatusEnumApi.Pending,
+ 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 },
+ },
+ dismissed: {
+ key: AIObservabilityInstrumentationCheckEnumApi.ToolCalls,
+ status: InstrumentationCheckStatusEnumApi.Dismissed,
+ 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 },
+ },
+}
+
+const USER_IDENTITY: Record<InstrumentationCheckStatusEnumApi, InstrumentationCheckApi> = {
+ ok: {
+ key: AIObservabilityInstrumentationCheckEnumApi.UserIdentity,
+ status: InstrumentationCheckStatusEnumApi.Ok,
+ title: 'User identity',
+ detail: 'AI events are attributed to identified users.',
+ docs_url: INSTALLATION_DOCS_URL,
+ stats: { sdk_generations: 1284, sdk_generations_identified: 1284 },
+ },
+ warning: {
+ key: AIObservabilityInstrumentationCheckEnumApi.UserIdentity,
+ status: InstrumentationCheckStatusEnumApi.Warning,
+ title: 'User identity',
+ detail: 'Generations are arriving with their trace ID as the distinct ID, so usage and cost cannot be tied to people. Set distinct_id to your own user identifier.',
+ docs_url: INSTALLATION_DOCS_URL,
+ stats: { sdk_generations: 1284, sdk_generations_identified: 0 },
+ },
+ pending: {
+ key: AIObservabilityInstrumentationCheckEnumApi.UserIdentity,
+ status: InstrumentationCheckStatusEnumApi.Pending,
+ title: 'User identity',
+ detail: 'This check runs once there are 20 generations from a PostHog SDK. Generations sent over OpenTelemetry are not counted, because we cannot tell whether they are identified.',
+ docs_url: INSTALLATION_DOCS_URL,
+ stats: { sdk_generations: 4, sdk_generations_identified: 0 },
+ },
+ dismissed: {
+ key: AIObservabilityInstrumentationCheckEnumApi.UserIdentity,
+ status: InstrumentationCheckStatusEnumApi.Dismissed,
+ title: 'User identity',
+ detail: 'Generations are arriving with their trace ID as the distinct ID, so usage and cost cannot be tied to people. Set distinct_id to your own user identifier.',
+ docs_url: INSTALLATION_DOCS_URL,
+ stats: { sdk_generations: 1284, sdk_generations_identified: 0 },
+ },
+}
+
+const TRACE_STRUCTURE: Record<InstrumentationCheckStatusEnumApi, InstrumentationCheckApi> = {
+ ok: {
+ key: AIObservabilityInstrumentationCheckEnumApi.TraceStructure,
+ status: InstrumentationCheckStatusEnumApi.Ok,
+ title: 'Trace structure',
+ detail: 'Traces show the steps around your LLM calls.',
+ docs_url: INSTALLATION_DOCS_URL,
+ stats: { total_events: 1611, spans: 327, events_with_parent: 327 },
+ },
+ warning: {
+ key: AIObservabilityInstrumentationCheckEnumApi.TraceStructure,
+ status: InstrumentationCheckStatusEnumApi.Warning,
+ title: 'Trace structure',
+ detail: 'Without spans, a trace shows LLM calls but not the retrieval, chains or sub-agent steps around them.',
+ docs_url: INSTALLATION_DOCS_URL,
+ stats: { total_events: 1611, spans: 0, events_with_parent: 0 },
+ },
+ pending: {
+ key: AIObservabilityInstrumentationCheckEnumApi.TraceStructure,
+ status: InstrumentationCheckStatusEnumApi.Pending,
+ title: 'Trace structure',
+ detail: 'Still collecting data. This check runs once there are 20 AI events.',
+ docs_url: INSTALLATION_DOCS_URL,
+ stats: { total_events: 6, spans: 0, events_with_parent: 0 },
+ },
+ dismissed: {
+ key: AIObservabilityInstrumentationCheckEnumApi.TraceStructure,
+ status: InstrumentationCheckStatusEnumApi.Dismissed,
+ title: 'Trace structure',
+ detail: 'Without spans, a trace shows LLM calls but not the retrieval, chains or sub-agent steps around them.',
+ docs_url: INSTALLATION_DOCS_URL,
+ stats: { total_events: 1611, spans: 0, events_with_parent: 0 },
+ },
+}
+
+function checklist(
+ sessions: InstrumentationCheckStatusEnumApi,
+ toolCalls: InstrumentationCheckStatusEnumApi,
+ userIdentity: InstrumentationCheckStatusEnumApi,
+ traceStructure: InstrumentationCheckStatusEnumApi
+): InstrumentationChecklistApi {
+ return {
+ window_days: 30,
+ checks: [
+ SESSIONS[sessions],
+ TOOL_CALLS[toolCalls],
+ USER_IDENTITY[userIdentity],
+ TRACE_STRUCTURE[traceStructure],
+ ],
+ }
+}
+
+function withChecklist(response: InstrumentationChecklistApi): ReturnType<typeof mswDecorator> {
+ return mswDecorator({
+ get: { '/api/projects/:team_id/ai_observability/instrumentation_checklist/': response },
+ post: {
+ '/api/projects/:team_id/ai_observability/instrumentation_checklist/dismiss/': {
+ ...response,
+ checks: response.checks.map((check, index) =>
+ index === 0 ? { ...check, status: InstrumentationCheckStatusEnumApi.Dismissed } : check
+ ),
+ },
+ '/api/projects/:team_id/ai_observability/instrumentation_checklist/restore/': response,
+ },
+ })
+}
+
+const meta: Meta<typeof InstrumentationChecklistCard> = {
+ component: InstrumentationChecklistCard,
+ title: 'Scenes-App/AI observability/Instrumentation checklist card',
+ parameters: {
+ layout: 'padded',
+ featureFlags: [FEATURE_FLAGS.AI_OBSERVABILITY_INSTRUMENTATION_CHECKLIST],
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof InstrumentationChecklistCard>
+
+export const Warnings: Story = {
+ decorators: [
+ withChecklist(
+ checklist(
+ InstrumentationCheckStatusEnumApi.Warning,
+ InstrumentationCheckStatusEnumApi.Warning,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Ok
+ )
+ ),
+ ],
+}
+
+export const WarningsWithADismissal: Story = {
+ decorators: [
+ withChecklist(
+ checklist(
+ InstrumentationCheckStatusEnumApi.Dismissed,
+ InstrumentationCheckStatusEnumApi.Warning,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Pending
+ )
+ ),
+ ],
+}
+
+export const Passing: Story = {
+ decorators: [
+ withChecklist(
+ checklist(
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Ok
+ )
+ ),
+ ],
+}
+
+export const Collecting: Story = {
+ decorators: [
+ withChecklist(
+ checklist(
+ InstrumentationCheckStatusEnumApi.Pending,
+ InstrumentationCheckStatusEnumApi.Pending,
+ InstrumentationCheckStatusEnumApi.Pending,
+ InstrumentationCheckStatusEnumApi.Pending
+ )
+ ),
+ ],
+}
+
+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.
+ testOptions: { waitForLoadersToDisappear: false },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/ai_observability/instrumentation_checklist/': () => new Promise(() => {}),
+ },
+ }),
+ ],
+}
diff --git a/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.test.tsx b/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.test.tsx
new file mode 100644
index 000000000000..827c8aa7619f
--- /dev/null
+++ b/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.test.tsx
@@ -0,0 +1,207 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { Provider } from 'kea'
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import {
+ aiObservabilityInstrumentationChecklistDismissCreate,
+ aiObservabilityInstrumentationChecklistRestoreCreate,
+ aiObservabilityInstrumentationChecklistRetrieve,
+} from '../generated/api'
+import {
+ AIObservabilityInstrumentationCheckEnumApi,
+ InstrumentationCheckStatusEnumApi,
+ InstrumentationChecklistApi,
+} from '../generated/api.schemas'
+import { InstrumentationChecklistCard } from './InstrumentationChecklistCard'
+import { clearCachedChecklistVerdict, instrumentationChecklistLogic } from './instrumentationChecklistLogic'
+
+jest.mock('../generated/api', () => ({
+ aiObservabilityInstrumentationChecklistRetrieve: jest.fn(),
+ aiObservabilityInstrumentationChecklistDismissCreate: jest.fn(),
+ aiObservabilityInstrumentationChecklistRestoreCreate: jest.fn(),
+}))
+
+const mockRetrieve = aiObservabilityInstrumentationChecklistRetrieve as jest.MockedFunction<
+ typeof aiObservabilityInstrumentationChecklistRetrieve
+>
+const mockDismiss = aiObservabilityInstrumentationChecklistDismissCreate as jest.MockedFunction<
+ typeof aiObservabilityInstrumentationChecklistDismissCreate
+>
+const mockRestore = aiObservabilityInstrumentationChecklistRestoreCreate as jest.MockedFunction<
+ typeof aiObservabilityInstrumentationChecklistRestoreCreate
+>
+
+const CHECK_KEYS = [
+ AIObservabilityInstrumentationCheckEnumApi.Sessions,
+ AIObservabilityInstrumentationCheckEnumApi.ToolCalls,
+ AIObservabilityInstrumentationCheckEnumApi.UserIdentity,
+ AIObservabilityInstrumentationCheckEnumApi.TraceStructure,
+]
+const CHECK_TITLES = ['Sessions', 'Tool calls', 'User identity', 'Trace structure']
+
+function buildChecklist(...statuses: InstrumentationCheckStatusEnumApi[]): InstrumentationChecklistApi {
+ return {
+ window_days: 30,
+ checks: statuses.map((status, index) => ({
+ key: CHECK_KEYS[index],
+ status,
+ title: CHECK_TITLES[index],
+ detail: `A sentence about ${CHECK_TITLES[index]}.`,
+ docs_url: 'https://posthog.com/docs/ai-observability/installation',
+ stats: { generations: 100 },
+ })),
+ }
+}
+
+const { Ok, Warning, Pending, Dismissed } = InstrumentationCheckStatusEnumApi
+
+function toggle(): HTMLElement | null {
+ return document.querySelector('[data-attr="ai-observability-instrumentation-checklist-toggle"]')
+}
+
+function panel(): Element | null {
+ return toggle()?.closest('.LemonCollapsePanel') ?? null
+}
+
+// Re-queried on every use: switching a button to disabled adds a tooltip wrapper, which remounts it.
+function actionButtons(): HTMLElement[] {
+ return Array.from(
+ document.querySelectorAll<HTMLElement>(
+ [
+ '[data-attr="ai-observability-instrumentation-checklist-dismiss"]',
+ '[data-attr="ai-observability-instrumentation-checklist-recheck"]',
+ '[data-attr="ai-observability-instrumentation-checklist-refresh"]',
+ ].join(',')
+ )
+ )
+}
+
+function renderCard(): void {
+ render(
+ <Provider>
+ <InstrumentationChecklistCard />
+ </Provider>
+ )
+}
+
+describe('InstrumentationChecklistCard', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ // Module state by design, so it outlives an unmount and would carry one case into the next.
+ clearCachedChecklistVerdict()
+ initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.AI_OBSERVABILITY_INSTRUMENTATION_CHECKLIST]: true,
+ })
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ const loudnessCases: [string, InstrumentationCheckStatusEnumApi[], string][] = [
+ ['expands on landing when a check is warning', [Warning, Ok, Ok, Dismissed], 'true'],
+ ['collapses when every check passes', [Ok, Ok, Dismissed, Ok], 'false'],
+ ['collapses while the checks are still collecting data', [Pending, Pending, Pending, Pending], 'false'],
+ ]
+
+ it.each(loudnessCases)('%s', async (_, statuses, expanded) => {
+ mockRetrieve.mockResolvedValue(buildChecklist(...statuses))
+ renderCard()
+
+ expect(await screen.findByText('Instrumentation checklist')).toBeInTheDocument()
+ expect(panel()).toHaveAttribute('aria-expanded', expanded)
+ })
+
+ it('stays expandable once every check passes, so a fix can still be verified', async () => {
+ mockRetrieve.mockResolvedValue(buildChecklist(Ok, Ok, Ok, Ok))
+ renderCard()
+
+ expect(await screen.findByText('Instrumentation checklist')).toBeInTheDocument()
+ expect(screen.queryByText('A sentence about Sessions.')).not.toBeInTheDocument()
+
+ await userEvent.click(toggle() as HTMLElement)
+
+ expect(await screen.findByText('A sentence about Sessions.')).toBeInTheDocument()
+ expect(panel()).toHaveAttribute('aria-expanded', 'true')
+ })
+
+ const noVerdictCases: [string, () => void][] = [
+ [
+ 'the feature flag is off',
+ () =>
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.AI_OBSERVABILITY_INSTRUMENTATION_CHECKLIST]: false,
+ }),
+ ],
+ ['the read failed', () => mockRetrieve.mockRejectedValue({ status: 500 })],
+ ]
+
+ it.each(noVerdictCases)('renders nothing, not a skeleton, while %s', async (_, arrange) => {
+ arrange()
+ renderCard()
+
+ await expectLogic(instrumentationChecklistLogic).toFinishAllListeners()
+ expect(screen.queryByText('Instrumentation checklist')).not.toBeInTheDocument()
+ expect(document.querySelector('.LemonSkeleton')).not.toBeInTheDocument()
+ expect(screen.queryByText('Could not refresh the checklist.')).not.toBeInTheDocument()
+ })
+
+ 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')
+
+ mockRetrieve.mockRejectedValue({ status: 500 })
+ await userEvent.click(screen.getByText('Refresh'))
+
+ expect(await screen.findByText('Could not refresh the checklist.')).toBeInTheDocument()
+ expect(screen.getByText('Try again')).toBeInTheDocument()
+ expect(screen.getByText('A sentence about Sessions.')).toBeInTheDocument()
+ })
+
+ it('offers a recheck on a dismissed row, so a dismissal is not a one-way door', async () => {
+ mockRetrieve.mockResolvedValue(buildChecklist(Dismissed, Warning, Ok, Ok))
+ mockRestore.mockResolvedValue(buildChecklist(Warning, Warning, Ok, Ok))
+ renderCard()
+
+ await userEvent.click(await screen.findByText('Recheck'))
+
+ expect(mockRestore).toHaveBeenCalledWith(expect.any(String), { check: 'sessions' })
+ await waitFor(() => expect(screen.queryByText('Recheck')).not.toBeInTheDocument())
+ })
+
+ it('blocks every other action while a dismissal is in flight', async () => {
+ mockRetrieve.mockResolvedValue(buildChecklist(Warning, Warning, Ok, Dismissed))
+ mockDismiss.mockImplementation(() => new Promise(() => {}))
+ renderCard()
+
+ await screen.findByText('Instrumentation checklist')
+ expect(actionButtons()).toHaveLength(4)
+ expect(actionButtons().map((button) => button.getAttribute('aria-disabled'))).toEqual([
+ 'false',
+ 'false',
+ 'false',
+ 'false',
+ ])
+
+ await userEvent.click(actionButtons()[0])
+
+ expect(actionButtons().map((button) => button.getAttribute('aria-disabled'))).toEqual([
+ 'true',
+ 'true',
+ 'true',
+ 'true',
+ ])
+ expect(mockDismiss).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.tsx b/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.tsx
new file mode 100644
index 000000000000..51e487a28691
--- /dev/null
+++ b/products/ai_observability/frontend/instrumentationChecklist/InstrumentationChecklistCard.tsx
@@ -0,0 +1,163 @@
+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 { InstrumentationCheckApi, InstrumentationCheckStatusEnumApi } from '../generated/api.schemas'
+import { instrumentationChecklistLogic } from './instrumentationChecklistLogic'
+
+const PANEL_KEY = 'instrumentation-checklist'
+const BUSY_REASON = 'Wait for the current update to finish'
+
+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" />,
+ [InstrumentationCheckStatusEnumApi.Pending]: <IconClock className="text-muted shrink-0 mt-0.5" />,
+ [InstrumentationCheckStatusEnumApi.Dismissed]: <IconMinusSquare className="text-muted shrink-0 mt-0.5" />,
+}
+
+function InstrumentationCheckRow({ check }: { check: InstrumentationCheckApi }): JSX.Element {
+ const { checklistBusy, pendingCheckKey } = useValues(instrumentationChecklistLogic)
+ const { dismissCheck, restoreCheck } = useActions(instrumentationChecklistLogic)
+
+ const isWarning = check.status === InstrumentationCheckStatusEnumApi.Warning
+ const isDismissed = check.status === InstrumentationCheckStatusEnumApi.Dismissed
+ const isWriting = pendingCheckKey === check.key
+
+ return (
+ <div className="flex items-start gap-2">
+ {STATUS_ICONS[check.status]}
+ <div className="flex-1 min-w-0">
+ <div className={clsx('text-sm font-medium', isDismissed && 'text-muted')}>
+ {check.title}
+ {isDismissed ? (
+ <LemonTag type="muted" size="small" className="ml-2">
+ Not applicable
+ </LemonTag>
+ ) : null}
+ </div>
+ <div className="text-muted text-sm">
+ {check.detail}{' '}
+ {isWarning ? (
+ <Link to={check.docs_url} target="_blank" targetBlankIcon>
+ Learn more
+ </Link>
+ ) : null}
+ </div>
+ </div>
+ {isWarning || isDismissed ? (
+ <LemonButton
+ type="secondary"
+ size="xsmall"
+ className="shrink-0"
+ loading={isWriting}
+ disabledReason={checklistBusy && !isWriting ? BUSY_REASON : undefined}
+ onClick={() => (isDismissed ? restoreCheck(check.key) : dismissCheck(check.key))}
+ data-attr={
+ isDismissed
+ ? 'ai-observability-instrumentation-checklist-recheck'
+ : 'ai-observability-instrumentation-checklist-dismiss'
+ }
+ >
+ {isDismissed ? 'Recheck' : 'Not applicable'}
+ </LemonButton>
+ ) : null}
+ </div>
+ )
+}
+
+/**
+ * Tells a project which AI observability features its instrumentation leaves dark, at the top of
+ * the tab people land on.
+ *
+ * How loud it is comes from `checklistCardState`. Warnings expand on landing; everything else
+ * 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.
+ */
+export function InstrumentationChecklistCard(): JSX.Element | null {
+ const {
+ checklist,
+ checklistLoading,
+ checklistEnabled,
+ 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 warningCount = checks.filter((check) => check.status === InstrumentationCheckStatusEnumApi.Warning).length
+
+ return (
+ <div className="mb-4" data-attr="ai-observability-instrumentation-checklist">
+ <LemonCollapse
+ defaultActiveKey={checklistCardState === 'warnings' ? PANEL_KEY : undefined}
+ panels={[
+ {
+ key: PANEL_KEY,
+ dataAttr: 'ai-observability-instrumentation-checklist-toggle',
+ header: {
+ children: (
+ <div className="flex w-full items-center gap-2">
+ <span className="font-semibold">Instrumentation checklist</span>
+ {checklistCardState === 'warnings' ? (
+ <LemonTag type="warning" size="small">
+ {warningCount === 1
+ ? '1 check needs attention'
+ : `${warningCount} checks need attention`}
+ </LemonTag>
+ ) : (
+ <span className="text-muted font-normal">
+ {checklistCardState === 'collecting'
+ ? 'Still collecting data'
+ : 'No checks need attention'}
+ </span>
+ )}
+ </div>
+ ),
+ },
+ content: (
+ <div className="flex flex-col gap-3">
+ {checks.map((check) => (
+ <InstrumentationCheckRow key={check.key} check={check} />
+ ))}
+ <div className="flex items-center justify-between gap-2 border-t pt-3">
+ {refreshFailed ? (
+ <span className="text-danger text-xs">Could not refresh the checklist.</span>
+ ) : (
+ <span className="text-muted text-xs">
+ Checked over the last {windowDays} days.
+ </span>
+ )}
+ <LemonButton
+ type="secondary"
+ size="xsmall"
+ icon={<IconRefresh />}
+ loading={checklistLoading}
+ disabledReason={pendingCheckKey !== null ? BUSY_REASON : undefined}
+ onClick={() => loadInstrumentationChecklist()}
+ data-attr="ai-observability-instrumentation-checklist-refresh"
+ >
+ {refreshFailed ? 'Try again' : 'Refresh'}
+ </LemonButton>
+ </div>
+ </div>
+ ),
+ },
+ ]}
+ />
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/instrumentationChecklist/TraceStructureNote.test.tsx b/products/ai_observability/frontend/instrumentationChecklist/TraceStructureNote.test.tsx
new file mode 100644
index 000000000000..3383185c7ab7
--- /dev/null
+++ b/products/ai_observability/frontend/instrumentationChecklist/TraceStructureNote.test.tsx
@@ -0,0 +1,133 @@
+import { cleanup, render, screen } from '@testing-library/react'
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { LLMTraceEvent } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+
+import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'
+import { aiObservabilityInstrumentationChecklistRetrieve } from '../generated/api'
+import {
+ AIObservabilityInstrumentationCheckEnumApi,
+ InstrumentationCheckStatusEnumApi,
+ InstrumentationChecklistApi,
+} from '../generated/api.schemas'
+import { hasRecentAIEvents } from '../utils/aiEvents'
+import { instrumentationChecklistLogic } from './instrumentationChecklistLogic'
+import { TraceStructureNote } from './TraceStructureNote'
+
+jest.mock('lib/api')
+jest.mock('../utils/aiEvents')
+jest.mock('../generated/api', () => ({
+ ...jest.requireActual('../generated/api'),
+ aiObservabilityInstrumentationChecklistRetrieve: jest.fn(),
+}))
+
+const mockRetrieve = aiObservabilityInstrumentationChecklistRetrieve as jest.MockedFunction<
+ typeof aiObservabilityInstrumentationChecklistRetrieve
+>
+const mockHasRecentAIEvents = hasRecentAIEvents as jest.MockedFunction<typeof hasRecentAIEvents>
+
+const NOTE_LABEL = 'No spans in this trace.'
+const TRACE_STRUCTURE_DETAIL =
+ 'Without spans, a trace shows LLM calls but not the retrieval, chains or sub-agent steps around them.'
+const DOCS_URL = 'https://posthog.com/docs/ai-observability/installation'
+
+const MODEL_FILTER: AnyPropertyFilter = {
+ type: PropertyFilterType.Event,
+ key: '$ai_model',
+ operator: PropertyOperator.Exact,
+ value: ['gpt-4o'],
+}
+
+function traceEvent(event: string, properties: Record<string, unknown> = {}): LLMTraceEvent {
+ return { id: `${event}-1`, event, properties, createdAt: '2026-01-01T00:00:00Z' }
+}
+
+const GENERATIONS_ONLY = [traceEvent('$ai_generation'), traceEvent('$ai_generation')]
+
+function checklistWith(status: InstrumentationCheckStatusEnumApi): InstrumentationChecklistApi {
+ return {
+ window_days: 30,
+ checks: [
+ {
+ key: AIObservabilityInstrumentationCheckEnumApi.TraceStructure,
+ status,
+ title: 'Trace structure',
+ detail: TRACE_STRUCTURE_DETAIL,
+ docs_url: DOCS_URL,
+ stats: { total_events: 100, spans: 0, events_with_parent: 0 },
+ },
+ ],
+ }
+}
+
+describe('TraceStructureNote', () => {
+ let checklistLogic: ReturnType<typeof instrumentationChecklistLogic.build>
+ let sharedLogic: ReturnType<typeof aiObservabilitySharedLogic.build>
+
+ beforeEach(async () => {
+ jest.clearAllMocks()
+ localStorage.clear()
+ mockHasRecentAIEvents.mockResolvedValue(true)
+ mockRetrieve.mockResolvedValue(checklistWith(InstrumentationCheckStatusEnumApi.Warning))
+ initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.AI_OBSERVABILITY_INSTRUMENTATION_CHECKLIST]: true,
+ })
+ sharedLogic = aiObservabilitySharedLogic()
+ sharedLogic.mount()
+ checklistLogic = instrumentationChecklistLogic()
+ checklistLogic.mount()
+ await expectLogic(checklistLogic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+ })
+
+ afterEach(() => {
+ cleanup()
+ checklistLogic.unmount()
+ sharedLogic.unmount()
+ featureFlagLogic.unmount()
+ })
+
+ // The list surfaces drop their verdict once a filter is on, since a filter can explain an empty
+ // table. Nothing a user narrows can explain a missing span, so this note must survive that state.
+ it('names the missing spans even under filters that suppress the tab empty states', () => {
+ sharedLogic.actions.setPropertyFilters([MODEL_FILTER])
+ sharedLogic.actions.setDates('-6m', null)
+
+ render(<TraceStructureNote events={GENERATIONS_ONLY} />)
+
+ expect(screen.getByText(NOTE_LABEL)).not.toBeNull()
+ expect(screen.getByText(TRACE_STRUCTURE_DETAIL, { exact: false })).not.toBeNull()
+ expect(screen.getByText('Learn more').closest('a')?.getAttribute('href')).toBe(DOCS_URL)
+ })
+
+ // The verdict covers 30 days, while a single trace still renders from beyond that window, so a
+ // project that stopped emitting spans can open a trace that visibly has them.
+ it.each([
+ ['a span', [traceEvent('$ai_generation'), traceEvent('$ai_span')]],
+ ['an event nested under a parent', [traceEvent('$ai_generation', { $ai_parent_id: 'trace-1' })]],
+ ])('says nothing about a trace that has %s', (_, events) => {
+ const { container } = render(<TraceStructureNote events={events} />)
+
+ expect(container.innerHTML).toBe('')
+ })
+
+ it.each([
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Pending,
+ InstrumentationCheckStatusEnumApi.Dismissed,
+ ])('stays out of the way when the check graded %s', async (status) => {
+ mockRetrieve.mockResolvedValue(checklistWith(status))
+ checklistLogic.actions.loadInstrumentationChecklist()
+ await expectLogic(checklistLogic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+
+ const { container } = render(<TraceStructureNote events={GENERATIONS_ONLY} />)
+
+ expect(container.innerHTML).toBe('')
+ })
+})
diff --git a/products/ai_observability/frontend/instrumentationChecklist/TraceStructureNote.tsx b/products/ai_observability/frontend/instrumentationChecklist/TraceStructureNote.tsx
new file mode 100644
index 000000000000..1e6b9d4998a6
--- /dev/null
+++ b/products/ai_observability/frontend/instrumentationChecklist/TraceStructureNote.tsx
@@ -0,0 +1,51 @@
+import { useValues } from 'kea'
+
+import { LemonBanner, Link } from '@posthog/lemon-ui'
+
+import { LLMTraceEvent } from '~/queries/schema/schema-general'
+
+import { AIObservabilityInstrumentationCheckEnumApi } from '../generated/api.schemas'
+import { instrumentationChecklistLogic } from './instrumentationChecklistLogic'
+
+// Mirrors the trace_structure check's own signals, `spans > 0 or events_with_parent > 0`.
+function hasTraceStructure(events: LLMTraceEvent[]): boolean {
+ return events.some((event) => event.event === '$ai_span' || !!event.properties.$ai_parent_id)
+}
+
+/**
+ * Says why a trace tree holds nothing but LLM calls, next to the tree itself.
+ *
+ * Gated on `warningForCheck` alone, unlike the list surfaces, which route through
+ * `useInstrumentationWarning` to suppress the verdict once the user narrows the view. One trace has
+ * no filters that could explain away a missing span, and that guard reads the same keyed
+ * `aiObservabilitySharedLogic` the list tabs write to, whose date range and property filters persist
+ * in localStorage, so it would silence the note here based on a view the reader is not looking at.
+ *
+ * The trace on screen gates it instead. The project verdict is graded over a 30 day window, while a
+ * single trace renders from the events table past that window, so a project that stopped emitting
+ * spans months ago can still open a trace that visibly has them.
+ */
+export function TraceStructureNote({ events }: { events: LLMTraceEvent[] }): JSX.Element | null {
+ const { warningForCheck } = useValues(instrumentationChecklistLogic)
+ const warning = warningForCheck(AIObservabilityInstrumentationCheckEnumApi.TraceStructure)
+
+ if (!warning || hasTraceStructure(events)) {
+ return null
+ }
+
+ return (
+ <LemonBanner type="info" square className="shrink-0 border-x-0 border-b-0">
+ <p className="text-xs font-normal">
+ <span className="font-medium">No spans in this trace.</span> {warning.detail}{' '}
+ <Link
+ to={warning.docs_url}
+ target="_blank"
+ targetBlankIcon
+ data-attr="llma-trace-structure-instrumentation-docs"
+ >
+ Learn more
+ </Link>
+ </p>
+ </LemonBanner>
+ )
+}
diff --git a/products/ai_observability/frontend/instrumentationChecklist/instrumentationChecklistLogic.test.ts b/products/ai_observability/frontend/instrumentationChecklist/instrumentationChecklistLogic.test.ts
new file mode 100644
index 000000000000..264254366e1a
--- /dev/null
+++ b/products/ai_observability/frontend/instrumentationChecklist/instrumentationChecklistLogic.test.ts
@@ -0,0 +1,399 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import {
+ aiObservabilityInstrumentationChecklistDismissCreate,
+ aiObservabilityInstrumentationChecklistRestoreCreate,
+ aiObservabilityInstrumentationChecklistRetrieve,
+} from '../generated/api'
+import {
+ AIObservabilityInstrumentationCheckEnumApi,
+ InstrumentationCheckStatusEnumApi,
+ InstrumentationChecklistApi,
+} from '../generated/api.schemas'
+import {
+ InstrumentationChecklistCardState,
+ clearCachedChecklistVerdict,
+ instrumentationChecklistLogic,
+} from './instrumentationChecklistLogic'
+
+jest.mock('../generated/api', () => ({
+ aiObservabilityInstrumentationChecklistRetrieve: jest.fn(),
+ aiObservabilityInstrumentationChecklistDismissCreate: jest.fn(),
+ aiObservabilityInstrumentationChecklistRestoreCreate: jest.fn(),
+}))
+
+const mockRetrieve = aiObservabilityInstrumentationChecklistRetrieve as jest.MockedFunction<
+ typeof aiObservabilityInstrumentationChecklistRetrieve
+>
+const mockDismiss = aiObservabilityInstrumentationChecklistDismissCreate as jest.MockedFunction<
+ typeof aiObservabilityInstrumentationChecklistDismissCreate
+>
+const mockRestore = aiObservabilityInstrumentationChecklistRestoreCreate as jest.MockedFunction<
+ typeof aiObservabilityInstrumentationChecklistRestoreCreate
+>
+
+const CHECK_KEYS = [
+ AIObservabilityInstrumentationCheckEnumApi.Sessions,
+ AIObservabilityInstrumentationCheckEnumApi.ToolCalls,
+ AIObservabilityInstrumentationCheckEnumApi.UserIdentity,
+ AIObservabilityInstrumentationCheckEnumApi.TraceStructure,
+]
+
+function buildChecklist(...statuses: InstrumentationCheckStatusEnumApi[]): InstrumentationChecklistApi {
+ return {
+ window_days: 30,
+ checks: statuses.map((status, index) => ({
+ key: CHECK_KEYS[index],
+ status,
+ title: 'Sessions',
+ detail: 'A sentence about the counts.',
+ docs_url: 'https://posthog.com/docs/ai-observability/installation',
+ stats: { generations: 100 },
+ })),
+ }
+}
+
+const ALL_OK = buildChecklist(
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Ok
+)
+
+describe('instrumentationChecklistLogic', () => {
+ let logic: ReturnType<typeof instrumentationChecklistLogic.build>
+
+ function setFlag(enabled: boolean): void {
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.AI_OBSERVABILITY_INSTRUMENTATION_CHECKLIST]: enabled,
+ })
+ }
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ // The verdict cache is module state, so it outlives a logic unmount by design and would
+ // otherwise carry one test's checklist into the next.
+ clearCachedChecklistVerdict()
+ mockRetrieve.mockResolvedValue(ALL_OK)
+ initKeaTests()
+ featureFlagLogic.mount()
+ setFlag(true)
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ featureFlagLogic.unmount()
+ })
+
+ it('reuses a fresh verdict instead of refetching on every remount', async () => {
+ // The trace view mounts this logic once per trace opened, and the read behind it is an
+ // uncached 30 day aggregate, so a remount has to reuse the verdict rather than refire it.
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+ expect(mockRetrieve).toHaveBeenCalledTimes(1)
+ logic.unmount()
+
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+
+ expect(mockRetrieve).toHaveBeenCalledTimes(1)
+ expect(logic.values.checklistCardState).toBe('passing')
+ })
+
+ it('loads the checklist on mount and exposes the graded checks', async () => {
+ const checklist = buildChecklist(
+ InstrumentationCheckStatusEnumApi.Warning,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Pending,
+ InstrumentationCheckStatusEnumApi.Dismissed
+ )
+ mockRetrieve.mockResolvedValue(checklist)
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+ expect(mockRetrieve).toHaveBeenCalledTimes(1)
+ expect(logic.values.checks).toEqual(checklist.checks)
+ expect(logic.values.windowDays).toBe(30)
+ })
+
+ it('makes no request while the feature flag is off', async () => {
+ setFlag(false)
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockRetrieve).not.toHaveBeenCalled()
+ expect(logic.values.checklist).toBeNull()
+ expect(logic.values.checklistCardState).toBe('hidden')
+ })
+
+ it('loads once the feature flag arrives after mount', async () => {
+ setFlag(false)
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ setFlag(true)
+
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+ expect(mockRetrieve).toHaveBeenCalledTimes(1)
+ expect(logic.values.checklistCardState).toBe('passing')
+ })
+
+ it('loads when the feature flag arrives in the same tick as mount', async () => {
+ setFlag(false)
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+ // No awaiting: this is the cold-page ordering, where flags land while a mount-time load
+ // would still be in flight. A load started before the flag resolves returns null and blocks
+ // the retry, so the card would sit hidden behind a skeleton that never resolves.
+ setFlag(true)
+
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+ expect(mockRetrieve).toHaveBeenCalledTimes(1)
+ expect(logic.values.checklistCardState).toBe('passing')
+ })
+
+ it('leaves every consumer on generic copy when the request fails, with nothing surfaced', async () => {
+ const toastError = jest.spyOn(lemonToast, 'error')
+ mockRetrieve.mockRejectedValue({ status: 500, detail: 'Something broke' })
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistFailure'])
+ expect(logic.values.checklist).toBeNull()
+ expect(logic.values.checks).toEqual([])
+ expect(logic.values.checklistCardState).toBe('hidden')
+ expect(logic.values.warningForCheck(AIObservabilityInstrumentationCheckEnumApi.Sessions)).toBeNull()
+ expect(logic.values.refreshFailed).toBe(false)
+ expect(toastError).not.toHaveBeenCalled()
+ })
+
+ it('flags a failed refresh, and clears the flag once a later load answers', async () => {
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+ expect(logic.values.refreshFailed).toBe(false)
+
+ mockRetrieve.mockRejectedValue({ status: 500 })
+ logic.actions.loadInstrumentationChecklist()
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistFailure'])
+ expect(logic.values.refreshFailed).toBe(true)
+ expect(logic.values.checklistCardState).toBe('passing')
+
+ mockRetrieve.mockResolvedValue(ALL_OK)
+ logic.actions.loadInstrumentationChecklist()
+ expect(logic.values.refreshFailed).toBe(false)
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+ expect(logic.values.refreshFailed).toBe(false)
+ })
+
+ const cardStateCases: [string, InstrumentationCheckStatusEnumApi[], InstrumentationChecklistCardState][] = [
+ [
+ 'a warning is present',
+ [
+ InstrumentationCheckStatusEnumApi.Warning,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Dismissed,
+ ],
+ 'warnings',
+ ],
+ [
+ 'everything is ok or dismissed',
+ [
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Dismissed,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Dismissed,
+ ],
+ 'passing',
+ ],
+ [
+ 'everything is dismissed',
+ [
+ InstrumentationCheckStatusEnumApi.Dismissed,
+ InstrumentationCheckStatusEnumApi.Dismissed,
+ InstrumentationCheckStatusEnumApi.Dismissed,
+ InstrumentationCheckStatusEnumApi.Dismissed,
+ ],
+ 'passing',
+ ],
+ [
+ 'every check is below its volume floor',
+ [
+ InstrumentationCheckStatusEnumApi.Pending,
+ InstrumentationCheckStatusEnumApi.Pending,
+ InstrumentationCheckStatusEnumApi.Pending,
+ InstrumentationCheckStatusEnumApi.Pending,
+ ],
+ 'collecting',
+ ],
+ [
+ 'every check that was not dismissed is below its volume floor',
+ [
+ InstrumentationCheckStatusEnumApi.Dismissed,
+ InstrumentationCheckStatusEnumApi.Pending,
+ InstrumentationCheckStatusEnumApi.Pending,
+ InstrumentationCheckStatusEnumApi.Pending,
+ ],
+ 'collecting',
+ ],
+ [
+ 'only some checks are below their volume floor',
+ [
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Pending,
+ InstrumentationCheckStatusEnumApi.Pending,
+ InstrumentationCheckStatusEnumApi.Pending,
+ ],
+ 'passing',
+ ],
+ ]
+
+ it.each(cardStateCases)('reports card state %s', async (_, statuses, expected) => {
+ mockRetrieve.mockResolvedValue(buildChecklist(...statuses))
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+ expect(logic.values.checklistCardState).toBe(expected)
+ })
+
+ // A stopped rollout has to take the card and the empty-state overrides with it, including in
+ // tabs that are already open and on the load where localStorage replays the old flag set.
+ it('takes a loaded checklist back off screen when the flag goes off', async () => {
+ mockRetrieve.mockResolvedValue(
+ buildChecklist(
+ InstrumentationCheckStatusEnumApi.Warning,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Ok
+ )
+ )
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+ expect(logic.values.checklistCardState).toBe('warnings')
+
+ setFlag(false)
+
+ expect(logic.values.checklistCardState).toBe('hidden')
+ expect(logic.values.warningForCheck(AIObservabilityInstrumentationCheckEnumApi.Sessions)).toBeNull()
+ })
+
+ it('only offers a check to an empty state when that check is warning', async () => {
+ mockRetrieve.mockResolvedValue(
+ buildChecklist(
+ InstrumentationCheckStatusEnumApi.Warning,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Pending,
+ InstrumentationCheckStatusEnumApi.Dismissed
+ )
+ )
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+
+ expect(logic.values.warningForCheck(AIObservabilityInstrumentationCheckEnumApi.Sessions)?.key).toBe('sessions')
+ expect(logic.values.warningForCheck(AIObservabilityInstrumentationCheckEnumApi.ToolCalls)).toBeNull()
+ expect(logic.values.warningForCheck(AIObservabilityInstrumentationCheckEnumApi.UserIdentity)).toBeNull()
+ expect(logic.values.warningForCheck(AIObservabilityInstrumentationCheckEnumApi.TraceStructure)).toBeNull()
+ })
+
+ const writeCases: [
+ string,
+ () => typeof mockDismiss,
+ (check: AIObservabilityInstrumentationCheckEnumApi) => void,
+ InstrumentationCheckStatusEnumApi,
+ ][] = [
+ [
+ 'dismissCheck',
+ () => mockDismiss,
+ (check) => logic.actions.dismissCheck(check),
+ InstrumentationCheckStatusEnumApi.Dismissed,
+ ],
+ [
+ 'restoreCheck',
+ () => mockRestore,
+ (check) => logic.actions.restoreCheck(check),
+ InstrumentationCheckStatusEnumApi.Warning,
+ ],
+ ]
+
+ it.each(writeCases)(
+ 'applies the checklist %s returns without refetching',
+ async (_, getMock, write, resultingStatus) => {
+ const recomputed = buildChecklist(
+ resultingStatus,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Ok,
+ InstrumentationCheckStatusEnumApi.Ok
+ )
+ getMock().mockResolvedValue(recomputed)
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+
+ await expectLogic(logic, () => {
+ write(AIObservabilityInstrumentationCheckEnumApi.Sessions)
+ }).toFinishAllListeners()
+
+ expect(getMock()).toHaveBeenCalledWith(expect.any(String), { check: 'sessions' })
+ expect(logic.values.checks[0].status).toBe(resultingStatus)
+ expect(logic.values.pendingCheckKey).toBeNull()
+ expect(mockRetrieve).toHaveBeenCalledTimes(1)
+ }
+ )
+
+ it('surfaces a failed write rather than leaving the click looking ignored', async () => {
+ const toastError = jest.spyOn(lemonToast, 'error')
+ mockDismiss.mockRejectedValue({ status: 500 })
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+ const statusBeforeWrite = logic.values.checks[0].status
+
+ await expectLogic(logic, () => {
+ logic.actions.dismissCheck(AIObservabilityInstrumentationCheckEnumApi.Sessions)
+ }).toFinishAllListeners()
+
+ expect(toastError).toHaveBeenCalledTimes(1)
+ expect(logic.values.checks[0].status).toBe(statusBeforeWrite)
+ expect(logic.values.pendingCheckKey).toBeNull()
+ expect(logic.values.checklistBusy).toBe(false)
+ })
+
+ it('ignores a repeat dismissal of the same check while the first is still in flight', async () => {
+ let resolveDismiss: (checklist: InstrumentationChecklistApi) => void = () => {}
+ mockDismiss.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveDismiss = resolve
+ })
+ )
+ logic = instrumentationChecklistLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadInstrumentationChecklistSuccess'])
+
+ logic.actions.dismissCheck(AIObservabilityInstrumentationCheckEnumApi.Sessions)
+ logic.actions.dismissCheck(AIObservabilityInstrumentationCheckEnumApi.Sessions)
+ expect(mockDismiss).toHaveBeenCalledTimes(1)
+ expect(logic.values.pendingCheckKey).toBe('sessions')
+ expect(logic.values.checklistBusy).toBe(true)
+
+ resolveDismiss(ALL_OK)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.pendingCheckKey).toBeNull()
+ expect(logic.values.checklistBusy).toBe(false)
+ })
+})
diff --git a/products/ai_observability/frontend/instrumentationChecklist/instrumentationChecklistLogic.ts b/products/ai_observability/frontend/instrumentationChecklist/instrumentationChecklistLogic.ts
new file mode 100644
index 000000000000..7de330ae71b0
--- /dev/null
+++ b/products/ai_observability/frontend/instrumentationChecklist/instrumentationChecklistLogic.ts
@@ -0,0 +1,304 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import {
+ aiObservabilityInstrumentationChecklistDismissCreate,
+ aiObservabilityInstrumentationChecklistRestoreCreate,
+ aiObservabilityInstrumentationChecklistRetrieve,
+} from '../generated/api'
+import {
+ AIObservabilityInstrumentationCheckEnumApi,
+ InstrumentationCheckActionApi,
+ InstrumentationCheckApi,
+ InstrumentationCheckStatusEnumApi,
+ InstrumentationChecklistApi,
+} from '../generated/api.schemas'
+
+/**
+ * How loudly the dashboard card should present itself.
+ *
+ * - `hidden`: nothing to say. No checklist has loaded, the flag is off, or the request failed.
+ * - `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'
+
+/**
+ * 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.
+ *
+ * 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.
+ */
+const VERDICT_TTL_MS = 5 * 60 * 1000
+let cachedVerdict: { at: number; teamId: number | null; checklist: InstrumentationChecklistApi } | null = null
+
+export function clearCachedChecklistVerdict(): void {
+ cachedVerdict = null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface instrumentationChecklistLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ currentTeamId: number | null // teamLogic
+ checklist: InstrumentationChecklistApi | null
+ checklistBusy: boolean
+ checklistCardState: InstrumentationChecklistCardState
+ checklistEnabled: boolean
+ checklistLoading: boolean
+ checks: InstrumentationCheckApi[]
+ lastLoadFailed: boolean
+ pendingCheckKey: AIObservabilityInstrumentationCheckEnumApi | null
+ refreshFailed: boolean
+ warningForCheck: (key: AIObservabilityInstrumentationCheckEnumApi) => InstrumentationCheckApi | null
+ windowDays: number | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface instrumentationChecklistLogicActions {
+ setFeatureFlags: (
+ flags: string[],
+ variants: Record<string, boolean | string>
+ ) => {
+ flags: string[]
+ variants: Record<string, boolean | string>
+ } // featureFlagLogic
+ dismissCheck: (check: AIObservabilityInstrumentationCheckEnumApi) => {
+ check: AIObservabilityInstrumentationCheckEnumApi
+ }
+ loadInstrumentationChecklist: (_: void) => void
+ loadInstrumentationChecklistFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadInstrumentationChecklistSuccess: (
+ checklist: InstrumentationChecklistApi | null,
+ payload?: void
+ ) => {
+ checklist: InstrumentationChecklistApi | null
+ payload?: void
+ }
+ restoreCheck: (check: AIObservabilityInstrumentationCheckEnumApi) => {
+ check: AIObservabilityInstrumentationCheckEnumApi
+ }
+ setPendingCheck: (check: AIObservabilityInstrumentationCheckEnumApi | null) => {
+ check: AIObservabilityInstrumentationCheckEnumApi | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface instrumentationChecklistLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ checklistEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ checks: (checklist: InstrumentationChecklistApi | null) => InstrumentationCheckApi[]
+ windowDays: (checklist: InstrumentationChecklistApi | null) => number | null
+ checklistBusy: (
+ checklistLoading: boolean,
+ pendingCheckKey: AIObservabilityInstrumentationCheckEnumApi | null
+ ) => boolean
+ checklistCardState: (
+ checklistEnabled: boolean,
+ checks: InstrumentationCheckApi[]
+ ) => InstrumentationChecklistCardState
+ warningForCheck: (
+ checklistEnabled: boolean,
+ checks: InstrumentationCheckApi[]
+ ) => (key: AIObservabilityInstrumentationCheckEnumApi) => InstrumentationCheckApi | null
+ refreshFailed: (checklist: InstrumentationChecklistApi | null, lastLoadFailed: boolean) => boolean
+ }
+}
+
+export type instrumentationChecklistLogicType = MakeLogicType<
+ instrumentationChecklistLogicValues,
+ instrumentationChecklistLogicActions,
+ Record<string, any>,
+ instrumentationChecklistLogicMeta
+>
+
+/**
+ * Owns the project's instrumentation checklist: the dashboard card, the tab empty-state
+ * overrides and the trace-detail note all read their verdict from here.
+ *
+ * Every failure mode collapses to the same shape: `checklistCardState` sits at 'hidden' and
+ * `warningForCheck` returns null, whether the flag is off, the request failed, or nothing has
+ * loaded yet. A consumer therefore needs one branch for "no checklist", and nothing here ever
+ * accuses a project of missing instrumentation on data it could not read.
+ *
+ * Both write endpoints return the whole recomputed checklist, so a dismissal or a restore
+ * installs its own response rather than triggering a second read.
+ */
+export const instrumentationChecklistLogic = kea<instrumentationChecklistLogicType>([
+ path(['products', 'ai_observability', 'frontend', 'instrumentationChecklist', 'instrumentationChecklistLogic']),
+ connect(() => ({
+ values: [featureFlagLogic, ['featureFlags'], teamLogic, ['currentTeamId']],
+ actions: [featureFlagLogic, ['setFeatureFlags']],
+ })),
+ actions({
+ dismissCheck: (check: AIObservabilityInstrumentationCheckEnumApi) => ({ check }),
+ restoreCheck: (check: AIObservabilityInstrumentationCheckEnumApi) => ({ check }),
+ setPendingCheck: (check: AIObservabilityInstrumentationCheckEnumApi | null) => ({ check }),
+ }),
+ loaders(({ values }) => ({
+ checklist: [
+ null as InstrumentationChecklistApi | null,
+ {
+ loadInstrumentationChecklist: async (
+ _: void,
+ breakpoint
+ ): Promise<InstrumentationChecklistApi | null> => {
+ if (!values.checklistEnabled) {
+ return null
+ }
+ const response = await aiObservabilityInstrumentationChecklistRetrieve(String(values.currentTeamId))
+ breakpoint()
+ cachedVerdict = { at: performance.now(), teamId: values.currentTeamId, checklist: response }
+ return response
+ },
+ },
+ ],
+ })),
+ reducers({
+ pendingCheckKey: [
+ null as AIObservabilityInstrumentationCheckEnumApi | null,
+ {
+ setPendingCheck: (_, { check }) => check,
+ },
+ ],
+ lastLoadFailed: [
+ false,
+ {
+ loadInstrumentationChecklist: () => false,
+ loadInstrumentationChecklistSuccess: () => false,
+ loadInstrumentationChecklistFailure: () => true,
+ },
+ ],
+ }),
+ selectors({
+ checklistEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean =>
+ !!featureFlags[FEATURE_FLAGS.AI_OBSERVABILITY_INSTRUMENTATION_CHECKLIST],
+ ],
+ checks: [
+ (s) => [s.checklist],
+ (checklist: InstrumentationChecklistApi | null): InstrumentationCheckApi[] => checklist?.checks ?? [],
+ ],
+ windowDays: [
+ (s) => [s.checklist],
+ (checklist: InstrumentationChecklistApi | null): number | null => checklist?.window_days ?? null,
+ ],
+ checklistBusy: [
+ (s) => [s.checklistLoading, s.pendingCheckKey],
+ (checklistLoading: boolean, pendingCheckKey: AIObservabilityInstrumentationCheckEnumApi | null): boolean =>
+ checklistLoading || pendingCheckKey !== null,
+ ],
+ checklistCardState: [
+ (s) => [s.checklistEnabled, s.checks],
+ (checklistEnabled: boolean, checks: InstrumentationCheckApi[]): InstrumentationChecklistCardState => {
+ if (!checklistEnabled || checks.length === 0) {
+ return 'hidden'
+ }
+ if (checks.some((check) => check.status === InstrumentationCheckStatusEnumApi.Warning)) {
+ return 'warnings'
+ }
+ // A dismissal is the team's judgement, not evidence the project passed anything, so
+ // it must not turn a project whose every other check is still pending into 'passing'.
+ const gradedOk = checks.some((check) => check.status === InstrumentationCheckStatusEnumApi.Ok)
+ const stillPending = checks.some((check) => check.status === InstrumentationCheckStatusEnumApi.Pending)
+ if (!gradedOk && stillPending) {
+ return 'collecting'
+ }
+ return 'passing'
+ },
+ ],
+ warningForCheck: [
+ (s) => [s.checklistEnabled, s.checks],
+ (
+ checklistEnabled: boolean,
+ checks: InstrumentationCheckApi[]
+ ): ((key: AIObservabilityInstrumentationCheckEnumApi) => InstrumentationCheckApi | null) => {
+ if (!checklistEnabled) {
+ return () => null
+ }
+ return (key: AIObservabilityInstrumentationCheckEnumApi) =>
+ checks.find(
+ (check) => check.key === key && check.status === InstrumentationCheckStatusEnumApi.Warning
+ ) ?? null
+ },
+ ],
+ // A failed first read stays invisible, so a retry is offered only for a refresh that
+ // failed under a checklist already on screen. kea-loaders keeps the previous value on
+ // failure, which is what makes the two cases distinguishable.
+ refreshFailed: [
+ (s) => [s.checklist, s.lastLoadFailed],
+ (checklist: InstrumentationChecklistApi | null, lastLoadFailed: boolean): boolean =>
+ checklist !== null && lastLoadFailed,
+ ],
+ }),
+ listeners(({ actions, values }) => {
+ async function writeCheck(
+ check: AIObservabilityInstrumentationCheckEnumApi,
+ write: (projectId: string, body: InstrumentationCheckActionApi) => Promise<InstrumentationChecklistApi>
+ ): Promise<void> {
+ // One request at a time. A repeat click would post twice, and a write racing a read
+ // would have its recomputed checklist overwritten by the read's older response.
+ if (values.checklistBusy) {
+ return
+ }
+ actions.setPendingCheck(check)
+ try {
+ const recomputed = await write(String(values.currentTeamId), { check })
+ cachedVerdict = { at: performance.now(), teamId: values.currentTeamId, checklist: recomputed }
+ actions.loadInstrumentationChecklistSuccess(recomputed)
+ } catch {
+ // The read path stays silent so we never accuse a project on data we could not read,
+ // but a click that visibly does nothing reads as a broken button.
+ lemonToast.error('Could not update this check. Try again.')
+ } finally {
+ actions.setPendingCheck(null)
+ }
+ }
+
+ return {
+ setFeatureFlags: () => {
+ // A staged-rollout flag is not part of the server-rendered app context, so on a
+ // cold load it only arrives after mount. Fetch then rather than waiting for the
+ // user to navigate.
+ if (values.checklistEnabled && values.checklist === null && !values.checklistLoading) {
+ actions.loadInstrumentationChecklist()
+ }
+ },
+ dismissCheck: ({ check }) => writeCheck(check, aiObservabilityInstrumentationChecklistDismissCreate),
+ restoreCheck: ({ check }) => writeCheck(check, aiObservabilityInstrumentationChecklistRestoreCreate),
+ }
+ }),
+ afterMount(({ actions, values }) => {
+ // Loading before the flag resolves would hold `checklistLoading` true while the request
+ // short-circuits to null, and the setFeatureFlags listener would then skip its own retry,
+ // leaving the card hidden for good. On a cold page the flag arriving starts the first load.
+ if (!values.checklistEnabled) {
+ return
+ }
+ if (
+ cachedVerdict &&
+ cachedVerdict.teamId === values.currentTeamId &&
+ performance.now() - cachedVerdict.at < VERDICT_TTL_MS
+ ) {
+ actions.loadInstrumentationChecklistSuccess(cachedVerdict.checklist)
+ return
+ }
+ actions.loadInstrumentationChecklist()
+ }),
+])
diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yaml
index f33b31299907..a21888183d0c 100644
--- a/products/ai_observability/mcp/tools.yaml
+++ b/products/ai_observability/mcp/tools.yaml
@@ -14,6 +14,15 @@ ui_apps:
data_type: LLMCostsData
view_component: LLMCostsView
tools:
+ ai-observability-instrumentation-checklist-dismiss-create:
+ operation: ai_observability_instrumentation_checklist_dismiss_create
+ enabled: false
+ ai-observability-instrumentation-checklist-restore-create:
+ operation: ai_observability_instrumentation_checklist_restore_create
+ enabled: false
+ ai-observability-instrumentation-checklist-retrieve:
+ operation: ai_observability_instrumentation_checklist_retrieve
+ enabled: false
datasets-exports-content-retrieve:
operation: datasets_exports_content_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f8bb076f1203..16617a64d93c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -31,6 +31,22 @@ export namespace Schemas {
AiGenerationClusters: '$ai_generation_clusters',
} as const;
+ /**
+ * * `sessions` - sessions
+ * * `tool_calls` - tool_calls
+ * * `user_identity` - user_identity
+ * * `trace_structure` - trace_structure
+ */
+ export type AIObservabilityInstrumentationCheckEnum = typeof AIObservabilityInstrumentationCheckEnum[keyof typeof AIObservabilityInstrumentationCheckEnum];
+
+
+ export const AIObservabilityInstrumentationCheckEnum = {
+ Sessions: 'sessions',
+ ToolCalls: 'tool_calls',
+ UserIdentity: 'user_identity',
+ TraceStructure: 'trace_structure',
+ } as const;
+
/**
* * `since_last_sent` - Since last report
* * `last_n_days` - Last N days
@@ -45134,6 +45150,69 @@ export namespace Schemas {
return_path?: string;
}
+ /**
+ * Counts this check was graded from, over the same window. Which counts appear depends on the check.
+ */
+ export type InstrumentationCheckStats = {[key: string]: number};
+
+ /**
+ * * `ok` - ok
+ * * `warning` - warning
+ * * `pending` - pending
+ * * `dismissed` - dismissed
+ */
+ export type InstrumentationCheckStatusEnum = typeof InstrumentationCheckStatusEnum[keyof typeof InstrumentationCheckStatusEnum];
+
+
+ export const InstrumentationCheckStatusEnum = {
+ Ok: 'ok',
+ Warning: 'warning',
+ Pending: 'pending',
+ Dismissed: 'dismissed',
+ } as const;
+
+ export interface InstrumentationCheck {
+ /** Identifier of the check. Stable across statuses, so a surface can key its own copy off it.
+ *
+ * * `sessions` - sessions
+ * * `tool_calls` - tool_calls
+ * * `user_identity` - user_identity
+ * * `trace_structure` - trace_structure */
+ key: AIObservabilityInstrumentationCheckEnum;
+ /** How the check graded: 'ok' when the instrumentation is present, 'warning' when it is absent, 'pending' when the project has too little traffic to judge, and 'dismissed' when someone on the team marked the check as not applicable.
+ *
+ * * `ok` - ok
+ * * `warning` - warning
+ * * `pending` - pending
+ * * `dismissed` - dismissed */
+ status: InstrumentationCheckStatusEnum;
+ /** Short label for the check, the same for every status. */
+ title: string;
+ /** Sentence explaining what the counts mean and, for a warning, what to send. A dismissed check keeps the sentence its counts earned. */
+ detail: string;
+ /** Documentation page covering how to send the missing instrumentation. */
+ docs_url: string;
+ /** Counts this check was graded from, over the same window. Which counts appear depends on the check. */
+ stats: InstrumentationCheckStats;
+ }
+
+ export interface InstrumentationCheckAction {
+ /** Key of the check to dismiss or restore.
+ *
+ * * `sessions` - sessions
+ * * `tool_calls` - tool_calls
+ * * `user_identity` - user_identity
+ * * `trace_structure` - trace_structure */
+ check: AIObservabilityInstrumentationCheckEnum;
+ }
+
+ export interface InstrumentationChecklist {
+ /** Length in days of the event window the checks were graded over. */
+ window_days: number;
+ /** Every check, graded. Checks are always all returned, including the ones that pass. */
+ checks: InstrumentationCheck[];
+ }
+
/**
* * `anthropic` - Anthropic
* * `apns` - Apple Push