: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): support idempotent emission (#72833)
Hugues Pouillot4ce0b512f68b
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.pyindex 6e3d0866da19..8426e0dbec99 100644--- a/products/signals/backend/facade/api.py+++ b/products/signals/backend/facade/api.py@@ -7,6 +7,7 @@ import pydanticimport structlogimport temporalioimport posthoganalytics+from temporalio.common import WorkflowIDReusePolicyfrom posthog.event_usage import groupsfrom posthog.helpers.tiktoken_encoding import LLM_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model@@ -206,6 +207,7 @@ async def emit_signal(weight: float = 0.5,extra: dict | None = None,remediation: SignalRemediation | None = None,+ idempotency_key: str | None = None,) -> None:"""Emit a signal for grouping and potential report generation, fire-and-forget.@@ -231,6 +233,8 @@ async def emit_signal((`human` + `agent` combined). When set, the signal is treated as actionable: the guidanceis surfaced to the research agent as authoritative direction, which it follows instead ofinvestigating from scratch. Not required by any existing source.+ idempotency_key: Optional stable key for callers that may retry. Repeated calls with+ the same key, source product, and source type start at most one emitter workflow.Example:await emit_signal(@@ -243,6 +247,9 @@ async def emit_signal(extra={"html_url": "https://github.com/posthog/posthog/issues/12345", "number": 12345, ...},)"""+ if idempotency_key is not None and not idempotency_key.strip():+ raise ValueError("idempotency_key must not be empty")+# Deferred: the temporal package imports the facade back (reingestion -> emit_signal), so# importing these workflows at module scope forms a circular import and drags the whole# temporal stack onto the Django startup path. Resolved lazily at call time instead.@@ -355,13 +362,26 @@ async def emit_signal(# Fire-and-forget: the emitter workflow will submit the signal to the buffer# via update, blocking if the buffer is full (backpressure).- await client.start_workflow(- SignalEmitterWorkflow.run,- SignalEmitterInput(team_id=team.id, signal=signal_input),- id=SignalEmitterWorkflow.workflow_id_for(team.id),- task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,- run_timeout=timedelta(minutes=10),+ emitter_idempotency_key = (+ f"{source_product}:{source_type}:{idempotency_key}" if idempotency_key is not None else None)+ try:+ await client.start_workflow(+ SignalEmitterWorkflow.run,+ SignalEmitterInput(team_id=team.id, signal=signal_input),+ id=SignalEmitterWorkflow.workflow_id_for(team.id, emitter_idempotency_key),+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,+ run_timeout=timedelta(minutes=10),+ id_reuse_policy=(+ WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY+ if emitter_idempotency_key is not None+ else WorkflowIDReusePolicy.ALLOW_DUPLICATE+ ),+ )+ except temporalio.exceptions.WorkflowAlreadyStartedError:+ if emitter_idempotency_key is None:+ raise+ return# Fire the analytics event only after the signal is definitively queued so# Temporal/connection failures don't inflate the "signals emitted" metric.diff --git a/products/signals/backend/temporal/emitter.py b/products/signals/backend/temporal/emitter.pyindex 57c91abd60b4..38b9ca14290d 100644--- a/products/signals/backend/temporal/emitter.py+++ b/products/signals/backend/temporal/emitter.py@@ -1,4 +1,5 @@import uuid+import hashlibfrom dataclasses import dataclassfrom datetime import timedelta@@ -23,12 +24,14 @@ class SignalEmitterWorkflow:Ephemeral per-signal workflow that submits a signal to the buffer workflowvia update. The update blocks if the buffer is full, providing backpressure.- emit_signal() starts this fire-and-forget with a unique ID per signal.+ emit_signal() starts this fire-and-forget with either a unique ID or a caller-provided+ idempotency key."""@staticmethod- def workflow_id_for(team_id: int) -> str:- return f"signal-emitter-{team_id}-{uuid.uuid4()}"+ def workflow_id_for(team_id: int, idempotency_key: str | None = None) -> str:+ suffix = hashlib.sha256(idempotency_key.encode()).hexdigest() if idempotency_key else str(uuid.uuid4())+ return f"signal-emitter-{team_id}-{suffix}"@temporalio.workflow.runasync def run(self, input: SignalEmitterInput) -> None:diff --git a/products/signals/backend/test/test_api.py b/products/signals/backend/test/test_api.pyindex 416733fe3012..6ec8bc2957a0 100644--- a/products/signals/backend/test/test_api.py+++ b/products/signals/backend/test/test_api.py@@ -5,6 +5,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pydanticimport temporalio.exceptions+from temporalio.common import WorkflowIDReusePolicyfrom products.signals.backend.contracts import SignalRemediationfrom products.signals.backend.facade.api import (@@ -181,6 +182,46 @@ class TestEmitSignalValidation:assert client.start_workflow.await_count == 2+ async def test_emit_signal_treats_an_existing_idempotent_emitter_as_success(self, team_stub):+ client = AsyncMock()+ client.start_workflow.side_effect = [+ temporalio.exceptions.WorkflowAlreadyStartedError("already started", "buffer-signals-1"),+ temporalio.exceptions.WorkflowAlreadyStartedError("already started", "signal-emitter-1-stable"),+ ]++ with (+ patch("products.signals.backend.facade.api.async_connect", return_value=client),+ patch.object(SignalSourceConfig, "is_source_enabled", return_value=True),+ ):+ await emit_signal(+ team=team_stub,+ source_product="github",+ source_type="issue",+ source_id="test-id-1",+ description="A valid signal",+ extra=GITHUB_ISSUE_EXTRA,+ idempotency_key="notification-1",+ )++ emitter_call = client.start_workflow.call_args_list[1]+ assert emitter_call.kwargs["id"] == SignalEmitterWorkflow.workflow_id_for(+ team_stub.id, "github:issue:notification-1"+ )+ assert emitter_call.kwargs["id_reuse_policy"] == WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY++ @pytest.mark.parametrize("idempotency_key", ["", " "])+ async def test_emit_signal_rejects_empty_idempotency_keys(self, team_stub, idempotency_key):+ with pytest.raises(ValueError, match="idempotency_key must not be empty"):+ await emit_signal(+ team=team_stub,+ source_product="github",+ source_type="issue",+ source_id="test-id-1",+ description="A valid signal",+ extra=GITHUB_ISSUE_EXTRA,+ idempotency_key=idempotency_key,+ )+@pytest.mark.asyncioclass TestEmitSignalAnalytics: