: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): count scout coordinator dispatch as a metric (#93131)
posthog[bot]ea499f87ca54
diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.pyindex 8577fe06f4ec..e2213c1636bf 100644--- a/products/signals/backend/temporal/agentic/scout_coordinator.py+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py@@ -53,6 +53,12 @@ from products.signals.backend.scout_harness.team_limits import (_team_configs,)from products.signals.backend.temporal.agentic.scout_scheduler import RunSignalsScoutInput, RunSignalsScoutWorkflow+from products.signals.backend.temporal.metrics import (+ COORDINATOR_DISPATCH_DEDUPED,+ COORDINATOR_DISPATCH_STARTED,+ increment_coordinator_dispatch,+ increment_coordinator_tick,+)logger = structlog.get_logger(__name__)@@ -91,11 +97,14 @@ class FetchEnabledRunsOutput:@frozenclass StampDispatchedRunsInput:- """The (team, skill) runs whose child workflow was dispatched this tick, and the tick's own- start time to anchor their stamps on (`None` falls back to the wall clock)."""+ """The (team, skill) runs whose child workflow was dispatched this batch, the tick's own+ start time to anchor their stamps on (`None` falls back to the wall clock), and how that+ batch split between freshly started children and dedupe-skipped ones."""dispatched_runs: list[PlannedRun]dispatched_at: datetime | None = None+ started_count: int = 0+ deduped_count: int = 0@dataclass@@ -140,6 +149,7 @@ async def fetch_enabled_signals_scout_runs_activity(enrollment, team_configs, default_team_config, global_max_runs_per_tick)logger.info("signals_scout coordinator: planned runs", count=len(planned))+ increment_coordinator_tick(len(planned))return FetchEnabledRunsOutput(planned_runs=planned, dispatch_smear_seconds=smear_seconds)@@ -165,6 +175,10 @@ async def stamp_dispatched_signals_scout_runs_activity(await database_sync_to_async(_stamp_dispatched_runs, thread_sensitive=False)(stamp_input.dispatched_runs, slot_aligned=slot_aligned, dispatched_at=stamp_input.dispatched_at)+ # Counted here rather than in the workflow so a replay cannot double-count it, and after the+ # stamp so a retried attempt counts the batch once.+ increment_coordinator_dispatch(COORDINATOR_DISPATCH_STARTED, stamp_input.started_count)+ increment_coordinator_dispatch(COORDINATOR_DISPATCH_DEDUPED, stamp_input.deduped_count)def _dispatch_slot(config_pk: str, run_interval_minutes: int) -> int:@@ -681,21 +695,31 @@ class SignalsScoutCoordinatorWorkflow:skipped = 0for batch_number, batch in enumerate(batches, start=1):dispatched: list[PlannedRun] = []+ batch_started = 0+ batch_deduped = 0for idx, planned in batch:if await _start_child(planned=planned, tick_id=tick_id, idx=idx):- started += 1+ batch_started += 1else:- skipped += 1+ batch_deduped += 1# Both branches mean a child for this (team, skill, tick) now exists (started, or# dedupe-skipped because a retry already started it) — so its schedule should# advance. A hard `start_child` error raises out of `_start_child` before reaching# here, leaving that config unstamped to re-dispatch next tick.dispatched.append(planned)+ started += batch_started+ skipped += batch_deduped+# Stamp only after dispatch, so a fan-out failure can't suppress a scout for a day.await workflow.execute_activity(stamp_dispatched_signals_scout_runs_activity,- StampDispatchedRunsInput(dispatched_runs=dispatched, dispatched_at=tick_started_at),+ StampDispatchedRunsInput(+ dispatched_runs=dispatched,+ dispatched_at=tick_started_at,+ started_count=batch_started,+ deduped_count=batch_deduped,+ ),start_to_close_timeout=timedelta(minutes=1),retry_policy=RetryPolicy(maximum_attempts=5),)diff --git a/products/signals/backend/temporal/metrics.py b/products/signals/backend/temporal/metrics.pyindex 0e5a1f37f587..0ed2b90a1148 100644--- a/products/signals/backend/temporal/metrics.py+++ b/products/signals/backend/temporal/metrics.py@@ -1,9 +1,39 @@-"""Business-level Prometheus counters for signals pipeline incident alerts."""+"""Business-level counters for signals pipeline incident alerts.+Pipeline counters go to the Temporal metric meter, so they only record inside a workflow or an+activity. The scout coordinator counters are Prometheus instruments with an OTLP twin instead+(the `replay_vision` pattern): both sinks carry one name, and the twin puts fleet dispatch+health in the PostHog Metrics product, where it can be alerted on directly rather than inferred+from downstream tool-call volume.+"""++from prometheus_client import Counterfrom temporalio import activity, workflow+from posthog.otel_metrics import OtelInstrumentFactoryfrom posthog.temporal.common.metrics import get_metric_meter+_otel = OtelInstrumentFactory("signals")++COORDINATOR_DISPATCH_STARTED = "started"+COORDINATOR_DISPATCH_DEDUPED = "deduped"++SCOUT_COORDINATOR_TICKS = Counter(+ "signals_scout_coordinator_ticks_total",+ "Signals scout coordinator ticks that finished planning",+)++SCOUT_COORDINATOR_PLANNED = Counter(+ "signals_scout_coordinator_planned_total",+ "Scout runs the coordinator planned to dispatch",+)++SCOUT_COORDINATOR_DISPATCHED = Counter(+ "signals_scout_coordinator_dispatched_total",+ "Scout child workflows the coordinator dispatched, by outcome",+ ["outcome"],+)+FUNNEL_STAGE_EMITTED = "emitted"FUNNEL_STAGE_GROUPED = "grouped"FUNNEL_STAGE_PROMOTED = "promoted"@@ -148,3 +178,29 @@ def increment_scout_run(status: str) -> None:"signals_scout_runs_total","Signals scout runs by terminal status",).add(1)+++def increment_coordinator_tick(planned_count: int) -> None:+ """Count a coordinator tick that finished planning, and the scout runs it planned.++ The tick counter carries the stall signal on its own: a schedule that stopped firing and a+ fleet with no work due both leave the planned and dispatched counters flat, and only this one+ tells them apart.+ """+ SCOUT_COORDINATOR_TICKS.inc()+ _otel.record_counter_twin(SCOUT_COORDINATOR_TICKS, 1, {})+ # Zero is the reading that matters, so the series is kept alive rather than guarded away.+ SCOUT_COORDINATOR_PLANNED.inc(planned_count)+ _otel.record_counter_twin(SCOUT_COORDINATOR_PLANNED, planned_count, {})+ # A labeled counter has no child series until code calls .labels(), and the dispatch counter is+ # only touched after a dispatch. So warm both outcomes to zero every tick. A stall is a run of+ # zero-plan ticks that never dispatch, which is exactly when the dispatch series would otherwise+ # be absent, so a zero-rate alert on it would read "no data" instead of zero and stay silent.+ for outcome in (COORDINATOR_DISPATCH_STARTED, COORDINATOR_DISPATCH_DEDUPED):+ increment_coordinator_dispatch(outcome, 0)+++def increment_coordinator_dispatch(outcome: str, count: int) -> None:+ """Count scout child workflows the coordinator dispatched, by outcome."""+ SCOUT_COORDINATOR_DISPATCHED.labels(outcome=outcome).inc(count)+ _otel.record_counter_twin(SCOUT_COORDINATOR_DISPATCHED, count, {"outcome": outcome})diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.pyindex e589f94e96a8..d15075523319 100644--- a/products/signals/backend/test/test_scout_coordinator.py+++ b/products/signals/backend/test/test_scout_coordinator.py@@ -489,6 +489,22 @@ async def test_disabled_config_is_skipped(ateam):assert await _run_activity() == []+async def test_a_tick_that_plans_nothing_still_counts_itself(ateam):+ # The zero-plan tick is the one that has to be counted: it is what a stalled fleet looks like,+ # and the dispatch counters stay silent through it.+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-errors")+ await database_sync_to_async(_create_config)(ateam, "signals-scout-errors", enabled=False)++ with patch(+ "products.signals.backend.temporal.agentic.scout_coordinator.increment_coordinator_tick"+ ) as increment_tick:+ assert await _run_activity() == []++ increment_tick.assert_called_once_with(0)++# ── Auto-register: author a skill, get a scout ──────────────────────────────────diff --git a/products/signals/backend/test/test_temporal_metrics.py b/products/signals/backend/test/test_temporal_metrics.pyindex ace0ad27c037..94252dc306f0 100644--- a/products/signals/backend/test/test_temporal_metrics.py+++ b/products/signals/backend/test/test_temporal_metrics.py@@ -1,5 +1,7 @@from unittest.mock import MagicMock, patch+from prometheus_client import REGISTRY+from products.signals.backend.temporal import metrics@@ -9,6 +11,10 @@ def _mock_meter() -> MagicMock:return meter+def _sample(metric_name: str) -> float:+ return REGISTRY.get_sample_value(metric_name) or 0.0++class TestCounterHelpers:def test_funnel_records_when_in_context(self):meter = _mock_meter()@@ -86,6 +92,25 @@ class TestCounterHelpers:assert get_meter.call_args[0][0] == {"stage": "match", "status": "error"}+ def test_coordinator_tick_counts_itself_even_when_nothing_was_planned(self):+ # A tick that plans nothing is what a stalled fleet looks like, so it has to be counted.+ before = _sample("signals_scout_coordinator_ticks_total")++ metrics.increment_coordinator_tick(0)++ assert _sample("signals_scout_coordinator_ticks_total") == before + 1++ def test_coordinator_tick_warms_both_dispatch_outcome_series(self):+ # A stall is a run of zero-plan ticks that never dispatch. The dispatch series must exist+ # anyway, or a zero-rate alert on it reads "no data" instead of zero and stays silent.+ metrics.increment_coordinator_tick(0)++ for outcome in (metrics.COORDINATOR_DISPATCH_STARTED, metrics.COORDINATOR_DISPATCH_DEDUPED):+ assert (+ REGISTRY.get_sample_value("signals_scout_coordinator_dispatched_total", {"outcome": outcome})+ is not None+ )+def test_ch_wait_timeout_counter(self):meter = _mock_meter()with (