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.

fix(growth): restrict ownership backfill to provider-fetched work-domain orgs (#82154)

Matt Brooker1d727ba46f64
diff --git a/products/growth/backend/management/commands/backfill_harmonic_ownership.py b/products/growth/backend/management/commands/backfill_harmonic_ownership.py
index 70e785fe9e75..5a1978c93bdf 100644
--- a/products/growth/backend/management/commands/backfill_harmonic_ownership.py
+++ b/products/growth/backend/management/commands/backfill_harmonic_ownership.py
@@ -1,16 +1,22 @@
"""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.
+Targets OrganizationEnrichment rows with no "ownership_status" key in `data`, restricted to
+orgs the live pipeline actually fetched from a provider (an OrganizationEnrichmentFetch row
+exists) and not explicitly flagged personal-domain (data__work_email is not False) — this
+excludes personal-domain signups, which never got a provider lookup and would otherwise have
+a vendor's own ownership data written onto them. Known gap, accepted: archive_provider_fetch
+never raises, so an org whose fetch succeeded but whose archive write failed silently has no
+fetch row and is skipped here — rare, and skipping is the safe direction for this command. The missing "ownership_status" key is
+otherwise 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
@@ -18,7 +24,7 @@ import asyncio
from typing import Any, Optional
from django.core.management.base import BaseCommand, CommandError, CommandParser
-from django.db.models import QuerySet
+from django.db.models import Exists, OuterRef, Q, QuerySet
from posthoganalytics.client import Client
@@ -29,7 +35,7 @@ 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
+from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch
_PROGRESS_INTERVAL = 100
_ACQUIRED_OR_MERGED = "ACQUIRED_OR_MERGED"
@@ -39,8 +45,18 @@ _MISS_PAYLOAD = {"companyFound": False}
def _unbackfilled_qs() -> QuerySet[OrganizationEnrichment]:
+ # Eligibility is "the live pipeline actually fetched this org from a provider", not
+ # "has a work_email flag" — personal-domain signups get a work_email=False record but
+ # never a provider fetch, so requiring a fetch row keeps them out without depending on
+ # work_email having been recorded (it postdates some existing rows).
+ has_fetch = OrganizationEnrichmentFetch.objects.filter(organization_id=OuterRef("organization_id"))
return (
OrganizationEnrichment.objects.exclude(data__has_key="ownership_status")
+ # Q(has_key) & Q(==False), not a bare exclude(data__work_email=False): JSONField key
+ # lookups return SQL NULL for a missing key, and exclude() on a bare comparison would
+ # drop those NULL rows too (Django's documented JSONField exclude() gotcha).
+ .exclude(Q(data__has_key="work_email") & Q(data__work_email=False))
+ .filter(Exists(has_fetch))
.select_related("organization")
.order_by("id")
)
@@ -49,10 +65,11 @@ def _unbackfilled_qs() -> QuerySet[OrganizationEnrichment]:
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."
+ "enriched work-domain organizations (personal-domain signups are excluded), 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:
diff --git a/products/growth/backend/tests/test_backfill_harmonic_ownership.py b/products/growth/backend/tests/test_backfill_harmonic_ownership.py
index 176c4adf1c1a..80ad0ec4ee2b 100644
--- a/products/growth/backend/tests/test_backfill_harmonic_ownership.py
+++ b/products/growth/backend/tests/test_backfill_harmonic_ownership.py
@@ -45,15 +45,26 @@ def _mock_provider(side_effect: list[Any]) -> MagicMock:
class _BackfillTestCase(BaseTest):
def _org(
- self, *, email: str, data: Optional[dict[str, Any]] = None, id: Optional[uuid.UUID] = None
+ self,
+ *,
+ email: str,
+ data: Optional[dict[str, Any]] = None,
+ id: Optional[uuid.UUID] = None,
+ with_fetch: bool = True,
) -> OrganizationEnrichment:
+ # with_fetch defaults True: every other test in this file models a work-domain org the
+ # live pipeline already enriched, which always leaves a fetch row behind. Only the
+ # personal-domain selection test needs the fetch-less shape, via with_fetch=False.
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)
+ record = OrganizationEnrichment.objects.create(**kwargs)
+ if with_fetch:
+ OrganizationEnrichmentFetch.objects.create(organization=org, provider="harmonic")
+ return record
class TestWritePath(_BackfillTestCase):
@@ -94,9 +105,8 @@ class TestWritePath(_BackfillTestCase):
},
)
pha_client.shutdown.assert_called_once()
- fetch = OrganizationEnrichmentFetch.objects.get(organization=record.organization)
+ fetch = OrganizationEnrichmentFetch.objects.get(organization=record.organization, is_recheck=True)
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):
@@ -139,6 +149,40 @@ class TestSelection(_BackfillTestCase):
target.refresh_from_db()
assert target.data["ownership_status"] == "ACTIVE"
+ def test_personal_domain_orgs_without_a_fetch_row_are_excluded(self):
+ personal = self._org(email="[email protected]", data={"work_email": False}, with_fetch=False)
+ work = self._org(email="[email protected]", data={"work_email": True})
+ 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")
+ personal.refresh_from_db()
+ work.refresh_from_db()
+ assert "ownership_status" not in personal.data
+ assert work.data["ownership_status"] == "ACTIVE"
+
+ def test_orgs_flagged_work_email_false_are_excluded_even_with_a_fetch_row(self):
+ # Pins the work_email exclude as the deciding factor: this org HAS a fetch row, so
+ # only the exclude keeps it out. Deleting the exclude would pass every other test.
+ flagged = self._org(email="[email protected]", data={"work_email": False})
+ 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")
+ flagged.refresh_from_db()
+ assert "ownership_status" not in flagged.data
+
class TestDryRun(_BackfillTestCase):
def test_dry_run_writes_nothing_and_never_touches_the_network_client(self):
@@ -162,7 +206,9 @@ class TestDryRun(_BackfillTestCase):
get_client_mock.assert_not_called()
record.refresh_from_db()
assert record.data == {}
- assert not OrganizationEnrichmentFetch.objects.filter(organization=record.organization).exists()
+ assert not OrganizationEnrichmentFetch.objects.filter(
+ organization=record.organization, is_recheck=True
+ ).exists()
class TestArchive(_BackfillTestCase):
@@ -176,9 +222,8 @@ class TestArchive(_BackfillTestCase):
):
call_command("backfill_harmonic_ownership", sleep=0)
- fetch = OrganizationEnrichmentFetch.objects.get(organization=record.organization)
+ fetch = OrganizationEnrichmentFetch.objects.get(organization=record.organization, is_recheck=True)
assert fetch.provider == "harmonic"
- assert fetch.is_recheck is True
assert fetch.payload == {"companyFound": False}
def test_a_fetch_failure_archives_nothing(self):
@@ -192,7 +237,9 @@ class TestArchive(_BackfillTestCase):
):
call_command("backfill_harmonic_ownership", sleep=0)
- assert not OrganizationEnrichmentFetch.objects.filter(organization=record.organization).exists()
+ assert not OrganizationEnrichmentFetch.objects.filter(
+ organization=record.organization, is_recheck=True
+ ).exists()
class TestResume(_BackfillTestCase):