: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): dispatch alert delivery workflow on lifecycle transitions (#90535)
Catalin632538b9be86
diff --git a/products/error_tracking/backend/logic/alerts.py b/products/error_tracking/backend/logic/alerts.pyindex 51208723b8e3..cbbb9b89e2b7 100644--- a/products/error_tracking/backend/logic/alerts.py+++ b/products/error_tracking/backend/logic/alerts.py@@ -3,7 +3,7 @@from typing import Any, Optionalfrom uuid import UUID-from django.db import transaction+from django.db import connection, transactionfrom django.db.models import QuerySetimport structlog@@ -67,6 +67,17 @@ def get_alert(team_id: int, alert_id: UUID | str) -> Optional[ErrorTrackingAlertreturn ErrorTrackingAlert.objects.for_team(team_id).prefetch_related("destinations").filter(id=parsed_id).first()+# Delivery plans every enabled alert and destination of the team on each lifecycle+# transition, so the graph it loads must stay small.+MAX_ALERTS_PER_TEAM = 50+MAX_DESTINATIONS_PER_ALERT = 10+++def _validate_destination_count(destinations: list[dict[str, Any]]) -> None:+ if len(destinations) > MAX_DESTINATIONS_PER_ALERT:+ raise AlertValidationError(f"An alert can have at most {MAX_DESTINATIONS_PER_ALERT} destinations.")++def create_alert(team_id: int,*,@@ -81,11 +92,17 @@ def create_alert(# paths (for_team) all agree on the same team id for child environments.team_id = resolve_effective_team_id(team_id)compiled_filters = _compile_filters(team_id, filters)+ _validate_destination_count(destinations)_reject_duplicate_destinations(destinations)for destination in destinations:_validate_destination(team_id, destination)with transaction.atomic():+ # Serializes concurrent creates for the team so the cap holds; the lock ends with the transaction.+ with connection.cursor() as cursor:+ cursor.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", [f"error_tracking_alerts:{team_id}"])+ if ErrorTrackingAlert.objects.for_team(team_id, canonical=True).count() >= MAX_ALERTS_PER_TEAM:+ raise AlertValidationError(f"A project can have at most {MAX_ALERTS_PER_TEAM} alerts.")alert = ErrorTrackingAlert.objects.for_team(team_id, canonical=True).create(team_id=team_id,name=name,@@ -127,6 +144,7 @@ def update_alert(return get_alert(team_id, parsed_id)if destinations is not None:+ _validate_destination_count(destinations)_reject_duplicate_destinations(destinations)with transaction.atomic():diff --git a/products/error_tracking/backend/logic/issue_mutations.py b/products/error_tracking/backend/logic/issue_mutations.pyindex fd67edfe03bc..10e999de8784 100644--- a/products/error_tracking/backend/logic/issue_mutations.py+++ b/products/error_tracking/backend/logic/issue_mutations.py@@ -25,8 +25,11 @@ from products.error_tracking.backend.logic.lifecycle_events import (ISSUE_SPLIT_EVENT,ISSUE_UNASSIGNED_EVENT,STATUS_CHANGE_EVENTS,+ PendingLifecycleEvent,assignee_property,+ prepare_issue_lifecycle_event,produce_issue_lifecycle_event_on_commit,+ produce_issue_lifecycle_events_on_commit,status_label,)from products.error_tracking.backend.models import (@@ -256,11 +259,12 @@ def assign_issue() -> None:with transaction.atomic():issue = _get_issue(team_id, issue_id, select_related=("team__organization",))- assignment_changed = _assign_one(issue, assignee, issue.team.organization, user, team_id, was_impersonated)- if assignment_changed:+ transition = _assign_one(issue, assignee, issue.team.organization, user, team_id, was_impersonated)+ if transition is not None:+ produce_issue_lifecycle_events_on_commit([transition])_stamp_issue_state(team_id=team_id, issue_ids=[issue.id])- if assignment_changed:+ if transition is not None:sync_issues_to_clickhouse(issue_ids=[issue.id], team_id=team_id)@@ -284,6 +288,7 @@ def bulk_update_issues(new_status = _status_from_string(status) if status is not None else Noneif new_status is None:raise InvalidIssueStatusError+ transitions = []for issue in issues:if issue.status == new_status:continue@@ -310,21 +315,28 @@ def bulk_update_issues(),)if new_status in STATUS_CHANGE_EVENTS:- produce_issue_lifecycle_event_on_commit(- event=STATUS_CHANGE_EVENTS[new_status],- issue=issue,- user=user,- status=new_status,- extra_properties={"previous_status": status_label(issue.status)},+ transitions.append(+ prepare_issue_lifecycle_event(+ event=STATUS_CHANGE_EVENTS[new_status],+ issue=issue,+ user=user,+ status=new_status,+ extra_properties={"previous_status": status_label(issue.status)},+ ))+ produce_issue_lifecycle_events_on_commit(transitions)if changed_issue_ids:ErrorTrackingIssue.objects.filter(team_id=team_id, id__in=changed_issue_ids).update(status=new_status, state_updated_at=timezone.now())elif action == "assign":+ transitions = []for issue in issues:- if _assign_one(issue, assignee, issue.team.organization, user, team_id, was_impersonated):+ transition = _assign_one(issue, assignee, issue.team.organization, user, team_id, was_impersonated)+ if transition is not None:+ transitions.append(transition)changed_issue_ids.append(issue.id)+ produce_issue_lifecycle_events_on_commit(transitions)_stamp_issue_state(team_id=team_id, issue_ids=changed_issue_ids)sync_issues_to_clickhouse(issue_ids=changed_issue_ids, team_id=team_id)@@ -346,7 +358,8 @@ def _assign_one(user: User,team_id: int,was_impersonated: bool,-) -> bool:+) -> PendingLifecycleEvent | None:+ """Apply one assignment change; returns its lifecycle transition for the caller to queue, or None if nothing changed."""assignment_before = ErrorTrackingIssueAssignment.objects.filter(issue_id=issue.id).first()serialized_assignment_before = _assignment_repr(assignment_before)@@ -363,7 +376,7 @@ def _assign_one("type": assignee["type"],}if serialized_assignment_before == serialized_assignment_after:- return False+ return None# nosemgrep: idor-lookup-without-team (assignee validated against org above)assignment_after, _ = ErrorTrackingIssueAssignment.objects.update_or_create(@@ -383,7 +396,7 @@ def _assign_one(assigner=user,)- produce_issue_lifecycle_event_on_commit(+ transition = prepare_issue_lifecycle_event(event=ISSUE_ASSIGNED_EVENT,issue=issue,user=user,@@ -391,14 +404,14 @@ def _assign_one()else:if assignment_before is None:- return False+ return Noneassignment_before.delete()serialized_assignment_after = Noneextra_properties = Noneif serialized_assignment_before and serialized_assignment_before.get("id") is not None:extra_properties = {"previous_assignee": assignee_property(serialized_assignment_before)}- produce_issue_lifecycle_event_on_commit(+ transition = prepare_issue_lifecycle_event(event=ISSUE_UNASSIGNED_EVENT,issue=issue,user=user,@@ -426,4 +439,4 @@ def _assign_one(],),)- return True+ return transitiondiff --git a/products/error_tracking/backend/logic/lifecycle_events.py b/products/error_tracking/backend/logic/lifecycle_events.pyindex 30d977d491d6..2636175b5f81 100644--- a/products/error_tracking/backend/logic/lifecycle_events.py+++ b/products/error_tracking/backend/logic/lifecycle_events.py@@ -7,6 +7,8 @@ events see the full picture."""import json+import uuid+import dataclassesfrom typing import Any, Optionalfrom django.db import transaction@@ -17,10 +19,12 @@ from posthog.cdp.internal_events import InternalEventEvent, InternalEventPerson,from posthog.models.user import Userfrom products.error_tracking.backend.models import (+ ErrorTrackingAlert,ErrorTrackingIssue,ErrorTrackingIssueAssignment,ErrorTrackingIssueFingerprintV2,)+from products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputslogger = structlog.get_logger(__name__)@@ -83,14 +87,29 @@ def _issue_fingerprint_for_links(issue: ErrorTrackingIssue) -> Optional[str]:)-def produce_issue_lifecycle_event_on_commit(+# One Celery task per this many transitions: a bulk status change over thousands of+# issues fans out into bounded tasks instead of one oversized payload.+ALERT_DISPATCH_BATCH_SIZE = 200++[email protected](frozen=True)+class PendingLifecycleEvent:+ """A transition snapshotted inside the mutation, emitted once it commits."""++ team_id: int+ internal_event: InternalEventEvent+ person: Optional[InternalEventPerson]+ alert_inputs: AlertDeliveryWorkflowInputs+++def prepare_issue_lifecycle_event(*,event: str,issue: ErrorTrackingIssue,user: Optional[User],status: Optional[str] = None,extra_properties: Optional[dict[str, Any]] = None,-) -> None:+) -> PendingLifecycleEvent:# Snapshot everything now: the issue row may be mutated again (or deleted, for# merge sources) before the surrounding transaction commits.team_id = issue.team_id@@ -99,6 +118,10 @@ def produce_issue_lifecycle_event_on_commit(# the mutation.fingerprint = _issue_fingerprint_for_links(issue)current_assignee = _current_assignee_property(issue)+ issue_id = str(issue.id)+ # The notification id names both the internal event and the alert delivery+ # workflow, so redelivered starts and retries stay idempotent per transition.+ notification_id = str(uuid.uuid4())# Same issue-property set the ingestion-driven producer emits (see# produce_issue_lifecycle_internal_event), so destination property filters# match both paths.@@ -113,9 +136,10 @@ def produce_issue_lifecycle_event_on_commit(**({"assignee": current_assignee} if current_assignee is not None else {}),**(extra_properties or {}),}- internal_event = InternalEventEvent(event=event, distinct_id=str(issue.id), properties=properties)+ internal_event = InternalEventEvent(event=event, distinct_id=issue_id, properties=properties, uuid=notification_id)person = None+ actor_email: Optional[str] = Noneif user is not None:# Deliberately a minimal actor subset: person reaches customer-configured# destinations verbatim (the default webhook body sends `{person}`), so no@@ -129,13 +153,89 @@ def produce_issue_lifecycle_event_on_commit("first_name": user.first_name,},)+ actor_email = user.email++ status_property = properties.get("status")+ assignee_property_value = properties.get("assignee")+ alert_inputs = AlertDeliveryWorkflowInputs.build(+ notification_id=notification_id,+ team_id=team_id,+ issue_id=issue_id,+ event=event,+ issue_name=issue.name,+ issue_description=issue.description,+ 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,+ )+ return PendingLifecycleEvent(+ team_id=team_id, internal_event=internal_event, person=person, alert_inputs=alert_inputs+ )+++def produce_issue_lifecycle_events_on_commit(events: list[PendingLifecycleEvent]) -> None:+ """Publish the internal events and queue alert dispatch once the transaction commits.++ One call per transaction: a bulk mutation hands over every transition at once so+ alert dispatch leaves as a handful of Celery tasks instead of one synchronous+ Temporal start per issue on the web worker.+ """+ if not events:+ return+ team_ids = {event.team_id for event in events}+ if len(team_ids) != 1:+ raise ValueError("Lifecycle events are emitted per team")+ team_id = events[0].team_iddef _produce() -> None:- try:- produce_internal_event(team_id=team_id, event=internal_event, person=person)- except Exception:- # Already logged by produce_internal_event; alert emission must never- # fail the mutation that triggered it.- pass-- transaction.on_commit(_produce)+ for pending in events:+ try:+ produce_internal_event(team_id=team_id, event=pending.internal_event, person=pending.person)+ except Exception:+ # Already logged by produce_internal_event; alert emission must never+ # fail the mutation that triggered it.+ pass+ # Teams without an enabled alert (nearly all of them) pay one EXISTS query and+ # queue nothing; the flag is evaluated once, inside the task.+ if not ErrorTrackingAlert.objects.for_team(team_id).filter(enabled=True).exists():+ return+ # The task module imports the Temporal package aggregator, which loads every+ # worker-only workflow module; keep it off the web import path.+ from products.error_tracking.backend.tasks.tasks import ( # noqa: PLC0415+ dispatch_error_tracking_alert_deliveries,+ )++ for start in range(0, len(events), ALERT_DISPATCH_BATCH_SIZE):+ chunk = events[start : start + ALERT_DISPATCH_BATCH_SIZE]+ try:+ dispatch_error_tracking_alert_deliveries.delay(+ team_id=team_id,+ notifications=[dataclasses.asdict(pending.alert_inputs) for pending in chunk],+ )+ except Exception:+ # The mutation has committed; a broker outage must not turn it into an error.+ logger.exception(+ "error_tracking_alert_dispatch_enqueue_failed",+ team_id=team_id,+ notification_ids=[pending.alert_inputs.notification_id for pending in chunk],+ )++ # robust: a failure here must not stop the mutation's other post-commit hooks.+ transaction.on_commit(_produce, robust=True)+++def produce_issue_lifecycle_event_on_commit(+ *,+ event: str,+ issue: ErrorTrackingIssue,+ user: Optional[User],+ status: Optional[str] = None,+ extra_properties: Optional[dict[str, Any]] = None,+) -> None:+ produce_issue_lifecycle_events_on_commit(+ [+ prepare_issue_lifecycle_event(+ event=event, issue=issue, user=user, status=status, extra_properties=extra_properties+ )+ ]+ )diff --git a/products/error_tracking/backend/tasks/__init__.py b/products/error_tracking/backend/tasks/__init__.pyindex 66ea641cee41..fc1db816e180 100644--- a/products/error_tracking/backend/tasks/__init__.py+++ b/products/error_tracking/backend/tasks/__init__.py@@ -1 +1,4 @@-from products.error_tracking.backend.tasks.tasks import compute_error_tracking_recommendation # noqa: F401+from products.error_tracking.backend.tasks.tasks import ( # noqa: F401+ compute_error_tracking_recommendation,+ dispatch_error_tracking_alert_deliveries,+)diff --git a/products/error_tracking/backend/tasks/tasks.py b/products/error_tracking/backend/tasks/tasks.pyindex 2ae31d0b8173..975cab7cc72d 100644--- a/products/error_tracking/backend/tasks/tasks.py+++ b/products/error_tracking/backend/tasks/tasks.py@@ -56,3 +56,33 @@ def compute_error_tracking_recommendation(recommendation_id: str, team_id: int)status=ErrorTrackingRecommendation.Status.READY,status_changed_at=now,)+++@shared_task(+ name="products.error_tracking.backend.tasks.dispatch_error_tracking_alert_deliveries",+ ignore_result=True,+ # Acked after the starts, and requeued if the worker dies mid-flight: every start+ # is idempotent on its notification id, so redelivery is safe and loss is not.+ acks_late=True,+ reject_on_worker_lost=True,+ autoretry_for=(Exception,),+ max_retries=5,+ retry_backoff=True,+ retry_backoff_max=300,+ retry_jitter=True,+)+@with_team_scope()+def dispatch_error_tracking_alert_deliveries(team_id: int, notifications: list[dict]) -> None:+ """Start the delivery workflows for one transaction's worth of manual lifecycle transitions.++ Queued after commit so the request never waits on Temporal. Every start is+ idempotent on its notification id, so a retry after a partial failure only+ fills in the starts Temporal never accepted.+ """+ # Anything under the temporal package pulls in its aggregator, which loads every+ # worker-only workflow module (and, through recommendations, this tasks package):+ # keep it off this module's import path.+ from products.error_tracking.backend.temporal.alerts.dispatch import start_alert_delivery_workflows # noqa: PLC0415+ from products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputs # noqa: PLC0415++ start_alert_delivery_workflows([AlertDeliveryWorkflowInputs(**notification) for notification in notifications])diff --git a/products/error_tracking/backend/temporal/__init__.py b/products/error_tracking/backend/temporal/__init__.pyindex 656d81e25076..f1f276586d7b 100644--- a/products/error_tracking/backend/temporal/__init__.py+++ b/products/error_tracking/backend/temporal/__init__.py@@ -1,3 +1,8 @@+from products.error_tracking.backend.temporal.alerts import (+ ACTIVITIES as ALERT_ACTIVITIES,+ WORKFLOWS as ALERT_WORKFLOWS,+ ErrorTrackingAlertDeliveryWorkflow,+)from products.error_tracking.backend.temporal.lifecycle import (ACTIVITIES as LIFECYCLE_ACTIVITIES,WORKFLOWS as LIFECYCLE_WORKFLOWS,@@ -32,9 +37,21 @@ from products.error_tracking.backend.temporal.weekly_digest import (send_org_digest_activity,)-WORKFLOWS = SYMBOL_SET_WORKFLOWS + SPIKE_EVENT_WORKFLOWS + RECOMMENDATIONS_REFRESH_WORKFLOWS + WEEKLY_DIGEST_WORKFLOWS+# Alert delivery rides the error tracking queue, not the lifecycle one: outbound Slack+# I/O must not share worker slots with issue-state work such as auto-merge.+WORKFLOWS = (+ SYMBOL_SET_WORKFLOWS+ + SPIKE_EVENT_WORKFLOWS+ + RECOMMENDATIONS_REFRESH_WORKFLOWS+ + WEEKLY_DIGEST_WORKFLOWS+ + ALERT_WORKFLOWS+)ACTIVITIES = (- SYMBOL_SET_ACTIVITIES + SPIKE_EVENT_ACTIVITIES + RECOMMENDATIONS_REFRESH_ACTIVITIES + WEEKLY_DIGEST_ACTIVITIES+ SYMBOL_SET_ACTIVITIES+ + SPIKE_EVENT_ACTIVITIES+ + RECOMMENDATIONS_REFRESH_ACTIVITIES+ + WEEKLY_DIGEST_ACTIVITIES+ + ALERT_ACTIVITIES)__all__ = [@@ -42,6 +59,7 @@ __all__ = ["LIFECYCLE_ACTIVITIES","LIFECYCLE_WORKFLOWS","WORKFLOWS",+ "ErrorTrackingAlertDeliveryWorkflow","ErrorTrackingIssueCreatedWorkflow","ErrorTrackingIssueReopenedWorkflow","ErrorTrackingIssueSpikingWorkflow",diff --git a/products/error_tracking/backend/temporal/alerts/__init__.py b/products/error_tracking/backend/temporal/alerts/__init__.pynew file mode 100644index 000000000000..10a72c34084a--- /dev/null+++ b/products/error_tracking/backend/temporal/alerts/__init__.py@@ -0,0 +1,14 @@+from products.error_tracking.backend.temporal.alerts.activities import (+ ACTIVITIES as ACTIVITIES,+ deliver_alert_notifications_activity,+)+from products.error_tracking.backend.temporal.alerts.workflow import ErrorTrackingAlertDeliveryWorkflow++WORKFLOWS = [ErrorTrackingAlertDeliveryWorkflow]++__all__ = [+ "ACTIVITIES",+ "WORKFLOWS",+ "ErrorTrackingAlertDeliveryWorkflow",+ "deliver_alert_notifications_activity",+]diff --git a/products/error_tracking/backend/temporal/alerts/activities.py b/products/error_tracking/backend/temporal/alerts/activities.pynew file mode 100644index 000000000000..8d18e585cb99--- /dev/null+++ b/products/error_tracking/backend/temporal/alerts/activities.py@@ -0,0 +1,17 @@+import posthoganalytics+from temporalio import activity++from 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+++@close_db_connections+def deliver_alert_notifications_activity(inputs: AlertDeliveryWorkflowInputs) -> int:+ return deliver_alert_notifications(inputs)+++ACTIVITIES = [deliver_alert_notifications_activity]diff --git a/products/error_tracking/backend/temporal/alerts/delivery.py b/products/error_tracking/backend/temporal/alerts/delivery.pynew file mode 100644index 000000000000..d32deea70e6e--- /dev/null+++ b/products/error_tracking/backend/temporal/alerts/delivery.py@@ -0,0 +1,91 @@+"""Alert delivery planning: which alert destinations a lifecycle transition reaches.++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.+"""++import dataclasses++import structlog++from products.error_tracking.backend.models import (+ ErrorTrackingAlert,+ ErrorTrackingAlertDestination,+ ErrorTrackingAlertThread,+)+from products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputs++logger = structlog.get_logger(__name__)++# Which lifecycle event satisfies which alert trigger. Only these open a thread;+# every other lifecycle event is delivered as a reply to an existing thread.+OPENER_TRIGGERS = {+ "$error_tracking_issue_created": ErrorTrackingAlert.Trigger.ISSUE_CREATED,+ "$error_tracking_issue_reopened": ErrorTrackingAlert.Trigger.ISSUE_REOPENED,+ "$error_tracking_issue_spiking": ErrorTrackingAlert.Trigger.ISSUE_SPIKING,+ "$error_tracking_issue_assigned": ErrorTrackingAlert.Trigger.ISSUE_ASSIGNED,+}++[email protected](frozen=True)+class PlannedDelivery:+ """One (alert, destination) conversation this transition reaches."""++ alert: ErrorTrackingAlert+ destination: ErrorTrackingAlertDestination+ is_opener: bool+ thread: ErrorTrackingAlertThread | None+++def plan_alert_deliveries(inputs: AlertDeliveryWorkflowInputs) -> list[PlannedDelivery]:+ trigger = 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):+ 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.+ threads_by_destination = {+ thread.destination_id: thread+ for thread in ErrorTrackingAlertThread.objects.for_team(inputs.team_id).filter(issue_id=inputs.issue_id)+ }++ planned: list[PlannedDelivery] = []+ for alert in alerts:+ trigger_matched = trigger is not None and trigger in alert.triggers+ for destination in destinations_by_alert.get(alert.id, []):+ thread = threads_by_destination.get(destination.id)+ if thread is None and not trigger_matched:+ # Replies never open threads: an update with no rooted thread stays+ # 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+ planned.append(PlannedDelivery(alert=alert, destination=destination, is_opener=is_opener, thread=thread))+ return planned+++def deliver_alert_notifications(inputs: AlertDeliveryWorkflowInputs) -> int:+ planned = plan_alert_deliveries(inputs)+ for delivery in planned:+ logger.info(+ "error_tracking_alert_delivery_planned",+ 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,+ 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)diff --git a/products/error_tracking/backend/temporal/alerts/dispatch.py b/products/error_tracking/backend/temporal/alerts/dispatch.pynew file mode 100644index 000000000000..3b5bf51bbe8c--- /dev/null+++ b/products/error_tracking/backend/temporal/alerts/dispatch.py@@ -0,0 +1,103 @@+"""Starts alert delivery workflows for lifecycle transitions.++Two durable callers: the lifecycle workflows run it as a retried activity+(ingestion-driven transitions), and a Celery task with retries runs it for the+manual transitions Django mutations queue after commit. Failures raise so the+caller's retry policy owns recovery; starts are idempotent on the notification id.+"""++import asyncio+from datetime import timedelta++from django.conf import settings++import structlog+from temporalio.client import Client+from temporalio.common import WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedError++from posthog.temporal.common.client import async_connect++from products.error_tracking.backend.logic.alerts import native_alerts_enabled+from products.error_tracking.backend.models import ErrorTrackingAlert+from products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputs+from products.error_tracking.backend.temporal.alerts.workflow import WORKFLOW_NAME, ErrorTrackingAlertDeliveryWorkflow++logger = structlog.get_logger(__name__)++# Bounds the connect handshake and each start individually; the caller retries a+# stalled Temporal instead of holding its worker.+DISPATCH_TIMEOUT = timedelta(seconds=10)+DISPATCH_CONCURRENCY = 8+++class AlertDispatchError(Exception):+ """At least one start was not accepted; the batch is safe to retry as a whole."""+++def team_has_enabled_alerts(team_id: int) -> bool:+ return ErrorTrackingAlert.objects.for_team(team_id).filter(enabled=True).exists()+++def alert_dispatch_enabled(team_id: int) -> bool:+ # Cheap opt-in gates, in cost order: teams without enabled alert rows never+ # evaluate the flag, and teams outside the flag never start a workflow.+ return team_has_enabled_alerts(team_id) and native_alerts_enabled(team_id)+++async def _start_one(temporal: Client, inputs: AlertDeliveryWorkflowInputs, limit: asyncio.Semaphore) -> bool:+ async with limit:+ try:+ await asyncio.wait_for(+ temporal.start_workflow(+ WORKFLOW_NAME,+ inputs,+ id=ErrorTrackingAlertDeliveryWorkflow.workflow_id_for(inputs.notification_id),+ task_queue=settings.ERROR_TRACKING_TASK_QUEUE,+ # A redelivered start after the first run completed must be a no-op+ # (the default ALLOW_DUPLICATE would run it again); failed runs stay+ # retryable by a fresh start.+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,+ ),+ timeout=DISPATCH_TIMEOUT.total_seconds(),+ )+ except WorkflowAlreadyStartedError:+ return True+ except Exception:+ logger.exception(+ "error_tracking_alert_delivery_dispatch_failed",+ team_id=inputs.team_id,+ lifecycle_event=inputs.event,+ notification_id=inputs.notification_id,+ )+ return False+ return True+++async def _connect_and_start(batch: list[AlertDeliveryWorkflowInputs]) -> None:+ temporal = await asyncio.wait_for(async_connect(), timeout=DISPATCH_TIMEOUT.total_seconds())+ limit = asyncio.Semaphore(DISPATCH_CONCURRENCY)+ accepted = await asyncio.gather(*(_start_one(temporal, inputs, limit) for inputs in batch))+ if not all(accepted):+ raise AlertDispatchError(f"{accepted.count(False)} of {len(batch)} alert delivery starts were not accepted")+++def start_alert_delivery_workflows(batch: list[AlertDeliveryWorkflowInputs]) -> None:+ """Start one delivery workflow per transition, all for the same team, over one connection.++ Returns without touching Temporal when the team has no enabled alerts or is+ outside the flag. Raises `AlertDispatchError` (or the connect failure) when any+ start was not accepted, so the caller's retry re-drives the whole batch.+ """+ if not batch:+ return+ team_ids = {inputs.team_id for inputs in batch}+ if len(team_ids) != 1:+ raise ValueError("Alert delivery batches are per team")+ if not alert_dispatch_enabled(batch[0].team_id):+ return+ asyncio.run(_connect_and_start(batch))+++def start_alert_delivery_workflow(inputs: AlertDeliveryWorkflowInputs) -> None:+ start_alert_delivery_workflows([inputs])diff --git a/products/error_tracking/backend/temporal/alerts/types.py b/products/error_tracking/backend/temporal/alerts/types.pynew file mode 100644index 000000000000..c47361bd2020--- /dev/null+++ b/products/error_tracking/backend/temporal/alerts/types.py@@ -0,0 +1,60 @@+import dataclasses++# Issue names/descriptions are unbounded text; notifications only need a headline,+# and an oversized Temporal payload (~2 MiB cap) would silently skip the alert.+MAX_ISSUE_NAME_LENGTH = 500+MAX_ISSUE_DESCRIPTION_LENGTH = 5000+++def _truncate(value: str | None, limit: int) -> str | None:+ if value is None or len(value) <= limit:+ return value+ return value[: limit - 1] + "…"++[email protected](frozen=True)+class AlertDeliveryWorkflowInputs:+ notification_id: str+ team_id: int+ issue_id: str+ event: str+ issue_name: str | None = None+ issue_description: str | None = None+ status: str | None = None+ assignee: str | None = None+ actor_email: str | None = None+ # Reference to the triggering exception event, when the transition has one+ # (ingestion-driven transitions). Event properties are fetched by reference+ # inside activities; nothing large crosses the Temporal payload boundary.+ event_uuid: str | None = None+ event_timestamp: str | None = None+ # Small event-specific extras (e.g. spike baseline values); never exception payloads.+ extra: dict[str, str] | None = None++ @classmethod+ def build(+ cls,+ *,+ notification_id: str,+ team_id: int,+ issue_id: str,+ event: str,+ issue_name: str | None = None,+ issue_description: str | None = None,+ **fields: object,+ ) -> "AlertDeliveryWorkflowInputs":+ """Bounded inputs: the only constructor producers should use."""+ return cls(+ notification_id=notification_id,+ team_id=team_id,+ issue_id=issue_id,+ event=event,+ issue_name=_truncate(issue_name, MAX_ISSUE_NAME_LENGTH),+ issue_description=_truncate(issue_description, MAX_ISSUE_DESCRIPTION_LENGTH),+ **fields, # type: ignore[arg-type]+ )++[email protected](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.pynew file mode 100644index 000000000000..6d878db1ac68--- /dev/null+++ b/products/error_tracking/backend/temporal/alerts/workflow.py@@ -0,0 +1,39 @@+from datetime import timedelta++from temporalio import common, workflow++from posthog.temporal.common.base import PostHogWorkflow++from products.error_tracking.backend.temporal.alerts.types import (+ AlertDeliveryWorkflowInputs,+ AlertDeliveryWorkflowResult,+)++WORKFLOW_NAME = "error-tracking-alert-delivery"++ACTIVITY_RETRY_POLICY = common.RetryPolicy(+ initial_interval=timedelta(seconds=2),+ maximum_interval=timedelta(seconds=60),+ maximum_attempts=5,+)+ACTIVITY_START_TO_CLOSE_TIMEOUT = timedelta(minutes=5)++[email protected](name=WORKFLOW_NAME)+class ErrorTrackingAlertDeliveryWorkflow(PostHogWorkflow):+ inputs_cls = AlertDeliveryWorkflowInputs++ @staticmethod+ def workflow_id_for(notification_id: str) -> str:+ # One workflow per lifecycle transition: redelivered starts are idempotent.+ return f"{WORKFLOW_NAME}-{notification_id}"++ @workflow.run+ async 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)diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py b/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.pyindex df6f671879ad..0a81cc118238 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py@@ -34,6 +34,7 @@ from products.error_tracking.backend.temporal.lifecycle.issue_created.types impofrom products.error_tracking.backend.temporal.lifecycle.rendering import render_stacktracefrom products.error_tracking.backend.temporal.lifecycle.side_effects import (KAFKA_DELIVERY_TIMEOUT_SECONDS,+ dispatch_issue_lifecycle_alert,emit_issue_lifecycle_signal,produce_issue_lifecycle_internal_event,)@@ -201,6 +202,13 @@ def merge_issue_created_fingerprint_activity(@activity.defn@posthoganalytics.scoped(capture_exceptions=False)@close_db_connections+def dispatch_issue_created_alert_activity(inputs: IssueCreatedWorkflowInputs) -> None:+ dispatch_issue_lifecycle_alert(inputs, event="$error_tracking_issue_created", humanize_status=False)+++@close_db_connectionsdef emit_issue_created_internal_event_activity(inputs: IssueCreatedWorkflowInputs) -> None:produce_issue_lifecycle_internal_event(inputs,@@ -222,6 +230,7 @@ async def emit_issue_created_signal_activity(inputs: IssueCreatedWorkflowInputs)ACTIVITIES = [+ dispatch_issue_created_alert_activity,generate_issue_created_embedding_activity,persist_issue_created_embedding_activity,merge_issue_created_fingerprint_activity,diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_created/test/test_workflow.py b/products/error_tracking/backend/temporal/lifecycle/issue_created/test/test_workflow.pyindex 30675843d4f2..45b36dc12ed7 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_created/test/test_workflow.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_created/test/test_workflow.py@@ -195,6 +195,7 @@ def test_falls_back_to_clickhouse_when_valkey_payload_expired(@pytest.mark.asyncioasync def test_only_notifies_for_an_issue_that_was_not_merged() -> None:+ alert_issue_ids: list[str] = []event_issue_ids: list[str] = []signal_issue_ids: list[str] = []signal_attempts: dict[str, int] = {}@@ -230,6 +231,10 @@ async def test_only_notifies_for_an_issue_that_was_not_merged() -> None:async def merge(inputs: FingerprintEmbeddingResultInputs) -> FingerprintEmbeddingMergeResult:return FingerprintEmbeddingMergeResult(merged_count=int(inputs.fingerprint == "merged"))+ @activity.defn(name="dispatch_issue_created_alert_activity")+ async def dispatch_alert(inputs: IssueCreatedWorkflowInputs) -> None:+ alert_issue_ids.append(inputs.issue_id)+@activity.defn(name="emit_issue_created_internal_event_activity")async def emit_event(inputs: IssueCreatedWorkflowInputs) -> None:event_issue_ids.append(inputs.issue_id)@@ -247,7 +252,7 @@ async def test_only_notifies_for_an_issue_that_was_not_merged() -> None:environment.client,task_queue=task_queue,workflows=[ErrorTrackingIssueCreatedWorkflow],- activities=[generate, persist, merge, emit_event, emit_signal],+ activities=[generate, persist, merge, dispatch_alert, emit_event, emit_signal],workflow_runner=UnsandboxedWorkflowRunner(),):merged_inputs = _inputs("merged")@@ -278,6 +283,7 @@ async def test_only_notifies_for_an_issue_that_was_not_merged() -> None:notified=True,embedding_skipped_reason="embedding_service_unavailable",)+ assert alert_issue_ids == [unmerged_inputs.issue_id, embedding_unavailable_inputs.issue_id]assert event_issue_ids == [unmerged_inputs.issue_id, embedding_unavailable_inputs.issue_id]assert signal_issue_ids == [unmerged_inputs.issue_id, embedding_unavailable_inputs.issue_id]assert signal_attempts == {diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_created/workflow.py b/products/error_tracking/backend/temporal/lifecycle/issue_created/workflow.pyindex cebee61b8ef1..bf7f0cd094c0 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_created/workflow.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_created/workflow.py@@ -1,4 +1,5 @@import json+import asynciofrom datetime import timedeltafrom temporalio import common, workflow@@ -23,6 +24,15 @@ ACTIVITY_RETRY_POLICY = common.RetryPolicy(maximum_attempts=10,)ACTIVITY_START_TO_CLOSE_TIMEOUT = timedelta(minutes=5)+ALERT_DISPATCH_PATCH = "error-tracking-alert-dispatch-activity"+# Unlimited attempts inside the window: the start is cheap and idempotent, and only a+# Temporal outage longer than this loses the alert.+ALERT_DISPATCH_RETRY_POLICY = common.RetryPolicy(+ initial_interval=timedelta(seconds=5),+ maximum_interval=timedelta(minutes=1),+ maximum_attempts=0,+)+ALERT_DISPATCH_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(hours=1)EMBEDDING_ACTIVITY_RETRY_POLICY = common.RetryPolicy(initial_interval=timedelta(seconds=1),maximum_interval=timedelta(seconds=15),@@ -97,18 +107,39 @@ class ErrorTrackingIssueCreatedWorkflow(PostHogWorkflow):if merge_result.merged_count > 0:return IssueCreatedWorkflowResult(merged=True)- await workflow.execute_activity(- "emit_issue_created_internal_event_activity",- inputs,- start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,- retry_policy=ACTIVITY_RETRY_POLICY,- )- await workflow.execute_activity(- "emit_issue_created_signal_activity",- inputs,- start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,- retry_policy=ACTIVITY_RETRY_POLICY,+ # Patched: executions in flight when this activity shipped replay the old sequence.+ # Dispatch runs alongside the other side effects and is always awaited, so a+ # failure on either side never suppresses the other. Its open-ended retry covers+ # a Temporal outage; starts are idempotent on the notification id.+ dispatch = (+ asyncio.create_task(+ workflow.execute_activity(+ "dispatch_issue_created_alert_activity",+ inputs,+ schedule_to_close_timeout=ALERT_DISPATCH_SCHEDULE_TO_CLOSE_TIMEOUT,+ start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,+ retry_policy=ALERT_DISPATCH_RETRY_POLICY,+ )+ )+ if workflow.patched(ALERT_DISPATCH_PATCH)+ else None)+ try:+ await workflow.execute_activity(+ "emit_issue_created_internal_event_activity",+ inputs,+ start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )+ await workflow.execute_activity(+ "emit_issue_created_signal_activity",+ inputs,+ start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )+ finally:+ if dispatch is not None:+ await dispatchreturn IssueCreatedWorkflowResult(notified=True,embedding_skipped_reason=preparation.skipped_reason,diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/activities.py b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/activities.pyindex e311fbfafd18..e905345a04aa 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/activities.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/activities.py@@ -6,11 +6,19 @@ from posthog.temporal.common.utils import close_db_connectionsfrom products.error_tracking.backend.temporal.lifecycle.issue_reopened.types import IssueReopenedWorkflowInputsfrom products.error_tracking.backend.temporal.lifecycle.side_effects import (+ dispatch_issue_lifecycle_alert,emit_issue_lifecycle_signal,produce_issue_lifecycle_internal_event,)+@close_db_connections+def dispatch_issue_reopened_alert_activity(inputs: IssueReopenedWorkflowInputs) -> None:+ dispatch_issue_lifecycle_alert(inputs, event="$error_tracking_issue_reopened")++@activity.defn@posthoganalytics.scoped()@close_db_connections@@ -37,6 +45,7 @@ async def emit_issue_reopened_signal_activity(inputs: IssueReopenedWorkflowInputACTIVITIES = [+ dispatch_issue_reopened_alert_activity,emit_issue_reopened_internal_event_activity,emit_issue_reopened_signal_activity,]diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/test/test_issue_reopened_workflow.py b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/test/test_issue_reopened_workflow.pyindex 8884c5aa67d7..3b50ee20439d 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/test/test_issue_reopened_workflow.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/test/test_issue_reopened_workflow.py@@ -5,6 +5,8 @@ import dataclassesimport pytestfrom temporalio import activity+from temporalio.client import WorkflowFailureError+from temporalio.exceptions import ApplicationErrorfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker@@ -52,6 +54,10 @@ async def test_retries_and_emits_both_reopened_side_effects() -> None:emitted_signals: list[str] = []signal_attempts = 0+ @activity.defn(name="dispatch_issue_reopened_alert_activity")+ async def dispatch_alert(_: IssueReopenedWorkflowInputs) -> None:+ return None+@activity.defn(name="emit_issue_reopened_internal_event_activity")async def emit_event(inputs: IssueReopenedWorkflowInputs) -> None:emitted_events.append(inputs.issue_id)@@ -71,7 +77,7 @@ async def test_retries_and_emits_both_reopened_side_effects() -> None:environment.client,task_queue=task_queue,workflows=[ErrorTrackingIssueReopenedWorkflow],- activities=[emit_event, emit_signal],+ activities=[dispatch_alert, emit_event, emit_signal],workflow_runner=UnsandboxedWorkflowRunner(),):result = await environment.client.execute_workflow(@@ -85,3 +91,40 @@ async def test_retries_and_emits_both_reopened_side_effects() -> None:assert emitted_events == [inputs.issue_id]assert emitted_signals == [inputs.issue_id]assert signal_attempts == 2+++async def test_alert_dispatch_runs_even_when_the_internal_event_fails_for_good() -> None:+ dispatched: list[str] = []++ @activity.defn(name="dispatch_issue_reopened_alert_activity")+ async def dispatch_alert(inputs: IssueReopenedWorkflowInputs) -> None:+ dispatched.append(inputs.issue_id)++ @activity.defn(name="emit_issue_reopened_internal_event_activity")+ async def emit_event(_: IssueReopenedWorkflowInputs) -> None:+ raise ApplicationError("kafka unavailable", non_retryable=True)++ @activity.defn(name="emit_issue_reopened_signal_activity")+ async def emit_signal(_: IssueReopenedWorkflowInputs) -> None:+ return None++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as environment:+ async with Worker(+ environment.client,+ task_queue=task_queue,+ workflows=[ErrorTrackingIssueReopenedWorkflow],+ activities=[dispatch_alert, emit_event, emit_signal],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ inputs = _inputs()+ with pytest.raises(WorkflowFailureError):+ await environment.client.execute_workflow(+ ErrorTrackingIssueReopenedWorkflow.run,+ inputs,+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert dispatched == [inputs.issue_id]diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/workflow.py b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/workflow.pyindex 008d25f916cb..466c7352e2b9 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/workflow.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/workflow.py@@ -1,4 +1,5 @@import json+import asynciofrom datetime import timedeltafrom temporalio import common, workflow@@ -19,6 +20,15 @@ ACTIVITY_RETRY_POLICY = common.RetryPolicy(maximum_attempts=10,)ACTIVITY_START_TO_CLOSE_TIMEOUT = timedelta(minutes=5)+ALERT_DISPATCH_PATCH = "error-tracking-alert-dispatch-activity"+# Unlimited attempts inside the window: the start is cheap and idempotent, and only a+# Temporal outage longer than this loses the alert.+ALERT_DISPATCH_RETRY_POLICY = common.RetryPolicy(+ initial_interval=timedelta(seconds=5),+ maximum_interval=timedelta(minutes=1),+ maximum_attempts=0,+)+ALERT_DISPATCH_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(hours=1)@workflow.defn(name=WORKFLOW_NAME)@@ -39,16 +49,37 @@ class ErrorTrackingIssueReopenedWorkflow(PostHogWorkflow):@workflow.runasync def run(self, inputs: IssueReopenedWorkflowInputs) -> IssueReopenedWorkflowResult:- await workflow.execute_activity(- "emit_issue_reopened_internal_event_activity",- inputs,- start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,- retry_policy=ACTIVITY_RETRY_POLICY,- )- await workflow.execute_activity(- "emit_issue_reopened_signal_activity",- inputs,- start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,- retry_policy=ACTIVITY_RETRY_POLICY,+ # Patched: executions in flight when this activity shipped replay the old sequence.+ # Dispatch runs alongside the other side effects and is always awaited, so a+ # failure on either side never suppresses the other. Its open-ended retry covers+ # a Temporal outage; starts are idempotent on the notification id.+ dispatch = (+ asyncio.create_task(+ workflow.execute_activity(+ "dispatch_issue_reopened_alert_activity",+ inputs,+ schedule_to_close_timeout=ALERT_DISPATCH_SCHEDULE_TO_CLOSE_TIMEOUT,+ start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,+ retry_policy=ALERT_DISPATCH_RETRY_POLICY,+ )+ )+ if workflow.patched(ALERT_DISPATCH_PATCH)+ else None)+ try:+ await workflow.execute_activity(+ "emit_issue_reopened_internal_event_activity",+ inputs,+ start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )+ await workflow.execute_activity(+ "emit_issue_reopened_signal_activity",+ inputs,+ start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )+ finally:+ if dispatch is not None:+ await dispatchreturn IssueReopenedWorkflowResult(notified=True)diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_spiking/activities.py b/products/error_tracking/backend/temporal/lifecycle/issue_spiking/activities.pyindex 7e50676f91d6..e729bde84982 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_spiking/activities.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_spiking/activities.py@@ -13,6 +13,7 @@ from products.error_tracking.backend.temporal.lifecycle.issue_spiking.types impoSpikeEventPersistenceResult,)from products.error_tracking.backend.temporal.lifecycle.side_effects import (+ dispatch_issue_lifecycle_alert,emit_issue_lifecycle_signal,produce_issue_lifecycle_internal_event,)@@ -52,6 +53,21 @@ def persist_issue_spiking_event_activity(inputs: IssueSpikingWorkflowInputs) ->)+@close_db_connections+def dispatch_issue_spiking_alert_activity(inputs: IssueSpikingWorkflowInputs) -> None:+ dispatch_issue_lifecycle_alert(+ inputs,+ event="$error_tracking_issue_spiking",+ extra_properties={+ "computed_baseline": inputs.computed_baseline,+ "current_bucket_value": inputs.current_bucket_value,+ },+ include_status=False,+ )++@activity.defn@posthoganalytics.scoped()@close_db_connections@@ -85,6 +101,7 @@ async def emit_issue_spiking_signal_activity(inputs: IssueSpikingWorkflowInputs)ACTIVITIES = [+ dispatch_issue_spiking_alert_activity,persist_issue_spiking_event_activity,emit_issue_spiking_internal_event_activity,emit_issue_spiking_signal_activity,diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_spiking/test/test_issue_spiking_workflow.py b/products/error_tracking/backend/temporal/lifecycle/issue_spiking/test/test_issue_spiking_workflow.pyindex 2ccc1f24feba..ff2d589e265c 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_spiking/test/test_issue_spiking_workflow.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_spiking/test/test_issue_spiking_workflow.py@@ -87,6 +87,10 @@ async def test_notifies_after_idempotent_persistence_and_ignores_missing_issues(}[inputs.fingerprint]return SpikeEventPersistenceResult(status=status)+ @activity.defn(name="dispatch_issue_spiking_alert_activity")+ async def dispatch_alert(_: IssueSpikingWorkflowInputs) -> None:+ return None+@activity.defn(name="emit_issue_spiking_internal_event_activity")async def emit_event(inputs: IssueSpikingWorkflowInputs) -> None:emitted_events.append(inputs.issue_id)@@ -102,7 +106,7 @@ async def test_notifies_after_idempotent_persistence_and_ignores_missing_issues(environment.client,task_queue=task_queue,workflows=[ErrorTrackingIssueSpikingWorkflow],- activities=[persist, emit_event, emit_signal],+ activities=[persist, dispatch_alert, emit_event, emit_signal],workflow_runner=UnsandboxedWorkflowRunner(),):results = {diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_spiking/workflow.py b/products/error_tracking/backend/temporal/lifecycle/issue_spiking/workflow.pyindex 5da390df9f33..a00effeeb7c3 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_spiking/workflow.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_spiking/workflow.py@@ -1,4 +1,5 @@import json+import asynciofrom datetime import timedeltafrom temporalio import common, workflow@@ -21,6 +22,15 @@ ACTIVITY_RETRY_POLICY = common.RetryPolicy(maximum_attempts=10,)ACTIVITY_START_TO_CLOSE_TIMEOUT = timedelta(minutes=5)+ALERT_DISPATCH_PATCH = "error-tracking-alert-dispatch-activity"+# Unlimited attempts inside the window: the start is cheap and idempotent, and only a+# Temporal outage longer than this loses the alert.+ALERT_DISPATCH_RETRY_POLICY = common.RetryPolicy(+ initial_interval=timedelta(seconds=5),+ maximum_interval=timedelta(minutes=1),+ maximum_attempts=0,+)+ALERT_DISPATCH_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(hours=1)@workflow.defn(name=WORKFLOW_NAME)@@ -72,16 +82,37 @@ class ErrorTrackingIssueSpikingWorkflow(PostHogWorkflow):}:raise ValueError(f"Unknown spike persistence status: {persistence.status}")- await workflow.execute_activity(- "emit_issue_spiking_internal_event_activity",- inputs,- start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,- retry_policy=ACTIVITY_RETRY_POLICY,- )- await workflow.execute_activity(- "emit_issue_spiking_signal_activity",- inputs,- start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,- retry_policy=ACTIVITY_RETRY_POLICY,+ # Patched: executions in flight when this activity shipped replay the old sequence.+ # Dispatch runs alongside the other side effects and is always awaited, so a+ # failure on either side never suppresses the other. Its open-ended retry covers+ # a Temporal outage; starts are idempotent on the notification id.+ dispatch = (+ asyncio.create_task(+ workflow.execute_activity(+ "dispatch_issue_spiking_alert_activity",+ inputs,+ schedule_to_close_timeout=ALERT_DISPATCH_SCHEDULE_TO_CLOSE_TIMEOUT,+ start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,+ retry_policy=ALERT_DISPATCH_RETRY_POLICY,+ )+ )+ if workflow.patched(ALERT_DISPATCH_PATCH)+ else None)+ try:+ await workflow.execute_activity(+ "emit_issue_spiking_internal_event_activity",+ inputs,+ start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )+ await workflow.execute_activity(+ "emit_issue_spiking_signal_activity",+ inputs,+ start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )+ finally:+ if dispatch is not None:+ await dispatchreturn IssueSpikingWorkflowResult(persisted=True, notified=True)diff --git a/products/error_tracking/backend/temporal/lifecycle/side_effects.py b/products/error_tracking/backend/temporal/lifecycle/side_effects.pyindex bafea573c554..99d68a4ffe3d 100644--- a/products/error_tracking/backend/temporal/lifecycle/side_effects.py+++ b/products/error_tracking/backend/temporal/lifecycle/side_effects.py@@ -14,6 +14,8 @@ from posthog.helpers.tiktoken_encoding import ()from posthog.models import Team+from products.error_tracking.backend.temporal.alerts.dispatch import start_alert_delivery_workflow+from products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputsfrom products.error_tracking.backend.temporal.lifecycle.event_properties import (EventPropertiesIssueSnapshot,fetch_event_properties,@@ -68,6 +70,75 @@ class IssueLifecycleWorkflowInputs(Protocol):def assignee(self) -> str | None: ...+_STATUS_LABELS = {+ "archived": "Archived",+ "active": "Active",+ "resolved": "Resolved",+ "pending_release": "Pending Release",+ "suppressed": "Suppressed",+}+++def _status_property(+ inputs: IssueLifecycleWorkflowInputs, *, include_status: bool, humanize_status: bool+) -> str | None:+ if not include_status:+ return None+ status = inputs.issue.status+ return _STATUS_LABELS.get(status, status) if humanize_status else status+++def alert_delivery_inputs(+ inputs: IssueLifecycleWorkflowInputs,+ *,+ event: str,+ extra_properties: dict[str, object] | None = None,+ include_status: bool = True,+ humanize_status: bool = True,+) -> AlertDeliveryWorkflowInputs:+ """The alert workflow's view of a lifecycle transition, mirroring the internal event's properties."""+ extra = {+ key: str(value)+ for key, value in (extra_properties or {}).items()+ if key in ("computed_baseline", "current_bucket_value") and value is not None+ }+ return AlertDeliveryWorkflowInputs.build(+ notification_id=inputs.notification_id,+ team_id=inputs.team_id,+ issue_id=inputs.issue_id,+ event=event,+ issue_name=inputs.issue.name,+ issue_description=inputs.issue.description,+ status=_status_property(inputs, include_status=include_status, humanize_status=humanize_status),+ assignee=inputs.assignee,+ event_uuid=inputs.event_uuid,+ # Paired with event_uuid, so it must be the exception's own time: spiking+ # passes the detection time as exception_timestamp, which can differ.+ event_timestamp=inputs.event_timestamp,+ extra=extra or None,+ )+++def dispatch_issue_lifecycle_alert(+ inputs: IssueLifecycleWorkflowInputs,+ *,+ event: str,+ extra_properties: dict[str, object] | None = None,+ include_status: bool = True,+ humanize_status: bool = True,+) -> None:+ """Start the alert delivery workflow; raises so the calling activity's retry policy re-drives it."""+ start_alert_delivery_workflow(+ alert_delivery_inputs(+ inputs,+ event=event,+ extra_properties=extra_properties,+ include_status=include_status,+ humanize_status=humanize_status,+ )+ )++def produce_issue_lifecycle_internal_event(inputs: IssueLifecycleWorkflowInputs,*,@@ -99,19 +170,9 @@ def produce_issue_lifecycle_internal_event("exception_timestamp": timestamp.isoformat(),"exception_props": event_properties,}- if include_status:- status = inputs.issue.status- properties["status"] = (- {- "archived": "Archived",- "active": "Active",- "resolved": "Resolved",- "pending_release": "Pending Release",- "suppressed": "Suppressed",- }.get(status, status)- if humanize_status- else status- )+ status_property = _status_property(inputs, include_status=include_status, humanize_status=humanize_status)+ if status_property is not None:+ properties["status"] = status_propertyif inputs.assignee is not None:properties["assignee"] = inputs.assigneeif extra_properties is not None:diff --git a/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.py b/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.pyindex 2c13e4096351..193497fc46bc 100644--- a/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.py+++ b/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.py@@ -16,8 +16,14 @@ from products.error_tracking.backend.temporal.lifecycle.issue_reopened.types impIssueReopenedSnapshot,IssueReopenedWorkflowInputs,)+from products.error_tracking.backend.temporal.lifecycle.issue_spiking.types import (+ IssueSpikingSnapshot,+ IssueSpikingWorkflowInputs,+)from products.error_tracking.backend.temporal.lifecycle.rendering import SIGNAL_MAX_TOKENSfrom products.error_tracking.backend.temporal.lifecycle.side_effects import (+ alert_delivery_inputs,+ dispatch_issue_lifecycle_alert,emit_issue_lifecycle_signal,produce_issue_lifecycle_internal_event,)@@ -156,6 +162,7 @@ def test_oversized_internal_event_retries_without_exception_properties() -> Nonedef test_internal_event_reraises_non_size_kafka_errors() -> None:+ inputs = _inputs()result = MagicMock()result.get.side_effect = KafkaException(KafkaError(KafkaError._TRANSPORT)) # type: ignore[attr-defined]sent_events: list[InternalEventEvent] = []@@ -181,9 +188,9 @@ def test_internal_event_reraises_non_size_kafka_errors() -> None:pytest.raises(KafkaException),):produce_issue_lifecycle_internal_event(- _inputs(),+ inputs,event="$error_tracking_issue_spiking",- exception_timestamp="invalid",+ exception_timestamp="2026-07-21T12:30:00Z",include_status=False,)@@ -191,6 +198,61 @@ def test_internal_event_reraises_non_size_kafka_errors() -> None:assert sent_events[0].event == "$error_tracking_issue_spiking"assert "status" not in sent_events[0].propertiesassert sent_events[0].properties["severity"] == "high"+ assert sent_events[0].properties["exception_timestamp"] == "2026-07-21T12:30:00+00:00"+++def test_alert_inputs_mirror_the_internal_event_and_key_the_exception_by_its_own_time() -> None:+ inputs = IssueSpikingWorkflowInputs(+ notification_id="01982721-5e00-7000-8000-000000000001",+ team_id=42,+ issue_id="01982721-5e00-7000-8000-000000000002",+ issue=IssueSpikingSnapshot(+ name="x" * 600,+ description="Something failed",+ status="active",+ created_at="2026-07-21T12:00:00Z",+ severity="high",+ ),+ fingerprint="fingerprint",+ event_uuid="01982721-5e00-7000-8000-000000000003",+ event_timestamp="2026-07-21T12:05:00Z",+ assignee=None,+ detected_at="2026-07-21T12:30:00Z",+ computed_baseline=2.0,+ current_bucket_value=40,+ )++ alert = alert_delivery_inputs(+ inputs,+ event="$error_tracking_issue_spiking",+ extra_properties={"computed_baseline": 2.0, "current_bucket_value": 40, "ignored": "x"},+ include_status=False,+ )++ assert alert.notification_id == inputs.notification_id+ assert alert.status is None+ # The alert keys the exception by its own timestamp even when the lifecycle event+ # carries the spike detection time.+ assert alert.event_uuid == inputs.event_uuid+ assert alert.event_timestamp == inputs.event_timestamp+ assert alert.extra == {"computed_baseline": "2.0", "current_bucket_value": "40"}+ assert alert.issue_name is not None and len(alert.issue_name) == 500++ reopened = alert_delivery_inputs(_inputs(), event="$error_tracking_issue_reopened")+ assert reopened.status == "Pending Release"+ assert reopened.assignee == '{"type":"user","id":1}'+++def test_dispatch_raises_so_the_activity_retries() -> None:+ with (+ patch(+ "products.error_tracking.backend.temporal.lifecycle.side_effects.start_alert_delivery_workflow",+ side_effect=RuntimeError("temporal down"),+ ) as start,+ pytest.raises(RuntimeError),+ ):+ dispatch_issue_lifecycle_alert(_inputs(), event="$error_tracking_issue_reopened")+ assert start.call_args.args[0].event == "$error_tracking_issue_reopened"@pytest.mark.asynciodiff --git a/products/error_tracking/backend/tests/api/test_alerts_api.py b/products/error_tracking/backend/tests/api/test_alerts_api.pyindex 243fef209379..ef1b395ee260 100644--- a/products/error_tracking/backend/tests/api/test_alerts_api.py+++ b/products/error_tracking/backend/tests/api/test_alerts_api.py@@ -202,6 +202,40 @@ class TestErrorTrackingAlerts(APIBaseTest):assert response.status_code == 400, response.json()assert ErrorTrackingAlert.objects.for_team(self.team.id).count() == 0+ def test_alert_limits_destinations_per_alert_and_alerts_per_team(self):+ integration = self._create_slack_integration()+ destinations = [+ {"channel_type": "slack", "integration_id": integration.id, "config": {"channel": f"C{i}"}}+ for i in range(3)+ ]+ with patch("products.error_tracking.backend.logic.alerts.MAX_DESTINATIONS_PER_ALERT", 2):+ create = self.client.post(+ f"/api/projects/{self.team.id}/error_tracking/alerts/",+ data=self._valid_payload(integration, destinations=destinations),+ format="json",+ )+ assert create.status_code == 400, create.json()+ assert "at most 2 destinations" in str(create.json())++ created = self._create_alert(integration)+ update = self.client.patch(+ f"/api/projects/{self.team.id}/error_tracking/alerts/{created['id']}/",+ data={"destinations": destinations},+ format="json",+ )+ assert update.status_code == 400, update.json()++ with patch("products.error_tracking.backend.logic.alerts.MAX_ALERTS_PER_TEAM", 2):+ self._create_alert(integration, name="Second")+ third = self.client.post(+ f"/api/projects/{self.team.id}/error_tracking/alerts/",+ data=self._valid_payload(integration, name="Third"),+ format="json",+ )+ assert third.status_code == 400, third.json()+ assert "at most 2 alerts" in str(third.json())+ assert ErrorTrackingAlert.objects.for_team(self.team.id).count() == 2+def test_alert_rejects_duplicate_destinations(self):integration = self._create_slack_integration()destination = {"channel_type": "slack", "integration_id": integration.id, "config": {"channel": "C0123"}}diff --git a/products/error_tracking/backend/tests/api/test_error_tracking_api.py b/products/error_tracking/backend/tests/api/test_error_tracking_api.pyindex 297d60f8338a..162e1c48665c 100644--- a/products/error_tracking/backend/tests/api/test_error_tracking_api.py+++ b/products/error_tracking/backend/tests/api/test_error_tracking_api.py@@ -19,6 +19,7 @@ from rest_framework import statusfrom posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.integration import Integration+from posthog.models.scoping import team_scopefrom posthog.models.utils import uuid7from posthog.settings import (OBJECT_STORAGE_ACCESS_KEY_ID,@@ -29,6 +30,7 @@ from posthog.settings import (from products.access_control.backend.models.role import Rolefrom products.error_tracking.backend.models import (+ ErrorTrackingAlert,ErrorTrackingIssue,ErrorTrackingIssueAssignment,ErrorTrackingIssueFingerprintV2,@@ -583,6 +585,133 @@ class TestErrorTracking(APIBaseTest):issue.refresh_from_db()assert issue.status == ErrorTrackingIssue.Status.RESOLVED+ def _enable_alerts(self) -> None:+ with team_scope(self.team.id):+ ErrorTrackingAlert.objects.create(team=self.team, name="Notify", triggers=["issue_created"])++ def test_issue_status_update_queues_alert_dispatch_with_the_event_uuid(self):+ issue = self.create_issue()+ self._enable_alerts()++ with (+ patch("products.error_tracking.backend.logic.lifecycle_events.produce_internal_event") as mock_produce,+ patch(+ "products.error_tracking.backend.tasks.tasks.dispatch_error_tracking_alert_deliveries.delay"+ ) as mock_dispatch,+ self.captureOnCommitCallbacks(execute=True),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/error_tracking/issues/{issue.id}",+ data={"status": "resolved"},+ )++ assert response.status_code == 200, response.json()+ mock_dispatch.assert_called_once()+ kwargs = mock_dispatch.call_args.kwargs+ assert kwargs["team_id"] == self.team.id+ (notification,) = kwargs["notifications"]+ assert notification["event"] == "$error_tracking_issue_resolved"+ assert notification["issue_id"] == str(issue.id)+ assert notification["status"] == "Resolved"+ assert notification["actor_email"] == self.user.email+ # The delivery workflow and the internal event share the notification id.+ assert notification["notification_id"] == mock_produce.call_args.kwargs["event"].uuid++ def test_issue_status_update_survives_a_broker_outage(self):+ issue = self.create_issue()+ self._enable_alerts()++ with (+ patch("products.error_tracking.backend.logic.lifecycle_events.produce_internal_event") as mock_produce,+ patch(+ "products.error_tracking.backend.tasks.tasks.dispatch_error_tracking_alert_deliveries.delay",+ side_effect=ConnectionError("broker down"),+ ),+ self.captureOnCommitCallbacks(execute=True),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/error_tracking/issues/{issue.id}",+ data={"status": "resolved"},+ )++ # The status committed before the enqueue ran, so the response reports success.+ assert response.status_code == 200, response.json()+ mock_produce.assert_called_once()+ issue.refresh_from_db()+ assert issue.status == ErrorTrackingIssue.Status.RESOLVED++ def test_issue_bulk_assign_queues_one_dispatch_task_per_transaction(self):+ issues = [self.create_issue() for _ in range(3)]+ self._enable_alerts()++ with (+ patch("products.error_tracking.backend.logic.lifecycle_events.produce_internal_event") as mock_produce,+ patch(+ "products.error_tracking.backend.tasks.tasks.dispatch_error_tracking_alert_deliveries.delay"+ ) as mock_dispatch,+ patch("products.error_tracking.backend.logic.issue_mutations.send_error_tracking_issue_assigned"),+ patch("products.error_tracking.backend.logic.issue_mutations.dispatch_issue_assigned_realtime"),+ self.captureOnCommitCallbacks(execute=True),+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/issues/bulk",+ data={+ "ids": [issue.id for issue in issues],+ "action": "assign",+ "assignee": {"id": self.user.id, "type": "user"},+ },+ )++ assert response.status_code == 200, response.json()+ assert mock_produce.call_count == 3+ mock_dispatch.assert_called_once()+ notifications = mock_dispatch.call_args.kwargs["notifications"]+ assert {n["event"] for n in notifications} == {"$error_tracking_issue_assigned"}+ assert {n["issue_id"] for n in notifications} == {str(issue.id) for issue in issues}++ def test_issue_status_update_queues_nothing_for_teams_without_alerts(self):+ issue = self.create_issue()++ with (+ patch("products.error_tracking.backend.logic.lifecycle_events.produce_internal_event"),+ patch(+ "products.error_tracking.backend.tasks.tasks.dispatch_error_tracking_alert_deliveries.delay"+ ) as mock_dispatch,+ self.captureOnCommitCallbacks(execute=True),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/error_tracking/issues/{issue.id}",+ data={"status": "resolved"},+ )++ assert response.status_code == 200, response.json()+ mock_dispatch.assert_not_called()++ def test_issue_bulk_set_status_queues_one_dispatch_task_per_transaction(self):+ issues = [self.create_issue() for _ in range(3)]+ self._enable_alerts()++ with (+ patch("products.error_tracking.backend.logic.lifecycle_events.produce_internal_event") as mock_produce,+ patch(+ "products.error_tracking.backend.tasks.tasks.dispatch_error_tracking_alert_deliveries.delay"+ ) as mock_dispatch,+ self.captureOnCommitCallbacks(execute=True),+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/issues/bulk",+ data={"ids": [issue.id for issue in issues], "action": "set_status", "status": "resolved"},+ )++ assert response.status_code == 200, response.json()+ assert mock_produce.call_count == 3+ mock_dispatch.assert_called_once()+ notifications = mock_dispatch.call_args.kwargs["notifications"]+ assert {n["issue_id"] for n in notifications} == {str(issue.id) for issue in issues}+ assert {n["notification_id"] for n in notifications} == {+ call.kwargs["event"].uuid for call in mock_produce.call_args_list+ }+def test_issue_update_without_status_transition_produces_no_lifecycle_event(self):issue = self.create_issue()diff --git a/products/error_tracking/backend/tests/test_alert_delivery.py b/products/error_tracking/backend/tests/test_alert_delivery.pynew file mode 100644index 000000000000..26027a10dafc--- /dev/null+++ b/products/error_tracking/backend/tests/test_alert_delivery.py@@ -0,0 +1,331 @@+import time+import asyncio+import dataclasses+from datetime import timedelta+from typing import Any++from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, MagicMock, patch++from django.conf import settings++from parameterized import parameterized+from temporalio.common import WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedError++from posthog.models.integration import Integration+from posthog.models.scoping import team_scope++from products.error_tracking.backend.models import ErrorTrackingAlert, ErrorTrackingAlertThread, ErrorTrackingIssue+from 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.dispatch import (+ AlertDispatchError,+ start_alert_delivery_workflow,+ start_alert_delivery_workflows,+)+from products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputs+++class AlertTestMixin(BaseTest):+ def setUp(self):+ super().setUp()+ with team_scope(self.team.id):+ self.integration = Integration.objects.create(+ team=self.team,+ kind=Integration.IntegrationKind.SLACK.value,+ config={"team": {"id": "T123"}},+ sensitive_config={"access_token": "token"},+ )+ self.issue = ErrorTrackingIssue.objects.create(team=self.team)++ def _create_alert(self, *, triggers=None, enabled=True) -> ErrorTrackingAlert:+ with team_scope(self.team.id):+ alert = ErrorTrackingAlert.objects.create(+ team=self.team,+ name="Notify #alerts",+ enabled=enabled,+ triggers=triggers if triggers is not None else ["issue_created"],+ )+ alert.destinations.create(+ team=self.team,+ channel_type="slack",+ integration=self.integration,+ config={"channel": "C0123"},+ )+ return alert++ def _inputs(self, event: str, notification_id: str = "notif-1", **overrides) -> AlertDeliveryWorkflowInputs:+ defaults: dict[str, Any] = {+ "notification_id": notification_id,+ "team_id": self.team.id,+ "issue_id": str(self.issue.id),+ "event": event,+ "issue_name": "TypeError",+ "issue_description": "Something failed",+ "status": "Active",+ "actor_email": "[email protected]",+ }+ defaults.update(overrides)+ return AlertDeliveryWorkflowInputs(**defaults)+++class TestAlertDeliveryPlanning(AlertTestMixin):+ @parameterized.expand(+ [+ ("issue_created", "$error_tracking_issue_created"),+ ("issue_reopened", "$error_tracking_issue_reopened"),+ ("issue_spiking", "$error_tracking_issue_spiking"),+ ("issue_assigned", "$error_tracking_issue_assigned"),+ ]+ )+ def test_subscribed_opener_is_planned(self, trigger, event):+ alert = self._create_alert(triggers=[trigger])++ planned = plan_alert_deliveries(self._inputs(event))++ assert len(planned) == 1+ assert planned[0].alert.id == alert.id+ assert planned[0].is_opener is True+ assert planned[0].thread is None++ @parameterized.expand(+ [+ ("trigger_not_subscribed", {"triggers": ["issue_spiking"]}),+ ("alert_disabled", {"enabled": False}),+ ]+ )+ def test_non_matching_alert_is_not_planned(self, _name, alert_kwargs):+ self._create_alert(**alert_kwargs)++ planned = plan_alert_deliveries(self._inputs("$error_tracking_issue_created"))++ assert planned == []++ def test_reply_without_thread_is_not_planned(self):+ # Replies never open threads: resolved is not an opener trigger.+ self._create_alert(triggers=["issue_created"])++ planned = plan_alert_deliveries(self._inputs("$error_tracking_issue_resolved"))++ assert planned == []++ def test_reply_follows_existing_thread(self):+ alert = self._create_alert(triggers=["issue_created"])+ with team_scope(self.team.id):+ thread = ErrorTrackingAlertThread.objects.create(+ team=self.team,+ alert=alert,+ issue=self.issue,+ destination=alert.destinations.get(),+ )++ planned = plan_alert_deliveries(self._inputs("$error_tracking_issue_resolved"))++ assert len(planned) == 1+ assert planned[0].is_opener is False+ assert planned[0].thread is not None+ assert planned[0].thread.id == thread.id++ def test_repeated_opener_event_with_thread_is_a_reply(self):+ alert = self._create_alert(triggers=["issue_created", "issue_reopened"])+ with team_scope(self.team.id):+ ErrorTrackingAlertThread.objects.create(+ team=self.team,+ alert=alert,+ issue=self.issue,+ destination=alert.destinations.get(),+ )++ planned = plan_alert_deliveries(self._inputs("$error_tracking_issue_reopened"))++ assert len(planned) == 1+ assert planned[0].is_opener is False+ assert planned[0].thread is not None++ def test_multi_destination_alert_plans_per_destination(self):+ alert = self._create_alert(triggers=["issue_created"])+ with team_scope(self.team.id):+ first_destination = alert.destinations.get()+ second_destination = alert.destinations.create(+ team=self.team,+ channel_type="slack",+ integration=self.integration,+ config={"channel": "C0456"},+ )+ # Only the second destination has a rooted thread for this issue.+ thread = ErrorTrackingAlertThread.objects.create(+ team=self.team,+ alert=alert,+ issue=self.issue,+ destination=second_destination,+ )++ opener = plan_alert_deliveries(self._inputs("$error_tracking_issue_created"))+ assert len(opener) == 2+ assert {planned.destination.id for planned in opener} == {first_destination.id, second_destination.id}++ reply = plan_alert_deliveries(self._inputs("$error_tracking_issue_resolved"))+ assert len(reply) == 1+ assert reply[0].destination.id == second_destination.id+ assert reply[0].thread is not None+ assert 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.+ self._create_alert(triggers=["issue_created"])++ assert deliver_alert_notifications(self._inputs("$error_tracking_issue_created")) == 1+++class TestAlertDeliveryDispatch(AlertTestMixin):+ def _dispatch(self, *notification_ids: str) -> None:+ batch = [+ self._inputs("$error_tracking_issue_created", notification_id=nid)+ for nid in notification_ids or ("notif-1",)+ ]+ start_alert_delivery_workflows(batch)++ def _temporal(self, start_workflow: AsyncMock | None = None) -> MagicMock:+ client = MagicMock()+ client.start_workflow = start_workflow or AsyncMock()+ return client++ def test_dispatch_skips_teams_without_enabled_alerts(self):+ self._create_alert(enabled=False)+ with (+ patch("products.error_tracking.backend.temporal.alerts.dispatch.async_connect") as connect,+ patch("products.error_tracking.backend.logic.alerts.feature_enabled_or_false", return_value=True) as flag,+ ):+ self._dispatch()+ connect.assert_not_called()+ # The row gate runs first, so teams without alerts never evaluate the flag.+ flag.assert_not_called()++ def test_dispatch_skips_teams_outside_the_flag(self):+ self._create_alert()+ with (+ patch("products.error_tracking.backend.temporal.alerts.dispatch.async_connect") as connect,+ patch("products.error_tracking.backend.logic.alerts.feature_enabled_or_false", return_value=False),+ ):+ self._dispatch()+ connect.assert_not_called()++ def test_dispatch_starts_idempotent_workflow(self):+ self._create_alert()+ client = self._temporal()+ with (+ patch(+ "products.error_tracking.backend.temporal.alerts.dispatch.async_connect",+ new_callable=AsyncMock,+ return_value=client,+ ),+ patch("products.error_tracking.backend.logic.alerts.feature_enabled_or_false", return_value=True),+ ):+ start_alert_delivery_workflow(self._inputs("$error_tracking_issue_created"))++ client.start_workflow.assert_called_once()+ args, kwargs = client.start_workflow.call_args+ assert args[0] == "error-tracking-alert-delivery"+ assert args[1].notification_id == "notif-1"+ assert kwargs["id"] == "error-tracking-alert-delivery-notif-1"+ # Delivery must never ride the lifecycle fleet: slow Slack retries would starve issue-state work.+ assert kwargs["task_queue"] == settings.ERROR_TRACKING_TASK_QUEUE+ # A redelivered start after completion must be rejected, not rerun.+ assert kwargs["id_reuse_policy"] == WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY++ def test_batch_shares_one_connection_and_tolerates_already_started(self):+ self._create_alert()+ client = self._temporal(AsyncMock(side_effect=[None, WorkflowAlreadyStartedError("id", "type"), None]))+ with (+ patch(+ "products.error_tracking.backend.temporal.alerts.dispatch.async_connect",+ new_callable=AsyncMock,+ return_value=client,+ ) as connect,+ patch("products.error_tracking.backend.logic.alerts.feature_enabled_or_false", return_value=True) as flag,+ ):+ self._dispatch("n-1", "n-2", "n-3")++ connect.assert_awaited_once()+ flag.assert_called_once()+ assert client.start_workflow.await_count == 3+ assert {call.kwargs["id"] for call in client.start_workflow.call_args_list} == {+ "error-tracking-alert-delivery-n-1",+ "error-tracking-alert-delivery-n-2",+ "error-tracking-alert-delivery-n-3",+ }++ def test_batch_raises_when_any_start_is_not_accepted(self):+ # The caller retries the whole batch; accepted starts are idempotent, so only the+ # rejected one takes effect on the retry.+ self._create_alert()+ client = self._temporal(AsyncMock(side_effect=[None, RuntimeError("temporal hiccup")]))+ with (+ patch(+ "products.error_tracking.backend.temporal.alerts.dispatch.async_connect",+ new_callable=AsyncMock,+ return_value=client,+ ),+ patch("products.error_tracking.backend.logic.alerts.feature_enabled_or_false", return_value=True),+ self.assertRaises(AlertDispatchError),+ ):+ self._dispatch("n-1", "n-2")++ def test_batch_rejects_mixed_teams(self):+ other = self._inputs("$error_tracking_issue_created", notification_id="n-2", team_id=self.team.id + 1)+ with self.assertRaises(ValueError):+ start_alert_delivery_workflows([self._inputs("$error_tracking_issue_created"), other])++ def test_dispatch_gives_up_on_a_stalled_temporal(self):+ self._create_alert()++ async def hang() -> None:+ await asyncio.sleep(5)++ with (+ patch("products.error_tracking.backend.temporal.alerts.dispatch.async_connect", side_effect=hang),+ patch(+ "products.error_tracking.backend.temporal.alerts.dispatch.DISPATCH_TIMEOUT", timedelta(milliseconds=50)+ ),+ patch("products.error_tracking.backend.logic.alerts.feature_enabled_or_false", return_value=True),+ ):+ started = time.monotonic()+ with self.assertRaises(TimeoutError):+ self._dispatch()++ # The caller gets control back well before the stalled connect would return, and retries.+ assert time.monotonic() - started < 2++ def test_dispatch_raises_temporal_errors_for_the_caller_to_retry(self):+ self._create_alert()+ with (+ patch(+ "products.error_tracking.backend.temporal.alerts.dispatch.async_connect",+ side_effect=RuntimeError("temporal down"),+ ),+ patch("products.error_tracking.backend.logic.alerts.feature_enabled_or_false", return_value=True),+ self.assertRaises(RuntimeError),+ ):+ self._dispatch()++ def test_celery_task_survives_worker_death(self):+ # Acked only after the starts and requeued on worker loss; redelivery is safe+ # because starts are idempotent on the notification id.+ assert dispatch_error_tracking_alert_deliveries.acks_late is True+ assert dispatch_error_tracking_alert_deliveries.reject_on_worker_lost is True++ def test_celery_task_rebuilds_inputs_and_starts_the_batch(self):+ notifications = [+ dataclasses.asdict(self._inputs("$error_tracking_issue_resolved", notification_id="n-1")),+ dataclasses.asdict(self._inputs("$error_tracking_issue_resolved", notification_id="n-2")),+ ]+ with patch("products.error_tracking.backend.temporal.alerts.dispatch.start_alert_delivery_workflows") as start:+ dispatch_error_tracking_alert_deliveries(team_id=self.team.id, notifications=notifications)++ start.assert_called_once()+ (batch,) = start.call_args.args+ assert [inputs.notification_id for inputs in batch] == ["n-1", "n-2"]+ assert all(isinstance(inputs, AlertDeliveryWorkflowInputs) for inputs in batch)