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): add orchestration-agnostic enrichment core (#70117)

Matt Brookerc9d8b6e56b80
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index e1569d4f691c..6d8b5dfb1930 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -163,6 +163,9 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
# Write-once idempotency guard keyed on the org, claimed via get_or_create from an
# internal enrichment write-back path, never looked up by user-supplied ID.
"EnrichmentSignupSnapshot",
+ # Append-only raw provider-payload archive written by the internal enrichment path;
+ # no API endpoint, never looked up by user-supplied ID.
+ "OrganizationEnrichmentFetch",
# Model kept to avoid a deletion migration but has no API endpoint
"ErrorTrackingAutoCaptureControls",
"DuckLakeBackfill",
diff --git a/ee/billing/salesforce_enrichment/harmonic_client.py b/ee/billing/salesforce_enrichment/harmonic_client.py
index bc4d50f8b008..b3a27e9e634d 100644
--- a/ee/billing/salesforce_enrichment/harmonic_client.py
+++ b/ee/billing/salesforce_enrichment/harmonic_client.py
@@ -100,6 +100,49 @@ class AsyncHarmonicClient:
return None
+ async def enrich_company_by_domain_strict(self, domain: str) -> Optional[dict[str, Any]]:
+ """Like enrich_company_by_domain, but distinguishes not-found from operational failure.
+
+ Returns None only for a genuine not-found (every domain variation returned a clean
+ GraphQL response with companyFound false). Operational failures (network errors, non-2xx
+ status, JSON decode, GraphQL errors) are re-raised so callers can retry and alert instead
+ of mistaking an outage for a missing company. Does not capture_exception — the caller owns
+ error handling.
+ """
+ await asyncio.sleep(0.2)
+ domain = self._clean_domain(domain)
+ domain_variations = [f"{prefix}{domain}" if prefix else domain for prefix in HARMONIC_DOMAIN_VARIATIONS]
+
+ last_error: Optional[Exception] = None
+ for domain_variation in domain_variations:
+ try:
+ variables = {"identifiers": {"websiteUrl": f"https://{domain_variation}"}}
+
+ if self.session is None:
+ raise RuntimeError("HTTP session not initialized. Use async context manager.")
+ async with self.session.post(
+ f"{HARMONIC_BASE_URL}/graphql",
+ params={"apikey": self.api_key},
+ json={"query": HARMONIC_COMPANY_ENRICHMENT_QUERY, "variables": variables},
+ headers={"Content-Type": "application/json"},
+ ) as response:
+ response.raise_for_status()
+ data = await response.json()
+
+ if "errors" in data:
+ raise RuntimeError(f"Harmonic GraphQL errors for {domain_variation}: {data['errors']}")
+
+ result = data.get("data", {}).get("enrichCompanyByIdentifiers", {})
+ if result.get("companyFound"):
+ return result.get("company")
+ except Exception as e:
+ last_error = e
+ continue
+
+ if last_error is not None:
+ raise last_error
+ return None
+
async def enrich_companies_batch(self, domains: list[str]) -> list[dict[str, Any] | None]:
"""Enrich multiple domains concurrently.
diff --git a/ee/billing/test/test_harmonic_client.py b/ee/billing/test/test_harmonic_client.py
new file mode 100644
index 000000000000..68bc7579ef16
--- /dev/null
+++ b/ee/billing/test/test_harmonic_client.py
@@ -0,0 +1,63 @@
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import aiohttp
+
+from ee.billing.salesforce_enrichment.harmonic_client import AsyncHarmonicClient
+
+
+def _response(*, json_data=None, raise_status=None):
+ resp = MagicMock()
+ resp.raise_for_status = MagicMock(side_effect=raise_status)
+ resp.json = AsyncMock(return_value=json_data)
+ cm = MagicMock()
+ cm.__aenter__ = AsyncMock(return_value=resp)
+ cm.__aexit__ = AsyncMock(return_value=False)
+ return cm
+
+
+def _client_with_responses(*responses):
+ client = AsyncHarmonicClient.__new__(AsyncHarmonicClient)
+ client.api_key = "test-key"
+ session = MagicMock()
+ session.post = MagicMock(side_effect=list(responses))
+ client.session = session
+ return client
+
+
+def _not_found():
+ return _response(json_data={"data": {"enrichCompanyByIdentifiers": {"companyFound": False}}})
+
+
+def _found(company):
+ return _response(json_data={"data": {"enrichCompanyByIdentifiers": {"companyFound": True, "company": company}}})
+
+
+def _http_500():
+ error = aiohttp.ClientResponseError(request_info=MagicMock(), history=(), status=500, message="Server Error")
+ return _response(raise_status=error)
+
+
+@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())
+async def test_strict_returns_none_when_not_found():
+ # Both domain variations return a clean companyFound=false.
+ client = _client_with_responses(_not_found(), _not_found())
+ assert await client.enrich_company_by_domain_strict("unknown.example") is None
+
+
+@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())
+async def test_strict_reraises_on_http_error():
+ client = _client_with_responses(_http_500(), _http_500())
+ with pytest.raises(aiohttp.ClientResponseError):
+ await client.enrich_company_by_domain_strict("posthog.com")
+
+
+@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())
+async def test_strict_falls_back_to_second_variation_after_error():
+ # First variation errors, second returns a company: the successful variation wins.
+ client = _client_with_responses(_http_500(), _found({"name": "PostHog"}))
+ result = await client.enrich_company_by_domain_strict("posthog.com")
+ assert result == {"name": "PostHog"}
diff --git a/products/growth/backend/enrichment/core.py b/products/growth/backend/enrichment/core.py
new file mode 100644
index 000000000000..589b57296cea
--- /dev/null
+++ b/products/growth/backend/enrichment/core.py
@@ -0,0 +1,53 @@
+"""Orchestration-agnostic enrichment core.
+
+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.
+"""
+
+from typing import Optional
+
+from asgiref.sync import sync_to_async
+from posthoganalytics.client import Client
+
+from products.growth.backend.enrichment.fields import EnrichmentFields
+from products.growth.backend.enrichment.providers import EnrichmentProvider
+from products.growth.backend.enrichment.writer import archive_provider_fetch, write_organization_enrichment
+
+# 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}
+
+
+async def enrich_organization(
+ *,
+ organization_id: str,
+ domain: str,
+ provider: EnrichmentProvider,
+ pha_client: Client,
+ is_recheck: bool = False,
+) -> Optional[EnrichmentFields]:
+ """Look up enrichment for a domain, archive the raw response, and persist the live stores.
+
+ Every fetch is archived verbatim — including a not-found — before the live-store write.
+ Returns the enrichment fields, or None when the provider has no match (nothing written to
+ the live stores). The Postgres writes run via sync_to_async to bridge the async provider.
+ """
+ lookup = await provider.enrich_by_domain(domain)
+
+ await sync_to_async(archive_provider_fetch)(
+ organization_id=organization_id,
+ provider=provider.name,
+ payload=lookup.raw_payload if lookup.raw_payload is not None else _MISS_PAYLOAD,
+ is_recheck=is_recheck,
+ )
+
+ if lookup.fields is None:
+ return None
+
+ await sync_to_async(write_organization_enrichment)(
+ organization_id=organization_id,
+ fields=lookup.fields,
+ pha_client=pha_client,
+ )
+ return lookup.fields
diff --git a/products/growth/backend/enrichment/countries.py b/products/growth/backend/enrichment/countries.py
new file mode 100644
index 000000000000..5b7bdc28a675
--- /dev/null
+++ b/products/growth/backend/enrichment/countries.py
@@ -0,0 +1,59 @@
+"""Country-name to ISO 3166-1 alpha-2 mapping for provider responses.
+
+Providers (Harmonic) return long English country names; the `icp_country` group
+property holds ISO alpha-2 codes. The base mapping comes from babel's CLDR
+territory data (already a dependency), inverted name->code; `_ALIASES` covers
+provider spellings where CLDR prefers a different form (e.g. CLDR says
+"Türkiye" and "Hong Kong SAR China").
+"""
+
+from functools import lru_cache
+from typing import Optional
+
+from babel import Locale
+
+_ALIASES: dict[str, str] = {
+ "united states of america": "US",
+ "usa": "US",
+ "united kingdom of great britain and northern ireland": "GB",
+ "uk": "GB",
+ "turkey": "TR",
+ "hong kong": "HK",
+ "macau": "MO",
+ "palestine": "PS",
+ "ivory coast": "CI",
+ "cape verde": "CV",
+ "democratic republic of the congo": "CD",
+ "republic of the congo": "CG",
+ "laos": "LA",
+ "brunei": "BN",
+ "syria": "SY",
+ "tanzania": "TZ",
+ "moldova": "MD",
+ "north korea": "KP",
+}
+
+
+def _normalize(name: str) -> str:
+ # CLDR spells names like "Côte d'Ivoire" with a typographic apostrophe (U+2019);
+ # providers send a straight one. Fold them so both forms resolve.
+ return name.strip().lower().replace("’", "'")
+
+
+@lru_cache(maxsize=1)
+def _name_to_code() -> dict[str, str]:
+ # Lazy so importing this module stays off the django.setup() hot path.
+ territories = Locale("en").territories
+ inverted = {_normalize(name): code for code, name in territories.items() if len(code) == 2 and code.isalpha()}
+ return {**inverted, **_ALIASES}
+
+
+def country_name_to_iso_code(name: Optional[str]) -> Optional[str]:
+ """Return the ISO alpha-2 code for a provider country name, or None when unmapped."""
+ if not name or not isinstance(name, str):
+ return None
+ normalized = _normalize(name)
+ mapping = _name_to_code()
+ if len(normalized) == 2 and normalized.upper() in mapping.values():
+ return normalized.upper()
+ return mapping.get(normalized)
diff --git a/products/growth/backend/enrichment/fields.py b/products/growth/backend/enrichment/fields.py
new file mode 100644
index 000000000000..ac25ef550dc0
--- /dev/null
+++ b/products/growth/backend/enrichment/fields.py
@@ -0,0 +1,57 @@
+"""Typed field registry for firmographic enrichment.
+
+The single source of truth every enrichment writer imports, so the Postgres record,
+the ClickHouse group-property projection, and the at-signup snapshot stay in lockstep.
+Provider-agnostic: providers transform their responses into this shape. icp_score is
+intentionally excluded from v0.
+
+Precedent: ee/billing/salesforce_enrichment/usage_signals.py (UsageSignals).
+"""
+
+import dataclasses
+from typing import Any, Optional
+
+# Prefix for the `enrichment_*` ClickHouse group properties written via group_identify.
+ENRICHMENT_PROPERTY_PREFIX = "enrichment_"
+
+# Fields whose provider source matches what already populates the icp_* group properties
+# (Harmonic-first in the incumbent waterfall), so we write the same keys and consumers
+# never migrate. Source-changing fields stay on the parallel `enrichment_*` namespace
+# until they pass their own comparison.
+SAME_KEY_GROUP_PROPERTIES: dict[str, str] = {
+ "headcount": "icp_employees",
+ "country": "icp_country",
+}
+
+
+class EnrichmentFields:
+ """Firmographic enrichment values for one organization."""
+
+ company_type: Optional[str] = None
+ headcount: Optional[int] = None
+ headcount_engineering: Optional[int] = None
+ industry: Optional[str] = None
+ country: Optional[str] = None
+ founded_year: Optional[int] = None
+ funding_stage: Optional[str] = None
+ total_raised: Optional[int] = None
+ last_round_size: Optional[int] = None
+ last_round_date: Optional[str] = None
+ investors: Optional[list[str]] = None
+ is_yc_company: Optional[bool] = None
+ is_ai_native: Optional[bool] = None
+ work_email: Optional[bool] = None
+
+ def to_dict(self) -> dict[str, Any]:
+ """Return set (non-None) fields keyed by registry name."""
+ return {
+ field.name: value for field in dataclasses.fields(self) if (value := getattr(self, field.name)) is not None
+ }
+
+ def to_group_properties(self) -> dict[str, Any]:
+ """Return the ClickHouse group properties: takeover fields on their icp_* keys, the rest as `enrichment_*`."""
+ return {
+ SAME_KEY_GROUP_PROPERTIES.get(name, f"{ENRICHMENT_PROPERTY_PREFIX}{name}"): value
+ for name, value in self.to_dict().items()
+ }
diff --git a/products/growth/backend/enrichment/providers.py b/products/growth/backend/enrichment/providers.py
new file mode 100644
index 000000000000..4c02ed7485a4
--- /dev/null
+++ b/products/growth/backend/enrichment/providers.py
@@ -0,0 +1,50 @@
+"""Enrichment provider interface and the Harmonic implementation.
+
+The interface keeps the enrichment core provider-agnostic; Harmonic is the first
+provider. AsyncHarmonicClient (ee/billing/salesforce_enrichment) is reused as-is —
+tach already allows products.growth to import ee.
+"""
+
+import abc
+import dataclasses
+from typing import Any, Optional
+
+from products.growth.backend.enrichment.fields import EnrichmentFields
+from products.growth.backend.enrichment.transform import transform_harmonic_company
+
+from ee.billing.salesforce_enrichment.harmonic_client import AsyncHarmonicClient
+
+
+class ProviderLookup:
+ """One provider lookup: the transformed fields plus the raw response kept for the archive.
+
+ `fields` is None on a not-found. `raw_payload` is the provider's verbatim response for the
+ company, or None when the provider returns nothing at all for a miss.
+ """
+
+ fields: Optional[EnrichmentFields]
+ raw_payload: Optional[dict[str, Any]]
+
+
+class EnrichmentProvider(abc.ABC):
+ """Looks up firmographic enrichment for a single company by domain."""
+
+ name: str
+
+ @abc.abstractmethod
+ async def enrich_by_domain(self, domain: str) -> ProviderLookup:
+ """Return the fields and raw payload for a domain; fields is None when not found.
+
+ Raises on operational failure (network, provider outage) so the caller can retry
+ and alert, rather than conflating an outage with a genuine not-found.
+ """
+
+
+class HarmonicEnrichmentProvider(EnrichmentProvider):
+ name = "harmonic"
+
+ async def enrich_by_domain(self, domain: str) -> ProviderLookup:
+ async with AsyncHarmonicClient() as client:
+ company = await client.enrich_company_by_domain_strict(domain)
+ return ProviderLookup(fields=transform_harmonic_company(company), raw_payload=company)
diff --git a/products/growth/backend/enrichment/transform.py b/products/growth/backend/enrichment/transform.py
new file mode 100644
index 000000000000..7e693faa6516
--- /dev/null
+++ b/products/growth/backend/enrichment/transform.py
@@ -0,0 +1,107 @@
+"""Transform a Harmonic company response into the enrichment field registry.
+
+Tag/YC/safe-cast heuristics are shared with the Salesforce enrichment transforms in
+ee/billing/salesforce_enrichment/enrichment.py and imported from there rather than copied.
+"""
+
+from typing import Any, Optional
+
+from products.growth.backend.enrichment.countries import country_name_to_iso_code
+from products.growth.backend.enrichment.fields import EnrichmentFields
+
+from ee.billing.salesforce_enrichment.enrichment import _extract_primary_tag, _is_yc_funded, _safe_dict, _safe_list
+
+
+def _latest_metric(traction: dict[str, Any], metric: str) -> Optional[int]:
+ value = _safe_dict(traction.get(metric)).get("latestMetricValue")
+ return int(value) if isinstance(value, (int, float)) else None
+
+
+def _founded_year(founding: dict[str, Any]) -> Optional[int]:
+ date = founding.get("date")
+ if isinstance(date, str) and "-" in date:
+ year = date.split("-", 1)[0]
+ if year.isdigit():
+ return int(year)
+ return None
+
+
+def _funding_amount(value: Any) -> Optional[int]:
+ # Harmonic reports funding as whole USD; store as int to keep it off floats.
+ return int(value) if isinstance(value, (int, float)) else None
+
+
+def _funding_date(value: Any) -> Optional[str]:
+ # Harmonic returns an ISO datetime (e.g. "2025-02-25T00:00:00Z"); keep the date.
+ if isinstance(value, str) and value:
+ return value.split("T", 1)[0]
+ return None
+
+
+# Bound the passthrough so the group property can't grow unboundedly for a heavily-funded company.
+MAX_INVESTORS = 25
+
+
+def _investor_names(investors: Any) -> Optional[list[str]]:
+ # Company entries carry `name`, Person (angel) entries carry `fullName`; keep both.
+ if not isinstance(investors, list):
+ return None
+ names = [
+ name
+ for investor in investors
+ if isinstance(investor, dict) and isinstance(name := investor.get("name") or investor.get("fullName"), str)
+ ]
+ return names[:MAX_INVESTORS] or None
+
+
+# Harmonic's own tagsV2 taxonomy spells these out; match conservatively on the phrases
+# rather than bare "AI"/"ML" tokens that collide with unrelated words.
+AI_NATIVE_TAG_MARKERS = ("artificial intelligence", "machine learning")
+
+
+def _is_ai_native(tags_v2: list[Any]) -> Optional[bool]:
+ # Empty tagsV2 is absence of tag data, not evidence the company isn't AI-native.
+ if not tags_v2:
+ return None
+ for tag in tags_v2:
+ display = _safe_dict(tag).get("displayValue")
+ if isinstance(display, str) and any(marker in display.lower() for marker in AI_NATIVE_TAG_MARKERS):
+ return True
+ return False
+
+
+def transform_harmonic_company(company: Optional[dict[str, Any]]) -> Optional[EnrichmentFields]:
+ """Map a Harmonic `enrichCompanyByIdentifiers.company` payload to EnrichmentFields.
+
+ Returns None when the payload is missing or not a dict.
+ """
+ if not company or not isinstance(company, dict):
+ return None
+
+ funding = _safe_dict(company.get("funding"))
+ traction = _safe_dict(company.get("tractionMetrics"))
+ location = _safe_dict(company.get("location"))
+ founding = _safe_dict(company.get("foundingDate"))
+
+ headcount = _latest_metric(traction, "headcount")
+ if headcount is None and isinstance(company.get("headcount"), (int, float)):
+ headcount = int(company["headcount"])
+
+ tags_v2 = _safe_list(company.get("tagsV2"))
+
+ return EnrichmentFields(
+ company_type=company.get("companyType"),
+ headcount=headcount,
+ headcount_engineering=_latest_metric(traction, "headcountEngineering"),
+ industry=_extract_primary_tag(_safe_list(company.get("tags")), tags_v2),
+ # ISO alpha-2 to match the format the icp_country group property already holds.
+ country=country_name_to_iso_code(location.get("country")),
+ founded_year=_founded_year(founding),
+ funding_stage=funding.get("fundingStage"),
+ total_raised=_funding_amount(funding.get("fundingTotal")),
+ last_round_size=_funding_amount(funding.get("lastFundingTotal")),
+ last_round_date=_funding_date(funding.get("lastFundingAt")),
+ investors=_investor_names(funding.get("investors")),
+ is_yc_company=_is_yc_funded(funding.get("investors")),
+ is_ai_native=_is_ai_native(tags_v2),
+ )
diff --git a/products/growth/backend/enrichment/writer.py b/products/growth/backend/enrichment/writer.py
new file mode 100644
index 000000000000..338402fc4a79
--- /dev/null
+++ b/products/growth/backend/enrichment/writer.py
@@ -0,0 +1,92 @@
+"""Writers for the live enrichment stores.
+
+Orchestration-agnostic: plain functions any orchestrator (the real-time Temporal
+workflow, a later batch Dagster asset) can call. Two of the three stores are written
+here — the Postgres record read in-request and the ClickHouse group-property
+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.
+"""
+
+from typing import Any
+
+from django.db import transaction
+
+from posthoganalytics.client import Client
+
+from posthog.exceptions_capture import capture_exception
+
+from products.growth.backend.enrichment.fields import EnrichmentFields
+from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch
+
+ORGANIZATION_GROUP_TYPE = "organization"
+
+
+def _merge_into_record(organization_id: str, values: dict[str, Any]) -> 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.
+ """
+ with transaction.atomic():
+ record, _ = OrganizationEnrichment.objects.select_for_update().get_or_create(organization_id=organization_id)
+ record.data = {**record.data, **values}
+ record.save(update_fields=["data", "updated_at"])
+
+
+def write_organization_enrichment(
+ *,
+ organization_id: str,
+ fields: EnrichmentFields,
+ pha_client: Client,
+) -> None:
+ """Persist enrichment to Postgres and project it onto the organization group.
+
+ - Postgres: merge the set registry fields into OrganizationEnrichment.data, preserving
+ any keys owned by other writers (e.g. company_type_deterministic).
+ - ClickHouse: project `enrichment_*` group properties via group_identify.
+
+ No-op when there are no set fields, so a Harmonic miss leaves both stores untouched.
+ """
+ values = fields.to_dict()
+ if not values:
+ return
+
+ _merge_into_record(organization_id, values)
+
+ pha_client.group_identify(
+ ORGANIZATION_GROUP_TYPE,
+ str(organization_id),
+ properties=fields.to_group_properties(),
+ )
+
+
+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.
+
+ Never raises: a raw-archive failure must not break enrichment — the live-store write and
+ the caller's return still happen. One row per fetch, so signup and recheck stay distinct.
+ """
+ try:
+ OrganizationEnrichmentFetch.objects.create(
+ organization_id=organization_id,
+ provider=provider,
+ is_recheck=is_recheck,
+ payload=payload,
+ )
+ except Exception as e:
+ 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).
+
+ 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.
+ """
+ _merge_into_record(organization_id, {"work_email": work_email})
diff --git a/products/growth/backend/migrations/0004_organizationenrichmentfetch.py b/products/growth/backend/migrations/0004_organizationenrichmentfetch.py
new file mode 100644
index 000000000000..a7c2895024cb
--- /dev/null
+++ b/products/growth/backend/migrations/0004_organizationenrichmentfetch.py
@@ -0,0 +1,51 @@
+# Generated by Django 5.2.14 on 2026-07-14 15:08
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("growth", "0003_enrichmentsignupsnapshot"),
+ ("posthog", "1251_alter_integration_kind"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="OrganizationEnrichmentFetch",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("provider", models.CharField(max_length=64)),
+ ("fetched_at", models.DateTimeField(auto_now_add=True)),
+ ("is_recheck", models.BooleanField(default=False)),
+ ("payload", models.JSONField(default=dict)),
+ (
+ "organization",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="enrichment_fetches",
+ to="posthog.organization",
+ ),
+ ),
+ ],
+ options={
+ "indexes": [
+ models.Index(
+ fields=["organization", "fetched_at"],
+ name="growth_enrich_fetch_org_time",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/growth/backend/migrations/max_migration.txt b/products/growth/backend/migrations/max_migration.txt
index db529cb0b0c9..bc1566a3d503 100644
--- a/products/growth/backend/migrations/max_migration.txt
+++ b/products/growth/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0003_enrichmentsignupsnapshot
+0004_organizationenrichmentfetch
diff --git a/products/growth/backend/models.py b/products/growth/backend/models.py
index f1f0714397cc..9b519366ba54 100644
--- a/products/growth/backend/models.py
+++ b/products/growth/backend/models.py
@@ -115,6 +115,33 @@ class OrganizationEnrichment(UUIDModel):
updated_at = models.DateTimeField(auto_now=True)
+class OrganizationEnrichmentFetch(UUIDModel):
+ """Append-only archive of raw provider responses, one row per fetch.
+
+ The signup attempt and any later recheck are separate rows on purpose: provider
+ responses are time-varying, so each fetch is a distinct observation kept verbatim —
+ including a not-found, which is evidence too.
+ """
+
+ # db_constraint=False keeps CreateModel off posthog_organization's lock path (hot table)
+ organization = models.ForeignKey(
+ "posthog.Organization",
+ on_delete=models.CASCADE,
+ db_constraint=False,
+ related_name="enrichment_fetches",
+ )
+ provider = models.CharField(max_length=64)
+ fetched_at = models.DateTimeField(auto_now_add=True)
+ is_recheck = models.BooleanField(default=False)
+ # The provider response verbatim, before any transform into the field registry.
+ payload = models.JSONField(default=dict)
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["organization", "fetched_at"], name="growth_enrich_fetch_org_time"),
+ ]
+
+
class EnrichmentSignupSnapshot(UUIDModel):
"""Write-once marker that the at-signup enrichment snapshot has been emitted for an org.
diff --git a/products/growth/backend/tests/test_enrichment_core.py b/products/growth/backend/tests/test_enrichment_core.py
new file mode 100644
index 000000000000..ecfe5536def2
--- /dev/null
+++ b/products/growth/backend/tests/test_enrichment_core.py
@@ -0,0 +1,78 @@
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from asgiref.sync import async_to_sync
+
+from products.growth.backend.enrichment.core import enrich_organization
+from products.growth.backend.enrichment.fields import EnrichmentFields
+from products.growth.backend.enrichment.providers import EnrichmentProvider, ProviderLookup
+from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch
+
+
+class _FakeProvider(EnrichmentProvider):
+ name = "harmonic"
+
+ def __init__(self, lookup: ProviderLookup):
+ self._lookup = lookup
+
+ async def enrich_by_domain(self, domain: str) -> ProviderLookup:
+ return self._lookup
+
+
+class TestEnrichmentCore(BaseTest):
+ def _enrich(self, lookup: ProviderLookup, is_recheck: bool = False):
+ return async_to_sync(enrich_organization)(
+ organization_id=str(self.organization.id),
+ domain="stripe.com",
+ provider=_FakeProvider(lookup),
+ pha_client=MagicMock(),
+ is_recheck=is_recheck,
+ )
+
+ def 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))
+
+ assert result 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
+
+ def test_each_fetch_is_a_separate_row(self):
+ self._enrich(ProviderLookup(fields=None, raw_payload={"companyFound": False, "n": 1}))
+ self._enrich(
+ ProviderLookup(fields=EnrichmentFields(company_type="STARTUP"), raw_payload={"n": 2}), is_recheck=True
+ )
+ rows = OrganizationEnrichmentFetch.objects.filter(organization=self.organization).order_by("fetched_at")
+ assert [r.is_recheck for r in rows] == [False, True]
+
+ 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"),
+ ),
+ patch("products.growth.backend.enrichment.writer.capture_exception") as capture_mock,
+ ):
+ result = self._enrich(ProviderLookup(fields=fields, raw_payload={"companyType": "STARTUP"}))
+
+ 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()
diff --git a/products/growth/backend/tests/test_enrichment_fields.py b/products/growth/backend/tests/test_enrichment_fields.py
new file mode 100644
index 000000000000..2bc11d68629e
--- /dev/null
+++ b/products/growth/backend/tests/test_enrichment_fields.py
@@ -0,0 +1,38 @@
+from products.growth.backend.enrichment.fields import EnrichmentFields
+
+
+def test_to_dict_drops_unset_fields():
+ fields = EnrichmentFields(company_type="startup", headcount=42)
+ assert fields.to_dict() == {"company_type": "startup", "headcount": 42}
+
+
+def test_to_dict_keeps_falsey_but_set_values():
+ fields = EnrichmentFields(founded_year=0, is_yc_company=False)
+ assert fields.to_dict() == {"founded_year": 0, "is_yc_company": False}
+
+
+def test_to_group_properties_writes_takeover_fields_on_icp_keys_and_the_rest_prefixed():
+ fields = EnrichmentFields(
+ company_type="startup",
+ industry="Fintech",
+ headcount=42,
+ country="US",
+ total_raised=12000000,
+ investors=["Y Combinator", "Sequoia"],
+ is_ai_native=True,
+ )
+ assert fields.to_group_properties() == {
+ "enrichment_company_type": "startup",
+ "enrichment_industry": "Fintech",
+ "enrichment_total_raised": 12000000,
+ "enrichment_investors": ["Y Combinator", "Sequoia"],
+ "enrichment_is_ai_native": True,
+ "icp_employees": 42,
+ "icp_country": "US",
+ }
+
+
+def test_empty_fields_produce_empty_dicts():
+ fields = EnrichmentFields()
+ assert fields.to_dict() == {}
+ assert fields.to_group_properties() == {}
diff --git a/products/growth/backend/tests/test_enrichment_providers.py b/products/growth/backend/tests/test_enrichment_providers.py
new file mode 100644
index 000000000000..76f21a1872f2
--- /dev/null
+++ b/products/growth/backend/tests/test_enrichment_providers.py
@@ -0,0 +1,39 @@
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from products.growth.backend.enrichment.providers import HarmonicEnrichmentProvider
+
+
+def _fake_harmonic_client(company):
+ """Build a mock standing in for `async with AsyncHarmonicClient() as client`."""
+ client = MagicMock()
+ client.enrich_company_by_domain_strict = AsyncMock(return_value=company)
+ cm = MagicMock()
+ cm.__aenter__ = AsyncMock(return_value=client)
+ cm.__aexit__ = AsyncMock(return_value=False)
+ return cm, client
+
+
+async def test_enrich_by_domain_transforms_response_and_keeps_raw_payload():
+ company = {"companyType": "STARTUP", "funding": {"fundingStage": "SEED"}}
+ cm, client = _fake_harmonic_client(company)
+ with patch("products.growth.backend.enrichment.providers.AsyncHarmonicClient", return_value=cm):
+ lookup = await HarmonicEnrichmentProvider().enrich_by_domain("posthog.com")
+
+ assert lookup.fields is not None
+ assert lookup.fields.company_type == "STARTUP"
+ assert lookup.fields.funding_stage == "SEED"
+ # The raw provider response is preserved verbatim for the archive.
+ assert lookup.raw_payload == company
+ client.enrich_company_by_domain_strict.assert_awaited_once_with("posthog.com")
+
+
+async def test_enrich_by_domain_returns_no_fields_and_no_payload_when_company_not_found():
+ cm, _ = _fake_harmonic_client(None)
+ with patch("products.growth.backend.enrichment.providers.AsyncHarmonicClient", return_value=cm):
+ lookup = await HarmonicEnrichmentProvider().enrich_by_domain("unknown.example")
+
+ assert lookup.fields is None
+ assert lookup.raw_payload is None
diff --git a/products/growth/backend/tests/test_enrichment_transform.py b/products/growth/backend/tests/test_enrichment_transform.py
new file mode 100644
index 000000000000..8c356738a5c4
--- /dev/null
+++ b/products/growth/backend/tests/test_enrichment_transform.py
@@ -0,0 +1,129 @@
+from parameterized import parameterized
+
+from products.growth.backend.enrichment.transform import MAX_INVESTORS, transform_harmonic_company
+
+
+def _company(**overrides):
+ company = {
+ "companyType": "STARTUP",
+ "headcount": 120,
+ "location": {"country": "United States"},
+ "foundingDate": {"date": "2019-06-01", "granularity": "DAY"},
+ "funding": {
+ "fundingStage": "SERIES_A",
+ "fundingTotal": 12000000,
+ "lastFundingTotal": 8000000,
+ "lastFundingAt": "2024-02-25T00:00:00Z",
+ "investors": [{"name": "Y Combinator"}],
+ },
+ "tractionMetrics": {
+ "headcount": {"latestMetricValue": 130},
+ "headcountEngineering": {"latestMetricValue": 45},
+ },
+ "tags": [{"type": "INDUSTRY", "displayValue": "Developer Tools", "isPrimaryTag": True}],
+ "tagsV2": [],
+ }
+ company.update(overrides)
+ return company
+
+
+def test_transform_maps_all_registry_fields():
+ fields = transform_harmonic_company(_company())
+ assert fields is not None
+ assert fields.to_dict() == {
+ "company_type": "STARTUP",
+ "headcount": 130, # tractionMetrics wins over the top-level headcount
+ "headcount_engineering": 45,
+ "industry": "Developer Tools",
+ "country": "US", # ISO alpha-2, matching the icp_country format
+ "founded_year": 2019,
+ "funding_stage": "SERIES_A",
+ "total_raised": 12000000,
+ "last_round_size": 8000000,
+ "last_round_date": "2024-02-25", # ISO datetime truncated to the date
+ "investors": ["Y Combinator"],
+ "is_yc_company": True,
+ # is_ai_native stays unset: tagsV2 is empty, which is absence of tag data
+ }
+
+
+def test_investors_capture_company_and_person_names_skipping_malformed_entries():
+ investors = [
+ {"name": "Formus Capital"},
+ {"fullName": "Julia Dewahl"}, # angels come back as Person entries
+ {"foo": "bar"}, # neither name nor fullName
+ "not-a-dict",
+ ]
+ fields = transform_harmonic_company(_company(funding={"investors": investors}))
+ assert fields is not None
+ assert fields.investors == ["Formus Capital", "Julia Dewahl"]
+
+
+def test_investors_unset_when_funding_has_no_investors():
+ fields = transform_harmonic_company(_company(funding={"fundingStage": "SEED"}))
+ assert fields is not None
+ assert fields.investors is None
+ assert "investors" not in fields.to_dict()
+
+
+def test_investors_capped_to_bound():
+ fields = transform_harmonic_company(_company(funding={"investors": [{"name": f"VC {i}"} for i in range(40)]}))
+ assert fields is not None
+ assert fields.investors is not None
+ assert len(fields.investors) == MAX_INVESTORS
+ assert fields.investors[0] == "VC 0"
+
+
+ [
+ ("ai_display_value", [{"type": "TECHNOLOGY_TYPE", "displayValue": "Artificial Intelligence (AI)"}], True),
+ ("ml_display_value", [{"type": "MARKET_VERTICAL", "displayValue": "Machine Learning"}], True),
+ ("non_ai_tags_present", [{"type": "MARKET_VERTICAL", "displayValue": "Fintech"}], False),
+ ]
+)
+def test_is_ai_native_matches_conservatively(_name, tags_v2, expected):
+ fields = transform_harmonic_company(_company(tagsV2=tags_v2))
+ assert fields is not None
+ assert fields.is_ai_native is expected
+
+
+def test_is_ai_native_unset_when_tags_v2_absent():
+ fields = transform_harmonic_company(_company(tagsV2=[]))
+ assert fields is not None
+ assert fields.is_ai_native is None
+ assert "is_ai_native" not in fields.to_dict()
+
+
+def test_headcount_falls_back_to_top_level_when_no_traction_metric():
+ fields = transform_harmonic_company(_company(tractionMetrics={}))
+ assert fields is not None
+ assert fields.headcount == 120
+
+
+def test_industry_falls_back_to_market_vertical_tag_v2():
+ fields = transform_harmonic_company(_company(tags=[], tagsV2=[{"type": "MARKET_VERTICAL", "displayValue": "SaaS"}]))
+ assert fields is not None
+ assert fields.industry == "SaaS"
+
+
+def test_non_yc_investors():
+ fields = transform_harmonic_company(_company(funding={"fundingStage": "SEED", "investors": [{"name": "Acme VC"}]}))
+ assert fields is not None
+ assert fields.is_yc_company is False
+
+
+def test_unmapped_country_name_is_dropped_not_written_raw():
+ fields = transform_harmonic_company(_company(location={"country": "Kingdom of Freedonia"}))
+ assert fields is not None
+ assert fields.country is None
+
+
+def test_none_and_empty_payloads_return_none():
+ assert transform_harmonic_company(None) is None
+ assert transform_harmonic_company({}) is None
+
+
+def test_partial_payload_leaves_missing_fields_unset():
+ fields = transform_harmonic_company({"companyType": "ENTERPRISE"})
+ assert fields is not None
+ assert fields.to_dict() == {"company_type": "ENTERPRISE", "is_yc_company": False}
diff --git a/products/growth/backend/tests/test_enrichment_writer.py b/products/growth/backend/tests/test_enrichment_writer.py
new file mode 100644
index 000000000000..44ee79126482
--- /dev/null
+++ b/products/growth/backend/tests/test_enrichment_writer.py
@@ -0,0 +1,72 @@
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock
+
+from products.growth.backend.enrichment.fields import EnrichmentFields
+from products.growth.backend.enrichment.writer import record_signup_work_email, write_organization_enrichment
+from products.growth.backend.models import OrganizationEnrichment
+
+
+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"})
+ pha_client = MagicMock()
+
+ write_organization_enrichment(
+ organization_id=str(self.organization.id),
+ fields=EnrichmentFields(company_type="STARTUP", headcount=130),
+ pha_client=pha_client,
+ )
+
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data == {
+ "company_type_deterministic": "yc",
+ "company_type": "STARTUP",
+ "headcount": 130,
+ }
+
+ def test_creates_record_when_missing(self):
+ write_organization_enrichment(
+ organization_id=str(self.organization.id),
+ fields=EnrichmentFields(industry="Fintech"),
+ pha_client=MagicMock(),
+ )
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data == {"industry": "Fintech"}
+
+ def test_projects_enrichment_group_properties(self):
+ pha_client = MagicMock()
+ write_organization_enrichment(
+ organization_id=str(self.organization.id),
+ fields=EnrichmentFields(company_type="STARTUP", founded_year=2019),
+ pha_client=pha_client,
+ )
+ pha_client.group_identify.assert_called_once_with(
+ "organization",
+ str(self.organization.id),
+ properties={"enrichment_company_type": "STARTUP", "enrichment_founded_year": 2019},
+ )
+
+ 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}
+
+ write_organization_enrichment(
+ organization_id=str(self.organization.id),
+ fields=EnrichmentFields(headcount=9),
+ pha_client=MagicMock(),
+ )
+ record_signup_work_email(organization_id=str(self.organization.id), work_email=True)
+ assert OrganizationEnrichment.objects.get(organization=self.organization).data == {
+ "work_email": True,
+ "headcount": 9,
+ }
+
+ def test_no_op_when_no_fields_set(self):
+ pha_client = MagicMock()
+ write_organization_enrichment(
+ organization_id=str(self.organization.id),
+ fields=EnrichmentFields(),
+ pha_client=pha_client,
+ )
+ assert not OrganizationEnrichment.objects.filter(organization=self.organization).exists()
+ pha_client.group_identify.assert_not_called()