: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(ingress): answer a retry status when a delivery was not accepted (#101508)
Julian Bezff8379429281
diff --git a/.agents/skills/adding-inbound-webhooks/SKILL.md b/.agents/skills/adding-inbound-webhooks/SKILL.mdindex e53ea63f03de..12dc199c4d13 100644--- a/.agents/skills/adding-inbound-webhooks/SKILL.md+++ b/.agents/skills/adding-inbound-webhooks/SKILL.md@@ -40,7 +40,7 @@ Rules that decide whether this works:- `name` is unique per provider and is part of the dedup cache key. **Treat it as fixed once it ships**: renaming one lets a redelivery run the consumer a second time.- `provider` and `app` must match a `ProviderSpec` some incarnation declares, and `event_types` must be a subset of what that app declares. Anything else raises `RegistryError` when the registry is built, rather than sitting there looking registered and never running.-- `handler` takes one `WebhookDelivery` and returns nothing. Its return value is ignored and it never decides the HTTP status.+- `handler` takes one `WebhookDelivery` and returns nothing. Its return value is ignored and never decides the HTTP status. A handler that raises does cost the request its receipt when the provider sets `retry_status`, which is how a consumer whose durable record is written inside the handler gets the delivery again.- Keep the module cheap to import. The registry imports it on the first delivery through `load_product_modules("webhook_consumers")`, so defer heavy imports into the handler behind `# noqa: PLC0415` with a reason.- The handler runs synchronously inside the request. Enqueue a task for real work, the way stamphog and conversations do.- A handler that reads the database wraps the read in `bounded_statement_timeout(ms, models=...)` from `posthog.ingress.dispatch.database`, passing only the models the read actually uses. Opening an alias is itself unbounded, so naming one the read never touches can stall the delivery on connection setup.@@ -62,6 +62,7 @@ Copy `github/` for the full shape, or `vapi/` for a small one.- `verify(request)` answers a `Verification`: the outcome, plus `facts`, whatever the scheme proved on the way. A scheme that validates a signed token puts its verified claims there and `deliveries` cross-checks the body against them; an HMAC scheme leaves it empty and `deliveries` ignores it.- `parse(request)` decodes the body, and defaults to JSON. Override it for a provider that posts a form, and raise `InvalidPayload` for a body it cannot read. Verification runs first and must, because reading `request.POST` consumes the request stream under ASGI.- `throttle_class` names a DRF throttle from `posthog.rate_limit`, run in front of verification. Set one when the endpoint is public and its verification is expensive, such as a JWT signing-key lookup.+ - `retry_status` is the status answered instead of the receipt when ingress cannot vouch that the delivery was accepted: the forward to the owning region failed, a consumer raised, or the budget skipped a consumer. Set it when the provider redelivers on a non-2xx, and leave it `None` when it does not, because the non-2xx then only loses the delivery. A retry replays the delivery against every consumer on the endpoint, and dedup is what stops the ones that already accepted it from running twice.- A `build_<provider>_provider(...)` function returning it. Secrets and verifiers a product owns are **passed into this builder**, never imported: nothing under `posthog/ingress/` may import a product.Then:@@ -81,7 +82,8 @@ Everything else goes through `build_webhook_view()`.## Non-goals-Ingress stores no delivery log, runs no queue, retry or dead letter, lets no consumer decide the response, and promises no consumer order.+Ingress stores no delivery log, runs no queue, retry or dead letter of its own, lets no consumer decide the response, and promises no consumer order.+It does answer `retry_status` when it cannot vouch that a delivery was accepted, which asks the provider's retry to run rather than adding one here.Each was a real proposal already; ["Non-goals" in the package README](../../../posthog/ingress/README.md#non-goals) records the reason for each one, so read it before proposing any of them again.## Verifydiff --git a/posthog/ingress/AGENTS.md b/posthog/ingress/AGENTS.mdindex 63a42a34bf24..a250650f870d 100644--- a/posthog/ingress/AGENTS.md+++ b/posthog/ingress/AGENTS.md@@ -2,6 +2,6 @@Read the README before adding a provider, changing a scheme, or touching the registry.Read a provider's own `README.md` before changing that provider, and invoke `/adding-inbound-webhooks` before adding or changing a provider.-Three things are easy to re-derive wrong: the response is a transport receipt (a consumer never decides the status), a consumer's `name` is a dedup cache key (renaming one lets a redelivery run twice), and nothing here may import a product — product-owned secrets and verifiers are passed into the provider builder.+Three things are easy to re-derive wrong: the response is a transport receipt (a consumer's return value never decides the status, though a provider that sets `retry_status` is not receipted when the work did not run), a consumer's `name` is a dedup cache key (renaming one lets a redelivery run twice), and nothing here may import a product — product-owned secrets and verifiers are passed into the provider builder.@README.mddiff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex 7f90653c5615..be45d6143075 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -78,9 +78,17 @@ A consumer that wants asynchronous work enqueues its own task and answers immedi**Ingress does not let a consumer decide the response.**The HTTP response is a transport receipt: the verification result, the method, and the payload decide the status, and consumer return values are ignored.-A consumer that fails must not turn a verified delivery into a 500 the provider will replay against every other consumer too.If a provider's protocol needs the response body to say something, the incarnation answers that handshake before dispatch.-The one exception is a failed forward to the owning region, which is a transport failure rather than a consumer outcome — see [Regional forwarding](#regional-forwarding).++What the transport does decide is whether it can vouch that the delivery was taken.+It cannot when the forward to the owning region failed, when a consumer raised, or when the budget skipped a consumer — in each case some of the work never ran.+A provider that redelivers on a non-2xx sets `retry_status` on its incarnation, and the view then answers that status with outcome `retry_requested` instead of the receipt, so the provider sends the delivery again.+A provider that does not redeliver leaves it at `None` and keeps the receipt, because a non-2xx buys it nothing.+That is still the transport deciding, on whether the work ran at all, rather than a consumer choosing an answer: a consumer cannot ask for a retry, and a delivery no consumer is registered for is accepted by construction.++The cost is fan-out: a retry replays the delivery against every consumer on the endpoint, not only the one that failed.+Dedup is what keeps that cheap — a consumer that already accepted the delivery is deduped on the redelivery, and only the one that raised or never started runs again.+A consumer with `dedup=False` runs on every redelivery, so a sibling that keeps failing makes it repeat its work.**Ingress does not promise an order.**Consumers are independent by construction; anything that depends on another consumer's result belongs in one consumer.@@ -124,6 +132,8 @@ A consumer that names a provider app nobody declares, reuses a name already takeA handler takes one `WebhookDelivery` and returns nothing.It runs synchronously inside the request, isolated: raising is logged and captured, and it releases its own dedup mark so the provider's redelivery reaches it again.+On a provider that sets `retry_status` a handler that raises also costs the request its receipt, so the provider redelivers rather than waiting for a sweeper to notice.+That is what a consumer whose durable record is written inside the handler needs: nothing else is holding the delivery.`dedup=False` turns the mark off for one consumer.That is right when the consumer already keys its own recovery on the provider's delivery id, so a redelivery is how work that never finished gets picked up.@@ -134,6 +144,7 @@ Leave it on everywhere else: without an idempotency key of its own, a consumer tEvery request gets one wall-clock budget, `INGRESS_DELIVERY_BUDGET_SECONDS` (default 8).Consumers draw from it in turn, across every delivery the request carries, because a request that batches several events would otherwise hold the connection open for one budget per event.When it is spent, the consumers that have not started are skipped with outcome `budget_exceeded` and a warning that names them, and they are **not** marked in dedup — so the provider's redelivery reaches them.+On a provider that sets `retry_status` a skipped consumer also costs the request its receipt, which is what makes that redelivery happen rather than waiting for the next event.The budget is a backstop, not a scheduler: it cannot interrupt a consumer that is already running.A consumer that touches the database on this path wraps its reads in `bounded_statement_timeout(ms, models=...)`, which installs `SET LOCAL statement_timeout` on each alias those models route to.@@ -166,15 +177,15 @@ A lookup that reads the database must be bounded with `bounded_statement_timeoutA lookup that raises is logged, captured, counted as `failed` and treated as `UNDECIDED`, so one consumer cannot cost the delivery the receipt it earned by signing.A failed forward keeps the receipt by default.-A provider that redelivers on a non-2xx (Slack does, GitHub does not) sets `forward_failure_status` on its incarnation, and the view answers that status with outcome `forward_failed` instead — so the provider sends the delivery again rather than losing it.-That is the transport deciding the response, not a consumer.+A provider that redelivers on a non-2xx (Slack does, GitHub does not) sets `retry_status` on its incarnation, and the view answers that status with outcome `forward_failed` instead — so the provider sends the delivery again rather than losing it.+The same attribute answers a delivery whose consumers did not accept it, under outcome `retry_requested`; see ["Ingress does not let a consumer decide the response"](#non-goals).## Adding a providerAdd 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.-- A `WebhookProvider` subclass — its `scheme()` (from `verify/`), its `deliveries()` (how to read event type, delivery id and context off the request), and any status codes its protocol fixes. The defaults are 403 on a bad signature, 500 when unconfigured, and 202 on success, with a short body naming the reason on the two rejections. An incarnation that answers 404 to withhold the endpoint's existence sets `explains_rejections = False` so the body stays empty as well. Two more hooks are optional: `parse()`, which decodes the body, and `throttle_class`, which caps request volume. See [The lanes one request runs through](#the-lanes-one-request-runs-through).+- A `WebhookProvider` subclass — its `scheme()` (from `verify/`), its `deliveries()` (how to read event type, delivery id and context off the request), and any status codes its protocol fixes. The defaults are 403 on a bad signature, 500 when unconfigured, and 202 on success, with a short body naming the reason on the two rejections. An incarnation that answers 404 to withhold the endpoint's existence sets `explains_rejections = False` so the body stays empty as well. Three more attributes are optional: `parse()`, which decodes the body, `throttle_class`, which caps request volume, and `retry_status`, which a provider that redelivers on a non-2xx sets so an unaccepted delivery is not receipted. See [The lanes one request runs through](#the-lanes-one-request-runs-through).- A `build_<provider>_provider(...)` function returning that provider, which the URLconf hands to `build_webhook_view()`.Add the module to `_INCARNATION_MODULES` in `posthog/ingress/providers.py`, so the registry finds its specs and any core consumers.@@ -211,6 +222,8 @@ Two shapes that already exist and are worth copying rather than re-deriving:Dedup is per `(provider, consumer, delivery_id)` in the Django cache, for 24 hours.The mark is set before the consumer runs and released when it raises, so a failure does not burn the delivery for a day.+Because it is set before the work finishes, it carries a state rather than a bare flag: a claim answers `CLAIMED`, `IN_PROGRESS` or `DONE`, and the consumer settles it to done when it returns.+Only `DONE` counts as accepted, so a delivery that meets a run still in flight is skipped with outcome `in_flight` and is not receipted, and a provider with `retry_status` sends it again once the first run settled rather than trusting a run that can still fail.Keying per consumer rather than per delivery matters: one delivery legitimately fans out to several consumers, and a delivery-wide key would starve every consumer but the first.A cache error fails **open** — dropping deliveries during a cache outage is worse than running a consumer twice, and consumers carry their own idempotency underneath this.@@ -218,8 +231,8 @@ A provider that sends no delivery id skips dedup entirely, and its own README sa## Observability-- **`posthog_ingress_deliveries_total{provider,app,outcome}`** — what the transport answered: `accepted`, `method_not_allowed`, `throttled`, `not_configured`, `invalid_signature`, `invalid_payload`, `forward_failed`. A consumer failure is not here, because a failing consumer still gets a 2xx receipt.-- **`posthog_ingress_consumer_runs_total{provider,consumer,outcome}`** — `succeeded`, `failed`, `deduped`, `budget_exceeded`.+- **`posthog_ingress_deliveries_total{provider,app,outcome}`** — what the transport answered: `accepted`, `method_not_allowed`, `throttled`, `not_configured`, `invalid_signature`, `invalid_payload`, `forward_failed`, `retry_requested`. A consumer failure lands here only on a provider that sets `retry_status`; everywhere else it is counted on the consumer metric alone, because the delivery still gets its receipt.+- **`posthog_ingress_consumer_runs_total{provider,consumer,outcome}`** — `succeeded`, `failed`, `deduped`, `budget_exceeded`, `in_flight`.- **`posthog_ingress_consumer_duration_seconds{provider,consumer}`** — where a delivery's budget actually went.- **`posthog_ingress_ownership_total{provider,consumer,outcome}`** — what a consumer answered when asked which region owns the delivery: `local`, `elsewhere`, `undecided`, `failed`.- **`posthog_ingress_forwards_total{provider,app,outcome}`** — what the owning region answered a forwarded request: `forwarded`, `rejected`, `failed`.diff --git a/posthog/ingress/contracts.py b/posthog/ingress/contracts.pyindex 63795ddc66eb..6a4844928321 100644--- a/posthog/ingress/contracts.py+++ b/posthog/ingress/contracts.py@@ -63,3 +63,15 @@ class ProviderSpec:provider: strapp: strevent_types: frozenset[str]+++@frozen+class DeliveryDispatch:+ """What the dispatcher can vouch for after one delivery's consumers ran.++ A consumer that raised or that the budget skipped is named here; a deduped one is not,+ because the earlier delivery accepted it. A delivery with nothing to run accepts by+ construction, so the names are empty and the transport keeps its receipt.+ """++ unaccepted_consumers: tuple[str, ...] = ()diff --git a/posthog/ingress/dispatch/dedup.py b/posthog/ingress/dispatch/dedup.pyindex 8d3f9175c57e..4e2d2a6ca94b 100644--- a/posthog/ingress/dispatch/dedup.py+++ b/posthog/ingress/dispatch/dedup.py@@ -1,5 +1,7 @@"""Per-delivery, per-consumer dedup marks in the Django cache."""+from enum import Enum+from django.core.cache import cacheimport structlog@@ -8,6 +10,17 @@ logger = structlog.get_logger(__name__)DELIVERY_DEDUP_TTL_SECONDS = 24 * 60 * 60+_IN_PROGRESS = "in_progress"+_DONE = "done"+++class DeliveryClaim(Enum):+ """What the mark says about this consumer's work on this delivery."""++ CLAIMED = "claimed" # nothing held the mark, so this run does the work+ IN_PROGRESS = "in_progress" # another run holds the mark and has not settled yet+ DONE = "done" # an earlier run finished the work+class DeliveryDedup:"""Marks a (provider, consumer, delivery id) so a redelivery skips work already done.@@ -15,26 +28,28 @@ class DeliveryDedup:Keyed per consumer, not per delivery: one delivery legitimately fans out to severalconsumers, so a delivery-wide key would starve every consumer but the first. This sitsalongside each consumer's own idempotency rather than replacing it.++ The mark carries a state because it is written before the handler runs. Without one, a+ redelivery that arrives while the first run is still going reads the mark as work already+ done and earns a receipt, which stops the provider from retrying a delivery the first run+ can still fail."""@staticmethoddef key(*, provider: str, consumer: str, delivery_id: str) -> str:return f"webhook_delivery:{provider}:{consumer}:{delivery_id}"- def claim(self, *, provider: str, consumer: str, delivery_id: str) -> bool:- """True when this process may run the consumer for this delivery.+ def claim(self, *, provider: str, consumer: str, delivery_id: str) -> DeliveryClaim:+ """Take the mark for this consumer, or say what state the holder left it in.Fail-open on a cache error: dropping deliveries during a cache outage is worse thanrunning a consumer twice, and consumers carry their own idempotency."""+ key = self.key(provider=provider, consumer=consumer, delivery_id=delivery_id)try:- return bool(- cache.add(- self.key(provider=provider, consumer=consumer, delivery_id=delivery_id),- True,- timeout=DELIVERY_DEDUP_TTL_SECONDS,- )- )+ if cache.add(key, _IN_PROGRESS, timeout=DELIVERY_DEDUP_TTL_SECONDS):+ return DeliveryClaim.CLAIMED+ held = cache.get(key)except Exception:logger.warning("ingress_dedup_cache_failed",@@ -43,7 +58,32 @@ class DeliveryDedup:delivery_id=delivery_id,exc_info=True,)- return True+ return DeliveryClaim.CLAIMED+ # Anything but the in-progress value counts as done. That covers a mark written before+ # this state existed, and a key that expired between the add and this read. Both mean+ # the delivery keeps its receipt, which is what those marks did before.+ return DeliveryClaim.IN_PROGRESS if held == _IN_PROGRESS else DeliveryClaim.DONE++ def complete(self, *, provider: str, consumer: str, delivery_id: str) -> None:+ """Settle the mark once the consumer returned, so a redelivery reads it as done.++ This resets the remaining time to the full TTL, because the cache does not report what+ is left. A redelivery is deduped for 24 hours from when the work finished.+ """+ try:+ cache.set(+ self.key(provider=provider, consumer=consumer, delivery_id=delivery_id),+ _DONE,+ timeout=DELIVERY_DEDUP_TTL_SECONDS,+ )+ except Exception:+ logger.warning(+ "ingress_dedup_complete_failed",+ provider=provider,+ consumer=consumer,+ delivery_id=delivery_id,+ exc_info=True,+ )def release(self, *, provider: str, consumer: str, delivery_id: str) -> None:"""Drop the mark after a consumer raised, so the provider's redelivery reaches it.diff --git a/posthog/ingress/dispatch/dispatcher.py b/posthog/ingress/dispatch/dispatcher.pyindex 09240b64f1d8..902b975f1f6c 100644--- a/posthog/ingress/dispatch/dispatcher.py+++ b/posthog/ingress/dispatch/dispatcher.py@@ -5,9 +5,9 @@ import timeimport structlogfrom posthog.exceptions_capture import capture_exception-from posthog.ingress.contracts import DeliveryOwnership, WebhookConsumer, WebhookDelivery+from posthog.ingress.contracts import DeliveryDispatch, DeliveryOwnership, WebhookConsumer, WebhookDeliveryfrom posthog.ingress.dispatch.budget import DeliveryBudget, delivery_budget_seconds-from posthog.ingress.dispatch.dedup import DeliveryDedup+from posthog.ingress.dispatch.dedup import DeliveryClaim, DeliveryDedupfrom posthog.ingress.dispatch.registry import ConsumerRegistryfrom posthog.ingress.observability.metrics import observe_consumer_duration, observe_consumer_run, observe_ownership@@ -17,8 +17,9 @@ logger = structlog.get_logger(__name__)class WebhookDispatcher:"""Runs the consumers registered for a delivery, in name order.- Each consumer is isolated: one raising is logged and captured but never stops another,- and never changes the response the provider already earned by signing the request.+ Each consumer is isolated: one raising is logged and captured but never stops another.+ The delivery reports which consumers did not accept it, so the transport can answer a+ retryable status for a provider that redelivers, but no consumer picks that status."""def __init__(@@ -32,13 +33,22 @@ class WebhookDispatcher:self._dedup = dedup if dedup is not None else DeliveryDedup()self._budget_seconds = budget_seconds- def _run(self, consumer: WebhookConsumer, delivery: WebhookDelivery) -> None:+ def _run(self, consumer: WebhookConsumer, delivery: WebhookDelivery) -> bool:+ """Run one consumer, and answer whether it accepted the delivery.++ A consumer deduped against a finished run accepted it then, so it answers True too. One+ deduped against a run that is still going answers False: that run can still fail, and a+ receipt now would stop the provider from ever sending the delivery again.+ """# A consumer that opted out of dedup claims and releases nothing, so a redelivery always# reaches it. Skipping is not an outcome of its own: it simply runs.delivery_id = delivery.delivery_id if consumer.dedup else None- if delivery_id and not self._dedup.claim(- provider=delivery.provider, consumer=consumer.name, delivery_id=delivery_id- ):+ claim = (+ self._dedup.claim(provider=delivery.provider, consumer=consumer.name, delivery_id=delivery_id)+ if delivery_id+ else DeliveryClaim.CLAIMED+ )+ if claim is DeliveryClaim.DONE:logger.info("ingress_consumer_deduped",provider=delivery.provider,@@ -47,7 +57,17 @@ class WebhookDispatcher:delivery_id=delivery.delivery_id,)observe_consumer_run(provider=delivery.provider, consumer=consumer.name, outcome="deduped")- return+ return True+ if claim is DeliveryClaim.IN_PROGRESS:+ logger.info(+ "ingress_consumer_in_flight",+ provider=delivery.provider,+ consumer=consumer.name,+ event_type=delivery.event_type,+ delivery_id=delivery.delivery_id,+ )+ observe_consumer_run(provider=delivery.provider, consumer=consumer.name, outcome="in_flight")+ return Falsestarted = time.monotonic()try:@@ -64,8 +84,12 @@ class WebhookDispatcher:if delivery_id:self._dedup.release(provider=delivery.provider, consumer=consumer.name, delivery_id=delivery_id)observe_consumer_run(provider=delivery.provider, consumer=consumer.name, outcome="failed")+ return Falseelse:+ if delivery_id:+ self._dedup.complete(provider=delivery.provider, consumer=consumer.name, delivery_id=delivery_id)observe_consumer_run(provider=delivery.provider, consumer=consumer.name, outcome="succeeded")+ return Truefinally:observe_consumer_duration(provider=delivery.provider, consumer=consumer.name, seconds=time.monotonic() - started@@ -117,8 +141,8 @@ class WebhookDispatcher:return DeliveryOwnership.LOCAL, ()return DeliveryOwnership.UNDECIDED, ()- def dispatch(self, delivery: WebhookDelivery, *, budget: DeliveryBudget | None = None) -> None:- """Run this delivery's consumers.+ def dispatch(self, delivery: WebhookDelivery, *, budget: DeliveryBudget | None = None) -> DeliveryDispatch:+ """Run this delivery's consumers, and answer which of them did not accept it.The caller passes a budget when one request carries several deliveries, so the requestis bounded rather than each delivery separately.@@ -132,7 +156,7 @@ class WebhookDispatcher:app=delivery.app,event_type=delivery.event_type,)- return+ return DeliveryDispatch()consumers = self._registry.consumers_for(provider=delivery.provider, app=delivery.app, event_type=delivery.event_type@@ -144,7 +168,7 @@ class WebhookDispatcher:app=delivery.app,event_type=delivery.event_type,)- return+ return DeliveryDispatch()logger.info("ingress_delivery_dispatch",@@ -159,10 +183,12 @@ class WebhookDispatcher:budget = DeliveryBudget(self._budget_seconds if self._budget_seconds is not None else delivery_budget_seconds())+ unaccepted: list[str] = []for index, consumer in enumerate(consumers):if budget.is_spent():skipped = consumers[index:]- # No dedup mark for these, so the provider's redelivery reaches them.+ # The mark is claimed inside the run, so a consumer that never started holds none+ # and the provider's redelivery reaches it.logger.warning("ingress_delivery_budget_exceeded",provider=delivery.provider,@@ -173,5 +199,8 @@ class WebhookDispatcher:)for pending in skipped:observe_consumer_run(provider=delivery.provider, consumer=pending.name, outcome="budget_exceeded")- return- self._run(consumer, delivery)+ unaccepted.append(pending.name)+ return DeliveryDispatch(unaccepted_consumers=tuple(unaccepted))+ if not self._run(consumer, delivery):+ unaccepted.append(consumer.name)+ return DeliveryDispatch(unaccepted_consumers=tuple(unaccepted))diff --git a/posthog/ingress/observability/metrics.py b/posthog/ingress/observability/metrics.pyindex 964aded29cdb..d1be84a48072 100644--- a/posthog/ingress/observability/metrics.py+++ b/posthog/ingress/observability/metrics.py@@ -4,9 +4,10 @@ from typing import Literalfrom prometheus_client import Counter, Histogram-# outcome: what the transport answered, never what a consumer decided. `accepted` means the-# delivery was verified, parsed and handed to the dispatcher -- consumer failures are counted-# on their own metric below, because a failing consumer still gets a 2xx receipt.+# outcome: what the transport answered, never what a consumer returned. `accepted` means the+# delivery was verified, parsed and taken by every consumer it was handed to. `retry_requested`+# means it was not, on a provider that redelivers on a non-2xx; on a provider that does not, the+# same delivery is still `accepted` and only the consumer metric below records the failure.DeliveryOutcome = Literal["accepted","method_not_allowed",@@ -15,11 +16,14 @@ DeliveryOutcome = Literal["invalid_signature","invalid_payload","forward_failed",+ "retry_requested",]# budget_exceeded means the delivery ran out of wall clock before this consumer started. It is-# not marked in dedup, so the provider's redelivery reaches it.-ConsumerOutcome = Literal["succeeded", "failed", "deduped", "budget_exceeded"]+# not marked in dedup, so the provider's redelivery reaches it. in_flight means another run of the+# same consumer for the same delivery had not settled yet, so this one did nothing and does not+# count as accepted.+ConsumerOutcome = Literal["succeeded", "failed", "deduped", "budget_exceeded", "in_flight"]# What a consumer answered when asked which region owns the delivery's resource; `failed` is the# lookup raising, which counts as undecided.diff --git a/posthog/ingress/providers.py b/posthog/ingress/providers.pyindex e5716814bf5a..aec76aa9229c 100644--- a/posthog/ingress/providers.py+++ b/posthog/ingress/providers.py@@ -57,11 +57,12 @@ class WebhookProvider(ABC):# whose verification is a local HMAC. It must be a fixed-rate throttle: `build_webhook_view`# refuses a `ScopedRateThrottle`, whose scope lives on a view this one does not have.throttle_class: type[BaseThrottle] | None = None- # Answered instead of the receipt when the forward to the owning region fails, so a provider- # that redelivers on a non-2xx tries again (Slack does, GitHub does not). `None` keeps the- # receipt. This is the one documented exception to "consumers never decide the response": the- # decision is the transport's, not a consumer's.- forward_failure_status: int | None = None+ # Answered instead of the receipt when ingress cannot vouch that the delivery was accepted:+ # the forward to the owning region failed, a consumer raised, or the budget skipped a+ # consumer. A provider that redelivers on a non-2xx then sends the delivery again (Slack+ # does, GitHub does not), and `None` keeps the receipt for one that does not. The decision is+ # the transport's own, taken on whether the work ran at all, never on what a consumer returned.+ retry_status: int | None = None# An incarnation that answers 404 to withhold the endpoint's existence sets this False, so the# body does not name the reason the status code was chosen to hide.explains_rejections: bool = Truediff --git a/posthog/ingress/test/test_dispatcher.py b/posthog/ingress/test/test_dispatcher.pyindex 9cd5c0933844..a93fe4c5d69e 100644--- a/posthog/ingress/test/test_dispatcher.py+++ b/posthog/ingress/test/test_dispatcher.py@@ -1,3 +1,4 @@+from dataclasses import replacefrom datetime import UTC, datetimefrom unittest.mock import Mock, patch@@ -9,7 +10,7 @@ from parameterized import parameterizedfrom posthog.ingress.contracts import DeliveryOwnership, ProviderSpec, WebhookConsumer, WebhookDeliveryfrom posthog.ingress.dispatch.budget import DEFAULT_DELIVERY_BUDGET_SECONDS, DeliveryBudget, delivery_budget_seconds-from posthog.ingress.dispatch.dedup import DeliveryDedup+from posthog.ingress.dispatch.dedup import DeliveryClaim, DeliveryDedupfrom posthog.ingress.dispatch.dispatcher import WebhookDispatcherfrom posthog.ingress.dispatch.registry import ConsumerRegistry@@ -61,6 +62,23 @@ class TestWebhookDispatcher(SimpleTestCase):def setUp(self) -> None:cache.clear()+ @parameterized.expand(+ [+ ("an_app_no_incarnation_declares", "other", "pull_request"),+ ("an_event_type_no_consumer_registered_for", "posthog", "issues"),+ ]+ )+ def test_a_delivery_with_nothing_to_run_names_no_unaccepted_consumer(+ self, _name: str, app: str, event_type: str+ ) -> None:+ dispatcher = _dispatcher([_consumer("alpha", Mock())])++ dispatched = dispatcher.dispatch(replace(_delivery(), app=app, event_type=event_type))++ # Nothing ran, so nothing failed: a provider that redelivers must not be asked to send+ # an event no consumer wants all over again.+ self.assertEqual(dispatched.unaccepted_consumers, ())+def test_runs_consumers_in_name_order(self) -> None:ran: list[str] = []consumers = [@@ -88,16 +106,19 @@ class TestWebhookDispatcher(SimpleTestCase):dispatcher = _dispatcher([_consumer("alpha", failing), _consumer("zulu", succeeding)])with patch("posthog.ingress.dispatch.dispatcher.capture_exception"):- dispatcher.dispatch(_delivery())+ dispatched = dispatcher.dispatch(_delivery())+ self.assertEqual(dispatched.unaccepted_consumers, ("alpha",))self.assertIsNone(cache.get(DeliveryDedup.key(provider="github", consumer="alpha", delivery_id="delivery-1")))self.assertTrue(cache.get(DeliveryDedup.key(provider="github", consumer="zulu", delivery_id="delivery-1")))with patch("posthog.ingress.dispatch.dispatcher.capture_exception"):- dispatcher.dispatch(_delivery())+ dispatched = dispatcher.dispatch(_delivery())self.assertEqual(failing.call_count, 2)self.assertEqual(succeeding.call_count, 1)+ # The deduped one accepted the earlier delivery, so only the failure is named again.+ self.assertEqual(dispatched.unaccepted_consumers, ("alpha",))def test_a_provider_without_a_delivery_id_skips_dedup(self) -> None:handler = Mock()@@ -140,9 +161,10 @@ class TestWebhookDispatcher(SimpleTestCase):patch("time.monotonic", lambda: elapsed["seconds"]),patch("posthog.ingress.dispatch.dispatcher.observe_consumer_run") as observe,):- dispatcher.dispatch(_delivery())+ dispatched = dispatcher.dispatch(_delivery())skipped.assert_not_called()+ self.assertEqual(dispatched.unaccepted_consumers, ("zulu",))self.assertIn({"provider": "github", "consumer": "zulu", "outcome": "budget_exceeded"},[call.kwargs for call in observe.call_args_list],@@ -170,6 +192,34 @@ class TestWebhookDispatcher(SimpleTestCase):second.assert_not_called()+@override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})+class TestDeliveryDedup(SimpleTestCase):+ def setUp(self) -> None:+ cache.clear()+ self.mark = {"provider": "github", "consumer": "alpha", "delivery_id": "delivery-1"}++ def test_the_mark_reports_the_state_its_holder_left_it_in(self) -> None:+ dedup = DeliveryDedup()++ self.assertEqual(dedup.claim(**self.mark), DeliveryClaim.CLAIMED)+ # A redelivery that arrives before the first run settles must not read this as done. That+ # run can still raise, and a receipt now stops the provider sending the delivery again.+ self.assertEqual(dedup.claim(**self.mark), DeliveryClaim.IN_PROGRESS)++ dedup.complete(**self.mark)+ self.assertEqual(dedup.claim(**self.mark), DeliveryClaim.DONE)++ dedup.release(**self.mark)+ self.assertEqual(dedup.claim(**self.mark), DeliveryClaim.CLAIMED)++ def test_a_mark_written_before_the_state_existed_still_dedupes(self) -> None:+ cache.set(DeliveryDedup.key(**self.mark), True)++ # Marks live for 24 hours, so a rollout meets the old ones. Reading one as in flight would+ # cost a receipt for every delivery still holding it.+ self.assertEqual(DeliveryDedup().claim(**self.mark), DeliveryClaim.DONE)++class TestDeliveryOwnership(SimpleTestCase):@parameterized.expand([diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.pyindex f327580891a0..207b546fe35c 100644--- a/posthog/ingress/test/test_views.py+++ b/posthog/ingress/test/test_views.py@@ -17,7 +17,13 @@ from requests import RequestExceptionfrom rest_framework.request import Request as DRFRequestfrom rest_framework.throttling import BaseThrottle, ScopedRateThrottle-from posthog.ingress.contracts import DeliveryOwnership, ProviderSpec, WebhookConsumer, WebhookDelivery+from posthog.ingress.contracts import (+ DeliveryDispatch,+ DeliveryOwnership,+ ProviderSpec,+ WebhookConsumer,+ WebhookDelivery,+)from posthog.ingress.dispatch.dispatcher import WebhookDispatcherfrom posthog.ingress.dispatch.forward import HOST_IDENTIFYING_HEADERS, forward_to_secondary_regionfrom posthog.ingress.dispatch.registry import ConsumerRegistry@@ -49,7 +55,7 @@ RAISES = object()class _RedeliveringGitHubProvider(GitHubProvider):# Stands in for a provider that replays a delivery the endpoint did not accept, which GitHub# itself does not do.- forward_failure_status = 502+ retry_status = 502class _ClaimsGitHubProvider(GitHubProvider):@@ -95,6 +101,7 @@ class TestWebhookView(SimpleTestCase):self.factory = RequestFactory()self.dispatcher = Mock()self.dispatcher.ownership_of.return_value = (DeliveryOwnership.UNDECIDED, ())+ self.dispatcher.dispatch.return_value = DeliveryDispatch()patcher = patch("posthog.ingress.views.get_dispatcher", return_value=self.dispatcher)patcher.start()self.addCleanup(patcher.stop)@@ -364,7 +371,9 @@ def _consumer(@override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})-class TestRegionalForwarding(SimpleTestCase):+class _DispatchingViewTestCase(SimpleTestCase):+ """A view driving the real dispatcher and registry, rather than a mocked one."""+def setUp(self) -> None:cache.clear()self.factory = RequestFactory()@@ -374,11 +383,6 @@ class TestRegionalForwarding(SimpleTestCase):secret.start()self.addCleanup(secret.stop)- forward = patch("posthog.ingress.dispatch.forward.requests.request")- self.requests = forward.start()- self.requests.return_value = Mock(ok=True, status_code=202)- self.addCleanup(forward.stop)-def _view(self, consumers: list[WebhookConsumer], *, provider: WebhookProvider | None = None):registry = ConsumerRegistry(providers=[GITHUB_SPEC, PANDADOC_SPEC], consumers=consumers)dispatcher = patch("posthog.ingress.views.get_dispatcher", return_value=WebhookDispatcher(registry))@@ -399,6 +403,15 @@ class TestRegionalForwarding(SimpleTestCase):},)++class TestRegionalForwarding(_DispatchingViewTestCase):+ def setUp(self) -> None:+ super().setUp()+ forward = patch("posthog.ingress.dispatch.forward.requests.request")+ self.requests = forward.start()+ self.requests.return_value = Mock(ok=True, status_code=202)+ self.addCleanup(forward.stop)+@parameterized.expand([("elsewhere_forwards_once", DeliveryOwnership.ELSEWHERE, 1, 0),@@ -488,6 +501,108 @@ class TestRegionalForwarding(SimpleTestCase):self.assertEqual(self.handler.call_count, 2)+class TestUnacceptedDelivery(_DispatchingViewTestCase):+ @parameterized.expand(+ [+ ("a_provider_that_redelivers_asks_for_one", _RedeliveringGitHubProvider, 502, "retry_requested", ["probe"]),+ ("a_provider_that_does_not_keeps_the_receipt", GitHubProvider, 202, "accepted", None),+ ]+ )+ def test_a_consumer_that_raised_costs_the_receipt_only_where_that_buys_a_redelivery(+ self,+ _name: str,+ provider_class: type[GitHubProvider],+ status: int,+ outcome: str,+ warned_about: list[str] | None,+ ) -> None:+ self.handler.side_effect = RuntimeError("the consumer's durable write failed")+ view = self._view(+ [_consumer(GITHUB_SPEC, name="probe", handler=self.handler)],+ provider=provider_class("posthog"),+ )++ with (+ patch("posthog.ingress.dispatch.dispatcher.capture_exception"),+ patch("posthog.ingress.views.observe_delivery") as observe,+ patch("posthog.ingress.views.logger") as logger,+ ):+ response = view(self._github_request())++ self.assertEqual(response.status_code, status)+ self.assertEqual([call.kwargs["outcome"] for call in observe.call_args_list], [outcome])+ # The dispatcher already logged the consumer's own failure, so the view says only that+ # the request is not receipted, and names what cost it.+ warnings = {call.args[0]: call.kwargs for call in logger.warning.call_args_list}+ self.assertEqual(warnings.get("ingress_delivery_retry_requested", {}).get("consumers"), warned_about)++ def test_a_consumer_the_budget_skipped_costs_the_receipt_the_same_way(self) -> None:+ elapsed = {"seconds": 0.0}++ def spend_the_budget(delivery: WebhookDelivery) -> None:+ elapsed["seconds"] += 30.0++ skipped = Mock()+ view = self._view(+ [+ _consumer(GITHUB_SPEC, name="alpha", handler=Mock(side_effect=spend_the_budget)),+ _consumer(GITHUB_SPEC, name="zulu", handler=skipped),+ ],+ provider=_RedeliveringGitHubProvider("posthog"),+ )++ with (+ patch("time.monotonic", lambda: elapsed["seconds"]),+ patch("posthog.ingress.views.logger") as logger,+ ):+ response = view(self._github_request())++ self.assertEqual(response.status_code, 502)+ skipped.assert_not_called()+ warnings = {call.args[0]: call.kwargs for call in logger.warning.call_args_list}+ self.assertEqual(warnings["ingress_delivery_retry_requested"]["consumers"], ["zulu"])++ def test_a_duplicate_that_arrives_while_the_first_run_is_going_is_not_receipted(self) -> None:+ runs = {"count": 0}+ answered: list[int] = []++ def deliver_again_mid_run(delivery: WebhookDelivery) -> None:+ runs["count"] += 1+ if runs["count"] == 1:+ answered.append(view(self._github_request()).status_code)++ view = self._view(+ [_consumer(GITHUB_SPEC, name="probe", handler=Mock(side_effect=deliver_again_mid_run))],+ provider=_RedeliveringGitHubProvider("posthog"),+ )++ self.assertEqual(view(self._github_request()).status_code, 202)+ # The duplicate met a run that had not settled, so it asks for the delivery again rather+ # than receipting work that can still raise.+ self.assertEqual(answered, [502])+ self.assertEqual(runs["count"], 1)++ def test_the_redelivery_reaches_only_the_consumer_that_did_not_accept(self) -> None:+ accepted = Mock()+ self.handler.side_effect = RuntimeError("the consumer's durable write failed")+ view = self._view(+ [+ _consumer(GITHUB_SPEC, name="alpha", handler=accepted),+ _consumer(GITHUB_SPEC, name="zulu", handler=self.handler),+ ],+ provider=_RedeliveringGitHubProvider("posthog"),+ )++ with patch("posthog.ingress.dispatch.dispatcher.capture_exception"):+ self.assertEqual(view(self._github_request()).status_code, 502)+ self.handler.side_effect = None+ self.assertEqual(view(self._github_request()).status_code, 202)++ # The one that accepted is deduped on the replay, so the retry costs it nothing.+ accepted.assert_called_once()+ self.assertEqual(self.handler.call_count, 2)++class TestForwardToSecondaryRegion(SimpleTestCase):def setUp(self) -> None:self.body = json.dumps({"action": "opened"}).encode()diff --git a/posthog/ingress/views.py b/posthog/ingress/views.pyindex 3ef0a48040a0..41469d211304 100644--- a/posthog/ingress/views.py+++ b/posthog/ingress/views.py@@ -48,8 +48,10 @@ def _throttle_refusal(provider: WebhookProvider, request: HttpRequest) -> HttpRedef build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], HttpResponse]:"""A Django view for one provider app.- The response is a transport receipt. The method, the throttle, verification and the payload- decide the status; consumers never do, and their return values are ignored.+ The response is a transport receipt: the method, the throttle, verification and the payload+ decide the status, and a consumer's return value is ignored. A provider that sets+ `retry_status` also gets that status when the work did not run at all, which is the+ transport saying so rather than a consumer choosing an answer."""# Refused at build rather than per request, because the failure is silent at request time:# a ScopedRateThrottle reads its rate from the view's `throttle_scope`, finds none here, and@@ -122,9 +124,9 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Httif is_primary_region(request):# Once for the request, not once per delivery: what is replayed is the signed body.forwarded = forward_to_secondary_region(request, provider=provider.provider, app=provider.app)- if not forwarded and provider.forward_failure_status is not None:+ if not forwarded and provider.retry_status is not None:observe_delivery(provider=provider.provider, app=provider.app, outcome="forward_failed")- return HttpResponse(status=provider.forward_failure_status)+ return HttpResponse(status=provider.retry_status)else:# A local miss on the secondary region is that consumer's unresolved routing, not# proof that no region owns the delivery.@@ -135,8 +137,22 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Httconsumers=list(elsewhere),)+ unaccepted: dict[str, None] = {}for delivery in deliveries:- dispatcher.dispatch(delivery, budget=budget)+ dispatched = dispatcher.dispatch(delivery, budget=budget)+ unaccepted.update(dict.fromkeys(dispatched.unaccepted_consumers))++ if unaccepted and provider.retry_status is not None:+ # The dispatcher already logged and captured each consumer's own failure, so this+ # only says the request is not being receipted, and which consumers cost it that.+ logger.warning(+ "ingress_delivery_retry_requested",+ provider=provider.provider,+ app=provider.app,+ consumers=list(unaccepted),+ )+ observe_delivery(provider=provider.provider, app=provider.app, outcome="retry_requested")+ return HttpResponse("Delivery not accepted", status=provider.retry_status)observe_delivery(provider=provider.provider, app=provider.app, outcome="accepted")return HttpResponse(status=provider.success_status)