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): poll Harmonic enrichment status daily and stamp it on the org (#93858)

Matt Brooker8024bbacce64
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 203fb9127226..69e03692f245 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -104,7 +104,10 @@ from products.experiments.backend.temporal.schedule import (
create_experiment_precompute_enrollment_census_schedule,
)
from products.exports.backend.temporal.subscriptions.types import ScheduleAllSubscriptionsWorkflowInputs
-from products.growth.backend.temporal.signup_enrichment.schedule import create_icp_reenrichment_sweep_schedule
+from products.growth.backend.temporal.signup_enrichment.schedule import (
+ create_harmonic_status_poll_schedule,
+ create_icp_reenrichment_sweep_schedule,
+)
from products.logs.backend.facade.temporal import create_logs_volume_tick_schedule
from products.managed_warehouse.backend.facade.temporal import DucklakeCompactionInput
from products.replay_vision.backend.temporal.estimates import create_replay_vision_estimates_schedule
@@ -964,6 +967,7 @@ if settings.CLOUD_DEPLOYMENT:
# The sweep re-fetches each region's own orgs from Harmonic, and only US and EU carry the key.
if settings.CLOUD_DEPLOYMENT in ("US", "EU"):
schedules.append(create_icp_reenrichment_sweep_schedule)
+ schedules.append(create_harmonic_status_poll_schedule)
if settings.EE_AVAILABLE:
schedules.append(create_schedule_all_subscriptions_schedule)
diff --git a/products/growth/backend/enrichment/providers.py b/products/growth/backend/enrichment/providers.py
index 2d87b92a676b..5376df7f9a9d 100644
--- a/products/growth/backend/enrichment/providers.py
+++ b/products/growth/backend/enrichment/providers.py
@@ -51,7 +51,13 @@ class EnrichmentProvider(abc.ABC):
No-op by default; a provider without async enrichment tracking has nothing to poll.
"""
- return None
+ return (await self.enrichment_statuses_for([urn])).get(urn)
+
+ async def enrichment_statuses_for(self, urns: list[str]) -> dict[str, str]:
+ """A URN the provider has nothing to report for is absent from the result rather than mapped to None,
+ so callers can use plain membership checks.
+ """
+ return {}
def _parent_company_urn(company: dict[str, Any]) -> Optional[str]:
@@ -82,12 +88,16 @@ class HarmonicEnrichmentProvider(EnrichmentProvider):
fields = await self._with_parent_company(client, company, fields)
return ProviderLookup(fields=fields, raw_payload=company, enrichment_urn=lookup.enrichment_urn)
- async def enrichment_status_for(self, urn: str) -> Optional[str]:
+ async def enrichment_statuses_for(self, urns: list[str]) -> dict[str, str]:
+ if not urns:
+ return {}
async with AsyncHarmonicClient(source="growth_enrichment_provider") 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
+ statuses = await client.get_enrichment_status(urns)
+ return {
+ urn: entry["status"]
+ for urn, entry in statuses.items()
+ if isinstance(entry, dict) and isinstance(entry.get("status"), str)
+ }
async def _with_parent_company(
self, client: AsyncHarmonicClient, company: dict[str, Any], fields: EnrichmentFields
diff --git a/products/growth/backend/enrichment/writer.py b/products/growth/backend/enrichment/writer.py
index 718b844c98d7..21840a65afa7 100644
--- a/products/growth/backend/enrichment/writer.py
+++ b/products/growth/backend/enrichment/writer.py
@@ -29,6 +29,12 @@ from products.growth.backend.models import OrganizationEnrichment, OrganizationE
ORGANIZATION_GROUP_TYPE = "organization"
+# Published in org_icp_fit_current, so these names are a contract and must stay spelled out
+# as constants rather than inlined.
+HARMONIC_STATUS_KEY = "harmonic_enrichment_status"
+HARMONIC_STATUS_AT_KEY = "harmonic_enrichment_status_at"
+HARMONIC_URN_KEY = "harmonic_enrichment_urn"
+
# Every fit key tied to one evaluation's numeric outcome. An evaluation that doesn't
# produce one of these strips it, so the record never carries a value the current
# evaluation didn't produce (e.g. components surviving a later disqualification).
@@ -63,6 +69,25 @@ def merge_into_record(
record.save(update_fields=["data", "updated_at"])
+def write_harmonic_enrichment_status(
+ organization_id: str, *, status: str, observed_at: str, urn: str, pha_client: Client
+) -> Optional[str]:
+ """Reads the record's stored status inside the same locked write that merges the new one, so a caller can
+ tell a genuine transition from a retried batch re-stamping the same status.
+ """
+ values = {HARMONIC_STATUS_KEY: status, HARMONIC_STATUS_AT_KEY: observed_at, HARMONIC_URN_KEY: urn}
+ previous_status: Optional[str] = None
+
+ def _merge(current: dict[str, Any]) -> dict[str, Any]:
+ nonlocal previous_status
+ previous_status = current.get(HARMONIC_STATUS_KEY)
+ return values
+
+ merge_into_record(organization_id, _merge)
+ pha_client.group_identify(ORGANIZATION_GROUP_TYPE, organization_id, properties=values)
+ return previous_status
+
+
def _fit_record_writes(fit: IcpFitResult) -> tuple[dict[str, Any], list[str]]:
"""The Postgres (data) writes and key removals for one fit evaluation.
diff --git a/products/growth/backend/temporal/signup_enrichment/__init__.py b/products/growth/backend/temporal/signup_enrichment/__init__.py
index 5b85aa29d2ca..919ee3f06538 100644
--- a/products/growth/backend/temporal/signup_enrichment/__init__.py
+++ b/products/growth/backend/temporal/signup_enrichment/__init__.py
@@ -1,3 +1,9 @@
+from products.growth.backend.temporal.signup_enrichment.harmonic_status_poll import (
+ HarmonicEnrichmentStatusPollWorkflow,
+ poll_status_batch_activity,
+ report_status_poll_run_activity,
+ select_status_poll_candidates_activity,
+)
from products.growth.backend.temporal.signup_enrichment.reenrichment import (
IcpReenrichmentSweepWorkflow,
reenrich_organization_activity,
@@ -9,11 +15,14 @@ from products.growth.backend.temporal.signup_enrichment.workflow import (
enrich_signup_organization_activity,
)
-WORKFLOWS = [SignupEnrichmentWorkflow, IcpReenrichmentSweepWorkflow]
+WORKFLOWS = [SignupEnrichmentWorkflow, IcpReenrichmentSweepWorkflow, HarmonicEnrichmentStatusPollWorkflow]
ACTIVITIES = [
enrich_signup_organization_activity,
select_reenrichment_candidates_activity,
reenrich_organization_activity,
report_sweep_run_activity,
+ select_status_poll_candidates_activity,
+ poll_status_batch_activity,
+ report_status_poll_run_activity,
]
diff --git a/products/growth/backend/temporal/signup_enrichment/harmonic_status_poll.py b/products/growth/backend/temporal/signup_enrichment/harmonic_status_poll.py
new file mode 100644
index 000000000000..5208b73ea014
--- /dev/null
+++ b/products/growth/backend/temporal/signup_enrichment/harmonic_status_poll.py
@@ -0,0 +1,316 @@
+"""Daily poller for Harmonic's async enrichment status.
+
+Batches every org's most recently archived open URN into `GET /enrichment_status` calls, since
+Harmonic has no webhook, and stamps the result onto `OrganizationEnrichment.data` for the
+re-enrichment sweep and RevOps to read.
+"""
+
+import typing
+import datetime as dt
+import itertools
+import dataclasses
+
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy
+
+from posthog.exceptions_capture import capture_exception
+from posthog.ph_client import get_regional_ph_client, ph_scoped_capture
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.logger import get_logger
+from posthog.temporal.common.utils import close_db_connections
+from posthog.utils import get_instance_region
+
+from products.growth.backend.enrichment.writer import (
+ HARMONIC_STATUS_AT_KEY,
+ HARMONIC_STATUS_KEY,
+ HARMONIC_URN_KEY,
+ write_harmonic_enrichment_status,
+)
+from products.growth.backend.temporal.signup_enrichment.workflow import MAX_ENRICH_ATTEMPTS
+
+LOGGER = get_logger(__name__)
+
+STATUS_CHANGED_EVENT = "harmonic_enrichment_status_changed"
+STATUS_POLL_RUN_EVENT = "harmonic_enrichment_status_poll_completed"
+
+# STALLED is derived here; Harmonic never returns it.
+NON_TERMINAL_STATUSES = ("QUEUED", "IN_PROGRESS")
+TERMINAL_STATUSES = ("COMPLETE", "FAILED", "NOT_FOUND")
+STALLED_STATUS = "STALLED"
+
+# Harmonic's own guidance is "a few hours"; a URN still pending past this age is stamped STALLED
+# so a consumer can tell late from never.
+STALL_AGE_HOURS = 14 * 24
+
+# Past this age the org's URN drops from selection and its stamp is left as last observed;
+# a later lookup issues a fresh URN and restarts the window.
+MAX_URN_AGE_DAYS = 30
+
+# Harmonic caps URNs per /enrichment_status call.
+POLL_BATCH_SIZE = 50
+
+# A hard ceiling well under Temporal's per-payload limit, so a growing backlog degrades to a
+# smaller nightly slice instead of one day failing outright.
+MAX_CANDIDATES_PER_RUN = 5000
+
+SELECT_ACTIVITY_TIMEOUT = dt.timedelta(minutes=5)
+# One Harmonic HTTP call plus a batch's worth of record writes and a final analytics flush,
+# sized with headroom over their combined cost.
+POLL_BATCH_ACTIVITY_TIMEOUT = dt.timedelta(seconds=60)
+
+
[email protected](frozen=True)
+class HarmonicStatusPollInputs:
+ pass
+
+
+@close_db_connections
+async def select_status_poll_candidates_activity(inputs: HarmonicStatusPollInputs) -> dict[str, typing.Any]:
+ """Read-only, so its kill-switch and region guards live here rather than in the schedule, letting a
+ config flip take effect on the next run without touching Temporal state.
+ """
+ from asgiref.sync import sync_to_async # noqa: PLC0415
+
+ from posthog.models.instance_setting import get_instance_setting # noqa: PLC0415
+
+ from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch # noqa: PLC0415
+
+ logger = LOGGER.bind()
+
+ if not await sync_to_async(get_instance_setting)("GROWTH_SIGNUP_ENRICHMENT_ENABLED"):
+ logger.info("harmonic_status_poll_skipped_kill_switch")
+ return {"candidates": [], "eligible": 0}
+ if get_instance_region() not in ("US", "EU"):
+ logger.info("harmonic_status_poll_skipped_region")
+ return {"candidates": [], "eligible": 0}
+
+ def _select() -> tuple[list[dict[str, typing.Any]], int]:
+ now = dt.datetime.now(dt.UTC)
+ urn_cutoff = now - dt.timedelta(days=MAX_URN_AGE_DAYS)
+
+ # Filtering non-null URN and the age cutoff ahead of the DISTINCT ON keeps a later null-URN fetch from
+ # shadowing an earlier open one, and is still correct since an org's true latest non-null-URN fetch
+ # lying outside the window means every earlier fetch does too.
+ latest_open_urn_fetches = (
+ OrganizationEnrichmentFetch.objects.filter(
+ provider="harmonic", payload__enrichmentUrn__isnull=False, fetched_at__gte=urn_cutoff
+ )
+ .exclude(payload__enrichmentUrn=None)
+ .order_by("organization_id", "-fetched_at", "-id")
+ .distinct("organization_id")
+ .only("organization_id", "payload", "fetched_at")
+ )
+
+ open_urns: dict[str, tuple[str, dt.datetime]] = {}
+ for row in latest_open_urn_fetches:
+ urn = row.payload.get("enrichmentUrn") if isinstance(row.payload, dict) else None
+ if isinstance(urn, str) and urn:
+ open_urns[str(row.organization_id)] = (urn, row.fetched_at)
+
+ if not open_urns:
+ return [], 0
+
+ stored = {
+ str(record.organization_id): record.data
+ for record in OrganizationEnrichment.objects.filter(organization_id__in=open_urns.keys()).only(
+ "organization_id", "data"
+ )
+ }
+
+ eligible = []
+ for organization_id, (urn, fetched_at) in open_urns.items():
+ data = stored.get(organization_id, {})
+ stored_status = data.get(HARMONIC_STATUS_KEY)
+ same_urn = data.get(HARMONIC_URN_KEY) == urn
+ if stored_status in TERMINAL_STATUSES and same_urn:
+ continue
+ eligible.append(
+ {
+ "organization_id": organization_id,
+ "enrichment_urn": urn,
+ "urn_fetched_at": fetched_at.isoformat(),
+ "previous_status": stored_status if same_urn else None,
+ "_never_polled": stored_status is None,
+ "_status_at": data.get(HARMONIC_STATUS_AT_KEY) or "",
+ }
+ )
+
+ # Never-polled orgs go first so a backlog doesn't starve first contact; the rest is
+ # oldest-checked-first so the cap doesn't repeatedly re-poll the same recently-checked orgs.
+ eligible.sort(key=lambda candidate: (not candidate["_never_polled"], candidate["_status_at"]))
+ candidates = [
+ {key: value for key, value in candidate.items() if not key.startswith("_")}
+ for candidate in eligible[:MAX_CANDIDATES_PER_RUN]
+ ]
+ return candidates, len(eligible)
+
+ candidates, eligible_count = await sync_to_async(_select)()
+ logger.info("harmonic_status_poll_selected", count=len(candidates), eligible=eligible_count)
+ return {"candidates": candidates, "eligible": eligible_count}
+
+
+@close_db_connections
+async def poll_status_batch_activity(candidates: list[dict[str, typing.Any]]) -> dict[str, typing.Any]:
+ """Re-checks the kill switch here, not only at selection, since a run spanning many batches must not
+ keep making paid Harmonic calls after the switch flips off.
+ """
+ from asgiref.sync import sync_to_async # noqa: PLC0415
+
+ from posthog.models.instance_setting import get_instance_setting # noqa: PLC0415
+
+ from products.growth.backend.enrichment.providers import HarmonicEnrichmentProvider # noqa: PLC0415
+
+ logger = LOGGER.bind()
+
+ empty_result = {"polled": 0, "unobserved": 0, "changed": 0, "stalled": 0}
+
+ if not await sync_to_async(get_instance_setting)("GROWTH_SIGNUP_ENRICHMENT_ENABLED"):
+ logger.info("harmonic_status_poll_skipped_kill_switch")
+ return dict(empty_result)
+
+ pha_client = get_regional_ph_client()
+ if pha_client is None:
+ logger.error("harmonic_status_poll_no_regional_client")
+ return dict(empty_result)
+
+ polled = unobserved = changed = stalled = 0
+ try:
+ urns = [candidate["enrichment_urn"] for candidate in candidates]
+ try:
+ statuses = await HarmonicEnrichmentProvider().enrichment_statuses_for(urns)
+ except Exception as e:
+ capture_exception(e, {"batch_size": len(candidates)})
+ raise
+
+ now = dt.datetime.now(dt.UTC)
+ observed_at = now.isoformat()
+
+ for candidate in candidates:
+ organization_id = candidate["organization_id"]
+ urn = candidate["enrichment_urn"]
+ raw_status = statuses.get(urn)
+ if raw_status is None:
+ # No entry back for this URN: leave the existing stamp alone rather than guess.
+ unobserved += 1
+ continue
+ polled += 1
+
+ urn_age = now - dt.datetime.fromisoformat(candidate["urn_fetched_at"])
+ hours_since_urn_issued = round(urn_age.total_seconds() / 3600)
+ effective_status = (
+ STALLED_STATUS
+ if raw_status in NON_TERMINAL_STATUSES and urn_age >= dt.timedelta(hours=STALL_AGE_HOURS)
+ else raw_status
+ )
+
+ previous_status = await sync_to_async(write_harmonic_enrichment_status)(
+ organization_id, status=effective_status, observed_at=observed_at, urn=urn, pha_client=pha_client
+ )
+
+ if effective_status == STALLED_STATUS:
+ stalled += 1
+
+ if effective_status != previous_status:
+ changed += 1
+ pha_client.capture(
+ distinct_id=organization_id,
+ event=STATUS_CHANGED_EVENT,
+ properties={
+ "organization_id": organization_id,
+ "previous_status": previous_status,
+ "status": effective_status,
+ "hours_since_urn_issued": hours_since_urn_issued,
+ },
+ groups={"organization": organization_id},
+ )
+ finally:
+ pha_client.shutdown()
+
+ logger.info(
+ "harmonic_status_poll_batch_completed", polled=polled, unobserved=unobserved, changed=changed, stalled=stalled
+ )
+ return {"polled": polled, "unobserved": unobserved, "changed": changed, "stalled": stalled}
+
+
[email protected](frozen=True)
+class HarmonicStatusPollRunSummary:
+ eligible: int
+ selected: int
+ polled: int
+ unobserved: int
+ changed: int
+ stalled: int
+ errors: int
+
+
+def report_status_poll_run_activity(summary: HarmonicStatusPollRunSummary) -> None:
+ """One event per run, so an absence alert can see a poller that stopped firing."""
+ region = get_instance_region()
+ if region not in ("US", "EU"):
+ LOGGER.error("harmonic_status_poll_no_regional_client")
+ return
+
+ with ph_scoped_capture(region=region) as capture:
+ capture(
+ distinct_id="harmonic-status-poller",
+ event=STATUS_POLL_RUN_EVENT,
+ properties=dataclasses.asdict(summary),
+ )
+
+
[email protected](name="harmonic-enrichment-status-poll")
+class HarmonicEnrichmentStatusPollWorkflow(PostHogWorkflow):
+ """Sequential batches keep the daily poll inside Harmonic's rate limit."""
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> HarmonicStatusPollInputs:
+ return HarmonicStatusPollInputs()
+
+ @workflow.run
+ async def run(self, inputs: HarmonicStatusPollInputs) -> dict[str, typing.Any]:
+ selection = await workflow.execute_activity(
+ select_status_poll_candidates_activity,
+ inputs,
+ start_to_close_timeout=SELECT_ACTIVITY_TIMEOUT,
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ candidates = selection["candidates"]
+
+ polled = unobserved = changed = stalled = errors = 0
+ for batch in itertools.batched(candidates, POLL_BATCH_SIZE, strict=False):
+ try:
+ result = await workflow.execute_activity(
+ poll_status_batch_activity,
+ list(batch),
+ start_to_close_timeout=POLL_BATCH_ACTIVITY_TIMEOUT,
+ retry_policy=RetryPolicy(
+ maximum_attempts=MAX_ENRICH_ATTEMPTS, initial_interval=dt.timedelta(seconds=5)
+ ),
+ )
+ polled += result["polled"]
+ unobserved += result["unobserved"]
+ changed += result["changed"]
+ stalled += result["stalled"]
+ except Exception:
+ # A batch's own retries are exhausted; one failed batch must not fail the whole run.
+ errors += len(batch)
+
+ summary = HarmonicStatusPollRunSummary(
+ eligible=selection["eligible"],
+ selected=len(candidates),
+ polled=polled,
+ unobserved=unobserved,
+ changed=changed,
+ stalled=stalled,
+ errors=errors,
+ )
+ await workflow.execute_activity(
+ report_status_poll_run_activity,
+ summary,
+ start_to_close_timeout=dt.timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ return dataclasses.asdict(summary)
diff --git a/products/growth/backend/temporal/signup_enrichment/schedule.py b/products/growth/backend/temporal/signup_enrichment/schedule.py
index db338453e3e8..02b8f5024063 100644
--- a/products/growth/backend/temporal/signup_enrichment/schedule.py
+++ b/products/growth/backend/temporal/signup_enrichment/schedule.py
@@ -1,8 +1,7 @@
-"""The Temporal Schedule for the daily ICP re-enrichment sweep.
+"""Temporal Schedules for the signup_enrichment daily jobs.
-Registered from posthog/temporal/schedule.py, so every deploy upserts it. The schedule only
-starts the workflow; the sweep re-checks the kill switch, region, and cap on every run, so
-pausing it is an instance-setting change, not a Temporal operation.
+Each schedule only starts its workflow; pausing one is an instance-setting change, since the
+workflow itself re-checks the kill switch and region on every run.
"""
from django.conf import settings
@@ -18,6 +17,7 @@ from temporalio.client import (
from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+from products.growth.backend.temporal.signup_enrichment.harmonic_status_poll import HarmonicStatusPollInputs
from products.growth.backend.temporal.signup_enrichment.reenrichment import IcpReenrichmentSweepInputs
SCHEDULE_ID = "icp-reenrichment-sweep-daily"
@@ -47,3 +47,31 @@ async def create_icp_reenrichment_sweep_schedule(client: Client) -> None:
await a_update_schedule(client, SCHEDULE_ID, schedule)
else:
await a_create_schedule(client, SCHEDULE_ID, schedule, trigger_immediately=False)
+
+
+HARMONIC_STATUS_POLL_SCHEDULE_ID = "harmonic-enrichment-status-poll-daily"
+
+# Ahead of the sweep so a same-day stamp is available to it.
+HARMONIC_STATUS_POLL_CRON = "40 6 * * *"
+
+
+def build_harmonic_status_poll_schedule() -> Schedule:
+ return Schedule(
+ action=ScheduleActionStartWorkflow(
+ "harmonic-enrichment-status-poll",
+ HarmonicStatusPollInputs(),
+ id=HARMONIC_STATUS_POLL_SCHEDULE_ID,
+ task_queue=settings.SIGNUP_ENRICHMENT_TASK_QUEUE,
+ ),
+ spec=ScheduleSpec(cron_expressions=[HARMONIC_STATUS_POLL_CRON]),
+ # A run that overruns its slot must not stack a second run of Harmonic calls on top.
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ )
+
+
+async def create_harmonic_status_poll_schedule(client: Client) -> None:
+ schedule = build_harmonic_status_poll_schedule()
+ if await a_schedule_exists(client, HARMONIC_STATUS_POLL_SCHEDULE_ID):
+ await a_update_schedule(client, HARMONIC_STATUS_POLL_SCHEDULE_ID, schedule)
+ else:
+ await a_create_schedule(client, HARMONIC_STATUS_POLL_SCHEDULE_ID, schedule, trigger_immediately=False)
diff --git a/products/growth/backend/temporal/signup_enrichment/tests/test_harmonic_status_poll.py b/products/growth/backend/temporal/signup_enrichment/tests/test_harmonic_status_poll.py
new file mode 100644
index 000000000000..f61c7de7a69a
--- /dev/null
+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_harmonic_status_poll.py
@@ -0,0 +1,388 @@
+import datetime as dt
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
+
+from asgiref.sync import async_to_sync
+from parameterized import parameterized
+
+from posthog.models.instance_setting import override_instance_config
+from posthog.models.organization import Organization
+
+from products.growth.backend.enrichment.writer import HARMONIC_STATUS_AT_KEY, HARMONIC_STATUS_KEY, HARMONIC_URN_KEY
+from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch
+from products.growth.backend.temporal.signup_enrichment.harmonic_status_poll import (
+ STALL_AGE_HOURS,
+ HarmonicStatusPollInputs,
+ HarmonicStatusPollRunSummary,
+ poll_status_batch_activity,
+ report_status_poll_run_activity,
+ select_status_poll_candidates_activity,
+)
+
+_MODULE = "products.growth.backend.temporal.signup_enrichment.harmonic_status_poll"
+
+
+def _now() -> dt.datetime:
+ return dt.datetime.now(dt.UTC)
+
+
+def _fetch(organization: Organization, *, urn: str | None, days_ago: float = 0, is_recheck: bool = False):
+ row = OrganizationEnrichmentFetch.objects.create(
+ organization=organization,
+ provider="harmonic",
+ is_recheck=is_recheck,
+ payload={"companyFound": True, "enrichmentUrn": urn},
+ )
+ OrganizationEnrichmentFetch.objects.filter(id=row.id).update(fetched_at=_now() - dt.timedelta(days=days_ago))
+ return row
+
+
+@override_settings(CLOUD_DEPLOYMENT="US")
+class TestSelectStatusPollCandidates(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.enterContext(override_instance_config("GROWTH_SIGNUP_ENRICHMENT_ENABLED", True))
+
+ def _select_result(self):
+ with patch(f"{_MODULE}.LOGGER"):
+ return async_to_sync(select_status_poll_candidates_activity)(HarmonicStatusPollInputs())
+
+ def _select(self):
+ return self._select_result()["candidates"]
+
+ def test_selects_an_org_with_a_fresh_open_urn_and_no_stored_status(self):
+ organization = Organization.objects.create(name="open.example")
+ _fetch(organization, urn="urn:harmonic:enrichment:open", days_ago=1)
+
+ candidates = self._select()
+
+ assert len(candidates) == 1
+ assert candidates[0]["organization_id"] == str(organization.id)
+ assert candidates[0]["enrichment_urn"] == "urn:harmonic:enrichment:open"
+ assert candidates[0]["previous_status"] is None
+
+ def test_excludes_an_org_whose_open_urn_is_30_days_or_older(self):
+ organization = Organization.objects.create(name="stale.example")
+ _fetch(organization, urn="urn:harmonic:enrichment:stale", days_ago=31)
+
+ assert self._select() == []
+
+ def test_excludes_an_org_with_a_terminal_stored_status_for_the_same_urn(self):
+ for status in ("COMPLETE", "FAILED", "NOT_FOUND"):
+ organization = Organization.objects.create(name=f"{status.lower()}.example")
+ urn = f"urn:harmonic:enrichment:{status}"
+ _fetch(organization, urn=urn, days_ago=2)
+ OrganizationEnrichment.objects.create(
+ organization=organization, data={HARMONIC_STATUS_KEY: status, HARMONIC_URN_KEY: urn}
+ )
+
+ assert self._select() == []
+
+ def test_includes_an_org_whose_terminal_stamp_is_for_an_older_urn(self):
+ # A re-lookup (backfill_harmonic_ownership, a manual recheck) can issue a fresh URN for
+ # an org whose old one already resolved. The old terminal stamp must not block the new
+ # URN from ever being polled.
+ organization = Organization.objects.create(name="rearmed.example")
+ _fetch(organization, urn="urn:harmonic:enrichment:A", days_ago=10)
+ _fetch(organization, urn="urn:harmonic:enrichment:B", days_ago=1)
+ OrganizationEnrichment.objects.create(
+ organization=organization,
+ data={HARMONIC_STATUS_KEY: "COMPLETE", HARMONIC_URN_KEY: "urn:harmonic:enrichment:A"},
+ )
+
+ candidates = self._select()
+
+ assert len(candidates) == 1
+ assert candidates[0]["enrichment_urn"] == "urn:harmonic:enrichment:B"
+ assert candidates[0]["previous_status"] is None
+
+ def test_includes_an_org_with_a_pending_or_stalled_stored_status(self):
+ for status in ("QUEUED", "IN_PROGRESS", "STALLED"):
+ organization = Organization.objects.create(name=f"{status.lower()}.example")
+ _fetch(organization, urn=f"urn:harmonic:enrichment:{status}", days_ago=2)
+ OrganizationEnrichment.objects.create(organization=organization, data={HARMONIC_STATUS_KEY: status})
+
+ assert len(self._select()) == 3
+
+ def test_a_later_null_urn_fetch_does_not_shadow_the_earlier_open_urn(self):
+ # Same gotcha _latest_archived_urn documents: a recheck that lands on an already-matched
+ # company archives a null URN, and a naive "latest row" read would shadow the earlier,
+ # still-open tracking URN with it.
+ organization = Organization.objects.create(name="shadow.example")
+ _fetch(organization, urn="urn:harmonic:enrichment:first", days_ago=5)
+ _fetch(organization, urn=None, days_ago=1, is_recheck=True)
+
+ candidates = self._select()
+
+ assert len(candidates) == 1
+ assert candidates[0]["enrichment_urn"] == "urn:harmonic:enrichment:first"
+
+ def test_caps_selection_never_polled_first_then_oldest_checked(self):
+ fresh = Organization.objects.create(name="fresh.example")
+ _fetch(fresh, urn="urn:harmonic:enrichment:fresh", days_ago=1)
+
+ old_check = Organization.objects.create(name="old-check.example")
+ _fetch(old_check, urn="urn:harmonic:enrichment:old-check", days_ago=2)
+ OrganizationEnrichment.objects.create(
+ organization=old_check,
+ data={
+ HARMONIC_STATUS_KEY: "QUEUED",
+ HARMONIC_URN_KEY: "urn:harmonic:enrichment:old-check",
+ HARMONIC_STATUS_AT_KEY: (_now() - dt.timedelta(days=5)).isoformat(),
+ },
+ )
+
+ recent_check = Organization.objects.create(name="recent-check.example")
+ _fetch(recent_check, urn="urn:harmonic:enrichment:recent-check", days_ago=2)
+ OrganizationEnrichment.objects.create(
+ organization=recent_check,
+ data={
+ HARMONIC_STATUS_KEY: "QUEUED",
+ HARMONIC_URN_KEY: "urn:harmonic:enrichment:recent-check",
+ HARMONIC_STATUS_AT_KEY: (_now() - dt.timedelta(hours=1)).isoformat(),
+ },
+ )
+
+ with patch(f"{_MODULE}.MAX_CANDIDATES_PER_RUN", 2):
+ result = self._select_result()
+
+ assert result["eligible"] == 3
+ assert [c["organization_id"] for c in result["candidates"]] == [str(fresh.id), str(old_check.id)]
+
+ def test_kill_switch_stops_selection(self):
+ organization = Organization.objects.create(name="off.example")
+ _fetch(organization, urn="urn:harmonic:enrichment:off", days_ago=1)
+
+ with override_instance_config("GROWTH_SIGNUP_ENRICHMENT_ENABLED", False):
+ assert self._select() == []
+
+ def test_region_gate_stops_selection(self):
+ organization = Organization.objects.create(name="region.example")
+ _fetch(organization, urn="urn:harmonic:enrichment:region", days_ago=1)
+
+ with override_settings(CLOUD_DEPLOYMENT="DEV"):
+ assert self._select() == []
+
+
+@override_settings(CLOUD_DEPLOYMENT="US")
+class TestPollStatusBatchActivity(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.enterContext(override_instance_config("GROWTH_SIGNUP_ENRICHMENT_ENABLED", True))
+
+ def _candidate(self, organization: Organization, *, urn: str, hours_ago: float = 1.0):
+ return {
+ "organization_id": str(organization.id),
+ "enrichment_urn": urn,
+ "urn_fetched_at": (_now() - dt.timedelta(hours=hours_ago)).isoformat(),
+ "previous_status": None,
+ }
+
+ def _run(self, candidates, statuses: dict[str, str]):
+ pha_client = MagicMock()
+ provider = MagicMock()
+
+ async def _statuses_for(urns):
+ return statuses
+
+ provider.enrichment_statuses_for = _statuses_for
+ with (
+ patch(f"{_MODULE}.get_regional_ph_client", return_value=pha_client),
+ patch("products.growth.backend.enrichment.providers.HarmonicEnrichmentProvider", return_value=provider),
+ ):
+ result = async_to_sync(poll_status_batch_activity)(candidates)
+ return result, pha_client
+
+ def test_stamps_the_record_and_projects_the_group_properties(self):
+ organization = Organization.objects.create(name="stamp.example")
+ candidate = self._candidate(organization, urn="urn:harmonic:enrichment:stamp")
+
+ result, pha_client = self._run([candidate], {"urn:harmonic:enrichment:stamp": "COMPLETE"})
+
+ assert result == {"polled": 1, "unobserved": 0, "changed": 1, "stalled": 0}
+ record = OrganizationEnrichment.objects.get(organization=organization)
+ assert record.data[HARMONIC_STATUS_KEY] == "COMPLETE"
+ assert record.data[HARMONIC_URN_KEY] == "urn:harmonic:enrichment:stamp"
+ assert record.data[HARMONIC_STATUS_AT_KEY]
+ pha_client.group_identify.assert_called_once()
+ group_call = pha_client.group_identify.call_args
+ assert group_call.args == ("organization", str(organization.id))
+ assert group_call.kwargs["properties"][HARMONIC_STATUS_KEY] == "COMPLETE"
+
+ def test_emits_a_transition_event_only_when_the_stored_status_actually_changes(self):
+ organization = Organization.objects.create(name="unchanged.example")
+ OrganizationEnrichment.objects.create(organization=organization, data={HARMONIC_STATUS_KEY: "QUEUED"})
+ candidate = self._candidate(organization, urn="urn:harmonic:enrichment:same")
+
+ result, pha_client = self._run([candidate], {"urn:harmonic:enrichment:same": "QUEUED"})
+
+ assert result == {"polled": 1, "unobserved": 0, "changed": 0, "stalled": 0}
+ pha_client.capture.assert_not_called()
+
+ def test_a_retried_batch_that_repeats_a_write_emits_no_event(self):
+ # The retry replays the same batch after a partial failure; selection-time
+ # previous_status ("QUEUED") is stale by the time this write lands, because the first
+ # attempt already wrote IN_PROGRESS. Only the record's actual stored status must gate
+ # the event.
+ organization = Organization.objects.create(name="retried.example")
+ OrganizationEnrichment.objects.create(organization=organization, data={HARMONIC_STATUS_KEY: "IN_PROGRESS"})
+ candidate = self._candidate(organization, urn="urn:harmonic:enrichment:retried")
+ candidate["previous_status"] = "QUEUED"
+
+ result, pha_client = self._run([candidate], {"urn:harmonic:enrichment:retried": "IN_PROGRESS"})
+
+ assert result == {"polled": 1, "unobserved": 0, "changed": 0, "stalled": 0}
+ pha_client.capture.assert_not_called()
+
+ def test_transition_event_carries_previous_status_and_hours_since_urn_issued(self):
+ organization = Organization.objects.create(name="transition.example")
+ OrganizationEnrichment.objects.create(organization=organization, data={HARMONIC_STATUS_KEY: "QUEUED"})
+ candidate = self._candidate(organization, urn="urn:harmonic:enrichment:transition", hours_ago=6)
+
+ _, pha_client = self._run([candidate], {"urn:harmonic:enrichment:transition": "COMPLETE"})
+
+ pha_client.capture.assert_called_once()
+ call = pha_client.capture.call_args
+ assert call.kwargs["event"] == "harmonic_enrichment_status_changed"
+ assert call.kwargs["distinct_id"] == str(organization.id)
+ assert call.kwargs["groups"] == {"organization": str(organization.id)}
+ properties = call.kwargs["properties"]
+ assert properties["previous_status"] == "QUEUED"
+ assert properties["status"] == "COMPLETE"
+ assert properties["hours_since_urn_issued"] == 6
+
+ def test_stalled_status_is_stamped_once_the_urn_is_14_days_old_and_still_pending(self):
+ organization = Organization.objects.create(name="stalled.example")
+ OrganizationEnrichment.objects.create(organization=organization, data={HARMONIC_STATUS_KEY: "IN_PROGRESS"})
+ candidate = self._candidate(organization, urn="urn:harmonic:enrichment:stalled", hours_ago=STALL_AGE_HOURS)
+
+ result, _ = self._run([candidate], {"urn:harmonic:enrichment:stalled": "IN_PROGRESS"})
+
+ assert result == {"polled": 1, "unobserved": 0, "changed": 1, "stalled": 1}
+ record = OrganizationEnrichment.objects.get(organization=organization)
+ assert record.data[HARMONIC_STATUS_KEY] == "STALLED"
+
+ def test_a_stalled_org_that_completes_late_records_the_transition(self):
+ organization = Organization.objects.create(name="latecomplete.example")
+ OrganizationEnrichment.objects.create(organization=organization, data={HARMONIC_STATUS_KEY: "STALLED"})
+ candidate = self._candidate(
+ organization, urn="urn:harmonic:enrichment:late", hours_ago=STALL_AGE_HOURS + 24 * 5
+ )
+
+ result, _ = self._run([candidate], {"urn:harmonic:enrichment:late": "COMPLETE"})
+
+ assert result == {"polled": 1, "unobserved": 0, "changed": 1, "stalled": 0}
+ record = OrganizationEnrichment.objects.get(organization=organization)
+ assert record.data[HARMONIC_STATUS_KEY] == "COMPLETE"
+
+ def test_a_stalled_org_still_pending_stays_stalled_without_a_transition(self):
+ organization = Organization.objects.create(name="stillstalled.example")
+ OrganizationEnrichment.objects.create(organization=organization, data={HARMONIC_STATUS_KEY: "STALLED"})
+ candidate = self._candidate(organization, urn="urn:harmonic:enrichment:still", hours_ago=STALL_AGE_HOURS + 24)
+
+ result, _ = self._run([candidate], {"urn:harmonic:enrichment:still": "IN_PROGRESS"})
+
+ assert result == {"polled": 1, "unobserved": 0, "changed": 0, "stalled": 1}
+ record = OrganizationEnrichment.objects.get(organization=organization)
+ assert record.data[HARMONIC_STATUS_KEY] == "STALLED"
+
+ @parameterized.expand([("an_hour_under", STALL_AGE_HOURS - 1), ("rounds_up_to_threshold", STALL_AGE_HOURS - 0.4)])
+ def test_a_urn_still_under_the_stall_age_stays_pending(self, _name: str, hours_ago: float):
+ organization = Organization.objects.create(name="notyetstalled.example")
+ OrganizationEnrichment.objects.create(organization=organization, data={HARMONIC_STATUS_KEY: "IN_PROGRESS"})
+ candidate = self._candidate(organization, urn="urn:harmonic:enrichment:notyet", hours_ago=hours_ago)
+
+ result, _ = self._run([candidate], {"urn:harmonic:enrichment:notyet": "IN_PROGRESS"})
+
+ assert result == {"polled": 1, "unobserved": 0, "changed": 0, "stalled": 0}
+ record = OrganizationEnrichment.objects.get(organization=organization)
+ assert record.data[HARMONIC_STATUS_KEY] == "IN_PROGRESS"
+
+ def test_leaves_the_stamp_untouched_for_a_urn_missing_from_the_response(self):
+ organization = Organization.objects.create(name="missing.example")
+ candidate = self._candidate(organization, urn="urn:harmonic:enrichment:missing")
+
+ result, _ = self._run([candidate], {})
+
+ assert result == {"polled": 0, "unobserved": 1, "changed": 0, "stalled": 0}
+ assert not OrganizationEnrichment.objects.filter(organization=organization).exists()
+
+ def test_a_batch_failure_captures_the_exception_writes_nothing_and_reraises(self):
+ organization = Organization.objects.create(name="boom.example")
+ candidate = self._candidate(organization, urn="urn:harmonic:enrichment:boom")
+ pha_client = MagicMock()
+ provider = MagicMock()
+
+ async def _raise(urns):
+ raise RuntimeError("harmonic is down")
+
+ provider.enrichment_statuses_for = _raise
+ with (
+ patch(f"{_MODULE}.get_regional_ph_client", return_value=pha_client),
+ patch("products.growth.backend.enrichment.providers.HarmonicEnrichmentProvider", return_value=provider),
+ patch(f"{_MODULE}.capture_exception") as mock_capture,
+ ):
+ with self.assertRaises(RuntimeError):
+ async_to_sync(poll_status_batch_activity)([candidate])
+
+ mock_capture.assert_called_once()
+ assert not OrganizationEnrichment.objects.filter(organization=organization).exists()
+ pha_client.shutdown.assert_called_once()
+
+ def test_kill_switch_skips_the_batch_without_calling_the_provider(self):
+ organization = Organization.objects.create(name="killed.example")
+ candidate = self._candidate(organization, urn="urn:harmonic:enrichment:killed")
+
+ with override_instance_config("GROWTH_SIGNUP_ENRICHMENT_ENABLED", False):
+ with patch("products.growth.backend.enrichment.providers.HarmonicEnrichmentProvider") as provider_cls:
+ result = async_to_sync(poll_status_batch_activity)([candidate])
+
+ assert result == {"polled": 0, "unobserved": 0, "changed": 0, "stalled": 0}
+ provider_cls.assert_not_called()
+ assert not OrganizationEnrichment.objects.filter(organization=organization).exists()
+
+
+class TestReportStatusPollRunActivity(BaseTest):
+ def test_emits_one_event_with_the_counts(self):
+ capture = MagicMock()
+ scoped_capture = MagicMock()
+ scoped_capture.__enter__.return_value = capture
+ with (
+ patch(f"{_MODULE}.get_instance_region", return_value="EU"),
+ patch(f"{_MODULE}.ph_scoped_capture", return_value=scoped_capture) as scoped_capture_factory,
+ ):
+ report_status_poll_run_activity(
+ HarmonicStatusPollRunSummary(
+ eligible=8, selected=5, polled=5, unobserved=0, changed=2, stalled=1, errors=0
+ )
+ )
+
+ scoped_capture_factory.assert_called_once_with(region="EU")
+ event = capture.call_args.kwargs
+ assert event["event"] == "harmonic_enrichment_status_poll_completed"
+ assert event["properties"] == {
+ "eligible": 8,
+ "selected": 5,
+ "polled": 5,
+ "unobserved": 0,
+ "changed": 2,
+ "stalled": 1,
+ "errors": 0,
+ }
+ scoped_capture.__exit__.assert_called_once()
+
+ def test_skips_outside_a_cloud_region(self):
+ with (
+ patch(f"{_MODULE}.get_instance_region", return_value=None),
+ patch(f"{_MODULE}.ph_scoped_capture") as scoped_capture_factory,
+ ):
+ report_status_poll_run_activity(
+ HarmonicStatusPollRunSummary(
+ eligible=0, selected=0, polled=0, unobserved=0, changed=0, stalled=0, errors=0
+ )
+ )
+
+ scoped_capture_factory.assert_not_called()
diff --git a/products/growth/backend/temporal/signup_enrichment/tests/test_schedule.py b/products/growth/backend/temporal/signup_enrichment/tests/test_schedule.py
index 5a04415fbe51..b5b4f3fb626f 100644
--- a/products/growth/backend/temporal/signup_enrichment/tests/test_schedule.py
+++ b/products/growth/backend/temporal/signup_enrichment/tests/test_schedule.py
@@ -4,7 +4,10 @@ from temporalio.client import ScheduleActionStartWorkflow, ScheduleOverlapPolicy
from products.growth.backend.temporal.signup_enrichment.schedule import (
CRON,
+ HARMONIC_STATUS_POLL_CRON,
+ HARMONIC_STATUS_POLL_SCHEDULE_ID,
SCHEDULE_ID,
+ build_harmonic_status_poll_schedule,
build_icp_reenrichment_sweep_schedule,
)
@@ -27,3 +30,25 @@ class TestIcpReenrichmentSweepSchedule:
schedule = build_icp_reenrichment_sweep_schedule()
assert schedule.policy.overlap == ScheduleOverlapPolicy.SKIP
assert schedule.spec.cron_expressions == [CRON]
+
+
+def _poll_action() -> ScheduleActionStartWorkflow:
+ action = build_harmonic_status_poll_schedule().action
+ assert isinstance(action, ScheduleActionStartWorkflow)
+ return action
+
+
+class TestHarmonicStatusPollSchedule:
+ def test_targets_the_signup_enrichment_queue(self) -> None:
+ assert _poll_action().task_queue == settings.SIGNUP_ENRICHMENT_TASK_QUEUE
+
+ def test_starts_the_poll_workflow_under_a_stable_id(self) -> None:
+ assert _poll_action().workflow == "harmonic-enrichment-status-poll"
+ assert _poll_action().id == HARMONIC_STATUS_POLL_SCHEDULE_ID
+
+ def test_skips_an_overlapping_run_and_fires_daily_an_hour_before_the_sweep(self) -> None:
+ schedule = build_harmonic_status_poll_schedule()
+ assert schedule.policy.overlap == ScheduleOverlapPolicy.SKIP
+ assert schedule.spec.cron_expressions == [HARMONIC_STATUS_POLL_CRON]
+ assert HARMONIC_STATUS_POLL_CRON == "40 6 * * *"
+ assert CRON == "40 7 * * *"
diff --git a/products/growth/backend/tests/test_enrichment_providers.py b/products/growth/backend/tests/test_enrichment_providers.py
index 32c0790b9adb..9314f116e57c 100644
--- a/products/growth/backend/tests/test_enrichment_providers.py
+++ b/products/growth/backend/tests/test_enrichment_providers.py
@@ -1,7 +1,7 @@
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
-from products.growth.backend.enrichment.providers import HarmonicEnrichmentProvider
+from products.growth.backend.enrichment.providers import EnrichmentProvider, HarmonicEnrichmentProvider, ProviderLookup
from ee.billing.salesforce_enrichment.harmonic_client import HarmonicCompanyLookup
@@ -165,3 +165,59 @@ async def test_enrichment_status_for_returns_none_when_urn_is_absent_from_the_re
status = await HarmonicEnrichmentProvider().enrichment_status_for("urn:harmonic:enrichment:abc")
assert status is None
+
+
+async def test_enrichment_statuses_for_returns_a_dict_keyed_by_urn():
+ cm, client = _fake_status_client(
+ {
+ "urn:harmonic:enrichment:a": {"status": "COMPLETE"},
+ "urn:harmonic:enrichment:b": {"status": "QUEUED"},
+ }
+ )
+ with patch("products.growth.backend.enrichment.providers.AsyncHarmonicClient", return_value=cm):
+ statuses = await HarmonicEnrichmentProvider().enrichment_statuses_for(
+ ["urn:harmonic:enrichment:a", "urn:harmonic:enrichment:b"]
+ )
+
+ assert statuses == {"urn:harmonic:enrichment:a": "COMPLETE", "urn:harmonic:enrichment:b": "QUEUED"}
+ client.get_enrichment_status.assert_awaited_once_with(["urn:harmonic:enrichment:a", "urn:harmonic:enrichment:b"])
+
+
+async def test_enrichment_statuses_for_omits_urns_missing_or_malformed_in_the_response():
+ cm, _ = _fake_status_client(
+ {
+ "urn:harmonic:enrichment:a": {"status": "COMPLETE"},
+ "urn:harmonic:enrichment:b": {"no_status_key": True},
+ "urn:harmonic:enrichment:c": "not a dict",
+ }
+ )
+ with patch("products.growth.backend.enrichment.providers.AsyncHarmonicClient", return_value=cm):
+ statuses = await HarmonicEnrichmentProvider().enrichment_statuses_for(
+ ["urn:harmonic:enrichment:a", "urn:harmonic:enrichment:b", "urn:harmonic:enrichment:c"]
+ )
+
+ assert statuses == {"urn:harmonic:enrichment:a": "COMPLETE"}
+
+
+async def test_enrichment_statuses_for_returns_empty_dict_for_no_urns_without_calling_the_client():
+ cm, client = _fake_status_client({})
+ with patch("products.growth.backend.enrichment.providers.AsyncHarmonicClient", return_value=cm):
+ statuses = await HarmonicEnrichmentProvider().enrichment_statuses_for([])
+
+ assert statuses == {}
+ client.get_enrichment_status.assert_not_called()
+
+
+class _NoOpProvider(EnrichmentProvider):
+ name = "noop"
+
+ async def enrich_by_domain(self, domain: str) -> ProviderLookup:
+ raise NotImplementedError
+
+
+async def test_enrichment_statuses_for_defaults_to_an_empty_dict_for_a_provider_without_tracking():
+ assert await _NoOpProvider().enrichment_statuses_for(["urn:harmonic:enrichment:abc"]) == {}
diff --git a/products/growth/backend/tests/test_enrichment_writer.py b/products/growth/backend/tests/test_enrichment_writer.py
index 08c25c6fc38f..3b2b6c9c2040 100644
--- a/products/growth/backend/tests/test_enrichment_writer.py
+++ b/products/growth/backend/tests/test_enrichment_writer.py
@@ -3,7 +3,11 @@ from unittest.mock import MagicMock
from products.growth.backend.enrichment.fields import EnrichmentFields
from products.growth.backend.enrichment.fit_score import IcpFitResult
-from products.growth.backend.enrichment.writer import record_signup_work_email, write_organization_enrichment
+from products.growth.backend.enrichment.writer import (
+ record_signup_work_email,
+ write_harmonic_enrichment_status,
+ write_organization_enrichment,
+)
from products.growth.backend.models import OrganizationEnrichment
@@ -265,6 +269,39 @@ class TestEnrichmentWriter(BaseTest):
record.refresh_from_db()
assert record.data["signup_role"] == "founder" # blank role never clobbers a recorded one
+ def test_write_harmonic_enrichment_status_merges_without_clobbering_and_returns_the_previous_status(self):
+ OrganizationEnrichment.objects.create(
+ organization=self.organization,
+ data={"company_type_deterministic": "yc", "harmonic_enrichment_status": "QUEUED"},
+ )
+ pha_client = MagicMock()
+
+ previous = write_harmonic_enrichment_status(
+ str(self.organization.id),
+ status="COMPLETE",
+ observed_at="2026-09-01T00:00:00+00:00",
+ urn="urn:harmonic:enrichment:abc",
+ pha_client=pha_client,
+ )
+
+ assert previous == "QUEUED"
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data == {
+ "company_type_deterministic": "yc",
+ "harmonic_enrichment_status": "COMPLETE",
+ "harmonic_enrichment_status_at": "2026-09-01T00:00:00+00:00",
+ "harmonic_enrichment_urn": "urn:harmonic:enrichment:abc",
+ }
+ pha_client.group_identify.assert_called_once_with(
+ "organization",
+ str(self.organization.id),
+ properties={
+ "harmonic_enrichment_status": "COMPLETE",
+ "harmonic_enrichment_status_at": "2026-09-01T00:00:00+00:00",
+ "harmonic_enrichment_urn": "urn:harmonic:enrichment:abc",
+ },
+ )
+
def test_no_op_when_no_fields_and_no_scores(self):
pha_client = MagicMock()
write_organization_enrichment(