: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): add signals_scout_run_finished analytics event (#63573)
Andrew Maguire4d24f5351965
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.pyindex e10b84262b4b..7cd8faac6313 100644--- a/products/signals/backend/scout_harness/runner.py+++ b/products/signals/backend/scout_harness/runner.py@@ -8,6 +8,9 @@ from typing import Anyfrom django.utils import timezone+import posthoganalytics++from posthog.event_usage import groupsfrom posthog.models.team.team import Teamfrom posthog.models.utils import uuid7from posthog.sync import database_sync_to_async@@ -151,6 +154,19 @@ async def arun_signals_scout(verbose=verbose,)runtime_s = time.monotonic() - started+ emitted_count, _ = await database_sync_to_async(_read_run_metrics, thread_sensitive=False)(+ run_id, team.parent_team_id or team.id+ )+ _capture_run_finished(+ team=team,+ config=config,+ skill=skill,+ run_id=run_id,+ task_run_id=task_run_id,+ status=TaskRun.Status.COMPLETED.value,+ runtime_s=runtime_s,+ emitted_count=emitted_count,+ )return RunResult(run_id=str(run_id),task_run_id=task_run_id,@@ -179,6 +195,26 @@ async def arun_signals_scout("row_persisted": row_persisted,},)+ # A partial run can still have emitted (and have a linked TaskRun) before failing,+ # so read both from the bridge row when it exists; otherwise it never ran far+ # enough to persist either.+ emitted_count, failed_task_run_id = (+ await database_sync_to_async(_read_run_metrics, thread_sensitive=False)(+ run_id, team.parent_team_id or team.id+ )+ if row_persisted+ else (0, None)+ )+ _capture_run_finished(+ team=team,+ config=config,+ skill=skill,+ run_id=run_id,+ task_run_id=failed_task_run_id,+ status=TaskRun.Status.FAILED.value,+ runtime_s=runtime_s,+ emitted_count=emitted_count,+ )return RunResult(run_id=str(run_id) if row_persisted else None,task_run_id=None,@@ -207,6 +243,18 @@ async def arun_signals_scout("runtime_s": runtime_s,},)+ # Synchronous, no DB read — the loop is collapsing, so don't await anything here;+ # `emitted_count` is left unknown rather than risk a query during cancellation.+ _capture_run_finished(+ team=team,+ config=config,+ skill=skill,+ run_id=run_id,+ task_run_id=None,+ status=TaskRun.Status.CANCELLED.value,+ runtime_s=runtime_s,+ emitted_count=None,+ )raise@@ -386,6 +434,67 @@ def _run_row_exists(run_id: Any, team_id: int) -> bool:return SignalScoutRun.objects.unscoped().filter(team_id=team_id, id=run_id).exists()+def _read_run_metrics(run_id: Any, team_id: int) -> tuple[int, str | None]:+ # The bridge row carries the authoritative emit tally (the emit tool bumps it in-run)+ # and the FK to the linked TaskRun — the join key into LLM analytics, where the+ # richer per-run metrics (tool calls, generations, tokens, cost) already live. Reading+ # both here keeps that linkage on failed runs too, not just clean completions. Returns+ # (0, None) when the row never persisted (failure before the first turn).+ row = (+ SignalScoutRun.objects.unscoped()+ .filter(team_id=team_id, id=run_id)+ .values_list("emitted_count", "task_run_id")+ .first()+ )+ if row is None:+ return 0, None+ emitted_count, task_run_id = row+ return emitted_count or 0, str(task_run_id) if task_run_id else None+++def _capture_run_finished(+ *,+ team: Team,+ config: SignalScoutConfig,+ skill: LoadedSkill,+ run_id: Any,+ task_run_id: str | None,+ status: str,+ runtime_s: float,+ emitted_count: int | None,+) -> None:+ """Emit the scout-owned per-run analytics event.++ Complements the generic `task_run_completed` / `task_run_failed` events (which only+ differentiate scout runs by `origin_product="signals_scout"`) with the dimensions a+ scout experiment segments on: skill identity, body version, outcome, duration, and+ emit volume — keyed on the team so it joins both to the emit-side `signal_emitted`+ events and to the team-level experiment exposure. Best-effort: a capture failure must+ never fail or mask the run outcome.+ """+ try:+ posthoganalytics.capture(+ event="signals_scout_run_finished",+ distinct_id=str(team.uuid),+ properties={+ "skill_name": skill.name,+ "skill_version": skill.version,+ "scout_config_id": str(config.id),+ "run_id": str(run_id),+ "task_run_id": task_run_id,+ "status": status,+ "runtime_seconds": round(runtime_s, 1),+ "emitted_count": emitted_count,+ },+ groups=groups(team.organization, team),+ )+ except Exception:+ logger.warning(+ "signals_scout: failed to capture run-finished analytics event",+ extra={"team_id": team.id, "run_id": str(run_id), "skill_name": skill.name},+ )++def _finalize_run_summary(*, run_id: Any, team_id: int, summary: str) -> None:# Targeted UPDATE rather than `.save()` — the row's other fields are untouched# by the agent's close-out, and `update()` skips the full model refresh.diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex aca39a5c8cf3..24543c6b653d 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -287,6 +287,93 @@ async def test_failed_run_returns_failed_outcome_and_skips_bridge_insert(ateam,assert not has_runs+async def test_successful_run_captures_run_finished_event(ateam, aerrors_skill):+ session, result = await database_sync_to_async(_make_fake_session, thread_sensitive=False)(ateam)++ with (+ patch(+ "products.signals.backend.scout_harness.runner.MultiTurnSession.start",+ new=_fake_start_invoking_hook(session, result),+ ),+ patch(+ "products.signals.backend.scout_harness.runner.get_or_create_signals_sandbox_env",+ return_value="env-id",+ ),+ patch(+ "products.signals.backend.scout_harness.runner.resolve_user_id_for_team",+ return_value=42,+ ),+ patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,+ ):+ run_result = await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")++ capture.assert_called_once()+ assert capture.call_args.kwargs["event"] == "signals_scout_run_finished"+ assert capture.call_args.kwargs["distinct_id"] == str(ateam.uuid)+ props = capture.call_args.kwargs["properties"]+ assert props["skill_name"] == "signals-scout-errors"+ assert props["skill_version"] == 1+ assert props["status"] == TaskRun.Status.COMPLETED.value+ assert props["emitted_count"] == 0+ assert props["run_id"] == run_result.run_id+ # task_run_id is the join key into LLM analytics for the richer per-run metrics.+ assert props["task_run_id"] == str(session.task_run.id)+ assert isinstance(props["runtime_seconds"], float)+++async def test_failed_run_captures_run_finished_event(ateam, aerrors_skill):+ with (+ patch(+ "products.signals.backend.scout_harness.runner.MultiTurnSession.start",+ new_callable=AsyncMock,+ side_effect=RuntimeError("sandbox refused to start"),+ ),+ patch(+ "products.signals.backend.scout_harness.runner.get_or_create_signals_sandbox_env",+ return_value="env-id",+ ),+ patch(+ "products.signals.backend.scout_harness.runner.resolve_user_id_for_team",+ return_value=42,+ ),+ patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,+ ):+ await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")++ capture.assert_called_once()+ props = capture.call_args.kwargs["properties"]+ assert capture.call_args.kwargs["event"] == "signals_scout_run_finished"+ assert props["status"] == TaskRun.Status.FAILED.value+ # No bridge row persisted (TaskRun never created), so no emit tally or join key.+ assert props["emitted_count"] == 0+ assert props["task_run_id"] is None+++async def test_cancelled_run_captures_run_finished_event(ateam, aerrors_skill):+ async def fake_spawn(**_kwargs):+ raise asyncio.CancelledError("worker is shutting down")++ with (+ patch("products.signals.backend.scout_harness.runner._spawn_and_run", side_effect=fake_spawn),+ patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,+ ):+ with pytest.raises(asyncio.CancelledError):+ await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")++ # The cancelled path still emits before re-raising, so the metric isn't lost on shutdown.+ capture.assert_called_once()+ props = capture.call_args.kwargs["properties"]+ assert props["status"] == TaskRun.Status.CANCELLED.value+ # Cancellation skips the DB read, so emit volume is left unknown rather than guessed.+ assert props["emitted_count"] is None++@pytest.mark.asyncio@pytest.mark.django_dbasync def test_missing_skill_does_not_create_run_row(ateam):