: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): daily re-enrichment sweep for score-less ICP evaluations (#83947)
minekansu910c8c26057e
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 7ce1332b70a8..4414d9daa5f0 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -364,6 +364,9 @@ SESSION_RISK_ENABLED = get_from_env("SESSION_RISK_ENABLED", not TEST, type_cast=# 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)# 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 anotherdiff --git a/products/growth/backend/enrichment/writer.py b/products/growth/backend/enrichment/writer.pyindex 668ca09c65d6..7aab4d918fc7 100644--- a/products/growth/backend/enrichment/writer.py+++ b/products/growth/backend/enrichment/writer.py@@ -13,7 +13,8 @@ threshold-tuned consumers migrate) and the ICP fit score on its own `icp_fit_*`The two never share a key, so neither can misattribute the other's values."""-from typing import Any, Optional+from collections.abc import Callable+from typing import Any, Optional, Unionfrom django.db import transaction@@ -34,19 +35,28 @@ ORGANIZATION_GROUP_TYPE = "organization"_FIT_NUMERIC_KEYS = ["icp_fit_score", "icp_fit_components", "icp_fit_flags", "icp_fit_dq_reason"]-def _merge_into_record(organization_id: str, values: dict[str, Any], remove: Optional[list[str]] = None) -> None:+def merge_into_record(+ organization_id: str,+ values: Union[dict[str, Any], Callable[[dict[str, Any]], dict[str, Any]]],+ remove: Optional[list[str]] = None,+) -> None:"""Row-locked read/merge/save into OrganizationEnrichment.data.select_for_update serializes concurrent writers on the same org (the request-pathsignup write and the fire-and-forget provider write). Without the lock they read thesame snapshot and the later save clobbers the other's keys, dropping enrichment data.+ `values` may be a callable receiving the locked row's current data — needed for a+ merge that depends on the current value (e.g. incrementing a counter) without a+ separate unlocked read racing the lock.+`remove` deletes keys in the same locked write — used to strip stale fit keys when anew evaluation supersedes them."""with transaction.atomic():record, _ = OrganizationEnrichment.objects.select_for_update().get_or_create(organization_id=organization_id)- merged = {**record.data, **values}+ computed = values(record.data) if callable(values) else values+ merged = {**record.data, **computed}for key in remove or []:merged.pop(key, None)record.data = merged@@ -150,7 +160,7 @@ def write_organization_enrichment(if not values:return- _merge_into_record(organization_id, values, remove=remove)+ merge_into_record(organization_id, values, remove=remove)properties = fields.to_group_properties() if fields is not None else {}if icp_score is not None:@@ -210,4 +220,4 @@ def record_signup_work_email(*, organization_id: str, work_email: bool, signup_rvalues: dict[str, Any] = {"work_email": work_email}if signup_role and signup_role.strip():values["signup_role"] = signup_role.strip().lower()- _merge_into_record(organization_id, values)+ merge_into_record(organization_id, values)diff --git a/products/growth/backend/management/commands/init_icp_reenrichment_schedule.py b/products/growth/backend/management/commands/init_icp_reenrichment_schedule.pynew file mode 100644index 000000000000..a0d3c35fec1a--- /dev/null+++ b/products/growth/backend/management/commands/init_icp_reenrichment_schedule.py@@ -0,0 +1,58 @@+"""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__.pyindex fc620870e0b2..9231d1925d16 100644--- a/products/growth/backend/temporal/signup_enrichment/__init__.py+++ b/products/growth/backend/temporal/signup_enrichment/__init__.py@@ -1,8 +1,17 @@+from products.growth.backend.temporal.signup_enrichment.reenrichment import (+ IcpReenrichmentSweepWorkflow,+ reenrich_organization_activity,+ select_reenrichment_candidates_activity,+)from products.growth.backend.temporal.signup_enrichment.workflow import (SignupEnrichmentWorkflow,enrich_signup_organization_activity,)-WORKFLOWS = [SignupEnrichmentWorkflow]+WORKFLOWS = [SignupEnrichmentWorkflow, IcpReenrichmentSweepWorkflow]-ACTIVITIES = [enrich_signup_organization_activity]+ACTIVITIES = [+ enrich_signup_organization_activity,+ select_reenrichment_candidates_activity,+ reenrich_organization_activity,+]diff --git a/products/growth/backend/temporal/signup_enrichment/reenrichment.py b/products/growth/backend/temporal/signup_enrichment/reenrichment.pynew file mode 100644index 000000000000..5895985c3988--- /dev/null+++ b/products/growth/backend/temporal/signup_enrichment/reenrichment.py@@ -0,0 +1,314 @@+"""Scheduled re-enrichment sweep for orgs whose V0.5 evaluation produced no score.++~25% of matched signups are empty-shell Harmonic profiles at signup (insufficient_data) and+a further ~5% aren't matched at all (not_found) — mostly brand-new companies that accrete+enrichment data over weeks, plus late Harmonic indexing (the enrich mutation seeds async+enrichment). The +4h recheck is too early for either. This sweep re-runs the standard+enrichment (fresh fetch, archive, transform, score) for those orgs on a 30–90-day window:++- **30 days minimum** since the org's last sweep *attempt* (stamped on `OrganizationEnrichment.data`+ before the org reaches the provider, so a raised Harmonic error still counts): an org is+ retried at most every 30 days, and an unrelated fetch row from another command can't move+ this clock.+- **90 days maximum** since the org's first fetch: retries self-terminate (~2 per org) — an+ org still empty after two spaced retries stays at its honest status.++Runs as a Temporal Schedule (see the init_icp_reenrichment_schedule command) 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+person-mirror policy; the write-once at-signup snapshot and the launch signal are untouched+by construction (both live only in the signup activity). Emits `icp_reenrichment_completed`+per org so the sweep has its own health signal.+"""++import json+import typing+import datetime as dt+import dataclasses++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.temporal.common.base import PostHogWorkflow+from posthog.temporal.common.logger import get_logger+from posthog.temporal.common.utils import close_db_connections++from products.growth.backend.temporal.signup_enrichment.workflow import ENRICH_ACTIVITY_TIMEOUT, MAX_ENRICH_ATTEMPTS++LOGGER = get_logger(__name__)++REENRICHMENT_EVENT = "icp_reenrichment_completed"++# Statuses the sweep retries. not_found is included on purpose: it doubles as recovery for+# late Harmonic indexing and for the match-bug population (pipeline-missed orgs).+SWEEPABLE_STATUSES = ("insufficient_data", "not_found")++MIN_DAYS_SINCE_LAST_ATTEMPT = 30+MAX_DAYS_SINCE_FIRST_FETCH = 90++# Stamped on every sweep attempt (see reenrich_organization_activity), not on a successful+# write — an archived fetch from an unrelated command (e.g. backfill_harmonic_ownership) or+# a raised Harmonic error must not silently move or freeze this org's retry clock.+ICP_REENRICHMENT_LAST_ATTEMPTED_AT_KEY = "icp_reenrichment_last_attempted_at"+ICP_REENRICHMENT_ATTEMPT_COUNT_KEY = "icp_reenrichment_attempt_count"++# Selection is a handful of indexed queries; keep it snappy so a hung DB can't stall the+# scheduled run into its next occurrence.+SELECT_ACTIVITY_TIMEOUT = dt.timedelta(minutes=5)++# Same signup-membership window as backfill_signup_enrichment: the signup creator's+# membership lands within seconds of the org row, so an older earliest membership means the+# signup user left and nobody can stand in for the signup identity.+_SIGNUP_MEMBERSHIP_WINDOW = dt.timedelta(minutes=5)++# Orgs that fail identity filtering never get a new fetch row, so they'd otherwise re-occupy+# a cap slot on every run. Over-fetch the window so the cap can still be filled from what+# survives filtering, without making the query unbounded.+_SELECTION_OVERFETCH_MULTIPLIER = 3++[email protected](frozen=True)+class IcpReenrichmentSweepInputs:+ # Overrides the GROWTH_ICP_REENRICH_DAILY_CAP setting when set (manual triggers).+ cap: typing.Optional[int] = None++[email protected](frozen=True)+class ReenrichOrgInputs:+ organization_id: str+ distinct_id: str+ domain: str+ role_at_organization: typing.Optional[str] = None+++@close_db_connections+async def select_reenrichment_candidates_activity(inputs: IcpReenrichmentSweepInputs) -> list[dict[str, typing.Any]]:+ """Pick the orgs due a re-enrichment attempt, oldest-attempted-first, up to the daily cap.++ 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 Min, Q # noqa: PLC0415++ from asgiref.sync import sync_to_async # noqa: PLC0415++ from posthog.models.organization import OrganizationMembership # noqa: PLC0415+ from posthog.utils import GenericEmails, get_instance_region # noqa: PLC0415++ from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch # noqa: PLC0415+ from products.growth.backend.temporal.signup_enrichment.trigger import domain_from_email # noqa: PLC0415++ logger = LOGGER.bind()++ if not settings.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+ generic_emails = GenericEmails()++ def _select() -> list[dict[str, typing.Any]]:+ now = dt.datetime.now(dt.UTC)+ attempt_cutoff = (now - dt.timedelta(days=MIN_DAYS_SINCE_LAST_ATTEMPT)).isoformat()+ first_fetch_cutoff = now - dt.timedelta(days=MAX_DAYS_SINCE_FIRST_FETCH)++ # JSONField key lookups return SQL NULL for a missing key, so a bare __lte would+ # silently drop never-attempted orgs instead of selecting them (same gotcha as+ # backfill_harmonic_ownership's has_key dance) — spell out "no key yet" explicitly.+ never_attempted = ~Q(data__has_key=ICP_REENRICHMENT_LAST_ATTEMPTED_AT_KEY)+ # nosemgrep: orm-field-injection -- ICP_REENRICHMENT_LAST_ATTEMPTED_AT_KEY is a module constant, not user input+ due_for_retry = Q(data__has_key=ICP_REENRICHMENT_LAST_ATTEMPTED_AT_KEY) & Q(+ **{f"data__{ICP_REENRICHMENT_LAST_ATTEMPTED_AT_KEY}__lte": attempt_cutoff}+ )+ attempt_eligible = {+ str(record.organization_id): record.data.get(ICP_REENRICHMENT_LAST_ATTEMPTED_AT_KEY)+ for record in OrganizationEnrichment.objects.filter(data__icp_fit_status__in=list(SWEEPABLE_STATUSES))+ .filter(never_attempted | due_for_retry)+ .only("organization_id", "data")+ }++ first_fetches = (+ OrganizationEnrichmentFetch.objects.filter(organization_id__in=attempt_eligible.keys())+ .values("organization_id")+ .annotate(first_fetch=Min("fetched_at"))+ .filter(first_fetch__gt=first_fetch_cutoff)+ )++ # Oldest-attempted-first, with never-attempted (None) sorting ahead of any+ # timestamp — an org the sweep hasn't touched yet is due before one it retried+ # last month.+ ordered_org_ids = sorted(+ (str(row["organization_id"]) for row in first_fetches),+ key=lambda organization_id: attempt_eligible[organization_id] or "",+ )[: cap * _SELECTION_OVERFETCH_MULTIPLIER]++ roles = {+ str(record.organization_id): record.data.get("signup_role")+ for record in OrganizationEnrichment.objects.filter(organization_id__in=ordered_org_ids).only(+ "organization_id", "data"+ )+ }++ candidates: list[dict[str, typing.Any]] = []+ for organization_id in ordered_org_ids:+ membership = (+ OrganizationMembership.objects.filter(organization_id=organization_id)+ .select_related("user", "organization")+ .order_by("joined_at")+ .first()+ )+ if membership is None or membership.user is None:+ continue+ if membership.joined_at - membership.organization.created_at > _SIGNUP_MEMBERSHIP_WINDOW:+ continue # signup user left; nobody can stand in for the signup identity+ user = membership.user+ domain = domain_from_email(user.email) if user.email else None+ if not user.distinct_id or not domain or generic_emails.is_generic(user.email):+ continue+ candidates.append(+ {+ "organization_id": organization_id,+ "distinct_id": user.distinct_id,+ "domain": domain,+ "role_at_organization": roles.get(organization_id),+ }+ )+ if len(candidates) >= cap:+ break+ return candidates++ candidates = await sync_to_async(_select)()+ logger.info("icp_reenrichment_selected", count=len(candidates), cap=cap)+ return candidates+++@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 asgiref.sync import sync_to_async # 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++ 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:+ logger.info("icp_reenrichment_skipped_kill_switch")+ return {"matched": False, "skipped": "kill_switch"}++ # Selection can be hours stale by the tail of a run, and the enrichment FKs skip DB+ # constraints — without this recheck, an org deleted mid-sweep would get its rows and+ # group properties recreated right after the deletion cascade removed them.+ if not await sync_to_async(Organization.objects.filter(id=inputs.organization_id).exists)():+ logger.info("icp_reenrichment_skipped_org_deleted")+ return {"matched": False, "skipped": "organization_deleted"}++ # 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()++ def _stamp_attempt(current: dict[str, typing.Any]) -> dict[str, typing.Any]:+ return {+ ICP_REENRICHMENT_LAST_ATTEMPTED_AT_KEY: attempted_at,+ ICP_REENRICHMENT_ATTEMPT_COUNT_KEY: current.get(ICP_REENRICHMENT_ATTEMPT_COUNT_KEY, 0) + 1,+ }++ await sync_to_async(merge_into_record)(inputs.organization_id, _stamp_attempt)++ pha_client = get_regional_ph_client()+ if pha_client is None:+ logger.error("icp_reenrichment_no_regional_client")+ return {"matched": False}++ try:+ outcome = await enrich_organization(+ organization_id=inputs.organization_id,+ domain=inputs.domain,+ provider=HarmonicEnrichmentProvider(),+ pha_client=pha_client,+ is_recheck=True,+ role_at_organization=inputs.role_at_organization,+ distinct_id=inputs.distinct_id,+ )+ matched = outcome.provider_fields is not None+ status = outcome.fit.status if outcome.fit else None+ pha_client.capture(+ distinct_id=inputs.distinct_id,+ event=REENRICHMENT_EVENT,+ properties={+ "organization_id": inputs.organization_id,+ "matched": matched,+ "icp_fit_status": status,+ },+ groups={"organization": inputs.organization_id},+ )+ logger.info("icp_reenrichment_completed", matched=matched, icp_fit_status=status)+ return {"matched": matched, "icp_fit_status": status}+ except Exception as e:+ capture_exception(e)+ raise+ finally:+ pha_client.shutdown()++[email protected](name="icp-reenrichment-sweep")+class IcpReenrichmentSweepWorkflow(PostHogWorkflow):+ """Daily sweep: select due orgs, then re-enrich them one at a time.++ Sequential on purpose — the per-call rate stays trivially inside Harmonic's limit, and+ at the default cap (500) a full run is well under two hours, far inside a daily+ schedule. A failed org (after the per-org retries) is logged and skipped: the window+ query naturally re-offers it next run if it stays eligible.+ """++ @staticmethod+ def parse_inputs(inputs: list[str]) -> IcpReenrichmentSweepInputs:+ if not inputs:+ return IcpReenrichmentSweepInputs()+ return IcpReenrichmentSweepInputs(**json.loads(inputs[0]))++ @workflow.run+ async def run(self, inputs: IcpReenrichmentSweepInputs) -> dict[str, typing.Any]:+ candidates = await workflow.execute_activity(+ select_reenrichment_candidates_activity,+ inputs,+ start_to_close_timeout=SELECT_ACTIVITY_TIMEOUT,+ retry_policy=RetryPolicy(maximum_attempts=2),+ )++ attempted = matched = failed = 0+ for candidate in candidates:+ attempted += 1+ try:+ result = await workflow.execute_activity(+ reenrich_organization_activity,+ ReenrichOrgInputs(**candidate),+ start_to_close_timeout=ENRICH_ACTIVITY_TIMEOUT,+ retry_policy=RetryPolicy(+ maximum_attempts=MAX_ENRICH_ATTEMPTS, initial_interval=dt.timedelta(seconds=5)+ ),+ )+ if result.get("matched"):+ matched += 1+ except Exception:+ # 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}diff --git a/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py b/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.pynew file mode 100644index 000000000000..54cc3cbb4bbb--- /dev/null+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py@@ -0,0 +1,275 @@+import datetime as dt++from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, MagicMock, patch++from django.test import override_settings++from asgiref.sync import async_to_sync++from posthog.models.organization import Organization, OrganizationMembership+from posthog.models.user import User++from products.growth.backend.enrichment.core import EnrichmentOutcome+from products.growth.backend.enrichment.fields import EnrichmentFields+from products.growth.backend.enrichment.fit_score import IcpFitResult+from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch+from products.growth.backend.temporal.signup_enrichment.reenrichment import (+ ICP_REENRICHMENT_ATTEMPT_COUNT_KEY,+ ICP_REENRICHMENT_LAST_ATTEMPTED_AT_KEY,+ IcpReenrichmentSweepInputs,+ ReenrichOrgInputs,+ reenrich_organization_activity,+ select_reenrichment_candidates_activity,+)++_MODULE = "products.growth.backend.temporal.signup_enrichment.reenrichment"+++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)+class TestReenrichmentSelection(BaseTest):+ 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")+ OrganizationMembership.objects.create(organization=organization, user=user)+ return organization++ def _prime(+ self,+ organization: Organization,+ *,+ status: str = "insufficient_data",+ last_attempted_days_ago: int | None = 31,+ first_fetch_days_ago: int = 40,+ signup_role: str | None = None,+ ) -> None:+ data: dict = {"icp_fit_status": status, "work_email": True}+ if signup_role:+ data["signup_role"] = signup_role+ if last_attempted_days_ago is not None:+ data[ICP_REENRICHMENT_LAST_ATTEMPTED_AT_KEY] = (+ _now() - dt.timedelta(days=last_attempted_days_ago)+ ).isoformat()+ OrganizationEnrichment.objects.create(organization=organization, data=data)+ first = OrganizationEnrichmentFetch.objects.create(+ organization=organization, provider="harmonic", payload={"companyFound": False}+ )+ OrganizationEnrichmentFetch.objects.filter(id=first.id).update(+ fetched_at=_now() - dt.timedelta(days=first_fetch_days_ago)+ )++ def _select(self, cap: int | None = None):+ with patch(f"{_MODULE}.LOGGER"):+ return async_to_sync(select_reenrichment_candidates_activity)(IcpReenrichmentSweepInputs(cap=cap))++ def test_selects_due_orgs_with_identity_and_role(self):+ organization = self._org_with_member("[email protected]")+ self._prime(organization, last_attempted_days_ago=31, first_fetch_days_ago=40, signup_role="engineering")++ candidates = self._select()++ assert len(candidates) == 1+ candidate = candidates[0]+ assert candidate["organization_id"] == str(organization.id)+ assert candidate["domain"] == "due.example"+ assert candidate["role_at_organization"] == "engineering"+ assert candidate["distinct_id"]++ def test_window_and_status_exclusions(self):+ too_recent = self._org_with_member("[email protected]")+ self._prime(too_recent, last_attempted_days_ago=10, first_fetch_days_ago=40)++ aged_out = self._org_with_member("[email protected]")+ self._prime(aged_out, last_attempted_days_ago=35, first_fetch_days_ago=100)++ already_scored = self._org_with_member("[email protected]")+ self._prime(already_scored, status="scored", last_attempted_days_ago=31, first_fetch_days_ago=40)++ due = self._org_with_member("[email protected]")+ self._prime(due, last_attempted_days_ago=31, first_fetch_days_ago=40)++ candidates = self._select()++ assert [c["organization_id"] for c in candidates] == [str(due.id)]++ def test_cap_takes_the_least_recently_attempted_org_first(self):+ newer = self._org_with_member("[email protected]")+ self._prime(newer, last_attempted_days_ago=31, first_fetch_days_ago=45)+ older = self._org_with_member("[email protected]")+ self._prime(older, last_attempted_days_ago=60, first_fetch_days_ago=70)++ candidates = self._select(cap=1)++ assert [c["organization_id"] for c in candidates] == [str(older.id)]++ def test_skips_org_whose_signup_user_left(self):+ organization = Organization.objects.create(name="left.example")+ user = User.objects.create_user(email="[email protected]", password=None, first_name="late")+ membership = OrganizationMembership.objects.create(organization=organization, user=user)+ # The earliest remaining membership joined long after signup: nobody can stand in+ # for the signup identity.+ OrganizationMembership.objects.filter(id=membership.id).update(+ joined_at=organization.created_at + dt.timedelta(hours=6)+ )+ self._prime(organization)++ 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() == []++ def test_selection_backfills_the_cap_when_the_oldest_rows_fail_identity_filtering(self):+ for i in range(3):+ unusable = self._org_with_member(f"person{i}@gmail.com")+ self._prime(unusable, last_attempted_days_ago=60 + i, first_fetch_days_ago=70 + i)++ usable_orgs = [self._org_with_member(f"founder{i}@usable.example") for i in range(2)]+ for usable in usable_orgs:+ self._prime(usable, last_attempted_days_ago=31, first_fetch_days_ago=40)++ candidates = self._select(cap=2)++ assert {c["organization_id"] for c in candidates} == {str(o.id) for o in usable_orgs}++ def test_an_unrelated_fetch_row_does_not_change_eligibility(self):+ organization = self._org_with_member("[email protected]")+ self._prime(organization, last_attempted_days_ago=31, first_fetch_days_ago=40)+ assert len(self._select()) == 1++ # Simulates backfill_harmonic_ownership: it archives a fresh fetch for every org it+ # touches without ever re-scoring them. Eligibility is keyed off the sweep's own+ # attempt stamp now, so an unrelated archive must not move it.+ OrganizationEnrichmentFetch.objects.create(+ organization=organization, provider="harmonic", payload={"companyFound": False}, is_recheck=True+ )+ assert len(self._select()) == 1++ def test_selects_an_org_never_attempted_by_the_sweep(self):+ organization = self._org_with_member("[email protected]")+ self._prime(organization, last_attempted_days_ago=None, first_fetch_days_ago=40)++ candidates = self._select()++ assert [c["organization_id"] for c in candidates] == [str(organization.id)]++ def test_an_attempt_that_raises_is_not_selected_again_the_same_day(self):+ organization = self._org_with_member("[email protected]")+ self._prime(organization, last_attempted_days_ago=None, first_fetch_days_ago=1)+ assert len(self._select()) == 1++ pha_client = MagicMock()+ enrich = AsyncMock(side_effect=RuntimeError("harmonic blew up"))+ with (+ patch(f"{_MODULE}.get_regional_ph_client", return_value=pha_client),+ patch("products.growth.backend.enrichment.core.enrich_organization", enrich),+ ):+ with self.assertRaises(RuntimeError):+ async_to_sync(reenrich_organization_activity)(+ ReenrichOrgInputs(+ organization_id=str(organization.id), distinct_id="signer", domain="retry.example"+ )+ )++ assert self._select() == []+++@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True)+class TestReenrichOrganizationActivity(BaseTest):+ def _run(self, outcome: EnrichmentOutcome) -> tuple[dict, MagicMock, AsyncMock]:+ pha_client = MagicMock()+ enrich = AsyncMock(return_value=outcome)+ with (+ patch(f"{_MODULE}.get_regional_ph_client", return_value=pha_client),+ patch("products.growth.backend.enrichment.core.enrich_organization", enrich),+ ):+ result = async_to_sync(reenrich_organization_activity)(+ ReenrichOrgInputs(+ organization_id=str(self.organization.id),+ distinct_id="signer",+ domain="stripe.com",+ role_at_organization="engineering",+ )+ )+ return result, pha_client, enrich++ def test_reenriches_as_a_recheck_and_emits_its_own_event(self):+ outcome = EnrichmentOutcome(+ provider_fields=EnrichmentFields(company_type="STARTUP"),+ fit=IcpFitResult(status="scored", score=48),+ )+ result, pha_client, enrich = self._run(outcome)++ assert result == {"matched": True, "icp_fit_status": "scored"}+ 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"+ event = pha_client.capture.call_args+ assert event.kwargs["event"] == "icp_reenrichment_completed"+ assert event.kwargs["properties"]["icp_fit_status"] == "scored"+ assert event.kwargs["properties"]["matched"] is True+ pha_client.shutdown.assert_called_once()++ def test_still_unmatched_reports_honestly(self):+ 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 pha_client.capture.call_args.kwargs["properties"]["icp_fit_status"] == "not_found"++ def test_skips_an_org_deleted_after_selection_without_writing_anything(self):+ doomed = Organization.objects.create(name="doomed.example")+ organization_id = str(doomed.id)+ doomed.delete()++ pha_client = MagicMock()+ enrich = AsyncMock()+ with (+ patch(f"{_MODULE}.get_regional_ph_client", return_value=pha_client),+ patch("products.growth.backend.enrichment.core.enrich_organization", enrich),+ ):+ result = async_to_sync(reenrich_organization_activity)(+ ReenrichOrgInputs(organization_id=organization_id, distinct_id="signer", domain="stripe.com")+ )++ assert result == {"matched": False, "skipped": "organization_deleted"}+ enrich.assert_not_awaited()+ 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 (+ patch(f"{_MODULE}.get_regional_ph_client", return_value=pha_client),+ patch("products.growth.backend.enrichment.core.enrich_organization", enrich),+ ):+ result = async_to_sync(reenrich_organization_activity)(+ ReenrichOrgInputs(organization_id=str(self.organization.id), distinct_id="signer", domain="stripe.com")+ )++ assert result == {"matched": False, "skipped": "kill_switch"}+ enrich.assert_not_awaited()+ pha_client.capture.assert_not_called()+ assert not OrganizationEnrichment.objects.filter(organization=self.organization).exists()++ def test_attempt_count_increments_across_attempts(self):+ outcome = EnrichmentOutcome(provider_fields=None, fit=IcpFitResult(status="not_found"))++ self._run(outcome)+ record = OrganizationEnrichment.objects.get(organization=self.organization)+ assert record.data[ICP_REENRICHMENT_ATTEMPT_COUNT_KEY] == 1+ first_attempt = record.data[ICP_REENRICHMENT_LAST_ATTEMPTED_AT_KEY]++ self._run(outcome)+ record.refresh_from_db()+ assert record.data[ICP_REENRICHMENT_ATTEMPT_COUNT_KEY] == 2+ assert record.data[ICP_REENRICHMENT_LAST_ATTEMPTED_AT_KEY] >= first_attempt