: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 observability metrics to the pipeline (#63230)
Joshua Snyder4c064399e89f
diff --git a/products/signals/backend/temporal/agentic/scout_scheduler.py b/products/signals/backend/temporal/agentic/scout_scheduler.pyindex 7548f4839533..f8f8c45092e9 100644--- a/products/signals/backend/temporal/agentic/scout_scheduler.py+++ b/products/signals/backend/temporal/agentic/scout_scheduler.py@@ -11,6 +11,7 @@ from posthog.temporal.common.heartbeat import Heartbeaterfrom products.signals.backend.scout_harness.limits import WORKFLOW_HARD_CEILING_Sfrom products.signals.backend.scout_harness.runner import RunResult, arun_signals_scout+from products.signals.backend.temporal import metricslogger = structlog.get_logger(__name__)@@ -61,6 +62,7 @@ async def run_signals_scout_activity(input: RunSignalsScoutInput) -> RunSignalsSskill_version=input.skill_version,repository=input.repository,)+ metrics.increment_scout_run(result.status or "unknown")logger.info("signals_scout activity finished",team_id=input.team_id,diff --git a/products/signals/backend/temporal/buffer.py b/products/signals/backend/temporal/buffer.pyindex 1e087ad84887..ce5ee2b4c3a1 100644--- a/products/signals/backend/temporal/buffer.py+++ b/products/signals/backend/temporal/buffer.py@@ -18,6 +18,7 @@ from posthog.storage import object_storagefrom posthog.temporal.common.client import async_connectfrom posthog.temporal.common.scoped import scoped_temporal+from products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.grouping_v2 import TeamSignalGroupingV2Workflowfrom products.signals.backend.temporal.safety_filter import SafetyFilterInput, safety_filter_activityfrom products.signals.backend.temporal.types import BufferSignalsInput, EmitSignalInputs, TeamSignalGroupingV2Input@@ -151,6 +152,7 @@ class BufferSignalsWorkflow:@temporalio.workflow.signalasync def submit_signal(self, signal: EmitSignalInputs) -> None:self._get_emitted_counter(signal.team_id, signal.source_product, signal.source_type).add(1)+ metrics.increment_funnel(metrics.FUNNEL_STAGE_EMITTED, signal.source_product)self._signal_buffer.append(signal)@temporalio.workflow.rundiff --git a/products/signals/backend/temporal/drop_telemetry.py b/products/signals/backend/temporal/drop_telemetry.pyindex f2aca90538ba..6c6095ca2b2f 100644--- a/products/signals/backend/temporal/drop_telemetry.py+++ b/products/signals/backend/temporal/drop_telemetry.py@@ -12,6 +12,7 @@ from posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connectionsfrom products.signals.backend.facade.api import _telemetry_props_from_extra+from products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.types import EmitSignalInputslogger = structlog.get_logger(__name__)@@ -56,6 +57,7 @@ def _summarize_drop_error(error: BaseException) -> tuple[str, str]:@close_db_connectionsasync def capture_signal_dropped_activity(input: CaptureSignalDroppedInput) -> None:"""Emit a lifecycle event when the pipeline drops a signal, so drops are trackable per signal."""+ metrics.increment_dropped(stage=input.stage, reason=input.error_type)try:team = await Team.objects.select_related("organization").aget(pk=input.team_id)posthoganalytics.capture(diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.pyindex bf8fc37e0766..23226f36c1dc 100644--- a/products/signals/backend/temporal/grouping.py+++ b/products/signals/backend/temporal/grouping.py@@ -30,6 +30,7 @@ from posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connectionsfrom products.signals.backend.models import SignalReport+from products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.drop_telemetry import capture_signal_droppedfrom products.signals.backend.temporal.llm import MAX_QUERY_TOKENS, call_llm, truncate_query_to_token_limitfrom products.signals.backend.temporal.signal_queries import (@@ -903,6 +904,12 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Asteam_id=input.team_id,source_id=input.source_id,)++ if not matched_deleted:+ metrics.increment_funnel(metrics.FUNNEL_STAGE_GROUPED, input.source_product)+ if promoted:+ metrics.increment_funnel(metrics.FUNNEL_STAGE_PROMOTED, input.source_product)+logger.debug(f"Assigned and emitted signal to report {report_id}",report_id=report_id,diff --git a/products/signals/backend/temporal/llm.py b/products/signals/backend/temporal/llm.pyindex d8ae9f21075f..60ab18913b37 100644--- a/products/signals/backend/temporal/llm.py+++ b/products/signals/backend/temporal/llm.py@@ -10,6 +10,8 @@ from anthropic.types import MessageParamfrom posthog.helpers.tiktoken_encoding import TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_modelfrom posthog.llm.gateway_client import get_async_anthropic_gateway_client+from products.signals.backend.temporal import metrics+logger = structlog.get_logger(__name__)MATCHING_MODEL = os.getenv("SIGNAL_MATCHING_LLM_MODEL", "claude-sonnet-4-5")@@ -118,18 +120,22 @@ async def call_llm(create_kwargs["temperature"] = 1 # Required for thinkinglast_exception: Exception | None = None+ stage_label = stage or "unknown"for attempt in range(retries):- response = None# NOTE - we explicitly don't want to retry if we fail to call the llm, or fail to extract text content,- # only if we fail to validate the response.- response = await client.messages.create(**create_kwargs)- text_content = _extract_text_content(response)+ # only if we fail to validate the response. A transport/extraction failure is a hot-path LLM error.+ try:+ response = await client.messages.create(**create_kwargs)+ text_content = _extract_text_content(response)+ except Exception:+ metrics.increment_llm_call(stage_label, metrics.LLM_STATUS_ERROR)+ raisetext_content = _strip_markdown_json_fences(text_content)if not thinking:# Prepend the `{` we pre-filledtext_content = "{" + text_contenttry:- return validate(text_content)+ result = validate(text_content)except Exception as e:logger.warning(f"LLM call failed (attempt {attempt + 1}/{retries}): {e}",@@ -142,8 +148,7 @@ async def call_llm(logger.warning(f"LLM response that failed validation:\n{text_content}",)- if response:- messages.append({"role": "assistant", "content": response.content})+ messages.append({"role": "assistant", "content": response.content})messages.append({"role": "user",@@ -157,4 +162,8 @@ async def call_llm(last_exception = econtinue+ metrics.increment_llm_call(stage_label, metrics.LLM_STATUS_OK)+ return result++ metrics.increment_llm_call(stage_label, metrics.LLM_STATUS_ERROR)raise last_exception or ValueError(f"LLM call failed after {retries} attempts")diff --git a/products/signals/backend/temporal/metrics.py b/products/signals/backend/temporal/metrics.pynew file mode 100644index 000000000000..59500d3e87de--- /dev/null+++ b/products/signals/backend/temporal/metrics.py@@ -0,0 +1,86 @@+"""Business-level Prometheus counters for signals pipeline incident alerts."""++from temporalio import activity, workflow++from posthog.temporal.common.metrics import get_metric_meter++FUNNEL_STAGE_EMITTED = "emitted"+FUNNEL_STAGE_GROUPED = "grouped"+FUNNEL_STAGE_PROMOTED = "promoted"++LLM_STATUS_OK = "ok"+LLM_STATUS_ERROR = "error"+++def _in_temporal_context() -> bool:+ return activity.in_activity() or workflow.in_workflow()+++def increment_funnel(stage: str, source_product: str = "unknown", count: int = 1) -> None:+ """Count signals reaching a pipeline funnel stage. No-ops outside a Temporal context."""+ if not _in_temporal_context() or count <= 0:+ return+ get_metric_meter({"stage": stage, "source_product": source_product}).create_counter(+ "signals_funnel_total",+ "Signals reaching each pipeline funnel stage",+ ).add(count)+++def increment_safety_blocked(source_product: str = "unknown") -> None:+ """Count a signal rejected by the safety filter — a legitimate terminal exit, not a drop."""+ if not _in_temporal_context():+ return+ get_metric_meter({"source_product": source_product}).create_counter(+ "signals_safety_blocked_total",+ "Signals rejected by the safety filter",+ ).add(1)+++def increment_dropped(stage: str, reason: str, count: int = 1) -> None:+ """Count signals lost to an error, attributed to a stage and reason."""+ if not _in_temporal_context() or count <= 0:+ return+ get_metric_meter({"stage": stage, "reason": reason}).create_counter(+ "signals_dropped_total",+ "Signals dropped from the pipeline by stage and reason",+ ).add(count)+++def increment_report_completed(result: str) -> None:+ """Count report completions by result (ready/failed/not_actionable/pending_input)."""+ if not _in_temporal_context():+ return+ get_metric_meter({"result": result}).create_counter(+ "signals_reports_total",+ "Signal reports completed by result",+ ).add(1)+++def increment_llm_call(stage: str, status: str) -> None:+ """Count an LLM call on the grouping/summary hot path by stage and outcome."""+ if not _in_temporal_context():+ return+ get_metric_meter({"stage": stage, "status": status}).create_counter(+ "signals_llm_calls_total",+ "LLM calls by stage and outcome",+ ).add(1)+++def increment_ch_wait_timeout() -> None:+ """Count a give-up of the wait-for-signal-in-ClickHouse consistency wait."""+ if not _in_temporal_context():+ return+ get_metric_meter().create_counter(+ "signals_ch_wait_timeouts_total",+ "Times the wait-for-signal-in-ClickHouse activity gave up after its max wait",+ ).add(1)+++def increment_scout_run(status: str) -> None:+ """Count a scout run by terminal status."""+ if not _in_temporal_context():+ return+ get_metric_meter({"status": status}).create_counter(+ "signals_scout_runs_total",+ "Signals scout runs by terminal status",+ ).add(1)diff --git a/products/signals/backend/temporal/safety_filter.py b/products/signals/backend/temporal/safety_filter.pyindex f920847a638e..13f6c545f19c 100644--- a/products/signals/backend/temporal/safety_filter.py+++ b/products/signals/backend/temporal/safety_filter.py@@ -13,6 +13,7 @@ from posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connectionsfrom products.signals.backend.facade.api import _telemetry_props_from_extra+from products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.llm import EmptyLLMResponseError, call_llmlogger = structlog.get_logger(__name__)@@ -250,6 +251,7 @@ async def safety_filter_activity(input: SafetyFilterInput) -> SafetyFilterOutputraiseif not result.safe:+ metrics.increment_safety_blocked(input.source_product or "unknown")await _capture_signal_blocked_event(input, result)return SafetyFilterOutput(diff --git a/products/signals/backend/temporal/signal_queries.py b/products/signals/backend/temporal/signal_queries.pyindex 50fba598c5a6..095c9fe825a9 100644--- a/products/signals/backend/temporal/signal_queries.py+++ b/products/signals/backend/temporal/signal_queries.py@@ -18,6 +18,7 @@ from posthog.models import Teamfrom posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connections+from products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.clickhouse import execute_hogql_query_with_retryfrom products.signals.backend.temporal.types import SignalCandidate, SignalData, SignalTypeExample@@ -447,6 +448,7 @@ async def wait_for_signal_in_clickhouse_activity(input: WaitForClickHouseInput)remaining -= chunktemporalio.activity.heartbeat(attempt)+ metrics.increment_ch_wait_timeout()logger.warning(f"Not all signals found in ClickHouse after {input.max_wait_time_seconds}s, proceeding anyway",signal_ids=signal_ids,diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.pyindex ff5000a6d2c8..4157c626bd79 100644--- a/products/signals/backend/temporal/summary.py+++ b/products/signals/backend/temporal/summary.py@@ -25,6 +25,7 @@ from posthog.temporal.common.utils import close_db_connectionsfrom products.signals.backend.models import SignalReportfrom products.signals.backend.report_generation.research import ActionabilityChoicefrom products.signals.backend.report_generation.select_repo import RepoSelectionResult+from products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.agentic.report import (RunAgenticReportInput,RunAgenticReportOutput,@@ -74,6 +75,10 @@ def _capture_report_event(properties["result"] = resultif failure_reason is not None:properties["failure_reason"] = failure_reason++ if event == "signal_report_completed" and result is not None:+ metrics.increment_report_completed(result)+try:posthoganalytics.capture(event=event,diff --git a/products/signals/backend/test/test_temporal_metrics.py b/products/signals/backend/test/test_temporal_metrics.pynew file mode 100644index 000000000000..ace0ad27c037--- /dev/null+++ b/products/signals/backend/test/test_temporal_metrics.py@@ -0,0 +1,98 @@+from unittest.mock import MagicMock, patch++from products.signals.backend.temporal import metrics+++def _mock_meter() -> MagicMock:+ meter = MagicMock()+ meter.create_counter.return_value = MagicMock()+ return meter+++class TestCounterHelpers:+ def test_funnel_records_when_in_context(self):+ meter = _mock_meter()+ with (+ patch.object(metrics, "_in_temporal_context", return_value=True),+ patch.object(metrics, "get_metric_meter", return_value=meter) as get_meter,+ ):+ metrics.increment_funnel(metrics.FUNNEL_STAGE_GROUPED, "error_tracking")++ assert get_meter.call_args[0][0] == {"stage": "grouped", "source_product": "error_tracking"}+ meter.create_counter.assert_called_once()+ meter.create_counter.return_value.add.assert_called_once_with(1)++ def test_funnel_defaults_source_product(self):+ meter = _mock_meter()+ with (+ patch.object(metrics, "_in_temporal_context", return_value=True),+ patch.object(metrics, "get_metric_meter", return_value=meter) as get_meter,+ ):+ metrics.increment_funnel(metrics.FUNNEL_STAGE_EMITTED)++ assert get_meter.call_args[0][0] == {"stage": "emitted", "source_product": "unknown"}++ def test_helpers_noop_outside_temporal_context(self):+ with (+ patch.object(metrics, "_in_temporal_context", return_value=False),+ patch.object(metrics, "get_metric_meter") as get_meter,+ ):+ metrics.increment_funnel(metrics.FUNNEL_STAGE_GROUPED, "error_tracking")+ metrics.increment_dropped("grouping_parallel", "ValueError")+ metrics.increment_report_completed("ready")+ metrics.increment_llm_call("match", metrics.LLM_STATUS_OK)+ metrics.increment_ch_wait_timeout()+ metrics.increment_scout_run("completed")++ get_meter.assert_not_called()++ def test_zero_count_is_a_noop(self):+ with (+ patch.object(metrics, "_in_temporal_context", return_value=True),+ patch.object(metrics, "get_metric_meter") as get_meter,+ ):+ metrics.increment_funnel(metrics.FUNNEL_STAGE_GROUPED, count=0)+ metrics.increment_dropped("grouping_parallel", "ValueError", count=0)++ get_meter.assert_not_called()++ def test_report_completed_label(self):+ meter = _mock_meter()+ with (+ patch.object(metrics, "_in_temporal_context", return_value=True),+ patch.object(metrics, "get_metric_meter", return_value=meter) as get_meter,+ ):+ metrics.increment_report_completed("not_actionable")++ assert get_meter.call_args[0][0] == {"result": "not_actionable"}++ def test_dropped_labels(self):+ meter = _mock_meter()+ with (+ patch.object(metrics, "_in_temporal_context", return_value=True),+ patch.object(metrics, "get_metric_meter", return_value=meter) as get_meter,+ ):+ metrics.increment_dropped("grouping_parallel", "ValueError")++ assert get_meter.call_args[0][0] == {"stage": "grouping_parallel", "reason": "ValueError"}++ def test_llm_call_labels(self):+ meter = _mock_meter()+ with (+ patch.object(metrics, "_in_temporal_context", return_value=True),+ patch.object(metrics, "get_metric_meter", return_value=meter) as get_meter,+ ):+ metrics.increment_llm_call("match", metrics.LLM_STATUS_ERROR)++ assert get_meter.call_args[0][0] == {"stage": "match", "status": "error"}++ def test_ch_wait_timeout_counter(self):+ meter = _mock_meter()+ with (+ patch.object(metrics, "_in_temporal_context", return_value=True),+ patch.object(metrics, "get_metric_meter", return_value=meter),+ ):+ metrics.increment_ch_wait_timeout()++ meter.create_counter.assert_called_once()+ meter.create_counter.return_value.add.assert_called_once_with(1)