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.

feat(alerts): give a delivery a conversation it can reply into (#108110)

Jimmy Zhu4d24f989d64c
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index e30a06322acd..28baab908f5f 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -391,6 +391,7 @@ rules:
|SubscriptionDelivery
|PlatformAlert
|PlatformAlertConfiguration
+ |PlatformAlertThread
|Survey
|SurveyResponseArchive
|TableCertification
@@ -827,6 +828,7 @@ rules:
|SubscriptionDelivery
|PlatformAlert
|PlatformAlertConfiguration
+ |PlatformAlertThread
|Survey
|SurveyResponseArchive
|TableCertification
diff --git a/products/alerts/backend/delivery/dispatch.py b/products/alerts/backend/delivery/dispatch.py
index 2816895aa343..d1182fb6caa6 100644
--- a/products/alerts/backend/delivery/dispatch.py
+++ b/products/alerts/backend/delivery/dispatch.py
@@ -5,10 +5,10 @@ it. Which destinations an alert has is resolved before this, so a change to that
reaches no transport.
"""
-from products.alerts.backend.delivery.message import build_message
+from products.alerts.backend.delivery.message import AlertMessage, build_message
from products.alerts.backend.delivery.telemetry import record_delivery
-from products.alerts.backend.delivery.thread_store import ThreadKey, ThreadStore
-from products.alerts.backend.delivery.transport import DeliveryTransport
+from products.alerts.backend.delivery.thread_store import ThreadBusy, ThreadKey, ThreadStore
+from products.alerts.backend.delivery.transport import DeliveryTransport, MessageHandle
from products.alerts.backend.facade.contracts import AlertDestinationData, AnnouncedTransition, EvaluationAnnouncement
@@ -18,6 +18,7 @@ def deliver(
thread_store: ThreadStore,
team_id: int,
configuration_id: str,
+ evaluation_key: str,
target: AlertDestinationData,
announcement: EvaluationAnnouncement,
) -> None:
@@ -30,25 +31,61 @@ def deliver(
channel_target=channel_target,
transition=transition,
)
- handle = thread_store.handle_for(key) if key is not None else None
- message = build_message(announcement, transition)
+ if key is None:
+ _send(
+ transport=transport,
+ team_id=team_id,
+ configuration_id=configuration_id,
+ target=target,
+ message=build_message(announcement, transition),
+ in_reply_to=None,
+ )
+ continue
+
try:
- sent = transport.deliver(team_id=team_id, target=target, message=message, in_reply_to=handle)
- except Exception:
- # Every failure class. Counting only the refusals a provider names leaves an outage
- # reading as no delivery attempted at all.
- record_delivery(
+ 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.
+ continue
+ if claim is None:
+ continue
+
+ try:
+ sent = _send(
+ transport=transport,
team_id=team_id,
configuration_id=configuration_id,
- provider=transport.provider,
- succeeded=False,
+ target=target,
+ message=build_message(announcement, transition),
+ in_reply_to=claim.handle,
)
+ except Exception:
+ thread_store.release(claim)
raise
- record_delivery(team_id=team_id, configuration_id=configuration_id, provider=transport.provider, succeeded=True)
- # Only the first message of a conversation is remembered. Remembering a reply would move
- # the thread onto itself, so a later message would reply to a reply.
- if sent is not None and handle is None and key is not None:
- thread_store.remember(key, sent)
+ thread_store.delivered(claim, sent)
+
+
+def _send(
+ *,
+ transport: DeliveryTransport,
+ team_id: int,
+ configuration_id: str,
+ target: AlertDestinationData,
+ message: AlertMessage,
+ in_reply_to: MessageHandle | None,
+) -> MessageHandle | None:
+ try:
+ sent = transport.deliver(team_id=team_id, target=target, message=message, in_reply_to=in_reply_to)
+ except Exception:
+ # Every failure class. Counting only the refusals a provider names leaves an outage
+ # reading as no delivery attempted at all.
+ record_delivery(
+ team_id=team_id, configuration_id=configuration_id, provider=transport.provider, succeeded=False
+ )
+ raise
+ record_delivery(team_id=team_id, configuration_id=configuration_id, provider=transport.provider, succeeded=True)
+ return sent
def _thread_key(
diff --git a/products/alerts/backend/delivery/thread_store.py b/products/alerts/backend/delivery/thread_store.py
index 9c47769d626a..9aa87c4758e9 100644
--- a/products/alerts/backend/delivery/thread_store.py
+++ b/products/alerts/backend/delivery/thread_store.py
@@ -1,9 +1,9 @@
"""Where a provider conversation is remembered between sends.
A resolve replies to the message that fired rather than posting beside it, which needs the
-handle from that first send. The store is an interface before it is a table: the key shape
-follows the delivery table in the implementation RFC, which is not settled, and the null
-implementation lets a transport ship without waiting on it.
+handle from that first send. The store holds that handle, and holds what makes a redelivery
+safe: no provider offers an idempotency key, so a send a crash left unrecorded repeats on
+retry unless the row says it already happened.
The key carries the firing as well, which the RFC's own shape does not. Without it the table
holds one row per alert instead of one per firing, and there is no version of that decision
@@ -14,12 +14,24 @@ ships, and fan-in was deprioritized on 2026-09-28, so the group is what identifi
conversation until then.
"""
-from datetime import datetime
+from datetime import datetime, timedelta
from typing import Protocol
+from django.db import models
+from django.utils import timezone
+
from posthog.dataclasses import frozen
from products.alerts.backend.delivery.transport import MessageHandle
+from products.alerts.backend.models import PlatformAlertThread
+
+# How long a send may hold a conversation before another attempt may take it. Long enough to
+# cover a provider's own timeout, so a retry that starts while the first attempt is still
+# posting waits rather than posting a second copy.
+PENDING_CLAIM_TTL = timedelta(minutes=2)
+
+# A thread lives as long as its firing, and the list only has to outlive a retry.
+DELIVERED_KEYS_CAP = 20
@frozen
@@ -42,21 +54,116 @@ class ThreadKey:
episode_started_at: datetime
+@frozen
+class ThreadClaim:
+ """A conversation held for the duration of one send.
+
+ `handle` is what to reply to, and is None when this send opens the conversation.
+ `claimed_at` fences the release: an attempt that outlived the TTL and was superseded must
+ not clear its successor's claim or record its own send over the successor's.
+ """
+
+ thread_id: str
+ evaluation_key: str
+ handle: MessageHandle | None
+ claimed_at: datetime
+
+
+class ThreadBusy(Exception):
+ """Another send holds this conversation and has not finished with it."""
+
+
class ThreadStore(Protocol):
- def handle_for(self, key: ThreadKey) -> MessageHandle | None: ...
+ def claim(self, key: ThreadKey, evaluation_key: str) -> ThreadClaim | None:
+ """Take the conversation for one send, or None when it already carried this evaluation.
+
+ Raises `ThreadBusy` when another send holds it and the hold is still fresh.
+ """
+ ...
+
+ def delivered(self, claim: ThreadClaim, handle: MessageHandle | None) -> None: ...
- def remember(self, key: ThreadKey, handle: MessageHandle) -> None: ...
+ def release(self, claim: ThreadClaim) -> None: ...
class NullThreadStore:
- """Remembers nothing, so every message is a new one.
+ """Remembers nothing, so every message is a new one and no send is ever skipped.
- Not a regression: the platform sends nothing today, so there is no thread to continue. It
- does mean a resolve posts beside the message that fired rather than under it.
+ Not a regression where nothing is wired: the platform sends nothing today. It does mean a
+ resolve posts beside the message that fired rather than under it, and that a retry after a
+ crash sends again.
"""
- def handle_for(self, key: ThreadKey) -> MessageHandle | None:
+ def claim(self, key: ThreadKey, evaluation_key: str) -> ThreadClaim | None:
+ return ThreadClaim(thread_id="", evaluation_key=evaluation_key, handle=None, claimed_at=timezone.now())
+
+ def delivered(self, claim: ThreadClaim, handle: MessageHandle | None) -> None:
return None
- def remember(self, key: ThreadKey, handle: MessageHandle) -> None:
+ def release(self, claim: ThreadClaim) -> None:
return None
+
+
+class DatabaseThreadStore:
+ """`PlatformAlertThread` as the conversation store.
+
+ Three states decide whether a send happens, in this order: already delivered, held by a
+ live claim, free. Reading them in any other order would let a retry of an evaluation that
+ already landed take a claim it does not need.
+ """
+
+ def __init__(self, team_id: int) -> None:
+ self._team_id = team_id
+
+ def claim(self, key: ThreadKey, evaluation_key: str) -> ThreadClaim | None:
+ thread, _ = PlatformAlertThread.objects.for_team(self._team_id).get_or_create(
+ configuration_id=key.configuration_id,
+ grouping_key=key.grouping_key,
+ provider=key.provider,
+ channel_target=key.channel_target,
+ episode_started_at=key.episode_started_at,
+ defaults={"team_id": self._team_id},
+ )
+ if evaluation_key in (thread.delivered_evaluation_keys or []):
+ return None
+
+ 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.
+ 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)
+ )
+ if not taken:
+ raise ThreadBusy(f"thread {thread.id} is being posted to by another send")
+
+ handle = MessageHandle(external_ref=thread.external_ref) if thread.external_ref else None
+ return ThreadClaim(thread_id=str(thread.id), evaluation_key=evaluation_key, handle=handle, claimed_at=now)
+
+ def delivered(self, claim: ThreadClaim, handle: MessageHandle | None) -> None:
+ thread = PlatformAlertThread.objects.for_team(self._team_id).filter(id=claim.thread_id).first()
+ if thread is None:
+ return
+ delivered = [*(thread.delivered_evaluation_keys or []), claim.evaluation_key][-DELIVERED_KEYS_CAP:]
+ fields: dict[str, object] = {
+ "delivered_evaluation_keys": delivered,
+ "pending_evaluation_key": None,
+ "pending_claimed_at": None,
+ }
+ # 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.
+ if handle is not None and not thread.external_ref:
+ fields["external_ref"] = handle.external_ref
+ self._fenced(claim).update(**fields)
+
+ def release(self, claim: ThreadClaim) -> None:
+ self._fenced(claim).update(pending_evaluation_key=None, pending_claimed_at=None)
+
+ def _fenced(self, claim: ThreadClaim) -> models.QuerySet[PlatformAlertThread]:
+ return PlatformAlertThread.objects.for_team(self._team_id).filter(
+ id=claim.thread_id, pending_claimed_at=claim.claimed_at
+ )
diff --git a/products/alerts/backend/migrations/0011_platformalertthread.py b/products/alerts/backend/migrations/0011_platformalertthread.py
new file mode 100644
index 000000000000..713297fc8699
--- /dev/null
+++ b/products/alerts/backend/migrations/0011_platformalertthread.py
@@ -0,0 +1,77 @@
+# Generated by Django 5.2.17 on 2026-10-01 23:17
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("alerts", "0010_alertconfiguration_evaluation_delay_intervals"),
+ ("posthog", "1391_organization_provisioning"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="PlatformAlertThread",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "grouping_key",
+ models.CharField(db_default="", default="", max_length=255),
+ ),
+ ("provider", models.CharField(max_length=32)),
+ ("channel_target", models.CharField(max_length=255)),
+ ("episode_started_at", models.DateTimeField()),
+ ("external_ref", models.JSONField(default=dict)),
+ ("delivered_evaluation_keys", models.JSONField(default=list)),
+ (
+ "pending_evaluation_key",
+ models.CharField(blank=True, max_length=255, null=True),
+ ),
+ ("pending_claimed_at", models.DateTimeField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "configuration",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="threads",
+ to="alerts.platformalertconfiguration",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ fields=(
+ "configuration",
+ "grouping_key",
+ "provider",
+ "channel_target",
+ "episode_started_at",
+ ),
+ name="platform_alert_thread_one_per_conversation",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/alerts/backend/migrations/max_migration.txt b/products/alerts/backend/migrations/max_migration.txt
index 0fae3069f5e3..c57484510afe 100644
--- a/products/alerts/backend/migrations/max_migration.txt
+++ b/products/alerts/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0010_alertconfiguration_evaluation_delay_intervals
+0011_platformalertthread
diff --git a/products/alerts/backend/models/__init__.py b/products/alerts/backend/models/__init__.py
index c9dec6f66540..9f06e91b7c63 100644
--- a/products/alerts/backend/models/__init__.py
+++ b/products/alerts/backend/models/__init__.py
@@ -1,5 +1,5 @@
from .alert import Alert, AlertCheck, AlertConfiguration, AlertSubscription, Threshold
-from .platform_alert import PlatformAlert, PlatformAlertConfiguration
+from .platform_alert import PlatformAlert, PlatformAlertConfiguration, PlatformAlertThread
__all__ = [
"Alert",
@@ -8,5 +8,6 @@ __all__ = [
"AlertSubscription",
"PlatformAlert",
"PlatformAlertConfiguration",
+ "PlatformAlertThread",
"Threshold",
]
diff --git a/products/alerts/backend/models/platform_alert.py b/products/alerts/backend/models/platform_alert.py
index 64eb8bd183a1..fc9ffd8b4249 100644
--- a/products/alerts/backend/models/platform_alert.py
+++ b/products/alerts/backend/models/platform_alert.py
@@ -104,3 +104,50 @@ class PlatformAlert(TeamScopedRootMixin, UUIDModel):
constraints = [
models.UniqueConstraint(fields=["configuration", "grouping_key"], name="platform_alert_one_per_group")
]
+
+
+class PlatformAlertThread(TeamScopedRootMixin, UUIDModel):
+ """One provider conversation, and what has already been said in it.
+
+ A resolve replies under the message that fired, which needs the handle from that first send.
+ One row is one conversation: the configuration, the group, the provider and the channel it
+ posts to, plus the firing it belongs to. Without the firing a thread would span every
+ incident an alert ever had; without the group two groups would share one.
+
+ It also carries what makes a redelivery safe. A send that a crash left unrecorded repeats
+ on retry, because no provider offers an idempotency key, so the row holds who has already
+ been delivered and who is mid-send right now.
+ """
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
+ configuration = models.ForeignKey(PlatformAlertConfiguration, on_delete=models.CASCADE, related_name="threads")
+
+ grouping_key = models.CharField(max_length=255, default="", db_default="")
+ provider = models.CharField(max_length=32)
+ # A repointed destination gives a different answer, which stops a reply going to the old place.
+ channel_target = models.CharField(max_length=255)
+ episode_started_at = models.DateTimeField()
+
+ # The provider's own handle, `{"channel": ..., "ts": ...}` for Slack. Opaque to everything
+ # but the transport that issued it.
+ external_ref = models.JSONField(default=dict)
+
+ # Evaluations already delivered into this conversation, newest last. Capped, because a
+ # thread lives as long as its firing and the list only has to outlive a retry.
+ delivered_evaluation_keys = models.JSONField(default=list)
+
+ # A send in flight. Held for `PENDING_CLAIM_TTL` so a retry that starts while the first
+ # attempt is still mid-post waits rather than posting a second copy.
+ pending_evaluation_key = models.CharField(max_length=255, null=True, blank=True)
+ pending_claimed_at = models.DateTimeField(null=True, blank=True)
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=["configuration", "grouping_key", "provider", "channel_target", "episode_started_at"],
+ name="platform_alert_thread_one_per_conversation",
+ )
+ ]
diff --git a/products/alerts/backend/test/test_delivery_dispatch.py b/products/alerts/backend/test/test_delivery_dispatch.py
index 5884c8fcb0bb..6ea74f53dc49 100644
--- a/products/alerts/backend/test/test_delivery_dispatch.py
+++ b/products/alerts/backend/test/test_delivery_dispatch.py
@@ -5,11 +5,12 @@ import pytest
from unittest.mock import patch
from django.test import SimpleTestCase
+from django.utils import timezone
from products.alerts.backend.delivery.dispatch import deliver
from products.alerts.backend.delivery.message import AlertMessage
from products.alerts.backend.delivery.telemetry import record_delivery
-from products.alerts.backend.delivery.thread_store import NullThreadStore, ThreadKey
+from products.alerts.backend.delivery.thread_store import NullThreadStore, ThreadClaim, ThreadKey
from products.alerts.backend.delivery.transport import DeliveryError, MessageHandle
from products.alerts.backend.facade.contracts import (
AlertDestinationData,
@@ -75,12 +76,26 @@ class RecordingThreadStore(NullThreadStore):
def __init__(self) -> None:
self.threads: dict[ThreadKey, MessageHandle] = {}
+ self.delivered_keys: dict[ThreadKey, list[str]] = {}
+ self._claimed: dict[str, ThreadKey] = {}
+
+ def claim(self, key: ThreadKey, evaluation_key: str) -> ThreadClaim | None:
+ if evaluation_key in self.delivered_keys.get(key, []):
+ return None
+ thread_id = str(len(self._claimed))
+ self._claimed[thread_id] = key
+ return ThreadClaim(
+ thread_id=thread_id,
+ evaluation_key=evaluation_key,
+ handle=self.threads.get(key),
+ claimed_at=timezone.now(),
+ )
- def handle_for(self, key: ThreadKey) -> MessageHandle | None:
- return self.threads.get(key)
-
- def remember(self, key: ThreadKey, handle: MessageHandle) -> None:
- self.threads[key] = handle
+ def delivered(self, claim: ThreadClaim, handle: MessageHandle | None) -> None:
+ key = self._claimed[claim.thread_id]
+ self.delivered_keys.setdefault(key, []).append(claim.evaluation_key)
+ if handle is not None and key not in self.threads:
+ self.threads[key] = handle
@property
def remembered(self) -> list[MessageHandle]:
@@ -88,13 +103,16 @@ class RecordingThreadStore(NullThreadStore):
class TestDeliveryDispatch(SimpleTestCase):
- def _deliver(self, transport: FakeTransport, store: Any, announcement: Any = None) -> Any:
+ def _deliver(
+ self, transport: FakeTransport, store: Any, announcement: Any = None, evaluation_key: str = "eval-1"
+ ) -> Any:
with patch("products.alerts.backend.delivery.dispatch.record_delivery") as recorded:
deliver(
transport=transport,
thread_store=store,
team_id=2,
configuration_id="cfg-1",
+ evaluation_key=evaluation_key,
target=TARGET,
announcement=announcement or _announcement(),
)
@@ -118,6 +136,7 @@ class TestDeliveryDispatch(SimpleTestCase):
thread_store=NullThreadStore(),
team_id=2,
configuration_id="cfg-1",
+ evaluation_key="eval-1",
target=TARGET,
announcement=_announcement(),
)
@@ -127,13 +146,13 @@ class TestDeliveryDispatch(SimpleTestCase):
def test_a_resolve_replies_under_its_own_firing_rather_than_an_earlier_one(self) -> None:
store = RecordingThreadStore()
first = FakeTransport(handle=MessageHandle(external_ref={"ts": "morning"}))
- self._deliver(first, store, _announcement(AlertEventKind.FIRING, FIRST_FIRING))
+ self._deliver(first, store, _announcement(AlertEventKind.FIRING, FIRST_FIRING), "eval-1")
resolve = FakeTransport(handle=MessageHandle(external_ref={"ts": "resolve"}))
- self._deliver(resolve, store, _announcement(AlertEventKind.RESOLVED, FIRST_FIRING))
+ self._deliver(resolve, store, _announcement(AlertEventKind.RESOLVED, FIRST_FIRING), "eval-2")
second = FakeTransport(handle=MessageHandle(external_ref={"ts": "evening"}))
- self._deliver(second, store, _announcement(AlertEventKind.FIRING, SECOND_FIRING))
+ self._deliver(second, store, _announcement(AlertEventKind.FIRING, SECOND_FIRING), "eval-3")
assert [handle for _, handle in resolve.sends] == [MessageHandle(external_ref={"ts": "morning"})]
assert [handle for _, handle in second.sends] == [None]
@@ -152,6 +171,15 @@ class TestDeliveryDispatch(SimpleTestCase):
assert [handle for _, handle in transport.sends] == [None, None]
assert len(store.threads) == 2
+ def test_a_retried_evaluation_does_not_send_a_second_copy(self) -> None:
+ store = RecordingThreadStore()
+ self._deliver(FakeTransport(), store, evaluation_key="eval-1")
+
+ retry = FakeTransport()
+ self._deliver(retry, store, evaluation_key="eval-1")
+
+ assert retry.sends == []
+
def test_a_check_that_never_fired_starts_no_conversation(self) -> None:
store = RecordingThreadStore()
transport = FakeTransport()
@@ -170,6 +198,7 @@ class TestDeliveryDispatch(SimpleTestCase):
thread_store=NullThreadStore(),
team_id=2,
configuration_id="cfg-1",
+ evaluation_key="eval-1",
target=TARGET,
announcement=_announcement(),
)
diff --git a/products/alerts/backend/test/test_delivery_thread_store.py b/products/alerts/backend/test/test_delivery_thread_store.py
new file mode 100644
index 000000000000..47dd25a67a43
--- /dev/null
+++ b/products/alerts/backend/test/test_delivery_thread_store.py
@@ -0,0 +1,107 @@
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from posthog.test.base import APIBaseTest
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models.scoping import team_scope
+
+from products.alerts.backend.delivery.thread_store import PENDING_CLAIM_TTL, DatabaseThreadStore, ThreadBusy, ThreadKey
+from products.alerts.backend.delivery.transport import MessageHandle
+from products.alerts.backend.models import PlatformAlertConfiguration, PlatformAlertThread
+
+FIRING = datetime(2026, 9, 30, 9, tzinfo=UTC)
+
+
+class TestDatabaseThreadStore(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ with team_scope(self.team.id):
+ self.configuration = PlatformAlertConfiguration.objects.create(
+ team=self.team,
+ name="API errors",
+ source_kind=PlatformAlertConfiguration.SourceKind.LOGS,
+ source_config={},
+ threshold_count=10,
+ threshold_operator="above",
+ window_minutes=5,
+ check_interval_minutes=10,
+ )
+ self.store = DatabaseThreadStore(self.team.id)
+
+ def _key(self, grouping_key: str = "", episode: datetime = FIRING) -> ThreadKey:
+ return ThreadKey(
+ configuration_id=str(self.configuration.id),
+ grouping_key=grouping_key,
+ provider="slack",
+ channel_target="C-ENG",
+ episode_started_at=episode,
+ )
+
+ def test_an_evaluation_that_already_landed_is_not_sent_again(self) -> None:
+ key = self._key()
+ claim = self.store.claim(key, "eval-1")
+ assert claim is not None
+ self.store.delivered(claim, MessageHandle(external_ref={"channel": "C-ENG", "ts": "1"}))
+
+ assert self.store.claim(key, "eval-1") is None
+
+ def test_a_later_evaluation_replies_to_the_message_that_opened_the_thread(self) -> None:
+ key = self._key()
+ opener = self.store.claim(key, "eval-1")
+ assert opener is not None
+ self.store.delivered(opener, MessageHandle(external_ref={"channel": "C-ENG", "ts": "1"}))
+
+ resolve = self.store.claim(key, "eval-2")
+ assert resolve is not None
+ assert resolve.handle == MessageHandle(external_ref={"channel": "C-ENG", "ts": "1"})
+
+ # A reply's own handle must not replace the root's, or the next message would reply to
+ # a reply and the conversation would walk away from where it started.
+ self.store.delivered(resolve, MessageHandle(external_ref={"channel": "C-ENG", "ts": "2"}))
+ third = self.store.claim(key, "eval-3")
+ assert third is not None
+ assert third.handle == MessageHandle(external_ref={"channel": "C-ENG", "ts": "1"})
+
+ @parameterized.expand([("fresh", timedelta(seconds=1), True), ("stale", PENDING_CLAIM_TTL * 2, False)])
+ def test_a_claim_blocks_another_send_until_it_goes_stale(
+ self, _name: str, age: timedelta, expect_busy: bool
+ ) -> None:
+ key = self._key()
+ first = self.store.claim(key, "eval-1")
+ assert first is not None
+ with team_scope(self.team.id):
+ PlatformAlertThread.objects.filter(id=first.thread_id).update(pending_claimed_at=timezone.now() - age)
+
+ if expect_busy:
+ with pytest.raises(ThreadBusy):
+ self.store.claim(key, "eval-2")
+ else:
+ assert self.store.claim(key, "eval-2") is not None
+
+ 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")
+ assert stalled is not None
+ with team_scope(self.team.id):
+ PlatformAlertThread.objects.filter(id=stalled.thread_id).update(
+ pending_claimed_at=timezone.now() - PENDING_CLAIM_TTL * 2
+ )
+ successor = self.store.claim(key, "eval-2")
+ assert successor is not None
+
+ self.store.release(stalled)
+
+ with team_scope(self.team.id):
+ thread = PlatformAlertThread.objects.get(id=successor.thread_id)
+ assert thread.pending_evaluation_key == "eval-2"
+
+ def test_two_groups_of_one_configuration_get_their_own_rows(self) -> None:
+ checkout = self.store.claim(self._key(grouping_key="checkout"), "eval-1")
+ search = self.store.claim(self._key(grouping_key="search"), "eval-1")
+
+ assert checkout is not None and search is not None
+ assert checkout.thread_id != search.thread_id