: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(growth): real-time signup enrichment workflow (#70118)
Matt Brooker9fc9cfa575f6
diff --git a/posthog/api/signup.py b/posthog/api/signup.pyindex 49ec1bc8d1e5..1a1426493f7f 100644--- a/posthog/api/signup.py+++ b/posthog/api/signup.py@@ -38,6 +38,7 @@ from posthog.models.organization_invite import INVITE_DAYS_VALIDITYfrom posthog.models.webauthn_credential import WebauthnCredentialfrom posthog.permissions import CanCreateOrgfrom posthog.rate_limit import SignupEmailPrecheckThrottle, SignupIPThrottle, SignupResendInviteThrottle+from posthog.temporal.signup_enrichment.trigger import start_signup_enrichment_workflowfrom posthog.utils import get_can_create_org, is_relative_urlfrom posthog.workos_radar import RadarAction, RadarAuthMethod, evaluate_auth_attempt@@ -303,6 +304,14 @@ class SignupSerializer(serializers.Serializer):referral_source_ai_prompt=referral_source_ai_prompt,)+ # Fire-and-forget real-time enrichment for onboarding routing. Fully guarded and+ # never raises, so it cannot block or fail signup.+ start_signup_enrichment_workflow(+ organization_id=str(self._organization.id),+ distinct_id=user.distinct_id,+ email=user.email,+ )+verify_email_or_login(request, user)return userdiff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex b4ef41534120..8f941ad2c4ab 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -149,6 +149,10 @@ from posthog.temporal.session_replay.surfacing_scoring_sweep import (SURFACING_SCORING_SWEEP_ACTIVITIES,SURFACING_SCORING_SWEEP_WORKFLOWS,)+from posthog.temporal.signup_enrichment import (+ ACTIVITIES as SIGNUP_ENRICHMENT_ACTIVITIES,+ WORKFLOWS as SIGNUP_ENRICHMENT_WORKFLOWS,+)from posthog.temporal.sync_events_retention import SYNC_EVENTS_RETENTION_ACTIVITIES, SYNC_EVENTS_RETENTION_WORKFLOWSfrom posthog.temporal.sync_person_distinct_ids import (ACTIVITIES as SYNC_PERSON_DISTINCT_IDS_ACTIVITIES,@@ -289,7 +293,8 @@ _task_queue_specs = [+ WAREHOUSE_SOURCES_QUEUE_PARTITION_WORKFLOWS+ SYNC_EVENTS_RETENTION_WORKFLOWS+ JOB_LOGS_WORKFLOWS- + NOTEBOOKS_WORKFLOWS,+ + NOTEBOOKS_WORKFLOWS+ + SIGNUP_ENRICHMENT_WORKFLOWS,PROXY_SERVICE_ACTIVITIES+ DELETE_PERSONS_ACTIVITIES+ DELETE_TEAMS_ACTIVITIES@@ -307,7 +312,16 @@ _task_queue_specs = [+ WAREHOUSE_SOURCES_QUEUE_PARTITION_ACTIVITIES+ SYNC_EVENTS_RETENTION_ACTIVITIES+ JOB_LOGS_ACTIVITIES- + NOTEBOOKS_ACTIVITIES,+ + NOTEBOOKS_ACTIVITIES+ + SIGNUP_ENRICHMENT_ACTIVITIES,+ ),+ # Dedicated landing zone for signup enrichment. Defaults to the general-purpose queue name (so it+ # merges into that fleet until a dedicated worker exists); setting SIGNUP_ENRICHMENT_TASK_QUEUE on a+ # worker registers these workflows under the dedicated queue, letting dispatch move there with no code change.+ (+ settings.SIGNUP_ENRICHMENT_TASK_QUEUE,+ SIGNUP_ENRICHMENT_WORKFLOWS,+ SIGNUP_ENRICHMENT_ACTIVITIES,),(settings.EXPERIMENTS_RECALCULATION_TASK_QUEUE,diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex fcd0039502b7..645b67752443 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -116,6 +116,12 @@ BATCH_EXPORTS_TASK_QUEUE = _set_temporal_task_queue("batch-exports-task-queue")DATA_MODELING_TASK_QUEUE = _set_temporal_task_queue("data-modeling-task-queue")SYNC_BATCH_EXPORTS_TASK_QUEUE = _set_temporal_task_queue("no-sandbox-python-django")GENERAL_PURPOSE_TASK_QUEUE = _set_temporal_task_queue("general-purpose-task-queue")+# Defaults to the general-purpose fleet so dispatch always has a live worker; set the env to+# "signup-enrichment-task-queue" to route unauthenticated signup enrichment to a dedicated,+# separately-scalable worker once one is deployed.+SIGNUP_ENRICHMENT_TASK_QUEUE = _set_temporal_task_queue(+ os.getenv("SIGNUP_ENRICHMENT_TASK_QUEUE", "general-purpose-task-queue")+)EXPERIMENTS_RECALCULATION_TASK_QUEUE = _set_temporal_task_queue("experiments-recalculation-task-queue")HEALTH_CHECK_TASK_QUEUE = _set_temporal_task_queue("health-check-task-queue")DUCKLAKE_TASK_QUEUE = _set_temporal_task_queue("ducklake-task-queue")diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 6e6152944b46..28c7714f698a 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -338,6 +338,10 @@ SESSION_COOKIE_CREATED_AT_KEY = get_from_env("SESSION_COOKIE_CREATED_AT_KEY", "s# off in the test suite (like AXES_ENABLED) so its per-request feature-flag check doesn't run during# tests that assert posthoganalytics.feature_enabled call counts.SESSION_RISK_ENABLED = get_from_env("SESSION_RISK_ENABLED", not TEST, type_cast=str_to_bool)+# Kill switch for the real-time signup enrichment workflow (products/growth/backend/enrichment).+# Off by default: it must stay off until the launch fill-rate/failure alert is in place, and v0 is+# US-only. Fire-and-forget from signup, so this only gates whether the workflow is dispatched at all.+GROWTH_SIGNUP_ENRICHMENT_ENABLED = get_from_env("GROWTH_SIGNUP_ENRICHMENT_ENABLED", False, type_cast=str_to_bool)# Session keys for risk-based step-up (posthog/session/risk.py). Named so every reader/writer shares# one source of truth, like SESSION_COOKIE_CREATED_AT_KEY above.SESSION_STEP_UP_REQUIRED_KEY = get_from_env("SESSION_STEP_UP_REQUIRED_KEY", "step_up_required")diff --git a/posthog/temporal/signup_enrichment/__init__.py b/posthog/temporal/signup_enrichment/__init__.pynew file mode 100644index 000000000000..7d3cec316090--- /dev/null+++ b/posthog/temporal/signup_enrichment/__init__.py@@ -0,0 +1,5 @@+from posthog.temporal.signup_enrichment.workflow import SignupEnrichmentWorkflow, enrich_signup_organization_activity++WORKFLOWS = [SignupEnrichmentWorkflow]++ACTIVITIES = [enrich_signup_organization_activity]diff --git a/posthog/temporal/signup_enrichment/trigger.py b/posthog/temporal/signup_enrichment/trigger.pynew file mode 100644index 000000000000..79343747e9be--- /dev/null+++ b/posthog/temporal/signup_enrichment/trigger.py@@ -0,0 +1,130 @@+"""Fire-and-forget dispatch of the signup enrichment workflow from the request path.++Every guard lives here so the signup serializer stays a one-line call. Dispatch is+gated by the kill switch and US-only for v0, and never raises — a Temporal outage+degrades to "enrichment did not run". The provider key lives on the workers only. Personal-domain+signups get no provider lookup, but the work-vs-personal email signal is recorded+for every signup so consumers can read it either way.+"""++import asyncio+import threading+from concurrent.futures import ThreadPoolExecutor+from email.utils import parseaddr++from django.conf import settings+from django.db import transaction++import structlog+from temporalio.common import WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedError+from temporalio.service import RPCError++from posthog.exceptions_capture import capture_exception+from posthog.temporal.common.client import sync_connect+from posthog.temporal.signup_enrichment.workflow import SignupEnrichmentInputs+from posthog.utils import GenericEmails, get_instance_region++from products.growth.backend.enrichment.writer import record_signup_work_email++logger = structlog.get_logger(__name__)++_generic_emails = GenericEmails()++# Bounded dispatch pool: a slow or unreachable Temporal must never let signup-triggered+# threads accumulate on web pods. When the pool's backlog cap is hit, dispatch drops —+# fire-and-forget degrades to "enrichment did not run", which the launch signal surfaces.+_DISPATCH_MAX_WORKERS = 4+_DISPATCH_MAX_PENDING = 64+_dispatch_executor = ThreadPoolExecutor(+ max_workers=_DISPATCH_MAX_WORKERS, thread_name_prefix="signup-enrichment-dispatch"+)+_dispatch_slots = threading.BoundedSemaphore(_DISPATCH_MAX_PENDING)+++def _domain_from_email(email: str) -> str | None:+ _, address = parseaddr(email or "")+ if "@" not in address:+ return None+ domain = address.rsplit("@", 1)[1].strip().lower()+ return domain or None+++def start_signup_enrichment_workflow(*, organization_id: str, distinct_id: str | None, email: str) -> None:+ """Dispatch enrichment for a freshly signed-up org, once the request transaction commits."""+ # The flag alone gates dispatch. Deliberately no provider-key check here: the key lives+ # only on the workers, and a keyless worker fails loudly into the launch alert instead of+ # web pods silently never dispatching (also keeps the key off the public web fleet).+ if not settings.GROWTH_SIGNUP_ENRICHMENT_ENABLED:+ return+ # v0 is US-only.+ if get_instance_region() != "US":+ return++ domain = _domain_from_email(email)+ if not domain:+ return++ work_email = not _generic_emails.is_generic(email)+ _record_work_email(organization_id=str(organization_id), work_email=work_email)+ if not work_email or not distinct_id:+ return++ inputs = SignupEnrichmentInputs(organization_id=str(organization_id), distinct_id=distinct_id, domain=domain)+ # on_commit so the worker never reads the org/enrichment rows before they are committed. The+ # callback fires inline on the signup request thread (it runs after that transaction commits),+ # so dispatch goes to the bounded pool: building the Temporal client must not add latency to+ # the signup response, and the pool caps how much a Temporal outage can pile up.+ transaction.on_commit(lambda: _submit_dispatch(inputs))+++def _submit_dispatch(inputs: SignupEnrichmentInputs) -> None:+ if not _dispatch_slots.acquire(blocking=False):+ logger.warning(+ "signup_enrichment_dispatch_dropped", organization_id=inputs.organization_id, reason="dispatch_backlog_full"+ )+ return+ try:+ _dispatch_executor.submit(_dispatch_and_release, inputs)+ except Exception as e:+ _dispatch_slots.release()+ capture_exception(e)+++def _dispatch_and_release(inputs: SignupEnrichmentInputs) -> None:+ try:+ _dispatch(inputs)+ finally:+ _dispatch_slots.release()+++def _record_work_email(*, organization_id: str, work_email: bool) -> None:+ # The write runs in its own savepoint; a failure here must never surface to signup.+ try:+ record_signup_work_email(organization_id=organization_id, work_email=work_email)+ except Exception as e:+ capture_exception(e)+++def _dispatch(inputs: SignupEnrichmentInputs) -> None:+ try:+ client = sync_connect()+ asyncio.run(+ client.start_workflow(+ "signup-enrichment",+ inputs,+ id=f"signup-enrichment-{inputs.organization_id}",+ # Rides the general-purpose fleet by default; the SIGNUP_ENRICHMENT_TASK_QUEUE env flips+ # this unauthenticated signup work onto a dedicated, bounded queue once a worker consumes it.+ task_queue=settings.SIGNUP_ENRICHMENT_TASK_QUEUE,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ )+ )+ except WorkflowAlreadyStartedError:+ # A re-signup race hits the still-running workflow id; expected, not an error.+ logger.info("signup_enrichment_dispatch_skipped", organization_id=inputs.organization_id)+ except RPCError as e:+ # A transient RPC issue must not surface to signup.+ logger.info("signup_enrichment_dispatch_skipped", organization_id=inputs.organization_id, error=str(e))+ except Exception as e:+ capture_exception(e)diff --git a/posthog/temporal/signup_enrichment/workflow.py b/posthog/temporal/signup_enrichment/workflow.pynew file mode 100644index 000000000000..03648782081c--- /dev/null+++ b/posthog/temporal/signup_enrichment/workflow.py@@ -0,0 +1,188 @@+"""Real-time signup enrichment: a fire-and-forget Temporal workflow started after signup.++The workflow wraps the orchestration-agnostic enrichment core (products/growth), writes the+live stores, wires the write-once at-signup snapshot, and emits a launch fill-rate/failure+signal. It is dispatched from the signup request path behind a kill switch and must never+block or fail signup — see posthog/temporal/signup_enrichment/trigger.py.+"""++import json+import typing+import datetime as dt+import dataclasses++from django.db import close_old_connections++from temporalio import activity, workflow+from temporalio.common import RetryPolicy++from posthog.exceptions_capture import capture_exception+from posthog.ph_client import get_client+from posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.common.logger import get_logger++from products.growth.backend.enrichment.core import enrich_organization+from products.growth.backend.enrichment.providers import HarmonicEnrichmentProvider+from products.growth.backend.enrichment.snapshot import SignupEnrichmentSnapshot, capture_signup_enrichment_snapshot+from products.growth.backend.models import OrganizationEnrichment++LOGGER = get_logger(__name__)++ENRICHMENT_SIGNAL_EVENT = "signup_enrichment_completed"+ENRICHMENT_RECHECK_EVENT = "signup_enrichment_recheck"++# Hard cap per attempt. The Harmonic client tries up to two domain variations at 30s each,+# so a single lookup can legitimately run ~60s; give it headroom then stop.+ENRICH_ACTIVITY_TIMEOUT = dt.timedelta(seconds=90)++# A couple of retries for transient provider/network blips, then give up quietly. Kept as a+# constant so the activity's failure-signal gate can't drift from the workflow's retry policy.+MAX_ENRICH_ATTEMPTS = 3++# Harmonic's enrich mutation seeds async enrichment for a company it doesn't yet index, so a+# domain it can't match at signup often resolves a few hours later. One delayed recheck recovers+# those late-indexed companies without polling.+RECHECK_DELAY = dt.timedelta(hours=4)+++class SignupEnrichmentInputs:+ organization_id: str+ distinct_id: str+ domain: str+++def _deterministic_company_type(organization_id: str) -> typing.Optional[str]:+ """The classifier's at-signup value, if the signup hook has written it."""+ record = OrganizationEnrichment.objects.filter(organization_id=organization_id).first()+ if record is None:+ return None+ value = record.data.get("company_type_deterministic")+ return value if isinstance(value, str) else None+++async def enrich_signup_organization_activity(+ inputs: SignupEnrichmentInputs, is_recheck: bool = False+) -> dict[str, typing.Any]:+ """Enrich one organization by domain and persist it to the live stores.++ First attempt (is_recheck=False): also captures the write-once at-signup snapshot and emits+ the launch signal. The recheck (is_recheck=True) writes the live stores exactly like a first+ attempt but leaves the snapshot and the launch signal untouched — the snapshot is at-signup by+ design, and the launch alert reads only the first attempt — emitting its own recheck event.+ """+ from asgiref.sync import sync_to_async # noqa: PLC0415 — heavy import kept off the workflow module path++ close_old_connections()+ logger = LOGGER.bind(organization_id=inputs.organization_id, is_recheck=is_recheck)++ if is_recheck:+ # The org owner can delete the org during the recheck delay; without this guard the+ # recheck would enrich a deleted org (db_constraint=False means orphan rows, and the+ # group projection would write properties for a dead org).+ from posthog.models import Organization # noqa: PLC0415 — heavy import kept off the workflow module path++ org_exists = await sync_to_async(Organization.objects.filter(id=inputs.organization_id).exists)()+ if not org_exists:+ logger.info("signup_enrichment_recheck_skipped_org_deleted")+ return {"matched": False, "fields_filled": 0, "org_deleted": True}++ pha_client = get_client()++ try:+ fields = await enrich_organization(+ organization_id=inputs.organization_id,+ domain=inputs.domain,+ provider=HarmonicEnrichmentProvider(),+ pha_client=pha_client,+ is_recheck=is_recheck,+ )+ filled = fields.to_dict() if fields else {}+ matched = fields is not None++ if not is_recheck:+ deterministic = await sync_to_async(_deterministic_company_type)(inputs.organization_id)+ snapshot = SignupEnrichmentSnapshot(+ company_type=(fields.company_type if fields else None) or deterministic,+ headcount=fields.headcount if fields else None,+ headcount_engineering=fields.headcount_engineering if fields else None,+ industry=fields.industry if fields else None,+ country=fields.country if fields else None,+ founded_year=fields.founded_year if fields else None,+ funding_stage=fields.funding_stage if fields else None,+ is_yc_company=fields.is_yc_company if fields else None,+ )+ await sync_to_async(capture_signup_enrichment_snapshot)(+ pha_client,+ organization_id=inputs.organization_id,+ distinct_id=inputs.distinct_id,+ snapshot=snapshot,+ )++ if pha_client is not None:+ if is_recheck:+ pha_client.capture(+ distinct_id=inputs.distinct_id,+ event=ENRICHMENT_RECHECK_EVENT,+ properties={+ "upgraded": matched,+ "fields_filled": len(filled),+ "organization_id": inputs.organization_id,+ },+ groups={"organization": inputs.organization_id},+ )+ else:+ pha_client.capture(+ distinct_id=inputs.distinct_id,+ event=ENRICHMENT_SIGNAL_EVENT,+ properties={"success": True, "matched": matched, "fields_filled": sorted(filled.keys())},+ groups={"organization": inputs.organization_id},+ )+ logger.info("signup_enrichment_completed", matched=matched, fields_filled=len(filled))+ return {"matched": matched, "fields_filled": len(filled)}++ except Exception as e:+ capture_exception(e)+ # Emit the failure signal only on a first attempt whose retries are exhausted; a transient+ # error a later attempt recovers from, and any recheck failure, must not count against the+ # launch fill-rate/failure signal.+ if not is_recheck and pha_client is not None and activity.info().attempt >= MAX_ENRICH_ATTEMPTS:+ pha_client.capture(+ distinct_id=inputs.distinct_id,+ event=ENRICHMENT_SIGNAL_EVENT,+ properties={"success": False, "error": type(e).__name__},+ groups={"organization": inputs.organization_id},+ )+ raise+ finally:+ if pha_client is not None:+ pha_client.shutdown()++[email protected](name="signup-enrichment")+class SignupEnrichmentWorkflow(PostHogWorkflow):+ """Fire-and-forget enrichment for one organization, started right after signup."""++ @staticmethod+ def parse_inputs(inputs: list[str]) -> SignupEnrichmentInputs:+ return SignupEnrichmentInputs(**json.loads(inputs[0]))++ @workflow.run+ async def run(self, inputs: SignupEnrichmentInputs) -> dict[str, typing.Any]:+ result = await self._enrich(inputs, is_recheck=False)+ if result.get("matched"):+ return result++ # Give Harmonic's seeded async enrichment time to index the company, then look once more.+ await workflow.sleep(RECHECK_DELAY)+ return await self._enrich(inputs, is_recheck=True)++ async def _enrich(self, inputs: SignupEnrichmentInputs, *, is_recheck: bool) -> dict[str, typing.Any]:+ return await workflow.execute_activity(+ enrich_signup_organization_activity,+ args=[inputs, is_recheck],+ start_to_close_timeout=ENRICH_ACTIVITY_TIMEOUT,+ # Onboarding routing already degrades to a safe default when enrichment is absent.+ retry_policy=RetryPolicy(maximum_attempts=MAX_ENRICH_ATTEMPTS, initial_interval=dt.timedelta(seconds=5)),+ )diff --git a/posthog/temporal/tests/signup_enrichment/__init__.py b/posthog/temporal/tests/signup_enrichment/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/temporal/tests/signup_enrichment/test_activity.py b/posthog/temporal/tests/signup_enrichment/test_activity.pynew file mode 100644index 000000000000..e360a412a7d9--- /dev/null+++ b/posthog/temporal/tests/signup_enrichment/test_activity.py@@ -0,0 +1,71 @@+import dataclasses++import pytest+from unittest.mock import AsyncMock, MagicMock, patch++from temporalio.testing import ActivityEnvironment++from posthog.temporal.signup_enrichment.workflow import (+ MAX_ENRICH_ATTEMPTS,+ SignupEnrichmentInputs,+ enrich_signup_organization_activity,+)++from products.growth.backend.enrichment.fields import EnrichmentFields++pytestmark = pytest.mark.asyncio++_MODULE = "posthog.temporal.signup_enrichment.workflow"+_INPUTS = SignupEnrichmentInputs(organization_id="org-1", distinct_id="d1", domain="stripe.com")+++def _patches(*, enrich_return, deterministic=None):+ pha_client = MagicMock()+ return pha_client, (+ patch(f"{_MODULE}.get_client", return_value=pha_client),+ patch(f"{_MODULE}.enrich_organization", AsyncMock(**enrich_return)),+ patch(f"{_MODULE}._deterministic_company_type", return_value=deterministic),+ patch(f"{_MODULE}.capture_signup_enrichment_snapshot"),+ )+++async def test_emits_success_signal_and_snapshot_on_match():+ fields = EnrichmentFields(company_type="STARTUP", headcount=130, industry="Fintech")+ pha_client, (get_client, enrich, det, snapshot) = _patches(enrich_return={"return_value": fields})+ with get_client, enrich, det, snapshot as snapshot_mock:+ result = await ActivityEnvironment().run(enrich_signup_organization_activity, _INPUTS)++ assert result == {"matched": True, "fields_filled": 3}+ # Snapshot captured once, built from the enriched fields.+ snapshot_mock.assert_called_once()+ assert snapshot_mock.call_args.kwargs["snapshot"].company_type == "STARTUP"+ # Launch signal emitted with success + the filled field keys.+ signal = next(c for c in pha_client.capture.call_args_list if c.kwargs["event"] == "signup_enrichment_completed")+ assert signal.kwargs["properties"]["success"] is True+ assert signal.kwargs["properties"]["matched"] is True+++async def test_falls_back_to_deterministic_company_type_on_miss():+ pha_client, (get_client, enrich, det, snapshot) = _patches(enrich_return={"return_value": None}, deterministic="yc")+ with get_client, enrich, det, snapshot as snapshot_mock:+ result = await ActivityEnvironment().run(enrich_signup_organization_activity, _INPUTS)++ assert result == {"matched": False, "fields_filled": 0}+ assert snapshot_mock.call_args.kwargs["snapshot"].company_type == "yc"++[email protected]("attempt,expect_signal", [(1, False), (MAX_ENRICH_ATTEMPTS, True)])+async def test_failure_signal_emitted_only_on_final_attempt(attempt, expect_signal):+ pha_client, (get_client, enrich, det, snapshot) = _patches(enrich_return={"side_effect": RuntimeError("boom")})+ env = ActivityEnvironment()+ env.info = dataclasses.replace(env.info, attempt=attempt)+ with get_client, enrich, det, snapshot, pytest.raises(RuntimeError):+ await env.run(enrich_signup_organization_activity, _INPUTS)++ signals = [c for c in pha_client.capture.call_args_list if c.kwargs["event"] == "signup_enrichment_completed"]+ if expect_signal:+ assert len(signals) == 1+ assert signals[0].kwargs["properties"]["success"] is False+ assert signals[0].kwargs["properties"]["error"] == "RuntimeError"+ else:+ assert signals == []diff --git a/posthog/temporal/tests/signup_enrichment/test_trigger.py b/posthog/temporal/tests/signup_enrichment/test_trigger.pynew file mode 100644index 000000000000..fb42c1c09ef0--- /dev/null+++ b/posthog/temporal/tests/signup_enrichment/test_trigger.py@@ -0,0 +1,153 @@+import pytest+from unittest.mock import patch++from django.test import override_settings++from temporalio.exceptions import WorkflowAlreadyStartedError++from posthog.temporal.signup_enrichment.trigger import start_signup_enrichment_workflow+++class _InlineExecutor:+ def submit(self, fn, *args):+ fn(*args)++[email protected](autouse=True)+def _run_dispatch_pool_inline():+ with patch("posthog.temporal.signup_enrichment.trigger._dispatch_executor", _InlineExecutor()):+ yield+++def _dispatch_mocks(region="US"):+ """Patch out the transaction/Temporal/DB boundaries so on_commit fires inline."""+ return (+ patch("posthog.temporal.signup_enrichment.trigger.transaction.on_commit", side_effect=lambda fn: fn()),+ patch("posthog.temporal.signup_enrichment.trigger.sync_connect"),+ patch("posthog.temporal.signup_enrichment.trigger.asyncio.run"),+ patch("posthog.temporal.signup_enrichment.trigger.get_instance_region", return_value=region),+ patch("posthog.temporal.signup_enrichment.trigger.record_signup_work_email"),+ )+++@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")+def test_dispatches_for_work_email_in_us_and_records_work_email():+ on_commit, connect, run, region, record = _dispatch_mocks()+ with on_commit, connect as connect_mock, run, region, record as record_mock:+ start_signup_enrichment_workflow(organization_id="org-1", distinct_id="d1", email="[email protected]")+ connect_mock.assert_called_once()+ record_mock.assert_called_once_with(organization_id="org-1", work_email=True)+++@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=False, HARMONIC_API_KEY="key")+def test_kill_switch_off_never_dispatches_or_writes():+ on_commit, connect, run, region, record = _dispatch_mocks()+ with on_commit, connect as connect_mock, run, region, record as record_mock:+ start_signup_enrichment_workflow(organization_id="org-1", distinct_id="d1", email="[email protected]")+ connect_mock.assert_not_called()+ record_mock.assert_not_called()+++@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="")+def test_missing_harmonic_key_still_dispatches():+ # The key lives on the workers only; web-side dispatch must not depend on it. A keyless+ # worker fails into the launch alert, which is the observable failure we want.+ on_commit, connect, run, region, record = _dispatch_mocks()+ with on_commit, connect as connect_mock, run, region, record:+ start_signup_enrichment_workflow(organization_id="org-1", distinct_id="d1", email="[email protected]")+ connect_mock.assert_called_once()+++@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")+def test_non_us_region_never_dispatches():+ on_commit, connect, run, region, record = _dispatch_mocks(region="EU")+ with on_commit, connect as connect_mock, run, region, record:+ start_signup_enrichment_workflow(organization_id="org-1", distinct_id="d1", email="[email protected]")+ connect_mock.assert_not_called()+++@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")+def test_personal_email_records_work_email_false_without_provider_dispatch():+ on_commit, connect, run, region, record = _dispatch_mocks()+ with on_commit, connect as connect_mock, run, region, record as record_mock:+ start_signup_enrichment_workflow(organization_id="org-1", distinct_id="d1", email="[email protected]")+ connect_mock.assert_not_called()+ record_mock.assert_called_once_with(organization_id="org-1", work_email=False)+++@override_settings(+ GROWTH_SIGNUP_ENRICHMENT_ENABLED=True,+ HARMONIC_API_KEY="key",+ SIGNUP_ENRICHMENT_TASK_QUEUE="signup-enrichment-task-queue",+)+def test_dispatch_uses_configured_signup_enrichment_task_queue():+ on_commit, connect, run, region, record = _dispatch_mocks()+ with on_commit, connect as connect_mock, run, region, record:+ start_signup_enrichment_workflow(organization_id="org-1", distinct_id="d1", email="[email protected]")+ _, kwargs = connect_mock.return_value.start_workflow.call_args+ assert kwargs["task_queue"] == "signup-enrichment-task-queue"+++@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")+def test_invalid_email_never_dispatches_or_writes():+ on_commit, connect, run, region, record = _dispatch_mocks()+ with on_commit, connect as connect_mock, run, region, record as record_mock:+ start_signup_enrichment_workflow(organization_id="org-1", distinct_id="d1", email="not-an-email")+ connect_mock.assert_not_called()+ record_mock.assert_not_called()+++@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")+def test_missing_distinct_id_records_work_email_but_never_dispatches():+ on_commit, connect, run, region, record = _dispatch_mocks()+ with on_commit, connect as connect_mock, run, region, record as record_mock:+ start_signup_enrichment_workflow(organization_id="org-1", distinct_id=None, email="[email protected]")+ connect_mock.assert_not_called()+ record_mock.assert_called_once_with(organization_id="org-1", work_email=True)+++@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")+def test_work_email_write_failure_does_not_block_dispatch():+ on_commit, connect, run, region, record = _dispatch_mocks()+ with on_commit, connect as connect_mock, run, region, record as record_mock:+ record_mock.side_effect = RuntimeError("db down")+ with patch("posthog.temporal.signup_enrichment.trigger.capture_exception") as capture_mock:+ start_signup_enrichment_workflow(organization_id="org-1", distinct_id="d1", email="[email protected]")+ connect_mock.assert_called_once()+ capture_mock.assert_called_once()+++@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")+def test_duplicate_workflow_is_logged_not_captured():+ on_commit, connect, run, region, record = _dispatch_mocks()+ with on_commit, connect, run as run_mock, region, record:+ run_mock.side_effect = WorkflowAlreadyStartedError("signup-enrichment-org-1", "signup-enrichment")+ with patch("posthog.temporal.signup_enrichment.trigger.capture_exception") as capture_mock:+ start_signup_enrichment_workflow(organization_id="org-1", distinct_id="d1", email="[email protected]")+ capture_mock.assert_not_called()+++@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True)+def test_dispatch_dropped_when_backlog_full():+ import threading++ full = threading.BoundedSemaphore(1)+ full.acquire()+ on_commit, connect, run, region, record = _dispatch_mocks()+ with patch("posthog.temporal.signup_enrichment.trigger._dispatch_slots", full):+ with on_commit, connect as connect_mock, run, region, record:+ start_signup_enrichment_workflow(organization_id="org-1", distinct_id="d1", email="[email protected]")+ connect_mock.assert_not_called()+++@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True)+def test_dispatch_slot_released_after_run():+ import threading++ single = threading.BoundedSemaphore(1)+ on_commit, connect, run, region, record = _dispatch_mocks()+ with patch("posthog.temporal.signup_enrichment.trigger._dispatch_slots", single):+ with on_commit, connect as connect_mock, run, region, record:+ start_signup_enrichment_workflow(organization_id="org-1", distinct_id="d1", email="[email protected]")+ start_signup_enrichment_workflow(organization_id="org-2", distinct_id="d2", email="[email protected]")+ assert connect_mock.call_count == 2diff --git a/posthog/temporal/tests/signup_enrichment/test_workflow.py b/posthog/temporal/tests/signup_enrichment/test_workflow.pynew file mode 100644index 000000000000..aaf374d47223--- /dev/null+++ b/posthog/temporal/tests/signup_enrichment/test_workflow.py@@ -0,0 +1,107 @@+import uuid++import pytest+from unittest.mock import AsyncMock, MagicMock, patch++from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.temporal.signup_enrichment.workflow import (+ SignupEnrichmentInputs,+ SignupEnrichmentWorkflow,+ enrich_signup_organization_activity,+)++from products.growth.backend.enrichment.fields import EnrichmentFields++pytestmark = pytest.mark.asyncio++_MODULE = "posthog.temporal.signup_enrichment.workflow"+_INPUTS = SignupEnrichmentInputs(organization_id="org-1", distinct_id="d1", domain="stripe.com")+_TASK_QUEUE = "signup-enrichment-test-queue"+++def _events(pha_client: MagicMock, name: str) -> list:+ return [c for c in pha_client.capture.call_args_list if c.kwargs["event"] == name]+++async def _run(enrich_side_effect) -> tuple[dict, MagicMock, AsyncMock, MagicMock]:+ pha_client = MagicMock()+ enrich = AsyncMock(side_effect=enrich_side_effect)+ with (+ patch(f"{_MODULE}.get_client", return_value=pha_client),+ patch(f"{_MODULE}.enrich_organization", enrich),+ patch(f"{_MODULE}._deterministic_company_type", return_value=None),+ patch(f"{_MODULE}.capture_signup_enrichment_snapshot") as snapshot,+ patch("posthog.models.Organization.objects") as org_objects,+ ):+ org_objects.filter.return_value.exists.return_value = True+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=_TASK_QUEUE,+ workflows=[SignupEnrichmentWorkflow],+ activities=[enrich_signup_organization_activity],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ SignupEnrichmentWorkflow.run,+ _INPUTS,+ id=f"signup-enrichment-{uuid.uuid4()}",+ task_queue=_TASK_QUEUE,+ )+ return result, pha_client, enrich, snapshot+++async def test_miss_then_recheck_upgrades_without_a_second_completed_event():+ fields = EnrichmentFields(company_type="STARTUP", headcount=130, industry="Fintech")+ result, pha_client, enrich, snapshot = await _run([None, fields])++ assert result == {"matched": True, "fields_filled": 3}+ assert enrich.await_count == 2+ # The is_recheck label is threaded through to the enrichment core: False first, True on recheck.+ assert enrich.await_args_list[0].kwargs["is_recheck"] is False+ assert enrich.await_args_list[1].kwargs["is_recheck"] is True+ # is_recheck=True skips the at-signup snapshot, so it is captured only on the first attempt.+ snapshot.assert_called_once()++ recheck = _events(pha_client, "signup_enrichment_recheck")+ assert len(recheck) == 1+ assert recheck[0].kwargs["properties"] == {+ "upgraded": True,+ "fields_filled": 3,+ "organization_id": "org-1",+ }+ # The launch signal fires exactly once — on the first attempt, unchanged.+ completed = _events(pha_client, "signup_enrichment_completed")+ assert len(completed) == 1+ assert completed[0].kwargs["properties"]["matched"] is False+++async def test_match_on_first_attempt_skips_the_recheck():+ fields = EnrichmentFields(company_type="STARTUP", headcount=130)+ result, pha_client, enrich, snapshot = await _run([fields])++ assert result == {"matched": True, "fields_filled": 2}+ assert enrich.await_count == 1+ snapshot.assert_called_once()+ assert _events(pha_client, "signup_enrichment_recheck") == []+ assert len(_events(pha_client, "signup_enrichment_completed")) == 1+++async def test_recheck_skips_deleted_organization():+ """The 4h recheck must not enrich or emit for an org deleted during the delay."""+ inputs = SignupEnrichmentInputs(+ organization_id="00000000-0000-0000-0000-00000000dead", distinct_id="d1", domain="gone.dev"+ )+ with (+ patch(f"{_MODULE}.enrich_organization") as enrich_mock,+ patch(f"{_MODULE}.get_client") as client_mock,+ patch("posthog.models.Organization.objects") as org_objects,+ ):+ org_objects.filter.return_value.exists.return_value = False+ result = await enrich_signup_organization_activity(inputs, is_recheck=True)+ assert result["org_deleted"] is True+ assert result["matched"] is False+ enrich_mock.assert_not_called()+ client_mock.assert_not_called()