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): archive Harmonic's enrichmentUrn on every company lookup (#88772)

Matt Brookerb4e3ab4362b3
diff --git a/ee/billing/salesforce_enrichment/constants.py b/ee/billing/salesforce_enrichment/constants.py
index 19c2bdf693a8..c5e8e71ad07d 100644
--- a/ee/billing/salesforce_enrichment/constants.py
+++ b/ee/billing/salesforce_enrichment/constants.py
@@ -17,6 +17,7 @@ HARMONIC_COMPANY_ENRICHMENT_QUERY = """
mutation($identifiers: CompanyEnrichmentIdentifiersInput!) {
enrichCompanyByIdentifiers(identifiers: $identifiers) {
companyFound
+ enrichmentUrn
company {
name
companyType
diff --git a/ee/billing/salesforce_enrichment/harmonic_client.py b/ee/billing/salesforce_enrichment/harmonic_client.py
index f456a5f82e81..2ce9f1de42cf 100644
--- a/ee/billing/salesforce_enrichment/harmonic_client.py
+++ b/ee/billing/salesforce_enrichment/harmonic_client.py
@@ -5,6 +5,7 @@ from django.conf import settings
import aiohttp
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from .constants import (
@@ -15,6 +16,23 @@ from .constants import (
)
+@frozen
+class HarmonicCompanyLookup:
+ """Result of a strict company lookup: the company payload plus its tracking URN.
+
+ enrichment_urn is set on every not-found (the enrichment Harmonic just queued for this
+ domain) and on a hit only when a refresh is pending; it is None on a fresh hit. On a
+ miss seen across multiple domain variations, the first non-null URN wins.
+ """
+
+ company: Optional[dict[str, Any]]
+ enrichment_urn: Optional[str]
+
+
+# Harmonic rate limit is 5 req/s; well under that at one request per batch.
+_ENRICHMENT_STATUS_BATCH_SIZE = 50
+
+
class AsyncHarmonicClient:
"""Async Harmonic API client with controlled concurrency.
@@ -101,18 +119,18 @@ class AsyncHarmonicClient:
return None
- async def enrich_company_by_domain_strict(self, domain: str) -> Optional[dict[str, Any]]:
+ async def enrich_company_by_domain_strict(self, domain: str) -> HarmonicCompanyLookup:
"""Like enrich_company_by_domain, but distinguishes not-found from operational failure.
- Returns None for a genuine not-found: at least one domain variation returned a clean
- GraphQL response with companyFound false, and no variation found the company. A clean
- not-found is an authoritative Harmonic answer even when the other variation errored —
- raising in that mixed case let one failing variation exhaust the caller's retries and
- fail the whole lookup with no archive row. In practice that mixed case has been rare
- (a prod trace attributed almost all no-archive-row orgs to DB errors before the lookup,
- not to this path); the point of returning the miss is that every terminal outcome now
- leaves an archived row, and a row is what the recheck, the backfill, and the
- re-enrichment sweep act on — an activity failure feeds none of them.
+ Returns a company-less lookup for a genuine not-found: at least one domain variation
+ returned a clean GraphQL response with companyFound false, and no variation found the
+ company. A clean not-found is an authoritative Harmonic answer even when the other
+ variation errored. Raising in that mixed case let one failing variation exhaust the
+ caller's retries and fail the whole lookup with no archive row. In practice that mixed
+ case has been rare (a prod trace attributed almost all no-archive-row orgs to DB errors
+ before the lookup, not to this path); the point of returning the miss is that every
+ terminal outcome now leaves an archived row, and a row is what the recheck, the
+ backfill, and the re-enrichment sweep act on. An activity failure feeds none of them.
Operational failures on EVERY variation (network errors, non-2xx status, JSON decode,
GraphQL errors) still re-raise, so callers retry and alert instead of mistaking an
@@ -127,6 +145,7 @@ class AsyncHarmonicClient:
last_error: Optional[Exception] = None
last_error_variation: Optional[str] = None
saw_clean_not_found = False
+ not_found_urn: Optional[str] = None
for domain_variation in domain_variations:
try:
variables = {"identifiers": {"websiteUrl": f"https://{domain_variation}"}}
@@ -148,9 +167,12 @@ class AsyncHarmonicClient:
result = data.get("data", {}).get("enrichCompanyByIdentifiers", {})
if result.get("companyFound"):
- return result.get("company")
+ return HarmonicCompanyLookup(
+ company=result.get("company"), enrichment_urn=result.get("enrichmentUrn")
+ )
if result.get("companyFound") is False:
saw_clean_not_found = True
+ not_found_urn = not_found_urn or result.get("enrichmentUrn")
except Exception as e:
last_error = e
last_error_variation = domain_variation
@@ -160,7 +182,7 @@ class AsyncHarmonicClient:
raise last_error
if last_error is not None:
capture_exception(last_error, {"domain": domain, "failed_variation": last_error_variation})
- return None
+ return HarmonicCompanyLookup(company=None, enrichment_urn=not_found_urn)
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.
@@ -186,6 +208,37 @@ class AsyncHarmonicClient:
response.raise_for_status()
return await response.json()
+ async def get_enrichment_status(self, urns: list[str]) -> dict[str, dict[str, Any]]:
+ """Poll Harmonic's /enrichment_status for a set of tracking URNs, keyed by entity_urn.
+
+ Batches at most 50 URNs per request. Raises on a non-2xx response or a body that
+ isn't a list, rather than silently reporting every URN as unqueried.
+ """
+ if self.session is None:
+ raise RuntimeError("HTTP session not initialized. Use async context manager.")
+
+ statuses: dict[str, dict[str, Any]] = {}
+ for start in range(0, len(urns), _ENRICHMENT_STATUS_BATCH_SIZE):
+ batch = urns[start : start + _ENRICHMENT_STATUS_BATCH_SIZE]
+ await asyncio.sleep(0.2)
+ # Same short cap as get_company_by_urn: this shares the recheck activity's 90s
+ # budget with the domain lookup, so it must not inherit the session's 30s total.
+ async with self.session.get(
+ f"{HARMONIC_BASE_URL}/enrichment_status",
+ params=[("urns", urn) for urn in batch],
+ headers={"apikey": self.api_key},
+ timeout=aiohttp.ClientTimeout(total=10),
+ ) as response:
+ response.raise_for_status()
+ data = await response.json()
+
+ if not isinstance(data, list):
+ raise ValueError(f"unexpected enrichment_status body: {type(data).__name__}")
+ for entry in data:
+ if isinstance(entry, dict) and isinstance(entry.get("entity_urn"), str):
+ statuses[entry["entity_urn"]] = entry
+ return statuses
+
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 f20e8dcb3293..9aa417e87892 100644
--- a/ee/billing/test/test_harmonic_client.py
+++ b/ee/billing/test/test_harmonic_client.py
@@ -2,6 +2,7 @@ import pytest
from unittest.mock import AsyncMock, MagicMock, patch
import aiohttp
+from parameterized import parameterized
from ee.billing.salesforce_enrichment.harmonic_client import AsyncHarmonicClient
@@ -35,12 +36,16 @@ def _client_with_get_responses(*responses):
return client
-def _not_found():
- return _response(json_data={"data": {"enrichCompanyByIdentifiers": {"companyFound": False}}})
+def _not_found(urn=None):
+ return _response(json_data={"data": {"enrichCompanyByIdentifiers": {"companyFound": False, "enrichmentUrn": urn}}})
-def _found(company):
- return _response(json_data={"data": {"enrichCompanyByIdentifiers": {"companyFound": True, "company": company}}})
+def _found(company, urn=None):
+ return _response(
+ json_data={
+ "data": {"enrichCompanyByIdentifiers": {"companyFound": True, "company": company, "enrichmentUrn": urn}}
+ }
+ )
def _missing_company_found_key():
@@ -61,7 +66,8 @@ def _http_500():
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
+ result = await client.enrich_company_by_domain_strict("unknown.example")
+ assert result.company is None
@pytest.mark.asyncio
@@ -78,7 +84,7 @@ 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"}
+ assert result.company == {"name": "PostHog"}
@pytest.mark.asyncio
@@ -88,14 +94,16 @@ async def test_strict_clean_not_found_is_authoritative_when_the_other_variation_
# is an authoritative not-found. Raising here made a deterministically-failing variation
# exhaust the caller's retries and leave the org with no archive row at all.
client = _client_with_responses(_http_500(), _not_found())
- assert await client.enrich_company_by_domain_strict("posthog.com") is None
+ result = await client.enrich_company_by_domain_strict("posthog.com")
+ assert result.company is None
@pytest.mark.asyncio
@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())
async def test_strict_clean_not_found_first_then_error_is_also_not_found():
client = _client_with_responses(_not_found(), _http_500())
- assert await client.enrich_company_by_domain_strict("posthog.com") is None
+ result = await client.enrich_company_by_domain_strict("posthog.com")
+ assert result.company is None
@pytest.mark.asyncio
@@ -110,7 +118,8 @@ async def test_strict_raises_when_companyfound_key_missing_and_sibling_errored()
@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())
async def test_strict_graphql_error_with_clean_not_found_sibling_returns_none():
client = _client_with_responses(_graphql_errors(), _not_found())
- assert await client.enrich_company_by_domain_strict("posthog.com") is None
+ result = await client.enrich_company_by_domain_strict("posthog.com")
+ assert result.company is None
@pytest.mark.asyncio
@@ -118,10 +127,37 @@ async def test_strict_graphql_error_with_clean_not_found_sibling_returns_none():
@patch("ee.billing.salesforce_enrichment.harmonic_client.capture_exception")
async def test_strict_captures_swallowed_error_on_mixed_path(mock_capture_exception):
client = _client_with_responses(_graphql_errors(), _not_found())
- assert await client.enrich_company_by_domain_strict("posthog.com") is None
+ result = await client.enrich_company_by_domain_strict("posthog.com")
+ assert result.company is None
mock_capture_exception.assert_called_once()
+@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())
+async def test_strict_not_found_surfaces_the_tracking_urn():
+ client = _client_with_responses(
+ _not_found(urn="urn:harmonic:enrichment:abc"), _not_found(urn="urn:harmonic:enrichment:abc")
+ )
+ result = await client.enrich_company_by_domain_strict("unknown.example")
+ assert result.company is None
+ assert result.enrichment_urn == "urn:harmonic:enrichment:abc"
+
+
+ [
+ ("no_pending_refresh", None),
+ ("pending_refresh", "urn:harmonic:enrichment:refresh"),
+ ]
+)
+@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())
+async def test_strict_found_surfaces_the_refresh_urn(_name, urn):
+ client = _client_with_responses(_found({"name": "PostHog"}, urn=urn))
+ result = await client.enrich_company_by_domain_strict("posthog.com")
+ assert result.company == {"name": "PostHog"}
+ assert result.enrichment_urn == urn
+
+
@pytest.mark.asyncio
@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())
async def test_strict_sends_api_key_as_header_not_in_url_or_params():
@@ -180,3 +216,44 @@ 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")
+
+
+@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())
+async def test_get_enrichment_status_builds_repeated_urns_query_and_maps_by_entity_urn():
+ entries = [
+ {"entity_urn": "urn:harmonic:enrichment:aaa", "status": "COMPLETE", "enriched_entity_urn": "urn:x:1"},
+ {"entity_urn": "urn:harmonic:enrichment:bbb", "status": "QUEUED", "enriched_entity_urn": None},
+ ]
+ client = _client_with_get_responses(_response(json_data=entries))
+ result = await client.get_enrichment_status(["urn:harmonic:enrichment:aaa", "urn:harmonic:enrichment:bbb"])
+
+ assert result == {
+ "urn:harmonic:enrichment:aaa": entries[0],
+ "urn:harmonic:enrichment:bbb": entries[1],
+ }
+ client.session.get.assert_called_once()
+ call = client.session.get.call_args
+ assert call.args[0] == "https://api.harmonic.ai/enrichment_status"
+ assert call.kwargs["params"] == [
+ ("urns", "urn:harmonic:enrichment:aaa"),
+ ("urns", "urn:harmonic:enrichment:bbb"),
+ ]
+ assert call.kwargs["headers"]["apikey"] == "test-key"
+ assert "test-key" not in call.args[0]
+
+
+@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())
+async def test_get_enrichment_status_raises_on_non_list_body():
+ client = _client_with_get_responses(_response(json_data={"error": "not a list"}))
+ with pytest.raises(ValueError):
+ await client.get_enrichment_status(["urn:harmonic:enrichment:aaa"])
+
+
+@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())
+async def test_get_enrichment_status_reraises_on_http_error():
+ client = _client_with_get_responses(_http_500())
+ with pytest.raises(aiohttp.ClientResponseError):
+ await client.get_enrichment_status(["urn:harmonic:enrichment:aaa"])
diff --git a/products/growth/backend/enrichment/core.py b/products/growth/backend/enrichment/core.py
index 75b7b2b8146f..ab05efd1e620 100644
--- a/products/growth/backend/enrichment/core.py
+++ b/products/growth/backend/enrichment/core.py
@@ -49,10 +49,14 @@ class EnrichmentOutcome:
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).
+ enrichment_status is the polled status of the org's previously archived tracking URN
+ (recheck only; always None on a first attempt), so callers can report it without a
+ second read of the archive.
"""
provider_fields: Optional[EnrichmentFields] = None
fit: Optional[IcpFitResult] = None
+ enrichment_status: Optional[str] = None
def _persisted_score_exists(organization_id: str) -> bool:
@@ -103,6 +107,42 @@ def latest_matched_payload(organization_id: str) -> Optional[dict[str, Any]]:
return None
+def _latest_archived_urn(organization_id: str) -> Optional[str]:
+ """The most recent enrichmentUrn Harmonic has given this org, or None.
+
+ Skips rows whose enrichmentUrn is null or absent: a recheck that lands on an
+ already-matched company archives a null urn (no pending refresh), and the latest row
+ by fetch time is often exactly that. A naive "latest row" read would then shadow an
+ earlier, still-open tracking urn (e.g. the original miss's) with a null one.
+ """
+ payload = (
+ OrganizationEnrichmentFetch.objects.filter(
+ organization_id=organization_id, payload__enrichmentUrn__isnull=False
+ )
+ .exclude(payload__enrichmentUrn=None)
+ .order_by("-fetched_at", "-id")
+ .values_list("payload", flat=True)
+ .first()
+ )
+ urn = payload.get("enrichmentUrn") if isinstance(payload, dict) else None
+ return urn if isinstance(urn, str) else None
+
+
+async def _recheck_enrichment_status(*, organization_id: str, provider: EnrichmentProvider) -> Optional[str]:
+ """Poll the provider for the status of the org's most recently archived tracking URN.
+
+ Never raises: a status-check failure must not block the recheck's own lookup below.
+ """
+ urn = await sync_to_async(_latest_archived_urn)(organization_id)
+ if not urn:
+ return None
+ try:
+ return await provider.enrichment_status_for(urn)
+ except Exception as e:
+ capture_exception(e, {"organization_id": organization_id, "enrichment_urn": urn})
+ 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.
@@ -252,6 +292,12 @@ async def enrich_organization(
Every fetch is archived verbatim — including a not-found — before the live-store write.
The Postgres writes run via sync_to_async to bridge the async provider.
+ On a recheck, the most recently archived non-null enrichmentUrn (if any) is polled for
+ its status before this attempt's own lookup runs, and the result rides along on this
+ fetch's archived payload as enrichmentStatus. The archive then shows what happened to
+ the tracking id a prior attempt saved, alongside the new observation. A first attempt
+ has no prior URN to poll, so it carries no enrichmentStatus key at all.
+
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,
@@ -267,12 +313,20 @@ async def enrich_organization(
fallback wrote a score), since that is what the workflow's matched/upgraded reporting
reads.
"""
+ enrichment_status: Optional[str] = None
+ if is_recheck:
+ enrichment_status = await _recheck_enrichment_status(organization_id=organization_id, provider=provider)
+
lookup = await provider.enrich_by_domain(domain)
+ base_payload = lookup.raw_payload if lookup.raw_payload is not None else _MISS_PAYLOAD
+ archived_payload = {**base_payload, "enrichmentUrn": lookup.enrichment_urn}
+ if is_recheck:
+ archived_payload["enrichmentStatus"] = enrichment_status
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,
+ payload=archived_payload,
is_recheck=is_recheck,
)
@@ -311,7 +365,7 @@ async def enrich_organization(
)
if fields is None and fit is None:
- return EnrichmentOutcome(provider_fields=None, fit=None)
+ return EnrichmentOutcome(provider_fields=None, fit=None, enrichment_status=enrichment_status)
await sync_to_async(write_organization_enrichment)(
organization_id=organization_id,
@@ -322,4 +376,4 @@ async def enrich_organization(
fit=fit,
fit_mirror_distinct_id=fit_mirror_distinct_id,
)
- return EnrichmentOutcome(provider_fields=lookup.fields, fit=fit)
+ return EnrichmentOutcome(provider_fields=lookup.fields, fit=fit, enrichment_status=enrichment_status)
diff --git a/products/growth/backend/enrichment/providers.py b/products/growth/backend/enrichment/providers.py
index b71f9b8f43ff..960d65ef673c 100644
--- a/products/growth/backend/enrichment/providers.py
+++ b/products/growth/backend/enrichment/providers.py
@@ -9,6 +9,7 @@ import abc
import dataclasses
from typing import Any, Optional
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from products.growth.backend.enrichment.fields import EnrichmentFields
@@ -17,16 +18,19 @@ from products.growth.backend.enrichment.transform import transform_harmonic_comp
from ee.billing.salesforce_enrichment.harmonic_client import AsyncHarmonicClient
+@frozen
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.
+ company, or None when the provider returns nothing at all for a miss. `enrichment_urn` is
+ the provider's tracking id for this lookup (Harmonic's enrichmentUrn), archived alongside
+ the payload so a later poll can check whether enrichment has since completed.
"""
fields: Optional[EnrichmentFields]
raw_payload: Optional[dict[str, Any]]
+ enrichment_urn: Optional[str] = None
class EnrichmentProvider(abc.ABC):
@@ -42,6 +46,13 @@ class EnrichmentProvider(abc.ABC):
and alert, rather than conflating an outage with a genuine not-found.
"""
+ async def enrichment_status_for(self, urn: str) -> Optional[str]:
+ """Poll the provider for the status of a previously archived tracking URN.
+
+ No-op by default; a provider without async enrichment tracking has nothing to poll.
+ """
+ return None
+
def _parent_company_urn(company: dict[str, Any]) -> Optional[str]:
"""Pick the parent-company URN from `relatedCompanies`: subsidiaryOf wins over acquiredBy.
@@ -64,11 +75,19 @@ class HarmonicEnrichmentProvider(EnrichmentProvider):
async def enrich_by_domain(self, domain: str) -> ProviderLookup:
async with AsyncHarmonicClient() as client:
- company = await client.enrich_company_by_domain_strict(domain)
+ lookup = await client.enrich_company_by_domain_strict(domain)
+ company = lookup.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)
+ return ProviderLookup(fields=fields, raw_payload=company, enrichment_urn=lookup.enrichment_urn)
+
+ async def enrichment_status_for(self, urn: str) -> Optional[str]:
+ async with AsyncHarmonicClient() as client:
+ statuses = await client.get_enrichment_status([urn])
+ entry = statuses.get(urn)
+ status = entry.get("status") if isinstance(entry, dict) else None
+ return status if isinstance(status, str) else None
async def _with_parent_company(
self, client: AsyncHarmonicClient, company: dict[str, Any], fields: EnrichmentFields
diff --git a/products/growth/backend/management/commands/backfill_harmonic_ownership.py b/products/growth/backend/management/commands/backfill_harmonic_ownership.py
index 5a1978c93bdf..fe4a99d6b7c3 100644
--- a/products/growth/backend/management/commands/backfill_harmonic_ownership.py
+++ b/products/growth/backend/management/commands/backfill_harmonic_ownership.py
@@ -154,10 +154,11 @@ class Command(BaseCommand):
# path (core.py) — the refreshed payload now carries ownershipStatus/relatedCompanies for
# the labels pipeline and any future offline re-analysis to read.
if not dry_run:
+ base_payload = lookup.raw_payload if lookup.raw_payload is not None else _MISS_PAYLOAD
archive_provider_fetch(
organization_id=str(record.organization_id),
provider=provider.name,
- payload=lookup.raw_payload if lookup.raw_payload is not None else _MISS_PAYLOAD,
+ payload={**base_payload, "enrichmentUrn": lookup.enrichment_urn},
is_recheck=True,
)
diff --git a/products/growth/backend/temporal/signup_enrichment/reenrichment.py b/products/growth/backend/temporal/signup_enrichment/reenrichment.py
index af5f0a0cc3be..bde7f44bddf4 100644
--- a/products/growth/backend/temporal/signup_enrichment/reenrichment.py
+++ b/products/growth/backend/temporal/signup_enrichment/reenrichment.py
@@ -295,6 +295,7 @@ async def reenrich_organization_activity(inputs: ReenrichOrgInputs) -> dict[str,
"organization_id": inputs.organization_id,
"matched": matched,
"icp_fit_status": status,
+ "harmonic_enrichment_status": outcome.enrichment_status,
**observed,
},
groups={"organization": inputs.organization_id},
diff --git a/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py b/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py
index a0401debb62a..f82aa0cef0c6 100644
--- a/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py
+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_reenrichment.py
@@ -218,6 +218,7 @@ class TestReenrichOrganizationActivity(BaseTest):
outcome = EnrichmentOutcome(
provider_fields=EnrichmentFields(company_type="STARTUP"),
fit=IcpFitResult(status="scored", score=48),
+ enrichment_status="NOT_FOUND",
)
result, pha_client, enrich = self._run(outcome)
@@ -235,6 +236,7 @@ class TestReenrichOrganizationActivity(BaseTest):
assert event.kwargs["event"] == "icp_reenrichment_completed"
assert event.kwargs["properties"]["icp_fit_status"] == "scored"
assert event.kwargs["properties"]["matched"] is True
+ assert event.kwargs["properties"]["harmonic_enrichment_status"] == "NOT_FOUND"
pha_client.shutdown.assert_called_once()
def test_still_unmatched_reports_honestly(self):
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 4ad68efe25c8..8fd4a248c66c 100644
--- a/products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py
+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_workflow.py
@@ -57,7 +57,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")
miss = EnrichmentOutcome(provider_fields=None, fit=IcpFitResult(status="not_found"))
- match = EnrichmentOutcome(provider_fields=fields, fit=IcpFitResult(status="scored", score=61))
+ match = EnrichmentOutcome(
+ provider_fields=fields, fit=IcpFitResult(status="scored", score=61), enrichment_status="COMPLETE"
+ )
result, pha_client, enrich, snapshot = await _run([miss, match])
assert result == {"matched": True, "fields_filled": 3}
@@ -75,6 +77,7 @@ async def test_miss_then_recheck_upgrades_without_a_second_completed_event():
"fields_filled": 3,
"organization_id": "org-1",
"icp_fit_status": "scored",
+ "harmonic_enrichment_status": "COMPLETE",
}
# The launch signal fires exactly once — on the first attempt, unchanged.
completed = _events(pha_client, "signup_enrichment_completed")
diff --git a/products/growth/backend/temporal/signup_enrichment/workflow.py b/products/growth/backend/temporal/signup_enrichment/workflow.py
index a6712e182046..3d4ebfb05bef 100644
--- a/products/growth/backend/temporal/signup_enrichment/workflow.py
+++ b/products/growth/backend/temporal/signup_enrichment/workflow.py
@@ -160,6 +160,7 @@ async def enrich_signup_organization_activity(
"fields_filled": len(filled),
"organization_id": inputs.organization_id,
"icp_fit_status": fit.status if fit else None,
+ "harmonic_enrichment_status": outcome.enrichment_status,
},
groups={"organization": inputs.organization_id},
)
diff --git a/products/growth/backend/tests/test_backfill_harmonic_ownership.py b/products/growth/backend/tests/test_backfill_harmonic_ownership.py
index 80ad0ec4ee2b..d9ae212c1337 100644
--- a/products/growth/backend/tests/test_backfill_harmonic_ownership.py
+++ b/products/growth/backend/tests/test_backfill_harmonic_ownership.py
@@ -23,9 +23,10 @@ def _lookup(
parent_company: Optional[str] = None,
parent_company_domain: Optional[str] = None,
found: bool = True,
+ enrichment_urn: Optional[str] = None,
) -> ProviderLookup:
if not found:
- return ProviderLookup(fields=None, raw_payload=None)
+ return ProviderLookup(fields=None, raw_payload=None, enrichment_urn=enrichment_urn)
fields = EnrichmentFields(
company_type="STARTUP", # a fresh-fetch field the backfill must never write back.
ownership_status=ownership_status,
@@ -33,7 +34,7 @@ def _lookup(
parent_company_domain=parent_company_domain,
)
raw_payload = {"companyType": "STARTUP", "ownershipStatus": ownership_status}
- return ProviderLookup(fields=fields, raw_payload=raw_payload)
+ return ProviderLookup(fields=fields, raw_payload=raw_payload, enrichment_urn=enrichment_urn)
def _mock_provider(side_effect: list[Any]) -> MagicMock:
@@ -77,6 +78,7 @@ class TestWritePath(_BackfillTestCase):
ownership_status="ACQUIRED_OR_MERGED",
parent_company="Salesforce",
parent_company_domain="salesforce.com",
+ enrichment_urn="urn:harmonic:enrichment:archived",
)
]
)
@@ -107,7 +109,11 @@ class TestWritePath(_BackfillTestCase):
pha_client.shutdown.assert_called_once()
fetch = OrganizationEnrichmentFetch.objects.get(organization=record.organization, is_recheck=True)
assert fetch.provider == "harmonic"
- assert fetch.payload == {"companyType": "STARTUP", "ownershipStatus": "ACQUIRED_OR_MERGED"}
+ assert fetch.payload == {
+ "companyType": "STARTUP",
+ "ownershipStatus": "ACQUIRED_OR_MERGED",
+ "enrichmentUrn": "urn:harmonic:enrichment:archived",
+ }
def test_skips_the_write_but_still_counts_processed_when_ownership_status_is_none(self):
record = self._org(email="[email protected]", data={"company_type": "STARTUP"})
@@ -214,7 +220,7 @@ class TestDryRun(_BackfillTestCase):
class TestArchive(_BackfillTestCase):
def test_archives_the_miss_payload_on_a_not_found_fetch(self):
record = self._org(email="[email protected]", data={})
- provider_cls = _mock_provider([_lookup(found=False)])
+ provider_cls = _mock_provider([_lookup(found=False, enrichment_urn="urn:harmonic:enrichment:miss")])
with (
patch(f"{_COMMAND_MODULE}.HarmonicEnrichmentProvider", provider_cls),
@@ -224,7 +230,7 @@ class TestArchive(_BackfillTestCase):
fetch = OrganizationEnrichmentFetch.objects.get(organization=record.organization, is_recheck=True)
assert fetch.provider == "harmonic"
- assert fetch.payload == {"companyFound": False}
+ assert fetch.payload == {"companyFound": False, "enrichmentUrn": "urn:harmonic:enrichment:miss"}
def test_a_fetch_failure_archives_nothing(self):
record = self._org(email="[email protected]", data={})
diff --git a/products/growth/backend/tests/test_enrichment_core.py b/products/growth/backend/tests/test_enrichment_core.py
index c3e1d509d617..b94e78ec62fb 100644
--- a/products/growth/backend/tests/test_enrichment_core.py
+++ b/products/growth/backend/tests/test_enrichment_core.py
@@ -1,3 +1,5 @@
+from typing import Optional
+
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -5,7 +7,7 @@ from asgiref.sync import async_to_sync
from parameterized import parameterized
from products.growth.backend.enrichment.bridge import ClayBridgeInputs
-from products.growth.backend.enrichment.core import enrich_organization
+from products.growth.backend.enrichment.core import _MISS_PAYLOAD, 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
@@ -15,12 +17,27 @@ from products.growth.backend.models import IcpScoringConfig, OrganizationEnrichm
class _FakeProvider(EnrichmentProvider):
name = "harmonic"
- def __init__(self, lookup: ProviderLookup):
+ def __init__(
+ self,
+ lookup: ProviderLookup,
+ *,
+ status: Optional[str] = None,
+ status_side_effect: Optional[Exception] = None,
+ ):
self._lookup = lookup
+ self._status = status
+ self._status_side_effect = status_side_effect
+ self.status_calls: list[str] = []
async def enrich_by_domain(self, domain: str) -> ProviderLookup:
return self._lookup
+ async def enrichment_status_for(self, urn: str) -> Optional[str]:
+ self.status_calls.append(urn)
+ if self._status_side_effect is not None:
+ raise self._status_side_effect
+ return self._status
+
# 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),
@@ -91,6 +108,7 @@ class TestEnrichmentCore(BaseTest):
person=None,
geoip_country_code=None,
domain="stripe.com",
+ provider=None,
):
person_patch_kwargs = {"side_effect": person} if isinstance(person, Exception) else {"return_value": person}
clay_patch_kwargs = (
@@ -103,7 +121,7 @@ class TestEnrichmentCore(BaseTest):
return async_to_sync(enrich_organization)(
organization_id=str(self.organization.id),
domain=domain,
- provider=_FakeProvider(lookup),
+ provider=provider or _FakeProvider(lookup),
pha_client=pha_client or MagicMock(),
is_recheck=is_recheck,
role_at_organization=role_at_organization,
@@ -116,15 +134,38 @@ class TestEnrichmentCore(BaseTest):
def test_archives_raw_payload_and_writes_live_stores_on_match(self):
company = {"companyType": "STARTUP", "funding": {"fundingStage": "SEED"}}
fields = EnrichmentFields(company_type="STARTUP")
- outcome = self._enrich(ProviderLookup(fields=fields, raw_payload=company))
+ outcome = self._enrich(
+ ProviderLookup(fields=fields, raw_payload=company, enrichment_urn="urn:harmonic:enrichment:abc")
+ )
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 row.payload == {**company, "enrichmentUrn": "urn:harmonic:enrichment:abc"}
assert OrganizationEnrichment.objects.filter(organization=self.organization).exists()
+ @parameterized.expand(
+ [
+ ("miss", None, None, {"companyFound": False, "enrichmentUrn": "urn:harmonic:enrichment:xyz"}),
+ (
+ "hit",
+ {"companyType": "STARTUP"},
+ EnrichmentFields(company_type="STARTUP"),
+ {"companyType": "STARTUP", "enrichmentUrn": "urn:harmonic:enrichment:xyz"},
+ ),
+ ]
+ )
+ def test_archived_payload_carries_the_enrichment_urn(self, _name, raw_payload, fields, expected_payload):
+ self._enrich(
+ ProviderLookup(fields=fields, raw_payload=raw_payload, enrichment_urn="urn:harmonic:enrichment:xyz")
+ )
+
+ row = OrganizationEnrichmentFetch.objects.get(organization=self.organization)
+ assert row.payload == expected_payload
+ # The module-level miss placeholder must never be mutated by the archive write.
+ assert _MISS_PAYLOAD == {"companyFound": False}
+
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
@@ -519,3 +560,102 @@ class TestEnrichmentCore(BaseTest):
pha_client.set.assert_called_once_with(
distinct_id="signer-distinct-id", properties={"icp_fit_status": "insufficient_data"}
)
+
+ # ---------- recheck enrichment status instrumentation ----------
+
+ def test_recheck_polls_the_stored_urn_and_archives_the_status(self):
+ # The first attempt's miss left a real tracking urn; a prior recheck already landed on
+ # that stub with no pending refresh (a null urn). The latest row is the null one, so
+ # polling must walk back to the first attempt's urn, not stop at the latest row.
+ OrganizationEnrichmentFetch.objects.create(
+ organization=self.organization,
+ provider="harmonic",
+ payload={"companyFound": False, "enrichmentUrn": "urn:harmonic:enrichment:prior"},
+ )
+ OrganizationEnrichmentFetch.objects.create(
+ organization=self.organization,
+ provider="harmonic",
+ is_recheck=True,
+ payload={"companyType": "STARTUP", "enrichmentUrn": None},
+ )
+ lookup = ProviderLookup(
+ fields=EnrichmentFields(company_type="STARTUP"),
+ raw_payload={"companyType": "STARTUP"},
+ enrichment_urn="urn:harmonic:enrichment:new",
+ )
+ provider = _FakeProvider(lookup, status="COMPLETE")
+
+ self._enrich(lookup, is_recheck=True, provider=provider)
+
+ assert provider.status_calls == ["urn:harmonic:enrichment:prior"]
+ row = OrganizationEnrichmentFetch.objects.filter(organization=self.organization).order_by("-fetched_at", "-id")[
+ 0
+ ]
+ assert row.payload["enrichmentStatus"] == "COMPLETE"
+ assert row.payload["enrichmentUrn"] == "urn:harmonic:enrichment:new"
+
+ def test_recheck_with_no_stored_urn_makes_no_status_call(self):
+ # Neither an absent key nor an explicit JSON null counts as a stored urn.
+ OrganizationEnrichmentFetch.objects.create(
+ organization=self.organization, provider="harmonic", payload={"companyType": "STARTUP"}
+ )
+ OrganizationEnrichmentFetch.objects.create(
+ organization=self.organization,
+ provider="harmonic",
+ is_recheck=True,
+ payload={"companyType": "STARTUP", "enrichmentUrn": None},
+ )
+ lookup = ProviderLookup(fields=None, raw_payload=None, enrichment_urn=None)
+ provider = _FakeProvider(lookup, status="COMPLETE")
+
+ self._enrich(lookup, is_recheck=True, provider=provider)
+
+ assert provider.status_calls == []
+
+ def test_status_call_failure_is_captured_and_the_recheck_still_archives_and_writes(self):
+ OrganizationEnrichmentFetch.objects.create(
+ organization=self.organization,
+ provider="harmonic",
+ payload={"companyFound": False, "enrichmentUrn": "urn:harmonic:enrichment:prior"},
+ )
+ fields = EnrichmentFields(headcount=750, country="US", founded_year=2021)
+ lookup = ProviderLookup(fields=fields, raw_payload=_empty_shell(), enrichment_urn="urn:harmonic:enrichment:new")
+ provider = _FakeProvider(lookup, status_side_effect=RuntimeError("harmonic is down"))
+
+ with patch("products.growth.backend.enrichment.core.capture_exception") as capture_mock:
+ outcome = self._enrich(lookup, is_recheck=True, provider=provider, role_at_organization="engineering")
+
+ capture_mock.assert_called_once()
+ exc_arg, context_arg = capture_mock.call_args.args
+ assert isinstance(exc_arg, RuntimeError)
+ assert context_arg == {
+ "organization_id": str(self.organization.id),
+ "enrichment_urn": "urn:harmonic:enrichment:prior",
+ }
+ assert outcome.provider_fields is fields
+ row = OrganizationEnrichmentFetch.objects.get(organization=self.organization, is_recheck=True)
+ assert row.payload["enrichmentStatus"] is None
+ assert row.payload["enrichmentUrn"] == "urn:harmonic:enrichment:new"
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data["icp_score"] == 12
+
+ def test_first_attempt_never_polls_status(self):
+ # A prior archived urn exists (e.g. from a backfill re-run), so an unguarded call
+ # would find something to poll; the first-attempt path must still never call it.
+ OrganizationEnrichmentFetch.objects.create(
+ organization=self.organization,
+ provider="harmonic",
+ payload={"companyFound": False, "enrichmentUrn": "urn:harmonic:enrichment:prior"},
+ )
+ lookup = ProviderLookup(
+ fields=EnrichmentFields(company_type="STARTUP"),
+ raw_payload={"companyType": "STARTUP"},
+ enrichment_urn="urn:harmonic:enrichment:new",
+ )
+ provider = _FakeProvider(lookup, status="COMPLETE")
+
+ self._enrich(lookup, is_recheck=False, provider=provider)
+
+ assert provider.status_calls == []
+ row = OrganizationEnrichmentFetch.objects.filter(organization=self.organization).latest("fetched_at")
+ assert "enrichmentStatus" not in row.payload
diff --git a/products/growth/backend/tests/test_enrichment_providers.py b/products/growth/backend/tests/test_enrichment_providers.py
index a278b9919a5c..32c0790b9adb 100644
--- a/products/growth/backend/tests/test_enrichment_providers.py
+++ b/products/growth/backend/tests/test_enrichment_providers.py
@@ -3,11 +3,15 @@ from unittest.mock import AsyncMock, MagicMock, patch
from products.growth.backend.enrichment.providers import HarmonicEnrichmentProvider
+from ee.billing.salesforce_enrichment.harmonic_client import HarmonicCompanyLookup
-def _fake_harmonic_client(company, *, parent_company=None, parent_side_effect=None):
+
+def _fake_harmonic_client(company, *, enrichment_urn=None, 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.enrich_company_by_domain_strict = AsyncMock(
+ return_value=HarmonicCompanyLookup(company=company, enrichment_urn=enrichment_urn)
+ )
client.get_company_by_urn = AsyncMock(return_value=parent_company, side_effect=parent_side_effect)
cm = MagicMock()
cm.__aenter__ = AsyncMock(return_value=client)
@@ -18,7 +22,7 @@ def _fake_harmonic_client(company, *, parent_company=None, parent_side_effect=No
@pytest.mark.asyncio
async def test_enrich_by_domain_transforms_response_and_keeps_raw_payload():
company = {"companyType": "STARTUP", "funding": {"fundingStage": "SEED"}}
- cm, client = _fake_harmonic_client(company)
+ cm, client = _fake_harmonic_client(company, enrichment_urn="urn:harmonic:enrichment:abc")
with patch("products.growth.backend.enrichment.providers.AsyncHarmonicClient", return_value=cm):
lookup = await HarmonicEnrichmentProvider().enrich_by_domain("posthog.com")
@@ -27,17 +31,19 @@ async def test_enrich_by_domain_transforms_response_and_keeps_raw_payload():
assert lookup.fields.funding_stage == "SEED"
# The raw provider response is preserved verbatim for the archive.
assert lookup.raw_payload == company
+ assert lookup.enrichment_urn == "urn:harmonic:enrichment:abc"
client.enrich_company_by_domain_strict.assert_awaited_once_with("posthog.com")
@pytest.mark.asyncio
async def test_enrich_by_domain_returns_no_fields_and_no_payload_when_company_not_found():
- cm, _ = _fake_harmonic_client(None)
+ cm, _ = _fake_harmonic_client(None, enrichment_urn="urn:harmonic:enrichment:xyz")
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
+ assert lookup.enrichment_urn == "urn:harmonic:enrichment:xyz"
@pytest.mark.asyncio
@@ -131,3 +137,31 @@ async def test_enrich_by_domain_skips_parent_resolution_for_empty_urn():
assert lookup.fields.parent_company is None
assert lookup.fields.parent_company_domain is None
client.get_company_by_urn.assert_not_awaited()
+
+
+def _fake_status_client(statuses):
+ client = MagicMock()
+ client.get_enrichment_status = AsyncMock(return_value=statuses)
+ cm = MagicMock()
+ cm.__aenter__ = AsyncMock(return_value=client)
+ cm.__aexit__ = AsyncMock(return_value=False)
+ return cm, client
+
+
+async def test_enrichment_status_for_returns_the_status_string():
+ cm, client = _fake_status_client({"urn:harmonic:enrichment:abc": {"status": "COMPLETE"}})
+ with patch("products.growth.backend.enrichment.providers.AsyncHarmonicClient", return_value=cm):
+ status = await HarmonicEnrichmentProvider().enrichment_status_for("urn:harmonic:enrichment:abc")
+
+ assert status == "COMPLETE"
+ client.get_enrichment_status.assert_awaited_once_with(["urn:harmonic:enrichment:abc"])
+
+
+async def test_enrichment_status_for_returns_none_when_urn_is_absent_from_the_response():
+ cm, _ = _fake_status_client({})
+ with patch("products.growth.backend.enrichment.providers.AsyncHarmonicClient", return_value=cm):
+ status = await HarmonicEnrichmentProvider().enrichment_status_for("urn:harmonic:enrichment:abc")
+
+ assert status is None