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.

refactor(growth): carry the enrichment phase in a context object and share the gates (#98497)

Matt Brookerf784588a82e7
diff --git a/products/growth/backend/enrichment/context.py b/products/growth/backend/enrichment/context.py
new file mode 100644
index 000000000000..8b06d3bc2149
--- /dev/null
+++ b/products/growth/backend/enrichment/context.py
@@ -0,0 +1,25 @@
+"""The identity and cadence of one enrichment run."""
+
+from enum import StrEnum
+
+from posthog.dataclasses import frozen
+
+
+class EnrichmentPhase(StrEnum):
+ AT_SIGNUP = "at_signup"
+ RECHECK = "recheck"
+ SWEEP = "sweep"
+
+
+@frozen
+class EnrichmentContext:
+ organization_id: str
+ domain: str
+ phase: EnrichmentPhase
+ distinct_id: str | None = None
+ role_at_organization: str | None = None
+ geoip_country_code: str | None = None
+
+ @property
+ def is_recheck(self) -> bool:
+ return self.phase is not EnrichmentPhase.AT_SIGNUP
diff --git a/products/growth/backend/enrichment/core.py b/products/growth/backend/enrichment/core.py
index 6032a2304589..b301848263cd 100644
--- a/products/growth/backend/enrichment/core.py
+++ b/products/growth/backend/enrichment/core.py
@@ -27,11 +27,12 @@ from products.growth.backend.enrichment.bridge import (
read_organization_bridge_inputs,
)
from products.growth.backend.enrichment.clearbit import ClearbitInputs, clearbit_inputs_from_person_properties
+from products.growth.backend.enrichment.context import EnrichmentContext
from products.growth.backend.enrichment.fields import EnrichmentFields
from products.growth.backend.enrichment.fit_score import IcpFitResult, score_company
from products.growth.backend.enrichment.harmonic_adapter import normalize_graphql_company
from products.growth.backend.enrichment.icp_lists import load_active_lists
-from products.growth.backend.enrichment.providers import EnrichmentProvider
+from products.growth.backend.enrichment.providers import EnrichmentProvider, ProviderLookup
from products.growth.backend.enrichment.score import IcpScoreInputs, compute_icp_score
from products.growth.backend.enrichment.writer import archive_provider_fetch, write_organization_enrichment
from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch
@@ -132,21 +133,50 @@ def _latest_archived_urn(organization_id: str) -> Optional[str]:
return urn if isinstance(urn, str) else None
-async def _recheck_enrichment_status(*, organization_id: str, provider: EnrichmentProvider) -> Optional[str]:
- """Poll the provider for the status of the org's most recently archived tracking URN.
-
- Never raises: a status-check failure must not block the recheck's own lookup below.
- """
- urn = await sync_to_async(_latest_archived_urn)(organization_id)
+async def _poll_prior_status(ctx: EnrichmentContext, provider: EnrichmentProvider) -> Optional[str]:
+ """Never raises: a status-check failure must not block the recheck's own lookup below."""
+ if not ctx.is_recheck:
+ return None
+ urn = await sync_to_async(_latest_archived_urn)(ctx.organization_id)
if not urn:
return None
try:
return await provider.enrichment_status_for(urn)
except Exception as e:
- capture_exception(e, {"organization_id": organization_id, "enrichment_urn": urn})
+ capture_exception(e, {"organization_id": ctx.organization_id, "enrichment_urn": urn})
return None
+async def _archive_lookup(
+ ctx: EnrichmentContext, provider: EnrichmentProvider, lookup: ProviderLookup, enrichment_status: Optional[str]
+) -> None:
+ base_payload = lookup.raw_payload if lookup.raw_payload is not None else _MISS_PAYLOAD
+ archived_payload = {**base_payload, "enrichmentUrn": lookup.enrichment_urn}
+ if ctx.is_recheck:
+ archived_payload["enrichmentStatus"] = enrichment_status
+ await sync_to_async(archive_provider_fetch)(
+ organization_id=ctx.organization_id,
+ provider=provider.name,
+ payload=archived_payload,
+ is_recheck=ctx.is_recheck,
+ )
+
+
+async def _resolve_fields(ctx: EnrichmentContext, lookup: ProviderLookup) -> Optional[EnrichmentFields]:
+ fields = lookup.fields
+ if fields is None:
+ fields = await sync_to_async(_reconstruct_fields_from_record)(ctx.organization_id)
+
+ if fields is not None and fields.country is None:
+ # A re-score with no new provider country would otherwise take the non-scored-country
+ # penalty the signup score avoided. replace() keeps provider_fields verbatim for the snapshot.
+ fallback_country = ctx.geoip_country_code or await sync_to_async(_stored_country)(ctx.organization_id)
+ if fallback_country:
+ fields = dataclasses.replace(fields, country=fallback_country)
+
+ return fields
+
+
def _fetch_recheck_person_inputs(distinct_id: str) -> tuple[bool, ClearbitInputs]:
"""Fetch the signer's person once for the two recheck-only reads: mirror eligibility and Clearbit's fallback inputs.
@@ -181,13 +211,7 @@ def _company_type_from_ownership(ownership_status: Optional[str]) -> Optional[st
def _score_and_mirror(
- *,
- organization_id: str,
- bridge_inputs: Optional[OrganizationBridgeInputs],
- fields: EnrichmentFields,
- role: Optional[str],
- is_recheck: bool,
- distinct_id: Optional[str],
+ ctx: EnrichmentContext, *, bridge_inputs: Optional[OrganizationBridgeInputs], fields: EnrichmentFields
) -> tuple[Optional[int], Optional[str]]:
"""Score one org under the legacy clay formula; on the recheck, also mirror onto the person.
@@ -201,7 +225,7 @@ def _score_and_mirror(
"""
try:
if bridge_inputs is None:
- if _persisted_score_exists(organization_id):
+ if _persisted_score_exists(ctx.organization_id):
return None, None
clay = ClayBridgeInputs()
else:
@@ -209,8 +233,8 @@ def _score_and_mirror(
mirror_ok = False
clearbit = ClearbitInputs()
- if is_recheck and distinct_id:
- mirror_ok, clearbit = _fetch_recheck_person_inputs(distinct_id)
+ if ctx.is_recheck and ctx.distinct_id:
+ mirror_ok, clearbit = _fetch_recheck_person_inputs(ctx.distinct_id)
icp_score = compute_icp_score(
IcpScoreInputs(
@@ -218,7 +242,7 @@ def _score_and_mirror(
# A Clay-written 0 is not information the formula can use either (_in_band is false
# at 0 same as at None), so it must not shadow a real Clearbit band.
est_revenue=clay.est_revenue or clearbit.est_revenue,
- role=role,
+ role=ctx.role_at_organization,
# Clay never projects its GitHub column into PostHog, so this input is always
# absent here — product-role orgs score 3, not 6, until v-next substitutes the
# signup's own GitHub auth. Kept on IcpScoreInputs for formula fidelity.
@@ -229,18 +253,23 @@ def _score_and_mirror(
)
)
- mirror_distinct_id = distinct_id if mirror_ok else None
+ mirror_distinct_id = ctx.distinct_id if mirror_ok else None
return icp_score, mirror_distinct_id
except Exception as e:
- capture_exception(e, {"organization_id": organization_id})
+ capture_exception(e, {"organization_id": ctx.organization_id})
return None, None
-def _read_bridge_inputs(*, organization_id: str) -> Optional[OrganizationBridgeInputs]:
+def _read_bridge_inputs(
+ ctx: EnrichmentContext, fields: Optional[EnrichmentFields]
+) -> Optional[OrganizationBridgeInputs]:
+ """Empty means the run never asked; None means the read failed, which the scorers treat differently."""
+ if fields is None and not ctx.is_recheck:
+ return OrganizationBridgeInputs()
try:
- return read_organization_bridge_inputs(organization_id=organization_id)
+ return read_organization_bridge_inputs(organization_id=ctx.organization_id)
except Exception as e:
- capture_exception(e, {"organization_id": organization_id})
+ capture_exception(e, {"organization_id": ctx.organization_id})
return None
@@ -251,14 +280,10 @@ def _persisted_wizard_ai_sdk(*, organization_id: str) -> bool:
def _score_fit(
+ ctx: EnrichmentContext,
*,
- organization_id: str,
bridge_inputs: Optional[OrganizationBridgeInputs],
raw_payload: Optional[dict[str, Any]],
- role: Optional[str],
- domain: str,
- distinct_id: Optional[str],
- is_recheck: bool,
) -> tuple[Optional[IcpFitResult], Optional[str]]:
"""Evaluate one org under the ICP fit score.
@@ -278,9 +303,9 @@ def _score_fit(
"""
try:
wizard_ai_sdk = False
- if is_recheck:
+ if ctx.is_recheck:
if bridge_inputs is None:
- if not _persisted_wizard_ai_sdk(organization_id=organization_id):
+ if not _persisted_wizard_ai_sdk(organization_id=ctx.organization_id):
return None, None
wizard_ai_sdk = True
else:
@@ -292,116 +317,52 @@ def _score_fit(
payload = normalize_graphql_company(raw_payload)
if payload is None:
- payload = normalize_graphql_company(latest_matched_payload(organization_id))
+ payload = normalize_graphql_company(latest_matched_payload(ctx.organization_id))
- result = score_company(payload, lists=lists, role=role, domain=domain, wizard_ai_sdk=wizard_ai_sdk)
+ result = score_company(
+ payload, lists=lists, role=ctx.role_at_organization, domain=ctx.domain, wizard_ai_sdk=wizard_ai_sdk
+ )
except Exception as e:
- capture_exception(e, {"organization_id": organization_id})
+ capture_exception(e, {"organization_id": ctx.organization_id})
return None, None
- return result, distinct_id
+ return result, ctx.distinct_id
async def enrich_organization(
- *,
- organization_id: str,
- domain: str,
- provider: EnrichmentProvider,
- pha_client: Client,
- is_recheck: bool = False,
- role_at_organization: Optional[str] = None,
- geoip_country_code: Optional[str] = None,
- distinct_id: Optional[str] = None,
+ ctx: EnrichmentContext, *, provider: EnrichmentProvider, pha_client: Client
) -> EnrichmentOutcome:
- """Look up enrichment for a domain, archive the raw response, and persist the live stores.
-
- Every fetch is archived verbatim — including a not-found — before the live-store write.
- The Postgres writes run via sync_to_async to bridge the async provider.
-
- On a recheck, the most recently archived non-null enrichmentUrn (if any) is polled for
- its status before this attempt's own lookup runs, and the result rides along on this
- fetch's archived payload as enrichmentStatus. The archive then shows what happened to
- the tracking id a prior attempt saved, alongside the new observation. A first attempt
- has no prior URN to poll, so it carries no enrichmentStatus key at all.
-
- A matched org is scored twice: under the legacy clay formula (see `_score_and_mirror`
- for its scoring and person-mirror policy) and under the ICP fit score (`_score_fit`),
- which also evaluates misses — from the last matched archived payload when one exists,
- or to an honest not_found status otherwise, which is what the re-enrichment sweep
- selects on. Either score failing degrades to writing what the rest produced, rather
- than a silently-wrong value; the delayed recheck gets a second chance, and the fetch
- archive backstops a later batch recompute.
-
- On a miss, a prior `OrganizationEnrichment` record (if any) is reconstructed into fields
- and clay-scored anyway — first attempt or recheck alike — so an org can't end up
- permanently score-less because of one flaky lookup. provider_fields on the returned
- outcome keeps tracking the provider lookup itself (None on a miss, even when the
- fallback wrote a score), since that is what the workflow's matched/upgraded reporting
- reads.
- """
- enrichment_status: Optional[str] = None
- if is_recheck:
- enrichment_status = await _recheck_enrichment_status(organization_id=organization_id, provider=provider)
+ """Archiving precedes the live-store write, so a fetch survives a later step failing.
- lookup = await provider.enrich_by_domain(domain)
-
- base_payload = lookup.raw_payload if lookup.raw_payload is not None else _MISS_PAYLOAD
- archived_payload = {**base_payload, "enrichmentUrn": lookup.enrichment_urn}
- if is_recheck:
- archived_payload["enrichmentStatus"] = enrichment_status
- await sync_to_async(archive_provider_fetch)(
- organization_id=organization_id,
- provider=provider.name,
- payload=archived_payload,
- is_recheck=is_recheck,
- )
-
- fields = lookup.fields
- if fields is None:
- fields = await sync_to_async(_reconstruct_fields_from_record)(organization_id)
+ Either scorer failing degrades to writing what the rest produced rather than a
+ silently-wrong value. The returned provider_fields tracks the lookup itself, staying
+ None on a miss even when an archived payload still scored, because that is what the
+ workflow's matched and upgraded reporting reads.
+ """
+ enrichment_status = await _poll_prior_status(ctx, provider)
- if fields is not None and fields.country is None:
- # The incumbent icp_country was a merge — provider country first, signup GeoIP as
- # fallback — so the score and all three stores see the merged value here. replace()
- # keeps the returned provider_fields verbatim for the at-signup snapshot.
- # Callers with no GeoIP to offer (the re-enrichment sweep) fall back to the country
- # already on the record. Without it a re-score that saw no new provider country takes
- # the non-scored-country penalty the signup score had avoided.
- fallback_country = geoip_country_code or await sync_to_async(_stored_country)(organization_id)
- if fallback_country:
- fields = dataclasses.replace(fields, country=fallback_country)
+ lookup = await provider.enrich_by_domain(ctx.domain)
+ await _archive_lookup(ctx, provider, lookup, enrichment_status)
- bridge_inputs: Optional[OrganizationBridgeInputs] = OrganizationBridgeInputs()
- if fields is not None or is_recheck:
- bridge_inputs = await sync_to_async(_read_bridge_inputs)(organization_id=organization_id)
+ fields = await _resolve_fields(ctx, lookup)
+ bridge_inputs = await sync_to_async(_read_bridge_inputs)(ctx, fields)
icp_score: Optional[int] = None
mirror_distinct_id: Optional[str] = None
if fields is not None:
icp_score, mirror_distinct_id = await sync_to_async(_score_and_mirror)(
- organization_id=organization_id,
- bridge_inputs=bridge_inputs,
- fields=fields,
- role=role_at_organization,
- is_recheck=is_recheck,
- distinct_id=distinct_id,
+ ctx, bridge_inputs=bridge_inputs, fields=fields
)
fit, fit_mirror_distinct_id = await sync_to_async(_score_fit)(
- organization_id=organization_id,
- bridge_inputs=bridge_inputs,
- raw_payload=lookup.raw_payload,
- role=role_at_organization,
- domain=domain,
- distinct_id=distinct_id,
- is_recheck=is_recheck,
+ ctx, bridge_inputs=bridge_inputs, raw_payload=lookup.raw_payload
)
if fields is None and fit is None:
return EnrichmentOutcome(provider_fields=None, fit=None, enrichment_status=enrichment_status)
await sync_to_async(write_organization_enrichment)(
- organization_id=organization_id,
+ organization_id=ctx.organization_id,
fields=fields,
pha_client=pha_client,
icp_score=icp_score,
diff --git a/products/growth/backend/enrichment/gates.py b/products/growth/backend/enrichment/gates.py
new file mode 100644
index 000000000000..ea249c7261c2
--- /dev/null
+++ b/products/growth/backend/enrichment/gates.py
@@ -0,0 +1,72 @@
+"""The guards every enrichment entry point applies before it reaches the provider."""
+
+import datetime as dt
+from email.utils import parseaddr
+from typing import Literal
+
+from posthog.dataclasses import frozen
+from posthog.models.instance_setting import get_instance_setting
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.utils import GenericEmails, get_instance_region
+
+KILL_SWITCH_SETTING = "GROWTH_SIGNUP_ENRICHMENT_ENABLED"
+CLOUD_REGIONS = ("US", "EU")
+
+# The signup creator's membership is written in the signup transaction, so an earliest
+# membership older than this means that user left and nobody can stand in for them.
+SIGNUP_MEMBERSHIP_WINDOW = dt.timedelta(minutes=5)
+
+_generic_emails = GenericEmails()
+
+
+def enrichment_enabled() -> bool:
+ return bool(get_instance_setting(KILL_SWITCH_SETTING))
+
+
+def region_allowed() -> bool:
+ return get_instance_region() in CLOUD_REGIONS
+
+
+def organization_exists(organization_id: str) -> bool:
+ return Organization.objects.filter(id=organization_id).exists()
+
+
+def domain_from_email(email: str) -> str | None:
+ _, address = parseaddr(email or "")
+ if "@" not in address:
+ return None
+ domain = address.rsplit("@", 1)[1].strip().lower()
+ return domain or None
+
+
+SignupIdentitySkipReason = Literal["signup_user_left", "no_usable_member"]
+
+
+@frozen
+class SignupIdentity:
+ distinct_id: str
+ domain: str
+
+
+@frozen
+class SignupIdentitySkip:
+ reason: SignupIdentitySkipReason
+
+
+def resolve_signup_identity(organization_id: str) -> SignupIdentity | SignupIdentitySkip:
+ membership = (
+ OrganizationMembership.objects.filter(organization_id=organization_id)
+ .select_related("user", "organization")
+ .order_by("joined_at")
+ .first()
+ )
+ if membership is None:
+ return SignupIdentitySkip(reason="no_usable_member")
+ if membership.joined_at - membership.organization.created_at > SIGNUP_MEMBERSHIP_WINDOW:
+ return SignupIdentitySkip(reason="signup_user_left")
+ user = membership.user
+ domain = domain_from_email(user.email) if user and user.email 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):
+ return SignupIdentitySkip(reason="no_usable_member")
+ return SignupIdentity(distinct_id=user.distinct_id, domain=domain)
diff --git a/products/growth/backend/management/commands/backfill_icp_fit_scores.py b/products/growth/backend/management/commands/backfill_icp_fit_scores.py
index e6e189410c8b..8524a77791a7 100644
--- a/products/growth/backend/management/commands/backfill_icp_fit_scores.py
+++ b/products/growth/backend/management/commands/backfill_icp_fit_scores.py
@@ -36,9 +36,11 @@ from posthoganalytics.client import Client
from posthog.exceptions_capture import capture_exception
from posthog.models.organization import Organization
from posthog.ph_client import get_regional_ph_client
-from posthog.utils import get_instance_region
-from products.growth.backend.enrichment import icp_lists as icp_lists_module
+from products.growth.backend.enrichment import (
+ gates,
+ icp_lists as icp_lists_module,
+)
from products.growth.backend.enrichment.bridge import read_organization_bridge_inputs
from products.growth.backend.enrichment.core import latest_matched_payload
from products.growth.backend.enrichment.fit_score import IcpFitResult, score_company
@@ -246,7 +248,7 @@ class Command(BaseCommand):
return "written"
def _run_backfill(self, options: dict[str, Any]) -> None:
- if get_instance_region() not in ("US", "EU"):
+ if not gates.region_allowed():
raise CommandError("Signup enrichment is Cloud-only; refusing to backfill in this region")
limit: int | None = options["limit"]
diff --git a/products/growth/backend/management/commands/backfill_signup_enrichment.py b/products/growth/backend/management/commands/backfill_signup_enrichment.py
index ad3ef8700ed9..044512dadc84 100644
--- a/products/growth/backend/management/commands/backfill_signup_enrichment.py
+++ b/products/growth/backend/management/commands/backfill_signup_enrichment.py
@@ -12,20 +12,12 @@ from typing import Any
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
+from posthog.models.organization import Organization
-from products.growth.backend.temporal.signup_enrichment.trigger import dispatch_signup_enrichment, domain_from_email
+from products.growth.backend.enrichment import gates
+from products.growth.backend.temporal.signup_enrichment.trigger import dispatch_signup_enrichment
from products.growth.backend.temporal.signup_enrichment.workflow import SignupEnrichmentInputs
-_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 = (
@@ -43,10 +35,9 @@ 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 get_instance_setting("GROWTH_SIGNUP_ENRICHMENT_ENABLED"):
+ if not gates.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"):
+ if not gates.region_allowed():
raise CommandError("Signup enrichment is US/EU-only; refusing to dispatch in this region")
after = self._parse_datetime(options["after"])
@@ -73,28 +64,22 @@ class Command(BaseCommand):
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:
+ identity = gates.resolve_signup_identity(str(org.id))
+ if isinstance(identity, gates.SignupIdentitySkip):
skipped += 1
- self.stdout.write(f"skip {org.id} ({org.created_at:%Y-%m-%d %H:%M}) (signup user no longer a member)")
+ if identity.reason == "signup_user_left":
+ self.stdout.write(
+ f"skip {org.id} ({org.created_at:%Y-%m-%d %H:%M}) (signup user no longer a member)"
+ )
+ else:
+ self.stdout.write(f"skip {org.id} ({org.created_at:%Y-%m-%d %H:%M}) (no usable signup 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)
+ inputs = SignupEnrichmentInputs(
+ organization_id=str(org.id), distinct_id=identity.distinct_id, domain=identity.domain
+ )
if options["dry_run"]:
- self.stdout.write(f"would dispatch {org.id} ({org.created_at:%Y-%m-%d %H:%M}) domain={domain}")
+ self.stdout.write(f"would dispatch {org.id} ({org.created_at:%Y-%m-%d %H:%M}) domain={identity.domain}")
else:
try:
dispatch_signup_enrichment(inputs)
@@ -102,7 +87,7 @@ class Command(BaseCommand):
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}")
+ self.stdout.write(f"dispatched {org.id} ({org.created_at:%Y-%m-%d %H:%M}) domain={identity.domain}")
time.sleep(options["delay"])
dispatched += 1
diff --git a/products/growth/backend/temporal/signup_enrichment/harmonic_status_poll.py b/products/growth/backend/temporal/signup_enrichment/harmonic_status_poll.py
index 5208b73ea014..daa51983b8cf 100644
--- a/products/growth/backend/temporal/signup_enrichment/harmonic_status_poll.py
+++ b/products/growth/backend/temporal/signup_enrichment/harmonic_status_poll.py
@@ -72,16 +72,15 @@ async def select_status_poll_candidates_activity(inputs: HarmonicStatusPollInput
"""
from asgiref.sync import sync_to_async # noqa: PLC0415
- from posthog.models.instance_setting import get_instance_setting # noqa: PLC0415
-
+ from products.growth.backend.enrichment import gates # noqa: PLC0415
from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch # noqa: PLC0415
logger = LOGGER.bind()
- if not await sync_to_async(get_instance_setting)("GROWTH_SIGNUP_ENRICHMENT_ENABLED"):
+ if not await sync_to_async(gates.enrichment_enabled)():
logger.info("harmonic_status_poll_skipped_kill_switch")
return {"candidates": [], "eligible": 0}
- if get_instance_region() not in ("US", "EU"):
+ if not gates.region_allowed():
logger.info("harmonic_status_poll_skipped_region")
return {"candidates": [], "eligible": 0}
@@ -158,15 +157,14 @@ async def poll_status_batch_activity(candidates: list[dict[str, typing.Any]]) ->
"""
from asgiref.sync import sync_to_async # noqa: PLC0415
- from posthog.models.instance_setting import get_instance_setting # noqa: PLC0415
-
+ from products.growth.backend.enrichment import gates # noqa: PLC0415
from products.growth.backend.enrichment.providers import HarmonicEnrichmentProvider # noqa: PLC0415
logger = LOGGER.bind()
empty_result = {"polled": 0, "unobserved": 0, "changed": 0, "stalled": 0}
- if not await sync_to_async(get_instance_setting)("GROWTH_SIGNUP_ENRICHMENT_ENABLED"):
+ if not await sync_to_async(gates.enrichment_enabled)():
logger.info("harmonic_status_poll_skipped_kill_switch")
return dict(empty_result)
diff --git a/products/growth/backend/temporal/signup_enrichment/reenrichment.py b/products/growth/backend/temporal/signup_enrichment/reenrichment.py
index d8322ec6b513..eac007330b11 100644
--- a/products/growth/backend/temporal/signup_enrichment/reenrichment.py
+++ b/products/growth/backend/temporal/signup_enrichment/reenrichment.py
@@ -21,7 +21,7 @@ not a backoff: `icp_reenrichment_attempt_count` is recorded but nothing reads it
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
+goes through `enrich_organization` as `EnrichmentPhase.SWEEP` — 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.
@@ -65,11 +65,6 @@ ICP_REENRICHMENT_ATTEMPT_COUNT_KEY = "icp_reenrichment_attempt_count"
# 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.
@@ -103,24 +98,21 @@ async def select_reenrichment_candidates_activity(inputs: IcpReenrichmentSweepIn
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
+ from products.growth.backend.enrichment import gates # 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 await sync_to_async(get_instance_setting)("GROWTH_SIGNUP_ENRICHMENT_ENABLED"):
+ if not await sync_to_async(gates.enrichment_enabled)():
logger.info("icp_reenrichment_skipped_kill_switch")
return []
- if get_instance_region() not in ("US", "EU"):
+ if not gates.region_allowed():
logger.info("icp_reenrichment_skipped_region")
return []
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]]:
now = dt.datetime.now(dt.UTC)
@@ -178,25 +170,14 @@ async def select_reenrichment_candidates_activity(inputs: IcpReenrichmentSweepIn
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):
+ identity = gates.resolve_signup_identity(organization_id)
+ if isinstance(identity, gates.SignupIdentitySkip):
continue
candidates.append(
{
"organization_id": organization_id,
- "distinct_id": user.distinct_id,
- "domain": domain,
+ "distinct_id": identity.distinct_id,
+ "domain": identity.domain,
"role_at_organization": roles.get(organization_id),
}
)
@@ -218,9 +199,8 @@ async def reenrich_organization_activity(inputs: ReenrichOrgInputs) -> dict[str,
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 import gates # noqa: PLC0415
+ from products.growth.backend.enrichment.context import EnrichmentContext, EnrichmentPhase # 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
@@ -230,14 +210,14 @@ async def reenrich_organization_activity(inputs: ReenrichOrgInputs) -> dict[str,
# 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 await sync_to_async(get_instance_setting)("GROWTH_SIGNUP_ENRICHMENT_ENABLED"):
+ if not await sync_to_async(gates.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)():
+ if not await sync_to_async(gates.organization_exists)(inputs.organization_id):
logger.info("icp_reenrichment_skipped_org_deleted")
return {"matched": False, "skipped": "organization_deleted"}
@@ -277,15 +257,14 @@ async def reenrich_organization_activity(inputs: ReenrichOrgInputs) -> dict[str,
return {"matched": False}
try:
- outcome = await enrich_organization(
+ ctx = EnrichmentContext(
organization_id=inputs.organization_id,
domain=inputs.domain,
- provider=HarmonicEnrichmentProvider(),
- pha_client=pha_client,
- is_recheck=True,
- role_at_organization=inputs.role_at_organization,
+ phase=EnrichmentPhase.SWEEP,
distinct_id=inputs.distinct_id,
+ role_at_organization=inputs.role_at_organization,
)
+ outcome = await enrich_organization(ctx=ctx, provider=HarmonicEnrichmentProvider(), pha_client=pha_client)
matched = outcome.provider_fields is not None
status = outcome.fit.status if outcome.fit else None
pha_client.capture(
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 f82aa0cef0c6..2a8c579789d0 100644
--- a/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py
+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py
@@ -230,8 +230,8 @@ class TestReenrichOrganizationActivity(BaseTest):
"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"
+ assert enrich.await_args.kwargs["ctx"].is_recheck is True
+ assert enrich.await_args.kwargs["ctx"].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"
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 c5a45bd056a8..2ce491514a73 100644
--- a/products/growth/backend/temporal/signup_enrichment/tests/test_trigger.py
+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_trigger.py
@@ -25,12 +25,12 @@ def _run_dispatch_pool_inline():
@pytest.fixture(autouse=True)
def _enrichment_enabled():
- with patch("products.growth.backend.temporal.signup_enrichment.trigger.get_instance_setting", return_value=True):
+ with patch("products.growth.backend.enrichment.gates.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)
+ return patch("products.growth.backend.enrichment.gates.get_instance_setting", return_value=False)
def _dispatch_mocks(region="US"):
@@ -42,7 +42,7 @@ def _dispatch_mocks(region="US"):
),
patch("products.growth.backend.temporal.signup_enrichment.trigger.sync_connect"),
patch("products.growth.backend.temporal.signup_enrichment.trigger.asyncio.run"),
- patch("products.growth.backend.temporal.signup_enrichment.trigger.get_instance_region", return_value=region),
+ patch("products.growth.backend.enrichment.gates.get_instance_region", return_value=region),
patch("products.growth.backend.temporal.signup_enrichment.trigger.record_signup_work_email"),
)
@@ -81,7 +81,7 @@ def test_kill_switch_off_never_dispatches_or_writes():
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",
+ "products.growth.backend.enrichment.gates.get_instance_setting",
side_effect=RuntimeError("db down"),
)
with on_commit, connect as connect_mock, run, region, record as record_mock, setting_read_fails:
diff --git a/products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py b/products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py
index 8fd4a248c66c..f8858a9c95e0 100644
--- a/products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py
+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py
@@ -65,8 +65,8 @@ async def test_miss_then_recheck_upgrades_without_a_second_completed_event():
assert result == {"matched": True, "fields_filled": 3}
assert enrich.await_count == 2
# The is_recheck label is threaded through to the enrichment core: False first, True on recheck.
- assert enrich.await_args_list[0].kwargs["is_recheck"] is False
- assert enrich.await_args_list[1].kwargs["is_recheck"] is True
+ assert enrich.await_args_list[0].kwargs["ctx"].is_recheck is False
+ assert enrich.await_args_list[1].kwargs["ctx"].is_recheck is True
# is_recheck=True skips the at-signup snapshot, so it is captured only on the first attempt.
snapshot.assert_called_once()
@@ -95,7 +95,7 @@ async def test_match_on_first_attempt_still_runs_the_recheck():
assert result == {"matched": True, "fields_filled": 2}
assert enrich.await_count == 2
- assert enrich.await_args_list[1].kwargs["is_recheck"] is True
+ assert enrich.await_args_list[1].kwargs["ctx"].is_recheck is True
snapshot.assert_called_once()
# Already matched at the first attempt, so matching again at recheck is not an upgrade.
diff --git a/products/growth/backend/temporal/signup_enrichment/trigger.py b/products/growth/backend/temporal/signup_enrichment/trigger.py
index 761d3e671aab..d92f5c4a6568 100644
--- a/products/growth/backend/temporal/signup_enrichment/trigger.py
+++ b/products/growth/backend/temporal/signup_enrichment/trigger.py
@@ -10,7 +10,6 @@ for every signup so consumers can read it either way.
import asyncio
import threading
from concurrent.futures import ThreadPoolExecutor
-from email.utils import parseaddr
from django.conf import settings
from django.db import transaction
@@ -22,10 +21,10 @@ 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
+from posthog.utils import GenericEmails
+from products.growth.backend.enrichment import gates
from products.growth.backend.enrichment.writer import record_signup_work_email
from products.growth.backend.temporal.signup_enrichment.workflow import SignupEnrichmentInputs
@@ -44,14 +43,6 @@ _dispatch_executor = ThreadPoolExecutor(
_dispatch_slots = threading.BoundedSemaphore(_DISPATCH_MAX_PENDING)
-def domain_from_email(email: str) -> str | None:
- _, address = parseaddr(email or "")
- if "@" not in address:
- return None
- domain = address.rsplit("@", 1)[1].strip().lower()
- return domain or None
-
-
def start_signup_enrichment_workflow(
*,
organization_id: str,
@@ -68,10 +59,10 @@ def start_signup_enrichment_workflow(
return
# Cloud only — self-hosted has no Harmonic key or internal project to score against. The
# instance setting above is the real per-region toggle.
- if get_instance_region() not in ("US", "EU"):
+ if not gates.region_allowed():
return
- domain = domain_from_email(email)
+ domain = gates.domain_from_email(email)
if not domain:
return
@@ -134,7 +125,7 @@ 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"))
+ return gates.enrichment_enabled()
except Exception as e:
capture_exception(e)
return False
diff --git a/products/growth/backend/temporal/signup_enrichment/workflow.py b/products/growth/backend/temporal/signup_enrichment/workflow.py
index 3d4ebfb05bef..8b022b58c871 100644
--- a/products/growth/backend/temporal/signup_enrichment/workflow.py
+++ b/products/growth/backend/temporal/signup_enrichment/workflow.py
@@ -20,6 +20,8 @@ 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.enrichment import gates
+from products.growth.backend.enrichment.context import EnrichmentContext, EnrichmentPhase
from products.growth.backend.enrichment.core import enrich_organization
from products.growth.backend.enrichment.providers import HarmonicEnrichmentProvider
from products.growth.backend.enrichment.snapshot import SignupEnrichmentSnapshot, capture_signup_enrichment_snapshot
@@ -93,9 +95,7 @@ async def enrich_signup_organization_activity(
# The org owner can delete the org during the recheck delay; without this guard the
# recheck would enrich a deleted org (db_constraint=False means orphan rows, and the
# group projection would write properties for a dead org).
- from posthog.models import Organization # noqa: PLC0415 — heavy import kept off the workflow module path
-
- org_exists = await sync_to_async(Organization.objects.filter(id=inputs.organization_id).exists)()
+ org_exists = await sync_to_async(gates.organization_exists)(inputs.organization_id)
if not org_exists:
logger.info("signup_enrichment_recheck_skipped_org_deleted")
return {"matched": False, "fields_filled": 0, "org_deleted": True}
@@ -108,16 +108,15 @@ async def enrich_signup_organization_activity(
return {"matched": False, "fields_filled": 0}
try:
- outcome = await enrich_organization(
+ ctx = EnrichmentContext(
organization_id=inputs.organization_id,
domain=inputs.domain,
- provider=HarmonicEnrichmentProvider(),
- pha_client=pha_client,
- is_recheck=is_recheck,
+ phase=EnrichmentPhase.RECHECK if is_recheck else EnrichmentPhase.AT_SIGNUP,
+ distinct_id=inputs.distinct_id,
role_at_organization=inputs.role_at_organization,
geoip_country_code=inputs.geoip_country_code,
- distinct_id=inputs.distinct_id,
)
+ outcome = await enrich_organization(ctx=ctx, provider=HarmonicEnrichmentProvider(), pha_client=pha_client)
fields, fit = outcome.provider_fields, outcome.fit
filled = fields.to_dict() if fields else {}
matched = fields is not None
diff --git a/products/growth/backend/tests/test_backfill_icp_fit_scores.py b/products/growth/backend/tests/test_backfill_icp_fit_scores.py
index 9a21cc4d63f8..d765b67c8626 100644
--- a/products/growth/backend/tests/test_backfill_icp_fit_scores.py
+++ b/products/growth/backend/tests/test_backfill_icp_fit_scores.py
@@ -10,6 +10,7 @@ from products.growth.backend.enrichment.icp_lists import clear_lists_cache
from products.growth.backend.models import IcpScoringConfig, OrganizationEnrichment, OrganizationEnrichmentFetch
_COMMAND_MODULE = "products.growth.backend.management.commands.backfill_icp_fit_scores"
+_GATES_MODULE = "products.growth.backend.enrichment.gates"
_PAYLOAD = {
"id": "company-1",
@@ -70,7 +71,7 @@ class TestBackfillIcpFitScores(BaseTest):
)
with (
- patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="US"),
+ patch(f"{_GATES_MODULE}.get_instance_region", return_value="US"),
patch(f"{_COMMAND_MODULE}.get_regional_ph_client", return_value=pha_client),
patch(f"{_COMMAND_MODULE}.read_organization_bridge_inputs", **bridge_patch_kwargs),
patch(f"{_COMMAND_MODULE}.capture_exception") as capture_mock,
@@ -91,7 +92,7 @@ class TestBackfillIcpFitScores(BaseTest):
pha_client = MagicMock()
with (
- patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="US"),
+ patch(f"{_GATES_MODULE}.get_instance_region", return_value="US"),
patch(f"{_COMMAND_MODULE}.get_regional_ph_client", return_value=pha_client),
patch(
f"{_COMMAND_MODULE}.read_organization_bridge_inputs",
diff --git a/products/growth/backend/tests/test_enrichment_backfill_command.py b/products/growth/backend/tests/test_enrichment_backfill_command.py
index 5264cba58f38..1453914b7d05 100644
--- a/products/growth/backend/tests/test_enrichment_backfill_command.py
+++ b/products/growth/backend/tests/test_enrichment_backfill_command.py
@@ -12,6 +12,7 @@ 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"
+_GATES_MODULE = "products.growth.backend.enrichment.gates"
def _window() -> dict[str, str]:
@@ -55,7 +56,7 @@ class TestBackfillSignupEnrichment(BaseTest):
self._org(email="[email protected]", joined_after=dt.timedelta(days=2))
with (
- patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="US"),
+ patch(f"{_GATES_MODULE}.get_instance_region", return_value="US"),
patch(f"{_COMMAND_MODULE}.dispatch_signup_enrichment") as dispatch,
):
call_command("backfill_signup_enrichment", "--delay=0", **_window())
@@ -75,7 +76,7 @@ class TestBackfillSignupEnrichment(BaseTest):
target = self._org(email="[email protected]")
with (
- patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="EU"),
+ patch(f"{_GATES_MODULE}.get_instance_region", return_value="EU"),
patch(f"{_COMMAND_MODULE}.dispatch_signup_enrichment") as dispatch,
):
call_command("backfill_signup_enrichment", "--delay=0", **_window())
@@ -85,7 +86,7 @@ class TestBackfillSignupEnrichment(BaseTest):
def test_refuses_outside_us_and_eu(self):
self._org(email="[email protected]")
- with patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="DEV"):
+ with patch(f"{_GATES_MODULE}.get_instance_region", return_value="DEV"):
with self.assertRaises(CommandError):
call_command("backfill_signup_enrichment", **_window())
@@ -94,7 +95,7 @@ class TestBackfillSignupEnrichment(BaseTest):
second = self._org(email="[email protected]")
with (
- patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="US"),
+ patch(f"{_GATES_MODULE}.get_instance_region", return_value="US"),
patch(
f"{_COMMAND_MODULE}.dispatch_signup_enrichment", side_effect=[RuntimeError("temporal down"), None]
) as dispatch,
@@ -107,7 +108,7 @@ class TestBackfillSignupEnrichment(BaseTest):
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"{_GATES_MODULE}.get_instance_region", return_value="US"),
patch(f"{_COMMAND_MODULE}.dispatch_signup_enrichment") as dispatch,
):
call_command("backfill_signup_enrichment", "--dry-run", **_window())
diff --git a/products/growth/backend/tests/test_enrichment_core.py b/products/growth/backend/tests/test_enrichment_core.py
index e52e2b383f5d..2e96f4574825 100644
--- a/products/growth/backend/tests/test_enrichment_core.py
+++ b/products/growth/backend/tests/test_enrichment_core.py
@@ -7,6 +7,7 @@ from asgiref.sync import async_to_sync
from parameterized import parameterized
from products.growth.backend.enrichment.bridge import ClayBridgeInputs, OrganizationBridgeInputs, WizardBridgeInputs
+from products.growth.backend.enrichment.context import EnrichmentContext, EnrichmentPhase
from products.growth.backend.enrichment.core import _MISS_PAYLOAD, enrich_organization
from products.growth.backend.enrichment.fields import EnrichmentFields
from products.growth.backend.enrichment.icp_lists import clear_lists_cache
@@ -127,19 +128,20 @@ class TestEnrichmentCore(BaseTest):
)
}
)
+ ctx = EnrichmentContext(
+ organization_id=str(self.organization.id),
+ domain=domain,
+ phase=EnrichmentPhase.RECHECK if is_recheck else EnrichmentPhase.AT_SIGNUP,
+ distinct_id=distinct_id,
+ role_at_organization=role_at_organization,
+ geoip_country_code=geoip_country_code,
+ )
with (
patch("products.growth.backend.enrichment.core.read_organization_bridge_inputs", **bridge_patch_kwargs),
patch("products.growth.backend.enrichment.core.get_person_by_distinct_id", **person_patch_kwargs),
):
return async_to_sync(enrich_organization)(
- organization_id=str(self.organization.id),
- domain=domain,
- provider=provider or _FakeProvider(lookup),
- pha_client=pha_client or MagicMock(),
- is_recheck=is_recheck,
- role_at_organization=role_at_organization,
- geoip_country_code=geoip_country_code,
- distinct_id=distinct_id,
+ ctx, provider=provider or _FakeProvider(lookup), pha_client=pha_client or MagicMock()
)
# ---------- archive + legacy clay behavior (unchanged contracts) ----------
@@ -324,6 +326,13 @@ class TestEnrichmentCore(BaseTest):
def test_first_attempt_does_not_look_up_the_person(self):
fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)
+ ctx = EnrichmentContext(
+ organization_id=str(self.organization.id),
+ domain="stripe.com",
+ phase=EnrichmentPhase.AT_SIGNUP,
+ distinct_id="signer-distinct-id",
+ role_at_organization="engineering",
+ )
with (
patch(
"products.growth.backend.enrichment.core.read_organization_bridge_inputs",
@@ -332,13 +341,9 @@ class TestEnrichmentCore(BaseTest):
patch("products.growth.backend.enrichment.core.get_person_by_distinct_id") as person_mock,
):
async_to_sync(enrich_organization)(
- organization_id=str(self.organization.id),
- domain="stripe.com",
+ ctx,
provider=_FakeProvider(ProviderLookup(fields=fields, raw_payload=_empty_shell())),
pha_client=MagicMock(),
- is_recheck=False,
- role_at_organization="engineering",
- distinct_id="signer-distinct-id",
)
person_mock.assert_not_called()
@@ -426,6 +431,12 @@ class TestEnrichmentCore(BaseTest):
# no person lookup, mirrored on every attempt — unlike the guarded clay mirror.
pha_client = MagicMock()
fields = EnrichmentFields(company_type="STARTUP")
+ ctx = EnrichmentContext(
+ organization_id=str(self.organization.id),
+ domain="acme.ai",
+ phase=EnrichmentPhase.AT_SIGNUP,
+ distinct_id="signer-distinct-id",
+ )
with (
patch(
"products.growth.backend.enrichment.core.read_organization_bridge_inputs",
@@ -434,12 +445,9 @@ class TestEnrichmentCore(BaseTest):
patch("products.growth.backend.enrichment.core.get_person_by_distinct_id") as person_mock,
):
async_to_sync(enrich_organization)(
- organization_id=str(self.organization.id),
- domain="acme.ai",
+ ctx,
provider=_FakeProvider(ProviderLookup(fields=fields, raw_payload=_company())),
pha_client=pha_client,
- is_recheck=False,
- distinct_id="signer-distinct-id",
)
person_mock.assert_not_called()
@@ -570,16 +578,15 @@ class TestEnrichmentCore(BaseTest):
def test_recheck_reads_the_wizard_bridge(self):
fields = EnrichmentFields(company_type="STARTUP", headcount=12)
payload = _company(description="We sell shoes", tagsV2=[{"displayValue": "S25", "type": "YC_BATCH"}])
+ ctx = EnrichmentContext(
+ organization_id=str(self.organization.id), domain="acme.com", phase=EnrichmentPhase.RECHECK
+ )
with patch(
"products.growth.backend.enrichment.core.read_organization_bridge_inputs",
return_value=OrganizationBridgeInputs(wizard=WizardBridgeInputs(ai_sdk_detected=True)),
) as bridge_mock:
outcome = async_to_sync(enrich_organization)(
- organization_id=str(self.organization.id),
- domain="acme.com",
- provider=_FakeProvider(ProviderLookup(fields=fields, raw_payload=payload)),
- pha_client=MagicMock(),
- is_recheck=True,
+ ctx, provider=_FakeProvider(ProviderLookup(fields=fields, raw_payload=payload)), pha_client=MagicMock()
)
bridge_mock.assert_called_once_with(organization_id=str(self.organization.id))
@@ -591,6 +598,9 @@ class TestEnrichmentCore(BaseTest):
def test_recheck_reads_the_organization_group_once_for_both_scores(self):
fields = EnrichmentFields(company_type="STARTUP", headcount=12)
group = MagicMock(group_properties={"wizard_ai_sdk_detected": True})
+ ctx = EnrichmentContext(
+ organization_id=str(self.organization.id), domain="acme.com", phase=EnrichmentPhase.RECHECK
+ )
with (
patch("products.growth.backend.enrichment.bridge.get_instance_region", return_value="US"),
patch("products.growth.backend.enrichment.bridge.Team.objects.get", return_value=self.team),
@@ -601,11 +611,9 @@ class TestEnrichmentCore(BaseTest):
patch("products.growth.backend.enrichment.bridge.get_group_by_key", return_value=group) as get_group,
):
outcome = async_to_sync(enrich_organization)(
- organization_id=str(self.organization.id),
- domain="acme.com",
+ ctx,
provider=_FakeProvider(ProviderLookup(fields=fields, raw_payload=_company())),
pha_client=MagicMock(),
- is_recheck=True,
)
assert outcome.fit is not None
@@ -614,16 +622,17 @@ class TestEnrichmentCore(BaseTest):
def test_first_attempt_ignores_the_wizard_bridge_input(self):
fields = EnrichmentFields(company_type="STARTUP", headcount=12)
+ ctx = EnrichmentContext(
+ organization_id=str(self.organization.id), domain="acme.ai", phase=EnrichmentPhase.AT_SIGNUP
+ )
with patch(
"products.growth.backend.enrichment.core.read_organization_bridge_inputs",
return_value=OrganizationBridgeInputs(wizard=WizardBridgeInputs(ai_sdk_detected=True)),
):
outcome = async_to_sync(enrich_organization)(
- organization_id=str(self.organization.id),
- domain="acme.ai",
+ ctx,
provider=_FakeProvider(ProviderLookup(fields=fields, raw_payload=_company())),
pha_client=MagicMock(),
- is_recheck=False,
)
assert outcome.fit is not None
@@ -632,6 +641,9 @@ class TestEnrichmentCore(BaseTest):
def test_wizard_bridge_read_failure_skips_a_fit_score_without_persisted_evidence(self):
fields = EnrichmentFields(company_type="STARTUP", headcount=12)
+ ctx = EnrichmentContext(
+ organization_id=str(self.organization.id), domain="acme.ai", phase=EnrichmentPhase.RECHECK
+ )
with (
patch(
"products.growth.backend.enrichment.core.read_organization_bridge_inputs",
@@ -640,11 +652,9 @@ class TestEnrichmentCore(BaseTest):
patch("products.growth.backend.enrichment.core.capture_exception") as capture_mock,
):
outcome = async_to_sync(enrich_organization)(
- organization_id=str(self.organization.id),
- domain="acme.ai",
+ ctx,
provider=_FakeProvider(ProviderLookup(fields=fields, raw_payload=_company())),
pha_client=MagicMock(),
- is_recheck=True,
)
capture_mock.assert_called_once()
@@ -661,6 +671,9 @@ class TestEnrichmentCore(BaseTest):
)
fields = EnrichmentFields(company_type="STARTUP", headcount=12)
payload = _company(description="We sell shoes", tagsV2=[{"displayValue": "S25", "type": "YC_BATCH"}])
+ ctx = EnrichmentContext(
+ organization_id=str(self.organization.id), domain="acme.com", phase=EnrichmentPhase.RECHECK
+ )
with (
patch(
"products.growth.backend.enrichment.core.read_organization_bridge_inputs",
@@ -669,11 +682,9 @@ class TestEnrichmentCore(BaseTest):
patch("products.growth.backend.enrichment.core.capture_exception"),
):
outcome = async_to_sync(enrich_organization)(
- organization_id=str(self.organization.id),
- domain="acme.com",
+ ctx,
provider=_FakeProvider(ProviderLookup(fields=fields, raw_payload=payload)),
pha_client=MagicMock(),
- is_recheck=True,
)
assert outcome.fit is not None
diff --git a/products/growth/backend/tests/test_enrichment_core_phases.py b/products/growth/backend/tests/test_enrichment_core_phases.py
new file mode 100644
index 000000000000..70ff34d498fc
--- /dev/null
+++ b/products/growth/backend/tests/test_enrichment_core_phases.py
@@ -0,0 +1,426 @@
+from typing import Optional
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, call, patch
+
+from asgiref.sync import async_to_sync
+
+from products.growth.backend.enrichment.bridge import ClayBridgeInputs, OrganizationBridgeInputs, WizardBridgeInputs
+from products.growth.backend.enrichment.context import EnrichmentContext, EnrichmentPhase
+from products.growth.backend.enrichment.core import enrich_organization
+from products.growth.backend.enrichment.fields import EnrichmentFields
+from products.growth.backend.enrichment.icp_lists import clear_lists_cache
+from products.growth.backend.enrichment.providers import EnrichmentProvider, ProviderLookup
+from products.growth.backend.models import IcpScoringConfig, OrganizationEnrichment, OrganizationEnrichmentFetch
+
+
+class _FakeProvider(EnrichmentProvider):
+ name = "harmonic"
+
+ def __init__(self, lookup: ProviderLookup, *, status: Optional[str] = None):
+ self._lookup = lookup
+ self._status = status
+
+ async def enrich_by_domain(self, domain: str) -> ProviderLookup:
+ return self._lookup
+
+ async def enrichment_status_for(self, urn: str) -> Optional[str]:
+ return self._status
+
+
+def _company(**overrides):
+ company = {
+ "companyType": "STARTUP",
+ "headcount": 12,
+ "description": "AI developer platform",
+ "funding": {"fundingTotal": 12_000_000, "investors": [{"name": "Y Combinator"}]},
+ "tagsV2": [
+ {"displayValue": "Artificial Intelligence", "type": "MARKET"},
+ {"displayValue": "S25", "type": "YC_BATCH"},
+ ],
+ "tractionMetrics": {
+ "webTraffic": {
+ "latestMetricValue": 120_000,
+ "metrics": [
+ {"timestamp": "2026-08-01T00:00:00Z", "metricValue": 120_000},
+ {"timestamp": "2026-04-01T00:00:00Z", "metricValue": 70_000},
+ ],
+ },
+ "headcount": {
+ "latestMetricValue": 12,
+ "metrics": [
+ {"timestamp": "2026-08-01T00:00:00Z", "metricValue": 12},
+ {"timestamp": "2026-01-01T00:00:00Z", "metricValue": 8},
+ ],
+ },
+ "headcountEngineering": {"latestMetricValue": 8, "metrics": []},
+ },
+ }
+ company.update(overrides)
+ return company
+
+
+class TestEnrichmentCorePhases(BaseTest):
+ def setUp(self):
+ super().setUp()
+ IcpScoringConfig.objects.create(
+ version="test-lists-1",
+ tags=[
+ {"tag": "Artificial Intelligence", "recommendation": "ai_positive"},
+ {"tag": "Developer Tools", "recommendation": "software_positive"},
+ ],
+ quality_investors=[{"investor": "Y Combinator", "aliases": ["YC"]}],
+ is_active=True,
+ )
+ clear_lists_cache()
+
+ def tearDown(self):
+ clear_lists_cache()
+ super().tearDown()
+
+ def _run(
+ self,
+ *,
+ provider,
+ pha_client,
+ is_recheck,
+ role_at_organization,
+ geoip_country_code,
+ distinct_id,
+ domain,
+ bridge_inputs,
+ person,
+ ):
+ ctx = EnrichmentContext(
+ organization_id=str(self.organization.id),
+ domain=domain,
+ phase=EnrichmentPhase.RECHECK if is_recheck else EnrichmentPhase.AT_SIGNUP,
+ distinct_id=distinct_id,
+ role_at_organization=role_at_organization,
+ geoip_country_code=geoip_country_code,
+ )
+ with (
+ patch(
+ "products.growth.backend.enrichment.core.read_organization_bridge_inputs",
+ return_value=bridge_inputs,
+ ),
+ patch("products.growth.backend.enrichment.core.get_person_by_distinct_id", return_value=person),
+ ):
+ return async_to_sync(enrich_organization)(ctx, provider=provider, pha_client=pha_client)
+
+ def _rows(self):
+ return list(
+ OrganizationEnrichmentFetch.objects.filter(organization=self.organization)
+ .order_by("id")
+ .values_list("provider", "is_recheck", "payload")
+ )
+
+ def test_at_signup_match(self):
+ pha_client = MagicMock()
+ provider = _FakeProvider(
+ ProviderLookup(
+ fields=EnrichmentFields(
+ company_type="STARTUP", headcount=12, founded_year=2020, ownership_status="PRIVATE"
+ ),
+ raw_payload=_company(),
+ enrichment_urn="urn:harmonic:1",
+ )
+ )
+
+ outcome = self._run(
+ provider=provider,
+ pha_client=pha_client,
+ is_recheck=False,
+ role_at_organization="engineering",
+ geoip_country_code="US",
+ distinct_id="d1",
+ domain="acme.com",
+ bridge_inputs=OrganizationBridgeInputs(
+ clay=ClayBridgeInputs(est_revenue=None), wizard=WizardBridgeInputs()
+ ),
+ person=None,
+ )
+
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ self.assertEqual(
+ record.data,
+ {
+ "company_type": "STARTUP",
+ "headcount": 12,
+ "founded_year": 2020,
+ "ownership_status": "PRIVATE",
+ "country": "US",
+ "icp_score": 12,
+ "icp_score_version": "clay-parity-2",
+ "icp_fit_status": "scored",
+ "icp_fit_version": "v0.6",
+ "icp_fit_lists_version": "test-lists-1",
+ "icp_fit_score": 100,
+ "icp_fit_components": {
+ "traction": 35,
+ "capital": 30,
+ "ai_pilled": 15,
+ "headcount_growth": 10,
+ "software_relevance": 10,
+ },
+ "icp_fit_flags": {
+ "quality_investor": True,
+ "data_coverage": 4,
+ "low_confidence": False,
+ "agency_flag": False,
+ "nonprofit_flag": False,
+ "wizard_ai_sdk": False,
+ "ai_pilled_source": "harmonic",
+ },
+ },
+ )
+ self.assertEqual(self._rows(), [("harmonic", False, {**_company(), "enrichmentUrn": "urn:harmonic:1"})])
+ self.assertEqual(
+ pha_client.group_identify.call_args_list,
+ [
+ call(
+ "organization",
+ str(self.organization.id),
+ properties={
+ "enrichment_company_type": "STARTUP",
+ "icp_employees": 12,
+ "icp_country": "US",
+ "enrichment_founded_year": 2020,
+ "enrichment_ownership_status": "PRIVATE",
+ "icp_score": 12,
+ "icp_score_version": "clay-parity-2",
+ "icp_fit_score": 100,
+ "icp_fit_version": "v0.6",
+ "icp_fit_status": "scored",
+ },
+ )
+ ],
+ )
+ self.assertEqual(
+ pha_client.set.call_args_list,
+ [
+ call(
+ distinct_id="d1",
+ properties={"icp_fit_score": 100, "icp_fit_version": "v0.6", "icp_fit_status": "scored"},
+ )
+ ],
+ )
+ self.assertEqual(
+ outcome.provider_fields,
+ EnrichmentFields(company_type="STARTUP", headcount=12, founded_year=2020, ownership_status="PRIVATE"),
+ )
+ self.assertEqual(outcome.fit.status, "scored")
+ self.assertEqual(outcome.fit.score, 100)
+ self.assertEqual(outcome.enrichment_status, None)
+
+ def test_recheck_miss_scores_from_archive(self):
+ OrganizationEnrichment.objects.create(
+ organization=self.organization,
+ data={
+ "work_email": True,
+ "signup_role": "engineering",
+ "company_type": "STARTUP",
+ "headcount": 12,
+ "founded_year": 2020,
+ "ownership_status": "PRIVATE",
+ "country": "US",
+ },
+ )
+ OrganizationEnrichmentFetch.objects.create(
+ organization=self.organization,
+ provider="harmonic",
+ is_recheck=False,
+ payload={**_company(), "enrichmentUrn": "urn:harmonic:1"},
+ )
+ pha_client = MagicMock()
+ provider = _FakeProvider(ProviderLookup(fields=None, raw_payload=None, enrichment_urn=None), status="COMPLETED")
+ person = MagicMock()
+ person.properties = {"icp_score": 7, "icp_score_version": "clay-parity-2"}
+
+ outcome = self._run(
+ provider=provider,
+ pha_client=pha_client,
+ is_recheck=True,
+ role_at_organization="engineering",
+ geoip_country_code=None,
+ distinct_id="d1",
+ domain="acme.com",
+ bridge_inputs=OrganizationBridgeInputs(
+ clay=ClayBridgeInputs(est_revenue=None), wizard=WizardBridgeInputs(ai_sdk_detected=True)
+ ),
+ person=person,
+ )
+
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ self.assertEqual(
+ record.data,
+ {
+ "work_email": True,
+ "signup_role": "engineering",
+ "company_type": "STARTUP",
+ "headcount": 12,
+ "founded_year": 2020,
+ "ownership_status": "PRIVATE",
+ "country": "US",
+ "icp_score": 12,
+ "icp_score_version": "clay-parity-2",
+ "icp_fit_status": "scored",
+ "icp_fit_version": "v0.6",
+ "icp_fit_lists_version": "test-lists-1",
+ "icp_fit_score": 100,
+ "icp_fit_components": {
+ "traction": 35,
+ "capital": 30,
+ "ai_pilled": 15,
+ "headcount_growth": 10,
+ "software_relevance": 10,
+ },
+ "icp_fit_flags": {
+ "quality_investor": True,
+ "data_coverage": 4,
+ "low_confidence": False,
+ "agency_flag": False,
+ "nonprofit_flag": False,
+ "wizard_ai_sdk": True,
+ "ai_pilled_source": "both",
+ },
+ },
+ )
+ self.assertEqual(
+ self._rows(),
+ [
+ ("harmonic", False, {**_company(), "enrichmentUrn": "urn:harmonic:1"}),
+ ("harmonic", True, {"companyFound": False, "enrichmentUrn": None, "enrichmentStatus": "COMPLETED"}),
+ ],
+ )
+ self.assertEqual(
+ pha_client.group_identify.call_args_list,
+ [
+ call(
+ "organization",
+ str(self.organization.id),
+ properties={
+ "enrichment_company_type": "STARTUP",
+ "icp_employees": 12,
+ "icp_country": "US",
+ "enrichment_founded_year": 2020,
+ "enrichment_ownership_status": "PRIVATE",
+ "icp_score": 12,
+ "icp_score_version": "clay-parity-2",
+ "icp_fit_score": 100,
+ "icp_fit_version": "v0.6",
+ "icp_fit_status": "scored",
+ },
+ )
+ ],
+ )
+ self.assertEqual(
+ pha_client.set.call_args_list,
+ [
+ call(distinct_id="d1", properties={"icp_score": 12, "icp_score_version": "clay-parity-2"}),
+ call(
+ distinct_id="d1",
+ properties={"icp_fit_score": 100, "icp_fit_version": "v0.6", "icp_fit_status": "scored"},
+ ),
+ ],
+ )
+ self.assertEqual(outcome.provider_fields, None)
+ self.assertEqual(outcome.fit.status, "scored")
+ self.assertEqual(outcome.fit.score, 100)
+ self.assertEqual(outcome.enrichment_status, "COMPLETED")
+
+ def test_recheck_match_with_stored_country(self):
+ OrganizationEnrichment.objects.create(
+ organization=self.organization, data={"work_email": True, "country": "DE"}
+ )
+ pha_client = MagicMock()
+ provider = _FakeProvider(
+ ProviderLookup(
+ fields=EnrichmentFields(company_type="STARTUP", headcount=40),
+ raw_payload=_company(headcount=40),
+ enrichment_urn=None,
+ ),
+ status=None,
+ )
+
+ outcome = self._run(
+ provider=provider,
+ pha_client=pha_client,
+ is_recheck=True,
+ role_at_organization=None,
+ geoip_country_code=None,
+ distinct_id="d2",
+ domain="acme.com",
+ bridge_inputs=OrganizationBridgeInputs(),
+ person=None,
+ )
+
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ self.assertEqual(
+ record.data,
+ {
+ "work_email": True,
+ "country": "DE",
+ "company_type": "STARTUP",
+ "headcount": 40,
+ "icp_score": 0,
+ "icp_score_version": "clay-parity-2",
+ "icp_fit_status": "scored",
+ "icp_fit_version": "v0.6",
+ "icp_fit_lists_version": "test-lists-1",
+ "icp_fit_score": 100,
+ "icp_fit_components": {
+ "traction": 35,
+ "capital": 30,
+ "ai_pilled": 15,
+ "headcount_growth": 10,
+ "software_relevance": 10,
+ },
+ "icp_fit_flags": {
+ "quality_investor": True,
+ "data_coverage": 4,
+ "low_confidence": False,
+ "agency_flag": False,
+ "nonprofit_flag": False,
+ "wizard_ai_sdk": False,
+ "ai_pilled_source": "harmonic",
+ },
+ },
+ )
+ self.assertEqual(
+ self._rows(),
+ [("harmonic", True, {**_company(headcount=40), "enrichmentUrn": None, "enrichmentStatus": None})],
+ )
+ self.assertEqual(
+ pha_client.group_identify.call_args_list,
+ [
+ call(
+ "organization",
+ str(self.organization.id),
+ properties={
+ "enrichment_company_type": "STARTUP",
+ "icp_employees": 40,
+ "icp_country": "DE",
+ "icp_score": 0,
+ "icp_score_version": "clay-parity-2",
+ "icp_fit_score": 100,
+ "icp_fit_version": "v0.6",
+ "icp_fit_status": "scored",
+ },
+ )
+ ],
+ )
+ self.assertEqual(
+ pha_client.set.call_args_list,
+ [
+ call(distinct_id="d2", properties={"icp_score": 0, "icp_score_version": "clay-parity-2"}),
+ call(
+ distinct_id="d2",
+ properties={"icp_fit_score": 100, "icp_fit_version": "v0.6", "icp_fit_status": "scored"},
+ ),
+ ],
+ )
+ self.assertEqual(outcome.provider_fields, EnrichmentFields(company_type="STARTUP", headcount=40))
+ self.assertEqual(outcome.fit.status, "scored")
+ self.assertEqual(outcome.fit.score, 100)
+ self.assertEqual(outcome.enrichment_status, None)
diff --git a/products/growth/backend/tests/test_enrichment_gates.py b/products/growth/backend/tests/test_enrichment_gates.py
new file mode 100644
index 000000000000..3fccbacf9967
--- /dev/null
+++ b/products/growth/backend/tests/test_enrichment_gates.py
@@ -0,0 +1,78 @@
+import datetime as dt
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.models.instance_setting import override_instance_config
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.user import User
+
+from products.growth.backend.enrichment.gates import (
+ SignupIdentity,
+ SignupIdentitySkip,
+ domain_from_email,
+ enrichment_enabled,
+ region_allowed,
+ resolve_signup_identity,
+)
+
+_MODULE = "products.growth.backend.enrichment.gates"
+
+
+class TestEnrichmentGates(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="signup")
+ OrganizationMembership.objects.create(organization=organization, user=user)
+ return organization
+
+ def test_resolve_signup_identity_with_no_membership_is_unusable(self):
+ organization = Organization.objects.create(name="empty.example")
+
+ assert resolve_signup_identity(str(organization.id)) == SignupIdentitySkip(reason="no_usable_member")
+
+ def test_resolve_signup_identity_after_the_membership_window_has_left(self):
+ organization = self._org_with_member("[email protected]")
+ OrganizationMembership.objects.filter(organization=organization).update(
+ joined_at=organization.created_at + dt.timedelta(minutes=10)
+ )
+
+ assert resolve_signup_identity(str(organization.id)) == SignupIdentitySkip(reason="signup_user_left")
+
+ def test_resolve_signup_identity_with_a_generic_email_is_unusable(self):
+ organization = self._org_with_member("[email protected]")
+
+ assert resolve_signup_identity(str(organization.id)) == SignupIdentitySkip(reason="no_usable_member")
+
+ def test_resolve_signup_identity_with_a_work_email_returns_a_lowercased_identity(self):
+ organization = self._org_with_member("[email protected]")
+ distinct_id = organization.memberships.get().user.distinct_id
+ assert distinct_id is not None
+
+ assert resolve_signup_identity(str(organization.id)) == SignupIdentity(
+ distinct_id=distinct_id, domain="stripe.com"
+ )
+
+ @parameterized.expand(
+ [
+ ("mixed_case", "[email protected]", "stripe.com"),
+ ("display_name_form", "Name <[email protected]>", "b.com"),
+ ("no_at", "not-an-email", None),
+ ("empty", "", None),
+ ]
+ )
+ def test_domain_from_email(self, _name, email, expected):
+ assert domain_from_email(email) == expected
+
+ @parameterized.expand([("us", "US", True), ("eu", "EU", True), ("self_hosted", None, False)])
+ def test_region_allowed(self, _name, region, expected):
+ with patch(f"{_MODULE}.get_instance_region", return_value=region):
+ assert region_allowed() is expected
+
+ def test_enrichment_enabled_reflects_the_instance_setting(self):
+ with override_instance_config("GROWTH_SIGNUP_ENRICHMENT_ENABLED", True):
+ assert enrichment_enabled() is True
+ with override_instance_config("GROWTH_SIGNUP_ENRICHMENT_ENABLED", False):
+ assert enrichment_enabled() is False