: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(egress): gate Harmonic calls through a shared budget (#92785)
Matt Brookerd13eb117608a
diff --git a/ee/billing/salesforce_enrichment/constants.py b/ee/billing/salesforce_enrichment/constants.pyindex c5e8e71ad07d..6a71e046ce6f 100644--- a/ee/billing/salesforce_enrichment/constants.py+++ b/ee/billing/salesforce_enrichment/constants.py@@ -5,7 +5,6 @@ SALESFORCE_STRIPE_ENRICHMENT_WATERMARK_KEY: str = "salesforce-enrichment:stripe:ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE: str = "OrgMappingsCacheMissing"HARMONIC_BASE_URL: str = "https://api.harmonic.ai"YC_INVESTOR_NAME: str = "y combinator"-HARMONIC_DEFAULT_MAX_CONCURRENT_REQUESTS: int = 5 # rate limit: 10/sHARMONIC_REQUEST_TIMEOUT_SECONDS: int = 30HARMONIC_BATCH_SIZE: int = 100HARMONIC_DOMAIN_VARIATIONS: list[str] = ["", "www."] # Try exact domain first, then with www prefixdiff --git a/ee/billing/salesforce_enrichment/enrichment.py b/ee/billing/salesforce_enrichment/enrichment.pyindex e43c0d40761c..8da0bf669e42 100644--- a/ee/billing/salesforce_enrichment/enrichment.py+++ b/ee/billing/salesforce_enrichment/enrichment.py@@ -10,6 +10,7 @@ from dateutil import parserfrom simple_salesforce.format import format_soqlfrom posthog.dataclasses import frozen+from posthog.egress.limiter.policies import Priorityfrom posthog.exceptions_capture import capture_exceptionfrom posthog.temporal.common.logger import get_logger@@ -745,7 +746,7 @@ async def _enrich_specific_domain_debug(if not accounts:return _build_debug_error_result(chunk_number, start_time, domain, "No Salesforce accounts found")- async with AsyncHarmonicClient() as harmonic_client:+ async with AsyncHarmonicClient(priority=Priority.BATCH, source="salesforce_enrichment_debug") as harmonic_client:harmonic_results = await harmonic_client.enrich_companies_batch([domain])harmonic_result = harmonic_results[0] if harmonic_results else None@@ -882,8 +883,7 @@ async def enrich_accounts_chunked_async(total_failed = 0update_records = []- # Process in batches with rate limiting (5 req/sec)- async with AsyncHarmonicClient() as harmonic_client:+ async with AsyncHarmonicClient(priority=Priority.BATCH, source="salesforce_enrichment_bulk") as harmonic_client:for batch_start in range(0, len(account_data), HARMONIC_BATCH_SIZE):batch_end = min(batch_start + HARMONIC_BATCH_SIZE, len(account_data))batch = account_data[batch_start:batch_end]diff --git a/ee/billing/salesforce_enrichment/harmonic_client.py b/ee/billing/salesforce_enrichment/harmonic_client.pyindex 2ce9f1de42cf..bac39e9906b6 100644--- a/ee/billing/salesforce_enrichment/harmonic_client.py+++ b/ee/billing/salesforce_enrichment/harmonic_client.py@@ -6,6 +6,9 @@ from django.conf import settingsimport aiohttpfrom posthog.dataclasses import frozen+from posthog.egress.harmonic.limiter import pace_seconds_harmonic+from posthog.egress.harmonic.transport import HarmonicEgressBudgetExhausted, harmonic_request+from posthog.egress.limiter.policies import Priorityfrom posthog.exceptions_capture import capture_exceptionfrom .constants import (@@ -29,31 +32,42 @@ class HarmonicCompanyLookup:enrichment_urn: Optional[str]-# Harmonic rate limit is 5 req/s; well under that at one request per batch.+# Harmonic documents this as the per-call cap on /enrichment_status URNs._ENRICHMENT_STATUS_BATCH_SIZE = 50+# Sized under the BATCH lane's share of the per-second budget, so a whole wave is admitted.+_ENRICH_WAVE_SIZE = 10+_ENRICH_MAX_ATTEMPTS = 3+class AsyncHarmonicClient:- """Async Harmonic API client with controlled concurrency.+ """Async Harmonic API client, gated and recorded through the Harmonic egress transport.Enriches company domains using Harmonic's GraphQL API with:- - 5 concurrent requests (configurable)- - 30s timeout per request+ - Every outbound call routed through posthog.egress.harmonic.transport.harmonic_request+ - 30s timeout per request (two endpoints override to a shorter cap; see their docstrings)- Domain variation fallbacks (www., non-www)- Automatic session management via context manager+ ``priority`` defaults to CRITICAL: the interactive callers (signup enrichment, the ICP+ re-enrichment sweep) run inside a 90-second Temporal activity budget and must never be+ starved or shed. The weekly bulk job passes ``Priority.BATCH`` explicitly so it yields to+ that traffic instead.+Usage:- async with AsyncHarmonicClient() as client:+ async with AsyncHarmonicClient(priority=Priority.BATCH, source="my_job") as client:data = await client.enrich_company_by_domain("posthog.com")"""- def __init__(self):+ def __init__(self, *, priority: Priority = Priority.CRITICAL, source: str = "harmonic_client") -> None:self.api_key = settings.HARMONIC_API_KEYif not self.api_key:raise ValueError("Missing Harmonic API key: HARMONIC_API_KEY")self.session: Optional[aiohttp.ClientSession] = Noneself._session_cm: Any = None+ self.priority = priority+ self.source = sourceasync def __aenter__(self):"""Async context manager entry - create session."""@@ -76,14 +90,15 @@ class AsyncHarmonicClient:Tries domain variations: example.com → www.example.com if first fails.+ None covers a not-found, an operational failure and a shed call alike. A caller that+ persists the result should use enrich_company_by_domain_strict, which tells them apart.+Args:domain: Company domain (e.g., "posthog.com")Returns:Company data dict or None if not found"""- # Rate limiting: 5 requests per second- await asyncio.sleep(0.2)domain = self._clean_domain(domain)# Try domain variations@@ -95,24 +110,34 @@ class AsyncHarmonicClient:if self.session is None:raise RuntimeError("HTTP session not initialized. Use async context manager.")- async with self.session.post(+ response = await harmonic_request(+ self.session,+ "POST",f"{HARMONIC_BASE_URL}/graphql",- json={"query": HARMONIC_COMPANY_ENRICHMENT_QUERY, "variables": variables},+ source=self.source,+ priority=self.priority,+ endpoint="/graphql",# Key in a header, not a query param: aiohttp errors carry request_info.real_url,# so a URL-borne key would leak into exception telemetry when a lookup raises.- headers={"Content-Type": "application/json", "apikey": self.api_key},- ) as response:- response.raise_for_status()- data = await response.json()+ headers={"apikey": self.api_key},+ json={"query": HARMONIC_COMPANY_ENRICHMENT_QUERY, "variables": variables},+ )+ response.raise_for_status()+ data = await response.json()- if "errors" in data:- continue+ if "errors" in data:+ continue- result = data.get("data", {}).get("enrichCompanyByIdentifiers", {})- if result.get("companyFound"):- company_data = result.get("company")- return company_data+ result = data.get("data", {}).get("enrichCompanyByIdentifiers", {})+ if result.get("companyFound"):+ company_data = result.get("company")+ return company_data+ except HarmonicEgressBudgetExhausted:+ # A shed is our own limiter declining to call out, not a Harmonic failure — the+ # limiter already records it as a metric; capturing it here would page on our+ # own throttling working as designed.+ continueexcept Exception as e:capture_exception(e)continue@@ -137,13 +162,17 @@ class AsyncHarmonicClient:outage for a missing company. On the mixed path — a clean not-found suppressing asibling error — the suppressed error is captured rather than discarded, since that isexactly the failure mode that let the original bug hide with no signal anywhere.++ A shed variation always re-raises and is never suppressed by a sibling not-found. A shed+ means Harmonic was never asked, so writing the miss would archive "no Harmonic company"+ over our own throttling, and the sweep would not revisit it for up to 90 days."""- await asyncio.sleep(0.2)domain = self._clean_domain(domain)domain_variations = [f"{prefix}{domain}" if prefix else domain for prefix in HARMONIC_DOMAIN_VARIATIONS]last_error: Optional[Exception] = Nonelast_error_variation: Optional[str] = None+ shed_error: Optional[HarmonicEgressBudgetExhausted] = Nonesaw_clean_not_found = Falsenot_found_urn: Optional[str] = Nonefor domain_variation in domain_variations:@@ -152,38 +181,59 @@ class AsyncHarmonicClient:if self.session is None:raise RuntimeError("HTTP session not initialized. Use async context manager.")- async with self.session.post(+ response = await harmonic_request(+ self.session,+ "POST",f"{HARMONIC_BASE_URL}/graphql",- json={"query": HARMONIC_COMPANY_ENRICHMENT_QUERY, "variables": variables},+ source=self.source,+ priority=self.priority,+ endpoint="/graphql",# Key in a header, not a query param: aiohttp errors carry request_info.real_url,# so a URL-borne key would leak into exception telemetry when a lookup raises.- headers={"Content-Type": "application/json", "apikey": self.api_key},- ) as response:- response.raise_for_status()- data = await response.json()-- if "errors" in data:- raise RuntimeError(f"Harmonic GraphQL errors for {domain_variation}: {data['errors']}")-- result = data.get("data", {}).get("enrichCompanyByIdentifiers", {})- if result.get("companyFound"):- return HarmonicCompanyLookup(- company=result.get("company"), enrichment_urn=result.get("enrichmentUrn")- )- if result.get("companyFound") is False:- saw_clean_not_found = True- not_found_urn = not_found_urn or result.get("enrichmentUrn")+ headers={"apikey": self.api_key},+ json={"query": HARMONIC_COMPANY_ENRICHMENT_QUERY, "variables": variables},+ )+ response.raise_for_status()+ data = await response.json()++ if "errors" in data:+ raise RuntimeError(f"Harmonic GraphQL errors for {domain_variation}: {data['errors']}")++ result = data.get("data", {}).get("enrichCompanyByIdentifiers", {})+ if result.get("companyFound"):+ return HarmonicCompanyLookup(+ company=result.get("company"), enrichment_urn=result.get("enrichmentUrn")+ )+ if result.get("companyFound") is False:+ saw_clean_not_found = True+ not_found_urn = not_found_urn or result.get("enrichmentUrn")+ except HarmonicEgressBudgetExhausted as e:+ shed_error = e+ continueexcept Exception as e:last_error = elast_error_variation = domain_variationcontinue+ if shed_error is not None:+ raise shed_errorif last_error is not None and not saw_clean_not_found:raise last_errorif last_error is not None:capture_exception(last_error, {"domain": domain, "failed_variation": last_error_variation})return HarmonicCompanyLookup(company=None, enrichment_urn=not_found_urn)+ async def _enrich_company_by_domain_observing_denial(self, domain: str) -> Optional[dict[str, Any]]:+ """Lookup for the batch path, which must see a denial rather than a miss.++ Delegates to enrich_company_by_domain_strict for its shed-always-wins precedence: a shed on+ one domain variation is never treated as a not-found even when a sibling variation returned+ a clean companyFound=false, because the shed means Harmonic was never asked. enrich_companies_batch+ relies on that to know a domain was denied, not missing, so it can retry it in a later wave.+ """+ lookup = await self.enrich_company_by_domain_strict(domain)+ return lookup.company+async def get_company_by_urn(self, urn: str) -> Optional[dict[str, Any]]:"""Resolve a Harmonic company URN (e.g. from relatedCompanies) via the REST profile endpoint.@@ -195,18 +245,25 @@ class AsyncHarmonicClient:if self.session is None:raise RuntimeError("HTTP session not initialized. Use async context manager.")- await asyncio.sleep(0.2)# Short cap: a single profile fetch, and it shares the signup activity's 90s budget with# the up-to-60s domain lookup — inheriting the session's 30s total would eat all headroom.- async with self.session.get(+ response = await harmonic_request(+ self.session,+ "GET",f"{HARMONIC_BASE_URL}/companies/{company_id}",+ source=self.source,+ priority=self.priority,+ endpoint="/companies/{id}",headers={"apikey": self.api_key},timeout=aiohttp.ClientTimeout(total=10),- ) as response:- if response.status == 404:- return None- response.raise_for_status()- return await response.json()+ )+ if response.status == 404:+ # Returning without reading the body leaves the connection to the garbage collector,+ # which drops it from the keep-alive pool instead of reusing it.+ response.release()+ return None+ response.raise_for_status()+ return await response.json()async def get_enrichment_status(self, urns: list[str]) -> dict[str, dict[str, Any]]:"""Poll Harmonic's /enrichment_status for a set of tracking URNs, keyed by entity_urn.@@ -220,17 +277,21 @@ class AsyncHarmonicClient:statuses: dict[str, dict[str, Any]] = {}for start in range(0, len(urns), _ENRICHMENT_STATUS_BATCH_SIZE):batch = urns[start : start + _ENRICHMENT_STATUS_BATCH_SIZE]- await asyncio.sleep(0.2)# Same short cap as get_company_by_urn: this shares the recheck activity's 90s# budget with the domain lookup, so it must not inherit the session's 30s total.- async with self.session.get(+ response = await harmonic_request(+ self.session,+ "GET",f"{HARMONIC_BASE_URL}/enrichment_status",+ source=self.source,+ priority=self.priority,+ endpoint="/enrichment_status",params=[("urns", urn) for urn in batch],headers={"apikey": self.api_key},timeout=aiohttp.ClientTimeout(total=10),- ) as response:- response.raise_for_status()- data = await response.json()+ )+ response.raise_for_status()+ data = await response.json()if not isinstance(data, list):raise ValueError(f"unexpected enrichment_status body: {type(data).__name__}")@@ -240,23 +301,66 @@ class AsyncHarmonicClient:return statusesasync def enrich_companies_batch(self, domains: list[str]) -> list[dict[str, Any] | None]:- """Enrich multiple domains concurrently.+ """Enrich multiple domains concurrently, in waves paced against the shared egress budget.++ Pacing is recomputed per wave because pace_seconds reads live limiter state, so a wave that+ finds the budget already drawn down waits for it.++ A shed domain is retried in a later wave rather than recorded: callers persist these results+ against a Salesforce account, and a shed means Harmonic was never asked.Args:domains: List of company domains to enrichReturns:- List of company data dicts (None for failed enrichments)+ List of company data dicts, same length and order as domains. A slot is None for a+ genuine not-found or an operational failure, and also for a domain still shed after+ every attempt: that last case is reported to error tracking first, since it must not+ look like a genuine miss on inspection there even though the return value can't carry+ the distinction (callers zip this list against the input domains)."""if not domains:return []- tasks = [self.enrich_company_by_domain(domain) for domain in domains]-- results: list[dict[str, Any] | BaseException | None] = await asyncio.gather(*tasks, return_exceptions=True)-- for result in results:- if isinstance(result, BaseException):- capture_exception(result)-- return [None if isinstance(result, BaseException) else result for result in results]+ results: list[dict[str, Any] | None] = [None] * len(domains)+ pending = list(range(len(domains)))++ for _attempt in range(_ENRICH_MAX_ATTEMPTS):+ if not pending:+ break++ denied: list[int] = []+ for wave_start in range(0, len(pending), _ENRICH_WAVE_SIZE):+ wave = pending[wave_start : wave_start + _ENRICH_WAVE_SIZE]++ # CRITICAL is never shed by the transport (_raise_if_denied never raises on it), so+ # pacing it would only add latency to an interactive caller for no admission benefit.+ if self.priority is not Priority.CRITICAL:+ pace = pace_seconds_harmonic(self.priority)+ if pace > 0:+ await asyncio.sleep(pace)++ wave_results: list[dict[str, Any] | BaseException | None] = await asyncio.gather(+ *(self._enrich_company_by_domain_observing_denial(domains[i]) for i in wave),+ return_exceptions=True,+ )++ for index, result in zip(wave, wave_results):+ if isinstance(result, HarmonicEgressBudgetExhausted):+ denied.append(index)+ elif isinstance(result, BaseException):+ capture_exception(result, {"domain": domains[index]})+ else:+ results[index] = result++ pending = denied++ for index in pending:+ capture_exception(+ HarmonicEgressBudgetExhausted(+ f"Harmonic egress budget denied this domain on every attempt ({_ENRICH_MAX_ATTEMPTS})"+ ),+ {"domain": domains[index]},+ )++ return resultsdiff --git a/ee/billing/test/test_harmonic_client.py b/ee/billing/test/test_harmonic_client.pyindex 9aa417e87892..0e781cc5dd35 100644--- a/ee/billing/test/test_harmonic_client.py+++ b/ee/billing/test/test_harmonic_client.py@@ -1,10 +1,24 @@+import asyncio+from collections.abc import Collection+import pytestfrom unittest.mock import AsyncMock, MagicMock, patchimport aiohttpfrom parameterized import parameterized-from ee.billing.salesforce_enrichment.harmonic_client import AsyncHarmonicClient+from posthog.egress.harmonic.transport import HarmonicEgressBudgetExhausted+from posthog.egress.limiter.policies import Priority++from ee.billing.salesforce_enrichment.harmonic_client import _ENRICH_WAVE_SIZE, AsyncHarmonicClient++HARMONIC_REQUEST = "ee.billing.salesforce_enrichment.harmonic_client.harmonic_request"+PACE_SECONDS_HARMONIC = "ee.billing.salesforce_enrichment.harmonic_client.pace_seconds_harmonic"+ASYNCIO_SLEEP = "ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep"++# Captured at import time, before any test patches asyncio.sleep, so the fake sleeps below always+# yield to the real event loop rather than recursing into whichever mock is active when they run.+_REAL_SLEEP = asyncio.sleepdef _response(*, json_data=None, raise_status=None, status=200):@@ -12,27 +26,15 @@ def _response(*, json_data=None, raise_status=None, status=200):resp.status = statusresp.raise_for_status = MagicMock(side_effect=raise_status)resp.json = AsyncMock(return_value=json_data)- cm = MagicMock()- cm.__aenter__ = AsyncMock(return_value=resp)- cm.__aexit__ = AsyncMock(return_value=False)- return cm+ return resp-def _client_with_responses(*responses):+def _client(*, priority=Priority.NORMAL):client = AsyncHarmonicClient.__new__(AsyncHarmonicClient)client.api_key = "test-key"- session = MagicMock()- session.post = MagicMock(side_effect=list(responses))- client.session = session- return client---def _client_with_get_responses(*responses):- client = AsyncHarmonicClient.__new__(AsyncHarmonicClient)- client.api_key = "test-key"- session = MagicMock()- session.get = MagicMock(side_effect=list(responses))- client.session = session+ client.priority = priority+ client.source = "test"+ client.session = MagicMock()return client@@ -61,84 +63,162 @@ def _http_500():return _response(raise_status=error)+# Shared by the patched pace and sleep, so a wave that waits sees the budget refill without the+# test costing wall-clock time.+class _FakeClock:+ def __init__(self) -> None:+ self.now = 0.0+++# Stands in for the Harmonic egress limiter. always_deny and not_found are keyed by the bare+# domain, so both HARMONIC_DOMAIN_VARIATIONS of one domain share a fate, as they do against the+# account-wide budget.+class _FakeGate:+ def __init__(+ self,+ clock: _FakeClock,+ *,+ budget: int,+ window: float = 1.0,+ always_deny: Collection[str] = frozenset(),+ not_found: Collection[str] = frozenset(),+ ) -> None:+ self.clock = clock+ self.budget = budget+ self.window = window+ self.always_deny = always_deny+ self.not_found = not_found+ self.window_start = clock.now+ self.used = 0++ def _refill(self) -> None:+ if self.clock.now - self.window_start >= self.window:+ self.window_start = self.clock.now+ self.used = 0++ def _admit(self, bare_domain: str) -> bool:+ self._refill()+ if bare_domain in self.always_deny:+ return False+ if self.used >= self.budget:+ return False+ self.used += 1+ return True++ def pace_seconds(self, _priority=None) -> float:+ self._refill()+ if self.used < self.budget:+ return 0.0+ return max(0.0, self.window - (self.clock.now - self.window_start))++ async def request(self, session, method, url, *, source, priority, endpoint, headers, json, **kwargs):+ website_url = json["variables"]["identifiers"]["websiteUrl"]+ bare_domain = website_url.removeprefix("https://").removeprefix("www.")+ if not self._admit(bare_domain):+ raise HarmonicEgressBudgetExhausted("degrading")+ if bare_domain in self.not_found:+ return _not_found()+ return _found({"name": bare_domain})+++# Awaits the real asyncio.sleep(0) so the call stays an event-loop suspension point that a+# pending cancellation can land on.+def _clock_advancing_sleep(clock: _FakeClock):+ async def fake_sleep(seconds: float) -> None:+ clock.now += seconds+ await _REAL_SLEEP(0)++ return fake_sleep++@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_strict_returns_none_when_not_found():# Both domain variations return a clean companyFound=false.- client = _client_with_responses(_not_found(), _not_found())- result = await client.enrich_company_by_domain_strict("unknown.example")+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=[_not_found(), _not_found()])):+ result = await _client().enrich_company_by_domain_strict("unknown.example")assert result.company is None@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_strict_reraises_on_http_error():- client = _client_with_responses(_http_500(), _http_500())- with pytest.raises(aiohttp.ClientResponseError):- await client.enrich_company_by_domain_strict("posthog.com")+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=[_http_500(), _http_500()])):+ with pytest.raises(aiohttp.ClientResponseError):+ await _client().enrich_company_by_domain_strict("posthog.com")@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_strict_falls_back_to_second_variation_after_error():# First variation errors, second returns a company: the successful variation wins.- client = _client_with_responses(_http_500(), _found({"name": "PostHog"}))- result = await client.enrich_company_by_domain_strict("posthog.com")+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=[_http_500(), _found({"name": "PostHog"})])):+ result = await _client().enrich_company_by_domain_strict("posthog.com")assert result.company == {"name": "PostHog"}@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_strict_clean_not_found_is_authoritative_when_the_other_variation_errored():# One variation errored, the other returned a clean companyFound=false: that clean answer# is an authoritative not-found. Raising here made a deterministically-failing variation# exhaust the caller's retries and leave the org with no archive row at all.- client = _client_with_responses(_http_500(), _not_found())- result = await client.enrich_company_by_domain_strict("posthog.com")+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=[_http_500(), _not_found()])):+ result = await _client().enrich_company_by_domain_strict("posthog.com")assert result.company is None@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_strict_clean_not_found_first_then_error_is_also_not_found():- client = _client_with_responses(_not_found(), _http_500())- result = await client.enrich_company_by_domain_strict("posthog.com")+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=[_not_found(), _http_500()])):+ result = await _client().enrich_company_by_domain_strict("posthog.com")assert result.company is None@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_strict_raises_when_companyfound_key_missing_and_sibling_errored():- client = _client_with_responses(_http_500(), _missing_company_found_key())- with pytest.raises(aiohttp.ClientResponseError):- await client.enrich_company_by_domain_strict("posthog.com")+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=[_http_500(), _missing_company_found_key()])):+ with pytest.raises(aiohttp.ClientResponseError):+ await _client().enrich_company_by_domain_strict("posthog.com")+++async def test_strict_never_swallows_a_shed_variation_into_a_not_found_clean_first():+ # A sibling's clean not-found is authoritative for a genuine network error (see the test+ # above), but not for a shed: a shed means Harmonic was never asked, so the sibling's answer+ # says nothing about it. Swallowing this would write a false not-found the re-enrichment+ # sweep would not revisit for up to 90 days, purely because our own budget was tight.+ side_effect = [_not_found(), HarmonicEgressBudgetExhausted("degrading")]+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=side_effect)):+ with pytest.raises(HarmonicEgressBudgetExhausted):+ await _client(priority=Priority.BATCH).enrich_company_by_domain_strict("posthog.com")+++async def test_strict_never_swallows_a_shed_variation_into_a_not_found_shed_first():+ side_effect = [HarmonicEgressBudgetExhausted("degrading"), _not_found()]+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=side_effect)):+ with pytest.raises(HarmonicEgressBudgetExhausted):+ await _client(priority=Priority.BATCH).enrich_company_by_domain_strict("posthog.com")@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_strict_graphql_error_with_clean_not_found_sibling_returns_none():- client = _client_with_responses(_graphql_errors(), _not_found())- result = await client.enrich_company_by_domain_strict("posthog.com")+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=[_graphql_errors(), _not_found()])):+ result = await _client().enrich_company_by_domain_strict("posthog.com")assert result.company is None@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())@patch("ee.billing.salesforce_enrichment.harmonic_client.capture_exception")async def test_strict_captures_swallowed_error_on_mixed_path(mock_capture_exception):- client = _client_with_responses(_graphql_errors(), _not_found())- result = await client.enrich_company_by_domain_strict("posthog.com")+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=[_graphql_errors(), _not_found()])):+ result = await _client().enrich_company_by_domain_strict("posthog.com")assert result.company is Nonemock_capture_exception.assert_called_once()@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_strict_not_found_surfaces_the_tracking_urn():- client = _client_with_responses(- _not_found(urn="urn:harmonic:enrichment:abc"), _not_found(urn="urn:harmonic:enrichment:abc")- )- result = await client.enrich_company_by_domain_strict("unknown.example")+ responses = [_not_found(urn="urn:harmonic:enrichment:abc"), _not_found(urn="urn:harmonic:enrichment:abc")]+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=responses)):+ result = await _client().enrich_company_by_domain_strict("unknown.example")assert result.company is Noneassert result.enrichment_urn == "urn:harmonic:enrichment:abc"@@ -150,110 +230,281 @@ async def test_strict_not_found_surfaces_the_tracking_urn():])@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_strict_found_surfaces_the_refresh_urn(_name, urn):- client = _client_with_responses(_found({"name": "PostHog"}, urn=urn))- result = await client.enrich_company_by_domain_strict("posthog.com")+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=[_found({"name": "PostHog"}, urn=urn)])):+ result = await _client().enrich_company_by_domain_strict("posthog.com")assert result.company == {"name": "PostHog"}assert result.enrichment_urn == urn@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())-async def test_strict_sends_api_key_as_header_not_in_url_or_params():- client = _client_with_responses(_found({"name": "PostHog"}))- await client.enrich_company_by_domain_strict("posthog.com")+async def test_strict_sends_api_key_as_header_not_in_url_or_params_and_uses_client_priority_and_source():+ client = _client(priority=Priority.BATCH)+ client.source = "billing_bulk"+ mock_request = AsyncMock(side_effect=[_found({"name": "PostHog"})])+ with patch(HARMONIC_REQUEST, new=mock_request):+ await client.enrich_company_by_domain_strict("posthog.com")- client.session.post.assert_called_once()- call = client.session.post.call_args- url = call.args[0]- params = call.kwargs.get("params")+ mock_request.assert_called_once()+ call = mock_request.call_args+ assert call.args[0] is client.session+ assert call.args[1] == "POST"+ url = call.args[2]assert call.kwargs["headers"]["apikey"] == "test-key"assert "test-key" not in url- assert params is None or "test-key" not in str(params)+ assert call.kwargs.get("params") is None+ assert call.kwargs["priority"] is Priority.BATCH+ assert call.kwargs["source"] == "billing_bulk"@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_non_strict_sends_api_key_as_header_not_in_url_or_params():- client = _client_with_responses(_found({"name": "PostHog"}))- await client.enrich_company_by_domain("posthog.com")+ mock_request = AsyncMock(side_effect=[_found({"name": "PostHog"})])+ with patch(HARMONIC_REQUEST, new=mock_request):+ await _client().enrich_company_by_domain("posthog.com")- call = client.session.post.call_args- params = call.kwargs.get("params")+ call = mock_request.call_args+ url = call.args[2]assert call.kwargs["headers"]["apikey"] == "test-key"- assert "test-key" not in call.args[0]- assert params is None or "test-key" not in str(params)+ assert "test-key" not in url+ assert call.kwargs.get("params") is None+++async def test_non_strict_returns_none_when_every_variation_is_rate_limited():+ # A limiter denial is swallowed by the same per-variation except block as a network error,+ # but must not be reported as one: the limiter already records it as a metric, and paging on+ # our own throttling working as designed would be noise.+ mock_request = AsyncMock(side_effect=HarmonicEgressBudgetExhausted("degrading"))+ with (+ patch(HARMONIC_REQUEST, new=mock_request),+ patch("ee.billing.salesforce_enrichment.harmonic_client.capture_exception") as mock_capture,+ ):+ result = await _client(priority=Priority.BATCH).enrich_company_by_domain("posthog.com")+ assert result is None+ mock_capture.assert_not_called()@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_get_company_by_urn_returns_parsed_json():- client = _client_with_get_responses(- _response(json_data={"name": "Salesforce", "website": {"domain": "salesforce.com"}})- )- result = await client.get_company_by_urn("urn:harmonic:company:9801263")+ response = _response(json_data={"name": "Salesforce", "website": {"domain": "salesforce.com"}})+ client = _client()+ mock_request = AsyncMock(return_value=response)+ with patch(HARMONIC_REQUEST, new=mock_request):+ result = await client.get_company_by_urn("urn:harmonic:company:9801263")assert result == {"name": "Salesforce", "website": {"domain": "salesforce.com"}}- client.session.get.assert_called_once_with(+ mock_request.assert_called_once_with(+ client.session,+ "GET","https://api.harmonic.ai/companies/9801263",+ source="test",+ priority=Priority.NORMAL,+ endpoint="/companies/{id}",headers={"apikey": "test-key"},timeout=aiohttp.ClientTimeout(total=10),)@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_get_company_by_urn_returns_none_on_not_found():- client = _client_with_get_responses(_response(status=404))- assert await client.get_company_by_urn("urn:harmonic:company:999999999") is None+ with patch(HARMONIC_REQUEST, new=AsyncMock(return_value=_response(status=404))):+ assert await _client().get_company_by_urn("urn:harmonic:company:999999999") is None@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_get_company_by_urn_reraises_on_http_error():- client = _client_with_get_responses(_http_500())- with pytest.raises(aiohttp.ClientResponseError):- await client.get_company_by_urn("urn:harmonic:company:9801263")+ with patch(HARMONIC_REQUEST, new=AsyncMock(return_value=_http_500())):+ with pytest.raises(aiohttp.ClientResponseError):+ await _client().get_company_by_urn("urn:harmonic:company:9801263")+++async def test_get_company_by_urn_raises_when_rate_limited():+ # No swallowing here: parent-company resolution is optional, and the caller decides whether+ # to catch this, same as any other operational failure from this method.+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=HarmonicEgressBudgetExhausted("degrading"))):+ with pytest.raises(HarmonicEgressBudgetExhausted):+ await _client(priority=Priority.BATCH).get_company_by_urn("urn:harmonic:company:9801263")@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_get_enrichment_status_builds_repeated_urns_query_and_maps_by_entity_urn():entries = [{"entity_urn": "urn:harmonic:enrichment:aaa", "status": "COMPLETE", "enriched_entity_urn": "urn:x:1"},{"entity_urn": "urn:harmonic:enrichment:bbb", "status": "QUEUED", "enriched_entity_urn": None},]- client = _client_with_get_responses(_response(json_data=entries))- result = await client.get_enrichment_status(["urn:harmonic:enrichment:aaa", "urn:harmonic:enrichment:bbb"])+ client = _client()+ mock_request = AsyncMock(return_value=_response(json_data=entries))+ with patch(HARMONIC_REQUEST, new=mock_request):+ result = await client.get_enrichment_status(["urn:harmonic:enrichment:aaa", "urn:harmonic:enrichment:bbb"])assert result == {"urn:harmonic:enrichment:aaa": entries[0],"urn:harmonic:enrichment:bbb": entries[1],}- client.session.get.assert_called_once()- call = client.session.get.call_args- assert call.args[0] == "https://api.harmonic.ai/enrichment_status"+ mock_request.assert_called_once()+ call = mock_request.call_args+ assert call.args[0] is client.session+ assert call.args[1] == "GET"+ assert call.args[2] == "https://api.harmonic.ai/enrichment_status"assert call.kwargs["params"] == [("urns", "urn:harmonic:enrichment:aaa"),("urns", "urn:harmonic:enrichment:bbb"),]assert call.kwargs["headers"]["apikey"] == "test-key"- assert "test-key" not in call.args[0]+ assert "test-key" not in call.args[2]@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_get_enrichment_status_raises_on_non_list_body():- client = _client_with_get_responses(_response(json_data={"error": "not a list"}))- with pytest.raises(ValueError):- await client.get_enrichment_status(["urn:harmonic:enrichment:aaa"])+ with patch(HARMONIC_REQUEST, new=AsyncMock(return_value=_response(json_data={"error": "not a list"}))):+ with pytest.raises(ValueError):+ await _client().get_enrichment_status(["urn:harmonic:enrichment:aaa"])@pytest.mark.asyncio-@patch("ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep", new=AsyncMock())async def test_get_enrichment_status_reraises_on_http_error():- client = _client_with_get_responses(_http_500())- with pytest.raises(aiohttp.ClientResponseError):- await client.get_enrichment_status(["urn:harmonic:enrichment:aaa"])+ with patch(HARMONIC_REQUEST, new=AsyncMock(return_value=_http_500())):+ with pytest.raises(aiohttp.ClientResponseError):+ await _client().get_enrichment_status(["urn:harmonic:enrichment:aaa"])+++@patch(PACE_SECONDS_HARMONIC)+@patch(ASYNCIO_SLEEP, new_callable=AsyncMock)+async def test_enrich_companies_batch_repaces_before_each_wave(mock_sleep, mock_pace):+ # A single pace for the whole batch lets a later wave burst past a budget an earlier wave+ # already drew down, so this asserts a pace per wave against live limiter state.+ clock = _FakeClock()+ gate = _FakeGate(clock, budget=_ENRICH_WAVE_SIZE) # exactly one wave's worth per window+ mock_pace.side_effect = gate.pace_seconds+ mock_sleep.side_effect = _clock_advancing_sleep(clock)++ domains = [f"d{i}.com" for i in range(_ENRICH_WAVE_SIZE + 5)] # spans two waves+ client = _client(priority=Priority.BATCH)+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=gate.request)):+ results = await client.enrich_companies_batch(domains)++ assert results == [{"name": d} for d in domains]+ assert mock_pace.call_count > 1+ mock_sleep.assert_awaited_once_with(pytest.approx(1.0))+++@patch(PACE_SECONDS_HARMONIC)+@patch(ASYNCIO_SLEEP, new_callable=AsyncMock)+async def test_enrich_companies_batch_retries_a_denied_domain_in_a_later_attempt(mock_sleep, mock_pace):+ clock = _FakeClock()+ gate = _FakeGate(clock, budget=2) # only the first two of three domains admit on attempt 1+ mock_pace.side_effect = gate.pace_seconds+ mock_sleep.side_effect = _clock_advancing_sleep(clock)++ domains = ["a.com", "b.com", "c.com"]+ client = _client(priority=Priority.BATCH)+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=gate.request)):+ results = await client.enrich_companies_batch(domains)++ # c.com was shed on attempt 1 and must come back with a result once the budget refills,+ # not silently become the same None a genuine miss returns.+ assert results == [{"name": "a.com"}, {"name": "b.com"}, {"name": "c.com"}]+ assert mock_pace.call_count > 1+ mock_sleep.assert_awaited_once_with(pytest.approx(1.0))+++@patch(PACE_SECONDS_HARMONIC)+@patch(ASYNCIO_SLEEP, new_callable=AsyncMock)+@patch("ee.billing.salesforce_enrichment.harmonic_client.capture_exception")+async def test_enrich_companies_batch_reports_denied_forever_distinctly_from_a_not_found(+ mock_capture, mock_sleep, mock_pace+):+ clock = _FakeClock()+ # Budget stays generous throughout: denied.com is denied by always_deny, never by the shared+ # budget, so this isolates "denied on every attempt" from "the budget never had headroom".+ gate = _FakeGate(clock, budget=100, always_deny={"denied.com"}, not_found={"miss.com"})+ mock_pace.side_effect = gate.pace_seconds+ mock_sleep.side_effect = _clock_advancing_sleep(clock)++ domains = ["denied.com", "miss.com"]+ client = _client(priority=Priority.BATCH)+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=gate.request)):+ results = await client.enrich_companies_batch(domains)++ # Both look the same in the return value, since enrich_companies_batch keeps its list+ # compatible with callers that zip it against the input domains, but only the denied one gets+ # captured to error tracking.+ assert results == [None, None]+ captured_domains = [call.args[1]["domain"] for call in mock_capture.call_args_list]+ assert captured_domains == ["denied.com"]+ assert isinstance(mock_capture.call_args_list[0].args[0], HarmonicEgressBudgetExhausted)+++@patch(PACE_SECONDS_HARMONIC, return_value=5.0)+async def test_enrich_companies_batch_propagates_cancellation_during_inter_wave_sleep(mock_pace):+ sleep_started = asyncio.Event()++ async def blocking_sleep(seconds: float) -> None:+ sleep_started.set()+ await _REAL_SLEEP(3600) # the test cancels well before this would ever return++ domains = ["a.com", "b.com"]+ client = _client(priority=Priority.BATCH)+ mock_request = AsyncMock(side_effect=[_found({"name": "A"}), _found({"name": "B"})])+ with patch(HARMONIC_REQUEST, new=mock_request), patch(ASYNCIO_SLEEP, new=blocking_sleep):+ task = asyncio.create_task(client.enrich_companies_batch(domains))+ await sleep_started.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+++@patch(PACE_SECONDS_HARMONIC)+@patch(ASYNCIO_SLEEP, new_callable=AsyncMock)+async def test_enrich_companies_batch_skips_pacing_for_critical_priority(mock_sleep, mock_pace):+ # CRITICAL is never shed by the transport (_raise_if_denied never raises on it), so pacing it+ # would only add latency to an interactive caller for no admission benefit.+ client = _client(priority=Priority.CRITICAL)+ mock_request = AsyncMock(side_effect=[_found({"name": "A"}), _found({"name": "B"})])+ with patch(HARMONIC_REQUEST, new=mock_request):+ results = await client.enrich_companies_batch(["a.com", "b.com"])++ assert results == [{"name": "A"}, {"name": "B"}]+ mock_pace.assert_not_called()+ mock_sleep.assert_not_awaited()+++@patch(PACE_SECONDS_HARMONIC, return_value=0.0)+@patch(ASYNCIO_SLEEP, new_callable=AsyncMock)+@patch("ee.billing.salesforce_enrichment.harmonic_client.capture_exception")+async def test_enrich_companies_batch_names_the_domain_of_an_operational_failure(mock_capture, mock_sleep, mock_pace):+ async def request(session, method, url, *, json, **kwargs):+ website_url = json["variables"]["identifiers"]["websiteUrl"]+ if "broken.com" in website_url:+ return _graphql_errors()+ return _found({"name": "ok"})++ client = _client(priority=Priority.BATCH)+ with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=request)):+ results = await client.enrich_companies_batch(["ok.com", "broken.com"])++ assert results == [{"name": "ok"}, None]+ mock_capture.assert_called_once()+ assert mock_capture.call_args.args[1:] == ({"domain": "broken.com"},)+++@patch(PACE_SECONDS_HARMONIC, return_value=0.0)+@patch(ASYNCIO_SLEEP, new_callable=AsyncMock)+async def test_enrich_companies_batch_with_a_single_domain(mock_sleep, mock_pace):+ # _enrich_specific_domain_debug calls enrich_companies_batch with exactly one domain; the+ # wave/retry slicing must not misbehave at that boundary.+ client = _client(priority=Priority.BATCH)+ mock_request = AsyncMock(side_effect=[_found({"name": "PostHog"})])+ with patch(HARMONIC_REQUEST, new=mock_request):+ results = await client.enrich_companies_batch(["posthog.com"])+ assert results == [{"name": "PostHog"}]diff --git a/posthog/egress/README.md b/posthog/egress/README.mdindex 433f2aed72f7..a9cb8063aec8 100644--- a/posthog/egress/README.md+++ b/posthog/egress/README.md@@ -81,6 +81,12 @@ One scrape is one credit, so those numbers cap a bill as much as a rate; they arEvery Firecrawl call runs on a sheddable lane: what gets scraped is derived from user-supplied input and callers can do without the scrape, so nothing in this domain runs `CRITICAL`.`FIRECRAWL_API_KEY` authenticates every call as a bearer token; an instance without one makes no request at all (`FirecrawlNotConfigured`).+Harmonic (`harmonic/`) meters one account-wide rate limit, and an instance holds a single API key, so it uses one constant scope like the two above.+The budget is a single per-second ceiling read from settings at acquire time: `HARMONIC_EGRESS_PER_SECOND_BUDGET` (default 15).+Harmonic publishes no rate limit we could confirm, so that default is seeded from observed throughput and is meant to be tuned against the rate-limit headers this domain records.+Harmonic is the first async domain: it subclasses `AsyncEgressClient` rather than `EgressClient`, because its client speaks `aiohttp`.+Its lanes carry very different traffic, so the reserve floor matters: signup enrichment and the ICP re-enrichment sweep run `CRITICAL` inside a short Temporal activity budget, while the Salesforce enrichment sweep runs `BATCH` and yields to them.+### Priority lanesPriority (`CRITICAL` / `NORMAL` / `BATCH`) controls how sheddable a call is when the budget gets tight.diff --git a/posthog/egress/firecrawl/observability.py b/posthog/egress/firecrawl/observability.pyindex 37c72f638892..7e4b85932b6c 100644--- a/posthog/egress/firecrawl/observability.py+++ b/posthog/egress/firecrawl/observability.py@@ -16,6 +16,7 @@ from posthog.egress.observability.observability import (RateLimitSnapshot,default_normalize_endpoint,register_egress_observability,+ unpack_requests_response,)FIRECRAWL_DOMAIN = "firecrawl"@@ -57,15 +58,13 @@ def _float_header(headers: Mapping[str, str] | None, name: str) -> float | None:return None-def _parse_firecrawl_rate_limit(response: requests.Response) -> RateLimitSnapshot:+def _parse_firecrawl_rate_limit(headers: Mapping[str, str] | None, url: str | None) -> RateLimitSnapshot:"""Read Firecrawl's rate-limit headers when the response carries them. ``reset_at`` is left unsetbecause Firecrawl does not document whether its reset header is an epoch or a number of seconds,- and a gauge that could be either is worse than an unset one."""- headers = response.headers if isinstance(response.headers, Mapping) else None- request = getattr(response, "request", None)- url = getattr(request, "url", None)+ and a gauge that could be either is worse than an unset one. ``resource`` comes from the request+ url, not a curated endpoint label, because Firecrawl meters each endpoint separately."""return RateLimitSnapshot(- resource=default_normalize_endpoint(url if isinstance(url, str) else None),+ resource=default_normalize_endpoint(url),remaining=_float_header(headers, "X-RateLimit-Remaining"),limit=_float_header(headers, "X-RateLimit-Limit"),)@@ -84,7 +83,17 @@ def record_firecrawl_api_response() -> None:"""Record one Firecrawl API response. The scope is always the instance's single account,because Firecrawl meters per API key and each instance holds exactly one."""- firecrawl_egress.record_response(response, source=source, scope="default", method=method, endpoint=endpoint)+ primitives = unpack_requests_response(response)+ firecrawl_egress.record_response(+ primitives.status_code,+ primitives.headers,+ source=source,+ scope="default",+ method=method,+ endpoint=endpoint,+ request_method=primitives.request_method,+ request_url=primitives.request_url,+ )def record_firecrawl_api_exception(diff --git a/posthog/egress/github/observability.py b/posthog/egress/github/observability.pyindex 07ec5506a52c..d6cfb156c1bb 100644--- a/posthog/egress/github/observability.py+++ b/posthog/egress/github/observability.py@@ -22,6 +22,7 @@ from posthog.egress.observability.observability import (EgressObservability,RateLimitSnapshot,register_egress_observability,+ unpack_requests_response,)GITHUB_DOMAIN = "github"@@ -66,8 +67,7 @@ def _float_header(headers: Mapping[str, str] | None, name: str) -> float | None:return None-def _parse_github_rate_limit(response: requests.Response) -> RateLimitSnapshot:- headers = response.headers if isinstance(response.headers, Mapping) else None+def _parse_github_rate_limit(headers: Mapping[str, str] | None, _url: str | None) -> RateLimitSnapshot:return RateLimitSnapshot(resource=headers.get("X-RateLimit-Resource", "unknown") if headers is not None else "unknown",remaining=_float_header(headers, "X-RateLimit-Remaining"),@@ -143,7 +143,17 @@ def record_github_api_response("""Record one GitHub API response. ``installation_id`` is the GitHub App installation — the sharedrate-limit budget GitHub meters. Pass it when known so the rate-limit gauges are set; identity-blindcallers (raw PATs) get request volume only. ``source`` attributes the call to a subsystem."""- github_egress.record_response(response, source=source, scope=installation_id, method=method, endpoint=endpoint)+ primitives = unpack_requests_response(response)+ github_egress.record_response(+ primitives.status_code,+ primitives.headers,+ source=source,+ scope=installation_id,+ method=method,+ endpoint=endpoint,+ request_method=primitives.request_method,+ request_url=primitives.request_url,+ )def record_github_api_exception(diff --git a/posthog/egress/google_workspace/observability.py b/posthog/egress/google_workspace/observability.pyindex 2c66ed44928c..101712fac217 100644--- a/posthog/egress/google_workspace/observability.py+++ b/posthog/egress/google_workspace/observability.py@@ -1,3 +1,5 @@+from collections.abc import Mapping+import requestsfrom prometheus_client import Counter, Gauge@@ -7,6 +9,7 @@ from posthog.egress.observability.observability import (EgressObservability,RateLimitSnapshot,register_egress_observability,+ unpack_requests_response,)_metrics = EgressMetrics(@@ -33,7 +36,7 @@ _metrics = EgressMetrics()-def _parse_google_workspace_rate_limit(_response: requests.Response) -> RateLimitSnapshot:+def _parse_google_workspace_rate_limit(_headers: Mapping[str, str] | None, _url: str | None) -> RateLimitSnapshot:return RateLimitSnapshot(resource="api")@@ -53,12 +56,16 @@ def record_google_workspace_api_response(method: str,endpoint: str,) -> None:+ primitives = unpack_requests_response(response)google_workspace_egress.record_response(- response,+ primitives.status_code,+ primitives.headers,source=source,scope=account_id,method=method,endpoint=endpoint,+ request_method=primitives.request_method,+ request_url=primitives.request_url,)diff --git a/posthog/egress/harmonic/__init__.py b/posthog/egress/harmonic/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/egress/harmonic/limiter.py b/posthog/egress/harmonic/limiter.pynew file mode 100644index 000000000000..5f41c4ca25b2--- /dev/null+++ b/posthog/egress/harmonic/limiter.py@@ -0,0 +1,68 @@+"""Harmonic egress budget.++Harmonic bills one account-wide rate limit — there is one ``HARMONIC_API_KEY`` per PostHog+instance, not one per installation or team — so every call anywhere in the codebase draws from a+single shared budget under the constant key ``harmonic:account:default``.++Harmonic publishes no rate limit, so the budget is an operator ceiling to tune against the+rate-limit headers this domain records.++Two very different consumers share this budget, so the priority lanes matter:+- CRITICAL (interactive): signup enrichment and the ICP re-enrichment sweep run inside a+ 90-second Temporal activity budget and must never be starved by bulk traffic.+- BATCH: the Salesforce enrichment sweep works through a large account backlog and can back off+ when the budget is tight.++Importing this module registers the policy as a side effect — import it (directly or via+``consume_harmonic``/``acquire_harmonic``) before using the ``harmonic:account:default`` key.+"""++from django.conf import settings++from posthog.egress.limiter.outbound import get_outbound_rate_limiter+from posthog.egress.limiter.policies import Priority, RatePolicy, register_policy++HARMONIC_DOMAIN = "harmonic"++# One account per instance — Harmonic meters usage account-wide, not per installation.+_ACCOUNT_SCOPE_ID = "default"+HARMONIC_ACCOUNT_KEY = f"{HARMONIC_DOMAIN}:account:{_ACCOUNT_SCOPE_ID}"++_DEFAULT_PER_SECOND_BUDGET = 15++# Same reserved-floor ladder as the other egress domains: BATCH is denied first as the budget+# fills, then NORMAL, so the interactive lane (CRITICAL) can never be starved by the weekly bulk+# enrichment job saturating the shared counter.+_RESERVE: dict[Priority, float] = {Priority.BATCH: 0.30, Priority.NORMAL: 0.10}+++# Registered as a provider so the budget is read at acquire time — a settings override applies+# without a process restart, matching the other egress domains.+def _harmonic_policy(_key: str) -> RatePolicy:+ per_second = int(getattr(settings, "HARMONIC_EGRESS_PER_SECOND_BUDGET", _DEFAULT_PER_SECOND_BUDGET))+ return RatePolicy(+ limits=((per_second, 1.0),),+ in_memory_divider=4,+ reserve=_RESERVE,+ )+++register_policy(HARMONIC_DOMAIN, _harmonic_policy)+++def consume_harmonic(priority: Priority = Priority.NORMAL, source: str = "unknown") -> bool:+ """Sync gate, for callers outside an event loop. Returns False when the budget (or this+ priority's reserved floor) is exhausted — degrade gracefully rather than calling out."""+ return get_outbound_rate_limiter().consume_sync(HARMONIC_ACCOUNT_KEY, priority=priority, source=source)+++async def acquire_harmonic(priority: Priority = Priority.NORMAL, source: str = "unknown") -> bool:+ """Async gate — the primary path, since the Harmonic client is aiohttp-based."""+ return await get_outbound_rate_limiter().acquire(HARMONIC_ACCOUNT_KEY, priority=priority, source=source)+++def pace_seconds_harmonic(priority: Priority = Priority.NORMAL) -> float:+ """Seconds to wait before the next call, for a caller that can wait (the bulk enrichment job+ walking pages) so it spreads its share of the budget instead of bursting into it and being+ shed. Advisory only — acquire/consume remain the sole admission authority."""+ return get_outbound_rate_limiter().pace_seconds(HARMONIC_ACCOUNT_KEY, priority=priority)diff --git a/posthog/egress/harmonic/observability.py b/posthog/egress/harmonic/observability.pynew file mode 100644index 000000000000..1ee93ea3ae81--- /dev/null+++ b/posthog/egress/harmonic/observability.py@@ -0,0 +1,114 @@+"""Harmonic egress telemetry.++Every Harmonic call funnels through these recorders so request volume and Harmonic's own+rate-limit headers land on one metric set, attributed by the ``source`` label — the same generic+:class:`EgressObservability` mechanism every other domain (github, logo.dev, Firecrawl, Vapi,+Google Workspace, Slack) uses. Harmonic's client is aiohttp-based+(``ee/billing/salesforce_enrichment/harmonic_client.py``), but ``record_response`` takes status+code, headers and request method/url as plain primitives, so it's transport-agnostic — Harmonic's+``HarmonicClient._record_response`` unpacks an ``aiohttp.ClientResponse`` itself and calls+``record_harmonic_api_response(response.status, response.headers, ...)``.++Harmonic bills one account-wide rate limit rather than a per-installation one, so ``_SCOPE`` (the+metric scope label) and ``_RATE_LIMIT_RESOURCE`` (the rate-limit resource) are two distinct+constants that happen to both be singletons for this domain today.++Harmonic's own rate-limit header names are not confirmed from public docs (their docs page is a+client-rendered SPA). The parser below reads the GitHub-style ``X-RateLimit-*`` names plus the+``X-Ratelimit-*-Second`` variants, and returns None for anything absent or unparseable rather than+raising — telemetry must never break the request it is recording.+"""++from collections.abc import Mapping++from prometheus_client import Counter, Gauge++from posthog.egress.observability.observability import (+ EgressMetrics,+ EgressObservability,+ RateLimitSnapshot,+ register_egress_observability,+)++HARMONIC_DOMAIN = "harmonic"++# Harmonic bills one account-wide limit, not a per-installation one, so every call shares this scope.+_SCOPE = "default"++# Harmonic rate-limits the whole account rather than per endpoint, so every observed header+# describes the same one resource.+_RATE_LIMIT_RESOURCE = "account"++_metrics = EgressMetrics(+ request_counter=Counter(+ "harmonic_api_requests",+ "Number of Harmonic API requests made through the Harmonic egress client.",+ labelnames=["scope", "method", "endpoint", "status_code", "source"],+ ),+ remaining_gauge=Gauge(+ "harmonic_api_rate_limit_remaining",+ "Most recently observed Harmonic rate limit remaining count.",+ labelnames=["scope", "resource"],+ ),+ limit_gauge=Gauge(+ "harmonic_api_rate_limit_limit",+ "Most recently observed Harmonic rate limit.",+ labelnames=["scope", "resource"],+ ),+ reset_gauge=Gauge(+ "harmonic_api_rate_limit_reset_timestamp_seconds",+ "Most recently observed Harmonic rate limit reset timestamp.",+ labelnames=["scope", "resource"],+ ),+)++# Preferred first: the per-second variant matches the window this domain's policy actually gates.+# Falls back to the GitHub-style name in case Harmonic serves only that one.+_REMAINING_HEADERS = ("X-Ratelimit-Remaining-Second", "X-RateLimit-Remaining")+_LIMIT_HEADERS = ("X-Ratelimit-Limit-Second", "X-RateLimit-Limit")+_RESET_HEADERS = ("X-RateLimit-Reset",)+++def _first_float_header(headers: Mapping[str, str], names: tuple[str, ...]) -> float | None:+ for name in names:+ raw = headers.get(name)+ if raw is None:+ continue+ try:+ return float(raw)+ except (TypeError, ValueError):+ continue+ return None+++def _parse_harmonic_rate_limit(headers: Mapping[str, str] | None, _url: str | None) -> RateLimitSnapshot:+ headers = headers or {}+ return RateLimitSnapshot(+ resource=_RATE_LIMIT_RESOURCE,+ remaining=_first_float_header(headers, _REMAINING_HEADERS),+ limit=_first_float_header(headers, _LIMIT_HEADERS),+ reset_at=_first_float_header(headers, _RESET_HEADERS),+ )+++harmonic_egress = EgressObservability(HARMONIC_DOMAIN, _metrics, _parse_harmonic_rate_limit)+register_egress_observability(harmonic_egress)+++def record_harmonic_api_response(+ status: int,+ headers: Mapping[str, str] | None,+ *,+ source: str,+ method: str,+ endpoint: str | None = None,+) -> None:+ """Record one Harmonic API response. ``method``/``endpoint`` are the caller's curated labels —+ Harmonic's few endpoints (``/graphql``, ``/companies/{id}``, ``/enrichment_status``) are cheap+ to pass explicitly, so there is no URL-derived endpoint normaliser here."""+ harmonic_egress.record_response(status, headers, source=source, scope=_SCOPE, method=method, endpoint=endpoint)+++def record_harmonic_api_exception(*, source: str, method: str, endpoint: str | None = None) -> None:+ """Record a request that raised before a response (timeout, connection error)."""+ harmonic_egress.record_exception(source=source, scope=_SCOPE, method=method, endpoint=endpoint)diff --git a/posthog/egress/harmonic/transport.py b/posthog/egress/harmonic/transport.pynew file mode 100644index 000000000000..afce382651e7--- /dev/null+++ b/posthog/egress/harmonic/transport.py@@ -0,0 +1,85 @@+"""Harmonic incarnation of the egress transport — async, since the Harmonic client is aiohttp-based+(``ee/billing/salesforce_enrichment/harmonic_client.py``). It subclasses+:class:`posthog.egress.transport.transport.AsyncEgressClient`, the aiohttp counterpart to the+``EgressClient`` base the sync domains (github, logo.dev, Firecrawl, Vapi) use.+"""++from typing import Any++import aiohttp++from posthog.egress.harmonic.limiter import acquire_harmonic+from posthog.egress.harmonic.observability import record_harmonic_api_exception, record_harmonic_api_response+from posthog.egress.limiter.policies import Priority+from posthog.egress.transport.transport import AsyncEgressClient, EgressBudgetExhausted++# Harmonic bills one account-wide budget, so every call carries the same scope. AsyncEgressClient+# skips its gate entirely on a falsy scope, and Harmonic has no per-caller identity to gate on+# instead, so this constant is what keeps every Harmonic call gated.+_ACCOUNT_SCOPE = "default"+++class HarmonicEgressBudgetExhausted(EgressBudgetExhausted):+ """A sheddable (BATCH/NORMAL) Harmonic call was shed by our egress limiter before it was ever+ sent — it is raised before the request reaches Harmonic, so it is never an+ aiohttp.ClientResponseError from Harmonic's own response. Callers that can degrade should catch+ this and back off; CRITICAL calls are never raised on, they proceed and let Harmonic's own rate+ limiting be the backstop.++ This is a transient operational condition, not evidence a company is missing. A caller that+ folds every exception into an enrichment miss (e.g. returning None on ``except Exception``)+ must catch this one first and re-raise or retry, or a throttled request gets permanently+ recorded as a Harmonic not-found."""+++class HarmonicClient(AsyncEgressClient):+ """The Harmonic incarnation of :class:`AsyncEgressClient`. Stateless; the caller supplies its+ own ``aiohttp.ClientSession`` (``AsyncHarmonicClient`` already manages one via ``async with``,+ matching aiohttp's recommended session-reuse pattern rather than one session per call)."""++ def _standard_headers(self) -> dict[str, str]:+ return {"Content-Type": "application/json"}++ async def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:+ return await acquire_harmonic(priority, source)++ def _record_response(+ self, response: aiohttp.ClientResponse, *, source: str, scope: str | None, method: str, endpoint: str | None+ ) -> None:+ record_harmonic_api_response(response.status, response.headers, source=source, method=method, endpoint=endpoint)++ def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:+ record_harmonic_api_exception(source=source, method=method, endpoint=endpoint)++ def _budget_exhausted_error(self, scope: str) -> HarmonicEgressBudgetExhausted:+ return HarmonicEgressBudgetExhausted("Harmonic egress budget exhausted; degrading")+++_harmonic_client = HarmonicClient()+++async def harmonic_request(+ session: aiohttp.ClientSession,+ method: str,+ url: str,+ *,+ source: str,+ priority: Priority = Priority.CRITICAL,+ endpoint: str | None = None,+ headers: dict[str, str] | None = None,+ **kwargs: Any,+) -> aiohttp.ClientResponse:+ """Make a gated, recorded Harmonic request on an existing session. ``source`` attributes the+ call to a subsystem; callers own auth (the ``apikey`` header, never a URL query param — a+ URL-borne key leaks into aiohttp exception telemetry)."""+ return await _harmonic_client.request(+ session,+ method,+ url,+ source=source,+ scope=_ACCOUNT_SCOPE,+ priority=priority,+ endpoint=endpoint,+ headers=headers,+ **kwargs,+ )diff --git a/posthog/egress/logodev/observability.py b/posthog/egress/logodev/observability.pyindex d9bc68c1f9de..1e9931a1c851 100644--- a/posthog/egress/logodev/observability.py+++ b/posthog/egress/logodev/observability.py@@ -7,6 +7,7 @@ snapshot and the gauges stay unset — they exist because :class:`EgressMetrics`instrument set, and they start reporting the moment logo.dev grows the headers."""+from collections.abc import Mappingfrom urllib.parse import urlparseimport requests@@ -17,6 +18,7 @@ from posthog.egress.observability.observability import (EgressObservability,RateLimitSnapshot,register_egress_observability,+ unpack_requests_response,)LOGODEV_DOMAIN = "logodev"@@ -45,7 +47,7 @@ _metrics = EgressMetrics()-def _parse_logodev_rate_limit(response: requests.Response) -> RateLimitSnapshot:+def _parse_logodev_rate_limit(_headers: Mapping[str, str] | None, _url: str | None) -> RateLimitSnapshot:return RateLimitSnapshot()@@ -77,7 +79,17 @@ def record_logodev_api_response() -> None:"""Record one logo.dev API response. The scope is always the instance's single account —logo.dev meters per token and each instance holds exactly one."""- logodev_egress.record_response(response, source=source, scope="default", method=method, endpoint=endpoint)+ primitives = unpack_requests_response(response)+ logodev_egress.record_response(+ primitives.status_code,+ primitives.headers,+ source=source,+ scope="default",+ method=method,+ endpoint=endpoint,+ request_method=primitives.request_method,+ request_url=primitives.request_url,+ )def record_logodev_api_exception(diff --git a/posthog/egress/observability/observability.py b/posthog/egress/observability/observability.pyindex b45091e5991d..c57702f78a9d 100644--- a/posthog/egress/observability/observability.py+++ b/posthog/egress/observability/observability.py@@ -10,13 +10,15 @@ valid and every API can name its metrics idiomatically — the reuse is in the rendpoint-normalisation, and the registry, not in a single metric series."""-from collections.abc import Callable+from collections.abc import Callable, Mappingfrom dataclasses import dataclassfrom urllib.parse import urlparseimport requestsfrom prometheus_client import Counter, Gauge+from posthog.dataclasses import frozen+@dataclass(frozen=True)class RateLimitSnapshot:@@ -29,9 +31,12 @@ class RateLimitSnapshot:reset_at: float | None = None-# Parses a response into a RateLimitSnapshot. Per-domain because each API exposes its budget-# differently (GitHub: X-RateLimit-* headers; others may use different headers or a body field).-ResponseParser = Callable[[requests.Response], RateLimitSnapshot]+# Parses a response into a RateLimitSnapshot from its headers and, for a domain that keys its+# gauge resource by endpoint (e.g. Firecrawl), the request url. Per-domain because each API exposes+# its budget differently (GitHub: X-RateLimit-* headers; others may use different headers or a body+# field), and transport-agnostic — headers and a url exist whether the request was requests- or+# aiohttp-based.+ResponseParser = Callable[[Mapping[str, str] | None, str | None], RateLimitSnapshot]@dataclass(frozen=True)@@ -68,6 +73,36 @@ def default_normalize_endpoint(url: str | None) -> str:return "/" + "/".join("{id}" if seg.isdigit() else seg for seg in path.split("/"))+@frozen+class ResponsePrimitives:+ """What :meth:`EgressObservability.record_response` needs, independent of the HTTP client that+ produced it. ``request_method`` and ``request_url`` come from the request, not the response."""++ status_code: int+ headers: Mapping[str, str] | None+ request_method: str | None+ request_url: str | None+++def unpack_requests_response(response: requests.Response) -> ResponsePrimitives:+ """Pull the primitives :meth:`EgressObservability.record_response` needs off a ``requests.Response``:+ status code, headers, and the prepared request's method/url. A response's ``.request`` (and its+ method/url) may be absent or non-string — a response built without a prepared request, or a test+ mock whose attributes are themselves Mocks — so this coerces to str-or-None/Mapping-or-None rather+ than raising: telemetry is best-effort, and a urlparse(Mock) blowing up here must not fail the+ actual outbound call."""+ headers = response.headers if isinstance(response.headers, Mapping) else None+ request = getattr(response, "request", None)+ req_method = getattr(request, "method", None)+ req_url = getattr(request, "url", None)+ return ResponsePrimitives(+ status_code=response.status_code,+ headers=headers,+ request_method=req_method if isinstance(req_method, str) else None,+ request_url=req_url if isinstance(req_url, str) else None,+ )++class EgressObservability:"""One third-party API's egress telemetry: a metric set, a response parser, and an endpointnormaliser. Construct one per domain and register it; consumers record through it.@@ -92,36 +127,31 @@ class EgressObservability:def record_response(self,- response: requests.Response,+ status_code: int,+ headers: Mapping[str, str] | None,*,source: str,scope: str | None = None,method: str | None = None,endpoint: str | None = None,+ request_method: str | None = None,+ request_url: str | None = None,) -> None:- # The response's .request (and its method/url) may be absent or non-string — a response built- # without a prepared request, or a test mock whose attributes are themselves Mocks. Coerce to- # str-or-None so a recorder never raises into the request flow: telemetry is best-effort, and a- # urlparse(Mock) blowing up here must not fail the actual GitHub call.- request = getattr(response, "request", None)- req_method = getattr(request, "method", None)- req_url = getattr(request, "url", None)- method_label = (method or (req_method if isinstance(req_method, str) else None) or "GET").upper()- endpoint_label = (- endpoint- if endpoint is not None- else self._normalize_endpoint(req_url if isinstance(req_url, str) else None)- )- self._metrics.request_counter.labels(- scope or "", method_label, endpoint_label, str(response.status_code), source- ).inc()+ """``status_code``/``headers`` are the response's own; ``request_method``/``request_url`` are+ the request's, used only as a fallback when the caller doesn't pass a curated ``method``/+ ``endpoint``. Callers unpack their transport's response type into these primitives (see+ :func:`unpack_requests_response` for the ``requests`` case) so this method stays+ transport-agnostic — sync (``requests``) and async (``aiohttp``) domains share it alike."""+ method_label = (method or request_method or "GET").upper()+ endpoint_label = endpoint if endpoint is not None else self._normalize_endpoint(request_url)+ self._metrics.request_counter.labels(scope or "", method_label, endpoint_label, str(status_code), source).inc()if scope is None:return# Gauges are keyed by (scope, resource) only — the shared budget owner, no source. Every# source sharing one budget updates one series; a per-source gauge would strand stale values.- snapshot = self._parser(response)+ snapshot = self._parser(headers, request_url)if snapshot.remaining is not None:self._metrics.remaining_gauge.labels(scope, snapshot.resource).set(snapshot.remaining)if snapshot.limit is not None:@@ -192,6 +222,14 @@ def record_outbound_api_response(endpoint: str | None = None,) -> None:"""Domain-keyed convenience for generic callers that hold only a domain string."""+ primitives = unpack_requests_response(response)resolve_egress_observability(domain).record_response(- response, source=source, scope=scope, method=method, endpoint=endpoint+ primitives.status_code,+ primitives.headers,+ source=source,+ scope=scope,+ method=method,+ endpoint=endpoint,+ request_method=primitives.request_method,+ request_url=primitives.request_url,)diff --git a/posthog/egress/slack/observability.py b/posthog/egress/slack/observability.pyindex 5b732ae391d5..45a4feb6b41f 100644--- a/posthog/egress/slack/observability.py+++ b/posthog/egress/slack/observability.py@@ -50,7 +50,7 @@ def _header(headers: Mapping[str, object], name: str) -> str | None:return None-def _parse_slack_rate_limit(response: requests.Response) -> RateLimitSnapshot:+def _parse_slack_rate_limit(_headers: Mapping[str, str] | None, _url: str | None) -> RateLimitSnapshot:return RateLimitSnapshot()@@ -76,8 +76,10 @@ def record_slack_api_response() -> None:normalized_workspace_id = workspace_id or Nonetyped_response = cast(requests.Response, response)+ headers = typed_response.headers if isinstance(typed_response.headers, Mapping) else Noneslack_egress.record_response(- typed_response,+ typed_response.status_code,+ headers,source=source,scope=normalized_workspace_id,method=method,diff --git a/posthog/egress/test/test_async_egress_client.py b/posthog/egress/test/test_async_egress_client.pynew file mode 100644index 000000000000..66cc6a100fcb--- /dev/null+++ b/posthog/egress/test/test_async_egress_client.py@@ -0,0 +1,86 @@+from unittest.mock import AsyncMock++import aiohttp++from posthog.egress.limiter.policies import Priority+from posthog.egress.transport.transport import AsyncEgressClient, EgressBudgetExhausted+++class _StubBudgetExhausted(EgressBudgetExhausted):+ pass+++class _StubAsyncEgressClient(AsyncEgressClient):+ def __init__(self, granted: bool) -> None:+ self._granted = granted+ self.recorded_exceptions: list[str] = []++ def _standard_headers(self) -> dict[str, str]:+ return {}++ async def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:+ return self._granted++ def _record_response(+ self, response: aiohttp.ClientResponse, *, source: str, scope: str | None, method: str, endpoint: str | None+ ) -> None:+ pass++ def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:+ self.recorded_exceptions.append(url)++ def _budget_exhausted_error(self, scope: str) -> _StubBudgetExhausted:+ return _StubBudgetExhausted("denied")+++def _fake_session(status: int = 200) -> AsyncMock:+ response = AsyncMock()+ response.status = status+ session = AsyncMock()+ session.request = AsyncMock(return_value=response)+ return session+++async def test_async_base_raises_for_a_denied_sheddable_call() -> None:+ # Proves the denial rule the async base shares with the sync one — a BATCH call sees no exemption.+ client = _StubAsyncEgressClient(granted=False)+ session = _fake_session()++ raised = False+ try:+ await client.request(+ session, "GET", "https://example.com", source="test", scope="scope", priority=Priority.BATCH+ )+ except _StubBudgetExhausted:+ raised = True++ assert raised+ session.request.assert_not_called()+++async def test_async_base_never_raises_for_a_denied_critical_call() -> None:+ client = _StubAsyncEgressClient(granted=False)+ session = _fake_session()++ await client.request(+ session, "GET", "https://example.com", source="test", scope="scope", priority=Priority.CRITICAL+ )++ session.request.assert_awaited_once()+++async def test_async_base_records_a_total_deadline_timeout() -> None:+ # aiohttp raises a bare TimeoutError when ClientTimeout.total expires, and only wraps the+ # connect phase into a ClientError, so catching ClientError alone loses the likeliest outage.+ client = _StubAsyncEgressClient(granted=True)+ session = _fake_session()+ session.request = AsyncMock(side_effect=TimeoutError())++ raised = False+ try:+ await client.request(session, "GET", "https://example.com", source="test", scope="scope")+ except TimeoutError:+ raised = True++ assert raised+ assert client.recorded_exceptions == ["https://example.com"]diff --git a/posthog/egress/test/test_firecrawl.py b/posthog/egress/test/test_firecrawl.pyindex 814aaa7f0695..67fab281a696 100644--- a/posthog/egress/test/test_firecrawl.py+++ b/posthog/egress/test/test_firecrawl.py@@ -8,9 +8,12 @@ from django.test import SimpleTestCase, override_settingsimport requestsfrom parameterized import parameterized+from prometheus_client import REGISTRY+from requests.structures import CaseInsensitiveDictfrom posthog.egress.firecrawl.client import FirecrawlNotConfigured, FirecrawlScrapeFailed, scrapefrom posthog.egress.firecrawl.limiter import consume_firecrawl_sync, firecrawl_account_key+from posthog.egress.firecrawl.observability import record_firecrawl_api_responsefrom posthog.egress.limiter.policies import Priority, resolve_policy_FAKE_API_KEY = "fake-key-for-tests"@@ -37,6 +40,17 @@ def _response(status: int, body: str) -> requests.Response:return response+def _response_with_rate_limit_headers(headers: dict[str, str], url: str) -> requests.Response:+ response = requests.models.Response()+ response.status_code = 200+ response.headers = CaseInsensitiveDict(headers)+ prepared = requests.models.PreparedRequest()+ prepared.method = "GET"+ prepared.url = url+ response.request = prepared+ return response++@contextmanagerdef _firecrawl_answers(response: requests.Response) -> Iterator[tuple[MagicMock, MagicMock]]:"""Yield the patched sender and limiter gate. The gate is patched so these tests never draw on@@ -115,3 +129,27 @@ class TestFirecrawlEgress(SimpleTestCase):# The policy reads settings through getattr defaults, which would swallow a renamed or# misspelled setting and quietly pin the budget to the code default forever.assert resolve_policy(firecrawl_account_key()).limits == ((7, 60.0), (11, 3600.0))++ def test_record_response_keys_the_rate_limit_gauges_by_the_request_url(self) -> None:+ # Firecrawl is the one domain whose gauge resource comes from the request url rather than a+ # curated endpoint label. Losing that wiring silently freezes every gauge under "unknown"+ # regardless of which endpoint was actually called.+ record_firecrawl_api_response(+ _response_with_rate_limit_headers(+ {"X-RateLimit-Remaining": "7", "X-RateLimit-Limit": "60"},+ "https://api.firecrawl.dev/v2/scrape",+ ),+ source="unit-test",+ )+ assert (+ REGISTRY.get_sample_value(+ "firecrawl_api_rate_limit_remaining", {"account": "default", "resource": "/v2/scrape"}+ )+ == 7+ )+ assert (+ REGISTRY.get_sample_value(+ "firecrawl_api_rate_limit_limit", {"account": "default", "resource": "/v2/scrape"}+ )+ == 60+ )diff --git a/posthog/egress/test/test_harmonic.py b/posthog/egress/test/test_harmonic.pynew file mode 100644index 000000000000..4f6167cef6d4--- /dev/null+++ b/posthog/egress/test/test_harmonic.py@@ -0,0 +1,144 @@+import uuid++from unittest.mock import AsyncMock, patch++from django.test import SimpleTestCase, override_settings++from parameterized import parameterized++from posthog.egress.harmonic.limiter import HARMONIC_ACCOUNT_KEY, consume_harmonic+from posthog.egress.harmonic.observability import _parse_harmonic_rate_limit+from posthog.egress.harmonic.transport import HarmonicEgressBudgetExhausted, harmonic_request+from posthog.egress.limiter.backends import LimitsBackend+from posthog.egress.limiter.outbound import OutboundRateLimiter+from posthog.egress.limiter.policies import Priority+from posthog.egress.observability.observability import RateLimitSnapshot+++def _unique_harmonic_key() -> str:+ # Distinct scope per test so it never shares a sliding window with the literal+ # "harmonic:account:default" key (or with another test) while still resolving to the real registered+ # harmonic policy, whose provider only inspects the "harmonic" domain segment.+ return f"harmonic:test:{uuid.uuid4().hex}"+++def _fake_session(status: int = 200, headers: dict | None = None) -> AsyncMock:+ response = AsyncMock()+ response.status = status+ response.headers = headers or {}+ session = AsyncMock()+ session.request = AsyncMock(return_value=response)+ return session+++class TestHarmonicLimiterRegistration(SimpleTestCase):+ def test_policy_is_registered_for_the_global_key(self) -> None:+ # consume raises for a domain with no registered policy — this catches the registration+ # side effect being lost (e.g. an import shuffle dropping the register_policy call).+ assert HARMONIC_ACCOUNT_KEY == "harmonic:account:default"+ assert consume_harmonic(source="test") is True+++@override_settings(HARMONIC_EGRESS_PER_SECOND_BUDGET=3)+async def test_policy_admits_at_the_configured_rate_and_denies_above_it() -> None:+ limiter = OutboundRateLimiter(LimitsBackend())+ key = _unique_harmonic_key()+ grants = [await limiter.acquire(key, priority=Priority.CRITICAL) for _ in range(4)]+ assert grants == [True, True, True, False]+++@override_settings(HARMONIC_EGRESS_PER_SECOND_BUDGET=10)+async def test_batch_pressure_does_not_starve_the_interactive_lane() -> None:+ # Fill the non-reserved share with BATCH (7 of 10, since BATCH reserves 30%), then prove BATCH+ # is denied while CRITICAL still draws from the SAME counter — the reserved floor protecting+ # exactly the headroom a Friday bulk burst must not be allowed to take from a signup lookup.+ limiter = OutboundRateLimiter(LimitsBackend())+ key = _unique_harmonic_key()+ assert all([await limiter.acquire(key, priority=Priority.BATCH) for _ in range(7)])+ assert await limiter.acquire(key, priority=Priority.BATCH) is False+ assert await limiter.acquire(key, priority=Priority.CRITICAL) is True+++class TestHarmonicRateLimitHeaderParser(SimpleTestCase):+ @parameterized.expand(+ [+ ("no_headers", None, RateLimitSnapshot(resource="account")),+ ("empty_headers", {}, RateLimitSnapshot(resource="account")),+ (+ "garbage_values",+ {"X-RateLimit-Remaining": "not-a-number", "X-RateLimit-Limit": "", "X-RateLimit-Reset": "soon"},+ RateLimitSnapshot(resource="account"),+ ),+ (+ "standard_names",+ {"X-RateLimit-Remaining": "42", "X-RateLimit-Limit": "100", "X-RateLimit-Reset": "1700000000"},+ RateLimitSnapshot(resource="account", remaining=42.0, limit=100.0, reset_at=1700000000.0),+ ),+ (+ "second_variant_preferred_over_standard",+ {+ "X-Ratelimit-Remaining-Second": "5",+ "X-RateLimit-Remaining": "500",+ "X-Ratelimit-Limit-Second": "15",+ },+ RateLimitSnapshot(resource="account", remaining=5.0, limit=15.0),+ ),+ (+ "second_variant_alone",+ {"X-Ratelimit-Remaining-Second": "9", "X-Ratelimit-Limit-Second": "15"},+ RateLimitSnapshot(resource="account", remaining=9.0, limit=15.0),+ ),+ ]+ )+ def test_parser_returns_none_for_absent_or_garbage_headers(self, _name, headers, expected) -> None:+ assert _parse_harmonic_rate_limit(headers, None) == expected+++async def test_request_gates_before_sending_and_records_the_response() -> None:+ session = _fake_session(status=201, headers={"X-Ratelimit-Remaining-Second": "9"})+ with (+ patch("posthog.egress.harmonic.transport.acquire_harmonic", AsyncMock(return_value=True)) as acquire,+ patch("posthog.egress.harmonic.transport.record_harmonic_api_response") as record_response,+ ):+ response = await harmonic_request(+ session,+ "POST",+ "https://api.harmonic.ai/graphql",+ source="test",+ priority=Priority.CRITICAL,+ endpoint="/graphql",+ headers={"apikey": "secret"},+ )++ assert response.status == 201+ acquire.assert_awaited_once_with(Priority.CRITICAL, "test")+ session.request.assert_awaited_once()+ assert session.request.call_args.kwargs["headers"]["apikey"] == "secret"+ record_response.assert_called_once_with(+ 201, {"X-Ratelimit-Remaining-Second": "9"}, source="test", method="POST", endpoint="/graphql"+ )+++async def test_request_raises_for_a_sheddable_call_when_the_budget_is_denied() -> None:+ session = _fake_session()+ with patch("posthog.egress.harmonic.transport.acquire_harmonic", AsyncMock(return_value=False)):+ try:+ await harmonic_request(+ session, "GET", "https://api.harmonic.ai/companies/1", source="test", priority=Priority.BATCH+ )+ raised = False+ except HarmonicEgressBudgetExhausted:+ raised = True+ assert raised+ session.request.assert_not_called()+++async def test_request_never_raises_for_critical_even_when_denied() -> None:+ # CRITICAL is never shed by us — it proceeds and lets Harmonic's own rate limiting be the+ # backstop, matching every other egress domain's denial semantics.+ session = _fake_session()+ with patch("posthog.egress.harmonic.transport.acquire_harmonic", AsyncMock(return_value=False)):+ await harmonic_request(+ session, "GET", "https://api.harmonic.ai/companies/1", source="test", priority=Priority.CRITICAL+ )+ session.request.assert_awaited_once()diff --git a/posthog/egress/transport/transport.py b/posthog/egress/transport/transport.pyindex a25acb594640..183984ddc97a 100644--- a/posthog/egress/transport/transport.py+++ b/posthog/egress/transport/transport.py@@ -6,13 +6,26 @@ can make a request that bypasses either. The gate→request→record algorithm adenial semantics are domain-agnostic and live here; each third-party API subclasses and fills thedomain hooks (standard headers, the limiter gate, the recorders, the endpoint normaliser, thebudget-exhausted exception). GitHub is the first incarnation — see :mod:`posthog.egress.github.transport`.++:class:`AsyncEgressClient` is the same algorithm for an aiohttp-based domain (Harmonic is the first —+see :mod:`posthog.egress.harmonic.transport`): ``request``/``_consume`` are coroutines and the transport+returns/catches aiohttp's types instead of ``requests``'. The two bases share the priority-based denial+rule via :func:`_raise_if_denied` rather than each encoding it themselves."""+from __future__ import annotations+from abc import ABC, abstractmethod-from typing import Any+from collections.abc import Callable+from typing import TYPE_CHECKING, Anyimport requests+# aiohttp is only needed by AsyncEgressClient, and the sync domains import this module during+# django.setup(). A module-level import would put aiohttp on the startup path of every process.+if TYPE_CHECKING:+ import aiohttp+from posthog.egress.limiter.policies import Priority@@ -23,6 +36,15 @@ class EgressBudgetExhausted(Exception):proceed and let the API's own rate limiting be the backstop."""+def _raise_if_denied(granted: bool, priority: Priority, make_error: Callable[[], EgressBudgetExhausted]) -> None:+ # CRITICAL never blocks: it records the decision (and consumes if there's room) but proceeds+ # regardless, so a user-facing call is never shed by us — the API's own 429 is the backstop.+ # Sheddable lanes back off so their headroom is left for higher-priority traffic. Shared by both+ # the sync and async gate so the rule can't drift between the two.+ if not granted and priority is not Priority.CRITICAL:+ raise make_error()++class EgressClient(ABC):"""One outbound API's transport: gate → request → record, with priority-based denial semantics.@@ -66,11 +88,7 @@ class EgressClient(ABC):if not scope:returngranted = self._consume(scope, priority, source, url)- # CRITICAL never blocks: it records the decision (and consumes if there's room) but proceeds- # regardless, so a user-facing call is never shed by us — the API's own 429 is the backstop.- # Sheddable lanes back off so their headroom is left for higher-priority traffic.- if not granted and priority is not Priority.CRITICAL:- raise self._budget_exhausted_error(scope)+ _raise_if_denied(granted, priority, lambda: self._budget_exhausted_error(scope))# --- domain hooks -------------------------------------------------------------------------------@@ -97,3 +115,75 @@ class EgressClient(ABC):def _budget_exhausted_error(self, scope: str) -> EgressBudgetExhausted:"""The domain-specific exception raised when a sheddable call is denied (a subclass of:class:`EgressBudgetExhausted`)."""+++class AsyncEgressClient(ABC):+ """The aiohttp counterpart to :class:`EgressClient`, for a domain whose client is async (Harmonic+ is the first — see :mod:`posthog.egress.harmonic.transport`). Same gate → request → record+ algorithm, same domain hooks, and the same ``scope``/priority semantics; only the transport is+ async and speaks aiohttp's types instead of ``requests``'.+ """++ async def request(+ self,+ session: aiohttp.ClientSession,+ method: str,+ url: str,+ *,+ source: str,+ headers: dict[str, str] | None = None,+ scope: str | None = None,+ priority: Priority = Priority.CRITICAL,+ endpoint: str | None = None,+ **kwargs: Any,+ ) -> aiohttp.ClientResponse:+ import aiohttp # noqa: PLC0415++ await self._gate(scope, source, priority, url)++ request_headers = {**self._standard_headers(), **(headers or {})}+ try:+ response = await session.request(method, url, headers=request_headers, **kwargs)+ except (aiohttp.ClientError, TimeoutError):+ # aiohttp raises a bare TimeoutError when ClientTimeout.total expires; only the connect+ # phase gets wrapped into a ClientError. Catching just ClientError would drop the most+ # likely outage from the metric.+ # Best-effort telemetry must never mask the real transport error — record and re-raise it.+ self._record_exception(source=source, scope=scope, method=method, url=url, endpoint=endpoint)+ raise++ self._record_response(response, source=source, scope=scope, method=method, endpoint=endpoint)+ return response++ async def _gate(self, scope: str | None, source: str, priority: Priority, url: str) -> None:+ # Identity-blind callers have no shared budget to draw on — record volume only, never gate.+ # An empty scope is no identity either: gating on it would key a phantom budget/metric series.+ if not scope:+ return+ granted = await self._consume(scope, priority, source, url)+ _raise_if_denied(granted, priority, lambda: self._budget_exhausted_error(scope))++ # --- domain hooks -------------------------------------------------------------------------------++ @abstractmethod+ def _standard_headers(self) -> dict[str, str]:+ """Default headers merged under the caller's (the caller's win) — e.g. Content-Type."""++ @abstractmethod+ async def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:+ """Draw ``1`` from the domain's shared budget for ``scope`` at ``priority``; True if granted."""++ @abstractmethod+ def _record_response(+ self, response: aiohttp.ClientResponse, *, source: str, scope: str | None, method: str, endpoint: str | None+ ) -> None:+ """Record a returned response (volume + the API's rate-limit headers) via the domain's recorder."""++ @abstractmethod+ def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:+ """Record a request that raised before returning a response (timeout, connection error)."""++ @abstractmethod+ def _budget_exhausted_error(self, scope: str) -> EgressBudgetExhausted:+ """The domain-specific exception raised when a sheddable call is denied (a subclass of+ :class:`EgressBudgetExhausted`)."""diff --git a/posthog/egress/vapi/observability.py b/posthog/egress/vapi/observability.pyindex 9a5d89924ebf..fb0ca86ec4d6 100644--- a/posthog/egress/vapi/observability.py+++ b/posthog/egress/vapi/observability.py@@ -1,5 +1,7 @@"""Vapi outbound API request telemetry."""+from collections.abc import Mapping+import requestsfrom prometheus_client import Counter, Gauge@@ -8,6 +10,7 @@ from posthog.egress.observability.observability import (EgressObservability,RateLimitSnapshot,register_egress_observability,+ unpack_requests_response,)from posthog.egress.vapi.limiter import VAPI_DOMAIN@@ -35,7 +38,7 @@ _metrics = EgressMetrics()-def _parse_vapi_rate_limit(_response: requests.Response) -> RateLimitSnapshot:+def _parse_vapi_rate_limit(_headers: Mapping[str, str] | None, _url: str | None) -> RateLimitSnapshot:return RateLimitSnapshot(resource="api")@@ -51,7 +54,17 @@ def record_vapi_api_response(method: str,endpoint: str,) -> None:- vapi_egress.record_response(response, source=source, scope=scope, method=method, endpoint=endpoint)+ primitives = unpack_requests_response(response)+ vapi_egress.record_response(+ primitives.status_code,+ primitives.headers,+ source=source,+ scope=scope,+ method=method,+ endpoint=endpoint,+ request_method=primitives.request_method,+ request_url=primitives.request_url,+ )def record_vapi_api_exception(*, source: str, scope: str, method: str, endpoint: str, url: str) -> None:diff --git a/products/growth/backend/enrichment/providers.py b/products/growth/backend/enrichment/providers.pyindex 960d65ef673c..2d87b92a676b 100644--- a/products/growth/backend/enrichment/providers.py+++ b/products/growth/backend/enrichment/providers.py@@ -74,7 +74,7 @@ class HarmonicEnrichmentProvider(EnrichmentProvider):name = "harmonic"async def enrich_by_domain(self, domain: str) -> ProviderLookup:- async with AsyncHarmonicClient() as client:+ async with AsyncHarmonicClient(source="growth_enrichment_provider") as client:lookup = await client.enrich_company_by_domain_strict(domain)company = lookup.companyfields = transform_harmonic_company(company)@@ -83,7 +83,7 @@ class HarmonicEnrichmentProvider(EnrichmentProvider):return ProviderLookup(fields=fields, raw_payload=company, enrichment_urn=lookup.enrichment_urn)async def enrichment_status_for(self, urn: str) -> Optional[str]:- async with AsyncHarmonicClient() as client:+ 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