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): map web traffic from Harmonic and add a generic enrichment backfill (#79062)

Matt Brooker0b792521b8cf
diff --git a/products/growth/backend/enrichment/fields.py b/products/growth/backend/enrichment/fields.py
index 0f5e201f0d76..745541f2a837 100644
--- a/products/growth/backend/enrichment/fields.py
+++ b/products/growth/backend/enrichment/fields.py
@@ -32,6 +32,7 @@ class EnrichmentFields:
company_type: Optional[str] = None
headcount: Optional[int] = None
headcount_engineering: Optional[int] = None
+ web_traffic: Optional[int] = None
industry: Optional[str] = None
country: Optional[str] = None
founded_year: Optional[int] = None
diff --git a/products/growth/backend/enrichment/transform.py b/products/growth/backend/enrichment/transform.py
index ac7479669812..83d0db91cc06 100644
--- a/products/growth/backend/enrichment/transform.py
+++ b/products/growth/backend/enrichment/transform.py
@@ -107,13 +107,15 @@ def transform_harmonic_company(company: Optional[dict[str, Any]]) -> Optional[En
if headcount is None and isinstance(company.get("headcount"), (int, float)):
headcount = int(company["headcount"])
+ tags = _safe_list(company.get("tags"))
tags_v2 = _safe_list(company.get("tagsV2"))
return EnrichmentFields(
company_type=company.get("companyType"),
headcount=headcount,
headcount_engineering=_latest_metric(traction, "headcountEngineering"),
- industry=_extract_primary_tag(_safe_list(company.get("tags")), tags_v2),
+ web_traffic=_latest_metric(traction, "webTraffic"),
+ industry=_extract_primary_tag(tags, tags_v2),
# ISO alpha-2 to match the format the icp_country group property already holds.
country=country_name_to_iso_code(location.get("country")),
founded_year=_founded_year(founding),
diff --git a/products/growth/backend/management/commands/backfill_enrichment_fields.py b/products/growth/backend/management/commands/backfill_enrichment_fields.py
new file mode 100644
index 000000000000..dc46f3bac4d0
--- /dev/null
+++ b/products/growth/backend/management/commands/backfill_enrichment_fields.py
@@ -0,0 +1,139 @@
+"""Re-derive enrichment fields from each org's latest archived Harmonic payload and rewrite them.
+
+Generic by design: this re-runs the CURRENT transform_harmonic_company against the stored raw
+payload, so it always picks up every field the transform produces at run time -- not just the
+fields present when this command was written. A later addition to EnrichmentFields therefore
+backfills through this same command with no changes here; only the field registry needs to grow.
+
+Safe to re-run: group_identify overwrites the same keys, and a payload that yields no fields is
+skipped rather than clearing anything already written.
+
+Also deletes stale suppressed-placeholder values (see SUPPRESSED_PLACEHOLDERS) from the Postgres
+record when the current transform no longer derives the key from the same payload. Deletion is
+Postgres-only: group properties cannot be deleted, so ClickHouse keeps any historical placeholder
+-- measure field completeness on this table's warehouse copy, not on group properties.
+"""
+
+import time
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+from django.db import transaction
+
+from posthog.ph_client import get_client
+from posthog.utils import get_instance_region
+
+from products.growth.backend.enrichment.labels import recent_latest_fetches_qs
+from products.growth.backend.enrichment.transform import transform_harmonic_company
+from products.growth.backend.enrichment.writer import write_organization_enrichment
+from products.growth.backend.models import OrganizationEnrichment
+
+# Values older transform versions wrote for a key that the current transform deliberately
+# suppresses when the payload can't substantiate them. Only these exact values are ever deleted,
+# so a genuine historical value can't be swept up by an over-eager cleanup.
+SUPPRESSED_PLACEHOLDERS: dict[str, frozenset[str]] = {"funding_stage": frozenset({"VENTURE_UNKNOWN"})}
+
+
+def stale_placeholder_keys(data: dict[str, Any], derived: dict[str, Any]) -> list[str]:
+ return [
+ key
+ for key, placeholders in SUPPRESSED_PLACEHOLDERS.items()
+ if key not in derived and data.get(key) in placeholders
+ ]
+
+
+def _strip_stale_placeholders(organization_id: str, derived: dict[str, Any]) -> list[str]:
+ # Same row lock as the writer's merge, for the same reason: a concurrent live write must not
+ # be clobbered by this read-modify-save.
+ with transaction.atomic():
+ record = OrganizationEnrichment.objects.select_for_update().filter(organization_id=organization_id).first()
+ if record is None:
+ return []
+ stale = stale_placeholder_keys(record.data, derived)
+ if stale:
+ record.data = {key: value for key, value in record.data.items() if key not in stale}
+ record.save(update_fields=["data", "updated_at"])
+ return stale
+
+
+class Command(BaseCommand):
+ help = (
+ "Re-derive enrichment fields from each organization's latest archived provider fetch and "
+ "rewrite the OrganizationEnrichment record and organization group properties. Generic: "
+ "re-runs the current transform against the stored payload, so a future field added to "
+ "EnrichmentFields backfills through this same command without any changes here. Never "
+ "computes or touches icp_score."
+ )
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--limit", type=int, default=None, help="Backfill at most this many organizations")
+ parser.add_argument("--delay", type=float, default=0.1, help="Seconds to sleep between writes")
+ parser.add_argument("--dry-run", action="store_true", help="Report what would be written without writing")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ # Enrichment is US-only for v0 (mirrors the signup-path region gate).
+ if get_instance_region() != "US":
+ raise CommandError("Signup enrichment is US-only; refusing to backfill in this region")
+
+ limit: int | None = options["limit"]
+ delay: float = options["delay"]
+ dry_run: bool = options["dry_run"]
+ if limit is not None and limit < 1:
+ raise CommandError("--limit must be a positive integer")
+ if delay < 0:
+ raise CommandError("--delay must be >= 0")
+ pha_client = get_client()
+
+ fetches = recent_latest_fetches_qs()
+ if limit is not None:
+ fetches = fetches[:limit]
+
+ considered = written = skipped_no_match = skipped_empty = stripped_stale = 0
+ for fetch in fetches.iterator():
+ considered += 1
+ payload = fetch.payload
+ # `{"companyFound": False}` is core.py's archived placeholder for a genuine provider
+ # miss -- a truthy dict that would otherwise sail through the isinstance check below
+ # and get scored as a real (if empty) company by transform_harmonic_company.
+ if not isinstance(payload, dict) or payload.get("companyFound") is False:
+ skipped_no_match += 1
+ continue
+
+ fields = transform_harmonic_company(payload)
+ if fields is None:
+ skipped_no_match += 1
+ continue
+
+ values = fields.to_dict()
+ if not values:
+ skipped_empty += 1
+ continue
+
+ written += 1
+ if dry_run:
+ record = OrganizationEnrichment.objects.filter(organization_id=fetch.organization_id).first()
+ stale = stale_placeholder_keys(record.data, values) if record else []
+ if stale:
+ stripped_stale += 1
+ suffix = f", would strip {stale}" if stale else ""
+ self.stdout.write(f"would write {fetch.organization_id}: {sorted(values)}{suffix}")
+ continue
+
+ write_organization_enrichment(
+ organization_id=str(fetch.organization_id), fields=fields, pha_client=pha_client
+ )
+ stale = _strip_stale_placeholders(str(fetch.organization_id), values)
+ if stale:
+ stripped_stale += 1
+ suffix = f", stripped {stale}" if stale else ""
+ self.stdout.write(f"wrote {fetch.organization_id}: {sorted(values)}{suffix}")
+ if delay:
+ time.sleep(delay)
+
+ verb = "would write" if dry_run else "wrote"
+ summary = (
+ f"considered {considered}, {verb} {written}, "
+ f"skipped_no_match {skipped_no_match}, skipped_empty {skipped_empty}, "
+ f"stripped_stale {stripped_stale}"
+ )
+ self.stdout.write(self.style.SUCCESS(summary))
diff --git a/products/growth/backend/tests/test_backfill_enrichment_fields.py b/products/growth/backend/tests/test_backfill_enrichment_fields.py
new file mode 100644
index 000000000000..5bed42c914d8
--- /dev/null
+++ b/products/growth/backend/tests/test_backfill_enrichment_fields.py
@@ -0,0 +1,164 @@
+import datetime as dt
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.core.management import CommandError, call_command
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models.organization import Organization
+
+from products.growth.backend.management.commands.backfill_enrichment_fields import stale_placeholder_keys
+from products.growth.backend.models import OrganizationEnrichment, OrganizationEnrichmentFetch
+
+_COMMAND_MODULE = "products.growth.backend.management.commands.backfill_enrichment_fields"
+
+_PAYLOAD = {
+ "companyType": "STARTUP",
+ "tractionMetrics": {"webTraffic": {"latestMetricValue": 551400}},
+ "tags": [
+ {"type": "TECHNOLOGY", "displayValue": "AWS"},
+ {"type": "TECHNOLOGY", "displayValue": "React"},
+ {"type": "INDUSTRY", "displayValue": "Enterprise Software", "isPrimaryTag": True},
+ ],
+ "tagsV2": [],
+}
+
+
+class TestBackfillEnrichmentFields(BaseTest):
+ def _fetch(
+ self, *, organization=None, payload=_PAYLOAD, fetched_at: dt.datetime | None = None
+ ) -> OrganizationEnrichmentFetch:
+ organization = organization or self.organization
+ fetch = OrganizationEnrichmentFetch.objects.create(
+ organization=organization, provider="harmonic", payload=payload
+ )
+ if fetched_at is not None:
+ OrganizationEnrichmentFetch.objects.filter(id=fetch.id).update(fetched_at=fetched_at)
+ return fetch
+
+ def test_refuses_outside_us_region(self):
+ with patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="EU"):
+ with self.assertRaises(CommandError):
+ call_command("backfill_enrichment_fields")
+
+ @parameterized.expand([("negative_limit", ["--limit=-1"]), ("negative_delay", ["--delay=-0.5"])])
+ def test_refuses_invalid_numeric_options(self, _name, args):
+ with patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="US"):
+ with self.assertRaises(CommandError):
+ call_command("backfill_enrichment_fields", *args)
+
+ def test_dry_run_writes_nothing(self):
+ self._fetch()
+ OrganizationEnrichment.objects.create(
+ organization=self.organization, data={"funding_stage": "VENTURE_UNKNOWN", "headcount": 5}
+ )
+ pha_client = MagicMock()
+ with (
+ patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="US"),
+ patch(f"{_COMMAND_MODULE}.get_client", return_value=pha_client),
+ ):
+ call_command("backfill_enrichment_fields", "--dry-run")
+
+ pha_client.group_identify.assert_not_called()
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert record.data == {"funding_stage": "VENTURE_UNKNOWN", "headcount": 5}
+
+ def test_writes_derived_fields_from_the_latest_fetch_per_org(self):
+ older_payload = {**_PAYLOAD, "tractionMetrics": {"webTraffic": {"latestMetricValue": 100}}}
+ self._fetch(payload=older_payload, fetched_at=timezone.now() - dt.timedelta(days=1))
+ self._fetch(payload=_PAYLOAD)
+ pha_client = MagicMock()
+
+ with (
+ patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="US"),
+ patch(f"{_COMMAND_MODULE}.get_client", return_value=pha_client),
+ ):
+ call_command("backfill_enrichment_fields", "--delay=0")
+
+ pha_client.group_identify.assert_called_once()
+ _, kwargs = pha_client.group_identify.call_args
+ assert kwargs["properties"]["enrichment_web_traffic"] == 551400
+
+ def test_limit_respected(self):
+ for i in range(3):
+ org = Organization.objects.create(name=f"org-{i}")
+ self._fetch(organization=org)
+ pha_client = MagicMock()
+
+ with (
+ patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="US"),
+ patch(f"{_COMMAND_MODULE}.get_client", return_value=pha_client),
+ ):
+ call_command("backfill_enrichment_fields", "--limit=2", "--delay=0")
+
+ assert pha_client.group_identify.call_count == 2
+
+ def test_skips_provider_miss_payload(self):
+ self._fetch(payload={"companyFound": False})
+ pha_client = MagicMock()
+
+ with (
+ patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="US"),
+ patch(f"{_COMMAND_MODULE}.get_client", return_value=pha_client),
+ ):
+ call_command("backfill_enrichment_fields", "--delay=0")
+
+ pha_client.group_identify.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("placeholder_no_longer_derived", {"funding_stage": "VENTURE_UNKNOWN"}, {}, ["funding_stage"]),
+ ("real_value_never_stripped", {"funding_stage": "SEED"}, {}, []),
+ (
+ "still_derived_kept",
+ {"funding_stage": "VENTURE_UNKNOWN"},
+ {"funding_stage": "VENTURE_UNKNOWN"},
+ [],
+ ),
+ ]
+ )
+ def test_stale_placeholder_keys(self, _name, data, derived, expected):
+ assert stale_placeholder_keys(data, derived) == expected
+
+ @parameterized.expand(
+ [
+ ("placeholder_stripped", "VENTURE_UNKNOWN", False),
+ ("real_stage_preserved", "SEED", True),
+ ]
+ )
+ def test_command_strips_only_stale_placeholders_from_the_record(self, _name, stored_stage, survives):
+ # _PAYLOAD carries no funding data, so the re-derived fields have no funding_stage.
+ self._fetch()
+ OrganizationEnrichment.objects.create(
+ organization=self.organization,
+ data={"funding_stage": stored_stage, "company_type_deterministic": "startup"},
+ )
+ pha_client = MagicMock()
+
+ with (
+ patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="US"),
+ patch(f"{_COMMAND_MODULE}.get_client", return_value=pha_client),
+ ):
+ call_command("backfill_enrichment_fields", "--delay=0")
+
+ record = OrganizationEnrichment.objects.get(organization=self.organization)
+ assert ("funding_stage" in record.data) is survives
+ assert record.data["company_type_deterministic"] == "startup"
+ assert record.data["web_traffic"] == 551400
+
+ def test_missing_keys_skip_cleanly_without_placeholder_values(self):
+ self._fetch(payload={"companyType": "ENTERPRISE"})
+ pha_client = MagicMock()
+
+ with (
+ patch(f"{_COMMAND_MODULE}.get_instance_region", return_value="US"),
+ patch(f"{_COMMAND_MODULE}.get_client", return_value=pha_client),
+ ):
+ call_command("backfill_enrichment_fields", "--delay=0")
+
+ pha_client.group_identify.assert_called_once()
+ _, kwargs = pha_client.group_identify.call_args
+ assert "enrichment_web_traffic" not in kwargs["properties"]
diff --git a/products/growth/backend/tests/test_enrichment_transform.py b/products/growth/backend/tests/test_enrichment_transform.py
index 39cb4148a8ba..564b2c37f077 100644
--- a/products/growth/backend/tests/test_enrichment_transform.py
+++ b/products/growth/backend/tests/test_enrichment_transform.py
@@ -19,6 +19,7 @@ def _company(**overrides):
"tractionMetrics": {
"headcount": {"latestMetricValue": 130},
"headcountEngineering": {"latestMetricValue": 45},
+ "webTraffic": {"latestMetricValue": 551400},
},
"tags": [{"type": "INDUSTRY", "displayValue": "Developer Tools", "isPrimaryTag": True}],
"tagsV2": [],
@@ -34,6 +35,7 @@ def test_transform_maps_all_registry_fields():
"company_type": "STARTUP",
"headcount": 130, # tractionMetrics wins over the top-level headcount
"headcount_engineering": 45,
+ "web_traffic": 551400,
"industry": "Developer Tools",
"country": "US", # ISO alpha-2, matching the icp_country format
"founded_year": 2019,
@@ -118,6 +120,19 @@ def test_unmapped_country_name_is_dropped_not_written_raw():
assert fields.country is None
+def test_web_traffic_maps_from_traction_metrics():
+ fields = transform_harmonic_company(_company(tractionMetrics={"webTraffic": {"latestMetricValue": 12345}}))
+ assert fields is not None
+ assert fields.web_traffic == 12345
+
+
+def test_web_traffic_unset_when_traction_metrics_missing_key():
+ fields = transform_harmonic_company(_company(tractionMetrics={"headcount": {"latestMetricValue": 130}}))
+ assert fields is not None
+ assert fields.web_traffic is None
+ assert "web_traffic" not in fields.to_dict()
+
+
def test_none_and_empty_payloads_return_none():
assert transform_harmonic_company(None) is None
assert transform_harmonic_company({}) is None