: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): score signup enrichment on first attempt (#79064)
Matt Brooker4c71d3200246
diff --git a/products/growth/backend/enrichment/core.py b/products/growth/backend/enrichment/core.pyindex 63325c7ab7ae..e08c3c0f422a 100644--- a/products/growth/backend/enrichment/core.py+++ b/products/growth/backend/enrichment/core.py@@ -16,7 +16,7 @@ from posthoganalytics.client import Clientfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.person.util import get_person_by_distinct_id-from products.growth.backend.enrichment.bridge import read_clay_bridge_inputs+from products.growth.backend.enrichment.bridge import ClayBridgeInputs, read_clay_bridge_inputsfrom products.growth.backend.enrichment.fields import EnrichmentFieldsfrom products.growth.backend.enrichment.providers import EnrichmentProviderfrom products.growth.backend.enrichment.score import IcpScoreInputs, compute_icp_score@@ -28,8 +28,13 @@ from products.growth.backend.models import OrganizationEnrichment_MISS_PAYLOAD = {"companyFound": False}+def _persisted_score_exists(organization_id: str) -> bool:+ record = OrganizationEnrichment.objects.filter(organization_id=organization_id).only("data").first()+ return bool(record and record.data.get("icp_score") is not None)++def _reconstruct_fields_from_record(organization_id: str) -> Optional[EnrichmentFields]:- """Rebuild EnrichmentFields from the last-written record for a recheck whose provider lookup missed.+ """Rebuild EnrichmentFields from the last-written record when a provider lookup misses.Registry keys are exactly the dataclass field names (see fields.py), so a prior write can bereplayed back into the same shape. Returns None when there is no prior record, or it carries@@ -77,11 +82,10 @@ def _score_and_mirror() -> tuple[Optional[int], Optional[str]]:"""Score one org and decide whether to mirror the score onto the signer's person profile.- A first attempt only scores once Clay's own bridge columns have landed (`clay_processed`) —- Clay's write lands after ours far more often than not, so scoring earlier would frequently- undercount. The recheck, four hours later, scores unconditionally: by then Clay's inputs have- either landed or never will, so scoring on whatever the bridge holds is no worse than what- Clay would have provided. The person mirror is recheck-only for the same reason, and skipped+ Clay's bridge columns are read as an optional input on every attempt — used when present,+ never waited for. Clay's own write lands after ours far more often than not, so most orgs+ score on our fields alone at signup; the +4h recheck re-reads the bridge and can upgrade the+ score if Clay's columns landed since. The person mirror stays recheck-only, and is skippedentirely when the person already carries a Clay-written score.Wrapped so a bridge-read or score failure degrades to no score rather than taking down the@@ -90,11 +94,15 @@ def _score_and_mirror(try:clay = read_clay_bridge_inputs(organization_id=organization_id)except Exception as e:+ # A failed bridge READ is not absent bridge data: the bridge is optional input, so a+ # read failure (unresolvable internal team, transient store error) degrades to scoring+ # without it rather than costing the score entirely. Degraded-mode scores only fill a+ # gap, though — a persisted score may have been computed WITH bridge data, and a+ # bridge-less recompute would silently downgrade it.capture_exception(e)- return None, None-- if not is_recheck and not clay.clay_processed:- return None, None+ if _persisted_score_exists(organization_id):+ return None, None+ clay = ClayBridgeInputs()icp_score = compute_icp_score(IcpScoreInputs(@@ -137,17 +145,17 @@ async def enrich_organization(Returns the enrichment fields, or None when the provider has no match. The Postgres writesrun via sync_to_async to bridge the async provider.- A matched org is also ICP-scored, from these fields plus the signer's role and Clay's- remaining columns — see `_score_and_mirror` for the first-attempt-vs-recheck scoring and- person-mirror policy. A bridge-read or score failure degrades to writing firmographics with- no score, rather than a silently-too-low one; the delayed recheck gets a second chance, and- the fetch archive backstops a later batch recompute.-- On a recheck whose provider lookup misses, a prior `OrganizationEnrichment` record (if any)- is reconstructed into fields and scored anyway — so an org matched at first attempt can't end- up permanently score-less because of one flaky recheck lookup. The return value 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.+ A matched org is also ICP-scored, from these fields plus the signer's role and Clay's bridge+ columns when present — see `_score_and_mirror` for the scoring and person-mirror policy. A+ bridge-read or score failure degrades to writing firmographics with no score, rather than a+ silently-too-low one; 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+ scored anyway — first attempt or recheck alike — so an org can't end up permanently+ score-less because of one flaky lookup. The return value 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."""lookup = await provider.enrich_by_domain(domain)@@ -160,8 +168,6 @@ async def enrich_organization(fields = lookup.fieldsif fields is None:- if not is_recheck:- return Nonefields = await sync_to_async(_reconstruct_fields_from_record)(organization_id)if fields is None:return Nonediff --git a/products/growth/backend/tests/test_enrichment_core.py b/products/growth/backend/tests/test_enrichment_core.pyindex 4beed3377908..8c4f334472d1 100644--- a/products/growth/backend/tests/test_enrichment_core.py+++ b/products/growth/backend/tests/test_enrichment_core.py@@ -85,8 +85,8 @@ class TestEnrichmentCore(BaseTest):assert [r.is_recheck for r in rows] == [False, True]def test_scores_the_org_from_our_fields_the_signup_role_and_clays_columns(self):- # First attempt: scores immediately because Clay has already processed the org- # (clay_processed=True) — but the person mirror is recheck-only, so `set` stays unused.+ # First attempt: Clay's bridge columns are already present, so they feed the score too —+ # but the person mirror is recheck-only, so `set` stays unused.pha_client = MagicMock()fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)self._enrich(@@ -105,16 +105,50 @@ class TestEnrichmentCore(BaseTest):assert properties["icp_score_version"] == "clay-parity-1"pha_client.set.assert_not_called()- def test_first_attempt_before_clay_has_processed_the_org_writes_no_score(self):- # Clay's bridge write lands after ours more often than not, so a first attempt with- # clay_processed=False must skip scoring entirely rather than write a too-low score.+ def test_first_attempt_scores_without_waiting_for_clay(self):+ # Clay's bridge write lands after ours more often than not, so the first attempt scores+ # on our fields alone (clay_processed=False) rather than waiting for the recheck.fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)- self._enrich(ProviderLookup(fields=fields, raw_payload={"n": 1}), role_at_organization="engineering")+ result = self._enrich(ProviderLookup(fields=fields, raw_payload={"n": 1}), role_at_organization="engineering")+ assert result is fields+ record = OrganizationEnrichment.objects.get(organization=self.organization)+ assert record.data["icp_score"] == 12+ assert record.data["icp_score_version"] == "clay-parity-1"++ def test_first_attempt_miss_reconstructs_fields_from_a_prior_record_and_scores(self):+ # A re-dispatched first attempt (e.g. via the backfill command) can land on an org that+ # already carries a partial record; it must score from that record just like a recheck+ # would, without mirroring onto the person (mirror stays recheck-only).+ OrganizationEnrichment.objects.create(+ organization=self.organization,+ data={"headcount": 750, "country": "US", "founded_year": 2021, "company_type_deterministic": "yc"},+ )+ pha_client = MagicMock()++ result = self._enrich(+ ProviderLookup(fields=None, raw_payload=None),+ role_at_organization="engineering",+ pha_client=pha_client,+ distinct_id="signer-distinct-id",+ )++ assert result is None+ record = OrganizationEnrichment.objects.get(organization=self.organization)+ assert record.data["icp_score"] == 12+ pha_client.set.assert_not_called()++ def test_first_attempt_miss_with_only_first_party_data_does_not_score(self):+ # The work_email row written before every dispatch must not count as prior provider data.+ OrganizationEnrichment.objects.create(organization=self.organization, data={"work_email": True})+ pha_client = MagicMock()++ result = self._enrich(ProviderLookup(fields=None, raw_payload=None), pha_client=pha_client)++ assert result is Nonerecord = OrganizationEnrichment.objects.get(organization=self.organization)assert "icp_score" not in record.data- assert "icp_score_version" not in record.data- assert record.data["headcount"] == 750+ pha_client.group_identify.assert_not_called()def test_recheck_scores_unconditionally_even_when_clay_never_processed(self):fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)@@ -220,21 +254,45 @@ class TestEnrichmentCore(BaseTest):assert "icp_score" not in record.datapha_client.group_identify.assert_not_called()- def test_bridge_read_failure_writes_no_score_rather_than_a_low_one(self):- fields = EnrichmentFields(headcount=750, country="US")+ def test_bridge_read_failure_still_scores_from_own_fields(self):+ # The bridge is optional input, so a failed READ scores exactly like an empty bridge+ # instead of costing the score entirely (a transient store error would otherwise leave+ # the org score-less until the next attempt).+ fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)with patch("products.growth.backend.enrichment.core.capture_exception") as capture_mock:result = self._enrich(ProviderLookup(fields=fields, raw_payload={"n": 1}),- is_recheck=True,+ role_at_organization="engineering",clay=RuntimeError("group store down"),)assert result is fieldscapture_mock.assert_called_once()record = OrganizationEnrichment.objects.get(organization=self.organization)- assert "icp_score" not in record.data+ assert record.data["icp_score"] == 12assert record.data["headcount"] == 750+ def test_bridge_read_failure_never_downgrades_a_persisted_score(self):+ # A persisted score may have been computed WITH bridge data (revenue, company type);+ # a bridge-less recompute at recheck would silently strip those points.+ OrganizationEnrichment.objects.create(+ organization=self.organization,+ data={"icp_score": 15, "icp_score_version": "clay-parity-1", "headcount": 750},+ )+ fields = EnrichmentFields(headcount=800, country="US", founded_year=2021)++ result = self._enrich(+ ProviderLookup(fields=fields, raw_payload={"n": 1}),+ is_recheck=True,+ role_at_organization="engineering",+ clay=RuntimeError("group store down"),+ )++ assert result is fields+ record = OrganizationEnrichment.objects.get(organization=self.organization)+ assert record.data["icp_score"] == 15+ assert record.data["headcount"] == 800+def test_archive_failure_does_not_break_enrich(self):fields = EnrichmentFields(company_type="STARTUP")with (