: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
feat(cdp): route logo.dev calls through egress and cache icon responses (#70158)
Chris Volzer0fc73372d2b7
diff --git a/posthog/cdp/services/icons.py b/posthog/cdp/services/icons.pyindex 634938e7f85a..471e7527679b 100644--- a/posthog/cdp/services/icons.py+++ b/posthog/cdp/services/icons.py@@ -1,19 +1,64 @@+import refrom base64 import b64encodefrom django.conf import settingsfrom django.core.cache import cachefrom django.http import HttpResponse-import requestsfrom rest_framework.exceptions import NotFound+from posthog.egress.limiter.outbound import get_outbound_rate_limiter+from posthog.egress.limiter.policies import Priority, RatePolicy, register_policy+from posthog.egress.logodev.transport import LogoDevEgressBudgetExhausted, logodev_request++ICON_CACHE_SECONDS = 60 * 60 * 24++# Per-team fairness gate in front of the instance-wide logo.dev account budget. Icon domains and+# search queries are caller-supplied and only definitive misses are cached, so without a per-team+# ceiling one team requesting endless unique domains could drain the shared account budget and+# blank icons for every other team on the instance. The ceilings leave a cold catalog render (tens+# of uncached icons) untouched while sitting well below the account budget, so a single team can't+# sustain instance-wide exhaustion. This is a consumer-side concern: the logodev egress limiter+# stays a pure account-budget mirror of what logo.dev actually meters.+_TEAM_BUDGET_DOMAIN = "cdp_icons"+_DEFAULT_TEAM_PER_MINUTE_BUDGET = 120+_DEFAULT_TEAM_HOURLY_BUDGET = 1_000+++# Registered as a provider so the budgets are read at acquire time — a settings override applies+# without a process restart, matching the egress domains.+def _team_budget_policy(key: str) -> RatePolicy:+ per_minute = int(getattr(settings, "CDP_ICONS_TEAM_PER_MINUTE_BUDGET", _DEFAULT_TEAM_PER_MINUTE_BUDGET))+ hourly = int(getattr(settings, "CDP_ICONS_TEAM_HOURLY_BUDGET", _DEFAULT_TEAM_HOURLY_BUDGET))+ return RatePolicy(limits=((per_minute, 60.0), (hourly, 3600.0)), in_memory_divider=4)+++register_policy(_TEAM_BUDGET_DOMAIN, _team_budget_policy)+++def _consume_team_icon_budget(team_id: int) -> bool:+ """Reserve one upstream logo.dev call against ``team_id``'s icon budget. Returns False when the+ team's budget is exhausted — degrade for that team only, before touching the account budget."""+ return get_outbound_rate_limiter().consume_sync(+ f"{_TEAM_BUDGET_DOMAIN}:team:{team_id}", priority=Priority.NORMAL, source="cdp_icons"+ )+++# Dot-separated LDH labels, lowercase — the only shape logo.dev serves. Rejecting everything else+# keeps caller-supplied ids from reaching logo.dev or minting cache entries.+_DOMAIN_RE = re.compile(r"^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")+_MAX_DOMAIN_LENGTH = 253++_ALLOWED_THEMES: frozenset[str | None] = frozenset({None, "dark", "light"})+_ALLOWED_FALLBACKS: frozenset[str] = frozenset({"monogram", "404"})+class CDPIconsService:@property- def supported(self):+ def supported(self) -> bool:return bool(settings.LOGO_DEV_TOKEN)- def list_icons(self, query: str, icon_url_base: str):+ def list_icons(self, query: str, icon_url_base: str, *, team_id: int) -> list[dict[str, str]]:if not self.supported:return []@@ -21,15 +66,22 @@ class CDPIconsService:data = cache.get(cache_key)if data is None:- res = requests.get(- f"https://search.logo.dev/api/icons",- params={- "token": settings.LOGO_DEV_TOKEN,- "query": query,- },- timeout=10,- )- data = res.json() or []+ # Queries are free-text, so cached entries don't bound upstream volume — gate uncached+ # searches on the caller's team budget before they reach the shared account budget.+ if not _consume_team_icon_budget(team_id):+ return []+ try:+ # NORMAL: a typeahead search degrades to no results when the shared budget is tight.+ res = logodev_request(+ "GET",+ "https://search.logo.dev/api/icons",+ source="cdp_icons",+ priority=Priority.NORMAL,+ params={"token": settings.LOGO_DEV_TOKEN, "query": query},+ timeout=10,+ )+ except LogoDevEgressBudgetExhausted:+ return []data = [{@@ -40,20 +92,82 @@ class CDPIconsService:for item in res.json() or []]- cache.set(cache_key, data, 60 * 60 * 24)+ cache.set(cache_key, data, ICON_CACHE_SECONDS)return data- def get_icon_http_response(self, id: str):+ def get_icon_http_response(+ self, id: str, theme: str | None = None, fallback: str = "monogram", *, team_id: int+ ) -> HttpResponse:if not self.supported:raise NotFound()+ if theme not in _ALLOWED_THEMES:+ raise ValueError(f"Unsupported logo.dev theme: {theme!r}")+ if fallback not in _ALLOWED_FALLBACKS:+ raise ValueError(f"Unsupported logo.dev fallback mode: {fallback!r}")++ # `id` is caller-supplied (a query param on the icon endpoint) — anything not domain-shaped+ # must never reach logo.dev nor mint a 24h entry in the shared cache. Domains are+ # case-insensitive, so lowercase first or each case variant would cache separately.+ domain = id.lower()+ if len(domain) > _MAX_DOMAIN_LENGTH or not _DOMAIN_RE.match(domain):+ raise NotFound()++ # Only the *fact* of a definitive miss is ever cached. Logo bytes must not be stored on our+ # infrastructure — logo.dev gates that behind a data-caching license our plan doesn't+ # include — so byte-level dedup is delegated to browser caching via Cache-Control below.+ # Every parameter that changes logo.dev's answer is part of the key; the validated charset+ # ([a-z0-9.-]) is cache-key-safe raw.+ miss_cache_key = f"@cdp/icon_miss/1/{domain}/{theme or ''}/{fallback}"+ if cache.get(miss_cache_key):+ raise NotFound()++ # Unique domains bypass the miss cache by construction, so gate the uncached fetch on the+ # caller's team budget. Transient and uncached, like account-budget exhaustion below.+ if not _consume_team_icon_budget(team_id):+ raise NotFound()- res = requests.get(- f"https://img.logo.dev/{id}",- params={- "token": settings.LOGO_DEV_TOKEN,- },- timeout=10,- )+ params = {+ "token": settings.LOGO_DEV_TOKEN,+ # PNG keeps the logo's transparency — the jpg default flattens it onto a white tile.+ "format": "png",+ "retina": "true",+ "fallback": fallback,+ }+ if theme:+ params["theme"] = theme+ try:+ # NORMAL, not CRITICAL: `id` is user-controlled — an exhausted budget must actually+ # stop upstream fetches rather than being advisory, so this lane is sheddable too.+ res = logodev_request(+ "GET",+ f"https://img.logo.dev/{domain}",+ source="cdp_icons",+ priority=Priority.NORMAL,+ params=params,+ timeout=10,+ )+ except LogoDevEgressBudgetExhausted:+ # Transient and uncached — the next render retries once the budget window rolls over.+ raise NotFound() from None+ if res.status_code == 404 and fallback == "404":+ # A definitive "no logo for this domain" — cache the miss so rendering an unknown+ # domain doesn't re-proxy to logo.dev for a day. Other upstream errors are treated+ # as transient and stay uncached.+ cache.set(miss_cache_key, True, ICON_CACHE_SECONDS)+ raise NotFound()+ if res.status_code != 200:+ raise NotFound()+ content_type = res.headers.get("Content-Type", "image/png")+ if not content_type.startswith("image/"):+ # A 200 that isn't an image (upstream anomaly, error page) must not be proxied from+ # our origin.+ raise NotFound()- return HttpResponse(res.content, content_type=res.headers["Content-Type"])+ response = HttpResponse(res.content, content_type=content_type)+ # Public brand assets — browser caching is the only dedup layer, so honor logo.dev's own+ # caching directive when present (their TTL tuning propagates) and match it otherwise.+ response["Cache-Control"] = res.headers.get("Cache-Control", f"public, max-age={ICON_CACHE_SECONDS}")+ # The body is upstream-controlled — never let a browser sniff it into something executable.+ response["X-Content-Type-Options"] = "nosniff"+ return responsediff --git a/posthog/cdp/test/test_icons.py b/posthog/cdp/test/test_icons.pynew file mode 100644index 000000000000..906b7c065f33--- /dev/null+++ b/posthog/cdp/test/test_icons.py@@ -0,0 +1,275 @@+import time+from itertools import count++from unittest.mock import patch++from django.core.cache import cache+from django.test import SimpleTestCase, override_settings++import requests+from parameterized import parameterized+from requests.structures import CaseInsensitiveDict+from rest_framework.exceptions import NotFound++from posthog.cdp.services.icons import CDPIconsService+from posthog.egress.limiter.outbound import get_outbound_rate_limiter++# Fresh team id per test (and per run) so consuming the real per-team budget never accumulates+# into a denial across tests or repeated local runs against a persistent Redis.+_TEAM_IDS = count(time.time_ns() % 1_000_000_000)+++def _response(+ status: int = 200,+ content: bytes = b"",+ content_type: str = "image/png",+ cache_control: str | None = None,+) -> requests.Response:+ response = requests.models.Response()+ response.status_code = status+ response._content = content+ response.headers = CaseInsensitiveDict({"Content-Type": content_type})+ if cache_control:+ response.headers["Cache-Control"] = cache_control+ prepared = requests.models.PreparedRequest()+ prepared.method = "GET"+ prepared.url = "https://img.logo.dev/linear.app"+ response.request = prepared+ return response+++@override_settings(LOGO_DEV_TOKEN="test-token")+class TestCDPIconsService(SimpleTestCase):+ def setUp(self) -> None:+ super().setUp()+ cache.clear()+ self.service = CDPIconsService()+ self.team_id = next(_TEAM_IDS)++ def test_icon_bytes_are_never_stored_and_browser_caching_is_directed(self) -> None:+ # Storing logo bytes server-side needs a logo.dev data-caching license our plan lacks —+ # every render must re-fetch upstream, with dedup delegated to the browser: logo.dev's own+ # Cache-Control passed through when present, our 24h directive otherwise.+ with (+ patch("posthog.egress.logodev.transport.consume_logodev_sync", return_value=True),+ patch(+ "requests.request",+ side_effect=[+ _response(content=b"png-bytes", cache_control="max-age=86400, stale-while-revalidate=600"),+ _response(content=b"png-bytes"),+ ],+ ) as upstream,+ ):+ first = self.service.get_icon_http_response("linear.app", team_id=self.team_id)+ second = self.service.get_icon_http_response("linear.app", team_id=self.team_id)++ assert upstream.call_count == 2+ assert first.content == b"png-bytes"+ assert first["Cache-Control"] == "max-age=86400, stale-while-revalidate=600"+ assert second["Cache-Control"] == "public, max-age=86400"+ assert first["X-Content-Type-Options"] == "nosniff"++ @parameterized.expand(+ [+ ("server_error", 500, "image/png"),+ ("non_image_200", 200, "text/html"),+ ]+ )+ def test_bad_upstream_response_raises_not_found_and_is_not_cached(+ self, _name: str, status: int, content_type: str+ ) -> None:+ # A logo.dev error body — or a 200 that isn't an image — must not be proxied through from+ # our origin, nor mint a 24h miss entry for a transient failure.+ with (+ patch("posthog.egress.logodev.transport.consume_logodev_sync", return_value=True),+ patch(+ "requests.request", return_value=_response(status=status, content=b"boom", content_type=content_type)+ ),+ ):+ with self.assertRaises(NotFound):+ self.service.get_icon_http_response("linear.app", team_id=self.team_id)++ with (+ patch("posthog.egress.logodev.transport.consume_logodev_sync", return_value=True),+ patch("requests.request", return_value=_response(content=b"png-bytes")),+ ):+ recovered = self.service.get_icon_http_response("linear.app", team_id=self.team_id)++ assert recovered.content == b"png-bytes"++ @parameterized.expand(+ [+ ("free_text", "not a domain!"),+ ("no_tld", "linear"),+ ("path_traversal", "../../etc/passwd"),+ ("query_injection", "linear.app?fallback=monogram"),+ ("extra_path_segment", "linear.app/evil"),+ ("overlong", "a" * 250 + ".app"),+ ]+ )+ def test_non_domain_id_is_rejected_without_upstream_call(self, _name: str, icon_id: str) -> None:+ # `id` is a caller-supplied query param — anything not domain-shaped must never reach+ # logo.dev nor mint a 24h entry in the shared cache.+ with (+ patch("posthog.egress.logodev.transport.consume_logodev_sync", return_value=True),+ patch("requests.request") as upstream,+ ):+ with self.assertRaises(NotFound):+ self.service.get_icon_http_response(icon_id, team_id=self.team_id)++ upstream.assert_not_called()++ def test_id_case_variants_share_one_cached_miss(self) -> None:+ # Domains are case-insensitive — without normalization each case variant would mint its+ # own miss entry and upstream fetch.+ with (+ patch("posthog.egress.logodev.transport.consume_logodev_sync", return_value=True),+ patch("requests.request", return_value=_response(status=404)) as upstream,+ ):+ for icon_id in ("Unknown.Example", "unknown.example"):+ with self.assertRaises(NotFound):+ self.service.get_icon_http_response(icon_id, fallback="404", team_id=self.team_id)++ assert upstream.call_count == 1++ @parameterized.expand([("theme", {"theme": "sepia"}), ("fallback", {"fallback": "icon"})])+ def test_unsupported_response_shaping_params_are_rejected(self, _name: str, kwargs: dict[str, str]) -> None:+ # theme/fallback become user-suppliable via the icon endpoint later in this stack — an+ # unvalidated value would partition the miss cache with unbounded keys.+ with (+ patch("posthog.egress.logodev.transport.consume_logodev_sync", return_value=True),+ patch("requests.request", return_value=_response()),+ ):+ with self.assertRaises(ValueError):+ self.service.get_icon_http_response("linear.app", team_id=self.team_id, **kwargs)++ def test_response_shaping_params_are_forwarded_upstream(self) -> None:+ # format/retina/theme/fallback shape logo.dev's bytes — dropping any of them regresses the+ # rendered icon (white-tiled jpg, wrong theme, monogram where the caller expects a 404).+ with (+ patch("posthog.egress.logodev.transport.consume_logodev_sync", return_value=True),+ patch("requests.request", return_value=_response(content=b"dark-png")) as upstream,+ ):+ response = self.service.get_icon_http_response(+ "linear.app", theme="dark", fallback="404", team_id=self.team_id+ )++ assert response.content == b"dark-png"+ params = upstream.call_args.kwargs["params"]+ assert params["format"] == "png"+ assert params["retina"] == "true"+ assert params["fallback"] == "404"+ assert params["theme"] == "dark"++ @parameterized.expand(+ [+ ("definitive_miss_is_cached", "404", 1),+ ("monogram_mode_stays_transient", "monogram", 2),+ ]+ )+ def test_upstream_404_caching_depends_on_fallback_mode(+ self, _name: str, fallback: str, expected_calls: int+ ) -> None:+ # With fallback="404" a miss is a definitive answer — without negative caching, every+ # render of an unknown domain would re-proxy to logo.dev. Monogram-mode 404s are+ # anomalies and must stay transient (uncached), as before.+ with (+ patch("posthog.egress.logodev.transport.consume_logodev_sync", return_value=True),+ patch("requests.request", return_value=_response(status=404)) as upstream,+ ):+ for _ in range(2):+ with self.assertRaises(NotFound):+ self.service.get_icon_http_response("unknown.example", fallback=fallback, team_id=self.team_id)++ assert upstream.call_count == expected_calls++ def test_cached_miss_is_scoped_to_fallback_mode(self) -> None:+ # A 404-mode miss means "no real logo" — monogram mode can still render a generated+ # monogram for the same domain, so the cached miss must not leak across modes.+ with (+ patch("posthog.egress.logodev.transport.consume_logodev_sync", return_value=True),+ patch(+ "requests.request",+ side_effect=[_response(status=404), _response(content=b"monogram-png")],+ ) as upstream,+ ):+ with self.assertRaises(NotFound):+ self.service.get_icon_http_response("unknown.example", fallback="404", team_id=self.team_id)+ monogram = self.service.get_icon_http_response("unknown.example", fallback="monogram", team_id=self.team_id)++ assert upstream.call_count == 2+ assert monogram.content == b"monogram-png"++ def test_icon_fetch_degrades_to_not_found_when_budget_exhausted(self) -> None:+ # The icon id is user-controlled, so the fetch runs on a sheddable lane: an exhausted+ # budget must stop upstream calls, not proceed as an advisory limit. Nothing is cached,+ # so the next render retries once the budget window rolls over.+ with (+ patch("posthog.egress.logodev.transport.consume_logodev_sync", return_value=False),+ patch("requests.request") as upstream,+ ):+ with self.assertRaises(NotFound):+ self.service.get_icon_http_response("linear.app", team_id=self.team_id)++ upstream.assert_not_called()++ with (+ patch("posthog.egress.logodev.transport.consume_logodev_sync", return_value=True),+ patch("requests.request", return_value=_response(content=b"png-bytes")) as upstream,+ ):+ recovered = self.service.get_icon_http_response("linear.app", team_id=self.team_id)++ assert upstream.call_count == 1+ assert recovered.content == b"png-bytes"++ def test_search_degrades_to_empty_when_budget_exhausted(self) -> None:+ # Icon search is sheddable (NORMAL lane) — when the shared budget is spent it must return no+ # results, not surface a 500 to the icon picker.+ with (+ patch("posthog.egress.logodev.transport.consume_logodev_sync", return_value=False),+ patch("requests.request") as upstream,+ ):+ assert self.service.list_icons("linear", icon_url_base="/base?id=", team_id=self.team_id) == []++ upstream.assert_not_called()++ def test_icon_fetch_degrades_to_not_found_when_team_budget_exhausted(self) -> None:+ # The account budget is instance-wide, so the per-team gate is what stops one team's+ # arbitrary-domain requests from blanking icons for every other team. Denial must be+ # charged to the calling team's own key, stay uncached, and never reach upstream.+ with (+ patch("posthog.cdp.services.icons.get_outbound_rate_limiter") as limiter,+ patch("requests.request") as upstream,+ ):+ limiter.return_value.consume_sync.return_value = False+ with self.assertRaises(NotFound):+ self.service.get_icon_http_response("linear.app", team_id=self.team_id)++ upstream.assert_not_called()+ assert limiter.return_value.consume_sync.call_args.args == (f"cdp_icons:team:{self.team_id}",)++ with (+ patch("posthog.egress.logodev.transport.consume_logodev_sync", return_value=True),+ patch("requests.request", return_value=_response(content=b"png-bytes")) as upstream,+ ):+ recovered = self.service.get_icon_http_response("linear.app", team_id=self.team_id)++ assert upstream.call_count == 1+ assert recovered.content == b"png-bytes"++ def test_search_degrades_to_empty_when_team_budget_exhausted(self) -> None:+ # Search queries are free text — the same per-team gate must cover them or a team could+ # drain the shared account budget through the search path instead.+ with (+ patch("posthog.cdp.services.icons.get_outbound_rate_limiter") as limiter,+ patch("requests.request") as upstream,+ ):+ limiter.return_value.consume_sync.return_value = False+ assert self.service.list_icons("linear", icon_url_base="/base?id=", team_id=self.team_id) == []++ upstream.assert_not_called()++ def test_team_budget_policy_is_registered(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 get_outbound_rate_limiter().consume_sync(f"cdp_icons:team:{self.team_id}", source="test") is Truediff --git a/posthog/egress/README.md b/posthog/egress/README.mdindex 9a8bba179950..4adc8d24fb1f 100644--- a/posthog/egress/README.md+++ b/posthog/egress/README.md@@ -1,7 +1,7 @@# Outbound egress: rate limiting, observability, transportGeneral-purpose controls for the calls PostHog makes _out_ to third-party APIs.-GitHub is the first consumer, but the package is built for more.+GitHub was the first consumer and logo.dev (`logodev/`) is the second, but the package is built for more.A new outbound integration that needs rate-limiting or egress telemetry belongs here as a `<domain>/` incarnation (see [Adding a new egress domain](#adding-a-new-egress-domain)), never hand-rolled around `requests`.Three lanes, one per subpackage:@@ -12,7 +12,7 @@ Three lanes, one per subpackage:This is _outbound_ egress — what PostHog sends.It is unrelated to `posthog.rate_limit`, which throttles _inbound_ DRF requests from clients.-All three lanes are **domain-generic** and domain-free; each third-party API is an incarnation under its own subpackage (`github/`), supplying a budget policy, a metric set + parser, and a transport subclass.+All three lanes are **domain-generic** and domain-free; each third-party API is an incarnation under its own subpackage (`github/`, `logodev/`), supplying a budget policy, a metric set + parser, and a transport subclass.Adding a new outbound API is another `<domain>/` folder, not a change to the mechanisms.## Rate limiting@@ -48,6 +48,11 @@ GitHub meters its REST resources on **separate per-installation counters**, so iThe two search budgets are static because GitHub's search rate limits are fixed regardless of the account's plan tier, so there is no tier to observe (unlike core).Budgets stay deliberately under the real ceiling so reactive backoff absorbs drift (clock skew, multi-process races, untracked PAT traffic on the same account).+logo.dev (`logodev/`) meters per account token, and each instance holds exactly one (`LOGO_DEV_TOKEN`), so a single `logodev` domain carries one instance-wide budget under a constant scope.+logo.dev publishes no rate-limit numbers, so the budgets are static operator ceilings read from settings at acquire time: `LOGODEV_EGRESS_PER_MINUTE_BUDGET` (default 300) smooths bursts and `LOGODEV_EGRESS_HOURLY_BUDGET` (default 5,000) caps total spend.+Every logo.dev call runs on a sheddable lane — the icon id is user-controlled, so nothing in this domain runs `CRITICAL`.+Icon bytes are never stored server-side (logo.dev licenses that separately), so steady-state traffic is deduped only by browser caching (`posthog/cdp/services/icons.py` sets `Cache-Control`) and tracks unique (user, icon) first views per day — raise the settings if that outgrows the defaults.+### Priority lanesPriority (`CRITICAL` / `NORMAL` / `BATCH`) controls how sheddable a call is when the budget gets tight.diff --git a/posthog/egress/logodev/__init__.py b/posthog/egress/logodev/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/egress/logodev/limiter.py b/posthog/egress/logodev/limiter.pynew file mode 100644index 000000000000..70f6e7e44422--- /dev/null+++ b/posthog/egress/logodev/limiter.py@@ -0,0 +1,59 @@+"""logo.dev egress budget.++logo.dev meters usage per account token, and each PostHog instance holds exactly one+(``settings.LOGO_DEV_TOKEN``), so the whole instance draws from a single shared budget under a+constant scope. logo.dev publishes no hard rate-limit numbers, so the defaults are deliberately+modest operator ceilings. Icon bytes are never stored server-side (logo.dev gates that behind a+data-caching license), so upstream volume is deduped only per user, by the browser caching that+:mod:`posthog.cdp.services.icons` directs — steady-state traffic tracks unique (user, icon) first+views per day. Raise the settings below if that outgrows the defaults.++Importing this module registers the policy as a side effect — import it (directly or via+``consume_logodev_sync``) before using a ``logodev:...`` limiter 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++LOGODEV_DOMAIN = "logodev"++# One account per instance — the constant id for the instance-wide shared budget.+_ACCOUNT_SCOPE_ID = "default"++# Same reserved-floor ladder as the other egress domains: BATCH is denied first as the budget+# fills, then NORMAL. All icon traffic runs NORMAL — the icon id is user-controlled, so nothing in+# this domain should run CRITICAL (a never-shed lane would make the budget advisory).+_RESERVE: dict[Priority, float] = {Priority.BATCH: 0.30, Priority.NORMAL: 0.10}++# Operator ceilings, not observed provider limits (logo.dev exposes none to observe). The per-minute+# rate smooths bursts (a catalog page fanning out cache misses), the hourly rate caps total spend.+_DEFAULT_PER_MINUTE_BUDGET = 300+_DEFAULT_HOURLY_BUDGET = 5_000+++# Registered as a provider so the budgets are read at acquire time — a settings override applies+# without a process restart, matching the other egress domains.+def _logodev_policy(key: str) -> RatePolicy:+ per_minute = int(getattr(settings, "LOGODEV_EGRESS_PER_MINUTE_BUDGET", _DEFAULT_PER_MINUTE_BUDGET))+ hourly = int(getattr(settings, "LOGODEV_EGRESS_HOURLY_BUDGET", _DEFAULT_HOURLY_BUDGET))+ return RatePolicy(+ limits=((per_minute, 60.0), (hourly, 3600.0)),+ in_memory_divider=4,+ reserve=_RESERVE,+ )+++register_policy(LOGODEV_DOMAIN, _logodev_policy)+++def logodev_account_key() -> str:+ """Limiter key for the instance's single logo.dev account — the unit logo.dev meters."""+ return f"{LOGODEV_DOMAIN}:account:{_ACCOUNT_SCOPE_ID}"+++def consume_logodev_sync(n: int = 1, *, priority: Priority = Priority.NORMAL, source: str = "unknown") -> bool:+ """Reserve ``n`` requests against the instance's logo.dev budget. 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(logodev_account_key(), n, priority=priority, source=source)diff --git a/posthog/egress/logodev/observability.py b/posthog/egress/logodev/observability.pynew file mode 100644index 000000000000..d9bc68c1f9de--- /dev/null+++ b/posthog/egress/logodev/observability.py@@ -0,0 +1,91 @@+"""logo.dev egress telemetry.++Every logo.dev call funnels through these recorders so request volume lands on one metric set+whichever subsystem made the call (CDP icon picker, MCP store icons, ...), attributed by the+``source`` label. logo.dev reports no rate-limit response headers, so the parser returns an empty+snapshot and the gauges stay unset — they exist because :class:`EgressMetrics` requires the full+instrument set, and they start reporting the moment logo.dev grows the headers.+"""++from urllib.parse import urlparse++import requests+from prometheus_client import Counter, Gauge++from posthog.egress.observability.observability import (+ EgressMetrics,+ EgressObservability,+ RateLimitSnapshot,+ register_egress_observability,+)++LOGODEV_DOMAIN = "logodev"++_metrics = EgressMetrics(+ request_counter=Counter(+ "logodev_api_requests",+ "Number of logo.dev API requests made through the logo.dev egress client.",+ labelnames=["account", "method", "endpoint", "status_code", "source"],+ ),+ remaining_gauge=Gauge(+ "logodev_api_rate_limit_remaining",+ "Most recently observed logo.dev rate limit remaining count (unset: logo.dev reports no rate-limit headers).",+ labelnames=["account", "resource"],+ ),+ limit_gauge=Gauge(+ "logodev_api_rate_limit_limit",+ "Most recently observed logo.dev rate limit (unset: logo.dev reports no rate-limit headers).",+ labelnames=["account", "resource"],+ ),+ reset_gauge=Gauge(+ "logodev_api_rate_limit_reset_timestamp_seconds",+ "Most recently observed logo.dev rate limit reset timestamp (unset: logo.dev reports no rate-limit headers).",+ labelnames=["account", "resource"],+ ),+)+++def _parse_logodev_rate_limit(response: requests.Response) -> RateLimitSnapshot:+ return RateLimitSnapshot()+++def _normalize_logodev_endpoint(url: str | None) -> str:+ """Collapse a logo.dev URL to a low-cardinality endpoint label. ``img.logo.dev/{brand-domain}``+ would otherwise mint one label per brand, so the brand path is templated to ``/img/{domain}``;+ the search API's fixed path is kept verbatim."""+ if not url:+ return "unknown"+ parsed = urlparse(url)+ if parsed.netloc == "img.logo.dev":+ return "/img/{domain}"+ path = parsed.path.rstrip("/")+ return path or "/"+++logodev_egress = EgressObservability(+ LOGODEV_DOMAIN, _metrics, _parse_logodev_rate_limit, endpoint_normalizer=_normalize_logodev_endpoint+)+register_egress_observability(logodev_egress)+++def record_logodev_api_response(+ response: requests.Response,+ *,+ source: str,+ method: str | None = None,+ endpoint: str | None = None,+) -> 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)+++def record_logodev_api_exception(+ *,+ source: str,+ method: str,+ endpoint: str | None = None,+ url: str | None = None,+) -> None:+ """Record a request that raised before a response (timeout, connection error)."""+ logodev_egress.record_exception(source=source, scope="default", method=method, endpoint=endpoint, url=url)diff --git a/posthog/egress/logodev/transport.py b/posthog/egress/logodev/transport.pynew file mode 100644index 000000000000..9a9ab96b8a8b--- /dev/null+++ b/posthog/egress/logodev/transport.py@@ -0,0 +1,73 @@+"""logo.dev incarnation of the egress transport.++``logodev_request`` is the one way to call logo.dev from anywhere in the codebase: it gates on the+instance's shared account budget and records telemetry by construction. The caller owns auth —+logo.dev takes the token as a ``token`` query parameter, so pass it via ``params``.+"""++from typing import Any++import requests++from posthog.egress.limiter.policies import Priority+from posthog.egress.logodev.limiter import consume_logodev_sync+from posthog.egress.logodev.observability import record_logodev_api_exception, record_logodev_api_response+from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient++# The whole instance shares one logo.dev account, so every call carries the same scope.+_ACCOUNT_SCOPE = "default"+++class LogoDevEgressBudgetExhausted(EgressBudgetExhausted):+ """A sheddable (BATCH/NORMAL) logo.dev call was shed by our egress limiter before it was sent.+ Callers that can degrade (e.g. an icon search returning no results) catch this and do so."""+++class LogoDevClient(EgressClient):+ """The logo.dev incarnation of :class:`EgressClient`. Stateless — one shared instance serves+ every caller; wire it through :func:`logodev_request`."""++ def _standard_headers(self) -> dict[str, str]:+ return {}++ def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:+ return consume_logodev_sync(priority=priority, source=source)++ def _record_response(+ self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | None+ ) -> None:+ record_logodev_api_response(response, source=source, method=method, endpoint=endpoint)++ def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:+ record_logodev_api_exception(source=source, method=method, url=url, endpoint=endpoint)++ def _budget_exhausted_error(self, scope: str) -> LogoDevEgressBudgetExhausted:+ return LogoDevEgressBudgetExhausted("logo.dev egress budget exhausted; degrading")+++# Stateless — one shared instance for the whole process.+_logodev_client = LogoDevClient()+++def logodev_request(+ method: str,+ url: str,+ *,+ source: str,+ priority: Priority = Priority.CRITICAL,+ endpoint: str | None = None,+ timeout: float | tuple[float, float] | None = None,+ **kwargs: Any,+) -> requests.Response:+ """Make a gated, recorded logo.dev request. ``source`` attributes the call to a subsystem; pass+ the account token via ``params`` (logo.dev's auth is a query parameter, not a header)."""+ return _logodev_client.request(+ method,+ url,+ source=source,+ scope=_ACCOUNT_SCOPE,+ priority=priority,+ endpoint=endpoint,+ timeout=timeout,+ **kwargs,+ )diff --git a/posthog/egress/test/test_logodev.py b/posthog/egress/test/test_logodev.pynew file mode 100644index 000000000000..1df3756e3717--- /dev/null+++ b/posthog/egress/test/test_logodev.py@@ -0,0 +1,27 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.egress.logodev.limiter import consume_logodev_sync, logodev_account_key+from posthog.egress.logodev.observability import _normalize_logodev_endpoint+++class TestLogoDevEgress(SimpleTestCase):+ @parameterized.expand(+ [+ ("img_brand_path", "https://img.logo.dev/linear.app?token=x", "/img/{domain}"),+ ("img_nested_brand_path", "https://img.logo.dev/some.brand.co", "/img/{domain}"),+ ("search_api", "https://search.logo.dev/api/icons?query=linear", "/api/icons"),+ ("no_url", None, "unknown"),+ ]+ )+ def test_endpoint_normalizer_bounds_cardinality(self, _name: str, url: str | None, expected: str) -> None:+ # Every brand domain minting its own endpoint label would blow up Prometheus cardinality —+ # the normalizer collapsing img paths to one label is what this domain's telemetry relies on.+ assert _normalize_logodev_endpoint(url) == expected++ def test_policy_is_registered_for_the_account_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 logodev_account_key() == "logodev:account:default"+ assert consume_logodev_sync(source="test") is Truediff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.pyindex 6eb86db398ee..4699fb2eec2a 100644--- a/products/cdp/backend/api/hog_function.py+++ b/products/cdp/backend/api/hog_function.py@@ -629,7 +629,9 @@ class HogFunctionViewSet(if not query:return Response([])- icons = CDPIconsService().list_icons(query, icon_url_base="/api/projects/@current/hog_functions/icon/?id=")+ icons = CDPIconsService().list_icons(+ query, icon_url_base="/api/projects/@current/hog_functions/icon/?id=", team_id=self.team_id+ )return Response(icons)@@ -641,7 +643,7 @@ class HogFunctionViewSet(icon_service = CDPIconsService()- return icon_service.get_icon_http_response(id)+ return icon_service.get_icon_http_response(id, team_id=self.team_id)@extend_schema(request=HogFunctionInvocationSerializer,