:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(growth): keep the country and the 30-day window on re-enrichment sweeps (#88706)
Matt Brooker743ce1f0f4d2
diff --git a/products/growth/backend/enrichment/core.py b/products/growth/backend/enrichment/core.pyindex 58d43619640b..75b7b2b8146f 100644--- a/products/growth/backend/enrichment/core.py+++ b/products/growth/backend/enrichment/core.py@@ -78,6 +78,11 @@ def _reconstruct_fields_from_record(organization_id: str) -> Optional[Enrichmentreturn fields if fields.to_dict() else None+def _stored_country(organization_id: str) -> Optional[str]:+ record = OrganizationEnrichment.objects.filter(organization_id=organization_id).only("data").first()+ return (record.data or {}).get("country") if record is not None else None++def latest_matched_payload(organization_id: str) -> Optional[dict[str, Any]]:"""The org's most recent archived payload that was an actual match, or None.@@ -275,11 +280,16 @@ async def enrich_organization(if fields is None:fields = await sync_to_async(_reconstruct_fields_from_record)(organization_id)- if fields is not None and fields.country is None and geoip_country_code:+ 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.- fields = dataclasses.replace(fields, country=geoip_country_code)+ # 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)icp_score: Optional[int] = Nonemirror_distinct_id: Optional[str] = Nonediff --git a/products/growth/backend/temporal/signup_enrichment/reenrichment.py b/products/growth/backend/temporal/signup_enrichment/reenrichment.pyindex 5895985c3988..ab96dd09b1c7 100644--- a/products/growth/backend/temporal/signup_enrichment/reenrichment.py+++ b/products/growth/backend/temporal/signup_enrichment/reenrichment.py@@ -1,18 +1,23 @@"""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:+Measured on prod-us 2026-08-24 over 14,848 scored orgs: 40.8% of matched signups are+empty-shell Harmonic profiles (insufficient_data) and 0.9% 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 isretried at most every 30 days, and an unrelated fetch row from another command can't move- this clock.+ this clock. An org the sweep has never attempted has no stamp, so its own last fetch stands+ in for one — without that it would be swept the morning after signup.- **90 days maximum** since the org's first fetch: retries self-terminate (~2 per org) — anorg still empty after two spaced retries stays at its honest status.+An org that Harmonic indexes after day 90 is never revisited. That is a deliberate ceiling,+not a backoff: `icp_reenrichment_attempt_count` is recorded but nothing reads it.+Runs as a Temporal Schedule (see the init_icp_reenrichment_schedule command) because theHarmonic key lives on the workers only. Selection re-checks the kill switch and region onevery run, so flipping GROWTH_SIGNUP_ENRICHMENT_ENABLED off also stops the sweep. Each org@@ -93,7 +98,7 @@ async def select_reenrichment_candidates_activity(inputs: IcpReenrichmentSweepInrun 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 django.db.models import Max, Min, Q # noqa: PLC0415from asgiref.sync import sync_to_async # noqa: PLC0415@@ -138,15 +143,27 @@ async def select_reenrichment_candidates_activity(inputs: IcpReenrichmentSweepInfirst_fetches = (OrganizationEnrichmentFetch.objects.filter(organization_id__in=attempt_eligible.keys()).values("organization_id")- .annotate(first_fetch=Min("fetched_at"))+ .annotate(first_fetch=Min("fetched_at"), latest_fetch=Max("fetched_at")).filter(first_fetch__gt=first_fetch_cutoff))+ # A never-attempted org has no stamp for the 30-day minimum to measure, so without this+ # it is swept the morning after signup — the same too-early lookup the +4h recheck just+ # made. Its own last fetch stands in. Orgs that carry a stamp keep using it: the stamp+ # exists so an unrelated fetch row (a backfill) cannot move their retry clock.+ never_attempted_ids = {org_id for org_id, stamp in attempt_eligible.items() if stamp is None}+ fetch_cutoff = now - dt.timedelta(days=MIN_DAYS_SINCE_LAST_ATTEMPT)+ due_rows = [+ row+ for row in first_fetches+ if str(row["organization_id"]) not in never_attempted_ids or row["latest_fetch"] <= 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),+ (str(row["organization_id"]) for row in due_rows),key=lambda organization_id: attempt_eligible[organization_id] or "",)[: cap * _SELECTION_OVERFETCH_MULTIPLIER]diff --git a/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py b/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.pyindex 54cc3cbb4bbb..9f9e05b43f8b 100644--- a/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py@@ -89,6 +89,9 @@ class TestReenrichmentSelection(BaseTest):already_scored = self._org_with_member("[email protected]")self._prime(already_scored, status="scored", last_attempted_days_ago=31, first_fetch_days_ago=40)+ never_attempted_but_freshly_fetched = self._org_with_member("[email protected]")+ self._prime(never_attempted_but_freshly_fetched, last_attempted_days_ago=None, first_fetch_days_ago=1)+due = self._org_with_member("[email protected]")self._prime(due, last_attempted_days_ago=31, first_fetch_days_ago=40)@@ -162,7 +165,7 @@ class TestReenrichmentSelection(BaseTest):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)+ self._prime(organization, last_attempted_days_ago=None, first_fetch_days_ago=40)assert len(self._select()) == 1pha_client = MagicMock()diff --git a/products/growth/backend/tests/test_enrichment_core.py b/products/growth/backend/tests/test_enrichment_core.pyindex 7ee756ba0fbb..c3e1d509d617 100644--- a/products/growth/backend/tests/test_enrichment_core.py+++ b/products/growth/backend/tests/test_enrichment_core.py@@ -218,6 +218,26 @@ class TestEnrichmentCore(BaseTest):properties = pha_client.group_identify.call_args.kwargs["properties"]assert properties.get("icp_country") == stored_country+ def test_country_falls_back_to_the_record_when_the_caller_has_no_geoip(self):+ OrganizationEnrichment.objects.update_or_create(+ organization=self.organization, defaults={"data": {"country": "DE", "work_email": True}}+ )+ pha_client = MagicMock()++ self._enrich(+ ProviderLookup(+ fields=EnrichmentFields(headcount=750, country=None, founded_year=2021), raw_payload=_empty_shell()+ ),+ is_recheck=True,+ role_at_organization="engineering",+ geoip_country_code=None,+ pha_client=pha_client,+ )++ record = OrganizationEnrichment.objects.get(organization=self.organization)+ assert record.data.get("country") == "DE"+ assert record.data["icp_score"] == 12+@parameterized.expand([("no_prior_person", None, True),