: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(growth): recycle dead db connections in signup enrichment worker (#72307)
Matt Brooker327b47470fdf
diff --git a/posthog/temporal/signup_enrichment/trigger.py b/posthog/temporal/signup_enrichment/trigger.pyindex 79343747e9be..8d22ae40cc18 100644--- a/posthog/temporal/signup_enrichment/trigger.py+++ b/posthog/temporal/signup_enrichment/trigger.py@@ -42,7 +42,7 @@ _dispatch_executor = ThreadPoolExecutor(_dispatch_slots = threading.BoundedSemaphore(_DISPATCH_MAX_PENDING)-def _domain_from_email(email: str) -> str | None:+def domain_from_email(email: str) -> str | None:_, address = parseaddr(email or "")if "@" not in address:return None@@ -61,7 +61,7 @@ def start_signup_enrichment_workflow(*, organization_id: str, distinct_id: str |if get_instance_region() != "US":return- domain = _domain_from_email(email)+ domain = domain_from_email(email)if not domain:return@@ -78,6 +78,20 @@ def start_signup_enrichment_workflow(*, organization_id: str, distinct_id: str |transaction.on_commit(lambda: _submit_dispatch(inputs))+def dispatch_signup_enrichment(inputs: SignupEnrichmentInputs) -> None:+ """Synchronous dispatch for operational re-runs (management commands).++ Applies no guards itself — callers own the kill switch and region gate (the backfill+ command enforces both before dispatching). Unlike the fire-and-forget signup path,+ dispatch errors propagate so the operator sees them; a still-running workflow for+ the org counts as dispatched.+ """+ try:+ _start_workflow(inputs)+ except WorkflowAlreadyStartedError:+ logger.info("signup_enrichment_dispatch_skipped", organization_id=inputs.organization_id)++def _submit_dispatch(inputs: SignupEnrichmentInputs) -> None:if not _dispatch_slots.acquire(blocking=False):logger.warning(@@ -106,20 +120,24 @@ def _record_work_email(*, organization_id: str, work_email: bool) -> None:capture_exception(e)+def _start_workflow(inputs: SignupEnrichmentInputs) -> None:+ 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,+ )+ )++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,- )- )+ _start_workflow(inputs)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)diff --git a/posthog/temporal/signup_enrichment/workflow.py b/posthog/temporal/signup_enrichment/workflow.pyindex 03648782081c..9c06e8a104b2 100644--- a/posthog/temporal/signup_enrichment/workflow.py+++ b/posthog/temporal/signup_enrichment/workflow.py@@ -11,8 +11,6 @@ import typingimport datetime as dtimport dataclasses-from django.db import close_old_connections-from temporalio import activity, workflowfrom temporalio.common import RetryPolicy@@ -20,6 +18,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.ph_client import get_clientfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.logger import get_logger+from posthog.temporal.common.utils import close_db_connectionsfrom products.growth.backend.enrichment.core import enrich_organizationfrom products.growth.backend.enrichment.providers import HarmonicEnrichmentProvider@@ -62,6 +61,7 @@ def _deterministic_company_type(organization_id: str) -> typing.Optional[str]:@activity.defn+@close_db_connectionsasync def enrich_signup_organization_activity(inputs: SignupEnrichmentInputs, is_recheck: bool = False) -> dict[str, typing.Any]:@@ -74,7 +74,6 @@ async def enrich_signup_organization_activity("""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:diff --git a/posthog/temporal/tests/signup_enrichment/test_activity.py b/posthog/temporal/tests/signup_enrichment/test_activity.pyindex e360a412a7d9..7f955e21ab8c 100644--- a/posthog/temporal/tests/signup_enrichment/test_activity.py+++ b/posthog/temporal/tests/signup_enrichment/test_activity.py@@ -1,8 +1,10 @@+import threadingimport dataclassesimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch+from asgiref.sync import sync_to_asyncfrom temporalio.testing import ActivityEnvironmentfrom posthog.temporal.signup_enrichment.workflow import (@@ -54,6 +56,31 @@ async def test_falls_back_to_deterministic_company_type_on_miss():assert snapshot_mock.call_args.kwargs["snapshot"].company_type == "yc"+async def test_connection_cleanup_runs_on_the_orm_thread():+ # Django connections are thread-local and the ORM work runs on asgiref's shared sync-executor+ # thread. Cleanup on any other thread is a no-op, and a dead connection in the executor thread+ # then fails every activity on the worker until the pod is replaced.+ cleanup_threads = []++ pha_client, (get_client, enrich, det, snapshot) = _patches(enrich_return={"return_value": None})+ with (+ get_client,+ enrich,+ det,+ snapshot,+ patch(+ "posthog.temporal.common.utils._close_initialized_connections",+ side_effect=lambda: cleanup_threads.append(threading.get_ident()),+ ),+ patch("posthog.temporal.common.utils.settings.TEST", False),+ ):+ await ActivityEnvironment().run(enrich_signup_organization_activity, _INPUTS)++ orm_thread = await sync_to_async(threading.get_ident)()+ assert cleanup_threads and all(t == orm_thread for t in cleanup_threads)+ assert orm_thread != threading.get_ident()++@pytest.mark.parametrize("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")})diff --git a/posthog/temporal/tests/signup_enrichment/test_trigger.py b/posthog/temporal/tests/signup_enrichment/test_trigger.pyindex fb42c1c09ef0..c9579ec9dd37 100644--- a/posthog/temporal/tests/signup_enrichment/test_trigger.py+++ b/posthog/temporal/tests/signup_enrichment/test_trigger.py@@ -5,7 +5,8 @@ from django.test import override_settingsfrom temporalio.exceptions import WorkflowAlreadyStartedError-from posthog.temporal.signup_enrichment.trigger import start_signup_enrichment_workflow+from posthog.temporal.signup_enrichment.trigger import dispatch_signup_enrichment, start_signup_enrichment_workflow+from posthog.temporal.signup_enrichment.workflow import SignupEnrichmentInputsclass _InlineExecutor:@@ -118,6 +119,23 @@ def test_work_email_write_failure_does_not_block_dispatch():@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")+ "error,propagates",+ [+ (WorkflowAlreadyStartedError("signup-enrichment-org-1", "signup-enrichment"), False),+ (RuntimeError("temporal unreachable"), True),+ ],+)+def test_dispatch_signup_enrichment_swallows_only_already_started(error, propagates):+ inputs = SignupEnrichmentInputs(organization_id="org-1", distinct_id="d1", domain="stripe.com")+ with patch("posthog.temporal.signup_enrichment.trigger._start_workflow", side_effect=error):+ if propagates:+ with pytest.raises(RuntimeError):+ dispatch_signup_enrichment(inputs)+ else:+ dispatch_signup_enrichment(inputs)++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:diff --git a/products/growth/backend/management/commands/backfill_signup_enrichment.py b/products/growth/backend/management/commands/backfill_signup_enrichment.pynew file mode 100644index 000000000000..e6cb76737f92--- /dev/null+++ b/products/growth/backend/management/commands/backfill_signup_enrichment.py@@ -0,0 +1,120 @@+"""Re-dispatch signup enrichment for organizations whose enrichment never persisted.++Targets orgs created in a window that were eligible at signup (work email recorded) but have+no archived provider fetch — the archive row is the first write of every enrichment run, so+its absence means the run never completed. Re-dispatch is safe: the workflow id reuse policy+allows a new run once the failed one has closed, and the writers merge rather than clobber.+"""++import time+import datetime as dt+from typing import Any++from django.conf import settings+from django.core.management.base import BaseCommand, CommandError, CommandParser++from posthog.models.organization import Organization, OrganizationMembership+from posthog.temporal.signup_enrichment.trigger import dispatch_signup_enrichment, domain_from_email+from posthog.temporal.signup_enrichment.workflow import SignupEnrichmentInputs+from posthog.utils import GenericEmails, get_instance_region++_generic_emails = GenericEmails()++# The signup creator's membership is written in the signup transaction, so it lands within+# seconds of the org row. An earliest membership older than this window means the signup+# user has left and the remaining members can't stand in for the signup identity.+_SIGNUP_MEMBERSHIP_WINDOW = dt.timedelta(minutes=5)+++class Command(BaseCommand):+ help = (+ "Re-dispatch signup enrichment for orgs created in [--after, --before) that were eligible "+ "(work email) but have no archived provider fetch, i.e. enrichment never completed."+ )++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--after", required=True, help="ISO 8601 datetime (UTC if naive): orgs created at or after")+ parser.add_argument("--before", required=True, help="ISO 8601 datetime (UTC if naive): orgs created before")+ parser.add_argument("--limit", type=int, default=None, help="Dispatch at most this many orgs")+ parser.add_argument("--delay", type=float, default=0.5, help="Seconds between dispatches")+ parser.add_argument("--dry-run", action="store_true", help="List the orgs without dispatching")++ def handle(self, *args: Any, **options: Any) -> None:+ # The kill switch is the master control for sending org data to the provider; a backfill+ # must not defeat it if it was turned off for a compliance, cost, or vendor reason.+ if not settings.GROWTH_SIGNUP_ENRICHMENT_ENABLED:+ raise CommandError("Signup enrichment is disabled (GROWTH_SIGNUP_ENRICHMENT_ENABLED); refusing to dispatch")+ # Enrichment is US-only for v0 (mirrors the signup-path region gate).+ if get_instance_region() != "US":+ raise CommandError("Signup enrichment is US-only; refusing to dispatch in this region")++ after = self._parse_datetime(options["after"])+ before = self._parse_datetime(options["before"])+ if after >= before:+ raise CommandError("--after must be earlier than --before")+ limit: int | None = options["limit"]++ orgs = (+ Organization.objects.filter(+ created_at__gte=after,+ created_at__lt=before,+ enrichment_record__data__work_email=True,+ )+ .exclude(enrichment_fetches__isnull=False)+ # The write-once snapshot guard row marks a completed first attempt, so a run whose+ # archive write was swallowed (archive_provider_fetch never raises) is still excluded.+ .exclude(enrichment_signup_snapshot__isnull=False)+ .order_by("created_at")+ .iterator()+ )++ dispatched = skipped = errored = 0+ for org in orgs:+ if limit is not None and dispatched >= limit:+ break+ membership = (+ OrganizationMembership.objects.filter(organization=org)+ .select_related("user")+ .order_by("joined_at")+ .first()+ )+ if membership is not None and membership.joined_at - org.created_at > _SIGNUP_MEMBERSHIP_WINDOW:+ skipped += 1+ self.stdout.write(f"skip {org.id} ({org.created_at:%Y-%m-%d %H:%M}) (signup user no longer a member)")+ continue++ user = membership.user if membership else None+ domain = domain_from_email(user.email) if user else None+ # The signup user's email can have changed since signup, so re-check it's a work email.+ if user is None or not user.distinct_id or not domain or _generic_emails.is_generic(user.email):+ skipped += 1+ self.stdout.write(f"skip {org.id} ({org.created_at:%Y-%m-%d %H:%M}) (no usable signup member)")+ continue++ inputs = SignupEnrichmentInputs(organization_id=str(org.id), distinct_id=user.distinct_id, domain=domain)+ if options["dry_run"]:+ self.stdout.write(f"would dispatch {org.id} ({org.created_at:%Y-%m-%d %H:%M}) domain={domain}")+ else:+ try:+ dispatch_signup_enrichment(inputs)+ except Exception as e:+ errored += 1+ self.stderr.write(f"error {org.id} ({org.created_at:%Y-%m-%d %H:%M}): {e}")+ continue+ self.stdout.write(f"dispatched {org.id} ({org.created_at:%Y-%m-%d %H:%M}) domain={domain}")+ time.sleep(options["delay"])+ dispatched += 1++ verb = "would dispatch" if options["dry_run"] else "dispatched"+ summary = f"{verb} {dispatched}, skipped {skipped}, errored {errored}"+ self.stdout.write(self.style.SUCCESS(summary) if errored == 0 else self.style.WARNING(summary))+ if errored:+ self.stderr.write("re-run the same window to retry errored orgs; completed orgs are excluded")++ @staticmethod+ def _parse_datetime(value: str) -> dt.datetime:+ try:+ parsed = dt.datetime.fromisoformat(value)+ except ValueError:+ raise CommandError(f"Invalid ISO 8601 datetime: {value!r}")+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=dt.UTC)diff --git a/products/growth/backend/tests/test_enrichment_backfill_command.py b/products/growth/backend/tests/test_enrichment_backfill_command.pynew file mode 100644index 000000000000..3f700a8fc3a1--- /dev/null+++ b/products/growth/backend/tests/test_enrichment_backfill_command.py@@ -0,0 +1,94 @@+import datetime as dt++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.management import CommandError, call_command+from django.test import override_settings++from posthog.models.organization import Organization, OrganizationMembership+from posthog.models.user import User++from products.growth.backend.models import EnrichmentSignupSnapshot, OrganizationEnrichment, OrganizationEnrichmentFetch++_COMMAND_MODULE = "products.growth.backend.management.commands.backfill_signup_enrichment"+++def _window() -> dict[str, str]:+ return {+ "after": (dt.datetime.now(dt.UTC) - dt.timedelta(hours=1)).isoformat(),+ "before": (dt.datetime.now(dt.UTC) + dt.timedelta(hours=1)).isoformat(),+ }+++@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True)+class TestBackfillSignupEnrichment(BaseTest):+ def _org(+ self,+ *,+ email: str,+ work_email: bool = True,+ fetched: bool = False,+ snapshotted: bool = False,+ joined_after: dt.timedelta | None = None,+ ) -> Organization:+ org = Organization.objects.create(name=email)+ user = User.objects.create_user(email=email, password=None, first_name="t")+ membership = OrganizationMembership.objects.create(organization=org, user=user)+ if joined_after is not None:+ OrganizationMembership.objects.filter(id=membership.id).update(joined_at=org.created_at + joined_after)+ OrganizationEnrichment.objects.create(organization=org, data={"work_email": work_email})+ if fetched:+ OrganizationEnrichmentFetch.objects.create(organization=org, provider="harmonic", payload={})+ if snapshotted:+ EnrichmentSignupSnapshot.objects.create(organization=org)+ return org++ def test_dispatches_only_eligible_orgs_without_a_fetch(self):+ target = self._org(email="[email protected]")+ self._org(email="[email protected]", fetched=True)+ self._org(email="[email protected]", work_email=False)+ self._org(email="[email protected]", snapshotted=True)+ self._org(email="[email protected]", joined_after=dt.timedelta(days=2))++ with (+ patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="US"),+ patch(f"{_COMMAND_MODULE}.dispatch_signup_enrichment") as dispatch,+ ):+ call_command("backfill_signup_enrichment", "--delay=0", **_window())++ assert dispatch.call_count == 1+ inputs = dispatch.call_args.args[0]+ assert inputs.organization_id == str(target.id)+ assert inputs.domain == "stripe.com"+ assert inputs.distinct_id == target.memberships.get().user.distinct_id++ def test_refuses_when_kill_switch_off(self):+ with override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=False):+ with self.assertRaises(CommandError):+ call_command("backfill_signup_enrichment", **_window())++ def test_continues_past_a_failed_dispatch(self):+ self._org(email="[email protected]")+ second = self._org(email="[email protected]")++ with (+ patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="US"),+ patch(+ f"{_COMMAND_MODULE}.dispatch_signup_enrichment", side_effect=[RuntimeError("temporal down"), None]+ ) as dispatch,+ ):+ call_command("backfill_signup_enrichment", "--delay=0", **_window())++ assert dispatch.call_count == 2+ assert dispatch.call_args.args[0].organization_id == str(second.id)++ def test_dry_run_dispatches_nothing(self):+ self._org(email="[email protected]")+ with (+ patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="US"),+ patch(f"{_COMMAND_MODULE}.dispatch_signup_enrichment") as dispatch,+ ):+ call_command("backfill_signup_enrichment", "--dry-run", **_window())++ dispatch.assert_not_called()