: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(error_tracking): deliver alert notifications as slack threads (#92051)
Catalin8d940977d82a
diff --git a/products/error_tracking/backend/logic/lifecycle_events.py b/products/error_tracking/backend/logic/lifecycle_events.pyindex 2636175b5f81..017c400ff193 100644--- a/products/error_tracking/backend/logic/lifecycle_events.py+++ b/products/error_tracking/backend/logic/lifecycle_events.py@@ -157,6 +157,12 @@ def prepare_issue_lifecycle_event(status_property = properties.get("status")assignee_property_value = properties.get("assignee")+ # Notifications only need counts; the id lists stay on the internal event.+ delivery_extra: dict[str, str] = {}+ for id_list_key, count_key in (("merged_issue_ids", "merged_count"), ("split_issue_ids", "split_count")):+ id_list = properties.get(id_list_key)+ if isinstance(id_list, list):+ delivery_extra[count_key] = str(len(id_list))alert_inputs = AlertDeliveryWorkflowInputs.build(notification_id=notification_id,team_id=team_id,@@ -167,6 +173,7 @@ def prepare_issue_lifecycle_event(status=status_property if isinstance(status_property, str) else None,assignee=assignee_property_value if isinstance(assignee_property_value, str) else None,actor_email=actor_email,+ extra=delivery_extra or None,)return PendingLifecycleEvent(team_id=team_id, internal_event=internal_event, person=person, alert_inputs=alert_inputsdiff --git a/products/error_tracking/backend/migrations/0040_errortrackingalertthread_pending_claim.py b/products/error_tracking/backend/migrations/0040_errortrackingalertthread_pending_claim.pynew file mode 100644index 000000000000..6fe90f45fb60--- /dev/null+++ b/products/error_tracking/backend/migrations/0040_errortrackingalertthread_pending_claim.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.17 on 2026-09-02 11:17++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("error_tracking", "0039_drop_superseded_fingerprint_constraint"),+ ]++ operations = [+ migrations.AddField(+ model_name="errortrackingalertthread",+ name="pending_claimed_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="errortrackingalertthread",+ name="pending_notification_id",+ field=models.CharField(blank=True, max_length=64, null=True),+ ),+ ]diff --git a/products/error_tracking/backend/migrations/max_migration.txt b/products/error_tracking/backend/migrations/max_migration.txtindex af78bf55bb8d..0a0330dce35d 100644--- a/products/error_tracking/backend/migrations/max_migration.txt+++ b/products/error_tracking/backend/migrations/max_migration.txt@@ -1 +1 @@-0039_drop_superseded_fingerprint_constraint+0040_errortrackingalertthread_pending_claimdiff --git a/products/error_tracking/backend/models.py b/products/error_tracking/backend/models.pyindex cb382c8528e8..e3f97c489e50 100644--- a/products/error_tracking/backend/models.py+++ b/products/error_tracking/backend/models.py@@ -973,9 +973,9 @@ class ErrorTrackingAlertThread(TeamScopedRootMixin, UUIDTModel):Maps an issue to the externally posted notification (e.g. a Slack message) solifecycle updates can be delivered as replies to the original message instead- of new fire-and-forget notifications. The unique constraint is the concurrency- primitive: concurrent deliveries race on the insert and the loser reuses the- winner's thread.+ of new fire-and-forget notifications. The unique constraint dedupes the row;+ `pending_notification_id` is the send claim: concurrent deliveries serialize on+ it so only one posts at a time, and the loser retries into the winner's thread."""team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)@@ -990,6 +990,10 @@ class ErrorTrackingAlertThread(TeamScopedRootMixin, UUIDTModel):# UUIDs of recently delivered lifecycle notifications (newest last, capped by the# delivery activity) so Temporal retries don't duplicate notifications.delivered_notification_ids = models.JSONField(default=list, blank=True)+ # Notification currently posting to this thread, with the claim time so a holder+ # that died before saving is treated as stale instead of wedging the thread.+ pending_notification_id = models.CharField(max_length=64, 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)diff --git a/products/error_tracking/backend/temporal/alerts/activities.py b/products/error_tracking/backend/temporal/alerts/activities.pyindex 8d18e585cb99..c81d1cdbd509 100644--- a/products/error_tracking/backend/temporal/alerts/activities.py+++ b/products/error_tracking/backend/temporal/alerts/activities.py@@ -1,17 +1,23 @@import posthoganalyticsfrom temporalio import activity+from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.common.utils import close_db_connections-from products.error_tracking.backend.temporal.alerts.delivery import deliver_alert_notifications-from products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputs+from products.error_tracking.backend.temporal.alerts.delivery import AlertThreadBusyError, deliver_alert_notifications+from products.error_tracking.backend.temporal.alerts.types import THREAD_BUSY_ERROR_TYPE, AlertDeliveryWorkflowInputs@activity.defn@posthoganalytics.scoped()@close_db_connectionsdef deliver_alert_notifications_activity(inputs: AlertDeliveryWorkflowInputs) -> int:- return deliver_alert_notifications(inputs)+ try:+ return deliver_alert_notifications(inputs)+ except AlertThreadBusyError as error:+ # Non-retryable here so contention never spends the activity's failure budget;+ # the workflow waits and schedules the activity again.+ raise ApplicationError(str(error), type=THREAD_BUSY_ERROR_TYPE, non_retryable=True) from errorACTIVITIES = [deliver_alert_notifications_activity]diff --git a/products/error_tracking/backend/temporal/alerts/delivery.py b/products/error_tracking/backend/temporal/alerts/delivery.pyindex d32deea70e6e..ddb6b47d0e79 100644--- a/products/error_tracking/backend/temporal/alerts/delivery.py+++ b/products/error_tracking/backend/temporal/alerts/delivery.py@@ -1,22 +1,43 @@-"""Alert delivery planning: which alert destinations a lifecycle transition reaches.+"""Alert delivery: one Slack thread per (alert, issue, destination).Triggers gate thread openers only. A transition whose event satisfies one of an-alert's triggers opens a notification thread per destination; every other-lifecycle event is delivered as a reply to an existing thread, without a second-trigger evaluation. The alert's stored filters are evaluated by the follow-up-filter-evaluation layer before openers actually send; until then the planner is-trigger-only and runs dark. Actual channel delivery (Slack threads) also lands in-a follow-up; this module currently records the plan and returns the match count.+alert's triggers opens a notification thread per destination: a root Slack+message whose `ts` is stored on the thread row. Every other lifecycle event is+delivered as a reply into that thread, without a second trigger evaluation, and+status transitions also edit the root in place.++Delivery is at-least-once. A per-thread send claim serializes concurrent+deliveries so two notifications never post at the same time (the loser retries+into the winner's thread), and delivered notification ids recorded on the row make+a retry after a successful save a no-op. A crash between the Slack post and that+save still re-posts on retry. The alert's stored filters are evaluated by the+follow-up filter-evaluation layer before openers actually send; until then+delivery is trigger-only."""import dataclasses+from datetime import datetime, timedelta++from django.db import IntegrityError+from django.db.models import Q+from django.utils import timezoneimport structlog+from slack_sdk import WebClient++from posthog.models.integration import Integration, SlackIntegrationfrom products.error_tracking.backend.models import (ErrorTrackingAlert,ErrorTrackingAlertDestination,ErrorTrackingAlertThread,+ ErrorTrackingIssue,+)+from products.error_tracking.backend.temporal.alerts.messages import (+ DEFAULT_HEADLINE,+ build_reply_text,+ build_root_edit,+ build_root_message,)from products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputs@@ -31,6 +52,23 @@ OPENER_TRIGGERS = {"$error_tracking_issue_assigned": ErrorTrackingAlert.Trigger.ISSUE_ASSIGNED,}+DELIVERED_NOTIFICATION_IDS_CAP = 200+# A send claim older than this belongs to a holder that died between posting and+# saving; the next delivery takes over. A live holder makes at most two Slack calls+# per thread (post, then root edit); each is up to two 30s attempts under the SDK's+# default connection-error retry, so ~130s worst case, and 240s cannot expire under+# a live holder. It must stay shorter than the workflow's busy wait (workflow.py)+# so a busy loser is still waiting when it expires.+PENDING_CLAIM_TTL = timedelta(seconds=240)+++class AlertThreadBusyError(Exception):+ """Another notification holds this thread's send claim; retry after it saves."""+++class AlertDeliveryError(Exception):+ pass+@dataclasses.dataclass(frozen=True)class PlannedDelivery:@@ -46,7 +84,11 @@ def plan_alert_deliveries(inputs: AlertDeliveryWorkflowInputs) -> list[PlannedDetrigger = OPENER_TRIGGERS.get(inputs.event)alerts = list(ErrorTrackingAlert.objects.for_team(inputs.team_id).filter(enabled=True))destinations_by_alert: dict = {}- for destination in ErrorTrackingAlertDestination.objects.for_team(inputs.team_id).filter(alert__in=alerts):+ for destination in (+ ErrorTrackingAlertDestination.objects.for_team(inputs.team_id)+ .filter(alert__in=alerts)+ .select_related("integration")+ ):destinations_by_alert.setdefault(destination.alert_id, []).append(destination)# Threads are unique per (alert, issue, destination): a multi-destination alert# holds one independent conversation per destination.@@ -58,6 +100,11 @@ def plan_alert_deliveries(inputs: AlertDeliveryWorkflowInputs) -> list[PlannedDeplanned: list[PlannedDelivery] = []for alert in alerts:trigger_matched = trigger is not None and trigger in alert.triggers+ if trigger_matched and _has_configured_filters(alert):+ # Until the filter-evaluation layer lands, alerts with configured+ # filters never open threads: missing an opener is better than posting+ # issues the user filtered out.+ trigger_matched = Falsefor destination in destinations_by_alert.get(alert.id, []):thread = threads_by_destination.get(destination.id)if thread is None and not trigger_matched:@@ -65,27 +112,260 @@ def plan_alert_deliveries(inputs: AlertDeliveryWorkflowInputs) -> list[PlannedDe# unclaimed so a later opener can still start the conversation cleanly.continue# Only the first matching transition opens; once a destination has a- # thread, every later transition is a reply into it, even a repeated- # opener event (e.g. spiking again, or reopen after resolve).- is_opener = trigger_matched and thread is None+ # rooted thread, every later transition is a reply into it, even a+ # repeated opener event (e.g. spiking again, or reopen after resolve).+ # An unrooted row is a failed root post: the next opener roots it.+ rooted = thread is not None and bool(thread.external_ref.get("ts"))+ is_opener = trigger_matched and not rootedplanned.append(PlannedDelivery(alert=alert, destination=destination, is_opener=is_opener, thread=thread))return planned+def _has_configured_filters(alert: ErrorTrackingAlert) -> bool:+ # Empty filters still carry trivially-true compiled bytecode, so look at the+ # configured predicate keys instead.+ filters = alert.filters or {}+ return any(filters.get(key) for key in ("events", "actions", "properties", "filter_test_accounts"))++def deliver_alert_notifications(inputs: AlertDeliveryWorkflowInputs) -> int:planned = plan_alert_deliveries(inputs)+ delivered = 0+ failures = 0+ busy = 0for delivery in planned:- logger.info(- "error_tracking_alert_delivery_planned",- team_id=inputs.team_id,+ try:+ if _deliver_one(delivery, inputs):+ delivered += 1+ except AlertThreadBusyError:+ # Expected contention, not a fault: the workflow waits and runs the+ # activity again once the holder has saved its root.+ logger.info(+ "error_tracking_alert_thread_busy",+ team_id=inputs.team_id,+ alert_id=str(delivery.alert.id),+ destination_id=str(delivery.destination.id),+ issue_id=inputs.issue_id,+ notification_id=inputs.notification_id,+ )+ busy += 1+ except Exception:+ # Give every destination a chance before surfacing the failure to+ # Temporal; the per-notification claim makes the retry safe for the+ # deliveries that already went out.+ logger.exception(+ "error_tracking_alert_delivery_failed",+ team_id=inputs.team_id,+ alert_id=str(delivery.alert.id),+ destination_id=str(delivery.destination.id),+ issue_id=inputs.issue_id,+ lifecycle_event=inputs.event,+ notification_id=inputs.notification_id,+ )+ failures += 1+ if failures:+ raise AlertDeliveryError(f"{failures} of {len(planned)} alert deliveries failed")+ if busy:+ # Only contention left: surfaced as its own error so the wait does not spend+ # the activity's failure budget.+ raise AlertThreadBusyError(f"{busy} of {len(planned)} alert threads are busy")+ return delivered+++def _deliver_one(delivery: PlannedDelivery, inputs: AlertDeliveryWorkflowInputs) -> bool:+ thread = delivery.thread+ if thread is None:+ # Planner guarantee: only openers arrive without a thread. The unique+ # constraint dedupes the row; the insert-race loser reuses the winner's.+ try:+ thread, _ = ErrorTrackingAlertThread.objects.for_team(delivery.alert.team_id, canonical=True).get_or_create(+ alert=delivery.alert,+ issue_id=inputs.issue_id,+ destination=delivery.destination,+ defaults={"team_id": delivery.alert.team_id},+ )+ except IntegrityError:+ # The issue row is gone (merged away or deleted): nothing to alert on.+ return False++ # A redelivered notification (activity retry, duplicate start) needs no claim:+ # it never contends with the holder for work it already finished.+ thread.refresh_from_db(fields=["delivered_notification_ids"])+ if inputs.notification_id in (thread.delivered_notification_ids or []):+ return False+ # Likewise a reply with nothing to say (a replayed created event on a rooted thread).+ if not delivery.is_opener and build_reply_text(inputs) is None:+ return False++ client = _slack_client(delivery.destination)+ if client is None:+ # A revoked or repointed integration is a configuration gap, not a+ # transient failure: retries cannot fix it, so skip without raising.+ # Per-destination failure records land in the follow-up outcomes layer.+ logger.warning(+ "error_tracking_alert_destination_unusable",+ team_id=delivery.alert.team_id,alert_id=str(delivery.alert.id),destination_id=str(delivery.destination.id),- issue_id=inputs.issue_id,- lifecycle_event=inputs.event,+ )+ return False++ claimed_at = _claim_thread(thread, inputs)+ try:+ # Everything below reads row state written by whoever held the claim last.+ thread.refresh_from_db()+ posted = _post_claimed(client, thread, delivery, inputs, claimed_at)+ except Exception:+ # A failed post frees the thread for whoever comes next; this notification's+ # retry then lands wherever the thread is by that time.+ _release_thread(thread, inputs, claimed_at)+ raise+ if not posted:+ _release_thread(thread, inputs, claimed_at)+ return posted+++def _post_claimed(+ client: WebClient,+ thread: ErrorTrackingAlertThread,+ delivery: PlannedDelivery,+ inputs: AlertDeliveryWorkflowInputs,+ claimed_at: datetime,+) -> bool:+ if inputs.notification_id in (thread.delivered_notification_ids or []):+ return False++ external_ref = thread.external_ref+ root_headline = thread.root_headline+ if not external_ref.get("ts"):+ if not delivery.is_opener:+ # The row exists but was never rooted (a previous root post failed):+ # leave this notification undelivered so a later opener still roots.+ return False+ channel = delivery.destination.config.get("channel")+ if not channel:+ return False+ # Transitions run as independent workflows, so a later one (resolved, assigned)+ # can land before the opener: the root shows the issue row as it is now, not+ # as the opener's payload saw it.+ root_inputs = _with_current_status(inputs)+ message = build_root_message(root_inputs)+ response = client.chat_postMessage(channel=channel, blocks=message["blocks"], text=message["text"])+ external_ref = {"channel": response["channel"], "ts": response["ts"], "root_status": root_inputs.status}+ root_headline = message["headline"]+ else:+ reply = build_reply_text(inputs)+ if reply is None:+ return False+ # Replies stay in the thread's own channel: a provider thread cannot move,+ # so a repointed destination only applies to newly opened threads.+ client.chat_postMessage(channel=external_ref["channel"], thread_ts=external_ref["ts"], text=reply)+ external_ref = _reconcile_root_status(client, thread, inputs)++ delivered_ids = [*(thread.delivered_notification_ids or []), inputs.notification_id][+ -DELIVERED_NOTIFICATION_IDS_CAP:+ ]+ # Fenced on the claim time: a holder that outlived the TTL and was superseded+ # must not overwrite the successor's state or clear the successor's claim.+ finalized = (+ ErrorTrackingAlertThread.objects.for_team(thread.team_id, canonical=True)+ .filter(id=thread.id, pending_notification_id=inputs.notification_id, pending_claimed_at=claimed_at)+ .update(+ external_ref=external_ref,+ root_headline=root_headline,+ delivered_notification_ids=delivered_ids,+ pending_notification_id=None,+ pending_claimed_at=None,+ updated_at=timezone.now(),+ )+ )+ if not finalized:+ logger.warning(+ "error_tracking_alert_thread_claim_superseded",+ thread_id=str(thread.id),notification_id=inputs.notification_id,- is_opener=delivery.is_opener,- has_thread=delivery.thread is not None,)- # No channel delivery yet: the count reports matched destinations so the dark- # wiring is observable end to end.- return len(planned)+ return True+++def _claim_thread(thread: ErrorTrackingAlertThread, inputs: AlertDeliveryWorkflowInputs) -> datetime:+ now = timezone.now()+ claimed = (+ ErrorTrackingAlertThread.objects.for_team(thread.team_id, canonical=True)+ .filter(id=thread.id)+ # A live claim is busy for everyone, this notification's own retry included:+ # a timed-out attempt may still be mid-post when Temporal starts the retry.+ # The retry of a holder that crashed waits for the claim to go stale instead.+ .filter(Q(pending_notification_id__isnull=True) | Q(pending_claimed_at__lt=now - PENDING_CLAIM_TTL))+ .update(pending_notification_id=inputs.notification_id, pending_claimed_at=now)+ )+ if not claimed:+ raise AlertThreadBusyError(f"thread {thread.id} is being posted to by another notification")+ return now+++def _release_thread(+ thread: ErrorTrackingAlertThread, inputs: AlertDeliveryWorkflowInputs, claimed_at: datetime+) -> None:+ # Fenced like the finalize: a newer attempt of the same notification may have+ # re-claimed, and this attempt must not release on its behalf.+ ErrorTrackingAlertThread.objects.for_team(thread.team_id, canonical=True).filter(+ id=thread.id, pending_notification_id=inputs.notification_id, pending_claimed_at=claimed_at+ ).update(pending_notification_id=None, pending_claimed_at=None)+++def _with_current_status(inputs: AlertDeliveryWorkflowInputs) -> AlertDeliveryWorkflowInputs:+ status = (+ ErrorTrackingIssue.objects.filter(id=inputs.issue_id, team_id=inputs.team_id)+ .values_list("status", flat=True)+ .first()+ )+ if status is None:+ return inputs+ try:+ label = str(ErrorTrackingIssue.Status(status).label)+ except ValueError:+ label = status+ return dataclasses.replace(inputs, status=label)+++def _reconcile_root_status(+ client: WebClient, thread: ErrorTrackingAlertThread, inputs: AlertDeliveryWorkflowInputs+) -> dict:+ """Edit the root's status line whenever it differs from the issue row's status.++ Every reply checks, not only status transitions: a root edit that failed on the+ resolve heals on the next assignment or spike instead of staying stale for good.+ The row is the reference, not the reply's payload: transitions arrive out of+ order, and a delayed assignment must not flip a resolved root back to Active.+ The headline never changes on edit: it is the thread's identity.+ """+ external_ref = thread.external_ref+ inputs = _with_current_status(inputs)+ if not inputs.status or inputs.status == external_ref.get("root_status"):+ return external_ref+ message = build_root_edit(inputs, headline=thread.root_headline or DEFAULT_HEADLINE)+ try:+ client.chat_update(+ channel=external_ref["channel"],+ ts=external_ref["ts"],+ blocks=message["blocks"],+ text=message["text"],+ )+ except Exception:+ # The threaded reply already delivered the update; the stale status line is+ # retried by the next reply, so it never fails the delivery.+ logger.exception(+ "error_tracking_alert_root_edit_failed",+ thread_id=str(thread.id),+ lifecycle_event=inputs.event,+ )+ return external_ref+ return {**external_ref, "root_status": inputs.status}+++def _slack_client(destination: ErrorTrackingAlertDestination) -> WebClient | None:+ integration = destination.integration+ if integration is None or integration.kind != Integration.IntegrationKind.SLACK:+ return None+ return SlackIntegration(integration).clientdiff --git a/products/error_tracking/backend/temporal/alerts/messages.py b/products/error_tracking/backend/temporal/alerts/messages.pynew file mode 100644index 000000000000..f92e910aaddf--- /dev/null+++ b/products/error_tracking/backend/temporal/alerts/messages.py@@ -0,0 +1,156 @@+"""Slack message shapes for alert notifications.++Issue names and descriptions come from exception data, so they are attacker+controlled: render them only inside `plain_text` blocks, and escape anything+interpolated into mrkdwn text.+"""++from django.conf import settings++from products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputs++ROOT_HEADLINES = {+ "$error_tracking_issue_created": "🔴 New issue",+ "$error_tracking_issue_reopened": "🔄 Issue reopened",+ "$error_tracking_issue_spiking": "📈 Issue spiking",+ "$error_tracking_issue_assigned": "👤 Issue assigned",+}+DEFAULT_HEADLINE = "🔴 Issue alert"++# Slack rejects header blocks whose complete text exceeds 150 characters, so the+# headline and title are truncated as one composed string.+MAX_HEADER_LENGTH = 150+MAX_DESCRIPTION_LENGTH = 500+++def escape_slack_text(text: str) -> str:+ return text.replace("&", "&").replace("<", "<").replace(">", ">")+++def _truncate(text: str, limit: int) -> str:+ return text if len(text) <= limit else text[: limit - 1] + "…"+++def issue_url(team_id: int, issue_id: str) -> str:+ return f"{settings.SITE_URL}/project/{team_id}/error_tracking/{issue_id}"+++def root_headline(event: str) -> str:+ return ROOT_HEADLINES.get(event, DEFAULT_HEADLINE)+++def _number(value: str | None) -> float | None:+ try:+ return float(value) if value is not None else None+ except ValueError:+ return None+++def spike_summary(extra: dict[str, str] | None) -> str | None:+ """Shared by the spiking root and reply so both surfaces describe the spike the same way."""+ current = _number((extra or {}).get("current_bucket_value"))+ if current is None or current <= 0:+ return None+ # The detector reports a zero baseline when the issue has no history yet; that is+ # a missing comparison, not a real baseline to compare against.+ baseline = _number((extra or {}).get("computed_baseline"))+ if baseline is None or baseline <= 0:+ return f"{current:g} events in the last window, no baseline yet"+ return f"{current:g} events in the last window vs baseline {baseline:g}"+++def _link_block(inputs: AlertDeliveryWorkflowInputs) -> dict:+ return {+ "type": "actions",+ "block_id": f"error_tracking_issue_actions:{inputs.issue_id}",+ "elements": [+ {+ "type": "button",+ "text": {"type": "plain_text", "text": "View issue", "emoji": True},+ "url": issue_url(inputs.team_id, inputs.issue_id),+ }+ ],+ }+++def _header_text(inputs: AlertDeliveryWorkflowInputs, headline: str) -> str:+ title = inputs.issue_name or "Unknown issue"+ return _truncate(f"{headline}: {title}", MAX_HEADER_LENGTH)+++def _build_blocks(inputs: AlertDeliveryWorkflowInputs, *, headline: str) -> list[dict]:+ blocks: list[dict] = [+ {"type": "header", "text": {"type": "plain_text", "text": _header_text(inputs, headline), "emoji": True}}+ ]+ if inputs.issue_description:+ blocks.append(+ {+ "type": "section",+ "text": {+ "type": "plain_text",+ "text": _truncate(inputs.issue_description, MAX_DESCRIPTION_LENGTH),+ },+ }+ )+ if inputs.status:+ blocks.append(+ {+ "type": "context",+ "elements": [{"type": "mrkdwn", "text": f"Status: {escape_slack_text(inputs.status)}"}],+ }+ )+ if inputs.event == "$error_tracking_issue_spiking":+ summary = spike_summary(inputs.extra)+ if summary:+ blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": summary}]})+ blocks.append(_link_block(inputs))+ return blocks+++def build_root_message(inputs: AlertDeliveryWorkflowInputs) -> dict:+ headline = root_headline(inputs.event)+ return {+ "blocks": _build_blocks(inputs, headline=headline),+ "text": escape_slack_text(_header_text(inputs, headline)),+ "headline": headline,+ }+++def build_root_edit(inputs: AlertDeliveryWorkflowInputs, *, headline: str) -> dict:+ # The headline never changes on edit: it is the thread's identity.+ return {+ "blocks": _build_blocks(inputs, headline=headline),+ "text": escape_slack_text(_header_text(inputs, headline)),+ }+++def build_reply_text(inputs: AlertDeliveryWorkflowInputs) -> str | None:+ by = f" by {escape_slack_text(inputs.actor_email)}" if inputs.actor_email else ""+ extra = inputs.extra or {}+ match inputs.event:+ case "$error_tracking_issue_resolved":+ return f"✅ Resolved{by}"+ case "$error_tracking_issue_suppressed":+ return f"🔇 Suppressed{by}"+ case "$error_tracking_issue_assigned":+ return f"👤 Assigned{by}"+ case "$error_tracking_issue_unassigned":+ return f"👤 Unassigned{by}"+ case "$error_tracking_issue_reopened":+ return f"🔄 Reopened{by}"+ case "$error_tracking_issue_created":+ # A created event can reach an existing thread only as a redelivered+ # opener; the root already tells the story.+ return None+ case "$error_tracking_issue_spiking":+ summary = spike_summary(extra)+ return f"📈 Spiking again: {summary}" if summary else "📈 Spiking again"+ case "$error_tracking_issue_merged":+ merged_count = extra.get("merged_count")+ issues = f"{merged_count} issues" if merged_count and merged_count != "1" else "an issue"+ return f"🔀 Merged {issues} into this issue{by}"+ case "$error_tracking_issue_split":+ split_count = extra.get("split_count")+ issues = f"{split_count} new issues" if split_count and split_count != "1" else "a new issue"+ return f"🔱 Split {issues} out of this issue{by}"+ return Nonediff --git a/products/error_tracking/backend/temporal/alerts/test/__init__.py b/products/error_tracking/backend/temporal/alerts/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/error_tracking/backend/temporal/alerts/test/test_workflow.py b/products/error_tracking/backend/temporal/alerts/test/test_workflow.pynew file mode 100644index 000000000000..01aa726c47bf--- /dev/null+++ b/products/error_tracking/backend/temporal/alerts/test/test_workflow.py@@ -0,0 +1,86 @@+import uuid++import pytest++from temporalio import activity+from temporalio.client import WorkflowFailureError+from temporalio.exceptions import ActivityError, ApplicationError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from products.error_tracking.backend.temporal.alerts.types import (+ THREAD_BUSY_ERROR_TYPE,+ AlertDeliveryWorkflowInputs,+ AlertDeliveryWorkflowResult,+)+from products.error_tracking.backend.temporal.alerts.workflow import ErrorTrackingAlertDeliveryWorkflow+++def _inputs() -> AlertDeliveryWorkflowInputs:+ return AlertDeliveryWorkflowInputs(+ notification_id=str(uuid.uuid4()),+ team_id=1,+ issue_id=str(uuid.uuid4()),+ event="$error_tracking_issue_resolved",+ status="Resolved",+ )+++async def _run(deliver, *, expect_failure: bool = False):+ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as environment:+ async with Worker(+ environment.client,+ task_queue=task_queue,+ workflows=[ErrorTrackingAlertDeliveryWorkflow],+ activities=[deliver],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ handle = await environment.client.start_workflow(+ ErrorTrackingAlertDeliveryWorkflow.run,+ _inputs(),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )+ if expect_failure:+ with pytest.raises(WorkflowFailureError) as raised:+ await handle.result()+ return raised.value+ return await handle.result()+++async def test_busy_thread_is_waited_out_without_spending_activity_attempts() -> None:+ attempts: list[int] = []++ @activity.defn(name="deliver_alert_notifications_activity")+ async def deliver(_: AlertDeliveryWorkflowInputs) -> int:+ # Every call is attempt 1: the wait happens in the workflow, not in the retry policy.+ attempts.append(activity.info().attempt)+ if len(attempts) < 3:+ raise ApplicationError("busy", type=THREAD_BUSY_ERROR_TYPE, non_retryable=True)+ return 1++ result = await _run(deliver)++ assert result == AlertDeliveryWorkflowResult(deliveries=1)+ assert attempts == [1, 1, 1]+++async def test_busy_wait_gives_up_after_its_deadline() -> None:+ calls = 0++ @activity.defn(name="deliver_alert_notifications_activity")+ async def deliver(_: AlertDeliveryWorkflowInputs) -> int:+ nonlocal calls+ calls += 1+ raise ApplicationError("busy", type=THREAD_BUSY_ERROR_TYPE, non_retryable=True)++ failure = await _run(deliver, expect_failure=True)++ assert isinstance(failure.cause, ActivityError)+ assert isinstance(failure.cause.cause, ApplicationError)+ assert failure.cause.cause.type == THREAD_BUSY_ERROR_TYPE+ # Ten minutes of five-second waits, then the busy error surfaces as the workflow failure.+ assert calls > 100diff --git a/products/error_tracking/backend/temporal/alerts/types.py b/products/error_tracking/backend/temporal/alerts/types.pyindex c47361bd2020..c229d87623f8 100644--- a/products/error_tracking/backend/temporal/alerts/types.py+++ b/products/error_tracking/backend/temporal/alerts/types.py@@ -55,6 +55,10 @@ class AlertDeliveryWorkflowInputs:)+# Activity error type the workflow waits on instead of spending activity retries.+THREAD_BUSY_ERROR_TYPE = "AlertThreadBusy"++@dataclasses.dataclass(frozen=True)class AlertDeliveryWorkflowResult:deliveries: int = 0diff --git a/products/error_tracking/backend/temporal/alerts/workflow.py b/products/error_tracking/backend/temporal/alerts/workflow.pyindex 6d878db1ac68..086933849229 100644--- a/products/error_tracking/backend/temporal/alerts/workflow.py+++ b/products/error_tracking/backend/temporal/alerts/workflow.py@@ -1,10 +1,12 @@from datetime import timedeltafrom temporalio import common, workflow+from temporalio.exceptions import ActivityError, ApplicationErrorfrom posthog.temporal.common.base import PostHogWorkflowfrom products.error_tracking.backend.temporal.alerts.types import (+ THREAD_BUSY_ERROR_TYPE,AlertDeliveryWorkflowInputs,AlertDeliveryWorkflowResult,)@@ -12,11 +14,18 @@ from products.error_tracking.backend.temporal.alerts.types import (WORKFLOW_NAME = "error-tracking-alert-delivery"ACTIVITY_RETRY_POLICY = common.RetryPolicy(- initial_interval=timedelta(seconds=2),+ initial_interval=timedelta(seconds=5),+ backoff_coefficient=2.0,maximum_interval=timedelta(seconds=60),- maximum_attempts=5,+ maximum_attempts=10,)ACTIVITY_START_TO_CLOSE_TIMEOUT = timedelta(minutes=5)+# A thread's send claim is held by one notification at a time. Contention is not a+# fault, so it is waited out here instead of spending the activity's retry budget.+# The wait must outlast the claim TTL (delivery.py): a holder that died between+# posting and saving frees the thread only when its claim goes stale.+BUSY_RETRY_DELAY = timedelta(seconds=5)+BUSY_WAIT_LIMIT = timedelta(minutes=10)@workflow.defn(name=WORKFLOW_NAME)@@ -30,10 +39,22 @@ class ErrorTrackingAlertDeliveryWorkflow(PostHogWorkflow):@workflow.runasync def run(self, inputs: AlertDeliveryWorkflowInputs) -> AlertDeliveryWorkflowResult:- deliveries = await workflow.execute_activity(- "deliver_alert_notifications_activity",- inputs,- start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,- retry_policy=ACTIVITY_RETRY_POLICY,- )- return AlertDeliveryWorkflowResult(deliveries=deliveries)+ deadline = workflow.now() + BUSY_WAIT_LIMIT+ while True:+ try:+ deliveries = await workflow.execute_activity(+ "deliver_alert_notifications_activity",+ inputs,+ start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )+ except ActivityError as error:+ if not _is_thread_busy(error) or workflow.now() >= deadline:+ raise+ await workflow.sleep(BUSY_RETRY_DELAY)+ continue+ return AlertDeliveryWorkflowResult(deliveries=deliveries)+++def _is_thread_busy(error: ActivityError) -> bool:+ return isinstance(error.cause, ApplicationError) and error.cause.type == THREAD_BUSY_ERROR_TYPEdiff --git a/products/error_tracking/backend/tests/test_alert_delivery.py b/products/error_tracking/backend/tests/test_alert_delivery.pyindex 26027a10dafc..b17735f6eb74 100644--- a/products/error_tracking/backend/tests/test_alert_delivery.py+++ b/products/error_tracking/backend/tests/test_alert_delivery.py@@ -8,23 +8,34 @@ from posthog.test.base import BaseTestfrom unittest.mock import AsyncMock, MagicMock, patchfrom django.conf import settings+from django.test import SimpleTestCase+from django.utils import timezonefrom parameterized import parameterizedfrom temporalio.common import WorkflowIDReusePolicy-from temporalio.exceptions import WorkflowAlreadyStartedError+from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedErrorfrom posthog.models.integration import Integrationfrom posthog.models.scoping import team_scopefrom products.error_tracking.backend.models import ErrorTrackingAlert, ErrorTrackingAlertThread, ErrorTrackingIssuefrom products.error_tracking.backend.tasks.tasks import dispatch_error_tracking_alert_deliveries-from products.error_tracking.backend.temporal.alerts.delivery import deliver_alert_notifications, plan_alert_deliveries+from products.error_tracking.backend.temporal.alerts.activities import deliver_alert_notifications_activity+from products.error_tracking.backend.temporal.alerts.delivery import (+ PENDING_CLAIM_TTL,+ AlertDeliveryError,+ AlertThreadBusyError,+ deliver_alert_notifications,+ plan_alert_deliveries,+)from products.error_tracking.backend.temporal.alerts.dispatch import (AlertDispatchError,start_alert_delivery_workflow,start_alert_delivery_workflows,)-from products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputs+from products.error_tracking.backend.temporal.alerts.messages import build_reply_text, build_root_message+from products.error_tracking.backend.temporal.alerts.types import THREAD_BUSY_ERROR_TYPE, AlertDeliveryWorkflowInputs+from products.error_tracking.backend.temporal.alerts.workflow import BUSY_WAIT_LIMITclass AlertTestMixin(BaseTest):@@ -127,7 +138,7 @@ class TestAlertDeliveryPlanning(AlertTestMixin):assert planned[0].thread is not Noneassert planned[0].thread.id == thread.id- def test_repeated_opener_event_with_thread_is_a_reply(self):+ def test_repeated_opener_event_with_rooted_thread_is_a_reply(self):alert = self._create_alert(triggers=["issue_created", "issue_reopened"])with team_scope(self.team.id):ErrorTrackingAlertThread.objects.create(@@ -135,6 +146,7 @@ class TestAlertDeliveryPlanning(AlertTestMixin):alert=alert,issue=self.issue,destination=alert.destinations.get(),+ external_ref={"channel": "C0123", "ts": "111.222"},)planned = plan_alert_deliveries(self._inputs("$error_tracking_issue_reopened"))@@ -171,14 +183,398 @@ class TestAlertDeliveryPlanning(AlertTestMixin):assert reply[0].thread is not Noneassert reply[0].thread.id == thread.id- def test_planned_delivery_is_reported_through_the_real_logger(self):- # The planning log runs structlog with the real processor chain: a kwarg- # that collides with structlog's positional `event` raises on every- # planned destination and fails the whole activity.++class TestAlertMessages(SimpleTestCase):+ def _inputs(self, **extra: str) -> AlertDeliveryWorkflowInputs:+ return AlertDeliveryWorkflowInputs(+ notification_id="notif-1",+ team_id=1,+ issue_id="issue-1",+ event="$error_tracking_issue_spiking",+ issue_name="TypeError",+ extra=extra or None,+ )++ @parameterized.expand(+ [+ ("with_baseline", {"current_bucket_value": "600", "computed_baseline": "12.5"}, "vs baseline 12.5"),+ # A zero baseline means the issue has no history, not a real comparison.+ ("zero_baseline", {"current_bucket_value": "600", "computed_baseline": "0.0"}, "no baseline yet"),+ ("missing_baseline", {"current_bucket_value": "600"}, "no baseline yet"),+ ]+ )+ def test_spike_summary_describes_the_baseline_honestly(self, _name, extra, expected):+ reply = build_reply_text(self._inputs(**extra))+ assert reply is not None+ assert reply.startswith("📈 Spiking again: 600 events")+ assert expected in reply++ def test_spiking_root_carries_the_measurements(self):+ # A spiking-only alert opens the thread with the spike, so the root must say how big it is.+ blocks = build_root_message(self._inputs(current_bucket_value="600", computed_baseline="12.5"))["blocks"]+ context_texts = [el["text"] for block in blocks if block["type"] == "context" for el in block["elements"]]+ assert "600 events in the last window vs baseline 12.5" in context_texts++ def test_spiking_reply_without_measurements_stays_short(self):+ assert build_reply_text(self._inputs()) == "📈 Spiking again"+++class TestSlackThreadDelivery(AlertTestMixin):+ def _mock_slack(self):+ slack_integration = patch("products.error_tracking.backend.temporal.alerts.delivery.SlackIntegration")+ mock = slack_integration.start()+ self.addCleanup(slack_integration.stop)+ client = mock.return_value.client+ client.chat_postMessage.return_value = {"channel": "C0123", "ts": "111.222"}+ return client++ def _thread(self, alert, *, rooted=True) -> ErrorTrackingAlertThread:+ with team_scope(self.team.id):+ return ErrorTrackingAlertThread.objects.create(+ team=self.team,+ alert=alert,+ issue=self.issue,+ destination=alert.destinations.get(),+ external_ref={"channel": "C0123", "ts": "111.222"} if rooted else {},+ root_headline="🔴 New issue" if rooted else "",+ )++ def test_opener_posts_root_and_stores_thread_state(self):+ client = self._mock_slack()+ alert = self._create_alert(triggers=["issue_created"])++ delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_created"))++ assert delivered == 1+ client.chat_postMessage.assert_called_once()+ kwargs = client.chat_postMessage.call_args.kwargs+ assert kwargs["channel"] == "C0123"+ assert "TypeError" in kwargs["text"]+ with team_scope(self.team.id):+ thread = ErrorTrackingAlertThread.objects.get(alert=alert, issue=self.issue)+ assert thread.external_ref == {"channel": "C0123", "ts": "111.222", "root_status": "Active"}+ assert thread.root_headline == "🔴 New issue"+ assert thread.delivered_notification_ids == ["notif-1"]++ def test_reply_posts_into_thread_and_edits_root_on_status_change(self):+ client = self._mock_slack()+ alert = self._create_alert(triggers=["issue_created"])+ self._thread(alert)++ delivered = deliver_alert_notifications(+ self._inputs("$error_tracking_issue_resolved", notification_id="notif-2", status="Resolved")+ )++ assert delivered == 1+ reply_kwargs = client.chat_postMessage.call_args.kwargs+ assert reply_kwargs["channel"] == "C0123"+ assert reply_kwargs["thread_ts"] == "111.222"+ assert "Resolved by [email protected]" in reply_kwargs["text"]+ edit_kwargs = client.chat_update.call_args.kwargs+ assert edit_kwargs["ts"] == "111.222"+ # The headline is the thread's identity: a status edit never changes it.+ assert edit_kwargs["text"].startswith("🔴 New issue")++ def test_redelivered_notification_is_not_posted_twice(self):+ client = self._mock_slack()self._create_alert(triggers=["issue_created"])+ inputs = self._inputs("$error_tracking_issue_created")++ assert deliver_alert_notifications(inputs) == 1+ assert deliver_alert_notifications(inputs) == 0++ client.chat_postMessage.assert_called_once()++ def test_reply_with_nothing_to_say_does_not_claim_the_thread(self):+ # A replayed created event on a rooted thread is a reply with no text: skip+ # without contending for the claim.+ client = self._mock_slack()+ alert = self._create_alert(triggers=["issue_created"])+ thread = self._thread(alert)+ thread.pending_notification_id = "notif-other"+ thread.pending_claimed_at = timezone.now()+ thread.save()++ assert deliver_alert_notifications(self._inputs("$error_tracking_issue_created", "notif-2")) == 0++ client.chat_postMessage.assert_not_called()+ thread.refresh_from_db()+ assert thread.pending_notification_id == "notif-other"++ def test_redelivered_notification_does_not_wait_behind_another_claim(self):+ # Already delivered: nothing left to do, so it must not contend for the thread.+ client = self._mock_slack()+ alert = self._create_alert(triggers=["issue_created"])+ thread = self._thread(alert)+ thread.delivered_notification_ids = ["notif-1"]+ thread.pending_notification_id = "notif-other"+ thread.pending_claimed_at = timezone.now()+ thread.save()++ assert deliver_alert_notifications(self._inputs("$error_tracking_issue_resolved")) == 0++ client.chat_postMessage.assert_not_called()+ thread.refresh_from_db()+ assert thread.pending_notification_id == "notif-other"+ def test_unrooted_thread_leaves_reply_unclaimed(self):+ client = self._mock_slack()+ alert = self._create_alert(triggers=["issue_created"])+ thread = self._thread(alert, rooted=False)++ delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_resolved"))++ assert delivered == 0+ client.chat_postMessage.assert_not_called()+ thread.refresh_from_db()+ assert thread.delivered_notification_ids == []++ def test_concurrent_opener_waits_for_the_holder_then_replies(self):+ # Two openers for the same issue race into the Slack call. The second must+ # not post a second root: it fails fast while the first holds the claim, and+ # its retry lands as a reply in the first one's thread.+ client = self._mock_slack()+ self._create_alert(triggers=["issue_created", "issue_reopened"])+ first = self._inputs("$error_tracking_issue_created", notification_id="notif-1")+ second = self._inputs("$error_tracking_issue_reopened", notification_id="notif-2")++ def post_while_holding_claim(**kwargs):+ client.chat_postMessage.side_effect = None+ with self.assertRaises(AlertThreadBusyError):+ deliver_alert_notifications(second)+ return {"channel": "C0123", "ts": "111.222"}++ client.chat_postMessage.side_effect = post_while_holding_claim+ assert deliver_alert_notifications(first) == 1+ assert deliver_alert_notifications(second) == 1++ assert client.chat_postMessage.call_count == 2+ assert client.chat_postMessage.call_args_list[1].kwargs["thread_ts"] == "111.222"+ with team_scope(self.team.id):+ thread = ErrorTrackingAlertThread.objects.get(issue=self.issue)+ assert thread.delivered_notification_ids == ["notif-1", "notif-2"]+ assert thread.pending_notification_id is None++ @parameterized.expand(+ [+ ("own_live_claim", "notif-1", timedelta(seconds=0), False),+ ("other_live_claim", "notif-other", timedelta(seconds=0), False),+ ("stale_claim", "notif-dead", PENDING_CLAIM_TTL + timedelta(seconds=1), True),+ ]+ )+ def test_live_claims_block_everyone_until_stale(self, _name, holder, age, proceeds):+ # Even this notification's own retry waits: a timed-out attempt may still be+ # mid-post when Temporal starts the retry.+ client = self._mock_slack()+ alert = self._create_alert(triggers=["issue_created"])+ thread = self._thread(alert, rooted=False)+ thread.pending_notification_id = holder+ thread.pending_claimed_at = timezone.now() - age+ thread.save()++ if proceeds:+ assert deliver_alert_notifications(self._inputs("$error_tracking_issue_created")) == 1+ client.chat_postMessage.assert_called_once()+ thread.refresh_from_db()+ assert thread.pending_notification_id is None+ assert thread.delivered_notification_ids == ["notif-1"]+ else:+ with self.assertRaises(AlertThreadBusyError):+ deliver_alert_notifications(self._inputs("$error_tracking_issue_created"))+ client.chat_postMessage.assert_not_called()+ thread.refresh_from_db()+ assert thread.pending_notification_id == holder++ def test_superseded_holder_does_not_overwrite_the_successor(self):+ # A holder that stalls past the TTL loses the claim; when it resumes and+ # finishes posting, its save must not clobber whatever the successor wrote.+ client = self._mock_slack()+ alert = self._create_alert(triggers=["issue_created"])+ thread = self._thread(alert, rooted=False)++ def takeover_during_post(**kwargs):+ with team_scope(self.team.id):+ ErrorTrackingAlertThread.objects.filter(id=thread.id).update(+ pending_notification_id="notif-successor", pending_claimed_at=timezone.now()+ )+ return {"channel": "C0123", "ts": "111.222"}++ client.chat_postMessage.side_effect = takeover_during_postassert deliver_alert_notifications(self._inputs("$error_tracking_issue_created")) == 1+ thread.refresh_from_db()+ assert thread.pending_notification_id == "notif-successor"+ assert thread.external_ref == {}+ assert thread.delivered_notification_ids == []++ def test_busy_wait_outlasts_the_claim_ttl(self):+ # A busy loser must still be waiting when a dead holder's claim goes stale,+ # otherwise the notification is dropped for good.+ assert BUSY_WAIT_LIMIT > PENDING_CLAIM_TTL++ def test_busy_thread_surfaces_as_a_non_retryable_activity_error(self):+ # Contention must not spend the activity's retry budget: the workflow waits instead.+ with (+ patch(+ "products.error_tracking.backend.temporal.alerts.activities.deliver_alert_notifications",+ side_effect=AlertThreadBusyError("busy"),+ ),+ self.assertRaises(ApplicationError) as raised,+ ):+ deliver_alert_notifications_activity(self._inputs("$error_tracking_issue_created"))+ assert raised.exception.type == THREAD_BUSY_ERROR_TYPE+ assert raised.exception.non_retryable is True++ def test_root_shows_the_issue_row_status_at_post_time(self):+ # A resolve that ran before the opener must not leave an "Active" root behind.+ client = self._mock_slack()+ alert = self._create_alert(triggers=["issue_created"])+ ErrorTrackingIssue.objects.filter(id=self.issue.id).update(status=ErrorTrackingIssue.Status.RESOLVED)++ delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_created", status="Active"))++ assert delivered == 1+ blocks = client.chat_postMessage.call_args.kwargs["blocks"]+ context_texts = [el["text"] for block in blocks if block["type"] == "context" for el in block["elements"]]+ assert "Status: Resolved" in context_texts+ with team_scope(self.team.id):+ thread = ErrorTrackingAlertThread.objects.get(alert=alert, issue=self.issue)+ assert thread.external_ref["root_status"] == "Resolved"++ def test_any_reply_reconciles_a_stale_root_status(self):+ client = self._mock_slack()+ alert = self._create_alert(triggers=["issue_created"])+ thread = self._thread(alert)+ thread.external_ref = {**thread.external_ref, "root_status": "Active"}+ thread.save()++ # The row says Active, as the root shows: nothing to edit.+ assert deliver_alert_notifications(self._inputs("$error_tracking_issue_assigned", "n-1", status="Active")) == 1+ client.chat_update.assert_not_called()++ # The resolve's root edit fails: the reply still counts, the root stays recorded as stale.+ ErrorTrackingIssue.objects.filter(id=self.issue.id).update(status=ErrorTrackingIssue.Status.RESOLVED)+ client.chat_update.side_effect = RuntimeError("slack hiccup")+ assert (+ deliver_alert_notifications(self._inputs("$error_tracking_issue_resolved", "n-2", status="Resolved")) == 1+ )+ thread.refresh_from_db()+ assert thread.external_ref["root_status"] == "Active"++ # A delayed assignment still carries the status it snapshotted before the resolve. The+ # row is the reference, so it heals the root to Resolved instead of flipping it back.+ client.chat_update.side_effect = None+ assert deliver_alert_notifications(self._inputs("$error_tracking_issue_assigned", "n-3", status="Active")) == 1+ assert client.chat_update.call_count == 2+ edit_kwargs = client.chat_update.call_args.kwargs+ assert edit_kwargs["ts"] == "111.222"+ assert edit_kwargs["text"].startswith("🔴 New issue")+ thread.refresh_from_db()+ assert thread.external_ref["root_status"] == "Resolved"++ def test_failed_post_releases_the_claim(self):+ client = self._mock_slack()+ client.chat_postMessage.side_effect = RuntimeError("slack down")+ alert = self._create_alert(triggers=["issue_created"])++ with self.assertRaises(AlertDeliveryError):+ deliver_alert_notifications(self._inputs("$error_tracking_issue_created"))++ with team_scope(self.team.id):+ thread = ErrorTrackingAlertThread.objects.get(alert=alert, issue=self.issue)+ assert thread.pending_notification_id is None+ assert thread.external_ref == {}++ def test_retry_after_failed_root_post_roots_the_thread(self):+ # A crash between the thread insert and the root post must not wedge the+ # destination: the next opener attempt roots the existing row.+ client = self._mock_slack()+ alert = self._create_alert(triggers=["issue_created"])+ thread = self._thread(alert, rooted=False)++ delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_created"))++ assert delivered == 1+ assert client.chat_postMessage.call_args.kwargs["channel"] == "C0123"+ thread.refresh_from_db()+ assert thread.external_ref == {"channel": "C0123", "ts": "111.222", "root_status": "Active"}+ assert thread.delivered_notification_ids == ["notif-1"]++ def test_opener_with_configured_filters_stays_dark(self):+ # Filter evaluation lands in a follow-up layer; until then a filtered+ # alert must not post issues the user may have excluded.+ client = self._mock_slack()+ with team_scope(self.team.id):+ alert = ErrorTrackingAlert.objects.create(+ team=self.team,+ name="Filtered",+ triggers=["issue_created"],+ filters={"properties": [{"key": "environment", "value": "production", "type": "event"}]},+ )+ alert.destinations.create(+ team=self.team, channel_type="slack", integration=self.integration, config={"channel": "C0123"}+ )++ delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_created"))++ assert delivered == 0+ client.chat_postMessage.assert_not_called()++ def test_root_header_stays_within_slack_limit(self):+ client = self._mock_slack()+ self._create_alert(triggers=["issue_created"])++ deliver_alert_notifications(self._inputs("$error_tracking_issue_created", issue_name="x" * 400))++ blocks = client.chat_postMessage.call_args.kwargs["blocks"]+ header = next(block for block in blocks if block["type"] == "header")+ assert len(header["text"]["text"]) <= 150++ def test_repointed_destination_replies_in_original_channel(self):+ client = self._mock_slack()+ alert = self._create_alert(triggers=["issue_created"])+ self._thread(alert)+ with team_scope(self.team.id):+ destination = alert.destinations.get()+ destination.config = {"channel": "C0456"}+ destination.save()++ deliver_alert_notifications(self._inputs("$error_tracking_issue_resolved", notification_id="notif-2"))++ # A provider thread cannot move: replies stay in the thread's own channel.+ assert client.chat_postMessage.call_args.kwargs["channel"] == "C0123"++ def test_missing_integration_skips_without_raising(self):+ client = self._mock_slack()+ alert = self._create_alert(triggers=["issue_created"])+ with team_scope(self.team.id):+ alert.destinations.update(integration=None)++ delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_created"))++ assert delivered == 0+ client.chat_postMessage.assert_not_called()++ def test_failed_destination_does_not_block_others_and_surfaces_for_retry(self):+ client = self._mock_slack()+ alert = self._create_alert(triggers=["issue_created"])+ with team_scope(self.team.id):+ alert.destinations.create(+ team=self.team,+ channel_type="slack",+ integration=self.integration,+ config={"channel": "C0456"},+ )+ client.chat_postMessage.side_effect = [Exception("channel archived"), {"channel": "C0456", "ts": "333.444"}]++ with self.assertRaises(AlertDeliveryError):+ deliver_alert_notifications(self._inputs("$error_tracking_issue_created"))++ assert client.chat_postMessage.call_count == 2+ with team_scope(self.team.id):+ rooted = [t for t in ErrorTrackingAlertThread.objects.filter(issue=self.issue) if t.external_ref.get("ts")]+ assert len(rooted) == 1+class TestAlertDeliveryDispatch(AlertTestMixin):def _dispatch(self, *notification_ids: str) -> None: