:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(growth): fall back to Clearbit person data for recheck score inputs (#81550)
Matt Brooker9b084ae8b18e
diff --git a/products/growth/backend/enrichment/bridge.py b/products/growth/backend/enrichment/bridge.pyindex 891e00155153..e1f326ea300c 100644--- a/products/growth/backend/enrichment/bridge.py+++ b/products/growth/backend/enrichment/bridge.py@@ -1,8 +1,8 @@"""Read the scoring inputs Clay still owns, off the organization group it writes.-Two of the ICP score's inputs have no first-party source yet, so while Clay runs in parallel-we read its own group properties back and score on them. That keeps `clay-parity-1` scores-bit-comparable with Clay's on the orgs it also scores.+The ICP score's revenue input has no first-party source, so while Clay runs in parallel we+read its own group property back and score on it. That keeps our scores bit-comparable with+Clay's on the orgs it also scores.The formula's third Clay-owned input, its GitHub profile lookup, is deliberately NOT readhere: Clay never projects that column into PostHog at all (verified against live group and@@ -41,7 +41,6 @@ class ClayBridgeInputs:"""Clay-owned score inputs for one org. All None when Clay never processed it."""est_revenue: Optional[float] = None- company_type: Optional[str] = None# Presence of the company-type key, not its coerced value — Clay fills that column on# essentially every row it writes, making raw key-presence a reliable ran/didn't-run signal.clay_processed: bool = False@@ -62,10 +61,6 @@ def _numeric(value: Any) -> Optional[float]:return None-def _text(value: Any) -> Optional[str]:- return value if isinstance(value, str) and value else None--def _organization_group_type_index(team: Team) -> int:for group_type in get_group_types_for_project(team.project_id):if group_type["group_type"] == ORGANIZATION_GROUP_TYPE:@@ -95,6 +90,5 @@ def read_clay_bridge_inputs(*, organization_id: str) -> ClayBridgeInputs:properties = group.group_properties or {}return ClayBridgeInputs(est_revenue=_numeric(properties.get(CLAY_EST_REVENUE_PROPERTY)),- company_type=_text(properties.get(CLAY_COMPANY_TYPE_PROPERTY)),clay_processed=CLAY_COMPANY_TYPE_PROPERTY in properties,)diff --git a/products/growth/backend/enrichment/clearbit.py b/products/growth/backend/enrichment/clearbit.pynew file mode 100644index 000000000000..27ed65bf8a5c--- /dev/null+++ b/products/growth/backend/enrichment/clearbit.py@@ -0,0 +1,53 @@+"""Clearbit fallback for the ICP score's est_revenue input.++A separate hog function projects Clearbit's own company lookup onto the signer's person+profile under `person.properties.clearbit.*`, independently of the Clay bridge and on its+own delay (median ~8s after signup, p99 ~3min). Pure extraction: no I/O — callers own the+person fetch and hand this module the resulting properties dict.+"""++import dataclasses+from typing import Any, Optional++# Clearbit reports revenue as a band string, not a number, but the formula's comparisons are+# strict (`1_000_000 < x < 50_000_001`) and need a number. Midpoints, never band lower bounds:+# a lower-bound representative sitting exactly on a boundary would silently miss the term it's+# meant to score. "$10B+" has no upper bound, so its representative is chosen past $10B rather+# than derived from one.+_REVENUE_BAND_MIDPOINTS: dict[str, float] = {+ "$0-$1M": 500_000.0,+ "$1M-$10M": 5_500_000.0,+ "$10M-$50M": 30_000_000.0,+ "$50M-$100M": 75_000_000.0,+ "$100M-$250M": 175_000_000.0,+ "$250M-$500M": 375_000_000.0,+ "$500M-$1B": 750_000_000.0,+ "$1B-$10B": 5_500_000_000.0,+ "$10B+": 15_000_000_000.0,+}++[email protected](frozen=True)+class ClearbitInputs:+ """Clearbit-owned score inputs read off the signer's person profile. Empty when never written."""++ est_revenue: Optional[float] = None+++def _get_dict(mapping: Any, key: str) -> dict[str, Any]:+ value = mapping.get(key) if isinstance(mapping, dict) else None+ return value if isinstance(value, dict) else {}+++def clearbit_inputs_from_person_properties(properties: dict[str, Any]) -> ClearbitInputs:+ """Extract Clearbit's revenue band off the person's `clearbit.*` properties.++ The payload is a third-party API response stored verbatim, so every level is guarded rather+ than assumed present or well-typed — a missing key, a None, or a wrong-shaped value at any+ level degrades to the corresponding field staying None instead of raising. US-only in+ effect: the Clearbit hog function writes only to the US internal project, so elsewhere the+ `clearbit` block is simply absent and extraction degrades to empty the same way.+ """+ company = _get_dict(_get_dict(properties, "clearbit"), "company")+ band = _get_dict(company, "metrics").get("estimatedAnnualRevenue")+ return ClearbitInputs(est_revenue=_REVENUE_BAND_MIDPOINTS.get(band) if isinstance(band, str) else None)diff --git a/products/growth/backend/enrichment/core.py b/products/growth/backend/enrichment/core.pyindex e08c3c0f422a..3909b6aedfc8 100644--- a/products/growth/backend/enrichment/core.py+++ b/products/growth/backend/enrichment/core.py@@ -17,6 +17,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.models.person.util import get_person_by_distinct_idfrom products.growth.backend.enrichment.bridge import ClayBridgeInputs, read_clay_bridge_inputs+from products.growth.backend.enrichment.clearbit import ClearbitInputs, clearbit_inputs_from_person_propertiesfrom products.growth.backend.enrichment.fields import EnrichmentFieldsfrom products.growth.backend.enrichment.providers import EnrichmentProviderfrom products.growth.backend.enrichment.score import IcpScoreInputs, compute_icp_score@@ -51,25 +52,37 @@ def _reconstruct_fields_from_record(organization_id: str) -> Optional[Enrichmentreturn fields if fields.to_dict() else None-def _person_score_is_ours_to_write(distinct_id: str) -> bool:- """False when the signer's person profile already carries a Clay-written score.+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.Clay's own writes never stamp icp_score_version; ours always do, so an unversioned icp_score- on the person is Clay's — never clobber it with a possibly-lower mirror. A person lookup- failure also says no, preferring a missed mirror over a possible clobber.+ on the person is Clay's — never clobber it with a possibly-lower mirror. A lookup failure or+ a malformed person record (unreadable properties) degrades both reads (no mirror, no+ Clearbit fallback) rather than raising out of the scoring path, preferring a missed mirror+ over a possible clobber."""try:person = get_person_by_distinct_id(team_id=settings.GROWTH_ENRICHMENT_INTERNAL_TEAM_ID, distinct_id=distinct_id)+ if person is None:+ return True, ClearbitInputs()++ properties = person.properties or {}+ clay_owned = properties.get("icp_score") is not None and properties.get("icp_score_version") is Noneexcept Exception as e:capture_exception(e)- return False+ return False, ClearbitInputs()++ return not clay_owned, clearbit_inputs_from_person_properties(properties)- if person is None:- return True- properties = person.properties or {}- clay_owned = properties.get("icp_score") is not None and properties.get("icp_score_version") is None- return not clay_owned+def _company_type_from_ownership(ownership_status: Optional[str]) -> Optional[str]:+ """Map Harmonic's ownershipStatus onto the private/public vocabulary the formula matches on.++ Only PRIVATE carries ownership information the formula can score. ACQUIRED_OR_MERGED,+ ACTIVE and OUT_OF_BUSINESS describe a company's state rather than who owns it, so they+ score nothing instead of being folded into either side.+ """+ return "private" if ownership_status == "PRIVATE" else Nonedef _score_and_mirror(@@ -80,13 +93,15 @@ def _score_and_mirror(is_recheck: bool,distinct_id: Optional[str],) -> tuple[Optional[int], Optional[str]]:- """Score one org and decide whether to mirror the score onto the signer's person profile.+ """Score one org; on the recheck, also mirror the score onto the signer's person profile.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 orgsscore 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 skipped- entirely when the person already carries a Clay-written score.+ score if Clay's columns landed since. The recheck adds one person lookup that serves two+ things: the mirror-ownership check and the Clearbit fallback for est_revenue (Clay wins when+ both exist). company_type comes from Harmonic's own ownershipStatus, fetched server-side in+ the same lookup as the other firmographics.Wrapped so a bridge-read or score failure degrades to no score rather than taking down thefirmographic write below — see enrich_organization's docstring.@@ -104,26 +119,29 @@ def _score_and_mirror(return None, Noneclay = ClayBridgeInputs()+ mirror_ok = False+ clearbit = ClearbitInputs()+ if is_recheck and distinct_id:+ mirror_ok, clearbit = _fetch_recheck_person_inputs(distinct_id)+icp_score = compute_icp_score(IcpScoreInputs(employees=fields.headcount,- est_revenue=clay.est_revenue,+ # 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,# 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.github_profile_url=None,- # Clay's own vocabulary ("private"/"public"), which our Harmonic `company_type`- # (raw enum, e.g. "STARTUP") does not share — so this stays a bridge read for now.- company_type=clay.company_type,+ company_type=_company_type_from_ownership(fields.ownership_status),founded_year=fields.founded_year,country=fields.country,))- mirror_distinct_id = None- if is_recheck and distinct_id and _person_score_is_ours_to_write(distinct_id):- mirror_distinct_id = distinct_id+ mirror_distinct_id = distinct_id if mirror_ok else Nonereturn icp_score, mirror_distinct_iddiff --git a/products/growth/backend/enrichment/score.py b/products/growth/backend/enrichment/score.pyindex 26b7a3ad8193..27be04ae7eba 100644--- a/products/growth/backend/enrichment/score.py+++ b/products/growth/backend/enrichment/score.py@@ -5,13 +5,21 @@ A faithful port, not a redesign: the formula, its weights, and its quirks are owrecompute historical orgs from the fetch archive under a new version without disturbing thisone. Behaviour is pinned to Clay's JS semantics — see `compute_icp_score`.+clay-parity-2's est_revenue can source from the signer's Clearbit person-profile block (see+enrichment/clearbit.py), which is not part of the fetch archive — an archive-driven recompute+of a v2 score can therefore diverge from what was written live. company_type sources from+Harmonic's ownershipStatus, which is archived.+Deterministic and I/O-free: callers resolve the inputs (see bridge.py for the Clay-owned ones)."""import dataclassesfrom typing import Optional-SCORE_VERSION = "clay-parity-1"+# clay-parity-2: same formula as clay-parity-1; est_revenue may source from the signer's+# Clearbit person-profile block instead of the Clay bridge at recheck time, and company_type+# from Harmonic's ownershipStatus instead of the bridge.+SCORE_VERSION = "clay-parity-2"# Exempt from the -5 penalty. Matched case-sensitively against ISO alpha-2, as Clay does —# `country_name_to_iso_code` already normalises provider names to this casing.diff --git a/products/growth/backend/tests/test_enrichment_bridge.py b/products/growth/backend/tests/test_enrichment_bridge.pyindex 6d82cad6b59f..5e738906ab88 100644--- a/products/growth/backend/tests/test_enrichment_bridge.py+++ b/products/growth/backend/tests/test_enrichment_bridge.py@@ -44,11 +44,7 @@ class TestEnrichmentBridge(BaseTest):)inputs, get_group = self._read(group)- assert inputs == ClayBridgeInputs(- est_revenue=25_000_000.0,- company_type="private",- clay_processed=True,- )+ assert inputs == ClayBridgeInputs(est_revenue=25_000_000.0, clay_processed=True)assert get_group.call_args.kwargs["group_type_index"] == 3assert get_group.call_args.kwargs["group_key"] == "org-1"@@ -66,7 +62,6 @@ class TestEnrichmentBridge(BaseTest):# clay_processed is a raw key-presence check, not the coerced value — Clay fills this# column on essentially every row it writes, so presence alone is the ran/didn't-run signal.inputs, _ = self._read(Group(group_properties={"icp_company_type": 12}))- assert inputs.company_type is Noneassert inputs.clay_processed is True@parameterized.expand(@@ -86,11 +81,6 @@ class TestEnrichmentBridge(BaseTest):inputs, _ = self._read(Group(group_properties={"icp_est_revenue": raw}))assert inputs.est_revenue == expected- @parameterized.expand([("empty_string", "", None), ("non_string", 12, None), ("value", "private", "private")])- def test_company_type_coercion(self, _name, raw, expected):- inputs, _ = self._read(Group(group_properties={"icp_company_type": raw}))- assert inputs.company_type == expected-def test_missing_organization_group_type_raises_rather_than_reading_as_absent(self):with self.assertRaises(OrganizationGroupTypeMissing):self._read(Group(group_properties={}), group_types=[{"group_type": "project", "group_type_index": 0}])diff --git a/products/growth/backend/tests/test_enrichment_clearbit.py b/products/growth/backend/tests/test_enrichment_clearbit.pynew file mode 100644index 000000000000..fce1cbda4377--- /dev/null+++ b/products/growth/backend/tests/test_enrichment_clearbit.py@@ -0,0 +1,55 @@+from parameterized import parameterized++from products.growth.backend.enrichment.clearbit import ClearbitInputs, clearbit_inputs_from_person_properties+from products.growth.backend.enrichment.score import IcpScoreInputs, compute_icp_score+++def _properties(band=None):+ company = {"metrics": {"estimatedAnnualRevenue": band}} if band is not None else {}+ return {"clearbit": {"company": company}}+++ [+ ("under_1m", "$0-$1M", 0),+ ("1m_to_10m", "$1M-$10M", 6),+ ("10m_to_50m", "$10M-$50M", 6),+ ("50m_to_100m", "$50M-$100M", 3),+ ("100m_to_250m", "$100M-$250M", 0),+ ("250m_to_500m", "$250M-$500M", 0),+ ("500m_to_1b", "$500M-$1B", 0),+ ("1b_to_10b", "$1B-$10B", 0),+ ("10b_plus", "$10B+", 0),+ ("unknown_band", "$1M-$2M", 0),+ ("missing_band", None, 0),+ ]+)+def test_revenue_band_midpoint_scores_the_formula_band_it_belongs_to(_name, band, expected_score):+ inputs = clearbit_inputs_from_person_properties(_properties(band=band))+ assert compute_icp_score(IcpScoreInputs(est_revenue=inputs.est_revenue, country="US")) == expected_score+++ [+ ("properties_is_none", None, ClearbitInputs()),+ ("properties_not_a_dict", "unexpected", ClearbitInputs()),+ ("missing_clearbit_key", {}, ClearbitInputs()),+ ("clearbit_is_none", {"clearbit": None}, ClearbitInputs()),+ ("clearbit_not_a_dict", {"clearbit": "unexpected"}, ClearbitInputs()),+ ("company_missing", {"clearbit": {}}, ClearbitInputs()),+ ("company_is_none", {"clearbit": {"company": None}}, ClearbitInputs()),+ ("metrics_not_a_dict", {"clearbit": {"company": {"metrics": "unexpected"}}}, ClearbitInputs()),+ (+ "band_not_a_string",+ {"clearbit": {"company": {"metrics": {"estimatedAnnualRevenue": 5_000_000}}}},+ ClearbitInputs(),+ ),+ (+ "band_present",+ {"clearbit": {"company": {"metrics": {"estimatedAnnualRevenue": "$1M-$10M"}}}},+ ClearbitInputs(est_revenue=5_500_000.0),+ ),+ ]+)+def test_extraction_tolerates_missing_or_malformed_shapes(_name, properties, expected):+ assert clearbit_inputs_from_person_properties(properties) == expecteddiff --git a/products/growth/backend/tests/test_enrichment_core.py b/products/growth/backend/tests/test_enrichment_core.pyindex 8c4f334472d1..1e10f9a46ce7 100644--- a/products/growth/backend/tests/test_enrichment_core.py+++ b/products/growth/backend/tests/test_enrichment_core.py@@ -88,21 +88,21 @@ class TestEnrichmentCore(BaseTest):# 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)+ fields = EnrichmentFields(headcount=750, country="US", founded_year=2021, ownership_status="PRIVATE")self._enrich(ProviderLookup(fields=fields, raw_payload={"n": 1}),role_at_organization="Founder",- clay=ClayBridgeInputs(est_revenue=25_000_000, company_type="private", clay_processed=True),+ clay=ClayBridgeInputs(est_revenue=25_000_000, clay_processed=True),pha_client=pha_client,distinct_id="signer-distinct-id",)record = OrganizationEnrichment.objects.get(organization=self.organization)assert record.data["icp_score"] == 21- assert record.data["icp_score_version"] == "clay-parity-1"+ assert record.data["icp_score_version"] == "clay-parity-2"properties = pha_client.group_identify.call_args.kwargs["properties"]assert properties["icp_score"] == 21- assert properties["icp_score_version"] == "clay-parity-1"+ assert properties["icp_score_version"] == "clay-parity-2"pha_client.set.assert_not_called()def test_first_attempt_scores_without_waiting_for_clay(self):@@ -114,7 +114,7 @@ class TestEnrichmentCore(BaseTest):assert result is fieldsrecord = OrganizationEnrichment.objects.get(organization=self.organization)assert record.data["icp_score"] == 12- assert record.data["icp_score_version"] == "clay-parity-1"+ assert record.data["icp_score_version"] == "clay-parity-2"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@@ -218,6 +218,113 @@ class TestEnrichmentCore(BaseTest):assert pha_client.set.called is expect_mirror+ def test_first_attempt_does_not_look_up_the_person(self):+ # The Clearbit hog function and the mirror check both need the signer's person, but+ # neither is recheck-independent — a first-attempt lookup would usually just read a+ # not-yet-written profile.+ fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)+ with (+ patch("products.growth.backend.enrichment.core.read_clay_bridge_inputs", return_value=ClayBridgeInputs()),+ 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",+ provider=_FakeProvider(ProviderLookup(fields=fields, raw_payload={"n": 1})),+ pha_client=MagicMock(),+ is_recheck=False,+ role_at_organization="engineering",+ distinct_id="signer-distinct-id",+ )++ person_mock.assert_not_called()++ def test_recheck_person_lookup_failure_still_scores_from_non_clearbit_inputs(self):+ pha_client = MagicMock()+ fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)+ self._enrich(+ ProviderLookup(fields=fields, raw_payload={"n": 1}),+ is_recheck=True,+ role_at_organization="engineering",+ pha_client=pha_client,+ distinct_id="signer-distinct-id",+ person=RuntimeError("personhog down"),+ )++ record = OrganizationEnrichment.objects.get(organization=self.organization)+ assert record.data["icp_score"] == 12+ pha_client.set.assert_not_called()++ @parameterized.expand(+ [+ (+ "clay_wins_when_both_present",+ ClayBridgeInputs(est_revenue=5_000_000),+ {"clearbit": {"company": {"metrics": {"estimatedAnnualRevenue": "$100M-$250M"}}}},+ 6,+ ),+ (+ "clearbit_fills_in_when_clay_is_absent",+ ClayBridgeInputs(),+ {"clearbit": {"company": {"metrics": {"estimatedAnnualRevenue": "$1M-$10M"}}}},+ 6,+ ),+ (+ "clay_zero_revenue_falls_back_to_clearbit",+ # Clay's own _numeric coerces a written 0 (or "0") into 0.0, which the formula's+ # strict bands treat exactly like a missing value — it must not shadow Clearbit's.+ ClayBridgeInputs(est_revenue=0.0),+ {"clearbit": {"company": {"metrics": {"estimatedAnnualRevenue": "$1M-$10M"}}}},+ 6,+ ),+ ("both_absent_scores_neither_branch", ClayBridgeInputs(), {}, 0),+ ]+ )+ def test_clearbit_fallback_composition_precedence(self, _name, clay, person_properties, expected_score):+ fields = EnrichmentFields(country="US")+ self._enrich(+ ProviderLookup(fields=fields, raw_payload={"n": 1}),+ is_recheck=True,+ clay=clay,+ distinct_id="signer-distinct-id",+ person=MagicMock(properties=person_properties),+ )++ record = OrganizationEnrichment.objects.get(organization=self.organization)+ assert record.data["icp_score"] == expected_score++ @parameterized.expand(+ [+ ("private", "PRIVATE", 3),+ ("public", "PUBLIC", 0),+ ("acquired_or_merged", "ACQUIRED_OR_MERGED", 0),+ ("active", "ACTIVE", 0),+ ("out_of_business", "OUT_OF_BUSINESS", 0),+ ("absent", None, 0),+ ]+ )+ def test_only_private_ownership_status_scores_the_company_type_term(self, _name, ownership_status, expected_score):+ fields = EnrichmentFields(country="US", ownership_status=ownership_status)+ self._enrich(ProviderLookup(fields=fields, raw_payload={"n": 1}))++ record = OrganizationEnrichment.objects.get(organization=self.organization)+ assert record.data["icp_score"] == expected_score++ def test_clearbit_fallback_does_not_block_the_mirror(self):+ pha_client = MagicMock()+ fields = EnrichmentFields(country="US")+ self._enrich(+ ProviderLookup(fields=fields, raw_payload={"n": 1}),+ is_recheck=True,+ clay=ClayBridgeInputs(),+ distinct_id="signer-distinct-id",+ person=MagicMock(properties={"clearbit": {"company": {"metrics": {"estimatedAnnualRevenue": "$1M-$10M"}}}}),+ pha_client=pha_client,+ )++ pha_client.set.assert_called_once()+ assert pha_client.set.call_args.kwargs["properties"]["icp_score"] == 6+def test_recheck_miss_reconstructs_fields_from_the_prior_record_and_scores(self):OrganizationEnrichment.objects.create(organization=self.organization,diff --git a/products/growth/backend/tests/test_enrichment_score.py b/products/growth/backend/tests/test_enrichment_score.pyindex 677fec9dd139..027b1c1a9f7f 100644--- a/products/growth/backend/tests/test_enrichment_score.py+++ b/products/growth/backend/tests/test_enrichment_score.py@@ -9,7 +9,7 @@ def _inputs(**overrides) -> IcpScoreInputs:def test_version_is_stamped():- assert SCORE_VERSION == "clay-parity-1"+ assert SCORE_VERSION == "clay-parity-2"def test_all_inputs_missing_scores_only_the_country_penalty():