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(growth): make the enrichment kill switch an instance setting and register the sweep on deploy (#88758)

Matt Brookera0875a384b63
diff --git a/posthog/ph_client.py b/posthog/ph_client.py
index 83e4fc97cea4..d2ccd620d22a 100644
--- a/posthog/ph_client.py
+++ b/posthog/ph_client.py
@@ -127,10 +127,11 @@ class ScopedCapture:
@contextmanager
-def ph_scoped_capture():
+def ph_scoped_capture(region: str = "US"):
"""Use this instead of posthoganalytics.capture() in Celery tasks — the global
client's background flush may never run before the worker exits, silently losing events.
This creates a dedicated client and flushes on context-manager exit.
+ Pass the deployment region when events must stay in their regional project.
In a long-lived worker (e.g. Temporal activities), prefer `ph_background_capture` —
the client setup and synchronous flush here add seconds of blocking per call.
@@ -140,7 +141,7 @@ def ph_scoped_capture():
with ph_scoped_capture() as capture:
capture(distinct_id="...", event="my_event", properties={...})
"""
- ph_client = get_client()
+ ph_client = get_client(region)
# Flush even when the caller's block raises — events already captured
# before the exception shouldn't be dropped with the buffer.
diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.py
index 60e157c9dada..6df6fcac5c18 100644
--- a/posthog/settings/dynamic_settings.py
+++ b/posthog/settings/dynamic_settings.py
@@ -257,6 +257,16 @@ CONSTANCE_CONFIG = {
"Whether rate limiting is enabled",
bool,
),
+ "GROWTH_SIGNUP_ENRICHMENT_ENABLED": (
+ get_from_env("GROWTH_SIGNUP_ENRICHMENT_ENABLED", False, type_cast=str_to_bool),
+ "Kill switch for signup enrichment (products/growth/backend/enrichment): dispatch at signup, the daily re-enrichment sweep, and the recovery backfill. Every pod reads this row, so it is the one per-region toggle.",
+ bool,
+ ),
+ "GROWTH_ICP_REENRICH_DAILY_CAP": (
+ get_from_env("GROWTH_ICP_REENRICH_DAILY_CAP", 500, type_cast=int),
+ "Max organizations the daily ICP re-enrichment sweep re-fetches from Harmonic per run. The provider spend bound.",
+ int,
+ ),
"CLICKHOUSE_KILL_SWITCH": (
get_from_env("CLICKHOUSE_KILL_SWITCH", "off"),
"ClickHouse overload protection. Values: 'off', 'light' (reduce resources, shed background work), 'full' (aggressive caps on everything).",
@@ -345,6 +355,8 @@ CONSTANCE_CONFIG = {
}
SETTINGS_ALLOWING_API_OVERRIDE = (
+ "GROWTH_SIGNUP_ENRICHMENT_ENABLED",
+ "GROWTH_ICP_REENRICH_DAILY_CAP",
"HOGQL_SHARED_INSIGHT_DATABASE_ENABLED",
"RECORDINGS_PERFORMANCE_EVENTS_TTL_WEEKS",
"AUTO_START_ASYNC_MIGRATIONS",
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 18d3631345d0..3c07d45213dc 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -357,16 +357,8 @@ 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. Also the
-# de facto per-region toggle, since it is the only region-specific control — dispatch itself is
-# open to both US and EU (see get_instance_region gate in signup_enrichment/trigger.py), so a
-# region stays enrichment-free only by leaving this unset there. 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)
-# Max orgs the daily ICP re-enrichment sweep re-fetches per run — the Harmonic spend/rate
-# bound for products/growth/backend/temporal/signup_enrichment/reenrichment.py.
-GROWTH_ICP_REENRICH_DAILY_CAP = get_from_env("GROWTH_ICP_REENRICH_DAILY_CAP", 500, type_cast=int)
+# GROWTH_SIGNUP_ENRICHMENT_ENABLED and GROWTH_ICP_REENRICH_DAILY_CAP are instance settings
+# (dynamic_settings.py): the env var seeds the default, the DB row is the value every pod reads.
# The internal analytics project the enrichment pipeline reads/writes bridge and mirror data
# against (products/growth/backend/enrichment). Region-defaulted to the deployment's own internal
# project (the same team split the usage report uses), so enrichment lookups never touch another
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 927e0289b1f3..536e6fcebe73 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -104,6 +104,7 @@ from products.experiments.backend.temporal.schedule import (
create_experiment_precompute_enrollment_census_schedule,
)
from products.exports.backend.temporal.subscriptions.types import ScheduleAllSubscriptionsWorkflowInputs
+from products.growth.backend.temporal.signup_enrichment.schedule import create_icp_reenrichment_sweep_schedule
from products.logs.backend.facade.temporal import create_logs_volume_tick_schedule
from products.managed_warehouse.backend.facade.temporal import DucklakeCompactionInput
from products.replay_vision.backend.temporal.estimates import create_replay_vision_estimates_schedule
@@ -955,6 +956,9 @@ if settings.CLOUD_DEPLOYMENT:
schedules.append(create_finalize_usage_reports_schedule)
if should_register_checkpoint_compaction_schedule():
schedules.append(create_checkpoint_compaction_schedule)
+ # The sweep re-fetches each region's own orgs from Harmonic, and only US and EU carry the key.
+ if settings.CLOUD_DEPLOYMENT in ("US", "EU"):
+ schedules.append(create_icp_reenrichment_sweep_schedule)
if settings.EE_AVAILABLE:
schedules.append(create_schedule_all_subscriptions_schedule)
diff --git a/posthog/test/test_ph_client.py b/posthog/test/test_ph_client.py
index fa793c87ecbb..40b2679911fe 100644
--- a/posthog/test/test_ph_client.py
+++ b/posthog/test/test_ph_client.py
@@ -1,10 +1,10 @@
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase, override_settings
import posthoganalytics
-from posthog.ph_client import ScopedCapture, get_client
+from posthog.ph_client import ScopedCapture, get_client, ph_scoped_capture
class TestAILaneOptIn(SimpleTestCase):
@@ -32,6 +32,19 @@ class TestScopedCaptureFlush(SimpleTestCase):
ScopedCapture(client).flush()
client.flush.assert_called_once_with(timeout_seconds=None)
+ @override_settings(CLOUD_DEPLOYMENT="EU")
+ @patch("posthog.ph_client.get_client")
+ def test_scoped_capture_uses_requested_region(self, get_client_mock: MagicMock) -> None:
+ client = MagicMock()
+ get_client_mock.return_value = client
+
+ with ph_scoped_capture(region="EU") as capture:
+ capture(distinct_id="person", event="event")
+
+ get_client_mock.assert_called_once_with("EU")
+ client.capture.assert_called_once_with(distinct_id="person", event="event")
+ client.shutdown.assert_called_once()
+
class TestGetClientTestGuard(SimpleTestCase):
def test_client_is_disabled_under_test_settings(self) -> None:
diff --git a/products/growth/backend/management/commands/backfill_signup_enrichment.py b/products/growth/backend/management/commands/backfill_signup_enrichment.py
index 3e8084675799..ad3ef8700ed9 100644
--- a/products/growth/backend/management/commands/backfill_signup_enrichment.py
+++ b/products/growth/backend/management/commands/backfill_signup_enrichment.py
@@ -10,9 +10,9 @@ 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.instance_setting import get_instance_setting
from posthog.models.organization import Organization, OrganizationMembership
from posthog.utils import GenericEmails, get_instance_region
@@ -43,7 +43,7 @@ class Command(BaseCommand):
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:
+ if not get_instance_setting("GROWTH_SIGNUP_ENRICHMENT_ENABLED"):
raise CommandError("Signup enrichment is disabled (GROWTH_SIGNUP_ENRICHMENT_ENABLED); refusing to dispatch")
# Cloud only, mirrors the signup-path region gate (products/growth/backend/temporal/signup_enrichment/trigger.py).
if get_instance_region() not in ("US", "EU"):
diff --git a/products/growth/backend/management/commands/init_icp_reenrichment_schedule.py b/products/growth/backend/management/commands/init_icp_reenrichment_schedule.py
deleted file mode 100644
index a0d3c35fec1a..000000000000
--- a/products/growth/backend/management/commands/init_icp_reenrichment_schedule.py
+++ /dev/null
@@ -1,58 +0,0 @@
-"""Create (or update) the Temporal Schedule that runs the daily ICP re-enrichment sweep.
-
-Idempotent: safe to re-run on deploy or by hand. The schedule only starts the workflow; all
-eligibility guards (kill switch, region, cap) are re-checked inside the sweep's selection
-activity on every run, so pausing the sweep is a settings change, not a Temporal operation.
-"""
-
-from typing import Any
-
-from django.conf import settings
-from django.core.management.base import BaseCommand, CommandParser
-
-from temporalio.client import Schedule, ScheduleActionStartWorkflow, ScheduleOverlapPolicy, SchedulePolicy, ScheduleSpec
-
-from posthog.temporal.common.client import sync_connect
-from posthog.temporal.common.schedule import create_schedule, schedule_exists, update_schedule
-from posthog.utils import get_instance_region
-
-from products.growth.backend.temporal.signup_enrichment.reenrichment import IcpReenrichmentSweepInputs
-
-SCHEDULE_ID = "icp-reenrichment-sweep-daily"
-
-# 07:40 UTC daily: off the hour to avoid the shared-queue thundering herd, and adjacent to
-# the existing 7am growth/billing batch window so operators find related runs together.
-CRON = "40 7 * * *"
-
-
-class Command(BaseCommand):
- help = "Create or update the daily ICP re-enrichment sweep schedule (idempotent)."
-
- def add_arguments(self, parser: CommandParser) -> None:
- parser.add_argument("--trigger-now", action="store_true", help="Also run the sweep immediately")
-
- def handle(self, *args: Any, **options: Any) -> None:
- if get_instance_region() not in ("US", "EU"):
- self.stdout.write("Cloud-only; nothing to do in this region")
- return
-
- schedule = Schedule(
- action=ScheduleActionStartWorkflow(
- "icp-reenrichment-sweep",
- IcpReenrichmentSweepInputs(),
- id=SCHEDULE_ID,
- task_queue=settings.SIGNUP_ENRICHMENT_TASK_QUEUE,
- ),
- spec=ScheduleSpec(cron_expressions=[CRON]),
- # A sweep that overruns its slot (huge backlog) must not stack a second run on top.
- policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
- )
-
- client = sync_connect()
- if schedule_exists(client, SCHEDULE_ID):
- update_schedule(client, SCHEDULE_ID, schedule)
- outcome = "updated"
- else:
- create_schedule(client, SCHEDULE_ID, schedule, trigger_immediately=options["trigger_now"])
- outcome = "created"
- self.stdout.write(self.style.SUCCESS(f"{outcome} schedule {SCHEDULE_ID} ({CRON} UTC)"))
diff --git a/products/growth/backend/temporal/signup_enrichment/__init__.py b/products/growth/backend/temporal/signup_enrichment/__init__.py
index 9231d1925d16..5b85aa29d2ca 100644
--- a/products/growth/backend/temporal/signup_enrichment/__init__.py
+++ b/products/growth/backend/temporal/signup_enrichment/__init__.py
@@ -1,6 +1,7 @@
from products.growth.backend.temporal.signup_enrichment.reenrichment import (
IcpReenrichmentSweepWorkflow,
reenrich_organization_activity,
+ report_sweep_run_activity,
select_reenrichment_candidates_activity,
)
from products.growth.backend.temporal.signup_enrichment.workflow import (
@@ -14,4 +15,5 @@ ACTIVITIES = [
enrich_signup_organization_activity,
select_reenrichment_candidates_activity,
reenrich_organization_activity,
+ report_sweep_run_activity,
]
diff --git a/products/growth/backend/temporal/signup_enrichment/reenrichment.py b/products/growth/backend/temporal/signup_enrichment/reenrichment.py
index ab96dd09b1c7..af5f0a0cc3be 100644
--- a/products/growth/backend/temporal/signup_enrichment/reenrichment.py
+++ b/products/growth/backend/temporal/signup_enrichment/reenrichment.py
@@ -18,7 +18,7 @@ for those orgs on a 30–90-day window:
An org that Harmonic indexes after day 90 is never revisited. That is a deliberate ceiling,
not a backoff: `icp_reenrichment_attempt_count` is recorded but nothing reads it.
-Runs as a Temporal Schedule (see the init_icp_reenrichment_schedule command) because the
+Runs as a Temporal Schedule (registered on deploy by signup_enrichment/schedule.py) because the
Harmonic key lives on the workers only. Selection re-checks the kill switch and region on
every run, so flipping GROWTH_SIGNUP_ENRICHMENT_ENABLED off also stops the sweep. Each org
goes through `enrich_organization(is_recheck=True)` — same archive, same writers, same
@@ -36,10 +36,11 @@ from temporalio import activity, workflow
from temporalio.common import RetryPolicy
from posthog.exceptions_capture import capture_exception
-from posthog.ph_client import get_regional_ph_client
+from posthog.ph_client import get_regional_ph_client, ph_scoped_capture
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import close_db_connections
+from posthog.utils import get_instance_region
from products.growth.backend.temporal.signup_enrichment.workflow import ENRICH_ACTIVITY_TIMEOUT, MAX_ENRICH_ATTEMPTS
@@ -97,11 +98,11 @@ async def select_reenrichment_candidates_activity(inputs: IcpReenrichmentSweepIn
Guards live here rather than in the schedule so a config flip takes effect on the next
run without touching Temporal state.
"""
- from django.conf import settings # noqa: PLC0415 — heavy imports kept off the workflow module path
from django.db.models import Max, Min, Q # noqa: PLC0415
from asgiref.sync import sync_to_async # noqa: PLC0415
+ from posthog.models.instance_setting import get_instance_setting # noqa: PLC0415
from posthog.models.organization import OrganizationMembership # noqa: PLC0415
from posthog.utils import GenericEmails, get_instance_region # noqa: PLC0415
@@ -110,14 +111,15 @@ async def select_reenrichment_candidates_activity(inputs: IcpReenrichmentSweepIn
logger = LOGGER.bind()
- if not settings.GROWTH_SIGNUP_ENRICHMENT_ENABLED:
+ if not await sync_to_async(get_instance_setting)("GROWTH_SIGNUP_ENRICHMENT_ENABLED"):
logger.info("icp_reenrichment_skipped_kill_switch")
return []
if get_instance_region() not in ("US", "EU"):
logger.info("icp_reenrichment_skipped_region")
return []
- cap = inputs.cap if inputs.cap and inputs.cap > 0 else settings.GROWTH_ICP_REENRICH_DAILY_CAP
+ daily_cap = await sync_to_async(get_instance_setting)("GROWTH_ICP_REENRICH_DAILY_CAP")
+ cap = inputs.cap if inputs.cap and inputs.cap > 0 else daily_cap
generic_emails = GenericEmails()
def _select() -> list[dict[str, typing.Any]]:
@@ -211,21 +213,24 @@ async def select_reenrichment_candidates_activity(inputs: IcpReenrichmentSweepIn
@close_db_connections
async def reenrich_organization_activity(inputs: ReenrichOrgInputs) -> dict[str, typing.Any]:
"""One org through the standard enrichment path, recheck-style, with its own event."""
- from django.conf import settings # noqa: PLC0415 — heavy imports kept off the workflow module path
+
+ from django.db.models import Min # noqa: PLC0415
from asgiref.sync import sync_to_async # noqa: PLC0415
+ from posthog.models.instance_setting import get_instance_setting # noqa: PLC0415
from posthog.models.organization import Organization # noqa: PLC0415
from products.growth.backend.enrichment.core import enrich_organization # noqa: PLC0415
from products.growth.backend.enrichment.providers import HarmonicEnrichmentProvider # noqa: PLC0415
from products.growth.backend.enrichment.writer import merge_into_record # noqa: PLC0415
+ from products.growth.backend.models import OrganizationEnrichmentFetch # noqa: PLC0415
logger = LOGGER.bind(organization_id=inputs.organization_id)
# Re-checked here, not just at selection: a run can span hours, and this is the only
# gate standing between a flipped-off switch and further paid Harmonic calls.
- if not settings.GROWTH_SIGNUP_ENRICHMENT_ENABLED:
+ if not await sync_to_async(get_instance_setting)("GROWTH_SIGNUP_ENRICHMENT_ENABLED"):
logger.info("icp_reenrichment_skipped_kill_switch")
return {"matched": False, "skipped": "kill_switch"}
@@ -239,16 +244,33 @@ async def reenrich_organization_activity(inputs: ReenrichOrgInputs) -> dict[str,
# Stamped before the org reaches the provider so a raised Harmonic error still counts
# as an attempt — otherwise a failing org never gets a fetch row and re-occupies the
# head of tomorrow's selection, burning another MAX_ENRICH_ATTEMPTS Harmonic calls.
- attempted_at = dt.datetime.now(dt.UTC).isoformat()
+ now = dt.datetime.now(dt.UTC)
+ attempted_at = now.isoformat()
+
+ # previous_status, attempt_number and days_since_first_fetch make the upgrade rate by
+ # attempt and by profile age measurable. That rate decides whether re-fetching an empty
+ # profile is worth its Harmonic quota, and nothing else records it.
+ observed: dict[str, typing.Any] = {}
def _stamp_attempt(current: dict[str, typing.Any]) -> dict[str, typing.Any]:
+ attempt_number = current.get(ICP_REENRICHMENT_ATTEMPT_COUNT_KEY, 0) + 1
+ observed["previous_status"] = current.get("icp_fit_status")
+ observed["attempt_number"] = attempt_number
return {
ICP_REENRICHMENT_LAST_ATTEMPTED_AT_KEY: attempted_at,
- ICP_REENRICHMENT_ATTEMPT_COUNT_KEY: current.get(ICP_REENRICHMENT_ATTEMPT_COUNT_KEY, 0) + 1,
+ ICP_REENRICHMENT_ATTEMPT_COUNT_KEY: attempt_number,
}
await sync_to_async(merge_into_record)(inputs.organization_id, _stamp_attempt)
+ def _first_fetched_at() -> typing.Optional[dt.datetime]:
+ return OrganizationEnrichmentFetch.objects.filter(organization_id=inputs.organization_id).aggregate(
+ first=Min("fetched_at")
+ )["first"]
+
+ first_fetched_at = await sync_to_async(_first_fetched_at)()
+ observed["days_since_first_fetch"] = (now - first_fetched_at).days if first_fetched_at else None
+
pha_client = get_regional_ph_client()
if pha_client is None:
logger.error("icp_reenrichment_no_regional_client")
@@ -273,11 +295,12 @@ async def reenrich_organization_activity(inputs: ReenrichOrgInputs) -> dict[str,
"organization_id": inputs.organization_id,
"matched": matched,
"icp_fit_status": status,
+ **observed,
},
groups={"organization": inputs.organization_id},
)
- logger.info("icp_reenrichment_completed", matched=matched, icp_fit_status=status)
- return {"matched": matched, "icp_fit_status": status}
+ logger.info("icp_reenrichment_completed", matched=matched, icp_fit_status=status, **observed)
+ return {"matched": matched, "icp_fit_status": status, **observed}
except Exception as e:
capture_exception(e)
raise
@@ -285,6 +308,33 @@ async def reenrich_organization_activity(inputs: ReenrichOrgInputs) -> dict[str,
pha_client.shutdown()
[email protected](frozen=True)
+class SweepRunSummary:
+ selected: int
+ attempted: int
+ matched: int
+ failed: int
+
+
+SWEEP_RUN_EVENT = "icp_reenrichment_sweep_completed"
+
+
+def report_sweep_run_activity(summary: SweepRunSummary) -> None:
+ """One event per run, so an alert can see a sweep that stopped firing or selects nothing."""
+ region = get_instance_region()
+ if region not in ("US", "EU"):
+ LOGGER.error("icp_reenrichment_no_regional_client")
+ return
+
+ with ph_scoped_capture(region=region) as capture:
+ capture(
+ distinct_id="icp-reenrichment-sweep",
+ event=SWEEP_RUN_EVENT,
+ properties=dataclasses.asdict(summary),
+ )
+
+
@workflow.defn(name="icp-reenrichment-sweep")
class IcpReenrichmentSweepWorkflow(PostHogWorkflow):
"""Daily sweep: select due orgs, then re-enrich them one at a time.
@@ -328,4 +378,14 @@ class IcpReenrichmentSweepWorkflow(PostHogWorkflow):
# Per-org failures must not sink the sweep; the org stays eligible next run.
failed += 1
- return {"selected": len(candidates), "attempted": attempted, "matched": matched, "failed": failed}
+ summary = SweepRunSummary(selected=len(candidates), attempted=attempted, matched=matched, failed=failed)
+ # Keep analytics I/O in an activity so workflow replay remains deterministic.
+ # Patched so an execution recorded before this activity existed still replays.
+ if workflow.patched("icp-sweep-run-summary-2026-08"):
+ await workflow.execute_activity(
+ report_sweep_run_activity,
+ summary,
+ start_to_close_timeout=dt.timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ return dataclasses.asdict(summary)
diff --git a/products/growth/backend/temporal/signup_enrichment/schedule.py b/products/growth/backend/temporal/signup_enrichment/schedule.py
new file mode 100644
index 000000000000..db338453e3e8
--- /dev/null
+++ b/products/growth/backend/temporal/signup_enrichment/schedule.py
@@ -0,0 +1,49 @@
+"""The Temporal Schedule for the daily ICP re-enrichment sweep.
+
+Registered from posthog/temporal/schedule.py, so every deploy upserts it. The schedule only
+starts the workflow; the sweep re-checks the kill switch, region, and cap on every run, so
+pausing it is an instance-setting change, not a Temporal operation.
+"""
+
+from django.conf import settings
+
+from temporalio.client import (
+ Client,
+ Schedule,
+ ScheduleActionStartWorkflow,
+ ScheduleOverlapPolicy,
+ SchedulePolicy,
+ ScheduleSpec,
+)
+
+from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+
+from products.growth.backend.temporal.signup_enrichment.reenrichment import IcpReenrichmentSweepInputs
+
+SCHEDULE_ID = "icp-reenrichment-sweep-daily"
+
+# 07:40 UTC daily: off the hour to avoid the shared-queue thundering herd, and adjacent to
+# the existing 7am growth/billing batch window so operators find related runs together.
+CRON = "40 7 * * *"
+
+
+def build_icp_reenrichment_sweep_schedule() -> Schedule:
+ return Schedule(
+ action=ScheduleActionStartWorkflow(
+ "icp-reenrichment-sweep",
+ IcpReenrichmentSweepInputs(),
+ id=SCHEDULE_ID,
+ task_queue=settings.SIGNUP_ENRICHMENT_TASK_QUEUE,
+ ),
+ spec=ScheduleSpec(cron_expressions=[CRON]),
+ # A sweep that overruns its slot (huge backlog) must not stack a second run on top.
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ )
+
+
+async def create_icp_reenrichment_sweep_schedule(client: Client) -> None:
+ schedule = build_icp_reenrichment_sweep_schedule()
+ if await a_schedule_exists(client, SCHEDULE_ID):
+ await a_update_schedule(client, SCHEDULE_ID, schedule)
+ else:
+ await a_create_schedule(client, SCHEDULE_ID, schedule, trigger_immediately=False)
diff --git a/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py b/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py
index 9f9e05b43f8b..a0401debb62a 100644
--- a/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py
+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py
@@ -7,6 +7,7 @@ from django.test import override_settings
from asgiref.sync import async_to_sync
+from posthog.models.instance_setting import override_instance_config
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.user import User
@@ -19,7 +20,9 @@ from products.growth.backend.temporal.signup_enrichment.reenrichment import (
ICP_REENRICHMENT_LAST_ATTEMPTED_AT_KEY,
IcpReenrichmentSweepInputs,
ReenrichOrgInputs,
+ SweepRunSummary,
reenrich_organization_activity,
+ report_sweep_run_activity,
select_reenrichment_candidates_activity,
)
@@ -30,8 +33,13 @@ def _now() -> dt.datetime:
return dt.datetime.now(dt.UTC)
-@override_settings(CLOUD_DEPLOYMENT="US", GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, GROWTH_ICP_REENRICH_DAILY_CAP=500)
+@override_settings(CLOUD_DEPLOYMENT="US")
class TestReenrichmentSelection(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.enterContext(override_instance_config("GROWTH_SIGNUP_ENRICHMENT_ENABLED", True))
+ self.enterContext(override_instance_config("GROWTH_ICP_REENRICH_DAILY_CAP", 500))
+
def _org_with_member(self, email: str) -> Organization:
organization = Organization.objects.create(name=email)
user = User.objects.create_user(email=email, password=None, first_name="sweep")
@@ -122,12 +130,12 @@ class TestReenrichmentSelection(BaseTest):
assert self._select() == []
- @override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=False)
def test_kill_switch_stops_the_sweep(self):
organization = self._org_with_member("[email protected]")
self._prime(organization)
- assert self._select() == []
+ with override_instance_config("GROWTH_SIGNUP_ENRICHMENT_ENABLED", False):
+ assert self._select() == []
def test_selection_backfills_the_cap_when_the_oldest_rows_fail_identity_filtering(self):
for i in range(3):
@@ -184,8 +192,11 @@ class TestReenrichmentSelection(BaseTest):
assert self._select() == []
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True)
class TestReenrichOrganizationActivity(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.enterContext(override_instance_config("GROWTH_SIGNUP_ENRICHMENT_ENABLED", True))
+
def _run(self, outcome: EnrichmentOutcome) -> tuple[dict, MagicMock, AsyncMock]:
pha_client = MagicMock()
enrich = AsyncMock(return_value=outcome)
@@ -210,7 +221,13 @@ class TestReenrichOrganizationActivity(BaseTest):
)
result, pha_client, enrich = self._run(outcome)
- assert result == {"matched": True, "icp_fit_status": "scored"}
+ assert result == {
+ "matched": True,
+ "icp_fit_status": "scored",
+ "previous_status": None,
+ "attempt_number": 1,
+ "days_since_first_fetch": None,
+ }
assert enrich.await_args is not None
assert enrich.await_args.kwargs["is_recheck"] is True
assert enrich.await_args.kwargs["role_at_organization"] == "engineering"
@@ -224,9 +241,60 @@ class TestReenrichOrganizationActivity(BaseTest):
outcome = EnrichmentOutcome(provider_fields=None, fit=IcpFitResult(status="not_found"))
result, pha_client, _ = self._run(outcome)
- assert result == {"matched": False, "icp_fit_status": "not_found"}
+ assert result == {
+ "matched": False,
+ "icp_fit_status": "not_found",
+ "previous_status": None,
+ "attempt_number": 1,
+ "days_since_first_fetch": None,
+ }
assert pha_client.capture.call_args.kwargs["properties"]["icp_fit_status"] == "not_found"
+ def test_event_carries_previous_status_attempt_number_and_profile_age(self):
+ OrganizationEnrichment.objects.create(
+ organization=self.organization,
+ data={"icp_fit_status": "insufficient_data", ICP_REENRICHMENT_ATTEMPT_COUNT_KEY: 1},
+ )
+ first = OrganizationEnrichmentFetch.objects.create(
+ organization=self.organization, provider="harmonic", payload={"companyFound": False}
+ )
+ OrganizationEnrichmentFetch.objects.filter(id=first.id).update(fetched_at=_now() - dt.timedelta(days=40))
+ outcome = EnrichmentOutcome(
+ provider_fields=EnrichmentFields(company_type="STARTUP"), fit=IcpFitResult(status="scored", score=12)
+ )
+
+ result, pha_client, _ = self._run(outcome)
+
+ expected = {"previous_status": "insufficient_data", "attempt_number": 2, "days_since_first_fetch": 40}
+ assert {k: result[k] for k in expected} == expected
+ properties = pha_client.capture.call_args.kwargs["properties"]
+ assert {k: properties[k] for k in expected} == expected
+
+ def test_run_summary_emits_one_event_with_the_counts(self):
+ capture = MagicMock()
+ scoped_capture = MagicMock()
+ scoped_capture.__enter__.return_value = capture
+ with (
+ patch(f"{_MODULE}.get_instance_region", return_value="EU"),
+ patch(f"{_MODULE}.ph_scoped_capture", return_value=scoped_capture) as scoped_capture_factory,
+ ):
+ report_sweep_run_activity(SweepRunSummary(selected=3, attempted=3, matched=1, failed=1))
+
+ scoped_capture_factory.assert_called_once_with(region="EU")
+ event = capture.call_args.kwargs
+ assert event["event"] == "icp_reenrichment_sweep_completed"
+ assert event["properties"] == {"selected": 3, "attempted": 3, "matched": 1, "failed": 1}
+ scoped_capture.__exit__.assert_called_once()
+
+ def test_run_summary_skips_outside_a_cloud_region(self):
+ with (
+ patch(f"{_MODULE}.get_instance_region", return_value=None),
+ patch(f"{_MODULE}.ph_scoped_capture") as scoped_capture_factory,
+ ):
+ report_sweep_run_activity(SweepRunSummary(selected=0, attempted=0, matched=0, failed=0))
+
+ scoped_capture_factory.assert_not_called()
+
def test_skips_an_org_deleted_after_selection_without_writing_anything(self):
doomed = Organization.objects.create(name="doomed.example")
organization_id = str(doomed.id)
@@ -247,11 +315,11 @@ class TestReenrichOrganizationActivity(BaseTest):
pha_client.capture.assert_not_called()
assert not OrganizationEnrichment.objects.filter(organization_id=organization_id).exists()
- @override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=False)
def test_skips_an_in_flight_org_when_the_kill_switch_flips_off(self):
pha_client = MagicMock()
enrich = AsyncMock()
with (
+ override_instance_config("GROWTH_SIGNUP_ENRICHMENT_ENABLED", False),
patch(f"{_MODULE}.get_regional_ph_client", return_value=pha_client),
patch("products.growth.backend.enrichment.core.enrich_organization", enrich),
):
diff --git a/products/growth/backend/temporal/signup_enrichment/tests/test_schedule.py b/products/growth/backend/temporal/signup_enrichment/tests/test_schedule.py
new file mode 100644
index 000000000000..5a04415fbe51
--- /dev/null
+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_schedule.py
@@ -0,0 +1,29 @@
+from django.conf import settings
+
+from temporalio.client import ScheduleActionStartWorkflow, ScheduleOverlapPolicy
+
+from products.growth.backend.temporal.signup_enrichment.schedule import (
+ CRON,
+ SCHEDULE_ID,
+ build_icp_reenrichment_sweep_schedule,
+)
+
+
+def _action() -> ScheduleActionStartWorkflow:
+ action = build_icp_reenrichment_sweep_schedule().action
+ assert isinstance(action, ScheduleActionStartWorkflow)
+ return action
+
+
+class TestIcpReenrichmentSweepSchedule:
+ def test_targets_the_signup_enrichment_queue(self) -> None:
+ assert _action().task_queue == settings.SIGNUP_ENRICHMENT_TASK_QUEUE
+
+ def test_starts_the_sweep_workflow_under_a_stable_id(self) -> None:
+ assert _action().workflow == "icp-reenrichment-sweep"
+ assert _action().id == SCHEDULE_ID
+
+ def test_skips_an_overlapping_run_and_fires_daily(self) -> None:
+ schedule = build_icp_reenrichment_sweep_schedule()
+ assert schedule.policy.overlap == ScheduleOverlapPolicy.SKIP
+ assert schedule.spec.cron_expressions == [CRON]
diff --git a/products/growth/backend/temporal/signup_enrichment/tests/test_trigger.py b/products/growth/backend/temporal/signup_enrichment/tests/test_trigger.py
index cef8bb963cdf..c5a45bd056a8 100644
--- a/products/growth/backend/temporal/signup_enrichment/tests/test_trigger.py
+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_trigger.py
@@ -23,6 +23,16 @@ def _run_dispatch_pool_inline():
yield
[email protected](autouse=True)
+def _enrichment_enabled():
+ with patch("products.growth.backend.temporal.signup_enrichment.trigger.get_instance_setting", return_value=True):
+ yield
+
+
+def _kill_switch_off():
+ return patch("products.growth.backend.temporal.signup_enrichment.trigger.get_instance_setting", return_value=False)
+
+
def _dispatch_mocks(region="US"):
"""Patch out the transaction/Temporal/DB boundaries so on_commit fires inline."""
return (
@@ -37,7 +47,7 @@ def _dispatch_mocks(region="US"):
)
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")
+@override_settings(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:
@@ -46,7 +56,7 @@ def test_dispatches_for_work_email_in_us_and_records_work_email():
record_mock.assert_called_once_with(organization_id="org-1", work_email=True, signup_role=None)
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")
+@override_settings(HARMONIC_API_KEY="key")
def test_signup_role_is_recorded_alongside_work_email():
# The role answer feeds the V0.5 student disqualification; persisting it makes the DQ
# replayable by the score backfill instead of living only on the workflow inputs.
@@ -58,16 +68,31 @@ def test_signup_role_is_recorded_alongside_work_email():
record_mock.assert_called_once_with(organization_id="org-1", work_email=True, signup_role="Student")
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=False, HARMONIC_API_KEY="key")
+@override_settings(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:
+ with _kill_switch_off(), 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="")
+@override_settings(HARMONIC_API_KEY="key")
+def test_kill_switch_read_failure_never_reaches_signup():
+ on_commit, connect, run, region, record = _dispatch_mocks()
+ setting_read_fails = patch(
+ "products.growth.backend.temporal.signup_enrichment.trigger.get_instance_setting",
+ side_effect=RuntimeError("db down"),
+ )
+ with on_commit, connect as connect_mock, run, region, record as record_mock, setting_read_fails:
+ with patch("products.growth.backend.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_not_called()
+ record_mock.assert_not_called()
+ capture_mock.assert_called_once()
+
+
+@override_settings(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.
@@ -77,7 +102,7 @@ def test_missing_harmonic_key_still_dispatches():
connect_mock.assert_called_once()
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")
+@override_settings(HARMONIC_API_KEY="key")
def test_eu_region_dispatches_when_enabled():
on_commit, connect, run, region, record = _dispatch_mocks(region="EU")
with on_commit, connect as connect_mock, run, region, record:
@@ -85,7 +110,7 @@ def test_eu_region_dispatches_when_enabled():
connect_mock.assert_called_once()
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")
+@override_settings(HARMONIC_API_KEY="key")
def test_self_hosted_region_never_dispatches():
on_commit, connect, run, region, record = _dispatch_mocks(region="DEV")
with on_commit, connect as connect_mock, run, region, record:
@@ -93,15 +118,15 @@ def test_self_hosted_region_never_dispatches():
connect_mock.assert_not_called()
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=False, HARMONIC_API_KEY="key")
+@override_settings(HARMONIC_API_KEY="key")
def test_kill_switch_off_never_dispatches_in_eu_either():
on_commit, connect, run, region, record = _dispatch_mocks(region="EU")
- with on_commit, connect as connect_mock, run, region, record:
+ with _kill_switch_off(), 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")
+@override_settings(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:
@@ -111,7 +136,6 @@ def test_personal_email_records_work_email_false_without_provider_dispatch():
@override_settings(
- GROWTH_SIGNUP_ENRICHMENT_ENABLED=True,
HARMONIC_API_KEY="key",
SIGNUP_ENRICHMENT_TASK_QUEUE="signup-enrichment-task-queue",
)
@@ -123,7 +147,7 @@ def test_dispatch_uses_configured_signup_enrichment_task_queue():
assert kwargs["task_queue"] == "signup-enrichment-task-queue"
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")
+@override_settings(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:
@@ -132,7 +156,7 @@ def test_invalid_email_never_dispatches_or_writes():
record_mock.assert_not_called()
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")
+@override_settings(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:
@@ -141,7 +165,7 @@ def test_missing_distinct_id_records_work_email_but_never_dispatches():
record_mock.assert_called_once_with(organization_id="org-1", work_email=True, signup_role=None)
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")
+@override_settings(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:
@@ -152,7 +176,7 @@ def test_work_email_write_failure_does_not_block_dispatch():
capture_mock.assert_called_once()
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")
+@override_settings(HARMONIC_API_KEY="key")
@pytest.mark.parametrize(
"error,propagates",
[
@@ -179,7 +203,6 @@ def test_duplicate_workflow_is_logged_not_captured():
capture_mock.assert_not_called()
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True)
def test_dispatch_dropped_when_backlog_full():
import threading
@@ -192,7 +215,6 @@ def test_dispatch_dropped_when_backlog_full():
connect_mock.assert_not_called()
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True)
def test_dispatch_slot_released_after_run():
import threading
@@ -205,7 +227,7 @@ def test_dispatch_slot_released_after_run():
assert connect_mock.call_count == 2
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")
+@override_settings(HARMONIC_API_KEY="key")
def test_signup_geoip_country_is_threaded_into_workflow_inputs():
on_commit, connect, run, region, record = _dispatch_mocks()
with (
@@ -226,7 +248,7 @@ def test_signup_geoip_country_is_threaded_into_workflow_inputs():
assert inputs.geoip_country_code == "US"
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")
+@override_settings(HARMONIC_API_KEY="key")
def test_geoip_failure_degrades_to_no_country_and_still_dispatches():
on_commit, connect, run, region, record = _dispatch_mocks()
with (
diff --git a/products/growth/backend/temporal/signup_enrichment/trigger.py b/products/growth/backend/temporal/signup_enrichment/trigger.py
index 812cc8d97c9d..761d3e671aab 100644
--- a/products/growth/backend/temporal/signup_enrichment/trigger.py
+++ b/products/growth/backend/temporal/signup_enrichment/trigger.py
@@ -22,6 +22,7 @@ from temporalio.service import RPCError
from posthog.exceptions_capture import capture_exception
from posthog.geoip import get_geoip_properties
+from posthog.models.instance_setting import get_instance_setting
from posthog.temporal.common.client import sync_connect
from posthog.utils import GenericEmails, get_instance_region
@@ -63,10 +64,10 @@ def start_signup_enrichment_workflow(
# 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:
+ if not _enrichment_enabled():
return
# Cloud only — self-hosted has no Harmonic key or internal project to score against. The
- # flag above is the real per-region toggle; it stays unset in EU until enabled there.
+ # instance setting above is the real per-region toggle.
if get_instance_region() not in ("US", "EU"):
return
@@ -129,6 +130,16 @@ def _dispatch_and_release(inputs: SignupEnrichmentInputs) -> None:
_dispatch_slots.release()
+def _enrichment_enabled() -> bool:
+ # Reading the instance setting hits the database on a cache miss, and signup must never fail
+ # or stall on it. A failed read means enrichment does not run for that signup.
+ try:
+ return bool(get_instance_setting("GROWTH_SIGNUP_ENRICHMENT_ENABLED"))
+ except Exception as e:
+ capture_exception(e)
+ return False
+
+
def _geoip_country_code(ip_address: str | None) -> str | None:
# get_geoip_properties already swallows lookup failures, but nothing geoip-related may ever
# surface to signup — so guard the whole call anyway.
diff --git a/products/growth/backend/tests/test_enrichment_backfill_command.py b/products/growth/backend/tests/test_enrichment_backfill_command.py
index c56f7ad8bad7..5264cba58f38 100644
--- a/products/growth/backend/tests/test_enrichment_backfill_command.py
+++ b/products/growth/backend/tests/test_enrichment_backfill_command.py
@@ -4,8 +4,8 @@ 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.instance_setting import override_instance_config
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.user import User
@@ -21,8 +21,11 @@ def _window() -> dict[str, str]:
}
-@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True)
class TestBackfillSignupEnrichment(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.enterContext(override_instance_config("GROWTH_SIGNUP_ENRICHMENT_ENABLED", True))
+
def _org(
self,
*,
@@ -64,7 +67,7 @@ class TestBackfillSignupEnrichment(BaseTest):
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 override_instance_config("GROWTH_SIGNUP_ENRICHMENT_ENABLED", False):
with self.assertRaises(CommandError):
call_command("backfill_signup_enrichment", **_window())