Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(devex): keep shared mechanisms out of egress and ingress domains (#104956)

Julian Bez6f84ccdf20c2
diff --git a/.agents/skills/adding-inbound-webhooks/SKILL.md b/.agents/skills/adding-inbound-webhooks/SKILL.md
index e1bd57960f2d..a26144cb3590 100644
--- a/.agents/skills/adding-inbound-webhooks/SKILL.md
+++ b/.agents/skills/adding-inbound-webhooks/SKILL.md
@@ -59,6 +59,7 @@ Reset the process-cached registry and the dedup cache between tests with `reset_
Create `posthog/ingress/<provider>/` with an `__init__.py` and a `provider.py`.
Copy `github/` for the full shape, or `vapi/` for a small one.
+Copy the layout, not the behavior: a provider package holds only what is specific to its third party. A need that a second provider could share becomes a lane, a scheme option or a `WebhookProvider` attribute, the way `retry_status` and `throttle_class` did. A true one-off stays in the provider with a `# One-off:` comment that says why no other provider needs it.
`provider.py` holds three things:
- `SPECS`, one `ProviderSpec` per app, naming the event types that app is subscribed to. The registry validates consumers against these.
diff --git a/.agents/skills/routing-outbound-api-calls/SKILL.md b/.agents/skills/routing-outbound-api-calls/SKILL.md
index f523482f2f96..f5dd8dd47219 100644
--- a/.agents/skills/routing-outbound-api-calls/SKILL.md
+++ b/.agents/skills/routing-outbound-api-calls/SKILL.md
@@ -65,6 +65,7 @@ Copy the closest reference domain for the file layout:
- **Copy the layout, not the numbers.** Redo the four decisions above for the new API. A copy keeps the reference's settings defaults, lane defaults, and header names.
- **Let the base client record.** The client sets `observability = <domain>_egress`. Do not add `record_<domain>_response` wrappers.
+- **Add a mechanism to the base, never to one domain.** Tracing, request timing, retries and recording go into the base clients in `transport/transport.py`, so every domain gets them. A reference domain is the next domain's template, so a mechanism added there spreads under new names. A true one-off stays in the domain with a `# One-off:` comment that says why, then a `# nosemgrep: shared-mechanisms-stay-out-of-egress-and-ingress-domains` line. See "Shared mechanisms" in the egress README.
- **Keep metric names explicit and stable.** Dashboards and alerts query them by name.
- **Keep `posthog.models` imports out of the domain package.**
- **The limiter never blocks.** The caller catches `<Domain>EgressBudgetExhausted` and backs off, defers, or degrades. A caller that folds exceptions into "not found" must catch it first.
diff --git a/.semgrep/rules/devex/shared-mechanisms-stay-out-of-egress-and-ingress-domains.py b/.semgrep/rules/devex/shared-mechanisms-stay-out-of-egress-and-ingress-domains.py
new file mode 100644
index 000000000000..c1c56edb0526
--- /dev/null
+++ b/.semgrep/rules/devex/shared-mechanisms-stay-out-of-egress-and-ingress-domains.py
@@ -0,0 +1,41 @@
+# Test cases for shared-mechanisms-stay-out-of-egress-and-ingress-domains rule.
+# ruff: noqa: F401, F841
+import requests
+from prometheus_client import Counter, Gauge, Histogram
+
+# ruleid: shared-mechanisms-stay-out-of-egress-and-ingress-domains
+from opentelemetry import trace
+
+from posthog.egress.observability.observability import EgressMetrics, EgressObservability
+
+tracer = trace.get_tracer(__name__)
+
+# ruleid: shared-mechanisms-stay-out-of-egress-and-ingress-domains
+_request_duration = Histogram("vendor_api_request_duration_seconds", "Request duration.", labelnames=["endpoint"])
+
+# ruleid: shared-mechanisms-stay-out-of-egress-and-ingress-domains
+_retries = Counter("vendor_api_retries", "Retries.", labelnames=["endpoint"])
+
+# ok: shared-mechanisms-stay-out-of-egress-and-ingress-domains
+vendor_egress = EgressObservability(
+ EgressMetrics(
+ request_counter=Counter(
+ "vendor_api_requests",
+ "Requests.",
+ labelnames=["scope", "method", "endpoint", "status_code", "source"],
+ ),
+ remaining_gauge=Gauge("vendor_api_rate_limit_remaining", "Remaining.", labelnames=["scope", "resource"]),
+ )
+)
+
+
+def traced_request(url: str) -> requests.Response:
+ # ruleid: shared-mechanisms-stay-out-of-egress-and-ingress-domains
+ with tracer.start_as_current_span("vendor.http.request"):
+ return requests.get(url)
+
+
+# One-off: only this vendor reports a Retry-After.
+# ok: shared-mechanisms-stay-out-of-egress-and-ingress-domains
+# nosemgrep: shared-mechanisms-stay-out-of-egress-and-ingress-domains
+_retry_at = Gauge("vendor_api_retry_at", "Retry-After.", labelnames=["scope"])
diff --git a/.semgrep/rules/devex/shared-mechanisms-stay-out-of-egress-and-ingress-domains.yaml b/.semgrep/rules/devex/shared-mechanisms-stay-out-of-egress-and-ingress-domains.yaml
new file mode 100644
index 000000000000..d0aaf9c3e9a1
--- /dev/null
+++ b/.semgrep/rules/devex/shared-mechanisms-stay-out-of-egress-and-ingress-domains.yaml
@@ -0,0 +1,55 @@
+rules:
+ - id: shared-mechanisms-stay-out-of-egress-and-ingress-domains
+ message: |
+ Tracing, request timing and metrics are shared mechanisms. Build them once in the
+ shared layer, so every domain gets them with no domain code:
+ - egress: the base clients in `posthog/egress/transport/transport.py` and the
+ recorder in `posthog/egress/observability/`
+ - ingress: `posthog/ingress/views.py`, `dispatch/` and `observability/`
+
+ A domain or provider package fills the hooks that layer defines. An egress domain
+ declares its request counter and rate-limit gauges inside `EgressMetrics(...)`, and
+ the base client records them.
+
+ Why: a reference domain such as `posthog/egress/github/` is the layout the next
+ domain copies. A mechanism added to one domain gets copied with its own names into
+ every new domain, and the domains that exist already never get it.
+
+ If only this domain can ever use it, keep it here and mark it on the lines above:
+ # One-off: <why no other domain needs it>
+ # nosemgrep: shared-mechanisms-stay-out-of-egress-and-ingress-domains
+ See "Shared mechanisms" in `posthog/egress/README.md`.
+ languages: [python]
+ severity: ERROR
+ pattern-either:
+ - patterns:
+ - pattern-either:
+ - pattern: import $MODULE
+ - pattern: from $MODULE import $NAME
+ - metavariable-regex:
+ metavariable: $MODULE
+ regex: ^opentelemetry(\..*)?$
+ - pattern: $TRACER.start_as_current_span(...)
+ - pattern: $TRACER.start_span(...)
+ - pattern: prometheus_client.Histogram(...)
+ - pattern: prometheus_client.Summary(...)
+ - patterns:
+ - pattern-either:
+ - pattern: prometheus_client.Counter(...)
+ - pattern: prometheus_client.Gauge(...)
+ - pattern-not-inside: EgressMetrics(...)
+ paths:
+ include:
+ - /posthog/egress/**/*.py
+ - /posthog/ingress/**/*.py
+ exclude:
+ # The shared layer, where these mechanisms belong.
+ - /posthog/egress/*.py
+ - /posthog/egress/transport/**
+ - /posthog/egress/observability/**
+ - /posthog/egress/limiter/**
+ - /posthog/ingress/*.py
+ - /posthog/ingress/dispatch/**
+ - /posthog/ingress/verify/**
+ - /posthog/ingress/observability/**
+ - '**/test/**'
diff --git a/posthog/egress/README.md b/posthog/egress/README.md
index 41d1d0ca262c..18e7b82cb766 100644
--- a/posthog/egress/README.md
+++ b/posthog/egress/README.md
@@ -127,6 +127,7 @@ Endpoint labels are normalized to bound cardinality: numeric ids are templated o
Harmonic also records `harmonic_api_request_duration_seconds` from the start of an HTTP request through response headers, and `harmonic_api_admission_wait_seconds` for waits in the bulk client's pacing loop, including time queued for the pacing lock.
The request duration excludes the local admission wait and response-body parsing.
+Both are one-offs, marked as such in `harmonic/observability.py`, and request duration moves into the base clients once a second domain needs it.
The weekly Salesforce sweep allows 24 company lookups in flight; each outbound request still draws from the shared BATCH budget.
## Transport
@@ -156,6 +157,21 @@ Per-caller attribution is the `source` label's job, not the identity's.
An identity that must not reach a metric label in plain form, such as a token, is hashed first (see `browserless/` and `vapi/`).
A caller with no identity in scope passes no scope: it records the counter only and skips both the limiter and the gauges.
+## Shared mechanisms
+
+A mechanism that more than one domain could use lives in the shared layer, never in a domain.
+The shared layer is the base clients in `transport/transport.py`, the recorder in `observability/` and the limiter in `limiter/`.
+Tracing, request timing, retries and response recording are such mechanisms.
+A domain only fills the hooks the bases define: its identity, its budget, its metric names and its header parser.
+
+A reference domain such as `github/` is the layout that the next domain copies.
+Code added to it gets copied into every later domain under new names, and the domains that exist already never get it.
+Add the mechanism to a base instead, so that every domain gets it with no domain code.
+
+When only one domain can ever use something, keep it in that domain and mark it.
+Put a `# One-off:` comment that says why no other domain needs it, then a `# nosemgrep: shared-mechanisms-stay-out-of-egress-and-ingress-domains` line.
+That semgrep rule fails CI on tracing, on histograms, and on a counter or gauge declared outside `EgressMetrics(...)` in a domain package, so an unmarked one does not land.
+
## Adding a new egress domain
Add a `<domain>/` subpackage and work through this list.
diff --git a/posthog/egress/harmonic/observability.py b/posthog/egress/harmonic/observability.py
index 7f158728588e..7e948b8d1a8d 100644
--- a/posthog/egress/harmonic/observability.py
+++ b/posthog/egress/harmonic/observability.py
@@ -27,12 +27,17 @@ _METRIC_SOURCES = frozenset(
)
_METRIC_ENDPOINTS = frozenset({"/graphql", "/companies/{id}", "/enrichment_status"})
+# One-off: no other domain records request latency. A second domain that needs it moves the timing
+# into the base clients in `transport/transport.py`, which gives every domain the same metric.
+# nosemgrep: shared-mechanisms-stay-out-of-egress-and-ingress-domains
_request_duration = Histogram(
"harmonic_api_request_duration_seconds",
"Time spent waiting for a Harmonic HTTP response, excluding local rate-limit admission waits.",
labelnames=["source", "priority", "endpoint", "outcome"],
buckets=(0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20, 30, 60),
)
+# One-off: the bulk client runs its own pacing loop, and no other domain waits outside the limiter.
+# nosemgrep: shared-mechanisms-stay-out-of-egress-and-ingress-domains
_admission_wait = Histogram(
"harmonic_api_admission_wait_seconds",
"Time a Harmonic caller waits before attempting a rate-limited request.",
diff --git a/posthog/egress/slack/observability.py b/posthog/egress/slack/observability.py
index aca5f831cd4a..555a10a2869d 100644
--- a/posthog/egress/slack/observability.py
+++ b/posthog/egress/slack/observability.py
@@ -22,6 +22,8 @@ slack_egress = EgressObservability(
# Slack returns no remaining-budget headers. Its only budget signal is the Retry-After on a 429,
# which applies to one app and one Web API method, so the resource label carries both.
+# One-off: the SDK retry handler sets it on a 429, outside the header parse `EgressMetrics` runs.
+# nosemgrep: shared-mechanisms-stay-out-of-egress-and-ingress-domains
_retry_at_gauge = Gauge(
"slack_api_rate_limit_reset_timestamp_seconds",
"Slack API retry timestamp after a rate-limited response.",
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index 76e9b08e8b4c..fada242c45bc 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -232,6 +232,12 @@ The same attribute answers a delivery whose consumers did not accept it, under o
## Adding a provider
+A provider package holds only what is specific to its third party: header names, how it names event types and delivery ids, how its body parses, and the status codes its protocol fixes.
+A need that a second provider could share becomes shared code: a lane in `views.py`, part of `dispatch/`, a scheme or scheme option in `verify/`, or an attribute on `WebhookProvider`.
+`throttle_class`, `retry_status` and the HMAC digest option each started as one provider's need and became shared that way.
+A true one-off stays in the provider, marked with a `# One-off:` comment that says why no other provider needs it.
+Tracing and metrics in a provider package fail CI unless marked, see "Shared mechanisms" in [the egress README](../egress/README.md#shared-mechanisms).
+
Add a `<provider>/` subpackage with a `provider.py` holding three things (see `github/` for the full shape, `vapi/` for a small one):
- `SPECS` — one `ProviderSpec` per app, naming the event types the app is subscribed to. The registry validates consumers against these.
diff --git a/posthog/ingress/mailgun/testing.py b/posthog/ingress/mailgun/testing.py
new file mode 100644
index 000000000000..2828a750ddc9
--- /dev/null
+++ b/posthog/ingress/mailgun/testing.py
@@ -0,0 +1,17 @@
+"""Signing a Mailgun route delivery the way Mailgun does, for tests that post to a Mailgun endpoint."""
+
+import hmac
+import time
+from uuid import uuid4
+
+
+def signed_mailgun_fields(signing_key: str, *, token: str | None = None, age_seconds: int = 0) -> dict[str, str]:
+ """A signature triple over a timestamp `age_seconds` in the past.
+
+ Mailgun mints a new token per delivery, and ingress dedups on it, so the default token is new on
+ every call. Pass a fixed token only for a test about a redelivery or a tampered token.
+ """
+ timestamp = str(int(time.time()) - age_seconds)
+ token = token if token is not None else uuid4().hex
+ signature = hmac.digest(signing_key.encode(), f"{timestamp}{token}".encode(), "sha256").hex()
+ return {"timestamp": timestamp, "token": token, "signature": signature}
diff --git a/posthog/ingress/test/test_mailgun.py b/posthog/ingress/test/test_mailgun.py
index bacc5e0ca03b..287b189dd47b 100644
--- a/posthog/ingress/test/test_mailgun.py
+++ b/posthog/ingress/test/test_mailgun.py
@@ -1,5 +1,3 @@
-import hmac
-import time
from urllib.parse import urlencode
from django.core.files.uploadedfile import SimpleUploadedFile
@@ -8,6 +6,7 @@ from django.test import RequestFactory, SimpleTestCase
from parameterized import parameterized
from posthog.ingress.mailgun.provider import FILES_KEY, MAX_FILES, MailgunProvider, build_mailgun_provider
+from posthog.ingress.mailgun.testing import signed_mailgun_fields
from posthog.ingress.providers import InvalidPayload
from posthog.ingress.verify.schemes import VerificationOutcome
@@ -16,12 +15,6 @@ URL = "/api/conversations/v1/email/inbound"
FORM_CONTENT_TYPE = "application/x-www-form-urlencoded"
-def _signed_fields(*, age_seconds: int = 0, token: str = "delivery-token") -> dict[str, str]:
- timestamp = str(int(time.time()) - age_seconds)
- signature = hmac.digest(SIGNING_KEY.encode(), f"{timestamp}{token}".encode(), "sha256").hex()
- return {"timestamp": timestamp, "token": token, "signature": signature}
-
-
def _provider(app: str = "inbound", *, signing_key: str | None = SIGNING_KEY) -> MailgunProvider:
return build_mailgun_provider(app, signing_key_getter=lambda: signing_key)
@@ -44,13 +37,13 @@ class TestMailgunProvider(SimpleTestCase):
signing_key: str | None,
expected: VerificationOutcome,
) -> None:
- fields = _signed_fields(age_seconds=age_seconds) | overrides
+ fields = signed_mailgun_fields(SIGNING_KEY, age_seconds=age_seconds) | overrides
request = RequestFactory().post(URL, data=urlencode(fields), content_type=FORM_CONTENT_TYPE)
self.assertEqual(_provider(signing_key=signing_key).verify(request).outcome, expected)
def test_a_multipart_delivery_verifies_and_parses_into_the_form_fields_and_its_files(self) -> None:
- fields = _signed_fields()
+ fields = signed_mailgun_fields(SIGNING_KEY)
request = RequestFactory().post(
URL,
data={
@@ -78,7 +71,9 @@ class TestMailgunProvider(SimpleTestCase):
[("inbound", "message_received"), ("outbound", "message_sent"), ("capture", "message_received")]
)
def test_each_app_types_its_delivery_by_the_route_it_serves(self, app: str, event_type: str) -> None:
- request = RequestFactory().post(URL, data=urlencode(_signed_fields()), content_type=FORM_CONTENT_TYPE)
+ request = RequestFactory().post(
+ URL, data=urlencode(signed_mailgun_fields(SIGNING_KEY)), content_type=FORM_CONTENT_TYPE
+ )
provider = _provider(app)
(delivery,) = provider.deliveries(request, provider.parse(request), {})
@@ -98,7 +93,7 @@ class TestMailgunProvider(SimpleTestCase):
f"attachment-{index}": SimpleUploadedFile(f"{index}.txt", b"attached", content_type="text/plain")
for index in range(MAX_FILES + 5)
}
- request = RequestFactory().post(URL, data={**_signed_fields(), **files})
+ request = RequestFactory().post(URL, data={**signed_mailgun_fields(SIGNING_KEY), **files})
payload = _provider().parse(request)
diff --git a/products/conversations/backend/api/tests/mailgun_signing.py b/products/conversations/backend/api/tests/mailgun_signing.py
index afdc38977f77..95142caa7f16 100644
--- a/products/conversations/backend/api/tests/mailgun_signing.py
+++ b/products/conversations/backend/api/tests/mailgun_signing.py
@@ -5,12 +5,8 @@ refuses a timestamp outside a 5 minute window. So a test drives the real route r
stubbing the verifier, and posts a freshly signed form each time.
"""
-import hmac
-import time
-import hashlib
from types import SimpleNamespace
from typing import Any
-from uuid import uuid4
from unittest.mock import patch
@@ -19,6 +15,7 @@ from django.test import Client
from django.utils import timezone
from posthog.ingress.contracts import WebhookDelivery
+from posthog.ingress.mailgun import testing as mailgun_testing
from posthog.ingress.mailgun.provider import FILES_KEY
from products.conversations.backend.services.mailgun_events import SENDER_STATUS_ABSENT, SENDER_STATUS_ABSENT_BODY
@@ -49,19 +46,8 @@ def _instance_setting(name: str) -> str:
def signed_mailgun_fields() -> dict[str, str]:
- """A fresh signature triple, with the token Mailgun mints per delivery.
-
- The token is the delivery id ingress dedups on, so it has to be new for every post: a real
- redelivery reuses it, and no test here is exercising a redelivery.
- """
- timestamp = str(int(time.time()))
- token = uuid4().hex
- signature = hmac.new(
- key=MAILGUN_SIGNING_KEY.encode("utf-8"),
- msg=f"{timestamp}{token}".encode(),
- digestmod=hashlib.sha256,
- ).hexdigest()
- return {"timestamp": timestamp, "token": token, "signature": signature}
+ """A fresh signature triple with a new token, under the key the endpoints verify against."""
+ return mailgun_testing.signed_mailgun_fields(MAILGUN_SIGNING_KEY)
def post_mailgun(client: Client, path: str, data: dict[str, Any]) -> Any: