: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
fix(ingress): let an unsettled dedup claim expire with the delivery budget (#102218)
Julian Beze418ce5bda1d
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex 276d272039b3..743f4ed58ed4 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -251,10 +251,17 @@ Two shapes that already exist and are worth copying rather than re-deriving:## Dedup-Dedup is per `(provider, consumer, delivery_id)` in the Django cache, for 24 hours.+Dedup is per `(provider, consumer, delivery_id)` in the Django cache.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.+A settled mark therefore lives for 24 hours, but an unsettled one is a lease and lives for the request's delivery budget plus a minute.+The lease exists because a process that dies mid-run leaves its mark behind and nothing settles it afterwards: a mark that outlived its run would answer every redelivery `in_flight` until the provider gave up, and the delivery would be lost.+Its cost is that a redelivery arriving after the lease ran out can run beside a first attempt that overran the budget, which is the exposure a provider without dedup has on every retry.+Because two runs can overlap, a second key (`<key>:holder`) names the run that holds the lease, and a run only deletes its own claim: a late failure from the first run cannot drop the second run's claim, nor the done mark a finished run wrote.+The token lives in its own key so that the mark itself stays the plain value every deployed version reads as in flight, which keeps a rolling deploy from receipting a delivery the new worker can still fail.+That fence reads the cache primary rather than a read replica, because a replica can still serve a token the primary already replaced.+Settling to done is not fenced that way, because a consumer that ran the delivery and returned makes the mark true whoever wrote the value it replaces; a run drops the mark only while it is still a lease, so a late failure cannot delete a mark another run settled.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.diff --git a/posthog/ingress/dispatch/dedup.py b/posthog/ingress/dispatch/dedup.pyindex 4e2d2a6ca94b..022d97e2b605 100644--- a/posthog/ingress/dispatch/dedup.py+++ b/posthog/ingress/dispatch/dedup.py@@ -1,19 +1,67 @@"""Per-delivery, per-consumer dedup marks in the Django cache."""from enum import Enum+from uuid import uuid4from django.core.cache import cacheimport structlog+from posthog.dataclasses import frozen+from posthog.ingress.dispatch.budget import delivery_budget_seconds+logger = structlog.get_logger(__name__)DELIVERY_DEDUP_TTL_SECONDS = 24 * 60 * 60+# What the lease adds to the request's delivery budget. The budget is checked between consumers+# and never inside one, so a consumer that starts just under the deadline overruns it, and the+# margin has to cover that overrun plus the rest of the request. A minute is long enough that a+# slow run keeps its claim, and short enough that a claim nobody settled costs one redelivery+# rather than the provider's whole retry window.+DELIVERY_CLAIM_LEASE_MARGIN_SECONDS = 60+_IN_PROGRESS = "in_progress"_DONE = "done"+def _holder_key(key: str) -> str:+ """The key that names the run holding the lease.++ The token sits beside the mark instead of inside it so that the mark keeps the exact value+ the previous version wrote. During a rolling deploy, a worker on that version reads any other+ value as done and receipts the delivery, which stops the provider retrying a delivery the new+ worker can still fail.+ """+ return f"{key}:holder"+++def _read_lease(key: str, holder_key: str) -> dict[str, object]:+ """Read the mark and its holder token together, from the cache's primary.++ The default cache is django_redis, which is replica aware when REDIS_READER_URL is set: it+ serves a read from a replica and sends a delete to the primary. A fence that reads a replica+ can act on a token the primary already replaced, and then `release()` deletes a mark this run+ does not hold. Ask the write client so that the read and the delete see the same Redis.++ A backend with no replica-aware client, such as the LocMemCache the tests run on, has a+ single cache to answer from.+ """+ client = getattr(cache, "client", None)+ if client is None or not hasattr(client, "get_client"):+ return cache.get_many([key, holder_key])+ return client.get_many([key, holder_key], client=client.get_client(write=True))+++def delivery_claim_lease_seconds() -> float:+ """How long an unsettled claim keeps a redelivery out.++ Read per claim, like the budget it is built on, so tuning the budget live carries into the+ lease.+ """+ return delivery_budget_seconds() + DELIVERY_CLAIM_LEASE_MARGIN_SECONDS++class DeliveryClaim(Enum):"""What the mark says about this consumer's work on this delivery."""@@ -22,6 +70,19 @@ class DeliveryClaim(Enum):DONE = "done" # an earlier run finished the work+@frozen+class DeliveryClaimResult:+ """What the claim answered, and the token that names the run holding the mark.++ The token is what lets `release()` tell its own claim from a newer run's. It is None when no+ run holds the mark on this run's behalf, which is every state but `CLAIMED`, plus a `CLAIMED`+ that the cache failed open on.+ """++ state: DeliveryClaim+ token: str | None = None++class DeliveryDedup:"""Marks a (provider, consumer, delivery id) so a redelivery skips work already done.@@ -33,23 +94,57 @@ class DeliveryDedup:redelivery that arrives while the first run is still going reads the mark as work alreadydone and earns a receipt, which stops the provider from retrying a delivery the first runcan still fail.++ The in-progress mark is a lease, not a fact. The process holding it can die before it settles,+ on a deploy or an OOM kill, and nothing settles it afterwards. A provider that redelivers reads+ an unsettled mark as in flight and is answered a retry status, so a mark that outlived its run+ would refuse every redelivery until the provider gave up and the delivery was lost. The lease+ therefore runs out on its own after `delivery_claim_lease_seconds()`, which means a redelivery+ can run beside a first attempt that overran the budget. That is the exposure a provider without+ dedup has on every retry, and consumers are required to be idempotent underneath this.++ Because two runs can overlap, a second key names the run that holds the mark. A run that lost+ its lease settles the mark to done, which stays true, but it cannot delete the claim or the+ done mark another run wrote in the meantime."""@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) -> DeliveryClaim:+ def claim(self, *, provider: str, consumer: str, delivery_id: str) -> DeliveryClaimResult:"""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.++ The follow-up read can be served by a replica, unlike the fenced read in `release()`. A+ stale value there answers in progress where the mark is free, which costs the delivery one+ redelivery and never a receipt the work did not earn."""key = self.key(provider=provider, consumer=consumer, delivery_id=delivery_id)+ token = uuid4().hex+ lease_seconds = delivery_claim_lease_seconds()try:- if cache.add(key, _IN_PROGRESS, timeout=DELIVERY_DEDUP_TTL_SECONDS):- return DeliveryClaim.CLAIMED- held = cache.get(key)+ for _ in range(2):+ if cache.add(key, _IN_PROGRESS, timeout=lease_seconds):+ # The mark's add picks the winner on its own; the holder key only names it. A+ # process that dies between the two writes leaves a lease that nobody can+ # release and that runs out on the lease timeout.+ cache.set(_holder_key(key), token, timeout=lease_seconds)+ return DeliveryClaimResult(state=DeliveryClaim.CLAIMED, token=token)+ held = cache.get(key)+ if held is None:+ # The lease ran out between the add and this read, so nobody holds the mark+ # now. Take it instead: a lease that ran out is a run that never settled, and+ # reading the gap as done would receipt work that did not finish.+ continue+ # Anything that is not the in-progress value counts as done. That covers a mark+ # written before this state existed, which keeps the receipt those marks earned+ # before.+ return DeliveryClaimResult(+ state=DeliveryClaim.IN_PROGRESS if held == _IN_PROGRESS else DeliveryClaim.DONE+ )except Exception:logger.warning("ingress_dedup_cache_failed",@@ -58,17 +153,22 @@ class DeliveryDedup:delivery_id=delivery_id,exc_info=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+ return DeliveryClaimResult(state=DeliveryClaim.CLAIMED)+ # Two leases ran out under this claim, so runs keep starting and never settling. Answer+ # in progress, which costs the delivery its receipt and has the provider send it again,+ # rather than claiming a mark this run cannot keep.+ return DeliveryClaimResult(state=DeliveryClaim.IN_PROGRESS)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 whatis left. A redelivery is deduped for 24 hours from when the work finished.++ The write is not fenced on the holder token, unlike `release()`. Done is a fact about the+ delivery rather than about who holds the key: this consumer ran the delivery and returned,+ so the mark is true whoever wrote the value it replaces. Fencing it would instead drop the+ mark of a run that outlived its lease, and let the provider redeliver finished work."""try:cache.set(@@ -85,14 +185,33 @@ class DeliveryDedup: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.+ def release(self, *, provider: str, consumer: str, delivery_id: str, token: str | None) -> None:+ """Drop this run's own mark after the consumer raised, so a redelivery reaches it.The mark is set before the consumer runs, so without this a failure would burn thedelivery for the whole TTL.++ Only this run's own mark, because the lease can run out while the consumer still runs. By+ then the key can carry a newer run's claim, which a delete would turn into a third run, or+ the done mark of a run that finished, which a delete would hand back to the provider as+ work to redeliver. So a delete needs the holder key to name this run and the mark to still+ be a lease. The holder key alone is not enough, because settling does not clear it, and+ this run would drop the done mark another run wrote while this one held the lease.++ The cache API has no compare-and-delete, so the read and the delete are two calls and a+ newer claim written between them is still deleted. That window is microseconds wide, and+ running a consumer twice is the exposure this mark only narrows: consumers are required to+ be idempotent underneath it."""+ if token is None:+ return+ key = self.key(provider=provider, consumer=consumer, delivery_id=delivery_id)+ holder_key = _holder_key(key)try:- cache.delete(self.key(provider=provider, consumer=consumer, delivery_id=delivery_id))+ held = _read_lease(key, holder_key)+ if held.get(holder_key) != token or held.get(key) != _IN_PROGRESS:+ return+ cache.delete_many([key, holder_key])except Exception:logger.warning("ingress_dedup_release_failed",diff --git a/posthog/ingress/dispatch/dispatcher.py b/posthog/ingress/dispatch/dispatcher.pyindex 11b1733da289..a9b41ea099ff 100644--- a/posthog/ingress/dispatch/dispatcher.py+++ b/posthog/ingress/dispatch/dispatcher.py@@ -13,7 +13,7 @@ from posthog.ingress.contracts import (WebhookDelivery,)from posthog.ingress.dispatch.budget import DeliveryBudget, delivery_budget_seconds-from posthog.ingress.dispatch.dedup import DeliveryClaim, DeliveryDedup+from posthog.ingress.dispatch.dedup import DeliveryClaim, DeliveryClaimResult, DeliveryDedupfrom posthog.ingress.dispatch.registry import ConsumerRegistryfrom posthog.ingress.observability.metrics import observe_consumer_duration, observe_consumer_run, observe_ownership@@ -52,9 +52,9 @@ class WebhookDispatcher:claim = (self._dedup.claim(provider=delivery.provider, consumer=consumer.name, delivery_id=delivery_id)if delivery_id- else DeliveryClaim.CLAIMED+ else DeliveryClaimResult(state=DeliveryClaim.CLAIMED))- if claim is DeliveryClaim.DONE:+ if claim.state is DeliveryClaim.DONE:logger.info("ingress_consumer_deduped",provider=delivery.provider,@@ -64,7 +64,7 @@ class WebhookDispatcher:)observe_consumer_run(provider=delivery.provider, consumer=consumer.name, outcome="deduped")return True- if claim is DeliveryClaim.IN_PROGRESS:+ if claim.state is DeliveryClaim.IN_PROGRESS:logger.info("ingress_consumer_in_flight",provider=delivery.provider,@@ -88,7 +88,12 @@ class WebhookDispatcher:)capture_exception(error)if delivery_id:- self._dedup.release(provider=delivery.provider, consumer=consumer.name, delivery_id=delivery_id)+ self._dedup.release(+ provider=delivery.provider,+ consumer=consumer.name,+ delivery_id=delivery_id,+ token=claim.token,+ )observe_consumer_run(provider=delivery.provider, consumer=consumer.name, outcome="failed")return Falseelse:diff --git a/posthog/ingress/test/test_dispatcher.py b/posthog/ingress/test/test_dispatcher.pyindex ada9617b8d30..1f303a01eda0 100644--- a/posthog/ingress/test/test_dispatcher.py+++ b/posthog/ingress/test/test_dispatcher.py@@ -1,3 +1,4 @@+import timefrom dataclasses import replacefrom datetime import UTC, datetime@@ -16,7 +17,7 @@ from posthog.ingress.contracts import (WebhookDelivery,)from posthog.ingress.dispatch.budget import DEFAULT_DELIVERY_BUDGET_SECONDS, DeliveryBudget, delivery_budget_seconds-from posthog.ingress.dispatch.dedup import DeliveryClaim, DeliveryDedup+from posthog.ingress.dispatch.dedup import DeliveryClaim, DeliveryDedup, delivery_claim_lease_secondsfrom posthog.ingress.dispatch.dispatcher import WebhookDispatcherfrom posthog.ingress.dispatch.registry import ConsumerRegistry@@ -198,32 +199,165 @@ class TestWebhookDispatcher(SimpleTestCase):second.assert_not_called()+class _WriteClient:+ """A django_redis client that answers from the Redis primary, as its write client does."""++ def __init__(self, primary: dict[str, object]) -> None:+ self.primary = primary++ def get_client(self, write: bool = True) -> dict[str, object]:+ return self.primary++ def get_many(self, keys: list[str], version: int | None = None, client: dict | None = None) -> dict:+ return {key: self.primary[key] for key in keys if key in self.primary}++@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_a_claim_reads_as_in_flight_to_the_version_that_knows_no_holder_token(self) -> None:+ claim = DeliveryDedup().claim(**self.mark)++ # The deployed version reads every value but this one as done. On a rolling deploy a token+ # in the mark would have an old worker receipt a delivery the new worker can still fail.+ key = DeliveryDedup.key(**self.mark)+ self.assertEqual(cache.get(key), "in_progress")+ self.assertEqual(cache.get(f"{key}:holder"), claim.token)++ def test_the_lease_fence_reads_the_cache_primary(self) -> None:+ dedup = DeliveryDedup()+ claim = dedup.claim(**self.mark)+ key = DeliveryDedup.key(**self.mark)+ # The lease ran out and a newer run took the key, so the primary names the newer run. The+ # LocMemCache beside it stands in for a replica that still serves this run's token.+ client = _WriteClient({key: "in_progress", f"{key}:holder": "a-token-from-a-newer-run"})++ with patch.object(cache, "client", client, create=True):+ dedup.release(**self.mark, token=claim.token)++ # A replica can still serve a token the primary already replaced, so a fence that read one+ # would drop the mark the newer run holds and start a third run beside the two going.+ self.assertEqual(dedup.claim(**self.mark).state, DeliveryClaim.IN_PROGRESS)+def test_the_mark_reports_the_state_its_holder_left_it_in(self) -> None:dedup = DeliveryDedup()- self.assertEqual(dedup.claim(**self.mark), DeliveryClaim.CLAIMED)+ claim = dedup.claim(**self.mark)+ self.assertEqual(claim.state, 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)+ self.assertEqual(dedup.claim(**self.mark).state, DeliveryClaim.IN_PROGRESS)++ dedup.release(**self.mark, token=claim.token)+ self.assertEqual(dedup.claim(**self.mark).state, DeliveryClaim.CLAIMED)dedup.complete(**self.mark)- self.assertEqual(dedup.claim(**self.mark), DeliveryClaim.DONE)+ self.assertEqual(dedup.claim(**self.mark).state, DeliveryClaim.DONE)- dedup.release(**self.mark)- self.assertEqual(dedup.claim(**self.mark), DeliveryClaim.CLAIMED)+ @parameterized.expand(+ [+ ("a_flag_from_before_the_state_existed", True, DeliveryClaim.DONE),+ ("a_lease_with_no_holder_key", "in_progress", DeliveryClaim.IN_PROGRESS),+ ("a_settled_mark", "done", DeliveryClaim.DONE),+ ]+ )+ def test_a_mark_this_run_did_not_write_still_dedupes(+ self, _name: str, held: object, expected: DeliveryClaim+ ) -> None:+ cache.set(DeliveryDedup.key(**self.mark), held)- 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 ones the previous version wrote. Reading+ # a flag as in flight would cost a receipt for every delivery still holding it, and reading+ # a lease as done would receipt a run that never settled.+ self.assertEqual(DeliveryDedup().claim(**self.mark).state, expected)- # 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)+ @parameterized.expand(+ [+ ("a_newer_run_holds_the_claim", False, DeliveryClaim.IN_PROGRESS),+ ("a_newer_run_settled_the_mark", True, DeliveryClaim.DONE),+ ]+ )+ def test_a_run_that_lost_its_lease_cannot_drop_the_mark_another_run_holds(+ self, _name: str, settle: bool, expected: DeliveryClaim+ ) -> None:+ dedup = DeliveryDedup()+ stale = dedup.claim(**self.mark)+ # The lease runs out while the first run is still working, and a second run takes the key.+ cache.delete(DeliveryDedup.key(**self.mark))+ dedup.claim(**self.mark)+ if settle:+ dedup.complete(**self.mark)++ dedup.release(**self.mark, token=stale.token)++ # Dropping the newer claim would let a third run start beside the two already going, and+ # dropping the done mark would hand finished work back to the provider to redeliver.+ self.assertEqual(dedup.claim(**self.mark).state, expected)++ def test_the_run_the_holder_key_names_cannot_drop_a_settled_mark(self) -> None:+ dedup = DeliveryDedup()+ dedup.claim(**self.mark)+ cache.delete(DeliveryDedup.key(**self.mark))+ newer = dedup.claim(**self.mark)+ dedup.complete(**self.mark)++ dedup.release(**self.mark, token=newer.token)++ # Settling does not clear the holder key, so the token still names this run. Releasing on+ # that alone would drop the done mark and hand finished work back to the provider.+ self.assertEqual(dedup.claim(**self.mark).state, DeliveryClaim.DONE)++ @parameterized.expand(+ [+ ("one_expiry_is_reclaimed", 1, DeliveryClaim.CLAIMED),+ ("a_key_that_keeps_vanishing_is_left_in_flight", 2, DeliveryClaim.IN_PROGRESS),+ ]+ )+ def test_a_lease_that_expires_between_the_add_and_the_read_is_never_read_as_done(+ self, _name: str, refusals: int, expected: DeliveryClaim+ ) -> None:+ real_add = cache.add+ refused = 0++ def refuse_then_add(*args, **kwargs):+ nonlocal refused+ if refused < refusals:+ refused += 1+ return False+ return real_add(*args, **kwargs)++ with patch.object(cache, "add", refuse_then_add):+ claim = DeliveryDedup().claim(**self.mark)++ # A refused add whose follow-up read finds nothing is a lease that ran out under the claim,+ # which is a run that never settled. Reading it as done would receipt work that never+ # finished, and a provider with retry_status would stop redelivering it.+ self.assertEqual(claim.state, expected)++ @parameterized.expand(+ [+ ("an_unsettled_claim_expires_with_its_lease", False, DeliveryClaim.CLAIMED),+ ("a_settled_mark_outlives_the_lease", True, DeliveryClaim.DONE),+ ]+ )+ def test_a_claim_only_outlives_its_lease_once_it_is_settled(+ self, _name: str, settle: bool, expected: DeliveryClaim+ ) -> None:+ start = time.time()++ with patch("time.time", lambda: start):+ DeliveryDedup().claim(**self.mark)+ if settle:+ DeliveryDedup().complete(**self.mark)++ # An in-progress mark nobody settled is what a killed process leaves behind. A provider+ # that redelivers reads it as in flight and is answered a retry status, so a mark that+ # outlived its run would refuse every redelivery until the provider gave up.+ with patch("time.time", lambda: start + delivery_claim_lease_seconds() + 1):+ self.assertEqual(DeliveryDedup().claim(**self.mark).state, expected)class TestDeliveryOwnership(SimpleTestCase):