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): port Clay icp_score formula (clay-parity-1) (#71619)

Matt Brookerfd52099e5b25
diff --git a/posthog/api/signup.py b/posthog/api/signup.py
index 1a1426493f7f..31bdb5eb9455 100644
--- a/posthog/api/signup.py
+++ b/posthog/api/signup.py
@@ -310,6 +310,7 @@ class SignupSerializer(serializers.Serializer):
organization_id=str(self._organization.id),
distinct_id=user.distinct_id,
email=user.email,
+ role_at_organization=role_at_organization,
)
verify_email_or_login(request, user)
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 4bb26d1fc5f1..52680e1c0ad3 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -351,6 +351,11 @@ SESSION_RISK_ENABLED = get_from_env("SESSION_RISK_ENABLED", not TEST, type_cast=
# Off by default: it must stay off until the launch fill-rate/failure alert is in place, and v0 is
# US-only. Fire-and-forget from signup, so this only gates whether the workflow is dispatched at all.
GROWTH_SIGNUP_ENRICHMENT_ENABLED = get_from_env("GROWTH_SIGNUP_ENRICHMENT_ENABLED", False, type_cast=str_to_bool)
+# The internal analytics project the enrichment pipeline reads/writes bridge and mirror data
+# against (products/growth/backend/enrichment). Defaults to project 2, the internal project the
+# enrichment group properties are projected onto; env-overridable since that id differs across
+# cloud deployments.
+GROWTH_ENRICHMENT_INTERNAL_TEAM_ID = get_from_env("GROWTH_ENRICHMENT_INTERNAL_TEAM_ID", 2, type_cast=int)
# Session keys for risk-based step-up (posthog/session/risk.py). Named so every reader/writer shares
# one source of truth, like SESSION_COOKIE_CREATED_AT_KEY above.
SESSION_STEP_UP_REQUIRED_KEY = get_from_env("SESSION_STEP_UP_REQUIRED_KEY", "step_up_required")
diff --git a/posthog/temporal/signup_enrichment/trigger.py b/posthog/temporal/signup_enrichment/trigger.py
index 8d22ae40cc18..aa620df1d99a 100644
--- a/posthog/temporal/signup_enrichment/trigger.py
+++ b/posthog/temporal/signup_enrichment/trigger.py
@@ -50,7 +50,9 @@ def domain_from_email(email: str) -> str | None:
return domain or None
-def start_signup_enrichment_workflow(*, organization_id: str, distinct_id: str | None, email: str) -> None:
+def start_signup_enrichment_workflow(
+ *, organization_id: str, distinct_id: str | None, email: str, role_at_organization: str = ""
+) -> 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
# only on the workers, and a keyless worker fails loudly into the launch alert instead of
@@ -70,7 +72,12 @@ def start_signup_enrichment_workflow(*, organization_id: str, distinct_id: str |
if not work_email or not distinct_id:
return
- inputs = SignupEnrichmentInputs(organization_id=str(organization_id), distinct_id=distinct_id, domain=domain)
+ inputs = SignupEnrichmentInputs(
+ organization_id=str(organization_id),
+ distinct_id=distinct_id,
+ domain=domain,
+ role_at_organization=role_at_organization or None,
+ )
# 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),
# so dispatch goes to the bounded pool: building the Temporal client must not add latency to
diff --git a/posthog/temporal/signup_enrichment/workflow.py b/posthog/temporal/signup_enrichment/workflow.py
index 9c06e8a104b2..b66c1fc36436 100644
--- a/posthog/temporal/signup_enrichment/workflow.py
+++ b/posthog/temporal/signup_enrichment/workflow.py
@@ -39,8 +39,11 @@ ENRICH_ACTIVITY_TIMEOUT = dt.timedelta(seconds=90)
MAX_ENRICH_ATTEMPTS = 3
# Harmonic's enrich mutation seeds async enrichment for a company it doesn't yet index, so a
-# domain it can't match at signup often resolves a few hours later. One delayed recheck recovers
-# those late-indexed companies without polling.
+# domain it can't match at signup often resolves a few hours later. The delay also gives Clay's
+# own bridge columns (icp_est_revenue, icp_company_type) time to land — Clay's write lands after
+# ours far more often than not, so scoring at signup alone would frequently undercount. One
+# delayed recheck, run unconditionally for every org, recovers late-indexed companies and
+# rescores against Clay's columns alike, without polling.
RECHECK_DELAY = dt.timedelta(hours=4)
@@ -49,6 +52,9 @@ class SignupEnrichmentInputs:
organization_id: str
distinct_id: str
domain: str
+ # 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
def _deterministic_company_type(organization_id: str) -> typing.Optional[str]:
@@ -63,7 +69,7 @@ def _deterministic_company_type(organization_id: str) -> typing.Optional[str]:
@activity.defn
@close_db_connections
async def enrich_signup_organization_activity(
- inputs: SignupEnrichmentInputs, is_recheck: bool = False
+ inputs: SignupEnrichmentInputs, is_recheck: bool = False, first_attempt_matched: bool = False
) -> dict[str, typing.Any]:
"""Enrich one organization by domain and persist it to the live stores.
@@ -71,6 +77,8 @@ async def enrich_signup_organization_activity(
the launch signal. The recheck (is_recheck=True) writes the live stores exactly like a first
attempt but leaves the snapshot and the launch signal untouched — the snapshot is at-signup by
design, and the launch alert reads only the first attempt — emitting its own recheck event.
+ `first_attempt_matched` (recheck only) is the first attempt's outcome, so the recheck event's
+ `upgraded` property reflects an actual upgrade rather than just the recheck's own match.
"""
from asgiref.sync import sync_to_async # noqa: PLC0415 — heavy import kept off the workflow module path
@@ -96,6 +104,8 @@ async def enrich_signup_organization_activity(
provider=HarmonicEnrichmentProvider(),
pha_client=pha_client,
is_recheck=is_recheck,
+ role_at_organization=inputs.role_at_organization,
+ distinct_id=inputs.distinct_id,
)
filled = fields.to_dict() if fields else {}
matched = fields is not None
@@ -125,7 +135,7 @@ async def enrich_signup_organization_activity(
distinct_id=inputs.distinct_id,
event=ENRICHMENT_RECHECK_EVENT,
properties={
- "upgraded": matched,
+ "upgraded": matched and not first_attempt_matched,
"fields_filled": len(filled),
"organization_id": inputs.organization_id,
},
@@ -169,18 +179,20 @@ class SignupEnrichmentWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, inputs: SignupEnrichmentInputs) -> dict[str, typing.Any]:
- result = await self._enrich(inputs, is_recheck=False)
- if result.get("matched"):
- return result
+ first_result = await self._enrich(inputs, is_recheck=False)
- # Give Harmonic's seeded async enrichment time to index the company, then look once more.
+ # Unconditional: give Harmonic's seeded async enrichment time to index the company, and
+ # Clay's bridge columns time to land, then look/score once more — for every org, matched
+ # or not on the first pass.
await workflow.sleep(RECHECK_DELAY)
- return await self._enrich(inputs, is_recheck=True)
+ return await self._enrich(inputs, is_recheck=True, first_attempt_matched=bool(first_result.get("matched")))
- async def _enrich(self, inputs: SignupEnrichmentInputs, *, is_recheck: bool) -> dict[str, typing.Any]:
+ async def _enrich(
+ self, inputs: SignupEnrichmentInputs, *, is_recheck: bool, first_attempt_matched: bool = False
+ ) -> dict[str, typing.Any]:
return await workflow.execute_activity(
enrich_signup_organization_activity,
- args=[inputs, is_recheck],
+ args=[inputs, is_recheck, first_attempt_matched],
start_to_close_timeout=ENRICH_ACTIVITY_TIMEOUT,
# Onboarding routing already degrades to a safe default when enrichment is absent.
retry_policy=RetryPolicy(maximum_attempts=MAX_ENRICH_ATTEMPTS, initial_interval=dt.timedelta(seconds=5)),
diff --git a/posthog/temporal/tests/signup_enrichment/test_workflow.py b/posthog/temporal/tests/signup_enrichment/test_workflow.py
index aaf374d47223..d0666044fb06 100644
--- a/posthog/temporal/tests/signup_enrichment/test_workflow.py
+++ b/posthog/temporal/tests/signup_enrichment/test_workflow.py
@@ -78,14 +78,21 @@ async def test_miss_then_recheck_upgrades_without_a_second_completed_event():
assert completed[0].kwargs["properties"]["matched"] is False
-async def test_match_on_first_attempt_skips_the_recheck():
+async def test_match_on_first_attempt_still_runs_the_recheck():
+ """The recheck now runs for every org, matched or not — it also re-scores against Clay's
+ bridge columns, which may not have landed yet at the first attempt."""
fields = EnrichmentFields(company_type="STARTUP", headcount=130)
- result, pha_client, enrich, snapshot = await _run([fields])
+ result, pha_client, enrich, snapshot = await _run([fields, fields])
assert result == {"matched": True, "fields_filled": 2}
- assert enrich.await_count == 1
+ assert enrich.await_count == 2
+ assert enrich.await_args_list[1].kwargs["is_recheck"] is True
snapshot.assert_called_once()
- assert _events(pha_client, "signup_enrichment_recheck") == []
+
+ # Already matched at the first attempt, so matching again at recheck is not an upgrade.
+ recheck = _events(pha_client, "signup_enrichment_recheck")
+ assert len(recheck) == 1
+ assert recheck[0].kwargs["properties"]["upgraded"] is False
assert len(_events(pha_client, "signup_enrichment_completed")) == 1
diff --git a/products/growth/backend/enrichment/bridge.py b/products/growth/backend/enrichment/bridge.py
new file mode 100644
index 000000000000..b658fcdf4ca8
--- /dev/null
+++ b/products/growth/backend/enrichment/bridge.py
@@ -0,0 +1,95 @@
+"""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 formula's third Clay-owned input, its GitHub profile lookup, is deliberately NOT read
+here: Clay never projects that column into PostHog at all (verified against live group and
+person writes), so product-role orgs score 3 rather than 6 until v-next substitutes a
+first-party signal.
+
+Every read is best-effort in coverage but strict about failure: an org Clay never processed
+simply has no properties (a real null, and Clay scored nothing for it either), whereas an
+unreachable group store raises. Scoring an org on inputs we failed to fetch would write a
+silently-too-low score, which is worse than writing none — so callers degrade to writing
+firmographics without a score on a raise, and get another chance at the delayed recheck.
+"""
+
+import dataclasses
+from typing import Any, Optional
+
+from django.conf import settings
+
+from posthog.models.group.util import get_group_by_key
+from posthog.models.group_type_mapping import get_group_types_for_project
+from posthog.models.team import Team
+
+from products.growth.backend.enrichment.writer import ORGANIZATION_GROUP_TYPE
+
+CLAY_EST_REVENUE_PROPERTY = "icp_est_revenue"
+CLAY_COMPANY_TYPE_PROPERTY = "icp_company_type"
+
+
+class OrganizationGroupTypeMissing(Exception):
+ """The internal project has no `organization` group type — a config problem, not a null input."""
+
+
[email protected](frozen=True)
+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
+
+
+def _numeric(value: Any) -> Optional[float]:
+ # Clay writes this through capture, so it can arrive as a JSON number or a numeric string;
+ # JS would coerce either in a `>` comparison, Python would raise on the string.
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, (int, float)):
+ return float(value)
+ if isinstance(value, str):
+ try:
+ return float(value.strip())
+ except ValueError:
+ return None
+ 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:
+ return int(group_type["group_type_index"])
+ # get_group_types_for_project swallows lookup failures into an empty list, so "not found"
+ # here can equally mean the mapping store was unreachable. Either way it is not a null input.
+ raise OrganizationGroupTypeMissing(f"no `{ORGANIZATION_GROUP_TYPE}` group type on project {team.project_id}")
+
+
+def read_clay_bridge_inputs(*, organization_id: str) -> ClayBridgeInputs:
+ """Fetch the Clay-written score inputs for one org. Raises if the group store can't be read."""
+ # The internal project the enrichment group properties are projected onto, and the same one
+ # the ProductLed_Outbound consumer reads them back from (ee/billing/dags/productled_outbound_targets.py).
+ team = Team.objects.get(id=settings.GROWTH_ENRICHMENT_INTERNAL_TEAM_ID)
+ group = get_group_by_key(
+ team_id=team.id,
+ group_type_index=_organization_group_type_index(team),
+ group_key=organization_id,
+ )
+ if group is None:
+ return 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/core.py b/products/growth/backend/enrichment/core.py
index 589b57296cea..dfc8ecc07115 100644
--- a/products/growth/backend/enrichment/core.py
+++ b/products/growth/backend/enrichment/core.py
@@ -5,20 +5,121 @@ orchestrator can await — the real-time Temporal workflow (fire-and-forget from
signup) today, a batch Dagster asset later. No orchestration concerns leak in here.
"""
+import dataclasses
from typing import Optional
+from django.conf import settings
+
from asgiref.sync import sync_to_async
from posthoganalytics.client import Client
+from posthog.exceptions_capture import capture_exception
+from 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.fields import EnrichmentFields
from products.growth.backend.enrichment.providers import EnrichmentProvider
+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
# Placeholder archived for a not-found when the provider hands back no response body — records
# the miss as a distinct observation, since absence at fetch time is evidence too.
_MISS_PAYLOAD = {"companyFound": False}
+def _reconstruct_fields_from_record(organization_id: str) -> Optional[EnrichmentFields]:
+ """Rebuild EnrichmentFields from the last-written record for a recheck whose provider lookup missed.
+
+ Registry keys are exactly the dataclass field names (see fields.py), so a prior write can be
+ replayed back into the same shape. Returns None when there is no prior record, or it carries
+ no provider-derived fields — same as a fresh miss. work_email is excluded: it is first-party
+ data recorded for every signup, so it neither proves a prior provider match nor belongs in
+ the group projection this replay feeds.
+ """
+ record = OrganizationEnrichment.objects.filter(organization_id=organization_id).first()
+ if record is None:
+ return None
+ fields = EnrichmentFields(
+ **{f.name: record.data.get(f.name) for f in dataclasses.fields(EnrichmentFields) if f.name != "work_email"}
+ )
+ return 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.
+
+ 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.
+ """
+ try:
+ person = get_person_by_distinct_id(team_id=settings.GROWTH_ENRICHMENT_INTERNAL_TEAM_ID, distinct_id=distinct_id)
+ except Exception as e:
+ capture_exception(e)
+ return False
+
+ 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 _score_and_mirror(
+ *,
+ organization_id: str,
+ fields: EnrichmentFields,
+ role: Optional[str],
+ 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.
+
+ 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
+ entirely 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
+ firmographic write below — see enrich_organization's docstring.
+ """
+ try:
+ clay = read_clay_bridge_inputs(organization_id=organization_id)
+ except Exception as e:
+ capture_exception(e)
+ return None, None
+
+ if not is_recheck and not clay.clay_processed:
+ return None, None
+
+ icp_score = compute_icp_score(
+ IcpScoreInputs(
+ employees=fields.headcount,
+ est_revenue=clay.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,
+ 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
+
+ return icp_score, mirror_distinct_id
+
+
async def enrich_organization(
*,
organization_id: str,
@@ -26,12 +127,26 @@ async def enrich_organization(
provider: EnrichmentProvider,
pha_client: Client,
is_recheck: bool = False,
+ role_at_organization: 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.
Every fetch is archived verbatim — including a not-found — before the live-store write.
- Returns the enrichment fields, or None when the provider has no match (nothing written to
- the live stores). The Postgres writes run via sync_to_async to bridge the async provider.
+ Returns the enrichment fields, or None when the provider has no match. The Postgres writes
+ run 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.
"""
lookup = await provider.enrich_by_domain(domain)
@@ -42,12 +157,27 @@ async def enrich_organization(
is_recheck=is_recheck,
)
- if lookup.fields is None:
- return None
+ fields = lookup.fields
+ if fields is None:
+ if not is_recheck:
+ return None
+ fields = await sync_to_async(_reconstruct_fields_from_record)(organization_id)
+ if fields is None:
+ return None
+
+ icp_score, mirror_distinct_id = await sync_to_async(_score_and_mirror)(
+ organization_id=organization_id,
+ fields=fields,
+ role=role_at_organization,
+ is_recheck=is_recheck,
+ distinct_id=distinct_id,
+ )
await sync_to_async(write_organization_enrichment)(
organization_id=organization_id,
- fields=lookup.fields,
+ fields=fields,
pha_client=pha_client,
+ icp_score=icp_score,
+ mirror_distinct_id=mirror_distinct_id,
)
return lookup.fields
diff --git a/products/growth/backend/enrichment/fields.py b/products/growth/backend/enrichment/fields.py
index ac25ef550dc0..21d4bf3fce0e 100644
--- a/products/growth/backend/enrichment/fields.py
+++ b/products/growth/backend/enrichment/fields.py
@@ -2,8 +2,9 @@
The single source of truth every enrichment writer imports, so the Postgres record,
the ClickHouse group-property projection, and the at-signup snapshot stay in lockstep.
-Provider-agnostic: providers transform their responses into this shape. icp_score is
-intentionally excluded from v0.
+Provider-agnostic: providers transform their responses into this shape. The ICP score is
+deliberately not a field here: it is derived rather than provider-reported, and the writer
+takes it separately so it stays out of the `fields_filled` launch signal.
Precedent: ee/billing/salesforce_enrichment/usage_signals.py (UsageSignals).
"""
diff --git a/products/growth/backend/enrichment/score.py b/products/growth/backend/enrichment/score.py
new file mode 100644
index 000000000000..26b7a3ad8193
--- /dev/null
+++ b/products/growth/backend/enrichment/score.py
@@ -0,0 +1,87 @@
+"""ICP scoring, transcribed from the Clay "ICP Scoring" formula column.
+
+A faithful port, not a redesign: the formula, its weights, and its quirks are owned by
+#team-demand-gen and revised separately. Scores are version-stamped so a later revision can
+recompute historical orgs from the fetch archive under a new version without disturbing this
+one. Behaviour is pinned to Clay's JS semantics — see `compute_icp_score`.
+
+Deterministic and I/O-free: callers resolve the inputs (see bridge.py for the Clay-owned ones).
+"""
+
+import dataclasses
+from typing import Optional
+
+SCORE_VERSION = "clay-parity-1"
+
+# 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.
+SCORED_COUNTRIES = frozenset(
+ {
+ "AU", "AT", "BE", "BR", "CA", "DK", "EE", "FI", "FR", "DE", "IS", "IE", "IL",
+ "IT", "JP", "LV", "LT", "NL", "NZ", "NO", "PT", "SG", "KR", "ES", "SE", "CH",
+ "GB", "US",
+ }
+) # fmt: skip
+
+ENGINEERING_LEANING_ROLES = frozenset({"engineering", "founder"})
+
+
[email protected](frozen=True)
+class IcpScoreInputs:
+ """One org's scoring inputs. Every field is optional: absence is a scoring outcome, not an error."""
+
+ employees: Optional[int] = None
+ est_revenue: Optional[float] = None
+ role: Optional[str] = None
+ github_profile_url: Optional[str] = None
+ company_type: Optional[str] = None
+ founded_year: Optional[int] = None
+ country: Optional[str] = None
+
+
+def _in_band(value: Optional[float], low: int, high: int) -> bool:
+ # Clay's `x > low && x < high` is false for a null x, where Python would raise.
+ return value is not None and low < value < high
+
+
+def _lowered(value: Optional[str]) -> Optional[str]:
+ # Clay's `x?.toLowerCase()`, including "" staying falsy rather than matching a branch.
+ return value.lower() if value else None
+
+
+def compute_icp_score(inputs: IcpScoreInputs) -> int:
+ """Score one org against the ICP, in the range -5..21 for whole-dollar revenue.
+
+ Ports Clay's null semantics exactly: numeric branches score 0 on a missing value and role
+ branches score 0 on a missing role, but a missing country lands outside the allowlist and
+ so takes the -5 penalty. That penalty-on-missing is Clay's own behaviour as of its
+ 2026-06-25 fix, not an oversight here — country fill rate therefore moves scores directly.
+ """
+ role = _lowered(inputs.role)
+ score = 0
+
+ if _in_band(inputs.employees, 500, 1001):
+ score += 3
+
+ # Two independent terms, as in Clay. They cannot both fire for a whole-dollar revenue, but
+ # a fractional one between 50000000 and 50000001 would score both — so don't fold them.
+ if _in_band(inputs.est_revenue, 1_000_000, 50_000_001):
+ score += 6
+ if _in_band(inputs.est_revenue, 50_000_000, 100_000_001):
+ score += 3
+
+ if role in ENGINEERING_LEANING_ROLES:
+ score += 6
+ elif role == "product":
+ score += 6 if inputs.github_profile_url else 3
+
+ if _lowered(inputs.company_type) == "private":
+ score += 3
+
+ if inputs.founded_year is not None and inputs.founded_year > 2014:
+ score += 3
+
+ if inputs.country not in SCORED_COUNTRIES:
+ score -= 5
+
+ return score
diff --git a/products/growth/backend/enrichment/writer.py b/products/growth/backend/enrichment/writer.py
index 338402fc4a79..fd0d0a417aa3 100644
--- a/products/growth/backend/enrichment/writer.py
+++ b/products/growth/backend/enrichment/writer.py
@@ -9,7 +9,7 @@ One writer per field: this owns the provider-derived registry keys. It never tou
`company_type_deterministic`, which the signup classifier owns.
"""
-from typing import Any
+from typing import Any, Optional
from django.db import transaction
@@ -18,6 +18,7 @@ from posthoganalytics.client import Client
from posthog.exceptions_capture import capture_exception
from products.growth.backend.enrichment.fields import EnrichmentFields
+from products.growth.backend.enrichment.score import SCORE_VERSION
from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch
ORGANIZATION_GROUP_TYPE = "organization"
@@ -41,6 +42,8 @@ def write_organization_enrichment(
organization_id: str,
fields: EnrichmentFields,
pha_client: Client,
+ icp_score: Optional[int] = None,
+ mirror_distinct_id: Optional[str] = None,
) -> None:
"""Persist enrichment to Postgres and project it onto the organization group.
@@ -48,20 +51,43 @@ def write_organization_enrichment(
any keys owned by other writers (e.g. company_type_deterministic).
- ClickHouse: project `enrichment_*` group properties via group_identify.
- No-op when there are no set fields, so a Harmonic miss leaves both stores untouched.
+ The score rides along on both stores when the caller computed one, version-stamped so a
+ later formula revision is distinguishable. `mirror_distinct_id`, when the caller passes
+ one, also sets the score on that person's profile: that is where Clay writes its own score,
+ and the live consumers (the ICP-threshold cohorts and their dashboards) read the person
+ property. The caller decides whether mirroring is safe here — this function just writes
+ what it's told; see enrich_organization for the policy (mirror is a coverage write for orgs
+ Clay didn't score itself, deferred to the delayed recheck pass, and never sent when it would
+ overwrite a Clay-written person score). The org group property is the new canonical surface
+ consumers migrate to.
+
+ No-op when there are no set fields, so a Harmonic miss leaves the stores untouched.
"""
values = fields.to_dict()
if not values:
return
+ if icp_score is not None:
+ values = {**values, "icp_score": icp_score, "icp_score_version": SCORE_VERSION}
+
_merge_into_record(organization_id, values)
+ properties = fields.to_group_properties()
+ if icp_score is not None:
+ properties = {**properties, "icp_score": icp_score, "icp_score_version": SCORE_VERSION}
+
pha_client.group_identify(
ORGANIZATION_GROUP_TYPE,
str(organization_id),
- properties=fields.to_group_properties(),
+ properties=properties,
)
+ if icp_score is not None and mirror_distinct_id:
+ pha_client.set(
+ distinct_id=mirror_distinct_id,
+ properties={"icp_score": icp_score, "icp_score_version": SCORE_VERSION},
+ )
+
def archive_provider_fetch(*, organization_id: str, provider: str, payload: dict[str, Any], is_recheck: bool) -> None:
"""Append one raw provider-response row to the fetch archive.
diff --git a/products/growth/backend/tests/test_enrichment_bridge.py b/products/growth/backend/tests/test_enrichment_bridge.py
new file mode 100644
index 000000000000..53097cf78259
--- /dev/null
+++ b/products/growth/backend/tests/test_enrichment_bridge.py
@@ -0,0 +1,88 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.models.group.group import Group
+
+from products.growth.backend.enrichment.bridge import (
+ ClayBridgeInputs,
+ OrganizationGroupTypeMissing,
+ read_clay_bridge_inputs,
+)
+
+_ORGANIZATION_GROUP_TYPES = [{"group_type": "organization", "group_type_index": 3}]
+
+
+class TestEnrichmentBridge(BaseTest):
+ def _read(self, group, group_types=_ORGANIZATION_GROUP_TYPES):
+ with (
+ patch("products.growth.backend.enrichment.bridge.Team.objects.get", return_value=self.team),
+ patch(
+ "products.growth.backend.enrichment.bridge.get_group_types_for_project",
+ return_value=group_types,
+ ),
+ patch("products.growth.backend.enrichment.bridge.get_group_by_key", return_value=group) as get_group,
+ ):
+ return read_clay_bridge_inputs(organization_id="org-1"), get_group
+
+ def test_reads_clays_columns_off_the_organization_group(self):
+ group = Group(
+ group_properties={
+ "icp_est_revenue": 25_000_000,
+ "icp_company_type": "private",
+ "icp_employees": 750,
+ }
+ )
+ inputs, get_group = self._read(group)
+
+ assert inputs == ClayBridgeInputs(
+ est_revenue=25_000_000.0,
+ company_type="private",
+ clay_processed=True,
+ )
+ assert get_group.call_args.kwargs["group_type_index"] == 3
+ assert get_group.call_args.kwargs["group_key"] == "org-1"
+
+ def test_org_with_no_group_yet_reads_as_all_absent(self):
+ inputs, _ = self._read(None)
+ assert inputs == ClayBridgeInputs()
+ assert inputs.clay_processed is False
+
+ def test_group_without_clays_columns_reads_as_all_absent(self):
+ inputs, _ = self._read(Group(group_properties={"icp_employees": 750}))
+ assert inputs == ClayBridgeInputs()
+ assert inputs.clay_processed is False
+
+ def test_clay_processed_true_even_when_the_company_type_value_itself_is_unusable(self):
+ # 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 None
+ assert inputs.clay_processed is True
+
+ @parameterized.expand(
+ [
+ ("json_number", 25_000_000, 25_000_000.0),
+ ("float", 25_000_000.5, 25_000_000.5),
+ # Clay writes through capture, so a numeric string is possible; JS would coerce it.
+ ("numeric_string", "25000000", 25_000_000.0),
+ ("padded_string", " 25000000 ", 25_000_000.0),
+ ("non_numeric_string", "unknown", None),
+ ("empty_string", "", None),
+ ("boolean", True, None),
+ ("null", None, None),
+ ]
+ )
+ def test_est_revenue_coercion(self, _name, raw, expected):
+ 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_core.py b/products/growth/backend/tests/test_enrichment_core.py
index ecfe5536def2..0f089e38d3bd 100644
--- a/products/growth/backend/tests/test_enrichment_core.py
+++ b/products/growth/backend/tests/test_enrichment_core.py
@@ -2,7 +2,9 @@ from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from asgiref.sync import async_to_sync
+from parameterized import parameterized
+from products.growth.backend.enrichment.bridge import ClayBridgeInputs
from products.growth.backend.enrichment.core import enrich_organization
from products.growth.backend.enrichment.fields import EnrichmentFields
from products.growth.backend.enrichment.providers import EnrichmentProvider, ProviderLookup
@@ -20,14 +22,33 @@ class _FakeProvider(EnrichmentProvider):
class TestEnrichmentCore(BaseTest):
- def _enrich(self, lookup: ProviderLookup, is_recheck: bool = False):
- return async_to_sync(enrich_organization)(
- organization_id=str(self.organization.id),
- domain="stripe.com",
- provider=_FakeProvider(lookup),
- pha_client=MagicMock(),
- is_recheck=is_recheck,
+ def _enrich(
+ self,
+ lookup: ProviderLookup,
+ is_recheck: bool = False,
+ role_at_organization=None,
+ clay=None,
+ pha_client=None,
+ distinct_id=None,
+ person=None,
+ ):
+ person_patch_kwargs = {"side_effect": person} if isinstance(person, Exception) else {"return_value": person}
+ clay_patch_kwargs = (
+ {"side_effect": clay} if isinstance(clay, Exception) else {"return_value": clay or ClayBridgeInputs()}
)
+ with (
+ patch("products.growth.backend.enrichment.core.read_clay_bridge_inputs", **clay_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="stripe.com",
+ provider=_FakeProvider(lookup),
+ pha_client=pha_client or MagicMock(),
+ is_recheck=is_recheck,
+ role_at_organization=role_at_organization,
+ distinct_id=distinct_id,
+ )
def test_archives_raw_payload_and_writes_live_stores_on_match(self):
company = {"companyType": "STARTUP", "funding": {"fundingStage": "SEED"}}
@@ -61,6 +82,133 @@ class TestEnrichmentCore(BaseTest):
rows = OrganizationEnrichmentFetch.objects.filter(organization=self.organization).order_by("fetched_at")
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.
+ pha_client = MagicMock()
+ fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)
+ 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),
+ 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"
+ properties = pha_client.group_identify.call_args.kwargs["properties"]
+ assert properties["icp_score"] == 21
+ 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.
+ fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)
+ self._enrich(ProviderLookup(fields=fields, raw_payload={"n": 1}), role_at_organization="engineering")
+
+ record = 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
+
+ def test_recheck_scores_unconditionally_even_when_clay_never_processed(self):
+ 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"
+ )
+
+ # No Clay columns: the revenue and company-type branches simply do not score.
+ assert OrganizationEnrichment.objects.get(organization=self.organization).data["icp_score"] == 12
+
+ 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()
+ fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)
+ self._enrich(ProviderLookup(fields=fields, raw_payload={"n": 1}), is_recheck=True, pha_client=pha_client)
+
+ pha_client.group_identify.assert_called_once()
+ pha_client.set.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("no_prior_person", None, True),
+ ("person_with_no_icp_score", MagicMock(properties={}), True),
+ ("person_with_clay_owned_score", MagicMock(properties={"icp_score": 18}), False),
+ (
+ "person_with_our_own_versioned_score",
+ MagicMock(properties={"icp_score": 9, "icp_score_version": "clay-parity-1"}),
+ True,
+ ),
+ ("person_lookup_raises", RuntimeError("personhog down"), False),
+ ]
+ )
+ def test_recheck_mirror_policy(self, _name, person, expect_mirror):
+ pha_client = MagicMock()
+ fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)
+ self._enrich(
+ ProviderLookup(fields=fields, raw_payload={"n": 1}),
+ is_recheck=True,
+ pha_client=pha_client,
+ distinct_id="signer-distinct-id",
+ person=person,
+ )
+
+ assert pha_client.set.called is expect_mirror
+
+ def test_recheck_miss_reconstructs_fields_from_the_prior_record_and_scores(self):
+ OrganizationEnrichment.objects.create(
+ organization=self.organization,
+ data={"headcount": 750, "country": "US", "founded_year": 2021, "company_type_deterministic": "yc"},
+ )
+
+ result = self._enrich(
+ ProviderLookup(fields=None, raw_payload=None), is_recheck=True, role_at_organization="engineering"
+ )
+
+ # Matches the provider-lookup miss, not the fallback score write — the workflow's
+ # matched/upgraded reporting tracks the provider lookup, not this backstop.
+ assert result is None
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data["icp_score"] == 12
+ assert record.data["company_type_deterministic"] == "yc"
+
+ def test_recheck_miss_with_no_prior_record_writes_nothing(self):
+ result = self._enrich(ProviderLookup(fields=None, raw_payload=None), is_recheck=True)
+
+ assert result is None
+ assert not OrganizationEnrichment.objects.filter(organization=self.organization).exists()
+
+ def test_recheck_miss_with_only_first_party_data_does_not_score(self):
+ # Every signup gets a work_email row before enrichment runs; it must not count as prior
+ # provider data, or every never-matched org would be scored on empty firmographics.
+ OrganizationEnrichment.objects.create(organization=self.organization, data={"work_email": True})
+ pha_client = MagicMock()
+
+ result = self._enrich(ProviderLookup(fields=None, raw_payload=None), is_recheck=True, pha_client=pha_client)
+
+ assert result is None
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert "icp_score" not in record.data
+ pha_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")
+ 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,
+ clay=RuntimeError("group store down"),
+ )
+
+ assert result is fields
+ capture_mock.assert_called_once()
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert "icp_score" not in record.data
+ assert record.data["headcount"] == 750
+
def test_archive_failure_does_not_break_enrich(self):
fields = EnrichmentFields(company_type="STARTUP")
with (
diff --git a/products/growth/backend/tests/test_enrichment_score.py b/products/growth/backend/tests/test_enrichment_score.py
new file mode 100644
index 000000000000..677fec9dd139
--- /dev/null
+++ b/products/growth/backend/tests/test_enrichment_score.py
@@ -0,0 +1,172 @@
+from parameterized import parameterized
+
+from products.growth.backend.enrichment.score import SCORE_VERSION, IcpScoreInputs, compute_icp_score
+
+
+# A country on the allowlist keeps the -5 penalty out of the way, so each case isolates its branch.
+def _inputs(**overrides) -> IcpScoreInputs:
+ return IcpScoreInputs(country="US", **overrides)
+
+
+def test_version_is_stamped():
+ assert SCORE_VERSION == "clay-parity-1"
+
+
+def test_all_inputs_missing_scores_only_the_country_penalty():
+ assert compute_icp_score(IcpScoreInputs()) == -5
+
+
+def test_no_signals_but_allowlisted_country_scores_zero():
+ assert compute_icp_score(_inputs()) == 0
+
+
+ [
+ ("below_band", 500, 0),
+ ("lower_edge", 501, 3),
+ ("upper_edge", 1000, 3),
+ ("above_band", 1001, 0),
+ ("far_below", 12, 0),
+ ("far_above", 50000, 0),
+ ("missing", None, 0),
+ ]
+)
+def test_employees_band(_name, employees, expected):
+ assert compute_icp_score(_inputs(employees=employees)) == expected
+
+
+ [
+ ("below_both", 1_000_000, 0),
+ ("lower_edge_of_first", 1_000_001, 6),
+ ("upper_edge_of_first", 50_000_000, 6),
+ ("lower_edge_of_second", 50_000_001, 3),
+ ("upper_edge_of_second", 100_000_000, 3),
+ ("above_both", 100_000_001, 0),
+ ("missing", None, 0),
+ ]
+)
+def test_est_revenue_bands(_name, est_revenue, expected):
+ assert compute_icp_score(_inputs(est_revenue=est_revenue)) == expected
+
+
+def test_est_revenue_bands_are_exclusive_for_whole_dollars():
+ # 6 and 3 are never both scored, so 6 is the most revenue alone can contribute.
+ scores = {compute_icp_score(_inputs(est_revenue=revenue)) for revenue in range(49_999_998, 50_000_004)}
+ assert scores == {6, 3}
+
+
+ [
+ ("engineering", "engineering", 6),
+ ("founder", "founder", 6),
+ ("mixed_case", "EnGiNeErInG", 6),
+ ("upper_case_founder", "FOUNDER", 6),
+ ("product", "product", 3),
+ ("marketing", "marketing", 0),
+ ("empty", "", 0),
+ ("missing", None, 0),
+ ]
+)
+def test_role_branches(_name, role, expected):
+ assert compute_icp_score(_inputs(role=role)) == expected
+
+
+ [
+ ("with_profile", "https://github.com/someone", 6),
+ ("mixed_case_role_with_profile", "https://github.com/someone", 6),
+ ("without_profile", None, 3),
+ ("empty_profile_url", "", 3),
+ ]
+)
+def test_product_role_splits_on_github_profile(_name, github_profile_url, expected):
+ assert compute_icp_score(_inputs(role="Product", github_profile_url=github_profile_url)) == expected
+
+
+def test_github_profile_only_matters_for_the_product_role():
+ assert compute_icp_score(_inputs(role="engineering", github_profile_url="https://github.com/someone")) == 6
+ assert compute_icp_score(_inputs(role="marketing", github_profile_url="https://github.com/someone")) == 0
+
+
+ [
+ ("private", "private", 3),
+ ("mixed_case", "Private", 3),
+ ("public", "public", 0),
+ ("personal", "personal", 0),
+ # Our own Harmonic-derived company_type is a raw enum in a different vocabulary, so it
+ # would never score this branch — hence the value is bridge-read from Clay.
+ ("harmonic_raw_enum", "STARTUP", 0),
+ ("empty", "", 0),
+ ("missing", None, 0),
+ ]
+)
+def test_company_type_branch(_name, company_type, expected):
+ assert compute_icp_score(_inputs(company_type=company_type)) == expected
+
+
+ [
+ ("on_the_edge", 2014, 0),
+ ("just_after", 2015, 3),
+ ("recent", 2024, 3),
+ ("older", 1998, 0),
+ ("missing", None, 0),
+ ]
+)
+def test_founded_year_branch(_name, founded_year, expected):
+ assert compute_icp_score(_inputs(founded_year=founded_year)) == expected
+
+
+ [
+ ("united_states", "US", 0),
+ ("germany", "DE", 0),
+ ("south_korea", "KR", 0),
+ ("india_not_allowlisted", "IN", -5),
+ ("missing", None, -5),
+ ("empty", "", -5),
+ # Clay matches the allowlist case-sensitively; our ISO codes are upper-cased upstream.
+ ("lower_case_is_not_allowlisted", "us", -5),
+ ]
+)
+def test_country_penalty(_name, country, expected):
+ assert compute_icp_score(IcpScoreInputs(country=country)) == expected
+
+
+def test_maximum_score():
+ inputs = IcpScoreInputs(
+ employees=750,
+ est_revenue=25_000_000,
+ role="founder",
+ company_type="private",
+ founded_year=2021,
+ country="US",
+ )
+ assert compute_icp_score(inputs) == 21
+
+
+def test_minimum_score():
+ inputs = IcpScoreInputs(
+ employees=5000,
+ est_revenue=500_000_000,
+ role="sales",
+ company_type="public",
+ founded_year=1998,
+ country="IN",
+ )
+ assert compute_icp_score(inputs) == -5
+
+
+def test_every_branch_scoring_together_with_the_country_penalty():
+ inputs = IcpScoreInputs(
+ employees=1000,
+ est_revenue=1_000_001,
+ role="product",
+ github_profile_url="https://github.com/someone",
+ company_type="private",
+ founded_year=2015,
+ country=None,
+ )
+ assert compute_icp_score(inputs) == 16