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.

fix(alerts): wait out a thread claim a dead delivery left behind (#112033)

Jimmy Zhub84144d9c23f
diff --git a/products/alerts_platform/backend/delivery/dispatch.py b/products/alerts_platform/backend/delivery/dispatch.py
index e870e044f6f5..751cbd78fc04 100644
--- a/products/alerts_platform/backend/delivery/dispatch.py
+++ b/products/alerts_platform/backend/delivery/dispatch.py
@@ -27,6 +27,7 @@ def deliver(
announcement: EvaluationAnnouncement,
) -> None:
channel_target = transport.channel_target(target)
+ busy = 0
for transition in announcement.transitions:
key = _thread_key(
@@ -49,8 +50,10 @@ def deliver(
try:
claim = thread_store.claim(key, evaluation_key)
except ThreadBusy:
- # Another attempt of this send is still posting. Leaving it is what stops the two
- # of them putting the same message in the channel twice.
+ # Another attempt may still be posting, so sending now could put the same message
+ # in the channel twice. The holder may also have died, and then its claim frees
+ # this thread only when it goes stale. The caller waits and runs the send again.
+ busy += 1
continue
if claim is None:
continue
@@ -69,6 +72,9 @@ def deliver(
raise
thread_store.delivered(claim, sent)
+ if busy:
+ raise ThreadBusy(f"{busy} of {len(announcement.transitions)} threads are held by another send")
+
def _send(
*,
diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.py
index 9cb3a3433926..0d4b1fe2b8d4 100644
--- a/products/alerts_platform/backend/delivery/evaluation.py
+++ b/products/alerts_platform/backend/delivery/evaluation.py
@@ -16,7 +16,7 @@ from posthog.models import Team
from products.alerts_platform.backend.delivery.destinations import list_alert_destination_groups
from products.alerts_platform.backend.delivery.dispatch import deliver
from products.alerts_platform.backend.delivery.slack import SlackTransport
-from products.alerts_platform.backend.delivery.thread_store import DatabaseThreadStore
+from products.alerts_platform.backend.delivery.thread_store import DatabaseThreadStore, ThreadBusy
from products.alerts_platform.backend.delivery.transport import DeliveryTransport
from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
@@ -93,6 +93,7 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:
thread_store = DatabaseThreadStore(request.team_id)
sent = 0
skipped = 0
+ busy: list[str] = []
# Per subscription rather than per destination. A destination subscribes to some of the
# kinds an alert can announce, so one that asked for firings must not be handed the resolve
# that another group produced in the same evaluation.
@@ -102,16 +103,22 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:
if transport_class is None:
skipped += 1
continue
- deliver(
- transport=transport_class(),
- thread_store=thread_store,
- team_id=request.team_id,
- configuration_id=request.configuration_id,
- evaluation_key=request.evaluation_key,
- target=target,
- announcement=replace(announced, transitions=transitions),
- )
- sent += 1
+ try:
+ deliver(
+ transport=transport_class(),
+ thread_store=thread_store,
+ team_id=request.team_id,
+ configuration_id=request.configuration_id,
+ evaluation_key=request.evaluation_key,
+ target=target,
+ announcement=replace(announced, transitions=transitions),
+ )
+ except ThreadBusy as error:
+ busy.append(str(error))
+ else:
+ sent += 1
+ if busy:
+ raise ThreadBusy("; ".join(busy))
return DeliveryOutcome(live=True, sent=sent, skipped_without_transport=skipped)
diff --git a/products/alerts_platform/backend/delivery/thread_store.py b/products/alerts_platform/backend/delivery/thread_store.py
index 2b6c8ef2df8e..893abc8c681e 100644
--- a/products/alerts_platform/backend/delivery/thread_store.py
+++ b/products/alerts_platform/backend/delivery/thread_store.py
@@ -129,14 +129,15 @@ class DatabaseThreadStore:
now = timezone.now()
# One conditional UPDATE rather than a read and a write: two attempts reading a free
- # claim at the same moment would both believe they held it.
+ # claim at the same moment would both believe they held it. Every write here sets
+ # `updated_at` itself, because `QuerySet.update()` skips `auto_now`.
taken = (
PlatformAlertThread.objects.for_team(self._team_id)
.filter(id=thread.id)
.filter(
models.Q(pending_evaluation_key__isnull=True) | models.Q(pending_claimed_at__lt=now - PENDING_CLAIM_TTL)
)
- .update(pending_evaluation_key=evaluation_key, pending_claimed_at=now)
+ .update(pending_evaluation_key=evaluation_key, pending_claimed_at=now, updated_at=now)
)
if not taken:
raise ThreadBusy(f"thread {thread.id} is being posted to by another send")
@@ -153,6 +154,7 @@ class DatabaseThreadStore:
"delivered_evaluation_keys": delivered,
"pending_evaluation_key": None,
"pending_claimed_at": None,
+ "updated_at": timezone.now(),
}
# Only the message that opened the conversation is remembered. Recording a reply would
# move the thread onto itself, so a later message would reply to a reply.
@@ -161,7 +163,7 @@ class DatabaseThreadStore:
self._fenced(claim).update(**fields)
def release(self, claim: ThreadClaim) -> None:
- self._fenced(claim).update(pending_evaluation_key=None, pending_claimed_at=None)
+ self._fenced(claim).update(pending_evaluation_key=None, pending_claimed_at=None, updated_at=timezone.now())
def _fenced(self, claim: ThreadClaim) -> models.QuerySet[PlatformAlertThread]:
return PlatformAlertThread.objects.for_team(self._team_id).filter(
diff --git a/products/alerts_platform/backend/facade/temporal.py b/products/alerts_platform/backend/facade/temporal.py
index c2728d1f4698..74ef52993c9d 100644
--- a/products/alerts_platform/backend/facade/temporal.py
+++ b/products/alerts_platform/backend/facade/temporal.py
@@ -6,6 +6,7 @@ from products.alerts_platform.backend.temporal.schedule import create_alerts_pla
from products.alerts_platform.backend.temporal.telemetry import AlertsPlatformTelemetryInterceptor
from products.alerts_platform.backend.temporal.workflows import (
DELIVERY_ACTIVITIES,
+ DELIVERY_EXECUTION_TIMEOUT,
DELIVERY_WORKFLOWS,
EVALUATION_ACTIVITIES,
EVALUATION_WORKFLOWS,
@@ -18,6 +19,7 @@ __all__ = [
"ALERTS_PLATFORM_LATENCY_HISTOGRAM_BUCKETS",
"ALERTS_PLATFORM_LATENCY_HISTOGRAM_METRICS",
"DELIVERY_ACTIVITIES",
+ "DELIVERY_EXECUTION_TIMEOUT",
"DELIVERY_WORKFLOWS",
"EVALUATION_ACTIVITIES",
"EVALUATION_WORKFLOWS",
diff --git a/products/alerts_platform/backend/temporal/workflows.py b/products/alerts_platform/backend/temporal/workflows.py
index 1945af859fee..58bf26107d97 100644
--- a/products/alerts_platform/backend/temporal/workflows.py
+++ b/products/alerts_platform/backend/temporal/workflows.py
@@ -16,6 +16,7 @@ from temporalio.exceptions import (
from posthog.dataclasses import frozen
from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.errors import NonReportableApplicationError, unwrap_temporal_cause
from posthog.temporal.common.logger import get_write_only_logger
from products.alerts_platform.backend.temporal.metrics import increment_deliveries_previewed, safe_record
@@ -33,6 +34,7 @@ with workflow.unsafe.imports_passed_through():
from posthog.sync import database_sync_to_async_pool
from products.alerts_platform.backend.delivery.evaluation import deliver_evaluation
+ from products.alerts_platform.backend.delivery.thread_store import PENDING_CLAIM_TTL, ThreadBusy
from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
AlertDemand,
@@ -69,6 +71,19 @@ SOURCE_DISPATCH_HEADROOM = dt.timedelta(seconds=1)
# which is what blocks a slow evaluation's own re-dispatch.
SOURCE_EVALUATION_TIMEOUT = dt.timedelta(seconds=75)
+THREAD_BUSY = "AlertsPlatformThreadBusy"
+DELIVERY_START_TO_CLOSE = dt.timedelta(seconds=10)
+DELIVERY_SCHEDULE_TO_CLOSE = dt.timedelta(seconds=30)
+# The workflow waits out a held thread because the activity's retries end inside
+# DELIVERY_SCHEDULE_TO_CLOSE, which is shorter than PENDING_CLAIM_TTL. A claim that a dead
+# attempt left looks fresh to every one of those retries.
+BUSY_RETRY_DELAY = dt.timedelta(seconds=20)
+# From the first busy result to the start of a later attempt. An attempt that starts this late
+# finds every claim the first one saw already stale, so a thread still held is a newer send's.
+BUSY_WAIT_LIMIT = PENDING_CLAIM_TTL + BUSY_RETRY_DELAY
+# The last attempt can start one attempt and one delay past the limit.
+DELIVERY_EXECUTION_TIMEOUT = 3 * DELIVERY_SCHEDULE_TO_CLOSE + BUSY_WAIT_LIMIT + BUSY_RETRY_DELAY
+
@frozen
class AlertsPlatformInputs:
@@ -104,7 +119,18 @@ async def alerts_platform_deliver_preview_activity(request: AlertDeliveryRequest
the ORM and posts over a blocking client. Django refuses an ORM call from a thread with a
running event loop, so the whole call crosses on the pool rather than one part of it.
"""
- outcome = await database_sync_to_async_pool(deliver_evaluation)(request)
+ try:
+ outcome = await database_sync_to_async_pool(deliver_evaluation)(request)
+ except ThreadBusy as error:
+ await LOGGER.ainfo(
+ "alerts_platform_delivery_thread_busy",
+ source=request.source.value,
+ configuration_id=request.configuration_id,
+ evaluation_key=request.evaluation_key,
+ )
+ # Non-retryable so that the wait does not use the retries a provider failure needs, and
+ # non-reportable because a held thread is expected contention. The workflow waits it out.
+ raise NonReportableApplicationError(str(error), type=THREAD_BUSY, non_retryable=True) from error
if not outcome.live:
await LOGGER.ainfo(
"alerts_platform_delivery_preview",
@@ -131,13 +157,27 @@ class AlertsPlatformDeliverPreviewWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, inputs: AlertDeliveryRequest) -> None:
- await workflow.execute_activity(
- alerts_platform_deliver_preview_activity,
- inputs,
- start_to_close_timeout=dt.timedelta(seconds=10),
- schedule_to_close_timeout=dt.timedelta(seconds=30),
- retry_policy=RetryPolicy(maximum_attempts=3),
- )
+ busy_deadline: dt.datetime | None = None
+ while True:
+ started_at = workflow.now()
+ try:
+ await workflow.execute_activity(
+ alerts_platform_deliver_preview_activity,
+ inputs,
+ start_to_close_timeout=DELIVERY_START_TO_CLOSE,
+ schedule_to_close_timeout=DELIVERY_SCHEDULE_TO_CLOSE,
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ return
+ except ActivityError as error:
+ cause = unwrap_temporal_cause(error)
+ if cause is None or cause.type != THREAD_BUSY:
+ raise
+ if busy_deadline is None:
+ busy_deadline = workflow.now() + BUSY_WAIT_LIMIT
+ elif started_at >= busy_deadline:
+ raise
+ await workflow.sleep(BUSY_RETRY_DELAY)
@workflow.defn(name="alerts-platform-deliver")
diff --git a/products/alerts_platform/backend/tests/test_delivery_thread_store.py b/products/alerts_platform/backend/tests/test_delivery_thread_store.py
index 6d9f68a3a709..3b51cb2b253f 100644
--- a/products/alerts_platform/backend/tests/test_delivery_thread_store.py
+++ b/products/alerts_platform/backend/tests/test_delivery_thread_store.py
@@ -1,7 +1,10 @@
+from dataclasses import replace
from datetime import UTC, datetime, timedelta
import pytest
+import time_machine
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from django.utils import timezone
@@ -9,6 +12,7 @@ from parameterized import parameterized
from posthog.models.scoping import team_scope
+from products.alerts_platform.backend.delivery.dispatch import deliver
from products.alerts_platform.backend.delivery.thread_store import (
PENDING_CLAIM_TTL,
DatabaseThreadStore,
@@ -17,6 +21,7 @@ from products.alerts_platform.backend.delivery.thread_store import (
)
from products.alerts_platform.backend.delivery.transport import MessageHandle
from products.alerts_platform.backend.models import PlatformAlertConfiguration, PlatformAlertThread
+from products.alerts_platform.backend.tests.test_delivery_dispatch import TARGET, FakeTransport, _announcement
FIRING = datetime(2026, 9, 30, 9, tzinfo=UTC)
@@ -48,9 +53,14 @@ class TestDatabaseThreadStore(APIBaseTest):
def test_an_evaluation_that_already_landed_is_not_sent_again(self) -> None:
key = self._key()
- claim = self.store.claim(key, "eval-1")
+ with time_machine.travel(FIRING, tick=False):
+ claim = self.store.claim(key, "eval-1")
assert claim is not None
- self.store.delivered(claim, MessageHandle(external_ref={"channel": "C-ENG", "ts": "1"}))
+ with time_machine.travel(FIRING + timedelta(minutes=10), tick=False):
+ self.store.delivered(claim, MessageHandle(external_ref={"channel": "C-ENG", "ts": "1"}))
+
+ with team_scope(self.team.id):
+ assert PlatformAlertThread.objects.get(id=claim.thread_id).updated_at == FIRING + timedelta(minutes=10)
assert self.store.claim(key, "eval-1") is None
@@ -87,6 +97,37 @@ class TestDatabaseThreadStore(APIBaseTest):
else:
assert self.store.claim(key, "eval-2") is not None
+ def test_a_send_that_a_dead_attempt_left_claimed_goes_out_once_the_claim_is_stale(self) -> None:
+ transport = FakeTransport()
+
+ def send() -> None:
+ with patch("products.alerts_platform.backend.delivery.dispatch.record_delivery"):
+ deliver(
+ transport=transport,
+ thread_store=self.store,
+ team_id=self.team.id,
+ configuration_id=str(self.configuration.id),
+ evaluation_key="eval-1",
+ target=TARGET,
+ announcement=_announcement(episode_started_at=FIRING),
+ )
+
+ dead = self.store.claim(replace(self._key(), provider=transport.provider), "eval-1")
+ assert dead is not None
+
+ with pytest.raises(ThreadBusy):
+ send()
+ assert transport.sends == []
+
+ with team_scope(self.team.id):
+ PlatformAlertThread.objects.filter(id=dead.thread_id).update(
+ pending_claimed_at=timezone.now() - PENDING_CLAIM_TTL * 2
+ )
+ send()
+ send()
+
+ assert len(transport.sends) == 1
+
def test_a_superseded_holder_does_not_clear_the_claim_that_replaced_it(self) -> None:
key = self._key()
stalled = self.store.claim(key, "eval-1")
diff --git a/products/alerts_platform/backend/tests/test_temporal_workflows.py b/products/alerts_platform/backend/tests/test_temporal_workflows.py
index 75344fdc70d0..9cbfbe2b63fd 100644
--- a/products/alerts_platform/backend/tests/test_temporal_workflows.py
+++ b/products/alerts_platform/backend/tests/test_temporal_workflows.py
@@ -35,8 +35,10 @@ from temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Worker
from posthog.models.scoping import team_scope
+from products.alerts_platform.backend.delivery.thread_store import PENDING_CLAIM_TTL
from products.alerts_platform.backend.facade.contracts import (
AlertBatchKey,
+ AlertDeliveryRequest,
AlertDemand,
DemandDiscoveryInputs,
OrchestrateInputs,
@@ -45,6 +47,7 @@ from products.alerts_platform.backend.facade.contracts import (
)
from products.alerts_platform.backend.facade.temporal import (
DELIVERY_ACTIVITIES,
+ DELIVERY_EXECUTION_TIMEOUT,
DELIVERY_WORKFLOWS,
EVALUATION_ACTIVITIES,
EVALUATION_WORKFLOWS,
@@ -56,6 +59,7 @@ from products.alerts_platform.backend.logic import demand
from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
from products.alerts_platform.backend.temporal import postgres
from products.alerts_platform.backend.temporal.workflows import (
+ THREAD_BUSY,
AlertsPlatformEvaluateWorkflow,
AlertsPlatformInputs,
AlertsPlatformOrchestrateWorkflow,
@@ -317,6 +321,51 @@ async def test_delivery_survives_parent_closure(
assert await child.result() is None
[email protected]("frees_after", [PENDING_CLAIM_TTL, None])
+async def test_delivery_waits_out_a_held_thread_and_fails_when_it_never_frees(
+ environment: WorkflowEnvironment, frees_after: dt.timedelta | None
+) -> None:
+ attempts: list[dt.datetime] = []
+
+ @activity.defn(name="alerts_platform_deliver_preview_activity")
+ async def held_thread(request: AlertDeliveryRequest) -> None:
+ scheduled = activity.info().current_attempt_scheduled_time
+ attempts.append(scheduled)
+ if frees_after is None or scheduled - attempts[0] < frees_after:
+ raise ApplicationError("thread held", type=THREAD_BUSY, non_retryable=True)
+
+ async with Worker(
+ environment.client,
+ task_queue=settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,
+ workflows=DELIVERY_WORKFLOWS,
+ activities=[held_thread],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ handle = await environment.client.start_workflow(
+ "alerts-platform-deliver-preview",
+ AlertDeliveryRequest(
+ source=SourceKind.LOGS,
+ team_id=1,
+ configuration_id="cfg-1",
+ evaluation_key="eval-1",
+ destination_alert_id="legacy-1",
+ event_ids_by_kind={},
+ ),
+ id=str(uuid.uuid4()),
+ task_queue=settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,
+ execution_timeout=DELIVERY_EXECUTION_TIMEOUT,
+ )
+ if frees_after is None:
+ with pytest.raises(WorkflowFailureError) as failure:
+ await handle.result()
+ assert isinstance(failure.value.cause, ActivityError)
+ else:
+ assert await handle.result() is None
+
+ assert attempts[-1] - attempts[0] >= PENDING_CLAIM_TTL
+
+
@pytest.mark.parametrize("timeout_type", [TimeoutType.START_TO_CLOSE, TimeoutType.SCHEDULE_TO_CLOSE])
async def test_probe_timeout_still_starts_independent_delivery(
environment: WorkflowEnvironment, caplog: pytest.LogCaptureFixture, timeout_type: TimeoutType
diff --git a/products/logs/backend/temporal/alert_evaluate.py b/products/logs/backend/temporal/alert_evaluate.py
index c8e8af257b8f..9f069e698cff 100644
--- a/products/logs/backend/temporal/alert_evaluate.py
+++ b/products/logs/backend/temporal/alert_evaluate.py
@@ -24,6 +24,7 @@ with workflow.unsafe.imports_passed_through():
SourceEvaluationInputs,
SourceOutcomeInputs,
)
+ from products.alerts_platform.backend.facade.temporal import DELIVERY_EXECUTION_TIMEOUT
WORKFLOW_NAME = "logs-alert-evaluate"
@@ -107,7 +108,7 @@ class LogsAlertEvaluateWorkflow(PostHogWorkflow):
id=f"alerts-deliver-preview-{delivery.configuration_id}:{delivery.evaluation_key}",
task_queue=settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,
parent_close_policy=workflow.ParentClosePolicy.ABANDON,
- execution_timeout=dt.timedelta(minutes=1),
+ execution_timeout=DELIVERY_EXECUTION_TIMEOUT,
)
for delivery in evaluation.deliveries
),