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(onboarding): add prometheus metrics for wizard runs (#69089)

Fernando Gomes416bdc1edbee
diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.ts
index 7e996805a639..b555ccff6384 100644
--- a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.ts
+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.ts
@@ -140,7 +140,11 @@ export const wizardActiveSessionDetectorLogic = kea<wizardActiveSessionDetectorL
try {
// 204 (no run) returns an empty body, which the api client resolves to null.
const session: WizardSessionDTOApi | null =
- (await wizardSessionsLatestRetrieve(String(projectId), { workflow_id: WORKFLOW_ID })) || null
+ (await wizardSessionsLatestRetrieve(
+ String(projectId),
+ { workflow_id: WORKFLOW_ID },
+ { headers: { 'X-Wizard-Poll-Source': 'detector' } }
+ )) || null
if (seq !== cache.pollSeq) {
return
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8231b5b74b23..eb565ecf1127 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -372,7 +372,7 @@ importers:
version: 0.25.12
jest:
specifier: ^29.7.0
puppeteer:
specifier: 19.0.0
version: 19.0.0([email protected])
@@ -457,7 +457,7 @@ importers:
version: 5.3.0
jest-image-snapshot:
specifier: ^6.4.0
mockdate:
specifier: ^3.0.5
version: 3.0.5
@@ -1869,7 +1869,7 @@ importers:
version: 3.6.0
jest-image-snapshot:
specifier: ^6.4.0
storybook:
specifier: 'catalog:'
@@ -2616,7 +2616,7 @@ importers:
version: 8.57.0
jest:
specifier: '*'
kea:
specifier: 'catalog:'
version: 4.0.0-pre.5([email protected])
@@ -3385,7 +3385,7 @@ importers:
version: 2.1.1
jest:
specifier: '*'
kea:
specifier: 'catalog:'
version: 4.0.0-pre.5([email protected])
@@ -4248,7 +4248,7 @@ importers:
version: 1.2.1
jest:
specifier: '*'
kea:
specifier: 'catalog:'
version: 4.0.0-pre.5([email protected])
@@ -4344,6 +4344,9 @@ importers:
kea:
specifier: 'catalog:'
version: 4.0.0-pre.5([email protected])
+ posthog-js:
+ specifier: 'catalog:'
+ version: 1.398.2
react:
specifier: 18.3.1
version: 18.3.1
@@ -26694,7 +26697,7 @@ snapshots:
- supports-color
- ts-node
dependencies:
'@jest/console': 30.0.5
'@jest/pattern': 30.0.1
@@ -26709,7 +26712,7 @@ snapshots:
exit-x: 0.2.2
graceful-fs: 4.2.11
jest-changed-files: 30.0.5
jest-haste-map: 30.0.5
jest-message-util: 30.0.5
jest-regex-util: 30.0.1
@@ -26730,7 +26733,7 @@ snapshots:
- supports-color
- ts-node
dependencies:
'@jest/console': 30.0.5
'@jest/pattern': 30.0.1
@@ -26745,7 +26748,7 @@ snapshots:
exit-x: 0.2.2
graceful-fs: 4.2.11
jest-changed-files: 30.0.5
jest-haste-map: 30.0.5
jest-message-util: 30.0.5
jest-regex-util: 30.0.1
@@ -37921,15 +37924,15 @@ snapshots:
- supports-color
- ts-node
dependencies:
'@jest/test-result': 30.0.5
'@jest/types': 30.0.5
chalk: 4.1.2
exit-x: 0.2.2
import-local: 3.2.0
jest-util: 30.0.5
jest-validate: 30.0.5
yargs: 17.7.2
@@ -37940,15 +37943,15 @@ snapshots:
- supports-color
- ts-node
dependencies:
- '@jest/core': 30.0.5([email protected]([email protected]))
'@jest/test-result': 30.0.5
'@jest/types': 30.0.5
chalk: 4.1.2
exit-x: 0.2.2
import-local: 3.2.0
- jest-config: 30.0.5([email protected]([email protected]))
jest-util: 30.0.5
jest-validate: 30.0.5
yargs: 17.7.2
@@ -38086,7 +38089,7 @@ snapshots:
- babel-plugin-macros
- supports-color
dependencies:
'@babel/core': 7.29.0
'@jest/get-type': 30.0.1
@@ -38115,11 +38118,12 @@ snapshots:
optionalDependencies:
'@types/node': 22.18.8
esbuild-register: 3.6.0([email protected])
transitivePeerDependencies:
- babel-plugin-macros
- supports-color
dependencies:
'@babel/core': 7.29.0
'@jest/get-type': 30.0.1
@@ -38148,7 +38152,7 @@ snapshots:
optionalDependencies:
'@types/node': 22.18.8
esbuild-register: 3.6.0([email protected])
transitivePeerDependencies:
- babel-plugin-macros
- supports-color
@@ -38186,7 +38190,7 @@ snapshots:
- babel-plugin-macros
- supports-color
dependencies:
'@babel/core': 7.29.0
'@jest/get-type': 30.0.1
@@ -38214,12 +38218,13 @@ snapshots:
strip-json-comments: 3.1.1
optionalDependencies:
'@types/node': 25.8.0
+ esbuild-register: 3.6.0([email protected])
transitivePeerDependencies:
- babel-plugin-macros
- supports-color
dependencies:
'@babel/core': 7.29.0
'@jest/get-type': 30.0.1
@@ -38246,7 +38251,8 @@ snapshots:
slash: 3.0.0
strip-json-comments: 3.1.1
optionalDependencies:
- esbuild-register: 3.6.0([email protected])
+ '@types/node': 25.8.0
transitivePeerDependencies:
- babel-plugin-macros
- supports-color
@@ -39141,12 +39147,12 @@ snapshots:
- supports-color
- ts-node
dependencies:
'@jest/types': 30.0.5
import-local: 3.2.0
transitivePeerDependencies:
- '@types/node'
- babel-plugin-macros
@@ -39154,12 +39160,12 @@ snapshots:
- supports-color
- ts-node
dependencies:
- '@jest/core': 30.0.5([email protected]([email protected]))
'@jest/types': 30.0.5
import-local: 3.2.0
transitivePeerDependencies:
- '@types/node'
- babel-plugin-macros
diff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.py
index b95e3680c6e2..df3a4e9cf05d 100644
--- a/posthog/api/wizard/http.py
+++ b/posthog/api/wizard/http.py
@@ -18,6 +18,7 @@ from openai.types.chat import (
)
from posthoganalytics.ai.gemini import genai
from posthoganalytics.ai.openai import OpenAI
+from prometheus_client import Counter
from rest_framework import exceptions, response, serializers, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import AuthenticationFailed
@@ -53,6 +54,12 @@ ERROR_PROJECT_NOT_FOUND = "This project does not exist."
OPENAI_SUPPORTED_MODELS = {"o4-mini", "gpt-5-mini", "gpt-5-nano", "gpt-5"}
+WIZARD_CLOUD_RUN_REQUESTS_TOTAL = Counter(
+ "posthog_wizard_cloud_run_requests_total",
+ "Cloud-run wizard kickoff requests, by outcome (created/unavailable/invalid/permission_denied)",
+ labelnames=["outcome"],
+)
+
# Supported Gemini models
GEMINI_SUPPORTED_MODELS = {
"gemini-2.5-flash",
@@ -434,6 +441,21 @@ class SetupWizardViewSet(viewsets.ViewSet):
from the agent's sandbox token. This is the cloud alternative to copy-pasting the wizard command
to run locally; it is intentionally rate limited heavily because each run starts a sandbox.
"""
+ try:
+ response = self._cloud_run(request)
+ except exceptions.NotFound:
+ WIZARD_CLOUD_RUN_REQUESTS_TOTAL.labels(outcome="unavailable").inc()
+ raise
+ except exceptions.PermissionDenied:
+ WIZARD_CLOUD_RUN_REQUESTS_TOTAL.labels(outcome="permission_denied").inc()
+ raise
+ except exceptions.ValidationError:
+ WIZARD_CLOUD_RUN_REQUESTS_TOTAL.labels(outcome="invalid").inc()
+ raise
+ WIZARD_CLOUD_RUN_REQUESTS_TOTAL.labels(outcome="created").inc()
+ return response
+
+ def _cloud_run(self, request: Request) -> Response:
if not bool(settings.WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID):
raise exceptions.NotFound("Running the setup wizard in the cloud is not available.")
diff --git a/products/wizard/backend/facade/api.py b/products/wizard/backend/facade/api.py
index 0247059938a8..6a70795d241a 100644
--- a/products/wizard/backend/facade/api.py
+++ b/products/wizard/backend/facade/api.py
@@ -12,6 +12,7 @@ from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Any
+from products.wizard.backend import metrics
from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardSessionDTO
from products.wizard.backend.logic import pubsub, sessions
@@ -58,3 +59,9 @@ async def subscribe_to_updates(
def serialize_dto(dto: WizardSessionDTO) -> bytes:
return pubsub.serialize_dto(dto)
+
+
+def record_latest_session_poll(raw_source: str | None, result: str) -> None:
+ metrics.WIZARD_LATEST_SESSION_REQUESTS_TOTAL.labels(
+ source=metrics.poll_source_label(raw_source), result=result
+ ).inc()
diff --git a/products/wizard/backend/logic/pubsub.py b/products/wizard/backend/logic/pubsub.py
index f645bfedb7f5..017f275fd9a2 100644
--- a/products/wizard/backend/logic/pubsub.py
+++ b/products/wizard/backend/logic/pubsub.py
@@ -25,6 +25,7 @@ import structlog
from posthog.redis import get_async_client, get_client
from products.wizard.backend.facade.contracts import WizardSessionDTO
+from products.wizard.backend.metrics import WIZARD_PUBSUB_PUBLISH_TOTAL
logger = structlog.get_logger(__name__)
@@ -69,6 +70,7 @@ def publish_session_update(dto: WizardSessionDTO) -> None:
try:
receivers = get_client().publish(channel, payload)
except Exception:
+ WIZARD_PUBSUB_PUBLISH_TOTAL.labels(outcome="failed").inc()
logger.exception(
"wizard_sessions publish failed",
channel=channel,
@@ -76,6 +78,7 @@ def publish_session_update(dto: WizardSessionDTO) -> None:
payload_bytes=len(payload),
)
return
+ WIZARD_PUBSUB_PUBLISH_TOTAL.labels(outcome="published").inc()
logger.debug(
"wizard_sessions publish",
channel=channel,
diff --git a/products/wizard/backend/logic/sessions.py b/products/wizard/backend/logic/sessions.py
index c79aade97cba..50eaf773026c 100644
--- a/products/wizard/backend/logic/sessions.py
+++ b/products/wizard/backend/logic/sessions.py
@@ -6,6 +6,7 @@ from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, W
from products.wizard.backend.facade.enums import RunPhase, TaskStatus
from products.wizard.backend.logic.pubsub import publish_session_update
from products.wizard.backend.logic.utils import is_stale
+from products.wizard.backend.metrics import report_session_upserted
from products.wizard.backend.models import WizardSession
@@ -18,6 +19,11 @@ def upsert_session(params: UpsertWizardSessionInput) -> tuple[WizardSessionDTO,
a brand-new session_id can race the unique constraint and surface as a
500; the CLI's normal HTTP retry handles that on the next attempt.
"""
+ previous_run_phase = (
+ WizardSession.objects.filter(team_id=params.team_id, session_id=params.session_id)
+ .values_list("run_phase", flat=True)
+ .first()
+ )
instance, created = WizardSession.objects.update_or_create(
team_id=params.team_id,
session_id=params.session_id,
@@ -39,6 +45,7 @@ def upsert_session(params: UpsertWizardSessionInput) -> tuple[WizardSessionDTO,
},
)
dto = _to_dto(instance)
+ report_session_upserted(previous_run_phase, dto)
publish_session_update(dto)
return dto, created
diff --git a/products/wizard/backend/metrics.py b/products/wizard/backend/metrics.py
new file mode 100644
index 000000000000..fd26d5416f7a
--- /dev/null
+++ b/products/wizard/backend/metrics.py
@@ -0,0 +1,56 @@
+from prometheus_client import Counter, Histogram
+
+from products.wizard.backend.facade.contracts import WizardSessionDTO
+from products.wizard.backend.facade.enums import RunPhase
+
+_KNOWN_WORKFLOWS = {"posthog-integration"}
+
+_TERMINAL_PHASES = {RunPhase.COMPLETED, RunPhase.ERROR}
+
+_KNOWN_POLL_SOURCES = {"detector", "transport"}
+
+
+def _workflow_label(workflow_id: str) -> str:
+ return workflow_id if workflow_id in _KNOWN_WORKFLOWS else "other"
+
+
+def poll_source_label(raw_source: str | None) -> str:
+ return raw_source if raw_source in _KNOWN_POLL_SOURCES else "unknown"
+
+
+WIZARD_SESSIONS_FINISHED_TOTAL = Counter(
+ "posthog_wizard_sessions_finished_total",
+ "Wizard sessions that transitioned into a terminal phase, observed at the upsert API",
+ labelnames=["workflow", "outcome"],
+)
+
+WIZARD_SESSION_RUN_DURATION_SECONDS = Histogram(
+ "posthog_wizard_session_run_duration_seconds",
+ "Wall-clock wizard run duration (started_at to the terminal upsert), by outcome",
+ labelnames=["workflow", "outcome"],
+ buckets=(30, 60, 120, 300, 600, 1200, 1800, 3600, float("inf")),
+)
+
+WIZARD_LATEST_SESSION_REQUESTS_TOTAL = Counter(
+ "posthog_wizard_latest_session_requests_total",
+ "Poll requests against the latest-session endpoint, by caller source "
+ "(detector/transport/unknown) and result (hit/empty/killswitch)",
+ labelnames=["source", "result"],
+)
+
+WIZARD_PUBSUB_PUBLISH_TOTAL = Counter(
+ "posthog_wizard_pubsub_publish_total",
+ "Redis fan-out publishes of session updates, by outcome (published/failed)",
+ labelnames=["outcome"],
+)
+
+
+def report_session_upserted(previous_run_phase: str | None, dto: WizardSessionDTO) -> None:
+ if dto.run_phase not in _TERMINAL_PHASES or previous_run_phase in _TERMINAL_PHASES:
+ return
+ workflow = _workflow_label(dto.workflow_id)
+ outcome = dto.run_phase.value
+ WIZARD_SESSIONS_FINISHED_TOTAL.labels(workflow=workflow, outcome=outcome).inc()
+ duration = (dto.updated_at - dto.started_at).total_seconds()
+ if duration >= 0:
+ WIZARD_SESSION_RUN_DURATION_SECONDS.labels(workflow=workflow, outcome=outcome).observe(duration)
diff --git a/products/wizard/backend/presentation/views.py b/products/wizard/backend/presentation/views.py
index 089926f41029..7067cdcb7be4 100644
--- a/products/wizard/backend/presentation/views.py
+++ b/products/wizard/backend/presentation/views.py
@@ -236,7 +236,9 @@ class WizardSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# Killswitch parity with `stream`: a 204 makes the client treat this as "no run"
# and wind the detector down, so flipping the flag in an incident also stops the
# 60s poll (and skips the DB read entirely), not just the SSE stream.
+ poll_source = request.headers.get("X-Wizard-Poll-Source")
if self._killswitch_active(request):
+ wizard_facade.record_latest_session_poll(poll_source, "killswitch")
return Response(status=status.HTTP_204_NO_CONTENT)
workflow_id = request.query_params.get("workflow_id")
if not workflow_id:
@@ -244,7 +246,9 @@ class WizardSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
skill_id = request.query_params.get("skill_id") or None
dto = wizard_facade.get_latest(self.team_id, workflow_id, skill_id)
if dto is None:
+ wizard_facade.record_latest_session_poll(poll_source, "empty")
return Response(status=status.HTTP_204_NO_CONTENT)
+ wizard_facade.record_latest_session_poll(poll_source, "hit")
return Response(WizardSessionSerializer(dto).data)
@extend_schema(
diff --git a/products/wizard/backend/tests/test_logic.py b/products/wizard/backend/tests/test_logic.py
index 3ef52dafbb05..821fb7665a6e 100644
--- a/products/wizard/backend/tests/test_logic.py
+++ b/products/wizard/backend/tests/test_logic.py
@@ -5,6 +5,7 @@ import pytest
from products.wizard.backend.facade import api as wizard_facade
from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardTaskDTO
from products.wizard.backend.facade.enums import RunPhase, TaskStatus
+from products.wizard.backend.metrics import WIZARD_SESSIONS_FINISHED_TOTAL
def _input(team_id: int, **overrides) -> UpsertWizardSessionInput:
@@ -134,3 +135,25 @@ def test_list_for_team_returns_sessions_ordered_by_started_at_desc(team):
sessions = wizard_facade.list_for_team(team.id, limit=100)
assert [s.session_id for s in sessions] == ["run-late", "run-early"]
+
+
+def test_upsert_counts_a_terminal_transition_exactly_once(team):
+ counter = WIZARD_SESSIONS_FINISHED_TOTAL.labels(workflow="other", outcome="completed")
+ before = counter._value.get()
+
+ wizard_facade.upsert(_input(team.id, run_phase=RunPhase.RUNNING))
+ wizard_facade.upsert(_input(team.id, run_phase=RunPhase.COMPLETED))
+ wizard_facade.upsert(_input(team.id, run_phase=RunPhase.COMPLETED))
+
+ assert counter._value.get() == before + 1
+
+
+def test_upsert_counts_a_session_created_already_terminal(team):
+ counter = WIZARD_SESSIONS_FINISHED_TOTAL.labels(workflow="other", outcome="error")
+ before = counter._value.get()
+
+ wizard_facade.upsert(_input(team.id, run_phase=RunPhase.ERROR, error={"type": "boom", "message": "x"}))
+
+ assert counter._value.get() == before + 1
diff --git a/products/wizard/frontend/wizardSessionStreamLogic.test.ts b/products/wizard/frontend/wizardSessionStreamLogic.test.ts
index 426863ad1d5f..317d0f058f0a 100644
--- a/products/wizard/frontend/wizardSessionStreamLogic.test.ts
+++ b/products/wizard/frontend/wizardSessionStreamLogic.test.ts
@@ -69,10 +69,14 @@ describe('wizardSessionStreamLogic polling mode', () => {
.toDispatchActions(['connectionOpened', 'sessionUpdated'])
.toMatchValues({ latestSession: session, connectionStatus: 'open' })
- expect(mockLatestRetrieve).toHaveBeenCalledWith(expect.any(String), {
- workflow_id: 'posthog-integration',
- skill_id: undefined,
- })
+ expect(mockLatestRetrieve).toHaveBeenCalledWith(
+ expect.any(String),
+ {
+ workflow_id: 'posthog-integration',
+ skill_id: undefined,
+ },
+ { headers: { 'X-Wizard-Poll-Source': 'transport' } }
+ )
})
it('keeps polling through a 204 (no session yet) without clobbering latestSession', async () => {
diff --git a/products/wizard/frontend/wizardSessionStreamLogic.ts b/products/wizard/frontend/wizardSessionStreamLogic.ts
index f0e6e74b1019..746752982555 100644
--- a/products/wizard/frontend/wizardSessionStreamLogic.ts
+++ b/products/wizard/frontend/wizardSessionStreamLogic.ts
@@ -1,4 +1,5 @@
import { actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
+import posthog from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic, getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'
@@ -104,6 +105,13 @@ export const wizardSessionStreamLogic = kea<wizardSessionStreamLogicType>([
return
}
+ // Per-connect-cycle transport telemetry: one "ready" (first session delivered) and at
+ // most one "error" per cycle, so SSE and polling performance stay comparable without
+ // an event per delivery or per EventSource retry.
+ cache.connectStartedAt = Date.now()
+ cache.transportReadyReported = false
+ cache.transportErrorReported = false
+
const debugSource = `session ${props.workflowId}::${props.skillId ?? '*'}`
// Mode is re-sampled on every connect, and the setFeatureFlags listener below reconnects
@@ -128,10 +136,14 @@ export const wizardSessionStreamLogic = kea<wizardSessionStreamLogicType>([
tick: async () => {
// 204 (no session yet, or killswitched) resolves to null — classify as
// empty so the loop backs off instead of polling at full cadence forever.
- const session = await wizardSessionsLatestRetrieve(String(projectId), {
- workflow_id: props.workflowId,
- skill_id: props.skillId,
- })
+ const session = await wizardSessionsLatestRetrieve(
+ String(projectId),
+ {
+ workflow_id: props.workflowId,
+ skill_id: props.skillId,
+ },
+ { headers: { 'X-Wizard-Poll-Source': 'transport' } }
+ )
logSyncDebug(
debugSource,
'poll',
@@ -212,6 +224,28 @@ export const wizardSessionStreamLogic = kea<wizardSessionStreamLogicType>([
logSyncDebug(`session ${props.workflowId}::${props.skillId ?? '*'}`, 'disconnect', 'disconnected')
cache.disposables.dispose('session-sync')
},
+ sessionUpdated: () => {
+ if (cache.transportReadyReported || cache.connectStartedAt === undefined) {
+ return
+ }
+ cache.transportReadyReported = true
+ posthog.capture('wizard sync transport ready', {
+ transport: cache.syncMode ?? 'sse',
+ workflow_id: props.workflowId,
+ ms_since_connect: Date.now() - cache.connectStartedAt,
+ })
+ },
+ connectionErrored: ({ error }) => {
+ if (cache.transportErrorReported || cache.connectStartedAt === undefined) {
+ return
+ }
+ cache.transportErrorReported = true
+ posthog.capture('wizard sync transport error', {
+ transport: cache.syncMode ?? 'sse',
+ workflow_id: props.workflowId,
+ error,
+ })
+ },
// Flags can resolve after a cold-cache connect (posthog-js loads them async), and ops can flip
// the mode mid-incident. Reconnect when the resolved mode differs from the running transport —
// the keyed disposable makes the swap idempotent.
diff --git a/products/wizard/package.json b/products/wizard/package.json
index e489499abe8c..1d8c6404879b 100644
--- a/products/wizard/package.json
+++ b/products/wizard/package.json
@@ -5,7 +5,8 @@
"backend:contract-check": "echo 'Contract files unchanged'"
},
"dependencies": {
- "kea": "catalog:"
+ "kea": "catalog:",
+ "posthog-js": "catalog:"
},
"devDependencies": {
"kea-test-utils": "catalog:"