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): backfill command for Harmonic ownership fields with base-rate stats (#79072)

Matt Brooker82f4512ddd1b
diff --git a/products/growth/backend/management/commands/backfill_harmonic_ownership.py b/products/growth/backend/management/commands/backfill_harmonic_ownership.py
new file mode 100644
index 000000000000..70e785fe9e75
--- /dev/null
+++ b/products/growth/backend/management/commands/backfill_harmonic_ownership.py
@@ -0,0 +1,198 @@
+"""Backfill ownership_status/parent_company/parent_company_domain for orgs enriched before
+Harmonic ownership lookup shipped.
+
+Targets OrganizationEnrichment rows with no "ownership_status" key in `data` — that key is
+absent both for pre-feature orgs and for orgs where Harmonic has no ownership opinion, so a
+re-run is a no-op for the latter rather than a retry; see the write skip below. Re-fetches each
+org fresh from Harmonic (paced by --sleep) rather than replaying the archived payload, since
+the field didn't exist in the response schema this repo requested at the time of the original
+fetch. The fresh fetch is archived the same way the live path archives one (including a
+not-found), so the refreshed payload is available to the labels pipeline and any later offline
+re-analysis; only the OrganizationEnrichment.data/group-property write is scoped to the three
+ownership fields. Prints base-rate stats at the end for the vendor decision this backfill exists
+to inform.
+"""
+
+import time
+import asyncio
+from typing import Any, Optional
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+from django.db.models import QuerySet
+
+from posthoganalytics.client import Client
+
+from posthog.exceptions_capture import capture_exception
+from posthog.ph_client import get_client
+
+from products.growth.backend.enrichment.fields import EnrichmentFields
+from products.growth.backend.enrichment.labels import signup_domain_for_organization
+from products.growth.backend.enrichment.providers import HarmonicEnrichmentProvider
+from products.growth.backend.enrichment.writer import archive_provider_fetch, write_organization_enrichment
+from products.growth.backend.models import OrganizationEnrichment
+
+_PROGRESS_INTERVAL = 100
+_ACQUIRED_OR_MERGED = "ACQUIRED_OR_MERGED"
+# Matches core.py's not-found placeholder verbatim (companyFound is part of Harmonic's own
+# response shape) rather than importing that module-private constant across files.
+_MISS_PAYLOAD = {"companyFound": False}
+
+
+def _unbackfilled_qs() -> QuerySet[OrganizationEnrichment]:
+ return (
+ OrganizationEnrichment.objects.exclude(data__has_key="ownership_status")
+ .select_related("organization")
+ .order_by("id")
+ )
+
+
+class Command(BaseCommand):
+ help = (
+ "Backfill ownership_status, parent_company, and parent_company_domain onto already-"
+ "enriched organizations, and print ACQUIRED_OR_MERGED / parent-resolution base rates. "
+ "An org whose fresh fetch has no ownership_status is counted as processed but left "
+ "unwritten and un-flagged for retry — re-running this command will fetch it again "
+ "every time until Harmonic starts returning a value for it."
+ )
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--after-id", default=None, help="Resume after this OrganizationEnrichment id")
+ parser.add_argument("--limit", type=int, default=500, help="Process at most this many orgs")
+ parser.add_argument("--dry-run", action="store_true", help="Fetch and count without writing anything")
+ parser.add_argument("--sleep", type=float, default=0.2, help="Seconds to sleep between Harmonic fetches")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ after_id: str | None = options["after_id"]
+ limit: int = options["limit"]
+ dry_run: bool = options["dry_run"]
+ sleep_seconds: float = options["sleep"]
+ if limit < 1:
+ raise CommandError("--limit must be at least 1")
+ if sleep_seconds < 0:
+ raise CommandError("--sleep must be at least 0")
+
+ qs = _unbackfilled_qs()
+ if after_id:
+ qs = qs.filter(id__gt=after_id)
+ records = list(qs[:limit])
+
+ provider = HarmonicEnrichmentProvider()
+ # Never constructed in --dry-run: nothing is written, so nothing should touch the network.
+ pha_client: Optional[Client] = None if dry_run else get_client()
+
+ counts = {
+ "processed": 0,
+ "no_domain": 0,
+ "fetch_failures": 0,
+ "not_found": 0,
+ "found_no_ownership_status": 0,
+ "errors": 0,
+ "classified": 0,
+ "acquired_or_merged": 0,
+ "acquired_or_merged_with_parent": 0,
+ }
+ last_id: str | None = after_id
+
+ try:
+ for record in records:
+ last_id = str(record.id)
+ try:
+ self._process_one(record, provider, pha_client, dry_run, sleep_seconds, counts)
+ except Exception as e:
+ capture_exception(e, {"organization_id": str(record.organization_id)})
+ counts["errors"] += 1
+ counts["processed"] += 1
+ if counts["processed"] % _PROGRESS_INTERVAL == 0:
+ self.stdout.write(f"processed {counts['processed']}/{len(records)}, last_id={last_id}")
+ finally:
+ if pha_client is not None:
+ pha_client.shutdown()
+
+ self.stdout.write(self._summary(counts, last_id))
+
+ def _process_one(
+ self,
+ record: OrganizationEnrichment,
+ provider: HarmonicEnrichmentProvider,
+ pha_client: Optional[Client],
+ dry_run: bool,
+ sleep_seconds: float,
+ counts: dict[str, int],
+ ) -> None:
+ domain = signup_domain_for_organization(record.organization)
+ if domain is None:
+ counts["no_domain"] += 1
+ return
+
+ try:
+ lookup = asyncio.run(provider.enrich_by_domain(domain))
+ except Exception as e:
+ capture_exception(e, {"organization_id": str(record.organization_id), "domain": domain})
+ counts["fetch_failures"] += 1
+ return
+ finally:
+ time.sleep(sleep_seconds)
+
+ # Every successful fetch is archived verbatim, including a not-found, same as the live
+ # 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:
+ 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,
+ is_recheck=True,
+ )
+
+ if lookup.fields is None:
+ counts["not_found"] += 1
+ return
+
+ ownership_status = lookup.fields.ownership_status
+ if ownership_status is None:
+ counts["found_no_ownership_status"] += 1
+ return
+
+ counts["classified"] += 1
+ if ownership_status == _ACQUIRED_OR_MERGED:
+ counts["acquired_or_merged"] += 1
+ if lookup.fields.parent_company:
+ counts["acquired_or_merged_with_parent"] += 1
+
+ if dry_run or pha_client is None:
+ return
+
+ # Scoped to just the three ownership keys: to_dict()/to_group_properties() only emit set
+ # fields, so leaving every other EnrichmentFields attribute unset keeps this write from
+ # touching icp_* or any other field a fresh fetch would otherwise churn.
+ write_organization_enrichment(
+ organization_id=str(record.organization_id),
+ fields=EnrichmentFields(
+ ownership_status=ownership_status,
+ parent_company=lookup.fields.parent_company,
+ parent_company_domain=lookup.fields.parent_company_domain,
+ ),
+ pha_client=pha_client,
+ )
+
+ def _summary(self, counts: dict[str, int], last_id: str | None) -> str:
+ processed = counts["processed"]
+ # Only orgs Harmonic returned an ownership_status for can carry a base rate. A no-domain,
+ # failed, not-found, or ownership-silent org is unknown rather than "not acquired" — the
+ # ownership fields are beta and silent on acquisitions we know happened, so counting those
+ # as negatives would understate the rate this backfill exists to measure.
+ classified = counts["classified"]
+ classified_pct = (classified / processed * 100) if processed else 0.0
+ acquired = counts["acquired_or_merged"]
+ acquired_pct = (acquired / classified * 100) if classified else 0.0
+ with_parent = counts["acquired_or_merged_with_parent"]
+ with_parent_pct = (with_parent / acquired * 100) if acquired else 0.0
+ return (
+ f"processed {processed}, fetch_failures {counts['fetch_failures']}, "
+ f"not_found {counts['not_found']}, no_domain {counts['no_domain']}, "
+ f"found_no_ownership_status {counts['found_no_ownership_status']}, errors {counts['errors']}, "
+ f"classified {classified} ({classified_pct:.1f}% of processed), "
+ f"acquired_or_merged {acquired} ({acquired_pct:.1f}% of classified), "
+ f"acquired_or_merged_with_parent {with_parent} ({with_parent_pct:.1f}% of acquired_or_merged), "
+ f"last_id={last_id}"
+ )
diff --git a/products/growth/backend/tests/test_backfill_harmonic_ownership.py b/products/growth/backend/tests/test_backfill_harmonic_ownership.py
new file mode 100644
index 000000000000..176c4adf1c1a
--- /dev/null
+++ b/products/growth/backend/tests/test_backfill_harmonic_ownership.py
@@ -0,0 +1,257 @@
+import uuid
+from io import StringIO
+from typing import Any, Optional
+
+from posthog.test.base import BaseTest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from django.core.management import call_command
+
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.user import User
+
+from products.growth.backend.enrichment.fields import EnrichmentFields
+from products.growth.backend.enrichment.providers import ProviderLookup
+from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch
+
+_COMMAND_MODULE = "products.growth.backend.management.commands.backfill_harmonic_ownership"
+
+
+def _lookup(
+ *,
+ ownership_status: Optional[str] = None,
+ parent_company: Optional[str] = None,
+ parent_company_domain: Optional[str] = None,
+ found: bool = True,
+) -> ProviderLookup:
+ if not found:
+ return ProviderLookup(fields=None, raw_payload=None)
+ fields = EnrichmentFields(
+ company_type="STARTUP", # a fresh-fetch field the backfill must never write back.
+ ownership_status=ownership_status,
+ parent_company=parent_company,
+ parent_company_domain=parent_company_domain,
+ )
+ raw_payload = {"companyType": "STARTUP", "ownershipStatus": ownership_status}
+ return ProviderLookup(fields=fields, raw_payload=raw_payload)
+
+
+def _mock_provider(side_effect: list[Any]) -> MagicMock:
+ provider_cls = MagicMock()
+ provider_cls.return_value.name = "harmonic"
+ provider_cls.return_value.enrich_by_domain = AsyncMock(side_effect=side_effect)
+ return provider_cls
+
+
+class _BackfillTestCase(BaseTest):
+ def _org(
+ self, *, email: str, data: Optional[dict[str, Any]] = None, id: Optional[uuid.UUID] = None
+ ) -> OrganizationEnrichment:
+ org = Organization.objects.create(name=email)
+ user = User.objects.create_user(email=email, password=None, first_name="t")
+ OrganizationMembership.objects.create(organization=org, user=user)
+ kwargs: dict[str, Any] = {"organization": org, "data": data if data is not None else {}}
+ if id is not None:
+ kwargs["id"] = id
+ return OrganizationEnrichment.objects.create(**kwargs)
+
+
+class TestWritePath(_BackfillTestCase):
+ def test_writes_only_the_three_ownership_keys_and_group_props(self):
+ record = self._org(email="[email protected]", data={"company_type": "OLD_VALUE", "headcount": 42})
+ pha_client = MagicMock()
+ provider_cls = _mock_provider(
+ [
+ _lookup(
+ ownership_status="ACQUIRED_OR_MERGED",
+ parent_company="Salesforce",
+ parent_company_domain="salesforce.com",
+ )
+ ]
+ )
+
+ with (
+ patch(f"{_COMMAND_MODULE}.HarmonicEnrichmentProvider", provider_cls),
+ patch(f"{_COMMAND_MODULE}.get_client", return_value=pha_client),
+ ):
+ call_command("backfill_harmonic_ownership", sleep=0)
+
+ record.refresh_from_db()
+ assert record.data == {
+ "company_type": "OLD_VALUE",
+ "headcount": 42,
+ "ownership_status": "ACQUIRED_OR_MERGED",
+ "parent_company": "Salesforce",
+ "parent_company_domain": "salesforce.com",
+ }
+ pha_client.group_identify.assert_called_once_with(
+ "organization",
+ str(record.organization_id),
+ properties={
+ "enrichment_ownership_status": "ACQUIRED_OR_MERGED",
+ "enrichment_parent_company": "Salesforce",
+ "enrichment_parent_company_domain": "salesforce.com",
+ },
+ )
+ pha_client.shutdown.assert_called_once()
+ fetch = OrganizationEnrichmentFetch.objects.get(organization=record.organization)
+ assert fetch.provider == "harmonic"
+ assert fetch.is_recheck is True
+ assert fetch.payload == {"companyType": "STARTUP", "ownershipStatus": "ACQUIRED_OR_MERGED"}
+
+ 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"})
+ pha_client = MagicMock()
+ provider_cls = _mock_provider([_lookup(ownership_status=None)])
+ out = StringIO()
+
+ with (
+ patch(f"{_COMMAND_MODULE}.HarmonicEnrichmentProvider", provider_cls),
+ patch(f"{_COMMAND_MODULE}.get_client", return_value=pha_client),
+ ):
+ call_command("backfill_harmonic_ownership", sleep=0, stdout=out)
+
+ record.refresh_from_db()
+ assert record.data == {"company_type": "STARTUP"}
+ pha_client.group_identify.assert_not_called()
+ summary = out.getvalue()
+ assert "processed 1" in summary
+ assert "found_no_ownership_status 1" in summary
+ assert "classified 0" in summary
+ # The write skip only applies to OrganizationEnrichment.data/group properties — the
+ # archive still happens, since it's a distinct, append-only store.
+ assert OrganizationEnrichmentFetch.objects.filter(organization=record.organization).exists()
+
+
+class TestSelection(_BackfillTestCase):
+ def test_orgs_already_backfilled_are_skipped(self):
+ self._org(email="[email protected]", data={"ownership_status": "ACTIVE"})
+ target = self._org(email="[email protected]", data={})
+ provider_cls = _mock_provider([_lookup(ownership_status="ACTIVE")])
+
+ with (
+ patch(f"{_COMMAND_MODULE}.HarmonicEnrichmentProvider", provider_cls),
+ patch(f"{_COMMAND_MODULE}.get_client", return_value=MagicMock()),
+ ):
+ call_command("backfill_harmonic_ownership", sleep=0)
+
+ provider_cls.return_value.enrich_by_domain.assert_called_once_with("acme.com")
+ target.refresh_from_db()
+ assert target.data["ownership_status"] == "ACTIVE"
+
+
+class TestDryRun(_BackfillTestCase):
+ def test_dry_run_writes_nothing_and_never_touches_the_network_client(self):
+ record = self._org(email="[email protected]", data={})
+ provider_cls = _mock_provider(
+ [
+ _lookup(
+ ownership_status="ACQUIRED_OR_MERGED",
+ parent_company="Salesforce",
+ parent_company_domain="salesforce.com",
+ )
+ ]
+ )
+
+ with (
+ patch(f"{_COMMAND_MODULE}.HarmonicEnrichmentProvider", provider_cls),
+ patch(f"{_COMMAND_MODULE}.get_client") as get_client_mock,
+ ):
+ call_command("backfill_harmonic_ownership", "--dry-run", sleep=0)
+
+ get_client_mock.assert_not_called()
+ record.refresh_from_db()
+ assert record.data == {}
+ assert not OrganizationEnrichmentFetch.objects.filter(organization=record.organization).exists()
+
+
+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)])
+
+ with (
+ patch(f"{_COMMAND_MODULE}.HarmonicEnrichmentProvider", provider_cls),
+ patch(f"{_COMMAND_MODULE}.get_client", return_value=MagicMock()),
+ ):
+ call_command("backfill_harmonic_ownership", sleep=0)
+
+ fetch = OrganizationEnrichmentFetch.objects.get(organization=record.organization)
+ assert fetch.provider == "harmonic"
+ assert fetch.is_recheck is True
+ assert fetch.payload == {"companyFound": False}
+
+ def test_a_fetch_failure_archives_nothing(self):
+ record = self._org(email="[email protected]", data={})
+ provider_cls = _mock_provider([RuntimeError("harmonic is down")])
+
+ with (
+ patch(f"{_COMMAND_MODULE}.HarmonicEnrichmentProvider", provider_cls),
+ patch(f"{_COMMAND_MODULE}.get_client", return_value=MagicMock()),
+ patch(f"{_COMMAND_MODULE}.capture_exception"),
+ ):
+ call_command("backfill_harmonic_ownership", sleep=0)
+
+ assert not OrganizationEnrichmentFetch.objects.filter(organization=record.organization).exists()
+
+
+class TestResume(_BackfillTestCase):
+ def test_after_id_resumes_past_already_seen_orgs(self):
+ # Explicit ids (rather than relying on uuid7's real-time ordering) make the id__gt
+ # boundary deterministic regardless of how close together the two creates land.
+ first = self._org(email="[email protected]", data={}, id=uuid.UUID(int=1))
+ second = self._org(email="[email protected]", data={}, id=uuid.UUID(int=2))
+ provider_cls = _mock_provider([_lookup(ownership_status="ACTIVE")])
+
+ with (
+ patch(f"{_COMMAND_MODULE}.HarmonicEnrichmentProvider", provider_cls),
+ patch(f"{_COMMAND_MODULE}.get_client", return_value=MagicMock()),
+ ):
+ call_command("backfill_harmonic_ownership", after_id=str(first.id), sleep=0)
+
+ provider_cls.return_value.enrich_by_domain.assert_called_once_with("acme.com")
+ first.refresh_from_db()
+ second.refresh_from_db()
+ assert "ownership_status" not in first.data
+ assert second.data["ownership_status"] == "ACTIVE"
+
+
+class TestSummary(_BackfillTestCase):
+ def test_summary_counts_every_outcome(self):
+ self._org(email="[email protected]", data={})
+ self._org(email="[email protected]", data={})
+ self._org(email="[email protected]", data={})
+ self._org(email="[email protected]", data={})
+ self._org(email="[email protected]", data={})
+
+ provider_cls = _mock_provider(
+ [
+ _lookup(
+ ownership_status="ACQUIRED_OR_MERGED",
+ parent_company="Salesforce",
+ parent_company_domain="salesforce.com",
+ ),
+ _lookup(ownership_status="ACQUIRED_OR_MERGED"),
+ _lookup(ownership_status="ACTIVE"),
+ _lookup(found=False),
+ RuntimeError("harmonic is down"),
+ ]
+ )
+ out = StringIO()
+ with (
+ patch(f"{_COMMAND_MODULE}.HarmonicEnrichmentProvider", provider_cls),
+ patch(f"{_COMMAND_MODULE}.get_client", return_value=MagicMock()),
+ patch(f"{_COMMAND_MODULE}.capture_exception") as capture_mock,
+ ):
+ call_command("backfill_harmonic_ownership", sleep=0, stdout=out)
+
+ summary = out.getvalue()
+ assert "processed 5" in summary
+ assert "fetch_failures 1" in summary
+ assert "not_found 1" in summary
+ # The not-found and the failed fetch are unknowns, so they stay out of the rate's
+ # denominator: 2 of the 3 orgs Harmonic actually classified, not 2 of 5 attempted.
+ assert "classified 3 (60.0% of processed)" in summary
+ assert "acquired_or_merged 2 (66.7% of classified)" in summary
+ assert "acquired_or_merged_with_parent 1 (50.0% of acquired_or_merged)" in summary
+ capture_mock.assert_called_once()