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): ICP fit score — a second score on its own icp_fit_* keys (#83944)

minekansu0f73a2c9dcfe
diff --git a/products/growth/backend/enrichment/core.py b/products/growth/backend/enrichment/core.py
index 3909b6aedfc8..58d43619640b 100644
--- a/products/growth/backend/enrichment/core.py
+++ b/products/growth/backend/enrichment/core.py
@@ -3,10 +3,15 @@
Wraps a provider lookup and the live-store write into one coroutine that any
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.
+
+Two scores ride each enrichment: the legacy clay-parity `icp_score` (score.py), still
+written because its live consumers are threshold-tuned to that scale, and the ICP fit
+score (fit_score.py) on its own `icp_fit_*` keys. The clay path retires once its
+consumers migrate to the fit keys.
"""
import dataclasses
-from typing import Optional
+from typing import Any, Optional
from django.conf import settings
@@ -19,15 +24,36 @@ from posthog.models.person.util import get_person_by_distinct_id
from products.growth.backend.enrichment.bridge import ClayBridgeInputs, read_clay_bridge_inputs
from products.growth.backend.enrichment.clearbit import ClearbitInputs, clearbit_inputs_from_person_properties
from products.growth.backend.enrichment.fields import EnrichmentFields
+from products.growth.backend.enrichment.fit_score import IcpFitResult, score_company
+from products.growth.backend.enrichment.harmonic_adapter import normalize_graphql_company
+from products.growth.backend.enrichment.icp_lists import load_active_lists
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
+from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch
# 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}
+# How many archived fetches to walk back looking for the last matched payload on a miss.
+_MATCHED_PAYLOAD_LOOKBACK = 10
+
+
[email protected](frozen=True)
+class EnrichmentOutcome:
+ """What one enrichment attempt produced.
+
+ provider_fields tracks the provider lookup itself (None on a miss, even when an
+ archived-payload fallback still scored the org) — that is what the workflow's
+ matched/upgraded reporting reads. fit is the ICP fit evaluation, present whenever fit
+ scoring ran (its status distinguishes scored/insufficient_data/not_found/disqualified);
+ None only when it degraded (no active curated-lists row, or an unexpected error).
+ """
+
+ provider_fields: Optional[EnrichmentFields] = None
+ fit: Optional[IcpFitResult] = None
+
def _persisted_score_exists(organization_id: str) -> bool:
record = OrganizationEnrichment.objects.filter(organization_id=organization_id).only("data").first()
@@ -52,6 +78,26 @@ def _reconstruct_fields_from_record(organization_id: str) -> Optional[Enrichment
return fields if fields.to_dict() 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.
+
+ The fit scorer consumes the raw payload (description, per-tag types, traction series —
+ all deliberately absent from EnrichmentFields), so on a provider miss the archive, not
+ the field record, is the scoring fallback. Public because the score backfill uses the
+ same lookback. Bounded walk: an org has a handful of fetches (signup + recheck +
+ occasional backfills), and a sentinel-only history is a real never-matched org.
+ """
+ payloads = (
+ OrganizationEnrichmentFetch.objects.filter(organization_id=organization_id)
+ .order_by("-fetched_at", "-id")
+ .values_list("payload", flat=True)[:_MATCHED_PAYLOAD_LOOKBACK]
+ )
+ for payload in payloads:
+ if isinstance(payload, dict) and payload and payload.get("companyFound") is not False:
+ return payload
+ return None
+
+
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.
@@ -93,7 +139,7 @@ def _score_and_mirror(
is_recheck: bool,
distinct_id: Optional[str],
) -> tuple[Optional[int], Optional[str]]:
- """Score one org; on the recheck, also mirror the score onto the signer's person profile.
+ """Score one org under the legacy clay formula; on the recheck, also mirror onto the person.
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
@@ -146,6 +192,45 @@ def _score_and_mirror(
return icp_score, mirror_distinct_id
+def _score_fit(
+ *,
+ organization_id: str,
+ raw_payload: Optional[dict[str, Any]],
+ role: Optional[str],
+ domain: str,
+ distinct_id: Optional[str],
+) -> tuple[Optional[IcpFitResult], Optional[str]]:
+ """Evaluate one org under the ICP fit score.
+
+ Scores from the raw provider payload — falling back to the org's last matched archived
+ payload on a miss, so one flaky lookup can't leave an org permanently score-less. No
+ active curated-lists row degrades to no evaluation at all (captured, never raised):
+ scoring against empty lists would floor three components and look like a real answer.
+
+ The fit person mirror needs no ownership guard and no person read: `icp_fit_score` is a
+ brand-new person key nothing else writes, so every evaluation mirrors blindly on every
+ attempt (unlike the clay mirror, which shares Clay's key and stays recheck-only behind
+ the ownership check) — including a score-less one, whose status overwrites a stale
+ number left by an earlier scored attempt.
+ """
+ try:
+ lists = load_active_lists()
+ if lists is None:
+ capture_exception(RuntimeError("icp_fit_no_active_lists: IcpScoringConfig has no active row"))
+ return None, None
+
+ payload = normalize_graphql_company(raw_payload)
+ if payload is None:
+ payload = normalize_graphql_company(latest_matched_payload(organization_id))
+
+ result = score_company(payload, lists=lists, role=role, domain=domain)
+ except Exception as e:
+ capture_exception(e)
+ return None, None
+
+ return result, distinct_id
+
+
async def enrich_organization(
*,
organization_id: str,
@@ -156,24 +241,26 @@ async def enrich_organization(
role_at_organization: Optional[str] = None,
geoip_country_code: Optional[str] = None,
distinct_id: Optional[str] = None,
-) -> Optional[EnrichmentFields]:
+) -> EnrichmentOutcome:
"""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. 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 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.
+ The Postgres writes run via sync_to_async to bridge the async provider.
+
+ A matched org is scored twice: under the legacy clay formula (see `_score_and_mirror`
+ for its scoring and person-mirror policy) and under the ICP fit score (`_score_fit`),
+ which also evaluates misses — from the last matched archived payload when one exists,
+ or to an honest not_found status otherwise, which is what the re-enrichment sweep
+ selects on. Either score failing degrades to writing what the rest produced, rather
+ than a silently-wrong value; 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 clay-scored anyway — first attempt or recheck alike — so an org can't end up
+ permanently score-less because of one flaky lookup. provider_fields on the returned
+ outcome 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)
@@ -187,28 +274,42 @@ async def enrich_organization(
fields = lookup.fields
if fields is None:
fields = await sync_to_async(_reconstruct_fields_from_record)(organization_id)
- if fields is None:
- return None
- if fields.country is None and geoip_country_code:
+ if fields is not None and 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.
+ # keeps the returned provider_fields 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)(
+ icp_score: Optional[int] = None
+ mirror_distinct_id: Optional[str] = None
+ if fields is not 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,
+ )
+
+ fit, fit_mirror_distinct_id = await sync_to_async(_score_fit)(
organization_id=organization_id,
- fields=fields,
+ raw_payload=lookup.raw_payload,
role=role_at_organization,
- is_recheck=is_recheck,
+ domain=domain,
distinct_id=distinct_id,
)
+ if fields is None and fit is None:
+ return EnrichmentOutcome(provider_fields=None, fit=None)
+
await sync_to_async(write_organization_enrichment)(
organization_id=organization_id,
fields=fields,
pha_client=pha_client,
icp_score=icp_score,
mirror_distinct_id=mirror_distinct_id,
+ fit=fit,
+ fit_mirror_distinct_id=fit_mirror_distinct_id,
)
- return lookup.fields
+ return EnrichmentOutcome(provider_fields=lookup.fields, fit=fit)
diff --git a/products/growth/backend/enrichment/fit_score.py b/products/growth/backend/enrichment/fit_score.py
new file mode 100644
index 000000000000..978f7161c470
--- /dev/null
+++ b/products/growth/backend/enrichment/fit_score.py
@@ -0,0 +1,244 @@
+"""The ICP fit score — encodes the Aug 2026 "who we build for" definition.
+
+Definitional score, not an MRR predictor: components are Traction (35), Capital (30),
+AIPilled (15), HeadcountGrowth (10), SoftwareRelevance (10), summing to 100. Spec:
+https://posthog.com/handbook/growth/revops/icp-scoring. Weights and rules are owned by
+RevOps and validated against a 382-company exemplar/customer set plus a 9.7k-signup
+cohort. The curated tag and investor lists ride in versioned DB rows (see icp_lists.py);
+a list update bumps the stamped `lists_version`, never SCORE_VERSION — only a formula
+change bumps SCORE_VERSION.
+
+Written to its own `icp_fit_*` key family, deliberately NOT the legacy `icp_score` keys:
+the live consumers of `icp_score` are threshold-tuned to the clay formula's -5..21 scale,
+and the clay scorer (score.py) keeps writing them until each consumer migrates. The pair
+of scores is by design — this one answers "does this company match who we build for?",
+the planned expected-revenue score answers "what is this signup likely to be worth?".
+
+Deterministic and I/O-free: consumes a Harmonic company payload in the provider's REST
+shape (snake_case, precomputed horizon blocks). Archived GraphQL payloads are normalized
+into that shape by harmonic_adapter.py. One deliberate divergence from the offline
+reference implementation, ruled by the score owner (Mine, 2026-08-19): the
+insufficient-data gate counts `investors` as a funding signal — matching the handbook
+spec and the coverage counter — so an EXISTS_BUT_UNDISCLOSED raise with a named quality
+investor scores capital 18 instead of falling out as insufficient_data.
+"""
+
+import re
+import dataclasses
+from typing import Any, Optional
+
+from products.growth.backend.enrichment.icp_lists import CuratedLists, norm
+
+SCORE_VERSION = "v0.5"
+
+STATUS_SCORED = "scored"
+STATUS_INSUFFICIENT_DATA = "insufficient_data"
+STATUS_NOT_FOUND = "not_found"
+STATUS_DISQUALIFIED = "disqualified"
+
+# Description regexes are formula, not curation: they change with SCORE_VERSION, so they
+# live here rather than in the DB-backed lists.
+SW_DESC = re.compile(
+ r"\b(software|platform|api|saas|application|developer|sdk|automat\w+|dashboard|analytics|infrastructure|integrat\w+)\b",
+ re.I,
+)
+AI_DESC = re.compile(
+ r"\b(ai|artificial intelligence|machine learning|ml|llms?|genai|generative|copilot|neural network)\b", re.I
+)
+
+# Metadata flags only — deliberately not score inputs: consulting/agencies qualify on their
+# merits (team + traffic), and .org non-profits include paying customers. Downstream teams
+# route on the flags instead.
+AGENCY_TAGS = frozenset({"consulting", "technology & digital consulting", "management & strategy consulting"})
+NONPROFIT_TAGS = frozenset({"non-profit & community organizations"})
+
+# Names at least this long may substring-match an observed investor name ("Sequoia Capital
+# India" contains "sequoia capital"); shorter names/acronyms (GV, NEA, CRV) never
+# substring-match, to avoid false hits inside unrelated words.
+QUALITY_INVESTOR_SUBSTRING_MIN_CHARS = 8
+
+
[email protected](frozen=True)
+class IcpFitResult:
+ """One org's fit evaluation. score is None unless status is scored/disqualified."""
+
+ status: str
+ score: Optional[int] = None
+ dq_reason: Optional[str] = None
+ components: Optional[dict[str, int]] = None
+ quality_investor: Optional[bool] = None
+ data_coverage: Optional[int] = None
+ low_confidence: Optional[bool] = None
+ agency_flag: Optional[bool] = None
+ nonprofit_flag: Optional[bool] = None
+ version: str = SCORE_VERSION
+ lists_version: Optional[str] = None
+
+
+def is_quality_investor(observed_name: str, quality_names: frozenset[str]) -> bool:
+ observed = norm(observed_name)
+ if observed in quality_names:
+ return True
+ return any(name in observed for name in quality_names if len(name) >= QUALITY_INVESTOR_SUBSTRING_MIN_CHARS)
+
+
+def _metric(payload: dict[str, Any], name: str, horizon: Optional[str] = None, field: str = "percent_change") -> Any:
+ metric = (payload.get("traction_metrics") or {}).get(name)
+ if not isinstance(metric, dict):
+ return None
+ if horizon is None:
+ return metric.get("latest_metric_value")
+ block = metric.get(horizon)
+ return block.get(field) if isinstance(block, dict) else None
+
+
+def score_company(
+ payload: Optional[dict[str, Any]],
+ *,
+ lists: CuratedLists,
+ role: Optional[str] = None,
+ domain: Optional[str] = None,
+) -> IcpFitResult:
+ """Score one company payload (REST shape — see module docstring) against the fit rules.
+
+ `role` is the signup's own role_at_organization answer (production-side, not in
+ Harmonic) and `domain` is the signup email domain (for the .ai TLD signal) — never the
+ payload's own website domain, which can be a different registrant.
+
+ Statuses: a student signup is disqualified before the payload is even consulted (we
+ know the answer regardless of enrichment); a missing/unmatched payload is not_found; a
+ matched but empty-shell profile is insufficient_data (no numeric score — "no data yet"
+ must never read as "evaluated and low"); everything else is scored 0–100.
+ """
+ if (role or "").strip().lower() == "student":
+ return IcpFitResult(status=STATUS_DISQUALIFIED, score=0, dq_reason="role=student", lists_version=lists.version)
+
+ if not payload or not isinstance(payload, dict):
+ return IcpFitResult(status=STATUS_NOT_FOUND, lists_version=lists.version)
+
+ tags = {norm(tag.get("display_value")) for tag in (payload.get("tags_v2") or []) if isinstance(tag, dict)}
+ tag_types = {tag.get("type") for tag in (payload.get("tags_v2") or []) if isinstance(tag, dict)}
+
+ # Hard DQ on company_type, not market tags: tags describe who a company SELLS TO
+ # (education-market startups carry "Schools" tags), while company_type=SCHOOL marks
+ # actual institutions.
+ if payload.get("company_type") == "SCHOOL":
+ return IcpFitResult(
+ status=STATUS_DISQUALIFIED, score=0, dq_reason="company_type=SCHOOL", lists_version=lists.version
+ )
+
+ funding = payload.get("funding") or {}
+ web_traffic = _metric(payload, "web_traffic", None)
+ headcount = payload.get("headcount") or _metric(payload, "headcount", None)
+ # Investors count as a funding signal here (matching the handbook and the coverage
+ # counter below): a raise Harmonic knows only through its investor list is still a
+ # profile worth scoring, not an empty shell.
+ if not any(
+ [headcount, funding.get("funding_total"), funding.get("investors"), payload.get("tags_v2"), web_traffic]
+ ):
+ return IcpFitResult(status=STATUS_INSUFFICIENT_DATA, lists_version=lists.version)
+
+ # Momentum horizons (validated 2026-08-13): traffic 90d (best discriminator; 365d is
+ # ~random), headcount 180d (90d is ±1-hire noise on small teams; 365d misses
+ # inflections). Thresholds are rescaled per horizon.
+ traffic_growth_90d = _metric(payload, "web_traffic", "90d_ago")
+ headcount_growth_180d = _metric(payload, "headcount", "180d_ago")
+ headcount_adds_180d = _metric(payload, "headcount", "180d_ago", "change")
+ engineering_headcount = _metric(payload, "headcount_engineering", None)
+ investors = [
+ investor.get("name") or "" for investor in (funding.get("investors") or []) if isinstance(investor, dict)
+ ]
+ funding_total = funding.get("funding_total") or 0
+
+ traffic_level = (
+ 15
+ if (web_traffic or 0) >= 100_000
+ else 10
+ if (web_traffic or 0) >= 10_000
+ else 5
+ if (web_traffic or 0) >= 1_000
+ else 0
+ )
+ traffic_growth = 0
+ if (web_traffic or 0) >= 5_000: # growth only counted above a minimum base: small-base %s invert the signal
+ traffic_growth = (
+ 20
+ if (traffic_growth_90d or 0) >= 40
+ else 12
+ if (traffic_growth_90d or 0) >= 15
+ else 5
+ if (traffic_growth_90d or 0) > 0
+ else 0
+ )
+ traction = traffic_level + traffic_growth
+
+ quality = (
+ "YC_BATCH" in tag_types # matched on tag type so future batches qualify without a list update
+ or bool(tags & lists.capital_quality)
+ or any(is_quality_investor(investor, lists.quality_investors) for investor in investors)
+ )
+ # EXISTS_BUT_UNDISCLOSED implies some funding exists -> base capital tier.
+ undisclosed = payload.get("funding_attribute_null_status") == "EXISTS_BUT_UNDISCLOSED"
+ capital = (
+ 20
+ if funding_total >= 10_000_000
+ else 14
+ if funding_total >= 2_000_000
+ else 8
+ if (funding_total > 0 or undisclosed)
+ else 0
+ )
+ capital = min(30, capital + (10 if quality else 0))
+
+ description = payload.get("description") or payload.get("short_description") or ""
+ # AI tags, AI language in the description, or a .ai signup domain all qualify in full.
+ ai_pilled = (
+ 15
+ if (tags & lists.ai_positive or (description and AI_DESC.search(description)) or (domain or "").endswith(".ai"))
+ else 0
+ )
+
+ headcount_growth = (
+ 10
+ if (headcount_growth_180d or 0) >= 15
+ else 6
+ if ((headcount_growth_180d or 0) >= 5 or (headcount_adds_180d or 0) >= 3)
+ else 3
+ if (headcount_growth_180d or 0) > 0
+ else 0
+ )
+
+ software_relevance = (
+ 10
+ if (engineering_headcount or 0) > 0
+ else 7
+ if (tags & lists.software_positive or SW_DESC.search(description))
+ else 0
+ )
+
+ coverage = sum(
+ [
+ bool(headcount and headcount >= 1),
+ bool((web_traffic or 0) >= 100),
+ bool(funding_total > 0 or investors),
+ bool(payload.get("tags_v2")),
+ ]
+ )
+
+ return IcpFitResult(
+ status=STATUS_SCORED,
+ score=traction + capital + ai_pilled + headcount_growth + software_relevance,
+ components={
+ "traction": traction,
+ "capital": capital,
+ "ai_pilled": ai_pilled,
+ "headcount_growth": headcount_growth,
+ "software_relevance": software_relevance,
+ },
+ quality_investor=quality,
+ data_coverage=coverage,
+ low_confidence=coverage <= 1,
+ agency_flag=bool(tags & AGENCY_TAGS),
+ nonprofit_flag=bool(tags & NONPROFIT_TAGS),
+ lists_version=lists.version,
+ )
diff --git a/products/growth/backend/enrichment/harmonic_adapter.py b/products/growth/backend/enrichment/harmonic_adapter.py
new file mode 100644
index 000000000000..98aaa5db89f5
--- /dev/null
+++ b/products/growth/backend/enrichment/harmonic_adapter.py
@@ -0,0 +1,136 @@
+"""Normalize an archived Harmonic GraphQL company payload into the REST shape score_v05 consumes.
+
+The fetch archive (OrganizationEnrichmentFetch.payload) holds GraphQL
+`enrichCompanyByIdentifiers.company` responses verbatim: camelCase keys and raw
+tractionMetrics time series. Harmonic's REST API — which the V0.5 rules were validated
+against — precomputes horizon blocks (`90d_ago.percent_change` etc.) that the GraphQL
+schema does not expose, so this module derives them from the archived series instead.
+
+Kept separate from the scorer so the scorer stays a line-for-line port of the validated
+reference, and separate from transform.py because the scorer needs payload fields
+(description, per-tag types, the series) that deliberately never became EnrichmentFields.
+
+As-of semantics for growth, matching the validated backtest derivation: the value at a
+horizon is the last observation at or before that point — no interpolation, no peeking
+forward — and growth is percent change from that value to the latest observation. A
+series too sparse to cover the horizon yields None (unknown), never 0.
+"""
+
+import datetime as dt
+from typing import Any, Optional
+
+WEB_TRAFFIC_GROWTH_DAYS = 90
+HEADCOUNT_GROWTH_DAYS = 180
+
+
+def _dict(value: Any) -> dict[str, Any]:
+ return value if isinstance(value, dict) else {}
+
+
+def _list(value: Any) -> list[Any]:
+ return value if isinstance(value, list) else []
+
+
+def _parse_series(metric_block: dict[str, Any]) -> list[tuple[dt.datetime, float]]:
+ """Parse a GraphQL tractionMetrics series into sorted (timestamp, value) pairs."""
+ points = []
+ for point in _list(metric_block.get("metrics")):
+ point = _dict(point)
+ timestamp, value = point.get("timestamp"), point.get("metricValue")
+ if not isinstance(timestamp, str) or not isinstance(value, (int, float)):
+ continue
+ try:
+ parsed = dt.datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
+ except ValueError:
+ continue
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=dt.UTC)
+ points.append((parsed, float(value)))
+ points.sort(key=lambda pair: pair[0])
+ return points
+
+
+def _value_asof(points: list[tuple[dt.datetime, float]], when: Optional[dt.datetime]) -> Optional[float]:
+ """Last observation at or before `when` (no interpolation, no peeking forward)."""
+ if not points:
+ return None
+ if when is None:
+ return points[-1][1]
+ eligible = [value for timestamp, value in points if timestamp <= when]
+ return eligible[-1] if eligible else None
+
+
+def _growth(points: list[tuple[dt.datetime, float]], days: int) -> tuple[Optional[float], Optional[int]]:
+ """(percent_change, absolute change) over the `days` window ending at the latest observation."""
+ if not points:
+ return None, None
+ end_at = points[-1][0]
+ end = _value_asof(points, end_at)
+ start = _value_asof(points, end_at - dt.timedelta(days=days))
+ if end is None or start is None or start <= 0:
+ return None, None
+ return round((end - start) / start * 100.0, 1), int(end - start)
+
+
+def _latest(metric_block: dict[str, Any]) -> Optional[int]:
+ value = metric_block.get("latestMetricValue")
+ return int(value) if isinstance(value, (int, float)) else None
+
+
+def _traction_metric(traction: dict[str, Any], graphql_name: str, growth_days: Optional[int]) -> dict[str, Any]:
+ block = _dict(traction.get(graphql_name))
+ normalized: dict[str, Any] = {"latest_metric_value": _latest(block)}
+ if growth_days is not None:
+ percent_change, change = _growth(_parse_series(block), growth_days)
+ normalized[f"{growth_days}d_ago"] = {"percent_change": percent_change, "change": change}
+ return normalized
+
+
+def _investors(investors: Any) -> list[dict[str, Any]]:
+ # Company entries carry `name`, Person (angel) entries carry `fullName`; fold to `name`,
+ # which is the key the scorer reads.
+ return [
+ {"name": name}
+ for investor in _list(investors)
+ if isinstance(investor, dict) and isinstance(name := investor.get("name") or investor.get("fullName"), str)
+ ]
+
+
+def _tags_v2(tags_v2: Any) -> list[dict[str, Any]]:
+ return [
+ {"display_value": tag.get("displayValue"), "type": tag.get("type")}
+ for tag in _list(tags_v2)
+ if isinstance(tag, dict)
+ ]
+
+
+def normalize_graphql_company(payload: Optional[dict[str, Any]]) -> Optional[dict[str, Any]]:
+ """Map an archived GraphQL company payload to the scorer's REST-ish shape.
+
+ Returns None for anything that is not a matched company — a missing payload, the
+ archived miss sentinel ({"companyFound": False}), or an empty dict — so callers can
+ hand the result straight to score_company, which reads None as not_found.
+ """
+ if not payload or not isinstance(payload, dict) or payload.get("companyFound") is False:
+ return None
+
+ funding = _dict(payload.get("funding"))
+ traction = _dict(payload.get("tractionMetrics"))
+ headcount = payload.get("headcount")
+
+ return {
+ "company_type": payload.get("companyType"),
+ "headcount": int(headcount) if isinstance(headcount, (int, float)) else None,
+ "description": payload.get("description"),
+ "funding": {
+ "funding_total": funding.get("fundingTotal"),
+ "investors": _investors(funding.get("investors")),
+ },
+ "funding_attribute_null_status": payload.get("fundingAttributeNullStatus"),
+ "tags_v2": _tags_v2(payload.get("tagsV2")),
+ "traction_metrics": {
+ "web_traffic": _traction_metric(traction, "webTraffic", WEB_TRAFFIC_GROWTH_DAYS),
+ "headcount": _traction_metric(traction, "headcount", HEADCOUNT_GROWTH_DAYS),
+ "headcount_engineering": _traction_metric(traction, "headcountEngineering", None),
+ },
+ }
diff --git a/products/growth/backend/enrichment/snapshot.py b/products/growth/backend/enrichment/snapshot.py
index e1826d15078e..660120dacff3 100644
--- a/products/growth/backend/enrichment/snapshot.py
+++ b/products/growth/backend/enrichment/snapshot.py
@@ -17,7 +17,7 @@ SNAPSHOT_EVENT_NAME = "enrichment_snapshot_at_signup"
SNAPSHOT_PROPERTY_SUFFIX = "_at_signup"
[email protected](frozen=True)
class SignupEnrichmentSnapshot:
"""PII-light firmographic values captured at signup.
@@ -33,8 +33,13 @@ class SignupEnrichmentSnapshot:
founded_year: Optional[int] = None
funding_stage: Optional[str] = None
is_yc_company: Optional[bool] = None
- icp_score: Optional[int] = None
- icp_score_version: Optional[str] = None
+ # The fit evaluation as it stood at signup. A numeric score snapshots with its version;
+ # a score-less evaluation snapshots the status alone, so "insufficient at signup" stays
+ # distinguishable from "never evaluated" forever. (The legacy clay icp_score was never
+ # fed into the snapshot, so these are the first score keys the event actually carries.)
+ icp_fit_score: Optional[int] = None
+ icp_fit_version: Optional[str] = None
+ icp_fit_status: Optional[str] = None
def to_event_properties(self) -> dict[str, Any]:
"""Return the snapshot as `*_at_signup` event properties, dropping unset values."""
diff --git a/products/growth/backend/enrichment/writer.py b/products/growth/backend/enrichment/writer.py
index fd0d0a417aa3..668ca09c65d6 100644
--- a/products/growth/backend/enrichment/writer.py
+++ b/products/growth/backend/enrichment/writer.py
@@ -7,6 +7,10 @@ projection. The at-signup person-event snapshot is a separate write-once store.
One writer per field: this owns the provider-derived registry keys. It never touches
`company_type_deterministic`, which the signup classifier owns.
+
+Two score families ride along: the legacy clay-parity `icp_score` (kept while its
+threshold-tuned consumers migrate) and the ICP fit score on its own `icp_fit_*` keys.
+The two never share a key, so neither can misattribute the other's values.
"""
from typing import Any, Optional
@@ -18,32 +22,96 @@ 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.fit_score import IcpFitResult
from products.growth.backend.enrichment.score import SCORE_VERSION
from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch
ORGANIZATION_GROUP_TYPE = "organization"
+# Every fit key tied to one evaluation's numeric outcome. An evaluation that doesn't
+# produce one of these strips it, so the record never carries a value the current
+# evaluation didn't produce (e.g. components surviving a later disqualification).
+_FIT_NUMERIC_KEYS = ["icp_fit_score", "icp_fit_components", "icp_fit_flags", "icp_fit_dq_reason"]
+
-def _merge_into_record(organization_id: str, values: dict[str, Any]) -> None:
+def _merge_into_record(organization_id: str, values: dict[str, Any], remove: Optional[list[str]] = None) -> None:
"""Row-locked read/merge/save into OrganizationEnrichment.data.
select_for_update serializes concurrent writers on the same org (the request-path
signup write and the fire-and-forget provider write). Without the lock they read the
same snapshot and the later save clobbers the other's keys, dropping enrichment data.
+
+ `remove` deletes keys in the same locked write — used to strip stale fit keys when a
+ new evaluation supersedes them.
"""
with transaction.atomic():
record, _ = OrganizationEnrichment.objects.select_for_update().get_or_create(organization_id=organization_id)
- record.data = {**record.data, **values}
+ merged = {**record.data, **values}
+ for key in remove or []:
+ merged.pop(key, None)
+ record.data = merged
record.save(update_fields=["data", "updated_at"])
+def _fit_record_writes(fit: IcpFitResult) -> tuple[dict[str, Any], list[str]]:
+ """The Postgres (data) writes and key removals for one fit evaluation.
+
+ Removals are derived from the keys this evaluation actually produced, so a scored org
+ that is later disqualified loses its stale components and flags, and a score-less
+ evaluation (insufficient_data / not_found) strips every numeric key — the status is
+ the result.
+ """
+ values: dict[str, Any] = {"icp_fit_status": fit.status, "icp_fit_version": fit.version}
+ if fit.lists_version:
+ values["icp_fit_lists_version"] = fit.lists_version
+
+ if fit.score is not None:
+ values["icp_fit_score"] = fit.score
+ if fit.components:
+ values["icp_fit_components"] = fit.components
+ flags = {
+ key: value
+ for key, value in {
+ "quality_investor": fit.quality_investor,
+ "data_coverage": fit.data_coverage,
+ "low_confidence": fit.low_confidence,
+ "agency_flag": fit.agency_flag,
+ "nonprofit_flag": fit.nonprofit_flag,
+ }.items()
+ if value is not None
+ }
+ if flags:
+ values["icp_fit_flags"] = flags
+ if fit.dq_reason:
+ values["icp_fit_dq_reason"] = fit.dq_reason
+
+ return values, [key for key in _FIT_NUMERIC_KEYS if key not in values]
+
+
+def _fit_projection(fit: IcpFitResult) -> dict[str, Any]:
+ """The fit projection for one evaluation — shared by the ClickHouse group properties
+ and the person mirror, since neither store can delete a stale key.
+
+ A score-less evaluation writes only the status key: pairing a fresh `icp_fit_version`
+ with a stale numeric `icp_fit_score` would misattribute that number to the new
+ evaluation. The (score, version) pair therefore always describes the same evaluation,
+ and `icp_fit_status` is the consumer's guard — a score is current only when status is
+ scored/disqualified.
+ """
+ if fit.score is None:
+ return {"icp_fit_status": fit.status}
+ return {"icp_fit_score": fit.score, "icp_fit_version": fit.version, "icp_fit_status": fit.status}
+
+
def write_organization_enrichment(
*,
organization_id: str,
- fields: EnrichmentFields,
+ fields: Optional[EnrichmentFields],
pha_client: Client,
icp_score: Optional[int] = None,
mirror_distinct_id: Optional[str] = None,
+ fit: Optional[IcpFitResult] = None,
+ fit_mirror_distinct_id: Optional[str] = None,
) -> None:
"""Persist enrichment to Postgres and project it onto the organization group.
@@ -51,36 +119,51 @@ def write_organization_enrichment(
any keys owned by other writers (e.g. company_type_deterministic).
- ClickHouse: project `enrichment_*` group properties via group_identify.
- 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.
+ The legacy clay 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 that score on the person's profile: that is
+ where Clay writes its own score, and the legacy 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 (never sent when it would overwrite a Clay-written person score).
+
+ The fit evaluation writes its own `icp_fit_*` family — status always, numeric keys
+ only when this evaluation produced them (see _fit_record_writes) — and mirrors the
+ same (score, version, status) or status-only shape onto the person via
+ `fit_mirror_distinct_id`, a blind write since nothing else owns that key. Any of the
+ three groups (fields / clay score / fit) may be absent: a fields-only write is the
+ field backfill, a fit-only write (fields=None) is the score backfill and the
+ miss-path status stamp.
+
+ No-op when there are no set fields and no scores, so a Harmonic miss with fit scoring
+ degraded leaves the stores untouched.
"""
- values = fields.to_dict()
- if not values:
- return
+ values = fields.to_dict() if fields is not None else {}
+ remove: list[str] = []
if icp_score is not None:
values = {**values, "icp_score": icp_score, "icp_score_version": SCORE_VERSION}
+ if fit is not None:
+ fit_values, remove = _fit_record_writes(fit)
+ values = {**values, **fit_values}
- _merge_into_record(organization_id, values)
+ if not values:
+ return
+
+ _merge_into_record(organization_id, values, remove=remove)
- properties = fields.to_group_properties()
+ properties = fields.to_group_properties() if fields is not None else {}
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=properties,
- )
+ if fit is not None:
+ properties = {**properties, **_fit_projection(fit)}
+
+ if properties:
+ pha_client.group_identify(
+ ORGANIZATION_GROUP_TYPE,
+ str(organization_id),
+ properties=properties,
+ )
if icp_score is not None and mirror_distinct_id:
pha_client.set(
@@ -88,6 +171,12 @@ def write_organization_enrichment(
properties={"icp_score": icp_score, "icp_score_version": SCORE_VERSION},
)
+ if fit is not None and fit_mirror_distinct_id:
+ pha_client.set(
+ distinct_id=fit_mirror_distinct_id,
+ properties=_fit_projection(fit),
+ )
+
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.
@@ -106,13 +195,19 @@ def archive_provider_fetch(*, organization_id: str, provider: str, payload: dict
capture_exception(e)
-def record_signup_work_email(*, organization_id: str, work_email: bool) -> None:
- """Persist whether the signup used a work email (vs a generic personal domain).
+def record_signup_work_email(*, organization_id: str, work_email: bool, signup_role: Optional[str] = None) -> None:
+ """Persist the signup's work-email signal, and its role answer when one was given.
First-party data known synchronously at signup, so it is written from the request
path for every signup — including personal-domain ones that never get a provider
- lookup. Postgres only for v0: work_email is never set by the provider transform, and
- personal domains get no provider write, so there's no group projection here. Projecting
- it onto the organization group is deferred until a consumer needs the group property.
+ lookup. Postgres only for v0: neither key is set by the provider transform, and
+ personal domains get no provider write, so there's no group projection here.
+
+ signup_role makes the fit score's student disqualification replayable from the record
+ by any later batch recompute — the role is otherwise only ever in flight on the
+ workflow inputs.
"""
- _merge_into_record(organization_id, {"work_email": work_email})
+ values: dict[str, Any] = {"work_email": work_email}
+ if signup_role and signup_role.strip():
+ values["signup_role"] = signup_role.strip().lower()
+ _merge_into_record(organization_id, values)
diff --git a/products/growth/backend/management/commands/backfill_icp_fit_scores.py b/products/growth/backend/management/commands/backfill_icp_fit_scores.py
new file mode 100644
index 000000000000..c8ab59cef8aa
--- /dev/null
+++ b/products/growth/backend/management/commands/backfill_icp_fit_scores.py
@@ -0,0 +1,298 @@
+"""Recompute the ICP fit score for every org from its latest archived provider payload.
+
+The score-side sibling of backfill_enrichment_fields (which owns the firmographic keys and
+never touches any score): this command writes ONLY the icp_fit_* keys — a fit-only
+write_organization_enrichment call — so the two backfills stay independently re-runnable,
+and the legacy clay icp_score is never touched here.
+No new Harmonic calls: everything replays from the fetch archive. A sentinel (miss) archive
+row scores as not_found, which is recorded rather than skipped so the re-enrichment sweep
+can find those orgs.
+
+Role for the student disqualification comes from the record's signup_role key, persisted at
+signup since the fit score shipped; historical orgs without it simply score without the
+student DQ.
+
+--parity is the offline validation harness: score payload files from disk against an
+expected CSV (the RevOps validation set) with no DB writes, exiting non-zero on any
+mismatch. Payloads may be REST-shaped (scored directly; matched-ness = payload has an `id`)
+or GraphQL-shaped (normalized through harmonic_adapter first, like production), detected
+per payload. Lists come from --tags-csv/--investors-csv when given (no DB dependency),
+else from the active IcpScoringConfig row.
+"""
+
+import csv
+import glob
+import gzip
+import json
+import time
+import statistics
+from pathlib import Path
+from typing import Any, Optional
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+
+from posthog.ph_client import get_regional_ph_client
+from posthog.utils import get_instance_region
+
+from products.growth.backend.enrichment import icp_lists as icp_lists_module
+from products.growth.backend.enrichment.core import latest_matched_payload
+from products.growth.backend.enrichment.fit_score import IcpFitResult, score_company
+from products.growth.backend.enrichment.harmonic_adapter import normalize_graphql_company
+from products.growth.backend.enrichment.icp_lists import (
+ CuratedLists,
+ load_active_lists,
+ norm,
+ parse_investors_csv_rows,
+ parse_tags_csv_rows,
+)
+from products.growth.backend.enrichment.labels import recent_latest_fetches_qs, signup_domain_for_organization
+from products.growth.backend.enrichment.writer import write_organization_enrichment
+from products.growth.backend.models import OrganizationEnrichment
+
+
+class _Stats:
+ def __init__(self) -> None:
+ self.statuses: dict[str, int] = {}
+ self.scores: list[int] = []
+
+ def add(self, result: IcpFitResult) -> None:
+ self.statuses[result.status] = self.statuses.get(result.status, 0) + 1
+ if result.status == "scored" and result.score is not None:
+ self.scores.append(result.score)
+
+ def summary(self) -> str:
+ total = sum(self.statuses.values())
+ lines = [f"evaluated {total}"]
+ for status, count in sorted(self.statuses.items(), key=lambda kv: -kv[1]):
+ lines.append(f" {status}: {count} ({count / total:.1%})")
+ if self.scores:
+ ordered = sorted(self.scores)
+ share = lambda threshold: sum(1 for s in ordered if s >= threshold) / len(ordered) # noqa: E731
+ lines.append(
+ f" scored: median {statistics.median(ordered):.0f} | "
+ f">=40 {share(40):.1%} | >=50 {share(50):.1%} | >=60 {share(60):.1%} | >=70 {share(70):.1%}"
+ )
+ return "\n".join(lines)
+
+
+def _normalize_any_payload(payload: Any) -> Optional[dict[str, Any]]:
+ """Accept either archive/GraphQL shape (normalized) or REST shape (passed through)."""
+ if not isinstance(payload, dict) or not payload:
+ return None
+ if "traction_metrics" in payload or "tags_v2" in payload or "id" in payload:
+ # REST shape: matched-ness is the `id` key, per the validation reference.
+ return payload if payload.get("id") else None
+ return normalize_graphql_company(payload)
+
+
+def _lists_from_csvs(tags_csv: str, investors_csv: str) -> CuratedLists:
+ def read(path: str) -> list[dict[str, Any]]:
+ with open(path, newline="", encoding="utf-8-sig") as handle:
+ return list(csv.DictReader(handle))
+
+ tags = parse_tags_csv_rows(read(tags_csv))
+ investors = parse_investors_csv_rows(read(investors_csv))
+ buckets: dict[str, set[str]] = {bucket: set() for bucket in icp_lists_module.TAG_BUCKETS}
+ for row in tags:
+ for bucket in row["recommendation"].split("+"):
+ if bucket in buckets:
+ buckets[bucket].add(norm(row["tag"]))
+ names: set[str] = set()
+ for row in investors:
+ names.add(norm(row["investor"]))
+ names.update(norm(alias) for alias in row["aliases"])
+ return CuratedLists(
+ version="csv-local",
+ capital_quality=frozenset(buckets["capital_quality"]),
+ ai_positive=frozenset(buckets["ai_positive"]),
+ software_positive=frozenset(buckets["software_positive"]),
+ software_negative=frozenset(buckets["software_negative"]),
+ dq=frozenset(buckets["dq"]),
+ quality_investors=frozenset(names),
+ )
+
+
+def _iter_parity_payloads(path: str):
+ """Yield (domain, payload) from a JSONL(.gz) file or a directory of per-domain JSON files."""
+ p = Path(path)
+ if p.is_dir():
+ for fp in sorted(glob.glob(str(p / "*.json"))):
+ doc = json.load(open(fp))
+ yield (doc.get("_domain") or Path(fp).stem).lower(), doc.get("payload")
+ return
+ opener = gzip.open if path.endswith(".gz") else open
+ with opener(path, "rt") as handle:
+ for line in handle:
+ line = line.strip()
+ if not line:
+ continue
+ doc = json.loads(line)
+ domain = (doc.get("domain") or doc.get("_domain") or "").lower()
+ yield domain, doc.get("company") if "company" in doc else doc.get("payload")
+
+
+class Command(BaseCommand):
+ help = (
+ "Recompute ICP fit scores from each organization's latest archived provider fetch "
+ "and write the score keys (fit-only; firmographic fields are "
+ "backfill_enrichment_fields' job). --parity scores payload files from disk against "
+ "an expected CSV instead, with no writes."
+ )
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--limit", type=int, default=None, help="Backfill at most this many organizations")
+ parser.add_argument("--delay", type=float, default=0.05, help="Seconds to sleep between writes")
+ parser.add_argument("--dry-run", action="store_true", help="Report what would be written without writing")
+ parser.add_argument("--stats", action="store_true", help="Print the score distribution summary at the end")
+ parser.add_argument("--parity", action="store_true", help="Offline parity mode: no DB writes")
+ parser.add_argument("--payloads", help="Parity: JSONL(.gz) file or directory of payload JSON files")
+ parser.add_argument("--expected", help="Parity: CSV of expected score/status per domain")
+ parser.add_argument("--tags-csv", help="Score with lists parsed from this tags export instead of the DB row")
+ parser.add_argument("--investors-csv", help="Goes with --tags-csv")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ if options["parity"]:
+ self._run_parity(options)
+ return
+ self._run_backfill(options)
+
+ # ---------- backfill ----------
+
+ def _load_lists(self, options: dict[str, Any]) -> CuratedLists:
+ if options.get("tags_csv") or options.get("investors_csv"):
+ if not (options.get("tags_csv") and options.get("investors_csv")):
+ raise CommandError("--tags-csv and --investors-csv must be given together")
+ return _lists_from_csvs(options["tags_csv"], options["investors_csv"])
+ lists = load_active_lists()
+ if lists is None:
+ raise CommandError(
+ "No active IcpScoringConfig row. Seed one with sync_icp_scoring_lists --activate "
+ "(or pass --tags-csv/--investors-csv)."
+ )
+ return lists
+
+ def _run_backfill(self, options: dict[str, Any]) -> None:
+ if get_instance_region() not in ("US", "EU"):
+ raise CommandError("Signup enrichment is Cloud-only; refusing to backfill in this region")
+
+ limit: int | None = options["limit"]
+ delay: float = options["delay"]
+ dry_run: bool = options["dry_run"]
+ if limit is not None and limit < 1:
+ raise CommandError("--limit must be a positive integer")
+ if delay < 0:
+ raise CommandError("--delay must be >= 0")
+
+ lists = self._load_lists(options)
+ pha_client = get_regional_ph_client()
+ if pha_client is None:
+ raise CommandError("no PostHog client for this instance's region; refusing to backfill")
+ stats = _Stats()
+
+ fetches = recent_latest_fetches_qs().select_related("organization")
+ if limit is not None:
+ fetches = fetches[:limit]
+
+ try:
+ considered = written = skipped_org_gone = 0
+ for fetch in fetches.iterator():
+ considered += 1
+ try:
+ organization = fetch.organization
+ except Exception:
+ organization = None
+ if organization is None:
+ # db_constraint=False allows orphan archive rows after org deletion; a score
+ # write (and its group projection) for a dead org is pointless.
+ skipped_org_gone += 1
+ continue
+
+ domain = signup_domain_for_organization(organization)
+ record = OrganizationEnrichment.objects.filter(organization_id=fetch.organization_id).first()
+ role = record.data.get("signup_role") if record else None
+
+ payload = _normalize_any_payload(fetch.payload)
+ if payload is None:
+ # Same lookback the live path uses: the latest fetch alone can be a flaky
+ # miss even when an earlier one matched.
+ payload = _normalize_any_payload(latest_matched_payload(str(fetch.organization_id)))
+ result = score_company(payload, lists=lists, role=role, domain=domain)
+ stats.add(result)
+
+ if dry_run:
+ written += 1
+ self.stdout.write(f"would write {fetch.organization_id}: {result.status} score={result.score}")
+ continue
+
+ write_organization_enrichment(
+ organization_id=str(fetch.organization_id), fields=None, pha_client=pha_client, fit=result
+ )
+ written += 1
+ self.stdout.write(f"wrote {fetch.organization_id}: {result.status} score={result.score}")
+ if delay:
+ time.sleep(delay)
+ finally:
+ pha_client.shutdown()
+
+ verb = "would write" if dry_run else "wrote"
+ self.stdout.write(
+ self.style.SUCCESS(f"considered {considered}, {verb} {written}, skipped_org_gone {skipped_org_gone}")
+ )
+ if options["stats"]:
+ self.stdout.write(stats.summary())
+
+ # ---------- parity ----------
+
+ _PARITY_COMPONENTS = ("traction", "capital", "ai_pilled", "headcount_growth", "software_relevance")
+
+ def _run_parity(self, options: dict[str, Any]) -> None:
+ if not options.get("payloads"):
+ raise CommandError("--parity requires --payloads")
+ lists = self._load_lists(options)
+
+ expected: dict[str, dict[str, str]] = {}
+ if options.get("expected"):
+ with open(options["expected"], newline="", encoding="utf-8-sig") as handle:
+ for row in csv.DictReader(handle):
+ expected[row["domain"].strip().lower()] = row
+
+ stats = _Stats()
+ mismatches = 0
+ compared = 0
+ for domain, raw_payload in _iter_parity_payloads(options["payloads"]):
+ payload = _normalize_any_payload(raw_payload)
+ result = score_company(payload, lists=lists, domain=domain)
+ stats.add(result)
+ want = expected.get(domain)
+ if want is None:
+ continue
+ compared += 1
+ diffs = self._parity_diffs(want, result)
+ if diffs:
+ mismatches += 1
+ self.stdout.write(f"MISMATCH {domain}: " + ", ".join(diffs))
+
+ self.stdout.write(stats.summary())
+ if expected:
+ self.stdout.write(f"compared {compared} against expected; mismatches {mismatches}")
+ if mismatches:
+ raise CommandError(f"parity failed: {mismatches} mismatches")
+ self.stdout.write(self.style.SUCCESS("parity passed"))
+
+ def _parity_diffs(self, want: dict[str, str], result: IcpFitResult) -> list[str]:
+ diffs = []
+ want_score = want.get("score", "")
+ got_score = "" if result.score is None else str(result.score)
+ if want_score != got_score:
+ diffs.append(f"score want={want_score!r} got={got_score!r}")
+ if want.get("status", "") != result.status:
+ diffs.append(f"status want={want.get('status')!r} got={result.status!r}")
+ components = result.components or {}
+ for key in self._PARITY_COMPONENTS:
+ want_value = want.get(key, "")
+ if want_value == "" and result.status != "scored":
+ continue
+ got_value = "" if key not in components else str(components[key])
+ if want_value != got_value:
+ diffs.append(f"{key} want={want_value!r} got={got_value!r}")
+ return diffs
diff --git a/products/growth/backend/temporal/signup_enrichment/tests/test_activity.py b/products/growth/backend/temporal/signup_enrichment/tests/test_activity.py
index 1b9dac9addee..1174638b16cd 100644
--- a/products/growth/backend/temporal/signup_enrichment/tests/test_activity.py
+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_activity.py
@@ -7,7 +7,13 @@ from unittest.mock import AsyncMock, MagicMock, patch
from asgiref.sync import sync_to_async
from temporalio.testing import ActivityEnvironment
+from posthog.models import Organization
+
+from products.growth.backend.enrichment.core import EnrichmentOutcome
from products.growth.backend.enrichment.fields import EnrichmentFields
+from products.growth.backend.enrichment.fit_score import IcpFitResult
+from products.growth.backend.enrichment.snapshot import SNAPSHOT_EVENT_NAME
+from products.growth.backend.models import EnrichmentSignupSnapshot
from products.growth.backend.temporal.signup_enrichment.workflow import (
MAX_ENRICH_ATTEMPTS,
SignupEnrichmentInputs,
@@ -31,28 +37,55 @@ def _patches(*, enrich_return, deterministic=None):
async def test_emits_success_signal_and_snapshot_on_match():
- fields = EnrichmentFields(company_type="STARTUP", headcount=130, industry="Fintech")
- pha_client, (get_client, enrich, det, snapshot) = _patches(enrich_return={"return_value": fields})
+ outcome = EnrichmentOutcome(
+ provider_fields=EnrichmentFields(company_type="STARTUP", headcount=130, industry="Fintech"),
+ fit=IcpFitResult(status="scored", score=77, lists_version="lists-1"),
+ )
+ pha_client, (get_client, enrich, det, snapshot) = _patches(enrich_return={"return_value": outcome})
with get_client, enrich, det, snapshot as snapshot_mock:
result = await ActivityEnvironment().run(enrich_signup_organization_activity, _INPUTS)
assert result == {"matched": True, "fields_filled": 3}
- # Snapshot captured once, built from the enriched fields.
+ # Snapshot captured once, built from the enriched fields plus the at-signup fit evaluation.
snapshot_mock.assert_called_once()
- assert snapshot_mock.call_args.kwargs["snapshot"].company_type == "STARTUP"
- # Launch signal emitted with success + the filled field keys.
+ snapshot_arg = snapshot_mock.call_args.kwargs["snapshot"]
+ assert snapshot_arg.company_type == "STARTUP"
+ assert snapshot_arg.icp_fit_score == 77
+ assert snapshot_arg.icp_fit_version == "v0.5"
+ assert snapshot_arg.icp_fit_status == "scored"
+ # Launch signal emitted with success + the filled field keys + the fit status.
signal = next(c for c in pha_client.capture.call_args_list if c.kwargs["event"] == "signup_enrichment_completed")
assert signal.kwargs["properties"]["success"] is True
assert signal.kwargs["properties"]["matched"] is True
+ assert signal.kwargs["properties"]["icp_fit_status"] == "scored"
async def test_falls_back_to_deterministic_company_type_on_miss():
- pha_client, (get_client, enrich, det, snapshot) = _patches(enrich_return={"return_value": None}, deterministic="yc")
+ outcome = EnrichmentOutcome(provider_fields=None, fit=IcpFitResult(status="not_found"))
+ pha_client, (get_client, enrich, det, snapshot) = _patches(
+ enrich_return={"return_value": outcome}, deterministic="yc"
+ )
with get_client, enrich, det, snapshot as snapshot_mock:
result = await ActivityEnvironment().run(enrich_signup_organization_activity, _INPUTS)
assert result == {"matched": False, "fields_filled": 0}
- assert snapshot_mock.call_args.kwargs["snapshot"].company_type == "yc"
+ snapshot_arg = snapshot_mock.call_args.kwargs["snapshot"]
+ assert snapshot_arg.company_type == "yc"
+ # A score-less evaluation snapshots the status alone: no number, no version.
+ assert snapshot_arg.icp_fit_score is None
+ assert snapshot_arg.icp_fit_version is None
+ assert snapshot_arg.icp_fit_status == "not_found"
+
+
+async def test_skipped_fit_scoring_leaves_the_write_once_snapshot_unclaimed():
+ outcome = EnrichmentOutcome(provider_fields=EnrichmentFields(company_type="STARTUP"), fit=None)
+ pha_client, (get_client, enrich, det, snapshot) = _patches(enrich_return={"return_value": outcome})
+ with get_client, enrich, det, snapshot as snapshot_mock:
+ await ActivityEnvironment().run(enrich_signup_organization_activity, _INPUTS)
+
+ snapshot_mock.assert_not_called()
+ signal = next(c for c in pha_client.capture.call_args_list if c.kwargs["event"] == "signup_enrichment_completed")
+ assert signal.kwargs["properties"]["icp_fit_status"] is None
async def test_connection_cleanup_runs_on_the_orm_thread():
@@ -61,7 +94,9 @@ async def test_connection_cleanup_runs_on_the_orm_thread():
# then fails every activity on the worker until the pod is replaced.
cleanup_threads = []
- pha_client, (get_client, enrich, det, snapshot) = _patches(enrich_return={"return_value": None})
+ pha_client, (get_client, enrich, det, snapshot) = _patches(
+ enrich_return={"return_value": EnrichmentOutcome(provider_fields=None, fit=None)}
+ )
with (
get_client,
enrich,
@@ -95,3 +130,58 @@ async def test_failure_signal_emitted_only_on_final_attempt(attempt, expect_sign
assert signals[0].kwargs["properties"]["error"] == "RuntimeError"
else:
assert signals == []
+
+
+class TestWriteOnceSnapshotEligibility:
+ """Exercises the real EnrichmentSignupSnapshot row rather than a mocked call site."""
+
+ async def test_skip_leaves_the_org_eligible_for_a_later_capture(self):
+ organization = await sync_to_async(Organization.objects.create)(name="Acme")
+ inputs = SignupEnrichmentInputs(organization_id=str(organization.id), distinct_id="d1", domain="acme.com")
+ fields = EnrichmentFields(company_type="STARTUP")
+ pha_client = MagicMock()
+
+ with (
+ patch(f"{_MODULE}.get_regional_ph_client", return_value=pha_client),
+ patch(
+ f"{_MODULE}.enrich_organization",
+ AsyncMock(return_value=EnrichmentOutcome(provider_fields=fields, fit=None)),
+ ),
+ patch(f"{_MODULE}._deterministic_company_type", return_value=None),
+ ):
+ await ActivityEnvironment().run(enrich_signup_organization_activity, inputs)
+
+ exists = await sync_to_async(EnrichmentSignupSnapshot.objects.filter(organization_id=organization.id).exists)()
+ assert exists is False
+ assert not any(c.kwargs["event"] == SNAPSHOT_EVENT_NAME for c in pha_client.capture.call_args_list)
+
+ evaluated = EnrichmentOutcome(provider_fields=fields, fit=IcpFitResult(status="insufficient_data"))
+ with (
+ patch(f"{_MODULE}.get_regional_ph_client", return_value=pha_client),
+ patch(f"{_MODULE}.enrich_organization", AsyncMock(return_value=evaluated)),
+ patch(f"{_MODULE}._deterministic_company_type", return_value=None),
+ ):
+ await ActivityEnvironment().run(enrich_signup_organization_activity, inputs)
+
+ exists = await sync_to_async(EnrichmentSignupSnapshot.objects.filter(organization_id=organization.id).exists)()
+ assert exists is True
+ snapshot_events = [c for c in pha_client.capture.call_args_list if c.kwargs["event"] == SNAPSHOT_EVENT_NAME]
+ assert len(snapshot_events) == 1
+ assert snapshot_events[0].kwargs["properties"]["icp_fit_status_at_signup"] == "insufficient_data"
+
+ async def test_insufficient_data_evaluation_claims_the_snapshot(self):
+ organization = await sync_to_async(Organization.objects.create)(name="Acme")
+ inputs = SignupEnrichmentInputs(organization_id=str(organization.id), distinct_id="d1", domain="acme.com")
+ outcome = EnrichmentOutcome(provider_fields=None, fit=IcpFitResult(status="insufficient_data"))
+ pha_client = MagicMock()
+
+ with (
+ patch(f"{_MODULE}.get_regional_ph_client", return_value=pha_client),
+ patch(f"{_MODULE}.enrich_organization", AsyncMock(return_value=outcome)),
+ patch(f"{_MODULE}._deterministic_company_type", return_value=None),
+ ):
+ await ActivityEnvironment().run(enrich_signup_organization_activity, inputs)
+
+ exists = await sync_to_async(EnrichmentSignupSnapshot.objects.filter(organization_id=organization.id).exists)()
+ assert exists is True
diff --git a/products/growth/backend/temporal/signup_enrichment/tests/test_trigger.py b/products/growth/backend/temporal/signup_enrichment/tests/test_trigger.py
index 26e0666e13fb..cef8bb963cdf 100644
--- a/products/growth/backend/temporal/signup_enrichment/tests/test_trigger.py
+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_trigger.py
@@ -43,7 +43,19 @@ def test_dispatches_for_work_email_in_us_and_records_work_email():
with on_commit, connect as connect_mock, run, region, record as record_mock:
start_signup_enrichment_workflow(organization_id="org-1", distinct_id="d1", email="[email protected]")
connect_mock.assert_called_once()
- record_mock.assert_called_once_with(organization_id="org-1", work_email=True)
+ record_mock.assert_called_once_with(organization_id="org-1", work_email=True, signup_role=None)
+
+
+@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")
+def test_signup_role_is_recorded_alongside_work_email():
+ # The role answer feeds the V0.5 student disqualification; persisting it makes the DQ
+ # replayable by the score backfill instead of living only on the workflow inputs.
+ on_commit, connect, run, region, record = _dispatch_mocks()
+ with on_commit, connect, run, region, record as record_mock:
+ start_signup_enrichment_workflow(
+ organization_id="org-1", distinct_id="d1", email="[email protected]", role_at_organization="Student"
+ )
+ record_mock.assert_called_once_with(organization_id="org-1", work_email=True, signup_role="Student")
@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=False, HARMONIC_API_KEY="key")
@@ -95,7 +107,7 @@ def test_personal_email_records_work_email_false_without_provider_dispatch():
with on_commit, connect as connect_mock, run, region, record as record_mock:
start_signup_enrichment_workflow(organization_id="org-1", distinct_id="d1", email="[email protected]")
connect_mock.assert_not_called()
- record_mock.assert_called_once_with(organization_id="org-1", work_email=False)
+ record_mock.assert_called_once_with(organization_id="org-1", work_email=False, signup_role=None)
@override_settings(
@@ -126,7 +138,7 @@ def test_missing_distinct_id_records_work_email_but_never_dispatches():
with on_commit, connect as connect_mock, run, region, record as record_mock:
start_signup_enrichment_workflow(organization_id="org-1", distinct_id=None, email="[email protected]")
connect_mock.assert_not_called()
- record_mock.assert_called_once_with(organization_id="org-1", work_email=True)
+ record_mock.assert_called_once_with(organization_id="org-1", work_email=True, signup_role=None)
@override_settings(GROWTH_SIGNUP_ENRICHMENT_ENABLED=True, HARMONIC_API_KEY="key")
diff --git a/products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py b/products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py
index cd60f90e3a88..4ad68efe25c8 100644
--- a/products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py
+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py
@@ -6,7 +6,9 @@ from unittest.mock import AsyncMock, MagicMock, patch
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+from products.growth.backend.enrichment.core import EnrichmentOutcome
from products.growth.backend.enrichment.fields import EnrichmentFields
+from products.growth.backend.enrichment.fit_score import IcpFitResult
from products.growth.backend.temporal.signup_enrichment.workflow import (
SignupEnrichmentInputs,
SignupEnrichmentWorkflow,
@@ -54,7 +56,9 @@ async def _run(enrich_side_effect) -> tuple[dict, MagicMock, AsyncMock, MagicMoc
async def test_miss_then_recheck_upgrades_without_a_second_completed_event():
fields = EnrichmentFields(company_type="STARTUP", headcount=130, industry="Fintech")
- result, pha_client, enrich, snapshot = await _run([None, fields])
+ miss = EnrichmentOutcome(provider_fields=None, fit=IcpFitResult(status="not_found"))
+ match = EnrichmentOutcome(provider_fields=fields, fit=IcpFitResult(status="scored", score=61))
+ result, pha_client, enrich, snapshot = await _run([miss, match])
assert result == {"matched": True, "fields_filled": 3}
assert enrich.await_count == 2
@@ -70,18 +74,21 @@ async def test_miss_then_recheck_upgrades_without_a_second_completed_event():
"upgraded": True,
"fields_filled": 3,
"organization_id": "org-1",
+ "icp_fit_status": "scored",
}
# The launch signal fires exactly once — on the first attempt, unchanged.
completed = _events(pha_client, "signup_enrichment_completed")
assert len(completed) == 1
assert completed[0].kwargs["properties"]["matched"] is False
+ assert completed[0].kwargs["properties"]["icp_fit_status"] == "not_found"
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, fields])
+ match = EnrichmentOutcome(provider_fields=fields, fit=IcpFitResult(status="scored", score=61))
+ result, pha_client, enrich, snapshot = await _run([match, match])
assert result == {"matched": True, "fields_filled": 2}
assert enrich.await_count == 2
diff --git a/products/growth/backend/temporal/signup_enrichment/trigger.py b/products/growth/backend/temporal/signup_enrichment/trigger.py
index 9323da259338..812cc8d97c9d 100644
--- a/products/growth/backend/temporal/signup_enrichment/trigger.py
+++ b/products/growth/backend/temporal/signup_enrichment/trigger.py
@@ -75,7 +75,9 @@ def start_signup_enrichment_workflow(
return
work_email = not _generic_emails.is_generic(email)
- _record_work_email(organization_id=str(organization_id), work_email=work_email)
+ _record_work_email(
+ organization_id=str(organization_id), work_email=work_email, signup_role=role_at_organization or None
+ )
if not work_email or not distinct_id:
return
@@ -137,10 +139,10 @@ def _geoip_country_code(ip_address: str | None) -> str | None:
return None
-def _record_work_email(*, organization_id: str, work_email: bool) -> None:
+def _record_work_email(*, organization_id: str, work_email: bool, signup_role: str | None = None) -> None:
# The write runs in its own savepoint; a failure here must never surface to signup.
try:
- record_signup_work_email(organization_id=organization_id, work_email=work_email)
+ record_signup_work_email(organization_id=organization_id, work_email=work_email, signup_role=signup_role)
except Exception as e:
capture_exception(e)
diff --git a/products/growth/backend/temporal/signup_enrichment/workflow.py b/products/growth/backend/temporal/signup_enrichment/workflow.py
index 4fce913b38c1..a6712e182046 100644
--- a/products/growth/backend/temporal/signup_enrichment/workflow.py
+++ b/products/growth/backend/temporal/signup_enrichment/workflow.py
@@ -108,7 +108,7 @@ async def enrich_signup_organization_activity(
return {"matched": False, "fields_filled": 0}
try:
- fields = await enrich_organization(
+ outcome = await enrich_organization(
organization_id=inputs.organization_id,
domain=inputs.domain,
provider=HarmonicEnrichmentProvider(),
@@ -118,10 +118,15 @@ async def enrich_signup_organization_activity(
geoip_country_code=inputs.geoip_country_code,
distinct_id=inputs.distinct_id,
)
+ fields, fit = outcome.provider_fields, outcome.fit
filled = fields.to_dict() if fields else {}
matched = fields is not None
- if not is_recheck:
+ # No later backfill re-attempts this snapshot, so claiming it while fit scoring was
+ # skipped (fit is None — no active IcpScoringConfig row, or an unexpected scoring
+ # error; see EnrichmentOutcome) would permanently strand the org without an
+ # at-signup fit score.
+ if not is_recheck and fit is not None:
deterministic = await sync_to_async(_deterministic_company_type)(inputs.organization_id)
snapshot = SignupEnrichmentSnapshot(
company_type=(fields.company_type if fields else None) or deterministic,
@@ -132,6 +137,11 @@ async def enrich_signup_organization_activity(
founded_year=fields.founded_year if fields else None,
funding_stage=fields.funding_stage if fields else None,
is_yc_company=fields.is_yc_company if fields else None,
+ # A numeric fit score snapshots with its version; a score-less evaluation
+ # snapshots the status alone (see SignupEnrichmentSnapshot).
+ icp_fit_score=fit.score,
+ icp_fit_version=fit.version if fit.score is not None else None,
+ icp_fit_status=fit.status,
)
await sync_to_async(capture_signup_enrichment_snapshot)(
pha_client,
@@ -149,6 +159,7 @@ async def enrich_signup_organization_activity(
"upgraded": matched and not first_attempt_matched,
"fields_filled": len(filled),
"organization_id": inputs.organization_id,
+ "icp_fit_status": fit.status if fit else None,
},
groups={"organization": inputs.organization_id},
)
@@ -156,7 +167,12 @@ async def enrich_signup_organization_activity(
pha_client.capture(
distinct_id=inputs.distinct_id,
event=ENRICHMENT_SIGNAL_EVENT,
- properties={"success": True, "matched": matched, "fields_filled": sorted(filled.keys())},
+ properties={
+ "success": True,
+ "matched": matched,
+ "fields_filled": sorted(filled.keys()),
+ "icp_fit_status": fit.status if fit else None,
+ },
groups={"organization": inputs.organization_id},
)
logger.info("signup_enrichment_completed", matched=matched, fields_filled=len(filled))
diff --git a/products/growth/backend/tests/test_enrichment_core.py b/products/growth/backend/tests/test_enrichment_core.py
index 1e10f9a46ce7..7ee756ba0fbb 100644
--- a/products/growth/backend/tests/test_enrichment_core.py
+++ b/products/growth/backend/tests/test_enrichment_core.py
@@ -7,8 +7,9 @@ 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.icp_lists import clear_lists_cache
from products.growth.backend.enrichment.providers import EnrichmentProvider, ProviderLookup
-from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch
+from products.growth.backend.models import IcpScoringConfig, OrganizationEnrichment, OrganizationEnrichmentFetch
class _FakeProvider(EnrichmentProvider):
@@ -21,7 +22,64 @@ class _FakeProvider(EnrichmentProvider):
return self._lookup
+# A GraphQL-shaped company the fit score maxes with the test lists: traction 35 (120k
+# visits, +71% 90d), capital 30 ($12M + YC), AI 15 (tag), headcount growth 10 (+50% 180d),
+# software 10 (eng headcount).
+def _company(**overrides):
+ company = {
+ "companyType": "STARTUP",
+ "headcount": 12,
+ "description": "AI developer platform",
+ "funding": {"fundingTotal": 12_000_000, "investors": [{"name": "Y Combinator"}]},
+ "tagsV2": [
+ {"displayValue": "Artificial Intelligence", "type": "MARKET"},
+ {"displayValue": "S25", "type": "YC_BATCH"},
+ ],
+ "tractionMetrics": {
+ "webTraffic": {
+ "latestMetricValue": 120_000,
+ "metrics": [
+ {"timestamp": "2026-08-01T00:00:00Z", "metricValue": 120_000},
+ {"timestamp": "2026-04-01T00:00:00Z", "metricValue": 70_000},
+ ],
+ },
+ "headcount": {
+ "latestMetricValue": 12,
+ "metrics": [
+ {"timestamp": "2026-08-01T00:00:00Z", "metricValue": 12},
+ {"timestamp": "2026-01-01T00:00:00Z", "metricValue": 8},
+ ],
+ },
+ "headcountEngineering": {"latestMetricValue": 8, "metrics": []},
+ },
+ }
+ company.update(overrides)
+ return company
+
+
+# Matched but empty-shell: no headcount, no funding, no investors, no tags, no traffic.
+def _empty_shell():
+ return {"companyType": "STARTUP", "funding": {}, "tagsV2": [], "tractionMetrics": {}}
+
+
class TestEnrichmentCore(BaseTest):
+ def setUp(self):
+ super().setUp()
+ IcpScoringConfig.objects.create(
+ version="test-lists-1",
+ tags=[
+ {"tag": "Artificial Intelligence", "recommendation": "ai_positive"},
+ {"tag": "Developer Tools", "recommendation": "software_positive"},
+ ],
+ quality_investors=[{"investor": "Y Combinator", "aliases": ["YC"]}],
+ is_active=True,
+ )
+ clear_lists_cache()
+
+ def tearDown(self):
+ clear_lists_cache()
+ super().tearDown()
+
def _enrich(
self,
lookup: ProviderLookup,
@@ -32,6 +90,7 @@ class TestEnrichmentCore(BaseTest):
distinct_id=None,
person=None,
geoip_country_code=None,
+ domain="stripe.com",
):
person_patch_kwargs = {"side_effect": person} if isinstance(person, Exception) else {"return_value": person}
clay_patch_kwargs = (
@@ -43,7 +102,7 @@ class TestEnrichmentCore(BaseTest):
):
return async_to_sync(enrich_organization)(
organization_id=str(self.organization.id),
- domain="stripe.com",
+ domain=domain,
provider=_FakeProvider(lookup),
pha_client=pha_client or MagicMock(),
is_recheck=is_recheck,
@@ -52,26 +111,20 @@ class TestEnrichmentCore(BaseTest):
distinct_id=distinct_id,
)
+ # ---------- archive + legacy clay behavior (unchanged contracts) ----------
+
def test_archives_raw_payload_and_writes_live_stores_on_match(self):
company = {"companyType": "STARTUP", "funding": {"fundingStage": "SEED"}}
fields = EnrichmentFields(company_type="STARTUP")
- result = self._enrich(ProviderLookup(fields=fields, raw_payload=company))
+ outcome = self._enrich(ProviderLookup(fields=fields, raw_payload=company))
- assert result is fields
+ assert outcome.provider_fields is fields
row = OrganizationEnrichmentFetch.objects.get(organization=self.organization)
assert row.provider == "harmonic"
assert row.is_recheck is False
assert row.payload == company # verbatim, un-transformed
assert OrganizationEnrichment.objects.filter(organization=self.organization).exists()
- def test_archives_miss_with_placeholder_and_skips_live_write(self):
- result = self._enrich(ProviderLookup(fields=None, raw_payload=None))
-
- assert result is None
- row = OrganizationEnrichmentFetch.objects.get(organization=self.organization)
- assert row.payload == {"companyFound": False}
- assert not OrganizationEnrichment.objects.filter(organization=self.organization).exists()
-
def test_recheck_labels_the_archive_row(self):
self._enrich(ProviderLookup(fields=None, raw_payload=None), is_recheck=True)
assert OrganizationEnrichmentFetch.objects.get(organization=self.organization).is_recheck is True
@@ -84,13 +137,14 @@ 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: Clay's bridge columns are already present, so they feed the score too —
- # but the person mirror is recheck-only, so `set` stays unused.
+ def test_clay_scores_from_our_fields_the_signup_role_and_clays_columns(self):
+ # First attempt: Clay's bridge columns are already present, so they feed the clay
+ # score too — but the clay person mirror is recheck-only, so the only person write
+ # is the fit mirror, and this payload's fit evaluation is score-less (insufficient).
pha_client = MagicMock()
fields = EnrichmentFields(headcount=750, country="US", founded_year=2021, ownership_status="PRIVATE")
self._enrich(
- ProviderLookup(fields=fields, raw_payload={"n": 1}),
+ ProviderLookup(fields=fields, raw_payload=_empty_shell()),
role_at_organization="Founder",
clay=ClayBridgeInputs(est_revenue=25_000_000, clay_processed=True),
pha_client=pha_client,
@@ -103,62 +157,43 @@ class TestEnrichmentCore(BaseTest):
properties = pha_client.group_identify.call_args.kwargs["properties"]
assert properties["icp_score"] == 21
assert properties["icp_score_version"] == "clay-parity-2"
- pha_client.set.assert_not_called()
+ pha_client.set.assert_called_once_with(
+ distinct_id="signer-distinct-id", properties={"icp_fit_status": "insufficient_data"}
+ )
- 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.
+ def test_clay_first_attempt_scores_without_waiting_for_clay(self):
fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)
- result = self._enrich(ProviderLookup(fields=fields, raw_payload={"n": 1}), role_at_organization="engineering")
+ outcome = self._enrich(
+ ProviderLookup(fields=fields, raw_payload=_empty_shell()), role_at_organization="engineering"
+ )
- assert result is fields
+ assert outcome.provider_fields is fields
record = OrganizationEnrichment.objects.get(organization=self.organization)
assert record.data["icp_score"] == 12
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
- # 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).
+ def test_first_attempt_miss_reconstructs_fields_from_a_prior_record_and_clay_scores(self):
OrganizationEnrichment.objects.create(
organization=self.organization,
data={"headcount": 750, "country": "US", "founded_year": 2021, "company_type_deterministic": "yc"},
)
pha_client = MagicMock()
- result = self._enrich(
+ outcome = 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
+ assert outcome.provider_fields 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 None
- record = OrganizationEnrichment.objects.get(organization=self.organization)
- assert "icp_score" not in record.data
- 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)
- self._enrich(
- ProviderLookup(fields=fields, raw_payload={"n": 1}), is_recheck=True, role_at_organization="engineering"
+ assert record.data["company_type_deterministic"] == "yc"
+ pha_client.set.assert_called_once_with(
+ distinct_id="signer-distinct-id", properties={"icp_fit_status": "not_found"}
)
- # 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"),
@@ -170,7 +205,7 @@ class TestEnrichmentCore(BaseTest):
pha_client = MagicMock()
fields = EnrichmentFields(headcount=750, country=provider_country, founded_year=2021)
self._enrich(
- ProviderLookup(fields=fields, raw_payload={"n": 1}),
+ ProviderLookup(fields=fields, raw_payload=_empty_shell()),
is_recheck=True,
role_at_organization="engineering",
geoip_country_code=geoip_country,
@@ -183,15 +218,6 @@ class TestEnrichmentCore(BaseTest):
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()
- 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),
@@ -205,23 +231,24 @@ class TestEnrichmentCore(BaseTest):
("person_lookup_raises", RuntimeError("personhog down"), False),
]
)
- def test_recheck_mirror_policy(self, _name, person, expect_mirror):
+ def test_clay_recheck_mirror_policy(self, _name, person, expect_mirror):
+ # Empty-shell payload keeps the fit evaluation score-less, and the fit mirror always
+ # sends its status regardless of person state, so isolate the guarded clay mirror by
+ # its own key rather than asserting on `set` calls overall.
pha_client = MagicMock()
fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)
self._enrich(
- ProviderLookup(fields=fields, raw_payload={"n": 1}),
+ ProviderLookup(fields=fields, raw_payload=_empty_shell()),
is_recheck=True,
pha_client=pha_client,
distinct_id="signer-distinct-id",
person=person,
)
- assert pha_client.set.called is expect_mirror
+ clay_calls = [c for c in pha_client.set.call_args_list if "icp_score" in c.kwargs["properties"]]
+ assert bool(clay_calls) 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()),
@@ -230,7 +257,7 @@ class TestEnrichmentCore(BaseTest):
async_to_sync(enrich_organization)(
organization_id=str(self.organization.id),
domain="stripe.com",
- provider=_FakeProvider(ProviderLookup(fields=fields, raw_payload={"n": 1})),
+ provider=_FakeProvider(ProviderLookup(fields=fields, raw_payload=_empty_shell())),
pha_client=MagicMock(),
is_recheck=False,
role_at_organization="engineering",
@@ -239,179 +266,236 @@ class TestEnrichmentCore(BaseTest):
person_mock.assert_not_called()
- def test_recheck_person_lookup_failure_still_scores_from_non_clearbit_inputs(self):
- pha_client = MagicMock()
+ def test_bridge_read_failure_still_clay_scores_from_own_fields(self):
fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)
- self._enrich(
- ProviderLookup(fields=fields, raw_payload={"n": 1}),
+ with patch("products.growth.backend.enrichment.core.capture_exception") as capture_mock:
+ outcome = self._enrich(
+ ProviderLookup(fields=fields, raw_payload=_empty_shell()),
+ role_at_organization="engineering",
+ clay=RuntimeError("group store down"),
+ )
+
+ assert outcome.provider_fields is fields
+ capture_mock.assert_called_once()
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data["icp_score"] == 12
+ assert record.data["headcount"] == 750
+
+ def test_bridge_read_failure_never_downgrades_a_persisted_clay_score(self):
+ 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)
+
+ outcome = self._enrich(
+ ProviderLookup(fields=fields, raw_payload=_empty_shell()),
is_recheck=True,
role_at_organization="engineering",
- pha_client=pha_client,
- distinct_id="signer-distinct-id",
- person=RuntimeError("personhog down"),
+ clay=RuntimeError("group store down"),
)
+ assert outcome.provider_fields is fields
record = OrganizationEnrichment.objects.get(organization=self.organization)
- assert record.data["icp_score"] == 12
- pha_client.set.assert_not_called()
+ assert record.data["icp_score"] == 15
+ assert record.data["headcount"] == 800
- @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,
+ def test_archive_failure_does_not_break_enrich(self):
+ fields = EnrichmentFields(company_type="STARTUP")
+ with (
+ patch(
+ "products.growth.backend.enrichment.writer.OrganizationEnrichmentFetch.objects.create",
+ side_effect=RuntimeError("db down"),
),
- ("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),
+ patch("products.growth.backend.enrichment.writer.capture_exception") as capture_mock,
+ ):
+ outcome = self._enrich(ProviderLookup(fields=fields, raw_payload={"companyType": "STARTUP"}))
+
+ assert outcome.provider_fields is fields
+ capture_mock.assert_called_once()
+ # The live-store write still happened despite the archive failure.
+ assert OrganizationEnrichment.objects.filter(organization=self.organization).exists()
+
+ # ---------- fit evaluation ----------
+
+ def test_fit_scores_the_raw_payload_next_to_the_clay_score(self):
+ pha_client = MagicMock()
+ fields = EnrichmentFields(company_type="STARTUP", headcount=12)
+ outcome = self._enrich(
+ ProviderLookup(fields=fields, raw_payload=_company()), pha_client=pha_client, domain="acme.ai"
)
+ assert outcome.fit is not None and outcome.fit.score == 100
record = OrganizationEnrichment.objects.get(organization=self.organization)
- assert record.data["icp_score"] == expected_score
+ assert record.data["icp_fit_score"] == 100
+ assert record.data["icp_fit_version"] == "v0.5"
+ assert record.data["icp_fit_status"] == "scored"
+ assert record.data["icp_fit_lists_version"] == "test-lists-1"
+ assert record.data["icp_fit_components"] == {
+ "traction": 35,
+ "capital": 30,
+ "ai_pilled": 15,
+ "headcount_growth": 10,
+ "software_relevance": 10,
+ }
+ # The clay score wrote its own family from the same enrichment, untouched by fit.
+ assert record.data["icp_score_version"] == "clay-parity-2"
+ properties = pha_client.group_identify.call_args.kwargs["properties"]
+ assert properties["icp_fit_score"] == 100
+ assert properties["icp_fit_status"] == "scored"
- @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}))
+ def test_fit_mirrors_the_person_on_the_first_attempt_without_a_person_read(self):
+ # icp_fit_score is a brand-new person key nothing else writes: no ownership guard,
+ # no person lookup, mirrored on every attempt — unlike the guarded clay mirror.
+ pha_client = MagicMock()
+ fields = EnrichmentFields(company_type="STARTUP")
+ 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="acme.ai",
+ provider=_FakeProvider(ProviderLookup(fields=fields, raw_payload=_company())),
+ pha_client=pha_client,
+ is_recheck=False,
+ distinct_id="signer-distinct-id",
+ )
- record = OrganizationEnrichment.objects.get(organization=self.organization)
- assert record.data["icp_score"] == expected_score
+ person_mock.assert_not_called()
+ pha_client.set.assert_called_once_with(
+ distinct_id="signer-distinct-id",
+ properties={"icp_fit_score": 100, "icp_fit_version": "v0.5", "icp_fit_status": "scored"},
+ )
- def test_clearbit_fallback_does_not_block_the_mirror(self):
+ def test_student_role_disqualifies_fit_regardless_of_the_payload(self):
pha_client = MagicMock()
- fields = EnrichmentFields(country="US")
+ fields = EnrichmentFields(company_type="STARTUP")
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"}}}}),
+ ProviderLookup(fields=fields, raw_payload=_company()),
+ role_at_organization="Student",
pha_client=pha_client,
)
- pha_client.set.assert_called_once()
- assert pha_client.set.call_args.kwargs["properties"]["icp_score"] == 6
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data["icp_fit_score"] == 0
+ assert record.data["icp_fit_status"] == "disqualified"
+ assert record.data["icp_fit_dq_reason"] == "role=student"
- 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"},
+ def test_fit_insufficient_data_writes_status_only(self):
+ pha_client = MagicMock()
+ fields = EnrichmentFields(company_type="STARTUP")
+ outcome = self._enrich(ProviderLookup(fields=fields, raw_payload=_empty_shell()), pha_client=pha_client)
+
+ assert outcome.fit is not None and outcome.fit.status == "insufficient_data"
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert "icp_fit_score" not in record.data
+ assert record.data["icp_fit_status"] == "insufficient_data"
+ properties = pha_client.group_identify.call_args.kwargs["properties"]
+ assert properties["icp_fit_status"] == "insufficient_data"
+ assert "icp_fit_score" not in properties
+
+ def test_fit_miss_scores_from_the_latest_matched_archived_payload(self):
+ # First attempt matched and archived; the recheck misses. The fit score must come
+ # from the archived payload (EnrichmentFields lack description/tags/series).
+ OrganizationEnrichmentFetch.objects.create(
+ organization=self.organization, provider="harmonic", payload=_company()
)
+ OrganizationEnrichment.objects.create(organization=self.organization, data={"headcount": 12})
+ pha_client = MagicMock()
- result = self._enrich(
- ProviderLookup(fields=None, raw_payload=None), is_recheck=True, role_at_organization="engineering"
+ outcome = self._enrich(
+ ProviderLookup(fields=None, raw_payload=None), is_recheck=True, pha_client=pha_client, domain="acme.ai"
)
- # 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
+ assert outcome.provider_fields is None # the workflow's matched signal tracks the lookup
+ assert outcome.fit is not None and outcome.fit.score == 100
record = OrganizationEnrichment.objects.get(organization=self.organization)
- assert record.data["icp_score"] == 12
- assert record.data["company_type_deterministic"] == "yc"
+ assert record.data["icp_fit_score"] == 100
- 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_fit_sentinel_only_archive_is_not_found(self):
+ OrganizationEnrichmentFetch.objects.create(
+ organization=self.organization, provider="harmonic", payload={"companyFound": False}
+ )
+ outcome = self._enrich(ProviderLookup(fields=None, raw_payload=None))
- 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()
+ assert outcome.fit is not None and outcome.fit.status == "not_found"
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data["icp_fit_status"] == "not_found"
+ assert "icp_fit_score" not in record.data
+ assert "icp_score" not in record.data # no fields -> no clay score either
- result = self._enrich(ProviderLookup(fields=None, raw_payload=None), is_recheck=True, pha_client=pha_client)
+ def test_fresh_miss_records_not_found_for_the_reenrichment_sweep(self):
+ outcome = self._enrich(ProviderLookup(fields=None, raw_payload=None))
- assert result is None
+ assert outcome.provider_fields 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_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).
+ assert record.data == {
+ "icp_fit_status": "not_found",
+ "icp_fit_version": "v0.5",
+ "icp_fit_lists_version": "test-lists-1",
+ }
+
+ def test_no_active_lists_degrades_to_clay_and_fields_only(self):
+ IcpScoringConfig.objects.update(is_active=False)
+ clear_lists_cache()
+ pha_client = MagicMock()
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}),
+ outcome = self._enrich(
+ ProviderLookup(fields=fields, raw_payload=_company()),
role_at_organization="engineering",
- clay=RuntimeError("group store down"),
+ pha_client=pha_client,
)
- assert result is fields
capture_mock.assert_called_once()
+ assert outcome.provider_fields is fields
+ assert outcome.fit is None
record = OrganizationEnrichment.objects.get(organization=self.organization)
- assert record.data["icp_score"] == 12
- assert record.data["headcount"] == 750
+ assert record.data["icp_score"] == 12 # clay unaffected by the fit degrade
+ assert "icp_fit_status" not in record.data
- 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)
+ def test_no_active_lists_and_a_miss_writes_nothing(self):
+ IcpScoringConfig.objects.update(is_active=False)
+ clear_lists_cache()
+ pha_client = MagicMock()
- result = self._enrich(
- ProviderLookup(fields=fields, raw_payload={"n": 1}),
- is_recheck=True,
- role_at_organization="engineering",
- clay=RuntimeError("group store down"),
- )
+ outcome = self._enrich(ProviderLookup(fields=None, raw_payload=None), pha_client=pha_client)
- assert result is fields
- record = OrganizationEnrichment.objects.get(organization=self.organization)
- assert record.data["icp_score"] == 15
- assert record.data["headcount"] == 800
+ assert outcome.provider_fields is None and outcome.fit is None
+ assert not OrganizationEnrichment.objects.filter(organization=self.organization).exists()
+ pha_client.group_identify.assert_not_called()
- def test_archive_failure_does_not_break_enrich(self):
- fields = EnrichmentFields(company_type="STARTUP")
+ def test_fit_scoring_failure_degrades_to_clay_and_fields_only(self):
+ fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)
with (
patch(
- "products.growth.backend.enrichment.writer.OrganizationEnrichmentFetch.objects.create",
- side_effect=RuntimeError("db down"),
+ "products.growth.backend.enrichment.core.score_company",
+ side_effect=RuntimeError("scorer exploded"),
),
- patch("products.growth.backend.enrichment.writer.capture_exception") as capture_mock,
+ patch("products.growth.backend.enrichment.core.capture_exception") as capture_mock,
):
- result = self._enrich(ProviderLookup(fields=fields, raw_payload={"companyType": "STARTUP"}))
+ outcome = self._enrich(
+ ProviderLookup(fields=fields, raw_payload=_company()), role_at_organization="engineering"
+ )
- assert result is fields
capture_mock.assert_called_once()
- # The live-store write still happened despite the archive failure.
- assert OrganizationEnrichment.objects.filter(organization=self.organization).exists()
+ assert outcome.provider_fields is fields
+ assert outcome.fit is None
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data["icp_score"] == 12
+ assert "icp_fit_score" not in record.data
+
+ def test_scoreless_fit_mirrors_status_only(self):
+ pha_client = MagicMock()
+ fields = EnrichmentFields(company_type="STARTUP")
+ self._enrich(
+ ProviderLookup(fields=fields, raw_payload=_empty_shell()),
+ pha_client=pha_client,
+ distinct_id="signer-distinct-id",
+ )
+
+ pha_client.set.assert_called_once_with(
+ distinct_id="signer-distinct-id", properties={"icp_fit_status": "insufficient_data"}
+ )
diff --git a/products/growth/backend/tests/test_enrichment_writer.py b/products/growth/backend/tests/test_enrichment_writer.py
index 44ee79126482..57336f968c6c 100644
--- a/products/growth/backend/tests/test_enrichment_writer.py
+++ b/products/growth/backend/tests/test_enrichment_writer.py
@@ -2,10 +2,27 @@ from posthog.test.base import BaseTest
from unittest.mock import MagicMock
from products.growth.backend.enrichment.fields import EnrichmentFields
+from products.growth.backend.enrichment.fit_score import IcpFitResult
from products.growth.backend.enrichment.writer import record_signup_work_email, write_organization_enrichment
from products.growth.backend.models import OrganizationEnrichment
+def _fit(score=72, **overrides):
+ kwargs = {
+ "status": "scored",
+ "score": score,
+ "components": {"traction": 25, "capital": 30, "ai_pilled": 15, "headcount_growth": 0, "software_relevance": 2},
+ "quality_investor": True,
+ "data_coverage": 3,
+ "low_confidence": False,
+ "agency_flag": False,
+ "nonprofit_flag": False,
+ "lists_version": "lists-1",
+ }
+ kwargs.update(overrides)
+ return IcpFitResult(**kwargs)
+
+
class TestEnrichmentWriter(BaseTest):
def test_merges_into_existing_record_without_clobbering_other_writers(self):
OrganizationEnrichment.objects.create(organization=self.organization, data={"company_type_deterministic": "yc"})
@@ -46,6 +63,168 @@ class TestEnrichmentWriter(BaseTest):
properties={"enrichment_company_type": "STARTUP", "enrichment_founded_year": 2019},
)
+ def test_legacy_clay_score_still_writes_its_own_keys(self):
+ # The clay score keeps its exact master behavior: same keys, same version stamp,
+ # same person mirror — its threshold-tuned consumers must not notice this PR.
+ pha_client = MagicMock()
+ write_organization_enrichment(
+ organization_id=str(self.organization.id),
+ fields=EnrichmentFields(company_type="STARTUP"),
+ pha_client=pha_client,
+ icp_score=12,
+ mirror_distinct_id="signer",
+ )
+
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data["icp_score"] == 12
+ assert record.data["icp_score_version"] == "clay-parity-2"
+ properties = pha_client.group_identify.call_args.kwargs["properties"]
+ assert properties["icp_score"] == 12
+ pha_client.set.assert_called_once_with(
+ distinct_id="signer", properties={"icp_score": 12, "icp_score_version": "clay-parity-2"}
+ )
+
+ def test_fit_writes_its_own_key_family_next_to_the_clay_score(self):
+ pha_client = MagicMock()
+ write_organization_enrichment(
+ organization_id=str(self.organization.id),
+ fields=EnrichmentFields(company_type="STARTUP"),
+ pha_client=pha_client,
+ icp_score=9,
+ fit=_fit(),
+ )
+
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ # The two families never share a key.
+ assert record.data["icp_score"] == 9
+ assert record.data["icp_fit_score"] == 72
+ assert record.data["icp_fit_version"] == "v0.5"
+ assert record.data["icp_fit_status"] == "scored"
+ assert record.data["icp_fit_lists_version"] == "lists-1"
+ assert record.data["icp_fit_components"]["capital"] == 30
+ assert record.data["icp_fit_flags"] == {
+ "quality_investor": True,
+ "data_coverage": 3,
+ "low_confidence": False,
+ "agency_flag": False,
+ "nonprofit_flag": False,
+ }
+ properties = pha_client.group_identify.call_args.kwargs["properties"]
+ assert properties["icp_score"] == 9
+ assert properties["icp_fit_score"] == 72
+ assert properties["icp_fit_version"] == "v0.5"
+ assert properties["icp_fit_status"] == "scored"
+
+ def test_fit_only_write_carries_no_field_or_clay_keys(self):
+ # The fit backfill passes fields=None and no clay score: only icp_fit_* keys move.
+ pha_client = MagicMock()
+ write_organization_enrichment(
+ organization_id=str(self.organization.id),
+ fields=None,
+ pha_client=pha_client,
+ fit=_fit(score=41),
+ )
+
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data["icp_fit_score"] == 41
+ assert "company_type" not in record.data
+ assert "icp_score" not in record.data
+ properties = pha_client.group_identify.call_args.kwargs["properties"]
+ assert set(properties) == {"icp_fit_score", "icp_fit_version", "icp_fit_status"}
+
+ def test_scoreless_fit_evaluation_strips_stale_numeric_keys_from_the_record(self):
+ OrganizationEnrichment.objects.create(
+ organization=self.organization,
+ data={
+ "icp_fit_score": 62,
+ "icp_fit_version": "v0.5",
+ "icp_fit_components": {"traction": 30},
+ "icp_score": 6, # clay key must survive fit stripping
+ "work_email": True,
+ },
+ )
+ pha_client = MagicMock()
+ write_organization_enrichment(
+ organization_id=str(self.organization.id),
+ fields=None,
+ pha_client=pha_client,
+ fit=IcpFitResult(status="insufficient_data", lists_version="lists-1"),
+ )
+
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data == {
+ "work_email": True,
+ "icp_score": 6,
+ "icp_fit_status": "insufficient_data",
+ "icp_fit_version": "v0.5",
+ "icp_fit_lists_version": "lists-1",
+ }
+ # Group properties cannot be deleted, so only the status key is projected: pairing
+ # the fresh version with the group's stale numeric score would misattribute it.
+ properties = pha_client.group_identify.call_args.kwargs["properties"]
+ assert properties == {"icp_fit_status": "insufficient_data"}
+
+ def test_disqualification_after_a_scored_pass_strips_the_stale_components_and_flags(self):
+ pha_client = MagicMock()
+ write_organization_enrichment(
+ organization_id=str(self.organization.id), fields=None, pha_client=pha_client, fit=_fit(score=62)
+ )
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data["icp_fit_components"]["capital"] == 30
+ assert "icp_fit_flags" in record.data
+
+ write_organization_enrichment(
+ organization_id=str(self.organization.id),
+ fields=None,
+ pha_client=pha_client,
+ fit=IcpFitResult(status="disqualified", score=0, dq_reason="role=student"),
+ )
+ record.refresh_from_db()
+ assert record.data["icp_fit_score"] == 0
+ assert record.data["icp_fit_dq_reason"] == "role=student"
+ assert "icp_fit_components" not in record.data
+ assert "icp_fit_flags" not in record.data
+
+ def test_scored_pass_after_a_disqualification_clears_the_dq_reason(self):
+ pha_client = MagicMock()
+ write_organization_enrichment(
+ organization_id=str(self.organization.id),
+ fields=None,
+ pha_client=pha_client,
+ fit=IcpFitResult(status="disqualified", score=0, dq_reason="company_type=SCHOOL"),
+ )
+ write_organization_enrichment(
+ organization_id=str(self.organization.id), fields=None, pha_client=pha_client, fit=_fit()
+ )
+
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data["icp_fit_score"] == 72
+ assert "icp_fit_dq_reason" not in record.data
+
+ def test_fit_mirror_carries_status_through_a_scored_to_insufficient_data_transition(self):
+ pha_client = MagicMock()
+ write_organization_enrichment(
+ organization_id=str(self.organization.id),
+ fields=None,
+ pha_client=pha_client,
+ fit=_fit(score=55),
+ fit_mirror_distinct_id="signer",
+ )
+ pha_client.set.assert_called_once_with(
+ distinct_id="signer",
+ properties={"icp_fit_score": 55, "icp_fit_version": "v0.5", "icp_fit_status": "scored"},
+ )
+
+ pha_client.reset_mock()
+ write_organization_enrichment(
+ organization_id=str(self.organization.id),
+ fields=None,
+ pha_client=pha_client,
+ fit=IcpFitResult(status="insufficient_data"),
+ fit_mirror_distinct_id="signer",
+ )
+ pha_client.set.assert_called_once_with(distinct_id="signer", properties={"icp_fit_status": "insufficient_data"})
+
def test_record_signup_work_email_merges_without_clobbering_provider_data(self):
record_signup_work_email(organization_id=str(self.organization.id), work_email=False)
assert OrganizationEnrichment.objects.get(organization=self.organization).data == {"work_email": False}
@@ -61,7 +240,16 @@ class TestEnrichmentWriter(BaseTest):
"headcount": 9,
}
- def test_no_op_when_no_fields_set(self):
+ def test_record_signup_work_email_lowercases_and_skips_blank_roles(self):
+ record_signup_work_email(organization_id=str(self.organization.id), work_email=True, signup_role="Founder")
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data == {"work_email": True, "signup_role": "founder"}
+
+ record_signup_work_email(organization_id=str(self.organization.id), work_email=True, signup_role=" ")
+ record.refresh_from_db()
+ assert record.data["signup_role"] == "founder" # blank role never clobbers a recorded one
+
+ def test_no_op_when_no_fields_and_no_scores(self):
pha_client = MagicMock()
write_organization_enrichment(
organization_id=str(self.organization.id),
diff --git a/products/growth/backend/tests/test_harmonic_adapter.py b/products/growth/backend/tests/test_harmonic_adapter.py
new file mode 100644
index 000000000000..1789981a0c40
--- /dev/null
+++ b/products/growth/backend/tests/test_harmonic_adapter.py
@@ -0,0 +1,175 @@
+from parameterized import parameterized
+
+from products.growth.backend.enrichment.fit_score import score_company
+from products.growth.backend.enrichment.harmonic_adapter import normalize_graphql_company
+from products.growth.backend.enrichment.icp_lists import CuratedLists
+
+
+def _normalized(company):
+ result = normalize_graphql_company(company)
+ assert result is not None
+ return result
+
+
+LISTS = CuratedLists(version="test-lists")
+
+
+def _series(*points):
+ """(iso_timestamp, value) pairs -> GraphQL metrics list, deliberately unsorted-friendly."""
+ return [{"timestamp": ts, "metricValue": value} for ts, value in points]
+
+
+ [
+ ("none", None),
+ ("miss_sentinel", {"companyFound": False}),
+ ("empty_dict", {}),
+ ("not_a_dict", ["companyFound"]),
+ ]
+)
+def test_unmatched_payloads_normalize_to_none(_name, payload):
+ assert normalize_graphql_company(payload) is None
+
+
+def test_camelcase_projection_to_the_scorer_shape():
+ company = {
+ "companyType": "STARTUP",
+ "headcount": 42,
+ "description": "An API platform",
+ "fundingAttributeNullStatus": "EXISTS_BUT_UNDISCLOSED",
+ "funding": {
+ "fundingTotal": 3_500_000,
+ # Company entries carry `name`, angel entries carry `fullName`; both fold to `name`.
+ "investors": [{"name": "Sequoia Capital"}, {"fullName": "Jane Angel"}, {"logo": "no-name.png"}],
+ },
+ "tagsV2": [{"displayValue": "Developer Tools", "type": "MARKET", "dateAdded": "2026-01-01"}],
+ "tractionMetrics": {
+ "webTraffic": {"latestMetricValue": 12_000, "metrics": []},
+ "headcount": {"latestMetricValue": 42, "metrics": []},
+ "headcountEngineering": {"latestMetricValue": 7, "metrics": []},
+ },
+ }
+
+ normalized = normalize_graphql_company(company)
+
+ assert normalized == {
+ "company_type": "STARTUP",
+ "headcount": 42,
+ "description": "An API platform",
+ "funding": {"funding_total": 3_500_000, "investors": [{"name": "Sequoia Capital"}, {"name": "Jane Angel"}]},
+ "funding_attribute_null_status": "EXISTS_BUT_UNDISCLOSED",
+ "tags_v2": [{"display_value": "Developer Tools", "type": "MARKET"}],
+ "traction_metrics": {
+ "web_traffic": {"latest_metric_value": 12_000, "90d_ago": {"percent_change": None, "change": None}},
+ "headcount": {"latest_metric_value": 42, "180d_ago": {"percent_change": None, "change": None}},
+ "headcount_engineering": {"latest_metric_value": 7},
+ },
+ }
+
+
+def test_growth_derived_as_of_the_latest_observation():
+ # Latest point 2026-06-01; the 90d-ago anchor (2026-03-03) resolves to the last
+ # observation at or before it (2026-02-20, value 8000) — no interpolation, no peeking.
+ company = {
+ "tractionMetrics": {
+ "webTraffic": {
+ "latestMetricValue": 12_000,
+ "metrics": _series(
+ ("2026-06-01T00:00:00.000Z", 12_000),
+ ("2026-02-20T00:00:00.000Z", 8_000),
+ ("2025-11-01T00:00:00.000Z", 2_000),
+ ),
+ }
+ }
+ }
+ block = _normalized(company)["traction_metrics"]["web_traffic"]
+ assert block["90d_ago"] == {"percent_change": 50.0, "change": 4_000}
+
+
+def test_headcount_growth_uses_the_180d_window_and_absolute_change():
+ company = {
+ "tractionMetrics": {
+ "headcount": {
+ "latestMetricValue": 23,
+ "metrics": _series(
+ ("2026-08-01T00:00:00.000Z", 23),
+ ("2026-01-15T00:00:00.000Z", 20), # last obs at/before 2026-02-02 anchor
+ ("2025-06-01T00:00:00.000Z", 5),
+ ),
+ }
+ }
+ }
+ block = _normalized(company)["traction_metrics"]["headcount"]
+ assert block["180d_ago"] == {"percent_change": 15.0, "change": 3}
+
+
+ [
+ ("empty_series", []),
+ ("single_point_cannot_cover_the_window", _series(("2026-06-01T00:00:00.000Z", 9_000))),
+ ("all_points_inside_the_window", _series(("2026-06-01T00:00:00Z", 9_000), ("2026-05-20T00:00:00Z", 7_000))),
+ ("zero_baseline", _series(("2026-06-01T00:00:00Z", 9_000), ("2026-01-01T00:00:00Z", 0))),
+ (
+ "malformed_points",
+ [
+ {"timestamp": None, "metricValue": 5},
+ {"timestamp": "not-a-date", "metricValue": 5},
+ {"timestamp": "2026-06-01T00:00:00Z"},
+ ],
+ ),
+ ]
+)
+def test_uncoverable_windows_yield_unknown_growth_never_zero(_name, metrics):
+ company = {"tractionMetrics": {"webTraffic": {"latestMetricValue": 9_000, "metrics": metrics}}}
+ block = _normalized(company)["traction_metrics"]["web_traffic"]
+ assert block["90d_ago"] == {"percent_change": None, "change": None}
+
+
+def test_unsorted_series_are_sorted_before_derivation():
+ company = {
+ "tractionMetrics": {
+ "webTraffic": {
+ "latestMetricValue": 6_000,
+ "metrics": _series(
+ ("2026-01-01T00:00:00Z", 3_000),
+ ("2026-06-01T00:00:00Z", 6_000),
+ ("2026-02-25T00:00:00Z", 4_000),
+ ),
+ }
+ }
+ }
+ block = _normalized(company)["traction_metrics"]["web_traffic"]
+ assert block["90d_ago"]["percent_change"] == 50.0 # 4000 (Feb 25, last <= Mar 3 anchor) -> 6000
+
+
+def test_normalized_output_scores_end_to_end():
+ company = {
+ "companyType": "STARTUP",
+ "headcount": 12,
+ "description": "AI developer platform",
+ "funding": {"fundingTotal": 12_000_000, "investors": [{"name": "Y Combinator"}]},
+ "tagsV2": [{"displayValue": "S25", "type": "YC_BATCH"}],
+ "tractionMetrics": {
+ "webTraffic": {
+ "latestMetricValue": 120_000,
+ "metrics": _series(("2026-08-01T00:00:00Z", 120_000), ("2026-04-01T00:00:00Z", 70_000)),
+ },
+ "headcount": {
+ "latestMetricValue": 12,
+ "metrics": _series(("2026-08-01T00:00:00Z", 12), ("2026-01-01T00:00:00Z", 8)),
+ },
+ "headcountEngineering": {"latestMetricValue": 8, "metrics": []},
+ },
+ }
+ result = score_company(normalize_graphql_company(company), lists=LISTS, domain="acme.ai")
+ assert result.status == "scored"
+ # traction 15+20 (71% 90d growth) + capital 20+10 capped at 30 ($12M + YC batch) +
+ # ai 15 (.ai + description) + headcount growth 10 (50% 180d) + software 10 (eng headcount)
+ assert result.score == 100
+ assert result.components == {
+ "traction": 35,
+ "capital": 30,
+ "ai_pilled": 15,
+ "headcount_growth": 10,
+ "software_relevance": 10,
+ }
diff --git a/products/growth/backend/tests/test_icp_fit_score.py b/products/growth/backend/tests/test_icp_fit_score.py
new file mode 100644
index 000000000000..052b0ae3fbbe
--- /dev/null
+++ b/products/growth/backend/tests/test_icp_fit_score.py
@@ -0,0 +1,351 @@
+from typing import Any
+
+from parameterized import parameterized
+
+from products.growth.backend.enrichment.fit_score import (
+ SCORE_VERSION,
+ STATUS_DISQUALIFIED,
+ STATUS_INSUFFICIENT_DATA,
+ STATUS_NOT_FOUND,
+ STATUS_SCORED,
+ is_quality_investor,
+ score_company,
+)
+from products.growth.backend.enrichment.icp_lists import CuratedLists, norm
+
+LISTS = CuratedLists(
+ version="test-lists",
+ capital_quality=frozenset({"ai grant batch 1"}),
+ ai_positive=frozenset({"artificial intelligence", "ai grant batch 1"}),
+ software_positive=frozenset({"developer tools"}),
+ quality_investors=frozenset({norm("Y Combinator"), norm("Sequoia Capital"), norm("GV")}),
+)
+
+
+def _payload(**overrides):
+ """A matched company that scores 0 with full data coverage absent; cases override one branch."""
+ payload: dict[str, Any] = {
+ "company_type": "STARTUP",
+ "headcount": None,
+ "description": None,
+ "funding": {"funding_total": None, "investors": []},
+ "funding_attribute_null_status": None,
+ "tags_v2": [{"display_value": "Logistics & Supply Chain", "type": "MARKET"}],
+ "traction_metrics": {
+ "web_traffic": {"latest_metric_value": None, "90d_ago": {"percent_change": None, "change": None}},
+ "headcount": {"latest_metric_value": None, "180d_ago": {"percent_change": None, "change": None}},
+ "headcount_engineering": {"latest_metric_value": None},
+ },
+ }
+ for key, value in overrides.items():
+ payload[key] = value
+ return payload
+
+
+def _traction(
+ web_traffic=None, traffic_growth=None, headcount=None, headcount_growth=None, headcount_adds=None, eng=None
+):
+ return {
+ "web_traffic": {
+ "latest_metric_value": web_traffic,
+ "90d_ago": {"percent_change": traffic_growth, "change": None},
+ },
+ "headcount": {
+ "latest_metric_value": headcount,
+ "180d_ago": {"percent_change": headcount_growth, "change": headcount_adds},
+ },
+ "headcount_engineering": {"latest_metric_value": eng},
+ }
+
+
+def test_version_is_stamped():
+ assert SCORE_VERSION == "v0.5"
+ result = score_company(_payload(), lists=LISTS)
+ assert result.version == "v0.5"
+ assert result.lists_version == "test-lists"
+
+
+# ---------- statuses ----------
+
+
+def test_student_role_disqualifies_before_the_payload_is_consulted():
+ result = score_company(None, lists=LISTS, role="Student")
+ assert (result.status, result.score, result.dq_reason) == (STATUS_DISQUALIFIED, 0, "role=student")
+
+
+def test_school_company_type_disqualifies():
+ result = score_company(_payload(company_type="SCHOOL"), lists=LISTS)
+ assert (result.status, result.score, result.dq_reason) == (STATUS_DISQUALIFIED, 0, "company_type=SCHOOL")
+
+
+def test_school_market_tags_do_not_disqualify_a_startup():
+ # Tags describe who a company sells to; only company_type=SCHOOL marks actual institutions.
+ result = score_company(_payload(tags_v2=[{"display_value": "Schools", "type": "MARKET"}]), lists=LISTS)
+ assert result.status == STATUS_SCORED
+
+
+def test_missing_payload_is_not_found():
+ assert score_company(None, lists=LISTS).status == STATUS_NOT_FOUND
+
+
+def test_empty_shell_profile_is_insufficient_data_not_a_low_score():
+ payload = _payload(tags_v2=[])
+ result = score_company(payload, lists=LISTS)
+ assert result.status == STATUS_INSUFFICIENT_DATA
+ assert result.score is None
+
+
+ [
+ ("headcount", {"headcount": 4}),
+ ("funding", {"funding": {"funding_total": 100_000, "investors": []}}),
+ # Investors are a funding signal on their own (handbook + coverage counter):
+ # a raise known only through the investor list is not an empty shell.
+ ("investors_only", {"funding": {"funding_total": None, "investors": [{"name": "Cousin Capital"}]}}),
+ ("tags", {}), # the base payload's tag row alone
+ ("web_traffic", {"traction_metrics": _traction(web_traffic=600)}),
+ ]
+)
+def test_any_single_core_signal_defeats_the_insufficient_data_gate(_name, overrides):
+ payload = _payload(tags_v2=[], **overrides) if "tags" not in _name else _payload()
+ assert score_company(payload, lists=LISTS).status == STATUS_SCORED
+
+
+def test_undisclosed_raise_with_a_quality_investor_scores_capital_18():
+ # The score owner's ruling (2026-08-19): EXISTS_BUT_UNDISCLOSED + a named quality
+ # investor is a scorable profile — base tier 8 plus the quality bonus — not
+ # insufficient_data, even when every other core signal is empty.
+ payload = _payload(
+ tags_v2=[],
+ funding={"funding_total": None, "investors": [{"name": "Sequoia Capital"}]},
+ funding_attribute_null_status="EXISTS_BUT_UNDISCLOSED",
+ )
+ result = score_company(payload, lists=LISTS)
+ assert result.status == STATUS_SCORED
+ assert (result.components or {}).get("capital") == 18
+ assert result.quality_investor is True
+
+
+# ---------- traction (35 = level 15 + growth 20) ----------
+
+
+ [
+ ("100k_visits", 100_000, 15),
+ ("10k_visits", 10_000, 10),
+ ("1k_visits", 1_000, 5),
+ ("999_visits", 999, 0),
+ ("none", None, 0),
+ ]
+)
+def test_traffic_level_tiers(_name, web_traffic, expected):
+ result = score_company(_payload(traction_metrics=_traction(web_traffic=web_traffic)), lists=LISTS)
+ assert (result.components or {}).get("traction") == expected
+
+
+ [
+ ("plus_40pct", 10_000, 40.0, 10 + 20),
+ ("plus_15pct", 10_000, 15.0, 10 + 12),
+ ("barely_positive", 10_000, 0.1, 10 + 5),
+ ("flat", 10_000, 0.0, 10 + 0),
+ ("shrinking", 10_000, -25.0, 10 + 0),
+ ("unknown_growth", 10_000, None, 10 + 0),
+ # Growth never counts below a 5k-visit base: small-base percentages invert the signal.
+ ("small_base_growth_ignored", 1_000, 300.0, 5 + 0),
+ ]
+)
+def test_traffic_growth_tiers_and_the_5k_base_gate(_name, web_traffic, growth, expected):
+ result = score_company(
+ _payload(traction_metrics=_traction(web_traffic=web_traffic, traffic_growth=growth)), lists=LISTS
+ )
+ assert (result.components or {}).get("traction") == expected
+
+
+# ---------- capital (30 = tier 20 + quality bonus 10, capped) ----------
+
+
+ [
+ ("10m", 10_000_000, None, 20),
+ ("2m", 2_000_000, None, 14),
+ ("any_funding", 1, None, 8),
+ ("undisclosed_but_exists", 0, "EXISTS_BUT_UNDISCLOSED", 8),
+ ("nothing", 0, None, 0),
+ ]
+)
+def test_funding_tiers(_name, funding_total, null_status, expected):
+ payload = _payload(
+ funding={"funding_total": funding_total, "investors": []}, funding_attribute_null_status=null_status
+ )
+ assert (score_company(payload, lists=LISTS).components or {}).get("capital") == expected
+
+
+ [
+ ("named_investor_exact", [{"name": "Sequoia Capital"}], True),
+ ("named_investor_substring", [{"name": "Sequoia Capital India"}], True),
+ ("short_name_never_substrings", [{"name": "GVK Industries"}], False),
+ ("short_name_exact_still_matches", [{"name": "GV"}], True),
+ ("unknown_investor", [{"name": "Cousin Capital"}], False),
+ ]
+)
+def test_quality_investor_matching(_name, investors, expect_quality):
+ payload = _payload(funding={"funding_total": 12_000_000, "investors": investors})
+ result = score_company(payload, lists=LISTS)
+ assert result.quality_investor is expect_quality
+ assert (result.components or {}).get("capital") == (30 if expect_quality else 20)
+
+
+def test_yc_batch_tag_type_confers_quality_capital_for_any_batch():
+ # Matched on tag TYPE so future batches (W27, ...) qualify without a list update.
+ payload = _payload(
+ funding={"funding_total": 500_000, "investors": []},
+ tags_v2=[{"display_value": "S26", "type": "YC_BATCH"}],
+ )
+ result = score_company(payload, lists=LISTS)
+ assert result.quality_investor is True
+ assert (result.components or {}).get("capital") == 8 + 10
+
+
+def test_capital_is_capped_at_30():
+ payload = _payload(funding={"funding_total": 50_000_000, "investors": [{"name": "Y Combinator"}]})
+ assert (score_company(payload, lists=LISTS).components or {}).get("capital") == 30
+
+
+def test_quality_bonus_alone_scores_without_any_recorded_funding():
+ payload = _payload(tags_v2=[{"display_value": "AI Grant Batch 1", "type": "ACCELERATOR"}])
+ result = score_company(payload, lists=LISTS)
+ assert (result.components or {}).get("capital") == 10
+ assert result.quality_investor is True
+
+
+# ---------- AI-pilled (15) ----------
+
+
+ [
+ ("ai_tag", [{"display_value": "Artificial Intelligence", "type": "MARKET"}], None, "acme.com", 15),
+ ("ai_description", None, "We build ML pipelines for robots", "acme.com", 15),
+ ("dot_ai_domain", None, None, "acme.ai", 15),
+ ("none_of_the_three", None, "We sell shoes", "acme.com", 0),
+ # \b word boundaries: "aid" or "mail" must not match the AI regex.
+ ("no_substring_false_positives", None, "First aid mail retail", "acme.com", 0),
+ ]
+)
+def test_ai_pilled_signals(_name, tags, description, domain, expected):
+ payload = _payload(description=description)
+ if tags:
+ payload["tags_v2"] = tags
+ result = score_company(payload, lists=LISTS, domain=domain)
+ assert (result.components or {}).get("ai_pilled") == expected
+
+
+# ---------- headcount growth (10) ----------
+
+
+ [
+ ("fast_growth", 15.0, None, 10),
+ ("moderate_growth", 5.0, None, 6),
+ ("three_net_hires_alternative", 2.0, 3, 6),
+ ("barely_growing", 1.0, None, 3),
+ ("three_hires_with_zero_pct", 0.0, 3, 6),
+ ("flat", 0.0, None, 0),
+ ("shrinking", -10.0, None, 0),
+ ("unknown", None, None, 0),
+ ]
+)
+def test_headcount_growth_tiers(_name, growth, adds, expected):
+ payload = _payload(traction_metrics=_traction(headcount=20, headcount_growth=growth, headcount_adds=adds))
+ assert (score_company(payload, lists=LISTS).components or {}).get("headcount_growth") == expected
+
+
+# ---------- software relevance (10) ----------
+
+
+ [
+ ("eng_headcount", _traction(eng=3), None, None, 10),
+ ("software_tag_only", _traction(), [{"display_value": "Developer Tools", "type": "MARKET"}], None, 7),
+ ("software_description_only", _traction(), None, "An API platform for teams", 7),
+ ("neither", _traction(), None, "We run a bakery", 0),
+ ]
+)
+def test_software_relevance_tiers(_name, traction, tags, description, expected):
+ payload = _payload(traction_metrics=traction, description=description)
+ if tags:
+ payload["tags_v2"] = tags
+ assert (score_company(payload, lists=LISTS).components or {}).get("software_relevance") == expected
+
+
+# ---------- flags & coverage ----------
+
+
+def test_agency_and_nonprofit_are_flags_not_penalties():
+ payload = _payload(
+ tags_v2=[
+ {"display_value": "Consulting", "type": "MARKET"},
+ {"display_value": "Non-Profit & Community Organizations", "type": "MARKET"},
+ ],
+ headcount=40,
+ )
+ result = score_company(payload, lists=LISTS)
+ assert result.status == STATUS_SCORED
+ assert result.agency_flag is True
+ assert result.nonprofit_flag is True
+
+
+def test_low_confidence_flags_thin_coverage():
+ result = score_company(_payload(), lists=LISTS) # tags only: 1 of 4 core signals
+ assert result.data_coverage == 1
+ assert result.low_confidence is True
+
+ rich = _payload(headcount=50, funding={"funding_total": 5_000_000, "investors": []})
+ rich["traction_metrics"] = _traction(web_traffic=20_000)
+ result = score_company(rich, lists=LISTS)
+ assert result.data_coverage == 4
+ assert result.low_confidence is False
+
+
+def test_archetype_scores_high_across_all_components():
+ payload = _payload(
+ headcount=12,
+ description="AI developer platform",
+ funding={"funding_total": 12_000_000, "investors": [{"name": "Y Combinator"}]},
+ tags_v2=[
+ {"display_value": "Artificial Intelligence", "type": "MARKET"},
+ {"display_value": "S25", "type": "YC_BATCH"},
+ ],
+ traction_metrics=_traction(
+ web_traffic=120_000, traffic_growth=55.0, headcount=12, headcount_growth=30.0, eng=8
+ ),
+ )
+ result = score_company(payload, lists=LISTS, domain="acme.ai")
+ assert result.status == STATUS_SCORED
+ assert result.score == 100
+ assert result.components == {
+ "traction": 35,
+ "capital": 30,
+ "ai_pilled": 15,
+ "headcount_growth": 10,
+ "software_relevance": 10,
+ }
+
+
+# ---------- helpers ----------
+
+
+ [
+ ("case_folds", "Y COMBINATOR", True),
+ ("and_normalizes", "management and strategy consulting", False), # not an investor list entry
+ ("whitespace", " y combinator ", True),
+ ]
+)
+def test_norm_based_matching(_name, observed, expected):
+ assert is_quality_investor(observed, LISTS.quality_investors) is expected
+
+
+def test_norm_folds_and_to_ampersand():
+ assert norm("Management and Strategy Consulting") == "management & strategy consulting"
diff --git a/products/growth/backend/tests/test_snapshot.py b/products/growth/backend/tests/test_snapshot.py
index d38480de5eab..3c917abb0132 100644
--- a/products/growth/backend/tests/test_snapshot.py
+++ b/products/growth/backend/tests/test_snapshot.py
@@ -17,7 +17,7 @@ class TestSignupEnrichmentSnapshot(BaseTest):
company_type="startup",
headcount=42,
industry="software",
- icp_score=80,
+ icp_fit_score=80,
)
properties = snapshot.to_event_properties()
@@ -26,10 +26,18 @@ class TestSignupEnrichmentSnapshot(BaseTest):
"company_type_at_signup": "startup",
"headcount_at_signup": 42,
"industry_at_signup": "software",
- "icp_score_at_signup": 80,
+ "icp_fit_score_at_signup": 80,
}
assert "country_at_signup" not in properties
+ def test_icp_fit_status_rides_along_without_a_numeric_score(self) -> None:
+ # An insufficient_data evaluation at signup snapshots the status alone, keeping
+ # "insufficient at signup" distinguishable from "never evaluated" forever.
+ snapshot = SignupEnrichmentSnapshot(company_type="startup", icp_fit_status="insufficient_data")
+ properties = snapshot.to_event_properties()
+ assert properties["icp_fit_status_at_signup"] == "insufficient_data"
+ assert "icp_fit_score_at_signup" not in properties
+
def test_emits_person_scoped_event_when_snapshot_lands(self) -> None:
pha_client = MagicMock()
snapshot = SignupEnrichmentSnapshot(company_type="startup", headcount=42)
@@ -88,15 +96,13 @@ class TestSignupEnrichmentSnapshot(BaseTest):
@parameterized.expand(
[
- ("present", "2026-07-01", True),
+ ("present", "v0.5", True),
("absent", None, False),
]
)
- def test_icp_score_version_in_properties(
- self, _name: str, icp_score_version: str | None, expect_version: bool
- ) -> None:
+ def test_icp_fit_version_in_properties(self, _name: str, icp_fit_version: str | None, expect_version: bool) -> None:
pha_client = MagicMock()
- snapshot = SignupEnrichmentSnapshot(icp_score=90, icp_score_version=icp_score_version)
+ snapshot = SignupEnrichmentSnapshot(icp_fit_score=90, icp_fit_version=icp_fit_version)
capture_signup_enrichment_snapshot(
pha_client,
@@ -106,7 +112,7 @@ class TestSignupEnrichmentSnapshot(BaseTest):
)
_, kwargs = pha_client.capture.call_args
- assert kwargs["properties"]["icp_score_at_signup"] == 90
- assert ("icp_score_version_at_signup" in kwargs["properties"]) is expect_version
+ assert kwargs["properties"]["icp_fit_score_at_signup"] == 90
+ assert ("icp_fit_version_at_signup" in kwargs["properties"]) is expect_version
if expect_version:
- assert kwargs["properties"]["icp_score_version_at_signup"] == icp_score_version
+ assert kwargs["properties"]["icp_fit_version_at_signup"] == icp_fit_version