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.

feat(growth): fall back to signup geoip country for icp scoring (#72972)

Matt Brooker592fca18f8bf
diff --git a/posthog/api/signup.py b/posthog/api/signup.py
index 31bdb5eb9455..44678ec8301f 100644
--- a/posthog/api/signup.py
+++ b/posthog/api/signup.py
@@ -39,7 +39,7 @@ from posthog.models.webauthn_credential import WebauthnCredential
from posthog.permissions import CanCreateOrg
from posthog.rate_limit import SignupEmailPrecheckThrottle, SignupIPThrottle, SignupResendInviteThrottle
from posthog.temporal.signup_enrichment.trigger import start_signup_enrichment_workflow
-from posthog.utils import get_can_create_org, is_relative_url
+from posthog.utils import get_can_create_org, get_trusted_client_ip, is_relative_url
from posthog.workos_radar import RadarAction, RadarAuthMethod, evaluate_auth_attempt
from products.demo.backend.facade.api import HedgeboxMatrix, MatrixManager
@@ -311,6 +311,8 @@ class SignupSerializer(serializers.Serializer):
distinct_id=user.distinct_id,
email=user.email,
role_at_organization=role_at_organization,
+ # Trusted-proxy-validated: a spoofed X-Forwarded-For must not pick the scored country.
+ ip_address=get_trusted_client_ip(request),
)
verify_email_or_login(request, user)
diff --git a/posthog/temporal/signup_enrichment/trigger.py b/posthog/temporal/signup_enrichment/trigger.py
index aa620df1d99a..0313311e22db 100644
--- a/posthog/temporal/signup_enrichment/trigger.py
+++ b/posthog/temporal/signup_enrichment/trigger.py
@@ -21,6 +21,7 @@ from temporalio.exceptions import WorkflowAlreadyStartedError
from temporalio.service import RPCError
from posthog.exceptions_capture import capture_exception
+from posthog.geoip import get_geoip_properties
from posthog.temporal.common.client import sync_connect
from posthog.temporal.signup_enrichment.workflow import SignupEnrichmentInputs
from posthog.utils import GenericEmails, get_instance_region
@@ -51,7 +52,12 @@ def domain_from_email(email: str) -> str | None:
def start_signup_enrichment_workflow(
- *, organization_id: str, distinct_id: str | None, email: str, role_at_organization: str = ""
+ *,
+ organization_id: str,
+ distinct_id: str | None,
+ email: str,
+ role_at_organization: str = "",
+ ip_address: str | None = None,
) -> None:
"""Dispatch enrichment for a freshly signed-up org, once the request transaction commits."""
# The flag alone gates dispatch. Deliberately no provider-key check here: the key lives
@@ -77,6 +83,7 @@ def start_signup_enrichment_workflow(
distinct_id=distinct_id,
domain=domain,
role_at_organization=role_at_organization or None,
+ geoip_country_code=_geoip_country_code(ip_address),
)
# on_commit so the worker never reads the org/enrichment rows before they are committed. The
# callback fires inline on the signup request thread (it runs after that transaction commits),
@@ -119,6 +126,16 @@ def _dispatch_and_release(inputs: SignupEnrichmentInputs) -> None:
_dispatch_slots.release()
+def _geoip_country_code(ip_address: str | None) -> str | None:
+ # get_geoip_properties already swallows lookup failures, but nothing geoip-related may ever
+ # surface to signup — so guard the whole call anyway.
+ try:
+ return get_geoip_properties(ip_address).get("$geoip_country_code")
+ except Exception as e:
+ capture_exception(e)
+ return None
+
+
def _record_work_email(*, organization_id: str, work_email: bool) -> None:
# The write runs in its own savepoint; a failure here must never surface to signup.
try:
diff --git a/posthog/temporal/signup_enrichment/workflow.py b/posthog/temporal/signup_enrichment/workflow.py
index b66c1fc36436..b0cf202dccfa 100644
--- a/posthog/temporal/signup_enrichment/workflow.py
+++ b/posthog/temporal/signup_enrichment/workflow.py
@@ -55,6 +55,10 @@ class SignupEnrichmentInputs:
# The signup's own role answer, passed at dispatch rather than re-read org-side. Defaulted so
# workflows already sleeping through the recheck delay at deploy still deserialize.
role_at_organization: typing.Optional[str] = None
+ # The signup request's GeoIP country (ISO alpha-2), the score's country fallback when the
+ # provider has none — mirroring the incumbent icp_country merge order. Defaulted for the
+ # same deserialization reason as role_at_organization.
+ geoip_country_code: typing.Optional[str] = None
def _deterministic_company_type(organization_id: str) -> typing.Optional[str]:
@@ -105,6 +109,7 @@ async def enrich_signup_organization_activity(
pha_client=pha_client,
is_recheck=is_recheck,
role_at_organization=inputs.role_at_organization,
+ geoip_country_code=inputs.geoip_country_code,
distinct_id=inputs.distinct_id,
)
filled = fields.to_dict() if fields else {}
diff --git a/posthog/temporal/tests/signup_enrichment/test_trigger.py b/posthog/temporal/tests/signup_enrichment/test_trigger.py
index c9579ec9dd37..9f084025eab2 100644
--- a/posthog/temporal/tests/signup_enrichment/test_trigger.py
+++ b/posthog/temporal/tests/signup_enrichment/test_trigger.py
@@ -169,3 +169,45 @@ def test_dispatch_slot_released_after_run():
start_signup_enrichment_workflow(organization_id="org-1", distinct_id="d1", email="[email protected]")
start_signup_enrichment_workflow(organization_id="org-2", distinct_id="d2", email="[email protected]")
assert connect_mock.call_count == 2
+
+
+@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")
+def test_signup_geoip_country_is_threaded_into_workflow_inputs():
+ on_commit, connect, run, region, record = _dispatch_mocks()
+ with (
+ on_commit,
+ connect as connect_mock,
+ run,
+ region,
+ record,
+ patch(
+ "posthog.temporal.signup_enrichment.trigger.get_geoip_properties",
+ return_value={"$geoip_country_code": "US"},
+ ),
+ ):
+ start_signup_enrichment_workflow(
+ organization_id="org-1", distinct_id="d1", email="[email protected]", ip_address="8.8.8.8"
+ )
+ inputs = connect_mock.return_value.start_workflow.call_args.args[1]
+ assert inputs.geoip_country_code == "US"
+
+
+@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")
+def test_geoip_failure_degrades_to_no_country_and_still_dispatches():
+ on_commit, connect, run, region, record = _dispatch_mocks()
+ with (
+ on_commit,
+ connect as connect_mock,
+ run,
+ region,
+ record,
+ patch(
+ "posthog.temporal.signup_enrichment.trigger.get_geoip_properties",
+ side_effect=RuntimeError("geoip db missing"),
+ ),
+ ):
+ start_signup_enrichment_workflow(
+ organization_id="org-1", distinct_id="d1", email="[email protected]", ip_address="8.8.8.8"
+ )
+ inputs = connect_mock.return_value.start_workflow.call_args.args[1]
+ assert inputs.geoip_country_code is None
diff --git a/products/growth/backend/enrichment/core.py b/products/growth/backend/enrichment/core.py
index dfc8ecc07115..63325c7ab7ae 100644
--- a/products/growth/backend/enrichment/core.py
+++ b/products/growth/backend/enrichment/core.py
@@ -128,6 +128,7 @@ async def enrich_organization(
pha_client: Client,
is_recheck: bool = False,
role_at_organization: Optional[str] = None,
+ geoip_country_code: Optional[str] = None,
distinct_id: Optional[str] = None,
) -> Optional[EnrichmentFields]:
"""Look up enrichment for a domain, archive the raw response, and persist the live stores.
@@ -165,6 +166,12 @@ async def enrich_organization(
if fields is None:
return None
+ if fields.country is None and geoip_country_code:
+ # 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 lookup.fields provider-verbatim for the at-signup snapshot.
+ fields = dataclasses.replace(fields, country=geoip_country_code)
+
icp_score, mirror_distinct_id = await sync_to_async(_score_and_mirror)(
organization_id=organization_id,
fields=fields,
diff --git a/products/growth/backend/tests/test_enrichment_core.py b/products/growth/backend/tests/test_enrichment_core.py
index 0f089e38d3bd..4beed3377908 100644
--- a/products/growth/backend/tests/test_enrichment_core.py
+++ b/products/growth/backend/tests/test_enrichment_core.py
@@ -31,6 +31,7 @@ class TestEnrichmentCore(BaseTest):
pha_client=None,
distinct_id=None,
person=None,
+ geoip_country_code=None,
):
person_patch_kwargs = {"side_effect": person} if isinstance(person, Exception) else {"return_value": person}
clay_patch_kwargs = (
@@ -47,6 +48,7 @@ class TestEnrichmentCore(BaseTest):
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,
)
@@ -123,6 +125,30 @@ class TestEnrichmentCore(BaseTest):
# No Clay columns: the revenue and company-type branches simply do not score.
assert OrganizationEnrichment.objects.get(organization=self.organization).data["icp_score"] == 12
+ @parameterized.expand(
+ [
+ ("geoip_fills_missing_provider_country", None, "US", 12, "US"),
+ ("provider_country_wins_over_geoip", "DE", "BR", 12, "DE"),
+ ("both_missing_keeps_the_penalty", None, None, 7, None),
+ ]
+ )
+ def test_country_falls_back_to_signup_geoip(self, _name, provider_country, geoip_country, score, stored_country):
+ pha_client = MagicMock()
+ fields = EnrichmentFields(headcount=750, country=provider_country, founded_year=2021)
+ self._enrich(
+ ProviderLookup(fields=fields, raw_payload={"n": 1}),
+ is_recheck=True,
+ role_at_organization="engineering",
+ geoip_country_code=geoip_country,
+ pha_client=pha_client,
+ )
+
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data["icp_score"] == score
+ assert record.data.get("country") == stored_country
+ properties = pha_client.group_identify.call_args.kwargs["properties"]
+ assert properties.get("icp_country") == stored_country
+
def test_no_person_write_without_a_distinct_id(self):
# Scoring happens (recheck), but with no distinct_id there is no one to mirror onto.
pha_client = MagicMock()