: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
fix(signals): emit signal_dropped when the ingestion gate drops a batch (#116531)
posthog[bot]0404e47b2bcb
diff --git a/products/signals/backend/temporal/buffer.py b/products/signals/backend/temporal/buffer.pyindex 85b8bc77a935..7bd1d0721378 100644--- a/products/signals/backend/temporal/buffer.py+++ b/products/signals/backend/temporal/buffer.py@@ -2,7 +2,7 @@ import jsonimport uuidimport randomimport asyncio-from dataclasses import asdict, dataclass+from dataclasses import asdict, dataclass, fieldfrom datetime import timedeltafrom django.conf import settings@@ -26,6 +26,7 @@ from posthog.temporal.common.utils import close_db_connectionsfrom products.signals.backend.daily_limit import capture_signal_report_daily_limit_paused, daily_report_limit_gatefrom products.signals.backend.quota import is_team_signals_quota_limitedfrom products.signals.backend.temporal import metrics+from products.signals.backend.temporal.drop_telemetry import capture_signal_dropped_event, signal_dropped_inputfrom 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@@ -80,6 +81,7 @@ class CheckSignalsQuotaInput:team_id: int# Defaults so activity inputs recorded before the field existed still decode on replay.signal_count: int = 0+ signals: list[EmitSignalInputs] = field(default_factory=list)@activity.defn@@ -87,8 +89,8 @@ class CheckSignalsQuotaInput:@close_db_connectionsasync def check_signals_quota_limited_activity(input: CheckSignalsQuotaInput) -> bool:"""Whether the batch must be dropped: the team is over its Signals credits quota, or over its- daily report limit. Owns the drop logging and metric so the reason label names the exact limit- that fired; the workflow only acts on the boolean.+ daily report limit. Owns the drop logging, metric and `signal_dropped` events so the reason+ names the exact limit that fired; the workflow only acts on the boolean."""team = await Team.objects.select_related("organization").aget(pk=input.team_id)quota_limited = await sync_to_async(is_team_signals_quota_limited, thread_sensitive=False)(team.api_token)@@ -104,6 +106,7 @@ async def check_signals_quota_limited_activity(input: CheckSignalsQuotaInput) ->signal_count=input.signal_count,)metrics.increment_dropped(stage="ingestion", reason="quota_limited", count=input.signal_count)+ _capture_ingestion_drops(team, input.signals, "quota_limited", "Signals credits quota exceeded")return Trueif daily_gate.limited:logger.info(@@ -112,10 +115,21 @@ async def check_signals_quota_limited_activity(input: CheckSignalsQuotaInput) ->signal_count=input.signal_count,)metrics.increment_dropped(stage="ingestion", reason="daily_report_limit", count=input.signal_count)+ _capture_ingestion_drops(team, input.signals, "daily_report_limit", "Daily report limit reached")return Truereturn False+def _capture_ingestion_drops(team: Team, signals: list[EmitSignalInputs], error_type: str, error: str) -> None:+ try:+ for signal in signals:+ capture_signal_dropped_event(team, signal_dropped_input(signal, "ingestion", error_type, error))+ except Exception as e:+ # Swallow the exception: a failed analytics event must not change the drop decision+ posthoganalytics.capture_exception(e)+ logger.exception("Failed to capture signal_dropped events", team_id=team.id, signal_count=len(signals))++@dataclassclass SignalWithStartGroupingV2Input:team_id: int@@ -242,7 +256,7 @@ class BufferSignalsWorkflow:if workflow.patched(_PATCH_QUOTA_INGESTION_GATE):over_limit = await workflow.execute_activity(check_signals_quota_limited_activity,- CheckSignalsQuotaInput(team_id=input.team_id, signal_count=len(batch)),+ CheckSignalsQuotaInput(team_id=input.team_id, signal_count=len(batch), signals=batch),start_to_close_timeout=timedelta(seconds=30),retry_policy=RetryPolicy(maximum_attempts=3),)diff --git a/products/signals/backend/temporal/drop_telemetry.py b/products/signals/backend/temporal/drop_telemetry.pyindex 9680ad234a68..7a08566ad4a3 100644--- a/products/signals/backend/temporal/drop_telemetry.py+++ b/products/signals/backend/temporal/drop_telemetry.py@@ -52,6 +52,51 @@ def summarize_drop_error(error: BaseException) -> tuple[str, str]:return error_type, message+def signal_dropped_input(+ signal: EmitSignalInputs, stage: str, error_type: str, error: str+) -> CaptureSignalDroppedInput:+ return CaptureSignalDroppedInput(+ team_id=signal.team_id,+ source_product=signal.source_product,+ source_type=signal.source_type,+ source_id=signal.source_id,+ weight=signal.weight,+ stage=stage,+ error_type=error_type,+ error=error,+ # Flatten before scheduling: the raw `extra` can nest large customer-derived+ # payloads, and the activity input is recorded verbatim in workflow history.+ extra=_telemetry_props_from_extra(signal.extra),+ )+++def capture_signal_dropped_event(team: Team, input: CaptureSignalDroppedInput) -> None:+ """Capture `signal_dropped` for one signal. Callers own the drop metric and the error handling.+ Requires `team.organization` to be loaded."""+ posthoganalytics.capture(+ event="signal_dropped",+ distinct_id=str(team.uuid),+ properties={+ # Flattened scalars only (truncated, nested lists/dicts dropped) — `extra`+ # nests customer-derived content that must not leak into product analytics.+ # Core keys win on conflict, same as signal_emitted / signal_emission_started.+ **_telemetry_props_from_extra(input.extra),+ # Composite of stage + error_type so drops are distinguishable by `reason`+ # alone — a transient ConnectError burst reads differently from the chronic+ # ClickHouseAtCapacity baseline instead of collapsing to one constant.+ "reason": f"{input.stage}:{input.error_type}",+ "stage": input.stage,+ "error_type": input.error_type,+ "error": input.error,+ "source_product": input.source_product,+ "source_type": input.source_type,+ "source_id": input.source_id,+ "weight": input.weight,+ },+ groups=groups(team.organization, team),+ )++@activity.defn@scoped_temporal()@close_db_connections@@ -60,28 +105,7 @@ async def capture_signal_dropped_activity(input: CaptureSignalDroppedInput) -> Nmetrics.increment_dropped(stage=input.stage, reason=input.error_type)try:team = await Team.objects.select_related("organization").aget(pk=input.team_id)- posthoganalytics.capture(- event="signal_dropped",- distinct_id=str(team.uuid),- properties={- # Flattened scalars only (truncated, nested lists/dicts dropped) — `extra`- # nests customer-derived content that must not leak into product analytics.- # Core keys win on conflict, same as signal_emitted / signal_emission_started.- **_telemetry_props_from_extra(input.extra),- # Composite of stage + error_type so drops are distinguishable by `reason`- # alone — a transient ConnectError burst reads differently from the chronic- # ClickHouseAtCapacity baseline instead of collapsing to one constant.- "reason": f"{input.stage}:{input.error_type}",- "stage": input.stage,- "error_type": input.error_type,- "error": input.error,- "source_product": input.source_product,- "source_type": input.source_type,- "source_id": input.source_id,- "weight": input.weight,- },- groups=groups(team.organization, team),- )+ capture_signal_dropped_event(team, input)except Exception as e:# Swallow the exception, to avoid breaking the flow over a failed analytics eventposthoganalytics.capture_exception(e)@@ -100,19 +124,7 @@ async def capture_signal_dropped(signal: EmitSignalInputs, error: BaseException,try:await workflow.execute_activity(capture_signal_dropped_activity,- CaptureSignalDroppedInput(- team_id=signal.team_id,- source_product=signal.source_product,- source_type=signal.source_type,- source_id=signal.source_id,- weight=signal.weight,- stage=stage,- error_type=error_type,- error=error_message,- # Flatten before scheduling: the raw `extra` can nest large customer-derived- # payloads, and the activity input is recorded verbatim in workflow history.- extra=_telemetry_props_from_extra(signal.extra),- ),+ signal_dropped_input(signal, stage, error_type, error_message),start_to_close_timeout=timedelta(minutes=1),retry_policy=RetryPolicy(maximum_attempts=2),)diff --git a/products/signals/backend/test/test_buffer_workflow.py b/products/signals/backend/test/test_buffer_workflow.pyindex 3062a0e88be7..0d17999ff9c1 100644--- a/products/signals/backend/test/test_buffer_workflow.py+++ b/products/signals/backend/test/test_buffer_workflow.py@@ -154,17 +154,24 @@ async def test_check_activity_attributes_drop_to_the_limit_that_fired(),patch(f"{BUFFER_MODULE}.metrics.increment_dropped") as dropped,patch(f"{BUFFER_MODULE}.capture_signal_report_daily_limit_paused") as capture,+ patch("products.signals.backend.temporal.drop_telemetry.posthoganalytics.capture") as analytics_capture,):+ signals = [_signal(ateam.id) for _ in range(3)]result = await ActivityEnvironment().run(check_signals_quota_limited_activity,- CheckSignalsQuotaInput(team_id=ateam.id, signal_count=3),+ CheckSignalsQuotaInput(team_id=ateam.id, signal_count=3, signals=signals),)assert result is expected+ dropped_events = [c.kwargs for c in analytics_capture.call_args_list if c.kwargs["event"] == "signal_dropped"]if expected_reason is None:dropped.assert_not_called()+ assert dropped_events == []else:dropped.assert_called_once_with(stage="ingestion", reason=expected_reason, count=3)+ # Every dropped signal gets its own terminal event, so the loss shows up per signal.+ assert sorted(e["properties"]["source_id"] for e in dropped_events) == sorted(s.source_id for s in signals)+ assert {e["properties"]["reason"] for e in dropped_events} == {f"ingestion:{expected_reason}"}# The capture event tracks its own gate: it fires whenever the daily limit binds, even when# the quota drop wins the single-reason metric attribution.if daily_limited: