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.

fix(signals): send scout coordinator counters to a live sink (#95650)

posthog[bot]52955dadb853
diff --git a/.agents/skills/instrumenting-first-party-metrics/SKILL.md b/.agents/skills/instrumenting-first-party-metrics/SKILL.md
index c145b10413fc..7c9c1185f82d 100644
--- a/.agents/skills/instrumenting-first-party-metrics/SKILL.md
+++ b/.agents/skills/instrumenting-first-party-metrics/SKILL.md
@@ -17,6 +17,16 @@ Never invent env vars or hand-roll OTel providers — every environment below al
| Monorepo Node services (`nodejs/`) | — (services don't run posthog-node) | internal twin: `nodejs/src/common/metrics/otel-metrics.ts` |
| PostHog-owned standalone service / script / other repo | SDK per public docs: `posthog.metrics.count/gauge/histogram` | OTLP env vars per docs (`OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=<host>/i/v1/metrics`, Bearer project token) |
+> [!WARNING]
+> **In a Temporal worker the OTel fallback is not a fallback — it is silence.** `OTEL_METRICS_EXPORT_URL`/`_TOKEN` are set on the web deployment, not on the worker deployments, so `OtelInstrumentFactory` binds a no-op meter there and every twin is dropped.
+> No metric recorded through the factory from a worker activity has ever reached the Metrics product, while SDK-path metrics from the same pods do.
+> From a worker, use the SDK path or the Temporal metric meter.
+>
+> Do not assume the `prometheus_client` half of a twin covers for the dropped twin, and do not drop the instrument either.
+> `create_worker` starts `CombinedMetricsServer` by default (`enable_combined_metrics_server=True`, from `TEMPORAL_COMBINED_METRICS_SERVER_ENABLED`), and that server serves the Python registry next to the Temporal SDK's own metrics on the worker's metrics port.
+> So the registry is exported by default, but it reaches Grafana only if the combined server is still enabled and the deployment scrapes that endpoint.
+> Both are deployment configuration outside this repository, so confirm them before you rely on a `prometheus_client` instrument as a worker's only sink.
+
## Step 2 — check the version gate (don't assume)
`posthog.metrics` shipped in: **posthog-python 7.23.0** (`posthoganalytics` is the same package renamed), **posthog-node 5.43.0**, **posthog-js ~1.399.0** (runtime check: `typeof posthog.metrics?.count === 'function'`).
@@ -50,7 +60,7 @@ _otel.histogram("myarea.job.duration", unit="s").record(1.87, {"queue": "default
_otel.gauge("myarea.backlog").set(42)
```
-Reference call sites: `products/dashboards/backend/access.py` (smallest), `products/replay_vision/backend/temporal/metrics.py` (full module).
+Reference call sites: `products/dashboards/backend/access.py` (smallest, web), `products/managed_warehouse/backend/metrics.py` (SDK path from a Temporal worker).
If a `prometheus_client` instrument already exists at the site and its Grafana series must be kept, mirror it with `record_counter_twin`/`record_histogram_twin`/`record_gauge_twin`/`timed_histogram_twin` instead of a direct instrument — the twin derives name/buckets from it so the sinks can't drift.
**Rules for both paths**: dot-separated stable names (`jobs.processed`, not `metric1`); explicit `unit` on histograms; low-cardinality attributes only (`route`, `status`, `plan` — never user/session/request IDs; `team_id` sparingly and deliberately).
diff --git a/products/signals/backend/temporal/metrics.py b/products/signals/backend/temporal/metrics.py
index 0ed2b90a1148..fcdf01676404 100644
--- a/products/signals/backend/temporal/metrics.py
+++ b/products/signals/backend/temporal/metrics.py
@@ -1,35 +1,37 @@
"""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.
+activity. The scout coordinator counters keep a Prometheus instrument for Grafana and push the
+same name through the PostHog SDK metrics client, which puts fleet dispatch health in the
+PostHog Metrics product, where it can be alerted on directly rather than inferred from
+downstream tool-call volume.
"""
+import posthoganalytics
from prometheus_client import Counter
from temporalio import activity, workflow
-from posthog.otel_metrics import OtelInstrumentFactory
from posthog.temporal.common.metrics import get_metric_meter
-_otel = OtelInstrumentFactory("signals")
-
COORDINATOR_DISPATCH_STARTED = "started"
COORDINATOR_DISPATCH_DEDUPED = "deduped"
+SCOUT_COORDINATOR_TICKS_METRIC = "signals_scout_coordinator_ticks_total"
+SCOUT_COORDINATOR_PLANNED_METRIC = "signals_scout_coordinator_planned_total"
+SCOUT_COORDINATOR_DISPATCHED_METRIC = "signals_scout_coordinator_dispatched_total"
+
SCOUT_COORDINATOR_TICKS = Counter(
- "signals_scout_coordinator_ticks_total",
+ SCOUT_COORDINATOR_TICKS_METRIC,
"Signals scout coordinator ticks that finished planning",
)
SCOUT_COORDINATOR_PLANNED = Counter(
- "signals_scout_coordinator_planned_total",
+ SCOUT_COORDINATOR_PLANNED_METRIC,
"Scout runs the coordinator planned to dispatch",
)
SCOUT_COORDINATOR_DISPATCHED = Counter(
- "signals_scout_coordinator_dispatched_total",
+ SCOUT_COORDINATOR_DISPATCHED_METRIC,
"Scout child workflows the coordinator dispatched, by outcome",
["outcome"],
)
@@ -180,6 +182,20 @@ def increment_scout_run(status: str) -> None:
).add(1)
+def _push_coordinator_metric(name: str, value: float, attributes: dict[str, str]) -> None:
+ """Push one coordinator counter into the PostHog Metrics product.
+
+ The SDK client is the only sink that carries a counter out of a Temporal worker into the
+ Metrics product: the worker exports no `prometheus_client` series there, and it has no OTLP
+ push configured. Failures are swallowed, because this runs in the planning activity and a
+ telemetry error that failed the tick would cause the dispatch stall these counters watch for.
+ """
+ try:
+ posthoganalytics.setup().metrics.count(name, value, attributes=attributes)
+ except Exception:
+ pass
+
+
def increment_coordinator_tick(planned_count: int) -> None:
"""Count a coordinator tick that finished planning, and the scout runs it planned.
@@ -188,10 +204,10 @@ def increment_coordinator_tick(planned_count: int) -> None:
tells them apart.
"""
SCOUT_COORDINATOR_TICKS.inc()
- _otel.record_counter_twin(SCOUT_COORDINATOR_TICKS, 1, {})
+ _push_coordinator_metric(SCOUT_COORDINATOR_TICKS_METRIC, 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, {})
+ _push_coordinator_metric(SCOUT_COORDINATOR_PLANNED_METRIC, 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
@@ -203,4 +219,4 @@ def increment_coordinator_tick(planned_count: int) -> None:
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})
+ _push_coordinator_metric(SCOUT_COORDINATOR_DISPATCHED_METRIC, count, {"outcome": outcome})
diff --git a/products/signals/backend/test/test_temporal_metrics.py b/products/signals/backend/test/test_temporal_metrics.py
index 94252dc306f0..4b46ac489c01 100644
--- a/products/signals/backend/test/test_temporal_metrics.py
+++ b/products/signals/backend/test/test_temporal_metrics.py
@@ -1,3 +1,5 @@
+from contextlib import contextmanager
+
from unittest.mock import MagicMock, patch
from prometheus_client import REGISTRY
@@ -15,6 +17,17 @@ def _sample(metric_name: str) -> float:
return REGISTRY.get_sample_value(metric_name) or 0.0
+@contextmanager
+def _captured_pushes():
+ """Collect the (name, value, attributes) triples pushed to the PostHog metrics client."""
+ pushed: list[tuple] = []
+ client = MagicMock()
+ client.metrics.count.side_effect = lambda name, value, attributes: pushed.append((name, value, attributes))
+ with patch.object(metrics, "posthoganalytics") as sdk:
+ sdk.setup.return_value = client
+ yield pushed
+
+
class TestCounterHelpers:
def test_funnel_records_when_in_context(self):
meter = _mock_meter()
@@ -100,16 +113,30 @@ class TestCounterHelpers:
assert _sample("signals_scout_coordinator_ticks_total") == before + 1
+ def test_coordinator_tick_pushes_all_three_series_to_the_metrics_product(self):
+ # The prometheus registry of a temporal worker reaches nothing outside the process, so a
+ # tick that only incremented it left the fleet with no alertable health series at all.
+ with _captured_pushes() as pushed:
+ metrics.increment_coordinator_tick(0)
+
+ assert {name for name, _, _ in pushed} == {
+ metrics.SCOUT_COORDINATOR_TICKS_METRIC,
+ metrics.SCOUT_COORDINATOR_PLANNED_METRIC,
+ metrics.SCOUT_COORDINATOR_DISPATCHED_METRIC,
+ }
+
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)
+ with _captured_pushes() as pushed:
+ 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
)
+ assert (metrics.SCOUT_COORDINATOR_DISPATCHED_METRIC, 0, {"outcome": outcome}) in pushed
def test_ch_wait_timeout_counter(self):
meter = _mock_meter()