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): fetch Harmonic ownership status and parent company in enrichment (#79061)

Matt Brooker97a549a7cafa
diff --git a/ee/billing/salesforce_enrichment/constants.py b/ee/billing/salesforce_enrichment/constants.py
index ef295616d600..cb38d742dd54 100644
--- a/ee/billing/salesforce_enrichment/constants.py
+++ b/ee/billing/salesforce_enrichment/constants.py
@@ -26,6 +26,15 @@ mutation($identifiers: CompanyEnrichmentIdentifiersInput!) {
}
headcount
description
+ ownershipStatus
+ relatedCompanies {
+ acquiredBy {
+ companyUrn
+ }
+ subsidiaryOf {
+ companyUrn
+ }
+ }
location {
city
country
diff --git a/ee/billing/salesforce_enrichment/harmonic_client.py b/ee/billing/salesforce_enrichment/harmonic_client.py
index b3a27e9e634d..5b15ea0a2554 100644
--- a/ee/billing/salesforce_enrichment/harmonic_client.py
+++ b/ee/billing/salesforce_enrichment/harmonic_client.py
@@ -143,6 +143,30 @@ class AsyncHarmonicClient:
raise last_error
return None
+ async def get_company_by_urn(self, urn: str) -> Optional[dict[str, Any]]:
+ """Resolve a Harmonic company URN (e.g. from relatedCompanies) via the REST profile endpoint.
+
+ Returns None only for a genuine not-found (404). Other failures propagate — like
+ enrich_company_by_domain_strict, this does not capture_exception; parent-company
+ resolution is optional, so the caller decides whether to swallow the error.
+ """
+ company_id = urn.rsplit(":", 1)[-1]
+
+ if self.session is None:
+ raise RuntimeError("HTTP session not initialized. Use async context manager.")
+ await asyncio.sleep(0.2)
+ # Short cap: a single profile fetch, and it shares the signup activity's 90s budget with
+ # the up-to-60s domain lookup — inheriting the session's 30s total would eat all headroom.
+ async with self.session.get(
+ f"{HARMONIC_BASE_URL}/companies/{company_id}",
+ headers={"apikey": self.api_key},
+ timeout=aiohttp.ClientTimeout(total=10),
+ ) as response:
+ if response.status == 404:
+ return None
+ response.raise_for_status()
+ return await response.json()
+
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
index 68bc7579ef16..54f6585cea47 100644
--- a/ee/billing/test/test_harmonic_client.py
+++ b/ee/billing/test/test_harmonic_client.py
@@ -6,8 +6,9 @@ import aiohttp
from ee.billing.salesforce_enrichment.harmonic_client import AsyncHarmonicClient
-def _response(*, json_data=None, raise_status=None):
+def _response(*, json_data=None, raise_status=None, status=200):
resp = MagicMock()
+ resp.status = status
resp.raise_for_status = MagicMock(side_effect=raise_status)
resp.json = AsyncMock(return_value=json_data)
cm = MagicMock()
@@ -25,6 +26,15 @@ def _client_with_responses(*responses):
return client
+def _client_with_get_responses(*responses):
+ client = AsyncHarmonicClient.__new__(AsyncHarmonicClient)
+ client.api_key = "test-key"
+ session = MagicMock()
+ session.get = MagicMock(side_effect=list(responses))
+ client.session = session
+ return client
+
+
def _not_found():
return _response(json_data={"data": {"enrichCompanyByIdentifiers": {"companyFound": False}}})
@@ -61,3 +71,33 @@ async def test_strict_falls_back_to_second_variation_after_error():
client = _client_with_responses(_http_500(), _found({"name": "PostHog"}))
result = await client.enrich_company_by_domain_strict("posthog.com")
assert result == {"name": "PostHog"}
+
+
+@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())
+async def test_get_company_by_urn_returns_parsed_json():
+ client = _client_with_get_responses(
+ _response(json_data={"name": "Salesforce", "website": {"domain": "salesforce.com"}})
+ )
+ result = await client.get_company_by_urn("urn:harmonic:company:9801263")
+ assert result == {"name": "Salesforce", "website": {"domain": "salesforce.com"}}
+ client.session.get.assert_called_once_with(
+ "https://api.harmonic.ai/companies/9801263",
+ headers={"apikey": "test-key"},
+ timeout=aiohttp.ClientTimeout(total=10),
+ )
+
+
+@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())
+async def test_get_company_by_urn_returns_none_on_not_found():
+ client = _client_with_get_responses(_response(status=404))
+ assert await client.get_company_by_urn("urn:harmonic:company:999999999") is None
+
+
+@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())
+async def test_get_company_by_urn_reraises_on_http_error():
+ client = _client_with_get_responses(_http_500())
+ with pytest.raises(aiohttp.ClientResponseError):
+ await client.get_company_by_urn("urn:harmonic:company:9801263")
diff --git a/posthog/temporal/signup_enrichment/workflow.py b/posthog/temporal/signup_enrichment/workflow.py
index b0cf202dccfa..cceffeae7eaf 100644
--- a/posthog/temporal/signup_enrichment/workflow.py
+++ b/posthog/temporal/signup_enrichment/workflow.py
@@ -31,7 +31,8 @@ ENRICHMENT_SIGNAL_EVENT = "signup_enrichment_completed"
ENRICHMENT_RECHECK_EVENT = "signup_enrichment_recheck"
# Hard cap per attempt. The Harmonic client tries up to two domain variations at 30s each,
-# so a single lookup can legitimately run ~60s; give it headroom then stop.
+# plus a parent-company profile fetch capped at 10s, so a single lookup can legitimately run
+# ~70s; give it headroom then stop.
ENRICH_ACTIVITY_TIMEOUT = dt.timedelta(seconds=90)
# A couple of retries for transient provider/network blips, then give up quietly. Kept as a
diff --git a/products/growth/backend/enrichment/fields.py b/products/growth/backend/enrichment/fields.py
index 21d4bf3fce0e..c6ac60c90250 100644
--- a/products/growth/backend/enrichment/fields.py
+++ b/products/growth/backend/enrichment/fields.py
@@ -43,6 +43,9 @@ class EnrichmentFields:
is_yc_company: Optional[bool] = None
is_ai_native: Optional[bool] = None
work_email: Optional[bool] = None
+ ownership_status: Optional[str] = None
+ parent_company: Optional[str] = None
+ parent_company_domain: Optional[str] = None
def to_dict(self) -> dict[str, Any]:
"""Return set (non-None) fields keyed by registry name."""
diff --git a/products/growth/backend/enrichment/providers.py b/products/growth/backend/enrichment/providers.py
index 4c02ed7485a4..b71f9b8f43ff 100644
--- a/products/growth/backend/enrichment/providers.py
+++ b/products/growth/backend/enrichment/providers.py
@@ -9,6 +9,8 @@ import abc
import dataclasses
from typing import Any, Optional
+from posthog.exceptions_capture import capture_exception
+
from products.growth.backend.enrichment.fields import EnrichmentFields
from products.growth.backend.enrichment.transform import transform_harmonic_company
@@ -41,10 +43,50 @@ class EnrichmentProvider(abc.ABC):
"""
+def _parent_company_urn(company: dict[str, Any]) -> Optional[str]:
+ """Pick the parent-company URN from `relatedCompanies`: subsidiaryOf wins over acquiredBy.
+
+ Both links are beta and sparse (often present with a null companyUrn even when
+ ownershipStatus says the company was acquired), so absence here is normal.
+ """
+ related = company.get("relatedCompanies")
+ if not isinstance(related, dict):
+ return None
+ for key in ("subsidiaryOf", "acquiredBy"):
+ link = related.get(key)
+ if isinstance(link, dict) and isinstance(urn := link.get("companyUrn"), str) and urn:
+ return urn
+ return None
+
+
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)
+ fields = transform_harmonic_company(company)
+ if fields is not None and company is not None:
+ fields = await self._with_parent_company(client, company, fields)
+ return ProviderLookup(fields=fields, raw_payload=company)
+
+ async def _with_parent_company(
+ self, client: AsyncHarmonicClient, company: dict[str, Any], fields: EnrichmentFields
+ ) -> EnrichmentFields:
+ """Best-effort parent-company resolution: never fails the lookup, just leaves the fields unset."""
+ urn = _parent_company_urn(company)
+ if urn is None:
+ return fields
+
+ try:
+ parent = await client.get_company_by_urn(urn)
+ except Exception as e:
+ capture_exception(e)
+ return fields
+
+ if not isinstance(parent, dict):
+ return fields
+
+ website = parent.get("website")
+ domain = website.get("domain") if isinstance(website, dict) else None
+ return dataclasses.replace(fields, parent_company=parent.get("name"), parent_company_domain=domain)
diff --git a/products/growth/backend/enrichment/transform.py b/products/growth/backend/enrichment/transform.py
index 7e693faa6516..1069f65d185d 100644
--- a/products/growth/backend/enrichment/transform.py
+++ b/products/growth/backend/enrichment/transform.py
@@ -104,4 +104,5 @@ def transform_harmonic_company(company: Optional[dict[str, Any]]) -> Optional[En
investors=_investor_names(funding.get("investors")),
is_yc_company=_is_yc_funded(funding.get("investors")),
is_ai_native=_is_ai_native(tags_v2),
+ ownership_status=company.get("ownershipStatus"),
)
diff --git a/products/growth/backend/tests/test_enrichment_providers.py b/products/growth/backend/tests/test_enrichment_providers.py
index 76f21a1872f2..a278b9919a5c 100644
--- a/products/growth/backend/tests/test_enrichment_providers.py
+++ b/products/growth/backend/tests/test_enrichment_providers.py
@@ -4,10 +4,11 @@ from unittest.mock import AsyncMock, MagicMock, patch
from products.growth.backend.enrichment.providers import HarmonicEnrichmentProvider
-def _fake_harmonic_client(company):
+def _fake_harmonic_client(company, *, parent_company=None, parent_side_effect=None):
"""Build a mock standing in for `async with AsyncHarmonicClient() as client`."""
client = MagicMock()
client.enrich_company_by_domain_strict = AsyncMock(return_value=company)
+ client.get_company_by_urn = AsyncMock(return_value=parent_company, side_effect=parent_side_effect)
cm = MagicMock()
cm.__aenter__ = AsyncMock(return_value=client)
cm.__aexit__ = AsyncMock(return_value=False)
@@ -37,3 +38,96 @@ async def test_enrich_by_domain_returns_no_fields_and_no_payload_when_company_no
assert lookup.fields is None
assert lookup.raw_payload is None
+
+
+async def test_enrich_by_domain_prefers_subsidiary_of_over_acquired_by():
+ company = {
+ "companyType": "STARTUP",
+ "relatedCompanies": {
+ "acquiredBy": {"companyUrn": "urn:harmonic:company:111"},
+ "subsidiaryOf": {"companyUrn": "urn:harmonic:company:222"},
+ },
+ }
+ parent = {"name": "Salesforce", "website": {"domain": "salesforce.com"}}
+ cm, client = _fake_harmonic_client(company, parent_company=parent)
+ 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.parent_company == "Salesforce"
+ assert lookup.fields.parent_company_domain == "salesforce.com"
+ client.get_company_by_urn.assert_awaited_once_with("urn:harmonic:company:222")
+
+
+async def test_enrich_by_domain_falls_back_to_acquired_by_when_no_subsidiary_of():
+ company = {
+ "companyType": "STARTUP",
+ "relatedCompanies": {"acquiredBy": {"companyUrn": "urn:harmonic:company:111"}, "subsidiaryOf": None},
+ }
+ parent = {"name": "Salesforce", "website": {"domain": "salesforce.com"}}
+ cm, client = _fake_harmonic_client(company, parent_company=parent)
+ 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.parent_company == "Salesforce"
+ client.get_company_by_urn.assert_awaited_once_with("urn:harmonic:company:111")
+
+
+async def test_enrich_by_domain_tolerates_missing_related_companies():
+ company = {"companyType": "STARTUP"}
+ 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.parent_company is None
+ assert lookup.fields.parent_company_domain is None
+ client.get_company_by_urn.assert_not_awaited()
+
+
+ "client_kwargs,expected_captures",
+ [
+ pytest.param({"parent_side_effect": RuntimeError("boom")}, 1, id="resolution_raises"),
+ pytest.param({"parent_company": None}, 0, id="resolution_returns_none"),
+ pytest.param({"parent_company": ["not", "a", "dict"]}, 0, id="resolution_returns_non_dict"),
+ ],
+)
+async def test_enrich_by_domain_tolerates_failed_parent_resolution(client_kwargs, expected_captures):
+ company = {
+ "companyType": "STARTUP",
+ "relatedCompanies": {"acquiredBy": {"companyUrn": "urn:harmonic:company:111"}},
+ }
+ cm, client = _fake_harmonic_client(company, **client_kwargs)
+ with (
+ patch("products.growth.backend.enrichment.providers.AsyncHarmonicClient", return_value=cm),
+ patch("products.growth.backend.enrichment.providers.capture_exception") as mock_capture,
+ ):
+ lookup = await HarmonicEnrichmentProvider().enrich_by_domain("posthog.com")
+
+ assert lookup.fields is not None
+ assert lookup.fields.company_type == "STARTUP"
+ assert lookup.fields.parent_company is None
+ assert lookup.fields.parent_company_domain is None
+ assert mock_capture.call_count == expected_captures
+
+
+async def test_enrich_by_domain_skips_parent_resolution_for_empty_urn():
+ company = {
+ "companyType": "STARTUP",
+ "relatedCompanies": {"acquiredBy": {"companyUrn": ""}},
+ }
+ 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.parent_company is None
+ assert lookup.fields.parent_company_domain is None
+ client.get_company_by_urn.assert_not_awaited()
diff --git a/products/growth/backend/tests/test_enrichment_transform.py b/products/growth/backend/tests/test_enrichment_transform.py
index 8c356738a5c4..41beeb48605c 100644
--- a/products/growth/backend/tests/test_enrichment_transform.py
+++ b/products/growth/backend/tests/test_enrichment_transform.py
@@ -127,3 +127,19 @@ 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}
+
+
+ [
+ ("mapped_when_present", {"ownershipStatus": "ACQUIRED_OR_MERGED"}, "ACQUIRED_OR_MERGED"),
+ ("unset_when_absent", {}, None),
+ ]
+)
+def test_ownership_status_mapping(_name, overrides, expected):
+ fields = transform_harmonic_company(_company(**overrides))
+ assert fields is not None
+ assert fields.ownership_status == expected
+ # Parent resolution is a provider-level concern (REST lookup), not part of the pure transform.
+ assert fields.parent_company is None
+ assert fields.parent_company_domain is None
+ assert "parent_company" not in fields.to_dict()