Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(conversations): durably process slack callbacks (#98370)

Alex V5cbbe17ac62e
diff --git a/docs/internal/conversations-reliability.md b/docs/internal/conversations-reliability.md
index 530368aec86c..98596961aadf 100644
--- a/docs/internal/conversations-reliability.md
+++ b/docs/internal/conversations-reliability.md
@@ -56,7 +56,25 @@ Terminal states require `terminal_at`; non-terminal states require it to be null
Queue transitions that use `QuerySet.update()` must set `updated_at` and the appropriate terminal timestamp explicitly.
Partial indexes cover pending due work, expired processing leases, payload cleanup, and terminal-row deletion.
-The table ships empty; later PRs persist on the Slack endpoints and run the sweeper.
+
+Slack Events API and interactivity endpoints persist a receipt, then acknowledge Slack.
+`X-Slack-Retry-Num` is stored as metadata. It is never used to drop a callback.
+A Slack retry of a row that is waiting on backoff does not skip `due_at`.
+Owning-region proxy failure returns 502 so Slack retries.
+Celery `on_commit` dispatch is a wake-up hint with `apply_async(..., retry=False)`, so a hung broker cannot stall the Slack ack.
+`sweep_inbound_events` (every minute) re-drives due and expired-lease rows, then drains payload cleanup and tombstone deletion in batches of 100 until a short batch or 20 rounds.
+
+Workers claim a row with a fencing token and a 20-minute lease.
+The lease covers a crashed worker. It is not a live handler wall-clock.
+Receipt tasks have no Celery `time_limit`, because Slack ticket create plus thread backfill can run longer than a couple of minutes.
+Completes, fails, and retries require `status=processing` and the claim's fencing token, so a retry that released the row cannot be settled by a stale worker.
+Retry uses jittered backoff capped at 15 minutes, until 20 attempts or 24 hours.
+Redis is not the dedupe record on the receipt path: losing Redis must not drop or suppress a callback.
+
+Receipt workers use task names separate from the legacy payload tasks (`process_supporthog_event_receipt`, `process_supporthog_interactivity_receipt`).
+Keep the legacy task names registered until payload tasks from the old endpoint have drained.
+Live queue gauges (backlog, oldest ready age, last-sweep timestamp) are pushed through `pushed_metrics_registry`.
+Do not emit a ClickHouse event for each sweep.
## Outbound email (already in Postgres)
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 65226c6c3d20..835b7236304f 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -78,6 +78,7 @@ from products.approvals.backend.tasks import expire_old_change_requests, validat
from products.canvas.backend.tasks import cleanup_canvas_builds, sweep_canvas_builds
from products.conversations.backend.tasks.email import flush_pending_email_replies
from products.conversations.backend.tasks.maintenance import wake_snoozed_tickets
+from products.conversations.backend.tasks.slack import sweep_inbound_events
from products.conversations.backend.tasks.teams import poll_teams_shared_channels
from products.data_modeling.backend.facade.tasks import cleanup_expired_test_saved_queries
from products.data_warehouse.backend.facade.tasks import (
@@ -1004,6 +1005,14 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="flush pending conversation email replies",
)
+ # Re-drive due Slack ingress receipts. Celery on_commit is only a wake-up hint.
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(minute="*"),
+ sweep_inbound_events.s(),
+ name="sweep conversation inbound events",
+ )
+
# Pull ambient messages from MS Teams shared channels (which never push them
# over the bot webhook) into the ticket pipeline via Graph messages/delta.
add_periodic_task_with_expiry(
diff --git a/products/conversations/backend/api/slack_events.py b/products/conversations/backend/api/slack_events.py
index 9162cc6dd982..2553aa011ccf 100644
--- a/products/conversations/backend/api/slack_events.py
+++ b/products/conversations/backend/api/slack_events.py
@@ -1,7 +1,7 @@
"""Slack events endpoint for SupportHog app."""
import json
-from typing import Any, cast
+from typing import Any
from django.conf import settings
from django.http import HttpRequest, HttpResponse, JsonResponse
@@ -11,9 +11,15 @@ import structlog
from posthog.models.integration import SlackIntegrationError
+from products.conversations.backend.models import ConversationInboundEventSource
+from products.conversations.backend.services.inbound_events import (
+ accept_inbound_event,
+ slack_events_source_id,
+ slack_retry_metadata,
+)
from products.conversations.backend.services.region_routing import is_primary_region, proxy_to_secondary_region
-from products.conversations.backend.support_slack import team_exists_for_slack_workspace, validate_support_request
-from products.conversations.backend.tasks.slack import process_supporthog_event
+from products.conversations.backend.support_slack import team_for_slack_workspace, validate_support_request
+from products.conversations.backend.tasks.slack import wake_inbound_event
logger = structlog.get_logger(__name__)
@@ -27,30 +33,47 @@ SUPPORT_EVENT_TYPES = [
]
-def _route_event_to_relevant_region(request: HttpRequest, data: dict) -> None:
- event_id = data.get("event_id") if isinstance(data.get("event_id"), str) else None
- event = data.get("event", {})
- slack_team_id = data.get("team_id", "")
+def _accept_event_callback(request: HttpRequest, data: dict[str, Any]) -> HttpResponse:
+ raw_event = data.get("event")
+ event: dict[str, Any] = raw_event if isinstance(raw_event, dict) else {}
+ slack_team_id = data.get("team_id", "") if isinstance(data.get("team_id"), str) else ""
inner_event_type = event.get("type")
+ retry_num, retry_reason = slack_retry_metadata(request)
logger.info(
"supporthog_event_callback",
inner_event_type=inner_event_type,
slack_team_id=slack_team_id,
channel=event.get("channel"),
+ retry_num=retry_num,
)
if inner_event_type not in SUPPORT_EVENT_TYPES:
- return
+ return HttpResponse(status=202)
+
+ team = team_for_slack_workspace(slack_team_id) if slack_team_id else None
+
+ if team is not None and not (settings.DEBUG and is_primary_region(request)):
+ event_id = data.get("event_id") if isinstance(data.get("event_id"), str) else None
+ accept_inbound_event(
+ team=team,
+ source=ConversationInboundEventSource.SLACK_EVENTS,
+ source_id=slack_events_source_id(event_id=event_id, signed_body=request.body),
+ provider_account_id=slack_team_id,
+ payload=data,
+ provider_retry_num=retry_num,
+ provider_retry_reason=retry_reason,
+ wake=wake_inbound_event,
+ )
+ return HttpResponse(status=202)
- team_exists = team_exists_for_slack_workspace(slack_team_id) if slack_team_id else False
+ if is_primary_region(request):
+ if not proxy_to_secondary_region(request, log_prefix="supporthog"):
+ return HttpResponse("Failed to reach owning region", status=502)
+ return HttpResponse(status=202)
- if team_exists and not (settings.DEBUG and is_primary_region(request)):
- cast(Any, process_supporthog_event).delay(event=event, slack_team_id=slack_team_id, event_id=event_id)
- elif is_primary_region(request):
- proxy_to_secondary_region(request, log_prefix="supporthog")
- else:
- logger.warning("supporthog_no_team_any_region", slack_team_id=slack_team_id)
+ logger.warning("supporthog_no_team_any_region", slack_team_id=slack_team_id)
+ return HttpResponse(status=202)
@csrf_exempt
@@ -64,6 +87,8 @@ def supporthog_event_handler(request: HttpRequest) -> HttpResponse:
Regional routing: EU is the primary region. If the workspace isn't found
locally, the request is proxied to the secondary region (US).
+ A 2xx means the owning region's Postgres receipt committed, not that a
+ worker has processed the callback.
"""
if request.method != "POST":
return HttpResponse(status=405)
@@ -74,15 +99,12 @@ def supporthog_event_handler(request: HttpRequest) -> HttpResponse:
logger.warning("supporthog_event_invalid_request", error=str(e))
return HttpResponse("Invalid request", status=403)
- retry_num = request.headers.get("X-Slack-Retry-Num")
- if retry_num:
- logger.info("supporthog_event_retry_skipped", retry_num=retry_num)
- return HttpResponse(status=200)
-
try:
data = json.loads(request.body)
except json.JSONDecodeError:
return HttpResponse("Invalid JSON", status=400)
+ if not isinstance(data, dict):
+ return HttpResponse("Invalid JSON", status=400)
logger.info("supporthog_event_received", event_type=data.get("type"))
@@ -94,7 +116,6 @@ def supporthog_event_handler(request: HttpRequest) -> HttpResponse:
return JsonResponse({"challenge": challenge})
if event_type == "event_callback":
- _route_event_to_relevant_region(request, data)
- return HttpResponse(status=202)
+ return _accept_event_callback(request, data)
return HttpResponse(status=200)
diff --git a/products/conversations/backend/api/slack_interactivity.py b/products/conversations/backend/api/slack_interactivity.py
index d6cfae50338a..bf53606eb2ba 100644
--- a/products/conversations/backend/api/slack_interactivity.py
+++ b/products/conversations/backend/api/slack_interactivity.py
@@ -7,7 +7,6 @@ The events endpoint posts the prompt; this endpoint handles the click and create
"""
import json
-from typing import Any, cast
from django.conf import settings
from django.http import HttpRequest, HttpResponse
@@ -17,9 +16,15 @@ import structlog
from posthog.models.integration import SlackIntegrationError
+from products.conversations.backend.models import ConversationInboundEventSource
+from products.conversations.backend.services.inbound_events import (
+ accept_inbound_event,
+ slack_interactivity_source_id,
+ slack_retry_metadata,
+)
from products.conversations.backend.services.region_routing import is_primary_region, proxy_to_secondary_region
-from products.conversations.backend.support_slack import team_exists_for_slack_workspace, validate_support_request
-from products.conversations.backend.tasks.slack import process_supporthog_interactivity
+from products.conversations.backend.support_slack import team_for_slack_workspace, validate_support_request
+from products.conversations.backend.tasks.slack import wake_inbound_event
logger = structlog.get_logger(__name__)
@@ -30,6 +35,8 @@ def supporthog_interactivity_handler(request: HttpRequest) -> HttpResponse:
Regional routing matches the events endpoint: EU is the primary region. If the
workspace isn't found locally, the request is proxied to the secondary region (US).
+ A 2xx means the owning region's Postgres receipt committed, not that a worker has
+ processed the click.
"""
if request.method != "POST":
return HttpResponse(status=405)
@@ -40,28 +47,53 @@ def supporthog_interactivity_handler(request: HttpRequest) -> HttpResponse:
logger.warning("supporthog_interactivity_invalid_request", error=str(e))
return HttpResponse("Invalid request", status=403)
+ # Hash the form `payload` field. request.body is already consumed after request.POST
+ # on ASGI, and Slack retries send the same payload JSON.
+ raw_payload = request.POST.get("payload", "{}")
try:
- payload = json.loads(request.POST.get("payload", "{}"))
+ payload = json.loads(raw_payload)
except (json.JSONDecodeError, TypeError):
return HttpResponse("Invalid JSON", status=400)
if not isinstance(payload, dict):
return HttpResponse("Invalid payload", status=400)
- slack_team_id = (payload.get("team") or {}).get("id", "")
+ slack_team = payload.get("team")
+ slack_team_id = slack_team.get("id", "") if isinstance(slack_team, dict) else ""
if not slack_team_id:
return HttpResponse(status=200)
- logger.info("supporthog_interactivity_received", payload_type=payload.get("type"), slack_team_id=slack_team_id)
+ retry_num, retry_reason = slack_retry_metadata(request)
+ logger.info(
+ "supporthog_interactivity_received",
+ payload_type=payload.get("type"),
+ slack_team_id=slack_team_id,
+ retry_num=retry_num,
+ )
+
+ team = team_for_slack_workspace(slack_team_id)
+ if team is not None and not (settings.DEBUG and is_primary_region(request)):
+ accept_inbound_event(
+ team=team,
+ source=ConversationInboundEventSource.SLACK_INTERACTIVITY,
+ source_id=slack_interactivity_source_id(
+ payload=payload,
+ signed_body=(raw_payload or "").encode("utf-8"),
+ ),
+ provider_account_id=slack_team_id,
+ payload=payload,
+ provider_retry_num=retry_num,
+ provider_retry_reason=retry_reason,
+ wake=wake_inbound_event,
+ )
+ return HttpResponse(status=200)
- if team_exists_for_slack_workspace(slack_team_id) and not (settings.DEBUG and is_primary_region(request)):
- cast(Any, process_supporthog_interactivity).delay(payload=payload, slack_team_id=slack_team_id)
- elif is_primary_region(request):
+ if is_primary_region(request):
# Acking a failed proxy with 200 makes the click silently vanish — Slack shows the
# clicker nothing and never resends. Surface the failure so Slack displays a
# delivery error and the user knows to click again.
if not proxy_to_secondary_region(request, log_prefix="supporthog_interactivity"):
return HttpResponse("Failed to reach owning region", status=502)
- else:
- logger.warning("supporthog_interactivity_no_team_any_region", slack_team_id=slack_team_id)
+ return HttpResponse(status=200)
+ logger.warning("supporthog_interactivity_no_team_any_region", slack_team_id=slack_team_id)
return HttpResponse(status=200)
diff --git a/products/conversations/backend/api/tests/test_slack_endpoints.py b/products/conversations/backend/api/tests/test_slack_endpoints.py
index 2e4a4654dabe..b8a2669e0acc 100644
--- a/products/conversations/backend/api/tests/test_slack_endpoints.py
+++ b/products/conversations/backend/api/tests/test_slack_endpoints.py
@@ -1,4 +1,5 @@
import json
+import hashlib
from typing import Any
from urllib.parse import parse_qs, urlencode, urlparse
@@ -6,6 +7,7 @@ from posthog.test.base import APIBaseTest, BaseTest
from unittest.mock import MagicMock, patch
from django.core.cache import cache
+from django.http import HttpResponse
from parameterized import parameterized
from rest_framework.test import APIClient
@@ -14,7 +16,12 @@ from slack_sdk.errors import SlackApiError
from posthog.models.integration import SlackIntegrationError
from posthog.models.organization import OrganizationMembership
-from products.conversations.backend.models import TeamConversationsSlackConfig
+from products.conversations.backend.models import (
+ ConversationInboundEvent,
+ ConversationInboundEventSource,
+ TeamConversationsSlackConfig,
+)
+from products.conversations.backend.models.inbound_event import INBOUND_PAYLOAD_MAX_BYTES
class TestSupportSlackEventsAPI(BaseTest):
@@ -40,6 +47,13 @@ class TestSupportSlackEventsAPI(BaseTest):
**kwargs,
)
+ def _post_committed(self, payload: dict[str, Any], **kwargs: Any) -> HttpResponse:
+ with self.captureOnCommitCallbacks(execute=True):
+ return self._post(payload, **kwargs)
+
+ def _event_row(self) -> ConversationInboundEvent:
+ return ConversationInboundEvent.objects.for_team(self.team.id).get()
+
@patch("products.conversations.backend.api.slack_events.validate_support_request")
def test_invalid_signature_returns_403(self, mock_validate: MagicMock):
mock_validate.side_effect = SlackIntegrationError("Invalid")
@@ -48,20 +62,28 @@ class TestSupportSlackEventsAPI(BaseTest):
assert response.status_code == 403
- @patch("products.conversations.backend.api.slack_events.process_supporthog_event")
+ @patch("products.conversations.backend.api.slack_events.wake_inbound_event")
@patch("products.conversations.backend.api.slack_events.validate_support_request")
- def test_slack_retry_returns_200_without_processing(self, mock_validate: MagicMock, mock_process: MagicMock):
+ def test_slack_retry_is_recorded_and_processed(self, mock_validate: MagicMock, mock_wake: MagicMock):
mock_validate.return_value = None
+ payload = {
+ "type": "event_callback",
+ "event_id": "Ev_retry",
+ "team_id": "T123",
+ "event": {"type": "message", "channel": "C1"},
+ }
- response = self.client.post(
- "/api/conversations/v1/slack/events",
- data=json.dumps({"type": "event_callback", "team_id": "T123", "event": {"type": "message"}}),
- content_type="application/json",
- headers={"x-slack-retry-num": "1"},
+ response = self._post_committed(
+ payload,
+ headers={"x-slack-retry-num": "2", "x-slack-retry-reason": "http_timeout"},
)
- assert response.status_code == 200
- mock_process.delay.assert_not_called()
+ assert response.status_code == 202
+ mock_wake.assert_called_once()
+ row = self._event_row()
+ assert row.provider_retry_num == 2
+ assert row.provider_retry_reason == "http_timeout"
+ assert row.status == ConversationInboundEvent.Status.PENDING
@patch("products.conversations.backend.api.slack_events.validate_support_request")
def test_invalid_json_returns_400(self, mock_validate: MagicMock):
@@ -84,9 +106,9 @@ class TestSupportSlackEventsAPI(BaseTest):
assert response.status_code == 200
assert response.json() == {"challenge": "challenge123"}
- @patch("products.conversations.backend.api.slack_events.process_supporthog_event")
+ @patch("products.conversations.backend.api.slack_events.wake_inbound_event")
@patch("products.conversations.backend.api.slack_events.validate_support_request")
- def test_event_callback_enqueues_processing(self, mock_validate: MagicMock, mock_process: MagicMock):
+ def test_event_callback_enqueues_processing(self, mock_validate: MagicMock, mock_wake: MagicMock):
mock_validate.return_value = None
payload = {
"type": "event_callback",
@@ -95,19 +117,20 @@ class TestSupportSlackEventsAPI(BaseTest):
"event": {"type": "message", "channel": "C1"},
}
- first = self._post(payload)
- second = self._post(payload)
+ first = self._post_committed(payload)
+ second = self._post_committed(payload)
assert first.status_code == 202
assert second.status_code == 202
- assert mock_process.delay.call_count == 2
+ assert ConversationInboundEvent.objects.for_team(self.team.id).count() == 1
+ assert mock_wake.call_count == 2
- @patch("products.conversations.backend.api.slack_events.process_supporthog_event")
+ @patch("products.conversations.backend.api.slack_events.wake_inbound_event")
@patch("products.conversations.backend.api.slack_events.validate_support_request")
- def test_event_callback_routes_to_handler(self, mock_validate: MagicMock, mock_process: MagicMock):
+ def test_event_callback_routes_to_handler(self, mock_validate: MagicMock, mock_wake: MagicMock):
mock_validate.return_value = None
- response = self._post(
+ response = self._post_committed(
{
"type": "event_callback",
"event_id": "Ev_456",
@@ -117,15 +140,55 @@ class TestSupportSlackEventsAPI(BaseTest):
)
assert response.status_code == 202
- mock_process.delay.assert_called_once()
+ mock_wake.assert_called_once()
+
+ @patch("products.conversations.backend.api.slack_events.wake_inbound_event")
+ @patch("products.conversations.backend.api.slack_events.validate_support_request")
+ def test_broker_failure_after_commit_still_acknowledges(self, mock_validate: MagicMock, mock_wake: MagicMock):
+ mock_validate.return_value = None
+ mock_wake.side_effect = ConnectionError("broker down")
+ payload = {
+ "type": "event_callback",
+ "event_id": "Ev_broker",
+ "team_id": "T123",
+ "event": {"type": "message", "channel": "C1"},
+ }
+
+ response = self._post_committed(payload)
+
+ assert response.status_code == 202
+ row = self._event_row()
+ assert row.status == ConversationInboundEvent.Status.PENDING
+ assert row.source_id == "Ev_broker"
+
+ @patch("products.conversations.backend.api.slack_events.wake_inbound_event")
+ @patch("products.conversations.backend.api.slack_events.validate_support_request")
+ def test_oversized_payload_is_tombstoned_and_acknowledged(self, mock_validate: MagicMock, mock_wake: MagicMock):
+ mock_validate.return_value = None
+ payload = {
+ "type": "event_callback",
+ "event_id": "Ev_poison",
+ "team_id": "T123",
+ "event": {"type": "message", "text": "x" * (INBOUND_PAYLOAD_MAX_BYTES + 1)},
+ }
+
+ response = self._post_committed(payload)
+
+ assert response.status_code == 202
+ mock_wake.assert_not_called()
+ row = self._event_row()
+ assert row.payload is None
+ assert row.status == ConversationInboundEvent.Status.FAILED
+ assert row.last_error_code == "payload_too_large"
@patch("products.conversations.backend.api.slack_events.proxy_to_secondary_region")
- @patch("products.conversations.backend.api.slack_events.process_supporthog_event")
+ @patch("products.conversations.backend.api.slack_events.wake_inbound_event")
@patch("products.conversations.backend.api.slack_events.validate_support_request")
def test_proxies_to_secondary_when_team_not_found_on_primary(
- self, mock_validate: MagicMock, mock_process: MagicMock, mock_proxy: MagicMock
+ self, mock_validate: MagicMock, mock_wake: MagicMock, mock_proxy: MagicMock
):
mock_validate.return_value = None
+ mock_proxy.return_value = True
with patch("products.conversations.backend.api.slack_events.is_primary_region", return_value=True):
response = self._post(
@@ -138,14 +201,37 @@ class TestSupportSlackEventsAPI(BaseTest):
)
assert response.status_code == 202
- mock_process.delay.assert_not_called()
+ mock_wake.assert_not_called()
mock_proxy.assert_called_once()
+ assert not ConversationInboundEvent.objects.unscoped().filter(source_id="Ev_proxy").exists()
@patch("products.conversations.backend.api.slack_events.proxy_to_secondary_region")
- @patch("products.conversations.backend.api.slack_events.process_supporthog_event")
+ @patch("products.conversations.backend.api.slack_events.wake_inbound_event")
+ @patch("products.conversations.backend.api.slack_events.validate_support_request")
+ def test_returns_502_when_event_proxy_to_secondary_fails(
+ self, mock_validate: MagicMock, mock_wake: MagicMock, mock_proxy: MagicMock
+ ):
+ mock_validate.return_value = None
+ mock_proxy.return_value = False
+
+ with patch("products.conversations.backend.api.slack_events.is_primary_region", return_value=True):
+ response = self._post(
+ {
+ "type": "event_callback",
+ "event_id": "Ev_proxy_fail",
+ "team_id": "T_UNKNOWN",
+ "event": {"type": "message", "channel": "C1"},
+ },
+ )
+
+ assert response.status_code == 502
+ mock_wake.assert_not_called()
+
+ @patch("products.conversations.backend.api.slack_events.proxy_to_secondary_region")
+ @patch("products.conversations.backend.api.slack_events.wake_inbound_event")
@patch("products.conversations.backend.api.slack_events.validate_support_request")
def test_drops_event_when_team_not_found_on_secondary(
- self, mock_validate: MagicMock, mock_process: MagicMock, mock_proxy: MagicMock
+ self, mock_validate: MagicMock, mock_wake: MagicMock, mock_proxy: MagicMock
):
mock_validate.return_value = None
@@ -160,7 +246,7 @@ class TestSupportSlackEventsAPI(BaseTest):
)
assert response.status_code == 202
- mock_process.delay.assert_not_called()
+ mock_wake.assert_not_called()
mock_proxy.assert_not_called()
@@ -191,6 +277,10 @@ class TestSupportSlackInteractivityAPI(BaseTest):
def _post(self, payload: Any, **kwargs):
return self._post_raw(json.dumps(payload), **kwargs)
+ def _post_committed(self, payload: Any, **kwargs: Any) -> HttpResponse:
+ with self.captureOnCommitCallbacks(execute=True):
+ return self._post(payload, **kwargs)
+
@patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
def test_invalid_signature_returns_403(self, mock_validate: MagicMock):
mock_validate.side_effect = SlackIntegrationError("Invalid")
@@ -215,32 +305,64 @@ class TestSupportSlackInteractivityAPI(BaseTest):
assert response.status_code == 400
- @patch("products.conversations.backend.api.slack_interactivity.process_supporthog_interactivity")
+ @patch("products.conversations.backend.api.slack_interactivity.wake_inbound_event")
@patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
- def test_missing_team_id_returns_200_without_processing(self, mock_validate: MagicMock, mock_process: MagicMock):
+ def test_missing_team_id_returns_200_without_processing(self, mock_validate: MagicMock, mock_wake: MagicMock):
mock_validate.return_value = None
response = self._post({"type": "block_actions"})
assert response.status_code == 200
- mock_process.delay.assert_not_called()
+ mock_wake.assert_not_called()
- @patch("products.conversations.backend.api.slack_interactivity.process_supporthog_interactivity")
+ @patch("products.conversations.backend.api.slack_interactivity.wake_inbound_event")
@patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
- def test_block_actions_enqueues_processing(self, mock_validate: MagicMock, mock_process: MagicMock):
+ def test_block_actions_enqueues_processing(self, mock_validate: MagicMock, mock_wake: MagicMock):
mock_validate.return_value = None
- payload = {"type": "block_actions", "team": {"id": "T123"}, "actions": []}
+ payload = {
+ "type": "block_actions",
+ "team": {"id": "T123"},
+ "trigger_id": "trig.1",
+ "actions": [{"action_id": "open"}],
+ "container": {"type": "message", "message_ts": "1.0", "channel_id": "C1"},
+ }
+
+ first = self._post_committed(payload)
+ second = self._post_committed(payload)
+
+ assert first.status_code == 200
+ assert second.status_code == 200
+ assert ConversationInboundEvent.objects.for_team(self.team.id).count() == 1
+ row = ConversationInboundEvent.objects.for_team(self.team.id).get()
+ assert row.source == ConversationInboundEventSource.SLACK_INTERACTIVITY
+ assert row.source_id.startswith("trig.1:")
+ assert mock_wake.call_count == 2
+
+ @patch("products.conversations.backend.api.slack_interactivity.wake_inbound_event")
+ @patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
+ def test_block_actions_without_trigger_id_hashes_payload_field(
+ self, mock_validate: MagicMock, mock_wake: MagicMock
+ ):
+ mock_validate.return_value = None
+ payload = {
+ "type": "block_actions",
+ "team": {"id": "T123"},
+ "actions": [{"action_id": "open"}],
+ }
+ raw_payload = json.dumps(payload)
- response = self._post(payload)
+ response = self._post_committed(payload)
assert response.status_code == 200
- mock_process.delay.assert_called_once_with(payload=payload, slack_team_id="T123")
+ row = ConversationInboundEvent.objects.for_team(self.team.id).get()
+ assert row.source_id == hashlib.sha256(raw_payload.encode("utf-8")).hexdigest()
+ mock_wake.assert_called_once()
@patch("products.conversations.backend.api.slack_interactivity.proxy_to_secondary_region")
- @patch("products.conversations.backend.api.slack_interactivity.process_supporthog_interactivity")
+ @patch("products.conversations.backend.api.slack_interactivity.wake_inbound_event")
@patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
def test_proxies_to_secondary_when_team_not_found_on_primary(
- self, mock_validate: MagicMock, mock_process: MagicMock, mock_proxy: MagicMock
+ self, mock_validate: MagicMock, mock_wake: MagicMock, mock_proxy: MagicMock
):
mock_validate.return_value = None
mock_proxy.return_value = True
@@ -249,16 +371,16 @@ class TestSupportSlackInteractivityAPI(BaseTest):
response = self._post({"type": "block_actions", "team": {"id": "T_UNKNOWN"}})
assert response.status_code == 200
- mock_process.delay.assert_not_called()
+ mock_wake.assert_not_called()
mock_proxy.assert_called_once()
@patch("products.conversations.backend.api.slack_interactivity.proxy_to_secondary_region")
- @patch("products.conversations.backend.api.slack_interactivity.process_supporthog_interactivity")
+ @patch("products.conversations.backend.api.slack_interactivity.wake_inbound_event")
@patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
def test_returns_502_when_proxy_to_secondary_fails(
- self, mock_validate: MagicMock, mock_process: MagicMock, mock_proxy: MagicMock
+ self, mock_validate: MagicMock, mock_wake: MagicMock, mock_proxy: MagicMock
):
- # Acking a failed proxy with 200 silently drops the click — Slack shows the
+ # Acking a failed proxy with 200 silently drops the click. Slack shows the
# clicker nothing and never resends. A non-2xx surfaces the failure in Slack.
mock_validate.return_value = None
mock_proxy.return_value = False
@@ -267,13 +389,13 @@ class TestSupportSlackInteractivityAPI(BaseTest):
response = self._post({"type": "block_actions", "team": {"id": "T_UNKNOWN"}})
assert response.status_code == 502
- mock_process.delay.assert_not_called()
+ mock_wake.assert_not_called()
@patch("products.conversations.backend.api.slack_interactivity.proxy_to_secondary_region")
- @patch("products.conversations.backend.api.slack_interactivity.process_supporthog_interactivity")
+ @patch("products.conversations.backend.api.slack_interactivity.wake_inbound_event")
@patch("products.conversations.backend.api.slack_interactivity.validate_support_request")
def test_drops_click_when_team_not_found_on_secondary(
- self, mock_validate: MagicMock, mock_process: MagicMock, mock_proxy: MagicMock
+ self, mock_validate: MagicMock, mock_wake: MagicMock, mock_proxy: MagicMock
):
mock_validate.return_value = None
@@ -281,7 +403,7 @@ class TestSupportSlackInteractivityAPI(BaseTest):
response = self._post({"type": "block_actions", "team": {"id": "T_UNKNOWN"}})
assert response.status_code == 200
- mock_process.delay.assert_not_called()
+ mock_wake.assert_not_called()
mock_proxy.assert_not_called()
diff --git a/products/conversations/backend/api/tests/test_slack_message_routing.py b/products/conversations/backend/api/tests/test_slack_message_routing.py
index 9b0f14296b6f..92b7954f9c08 100644
--- a/products/conversations/backend/api/tests/test_slack_message_routing.py
+++ b/products/conversations/backend/api/tests/test_slack_message_routing.py
@@ -9,6 +9,7 @@ from django.test import override_settings
from celery.exceptions import MaxRetriesExceededError, Retry
from parameterized import parameterized
+from slack_sdk.errors import SlackApiError
from posthog.models.team.extensions import get_or_create_team_extension
@@ -18,6 +19,7 @@ from products.conversations.backend.models.constants import Channel, ChannelDeta
from products.conversations.backend.slack import (
TICKET_CONFIRM_ACTION_DISMISS,
TICKET_CONFIRM_ACTION_OPEN,
+ SlackConfirmationNeedsRetry,
create_ticket_from_confirmation,
handle_member_joined_channel,
handle_member_left_channel,
@@ -911,14 +913,26 @@ class TestSlackNudge(BaseTest):
assert kwargs["channel_detail"] == ChannelDetail.SLACK_CHANNEL_MESSAGE
mock_backfill.assert_called_once()
+ @parameterized.expand(
+ [
+ (
+ "wrong_ts",
+ {
+ "messages": [
+ {"user": "U_SOMEONE_ELSE", "text": "Unrelated earlier message", "ts": "1699999999.000001"}
+ ]
+ },
+ ),
+ ("empty_history", {"messages": []}),
+ ("empty_content", {"messages": [{"user": "U_OP", "text": " ", "ts": "1700000000.000100"}]}),
+ ]
+ )
@patch(f"{MODULE}.get_slack_client")
@patch(f"{MODULE}.create_or_update_slack_ticket")
- def test_create_ticket_from_confirmation_rejects_wrong_message(self, mock_create_or_update, mock_get_client):
- # `latest` is an upper bound: if the source message was deleted, Slack returns the
- # previous channel message instead. That must not seed a ticket.
- mock_get_client.return_value.conversations_history.return_value = {
- "messages": [{"user": "U_SOMEONE_ELSE", "text": "Unrelated earlier message", "ts": "1699999999.000001"}]
- }
+ def test_create_ticket_from_confirmation_returns_none_for_unusable_source(
+ self, _name, history, mock_create_or_update, mock_get_client
+ ):
+ mock_get_client.return_value.conversations_history.return_value = history
result = create_ticket_from_confirmation(
team=self.team,
@@ -930,6 +944,37 @@ class TestSlackNudge(BaseTest):
assert result is None
mock_create_or_update.assert_not_called()
+ @patch(f"{MODULE}.get_slack_client")
+ @patch(f"{MODULE}.create_or_update_slack_ticket")
+ def test_create_ticket_from_confirmation_fetch_failure_is_retryable(self, mock_create_or_update, mock_get_client):
+ mock_get_client.return_value.conversations_history.side_effect = RuntimeError("slack down")
+
+ with self.assertRaises(SlackConfirmationNeedsRetry):
+ create_ticket_from_confirmation(
+ team=self.team,
+ slack_team_id="T123",
+ slack_channel_id="C_OTHER",
+ message_ts="1700000000.000100",
+ )
+
+ mock_create_or_update.assert_not_called()
+
+ @patch(f"{MODULE}.get_slack_client")
+ @patch(f"{MODULE}.create_or_update_slack_ticket")
+ def test_create_ticket_from_confirmation_create_none_is_retryable(self, mock_create_or_update, mock_get_client):
+ mock_get_client.return_value.conversations_history.return_value = {
+ "messages": [{"user": "U_OP", "text": "Original message", "ts": "1700000000.000100"}]
+ }
+ mock_create_or_update.return_value = None
+
+ with self.assertRaises(SlackConfirmationNeedsRetry):
+ create_ticket_from_confirmation(
+ team=self.team,
+ slack_team_id="T123",
+ slack_channel_id="C_OTHER",
+ message_ts="1700000000.000100",
+ )
+
@patch(f"{MODULE}.get_slack_client")
@patch(f"{MODULE}.create_or_update_slack_ticket")
def test_create_ticket_from_confirmation_is_idempotent(self, mock_create_or_update, mock_get_client):
@@ -1197,12 +1242,8 @@ class TestSupporthogInteractivity(BaseTest):
@patch(f"{TASKS_MODULE}.get_slack_client")
@patch(f"{TASKS_MODULE}.create_ticket_from_confirmation")
- def test_open_retries_when_create_returns_none(self, mock_create, mock_get_client):
- # A duplicate delivery that loses the per-thread create lock gets None back while
- # the sibling's ticket is mid-create. The task must retry — resolving to the
- # committed ticket on the re-run — not report a false "couldn't open a ticket"
- # to the user and a false ticket_created=false to the funnel.
- mock_create.return_value = None
+ def test_open_retries_when_create_needs_retry(self, mock_create, mock_get_client):
+ mock_create.side_effect = SlackConfirmationNeedsRetry()
with self.assertRaises(Retry):
process_supporthog_interactivity(
@@ -1259,22 +1300,46 @@ class TestSupporthogInteractivity(BaseTest):
client.chat_update.assert_called_once()
assert "ticket #7" in client.chat_update.call_args.kwargs["text"].lower()
- @parameterized.expand(
- [
- ("create_raises", RuntimeError("boom")),
- ("create_returns_none", None),
- ]
- )
@patch(f"{TASKS_MODULE}.get_slack_client")
@patch(f"{TASKS_MODULE}.create_ticket_from_confirmation")
- def test_open_shows_error_when_retries_exhausted(self, _name, failure, mock_create, mock_get_client):
- # A persistent failure (create raising, or a None that never resolves into a
- # ticket) retries and eventually exhausts — the prompt must still be replaced
- # with the error state, not left with live buttons forever.
- if isinstance(failure, Exception):
- mock_create.side_effect = failure
- else:
- mock_create.return_value = failure
+ def test_open_does_not_retry_permanent_prompt_update_failure(self, mock_create, mock_get_client):
+ mock_create.return_value = Mock(ticket_number=42, id="ticket-1")
+ mock_get_client.return_value.chat_update.side_effect = SlackApiError(
+ "message_not_found", response={"error": "message_not_found"}
+ )
+
+ process_supporthog_interactivity(
+ self._payload(TICKET_CONFIRM_ACTION_OPEN, {"channel": "C_CONFIG", "message_ts": "1700000000.000100"}),
+ "T123",
+ )
+
+ self.mock_capture_event.assert_called_once()
+ _team, event_name, event_props = self.mock_capture_event.call_args.args
+ assert event_name == "support nudge open ticket clicked"
+ assert event_props["ticket_created"] is True
+
+ @patch(f"{TASKS_MODULE}.get_slack_client")
+ @patch(f"{TASKS_MODULE}.create_ticket_from_confirmation")
+ def test_open_shows_error_when_create_returns_none(self, mock_create, mock_get_client):
+ mock_create.return_value = None
+
+ process_supporthog_interactivity(
+ self._payload(TICKET_CONFIRM_ACTION_OPEN, {"channel": "C_CONFIG", "message_ts": "1700000000.000100"}),
+ "T123",
+ )
+
+ client = mock_get_client.return_value
+ assert client.chat_update.call_count == 2
+ assert "couldn't" in client.chat_update.call_args.kwargs["text"].lower()
+ self.mock_capture_event.assert_called_once()
+ _team, event_name, event_props = self.mock_capture_event.call_args.args
+ assert event_name == "support nudge open ticket clicked"
+ assert event_props["ticket_created"] is False
+
+ @patch(f"{TASKS_MODULE}.get_slack_client")
+ @patch(f"{TASKS_MODULE}.create_ticket_from_confirmation")
+ def test_open_shows_error_when_retries_exhausted(self, mock_create, mock_get_client):
+ mock_create.side_effect = RuntimeError("boom")
with patch.object(process_supporthog_interactivity, "retry", side_effect=MaxRetriesExceededError()):
process_supporthog_interactivity(
diff --git a/products/conversations/backend/metrics.py b/products/conversations/backend/metrics.py
index 6f9819db702d..4bde635ebb75 100644
--- a/products/conversations/backend/metrics.py
+++ b/products/conversations/backend/metrics.py
@@ -15,3 +15,14 @@ TICKET_SEARCH_DURATION_SECONDS = Histogram(
labelnames=["search_path"], # ticket_number | text
buckets=(0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, float("inf")),
)
+
+INBOUND_ATTEMPTS_TOTAL = Counter(
+ "posthog_conversations_inbound_attempts_total",
+ "Inbound receipt processing attempts by source and result",
+ labelnames=["source", "result"], # processed | retry | failed | claimed
+)
+INBOUND_LEASES_TOTAL = Counter(
+ "posthog_conversations_inbound_leases_total",
+ "Inbound receipt lease outcomes",
+ labelnames=["result"], # claimed | expired_reclaim | busy
+)
diff --git a/products/conversations/backend/services/inbound_events.py b/products/conversations/backend/services/inbound_events.py
new file mode 100644
index 000000000000..32bfd9702f7b
--- /dev/null
+++ b/products/conversations/backend/services/inbound_events.py
@@ -0,0 +1,481 @@
+from __future__ import annotations
+
+import random
+import hashlib
+from collections.abc import Callable
+from datetime import datetime, timedelta
+from typing import Any, cast
+from uuid import UUID
+
+from django.db import IntegrityError, transaction
+from django.db.models import Q, QuerySet
+from django.http import HttpRequest
+from django.utils import timezone
+
+import structlog
+from prometheus_client import Gauge
+
+from posthog.dataclasses import frozen
+from posthog.metrics import pushed_metrics_registry
+from posthog.models.team import Team
+
+from products.conversations.backend.metrics import INBOUND_ATTEMPTS_TOTAL, INBOUND_LEASES_TOTAL
+from products.conversations.backend.models import ConversationInboundEvent, ConversationInboundEventSource
+from products.conversations.backend.models.inbound_event import (
+ INBOUND_ERROR_MAX_LENGTH,
+ INBOUND_PAYLOAD_TTL,
+ INBOUND_TOMBSTONE_TTL,
+ InboundPayloadTooLargeError,
+ reject_oversized_inbound_payload,
+)
+
+logger = structlog.get_logger(__name__)
+
+# Covers a crashed worker. Live Slack create+backfill has no Celery time_limit, so this
+# is reclaim latency, not a handler wall-clock.
+INBOUND_LEASE_SECONDS = 20 * 60
+INBOUND_MAX_ATTEMPTS = 20
+INBOUND_BACKOFF_BASE_SECONDS = 15
+INBOUND_BACKOFF_MAX_SECONDS = 15 * 60
+INBOUND_MAX_AGE = INBOUND_PAYLOAD_TTL
+INBOUND_SWEEP_BATCH_SIZE = 100
+# Caps one Beat tick so retention catch-up cannot run unbounded.
+INBOUND_SWEEP_MAX_ROUNDS = 20
+
+InboundWake = Callable[[ConversationInboundEvent], object]
+
+
+class TransientInboundError(Exception):
+ """Work that should be retried from the Postgres receipt rather than Celery retry."""
+
+
+@frozen
+class InboundClaim:
+ event: ConversationInboundEvent
+ allow_retry: bool
+ expired_reclaim: bool
+
+
+@frozen
+class InboundQueueMetrics:
+ pending_count: int
+ processing_count: int
+ oldest_ready_age_seconds: float
+
+
+def slack_retry_metadata(request: HttpRequest) -> tuple[int | None, str]:
+ raw_num = request.headers.get("X-Slack-Retry-Num")
+ reason = (request.headers.get("X-Slack-Retry-Reason") or "")[:64]
+ if not raw_num:
+ return None, reason
+ try:
+ retry_num = int(raw_num)
+ except ValueError:
+ return None, reason
+ if retry_num < 0:
+ return None, reason
+ return retry_num, reason
+
+
+def slack_events_source_id(*, event_id: str | None, signed_body: bytes) -> str:
+ if event_id:
+ return event_id[:512]
+ return hashlib.sha256(signed_body).hexdigest()
+
+
+def slack_interactivity_source_id(*, payload: dict[str, Any], signed_body: bytes) -> str:
+ trigger_id = str(payload.get("trigger_id") or "")
+ if not trigger_id:
+ return hashlib.sha256(signed_body).hexdigest()
+ actions = payload.get("actions") or []
+ raw_action = actions[0] if actions else None
+ action: dict[str, Any] = raw_action if isinstance(raw_action, dict) else {}
+ action_id = str(action.get("action_id") or "")
+ raw_container = payload.get("container")
+ container: dict[str, Any] = raw_container if isinstance(raw_container, dict) else {}
+ container_key = ":".join(str(container.get(key) or "") for key in ("type", "message_ts", "channel_id", "thread_ts"))
+ composed = f"{trigger_id}:{action_id}:{container_key}"
+ if len(composed) <= 512:
+ return composed
+ return hashlib.sha256(composed.encode()).hexdigest()
+
+
+def retry_delay_seconds(attempts: int) -> int:
+ exponent = max(attempts - 1, 0)
+ backoff = min(INBOUND_BACKOFF_BASE_SECONDS * (2 ** min(exponent, 8)), INBOUND_BACKOFF_MAX_SECONDS)
+ jitter = random.uniform(0, backoff * 0.5)
+ return max(int(backoff + jitter), 1)
+
+
+def _safe_wake(wake: InboundWake, row: ConversationInboundEvent) -> None:
+ try:
+ wake(row)
+ except Exception:
+ logger.exception("inbound_event_dispatch_failed", inbound_event_id=str(row.id), source=row.source)
+
+
+def _should_wake(row: ConversationInboundEvent, *, now: datetime) -> bool:
+ if row.status == ConversationInboundEvent.Status.PENDING:
+ return row.due_at <= now
+ return (
+ row.status == ConversationInboundEvent.Status.PROCESSING
+ and row.lease_expires_at is not None
+ and row.lease_expires_at <= now
+ )
+
+
+def persist_inbound_event(
+ *,
+ team: Team,
+ source: str,
+ source_id: str,
+ provider_account_id: str,
+ payload: dict[str, Any] | None,
+ provider_retry_num: int | None,
+ provider_retry_reason: str,
+) -> ConversationInboundEvent:
+ status = ConversationInboundEvent.Status.PENDING
+ error_code = ""
+ error = ""
+ terminal_at = None
+ stored_payload: dict[str, Any] | None = payload
+ try:
+ reject_oversized_inbound_payload(payload)
+ except InboundPayloadTooLargeError as exc:
+ stored_payload = None
+ status = ConversationInboundEvent.Status.FAILED
+ error_code = "payload_too_large"
+ error = str(exc)[:INBOUND_ERROR_MAX_LENGTH]
+ terminal_at = timezone.now()
+
+ defaults = {
+ "provider_account_id": provider_account_id,
+ "provider_retry_num": provider_retry_num,
+ "provider_retry_reason": provider_retry_reason,
+ "status": status,
+ "payload": stored_payload,
+ "last_error_code": error_code,
+ "last_error": error,
+ "terminal_at": terminal_at,
+ "due_at": timezone.now(),
+ }
+ try:
+ with transaction.atomic():
+ return ConversationInboundEvent.objects.for_team(team.id).create(
+ team=team,
+ source=source,
+ source_id=source_id,
+ **defaults,
+ )
+ except IntegrityError as exc:
+ try:
+ with transaction.atomic():
+ # Concurrent Slack retries can both hit IntegrityError. Lock the existing
+ # row so retry metadata updates cannot race.
+ row = (
+ ConversationInboundEvent.objects.for_team(team.id)
+ .select_for_update()
+ .get(source=source, source_id=source_id)
+ )
+ ConversationInboundEvent.objects.for_team(team.id).filter(id=row.id).update(
+ provider_retry_num=provider_retry_num,
+ provider_retry_reason=provider_retry_reason,
+ updated_at=timezone.now(),
+ )
+ row.refresh_from_db()
+ return row
+ except ConversationInboundEvent.DoesNotExist:
+ # Unique conflict is the only IntegrityError that leaves a row to replay.
+ raise exc from None
+
+
+def accept_inbound_event(
+ *,
+ team: Team,
+ source: str,
+ source_id: str,
+ provider_account_id: str,
+ payload: dict[str, Any] | None,
+ provider_retry_num: int | None,
+ provider_retry_reason: str,
+ wake: InboundWake,
+) -> ConversationInboundEvent:
+ with transaction.atomic():
+ row = persist_inbound_event(
+ team=team,
+ source=source,
+ source_id=source_id,
+ provider_account_id=provider_account_id,
+ payload=payload,
+ provider_retry_num=provider_retry_num,
+ provider_retry_reason=provider_retry_reason,
+ )
+ if _should_wake(row, now=timezone.now()):
+ transaction.on_commit(lambda: _safe_wake(wake, row))
+ return row
+
+
+def _fail_row_without_claim(
+ row: ConversationInboundEvent,
+ *,
+ now: datetime,
+ error_code: str,
+ error: str,
+) -> None:
+ row.status = ConversationInboundEvent.Status.FAILED
+ row.terminal_at = now
+ row.lease_expires_at = None
+ row.last_error_code = error_code
+ row.last_error = error[:INBOUND_ERROR_MAX_LENGTH]
+ row.save(
+ update_fields=[
+ "status",
+ "terminal_at",
+ "lease_expires_at",
+ "last_error_code",
+ "last_error",
+ "updated_at",
+ ]
+ )
+ transaction.on_commit(lambda: INBOUND_ATTEMPTS_TOTAL.labels(source=row.source, result="failed").inc())
+
+
+def claim_inbound_event(inbound_event_id: str) -> InboundClaim | None:
+ now = timezone.now()
+ lease_until = now + timedelta(seconds=INBOUND_LEASE_SECONDS)
+ with transaction.atomic():
+ row = (
+ # nosemgrep: idor-lookup-without-team (cross-team worker; ID comes from the committed receipt dispatch)
+ ConversationInboundEvent.objects.unscoped()
+ .select_for_update(skip_locked=True)
+ .filter(id=inbound_event_id)
+ .filter(
+ Q(status=ConversationInboundEvent.Status.PENDING, due_at__lte=now)
+ | Q(status=ConversationInboundEvent.Status.PROCESSING, lease_expires_at__lte=now)
+ )
+ .first()
+ )
+ if row is None:
+ INBOUND_LEASES_TOTAL.labels(result="busy").inc()
+ return None
+ if row.created_at < now - INBOUND_MAX_AGE:
+ _fail_row_without_claim(
+ row,
+ now=now,
+ error_code="max_age",
+ error="Exceeded inbound processing age",
+ )
+ return None
+ if row.attempts >= INBOUND_MAX_ATTEMPTS:
+ _fail_row_without_claim(
+ row,
+ now=now,
+ error_code="max_attempts",
+ error=f"Exceeded {INBOUND_MAX_ATTEMPTS} processing attempts",
+ )
+ return None
+ expired_reclaim = row.status == ConversationInboundEvent.Status.PROCESSING
+ row.status = ConversationInboundEvent.Status.PROCESSING
+ row.lease_expires_at = lease_until
+ row.fencing_token += 1
+ row.attempts += 1
+ row.save(update_fields=["status", "lease_expires_at", "fencing_token", "attempts", "updated_at"])
+ INBOUND_LEASES_TOTAL.labels(result="expired_reclaim" if expired_reclaim else "claimed").inc()
+ INBOUND_ATTEMPTS_TOTAL.labels(source=row.source, result="claimed").inc()
+ return InboundClaim(
+ event=row,
+ allow_retry=row.attempts < INBOUND_MAX_ATTEMPTS,
+ expired_reclaim=expired_reclaim,
+ )
+
+
+def _fenced(claim: InboundClaim) -> QuerySet[ConversationInboundEvent]:
+ # Retry leaves the same fencing token on a PENDING row. Status must still be
+ # PROCESSING so a later complete or fail cannot settle work that was released.
+ return ConversationInboundEvent.objects.unscoped().filter( # nosemgrep: idor-lookup-without-team (ID comes from the claimed row)
+ id=claim.event.id,
+ fencing_token=claim.event.fencing_token,
+ status=ConversationInboundEvent.Status.PROCESSING,
+ )
+
+
+def complete_inbound_event(claim: InboundClaim, *, error_code: str = "", error: str = "") -> bool:
+ now = timezone.now()
+ updated = _fenced(claim).update(
+ status=ConversationInboundEvent.Status.PROCESSED,
+ terminal_at=now,
+ lease_expires_at=None,
+ last_error_code=error_code,
+ last_error=error[:INBOUND_ERROR_MAX_LENGTH],
+ updated_at=now,
+ )
+ if updated:
+ INBOUND_ATTEMPTS_TOTAL.labels(source=claim.event.source, result="processed").inc()
+ return updated == 1
+
+
+def fail_inbound_event(claim: InboundClaim, *, error_code: str, error: str) -> bool:
+ now = timezone.now()
+ updated = _fenced(claim).update(
+ status=ConversationInboundEvent.Status.FAILED,
+ terminal_at=now,
+ lease_expires_at=None,
+ last_error_code=error_code,
+ last_error=error[:INBOUND_ERROR_MAX_LENGTH],
+ updated_at=now,
+ )
+ if updated:
+ INBOUND_ATTEMPTS_TOTAL.labels(source=claim.event.source, result="failed").inc()
+ return updated == 1
+
+
+def schedule_inbound_retry(claim: InboundClaim, *, error_code: str, error: str) -> int | None:
+ delay = retry_delay_seconds(claim.event.attempts)
+ now = timezone.now()
+ updated = _fenced(claim).update(
+ status=ConversationInboundEvent.Status.PENDING,
+ due_at=now + timedelta(seconds=delay),
+ lease_expires_at=None,
+ last_error_code=error_code,
+ last_error=error[:INBOUND_ERROR_MAX_LENGTH],
+ updated_at=now,
+ )
+ if not updated:
+ return None
+ INBOUND_ATTEMPTS_TOTAL.labels(source=claim.event.source, result="retry").inc()
+ return delay
+
+
+def _pending_inbound_events(*, now: datetime) -> QuerySet[ConversationInboundEvent]:
+ return ConversationInboundEvent.objects.unscoped().filter(
+ status=ConversationInboundEvent.Status.PENDING,
+ due_at__lte=now,
+ )
+
+
+def _expired_inbound_events(*, now: datetime) -> QuerySet[ConversationInboundEvent]:
+ return ConversationInboundEvent.objects.unscoped().filter(
+ status=ConversationInboundEvent.Status.PROCESSING,
+ lease_expires_at__lte=now,
+ )
+
+
+def due_inbound_event_ids(*, limit: int, now: datetime) -> list[tuple[UUID, str]]:
+ pending = list(_pending_inbound_events(now=now).order_by("due_at").values_list("id", "source", "due_at")[:limit])
+ expired = list(
+ _expired_inbound_events(now=now)
+ .order_by("lease_expires_at")
+ .values_list("id", "source", "lease_expires_at")[:limit]
+ )
+ ready = sorted([*pending, *expired], key=lambda row: cast(datetime, row[2]))
+ return [(event_id, source) for event_id, source, _ in ready[:limit]]
+
+
+def cleanup_inbound_payloads(now: datetime, *, limit: int = INBOUND_SWEEP_BATCH_SIZE) -> int:
+ cutoff = now - INBOUND_PAYLOAD_TTL
+ event_ids = list(
+ ConversationInboundEvent.objects.unscoped()
+ .filter(
+ status__in=ConversationInboundEvent.TERMINAL_STATUSES,
+ payload__isnull=False,
+ terminal_at__lte=cutoff,
+ )
+ .order_by("terminal_at")
+ .values_list("id", flat=True)[:limit]
+ )
+ # nosemgrep: idor-lookup-without-team (IDs come from the cross-team retention query above)
+ return ConversationInboundEvent.objects.unscoped().filter(id__in=event_ids).update(payload=None, updated_at=now)
+
+
+def delete_inbound_tombstones(now: datetime, *, limit: int = INBOUND_SWEEP_BATCH_SIZE) -> int:
+ cutoff = now - INBOUND_TOMBSTONE_TTL
+ event_ids = list(
+ ConversationInboundEvent.objects.unscoped()
+ .filter(
+ status__in=ConversationInboundEvent.TERMINAL_STATUSES,
+ terminal_at__lte=cutoff,
+ )
+ .order_by("terminal_at")
+ .values_list("id", flat=True)[:limit]
+ )
+ # nosemgrep: idor-lookup-without-team (IDs come from the cross-team retention query above)
+ deleted, _ = ConversationInboundEvent.objects.unscoped().filter(id__in=event_ids).delete()
+ return deleted
+
+
+def drain_inbound_retention(cleanup: Callable[[datetime], int], now: datetime) -> int:
+ total = 0
+ for _ in range(INBOUND_SWEEP_MAX_ROUNDS):
+ cleaned = cleanup(now)
+ total += cleaned
+ if cleaned < INBOUND_SWEEP_BATCH_SIZE:
+ break
+ return total
+
+
+def _push_inbound_queue_gauges(*, backlog: list[tuple[str, str, int]], oldest_age: float, now: datetime) -> None:
+ """Push the inbound queue snapshot as region-scoped gauges.
+
+ These values describe the whole receipt table, not the pod that measured them.
+ A module-level gauge would make every worker that swept export its own snapshot.
+ ``multiprocess_mode`` writes PROMETHEUS_MULTIPROC_DIR even on a throwaway
+ registry, so the value would reappear on every worker /metrics scrape.
+ """
+ with pushed_metrics_registry("conversations_inbound_queue") as registry:
+ backlog_gauge = Gauge(
+ "posthog_conversations_inbound_backlog",
+ "Non-terminal inbound callback receipts by status and source",
+ labelnames=["status", "source"],
+ registry=registry,
+ )
+ for status, source, count in backlog:
+ backlog_gauge.labels(status=status, source=source).set(count)
+ Gauge(
+ "posthog_conversations_inbound_oldest_ready_age_seconds",
+ "Age in seconds of the oldest due or expired-lease inbound receipt",
+ registry=registry,
+ ).set(oldest_age)
+ # Pushgateway gauges never expire. Without this, a dead sweeper freezes an empty
+ # backlog forever and a backlog alert can never fire.
+ Gauge(
+ "posthog_conversations_inbound_last_sweep_timestamp_seconds",
+ "Unix timestamp of the last completed inbound queue sweep",
+ registry=registry,
+ ).set(now.timestamp())
+
+
+def record_inbound_queue_metrics(now: datetime) -> InboundQueueMetrics:
+ oldest_age = 0.0
+ counts = {
+ ConversationInboundEvent.Status.PENDING: 0,
+ ConversationInboundEvent.Status.PROCESSING: 0,
+ }
+ backlog: list[tuple[str, str, int]] = []
+ for source in ConversationInboundEventSource.values:
+ for status in (ConversationInboundEvent.Status.PENDING, ConversationInboundEvent.Status.PROCESSING):
+ count = ConversationInboundEvent.objects.unscoped().filter(source=source, status=status).count()
+ backlog.append((status, source, count))
+ counts[status] += count
+ oldest_pending = _pending_inbound_events(now=now).order_by("due_at").values_list("due_at", flat=True).first()
+ oldest_expired = (
+ _expired_inbound_events(now=now).order_by("lease_expires_at").values_list("lease_expires_at", flat=True).first()
+ )
+ oldest = min((ready_at for ready_at in (oldest_pending, oldest_expired) if ready_at is not None), default=None)
+ if oldest is not None:
+ oldest_age = max((now - oldest).total_seconds(), 0.0)
+ _push_inbound_queue_gauges(backlog=backlog, oldest_age=oldest_age, now=now)
+ return InboundQueueMetrics(
+ pending_count=counts[ConversationInboundEvent.Status.PENDING],
+ processing_count=counts[ConversationInboundEvent.Status.PROCESSING],
+ oldest_ready_age_seconds=oldest_age,
+ )
+
+
+def inbound_event_payload_event(row: ConversationInboundEvent) -> dict[str, Any] | None:
+ payload = row.payload
+ if not isinstance(payload, dict):
+ return None
+ inner = payload.get("event")
+ if isinstance(inner, dict):
+ return inner
+ return None
diff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.py
index f1566bab063a..021f142c1a87 100644
--- a/products/conversations/backend/slack.py
+++ b/products/conversations/backend/slack.py
@@ -1118,6 +1118,10 @@ def _create_ticket_and_backfill(
return ticket
+class SlackConfirmationNeedsRetry(Exception):
+ """Transient confirmation failure. The interactivity handler retries this."""
+
+
def create_ticket_from_confirmation(
*,
team: Team,
@@ -1130,9 +1134,8 @@ def create_ticket_from_confirmation(
Mirrors the emoji-reaction path: re-fetch the source message, create the ticket, then
backfill any replies posted while the prompt was pending. Idempotent — a duplicate
click returns the already-open ticket so the caller can confirm rather than error.
- Returns None on genuine failure (source message gone, fetch error, empty content), but
- also when a concurrent duplicate delivery holds the create lock mid-flight — callers
- should treat None as retryable, since a re-run resolves to the winner's committed ticket.
+ Returns None only for a missing or unusable source message.
+ Raises SlackConfirmationNeedsRetry for Slack fetch errors and create-lock contention.
"""
existing = Ticket.objects.filter(team=team, slack_channel_id=slack_channel_id, slack_thread_ts=message_ts).first()
if existing:
@@ -1150,9 +1153,9 @@ def create_ticket_from_confirmation(
limit=1,
)
messages: list[dict] = result.get("messages", [])
- except Exception:
+ except Exception as exc:
logger.warning("slack_support_confirmation_fetch_failed", channel=slack_channel_id, message_ts=message_ts)
- return None
+ raise SlackConfirmationNeedsRetry from exc
if not messages:
return None
@@ -1169,7 +1172,7 @@ def create_ticket_from_confirmation(
if not original_msg.get("user") or (not original_text.strip() and not original_msg.get("files")):
return None
- return _create_ticket_and_backfill(
+ ticket = _create_ticket_and_backfill(
client=client,
team=team,
slack_channel_id=slack_channel_id,
@@ -1180,6 +1183,9 @@ def create_ticket_from_confirmation(
# The interactivity handler updates the prompt in place into the confirmation.
post_confirmation=False,
)
+ if ticket is None:
+ raise SlackConfirmationNeedsRetry
+ return ticket
def handle_support_mention(event: dict, team: Team, slack_team_id: str) -> None:
diff --git a/products/conversations/backend/support_slack.py b/products/conversations/backend/support_slack.py
index bf565f204b79..017255bb28f2 100644
--- a/products/conversations/backend/support_slack.py
+++ b/products/conversations/backend/support_slack.py
@@ -58,12 +58,18 @@ def get_support_slack_workspace_id(team: "Team") -> str | None:
return config.slack_team_id or None
-def team_exists_for_slack_workspace(slack_team_id: str) -> bool:
- """Whether any team has SupportHog connected to this Slack workspace.
+def team_for_slack_workspace(slack_team_id: str) -> "Team | None":
+ """Return the team that owns this Slack workspace, if SupportHog is connected."""
+ config = (
+ TeamConversationsSlackConfig.objects.filter(slack_team_id=slack_team_id, slack_bot_token__isnull=False)
+ .select_related("team")
+ .first()
+ )
+ return config.team if config else None
- Used by the webhook endpoints for region routing — the Celery task re-resolves
- the full config, so only existence matters here.
- """
+
+def team_exists_for_slack_workspace(slack_team_id: str) -> bool:
+ """Whether any team has SupportHog connected to this Slack workspace."""
return TeamConversationsSlackConfig.objects.filter(
slack_team_id=slack_team_id, slack_bot_token__isnull=False
).exists()
diff --git a/products/conversations/backend/tasks/slack.py b/products/conversations/backend/tasks/slack.py
index ae52d2301725..8b1abc1d2ff5 100644
--- a/products/conversations/backend/tasks/slack.py
+++ b/products/conversations/backend/tasks/slack.py
@@ -1,16 +1,18 @@
"""Slack inbound events, interactivity, and outbound replies."""
import json
-from typing import Any, cast, get_args
+from typing import Any, Literal, cast, get_args
from urllib.parse import urlparse
from uuid import UUID
from django.core.cache import cache
+from django.utils import timezone
import requests
import structlog
from celery import shared_task
-from celery.exceptions import MaxRetriesExceededError, Retry
+from celery.exceptions import MaxRetriesExceededError
+from slack_sdk.errors import SlackApiError
from posthog.comment.formatting import extract_images_from_rich_content, rich_content_to_slack_payload
from posthog.helpers.slack_identity import resolve_slack_avatar_by_email
@@ -20,14 +22,35 @@ from posthog.scoping_audit import skip_team_scope_audit
from posthog.storage import object_storage
from products.conversations.backend.cache import NUDGE_DISMISS_TTL, suppress_nudge
-from products.conversations.backend.models import TeamConversationsSlackConfig
+from products.conversations.backend.models import (
+ ConversationInboundEvent,
+ ConversationInboundEventSource,
+ TeamConversationsSlackConfig,
+)
+from products.conversations.backend.models.inbound_event import INBOUND_ERROR_MAX_LENGTH
from products.conversations.backend.models.ticket import Ticket
from products.conversations.backend.services.attachments import CONVERSATIONS_MAX_IMAGE_BYTES
+from products.conversations.backend.services.inbound_events import (
+ INBOUND_SWEEP_BATCH_SIZE,
+ InboundClaim,
+ TransientInboundError,
+ claim_inbound_event,
+ cleanup_inbound_payloads,
+ complete_inbound_event,
+ delete_inbound_tombstones,
+ drain_inbound_retention,
+ due_inbound_event_ids,
+ fail_inbound_event,
+ inbound_event_payload_event,
+ record_inbound_queue_metrics,
+ schedule_inbound_retry,
+)
from products.conversations.backend.slack import (
TICKET_CONFIRM_ACTION_DISMISS,
TICKET_CONFIRM_ACTION_OPEN,
NudgeClassifierVerdict,
NudgeFunnelVerdict,
+ SlackConfirmationNeedsRetry,
capture_nudge_event,
create_ticket_from_confirmation,
get_bot_user_id,
@@ -47,6 +70,21 @@ from ..support_slack import SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES, supporthog_miss
logger = structlog.get_logger(__name__)
SUPPORTHOG_EVENT_IDEMPOTENCY_TTL_SECONDS = 6 * 60
SUPPORTHOG_EVENT_IDEMPOTENCY_KEY_PREFIX = "supporthog:slack:event:"
+PromptUpdateResult = Literal["updated", "missing", "transient", "permanent"]
+_PERMANENT_PROMPT_UPDATE_ERROR_CODES = frozenset(
+ {
+ "account_inactive",
+ "cannot_update_message",
+ "cant_update_message",
+ "channel_not_found",
+ "invalid_auth",
+ "is_archived",
+ "message_not_found",
+ "msg_too_long",
+ "not_in_channel",
+ "token_revoked",
+ }
+)
def _is_duplicate_supporthog_event(event_id: str) -> bool:
@@ -54,6 +92,109 @@ def _is_duplicate_supporthog_event(event_id: str) -> bool:
return not cache.add(key, True, timeout=SUPPORTHOG_EVENT_IDEMPOTENCY_TTL_SECONDS)
+def _slack_config_for_workspace(
+ slack_team_id: str, *, receipt_team_id: int | None = None
+) -> TeamConversationsSlackConfig | None:
+ config = (
+ TeamConversationsSlackConfig.objects.filter(
+ slack_team_id=slack_team_id,
+ slack_bot_token__isnull=False,
+ )
+ .select_related("team")
+ .first()
+ )
+ if config is None or receipt_team_id is None:
+ return config
+ config_root_team_id = config.team.parent_team_id or config.team_id
+ return config if config_root_team_id == receipt_team_id else None
+
+
+def _handle_supporthog_event(event: dict[str, Any], team: Team, slack_team_id: str) -> None:
+ event_type = event.get("type")
+ if event_type == "message":
+ handle_support_message(event, team, slack_team_id)
+ elif event_type == "app_mention":
+ handle_support_mention(event, team, slack_team_id)
+ elif event_type == "reaction_added":
+ handle_support_reaction(event, team, slack_team_id)
+ elif event_type == "member_joined_channel":
+ handle_member_joined_channel(event, team, slack_team_id)
+ elif event_type == "member_left_channel":
+ handle_member_left_channel(event, team, slack_team_id)
+
+
+def wake_inbound_event(row: ConversationInboundEvent, *, countdown: int | None = None) -> bool:
+ task = (
+ process_supporthog_event_receipt
+ if row.source == ConversationInboundEventSource.SLACK_EVENTS
+ else process_supporthog_interactivity_receipt
+ )
+ kwargs = {"inbound_event_id": str(row.id)}
+ try:
+ # retry=False: the receipt is already committed, so a hung broker must not
+ # stall the Slack ack. The minute sweeper re-drives pending rows.
+ apply_kwargs: dict[str, Any] = {"kwargs": kwargs, "retry": False}
+ if countdown is not None:
+ apply_kwargs["countdown"] = countdown
+ cast(Any, task).apply_async(**apply_kwargs)
+ except Exception:
+ logger.exception("inbound_event_redrive_failed", inbound_event_id=str(row.id), source=row.source)
+ return False
+ return True
+
+
+def _retry_inbound_claim(claim: InboundClaim, *, error_code: str, error: str) -> None:
+ if not claim.allow_retry:
+ fail_inbound_event(claim, error_code=error_code, error=error)
+ return
+ delay = schedule_inbound_retry(claim, error_code=error_code, error=error)
+ if delay is not None:
+ wake_inbound_event(claim.event, countdown=delay)
+
+
+def _process_event_from_receipt(inbound_event_id: str) -> None:
+ claim = claim_inbound_event(inbound_event_id)
+ if claim is None:
+ return
+ event = inbound_event_payload_event(claim.event)
+ if event is None:
+ fail_inbound_event(
+ claim, error_code="poison_payload", error="inbound event payload is missing or not an object"
+ )
+ return
+ config = _slack_config_for_workspace(
+ claim.event.provider_account_id,
+ receipt_team_id=claim.event.team_id,
+ )
+ if not config:
+ _retry_inbound_claim(claim, error_code="no_team", error="slack workspace is not connected")
+ return
+ team = config.team
+ if not (team.conversations_settings or {}).get("slack_enabled"):
+ complete_inbound_event(claim)
+ return
+ try:
+ _handle_supporthog_event(event, team, claim.event.provider_account_id)
+ complete_inbound_event(claim)
+ except Exception as exc:
+ logger.exception(
+ "supporthog_event_handler_failed",
+ event_type=event.get("type"),
+ inbound_event_id=inbound_event_id,
+ error=str(exc),
+ )
+ _retry_inbound_claim(claim, error_code="handler_failed", error=str(exc)[:INBOUND_ERROR_MAX_LENGTH])
+
+
+@shared_task(
+ name="products.conversations.backend.tasks.process_supporthog_event_receipt",
+ ignore_result=True,
+)
+@skip_team_scope_audit
+def process_supporthog_event_receipt(inbound_event_id: str) -> None:
+ _process_event_from_receipt(inbound_event_id)
+
+
@shared_task(
name="products.conversations.backend.tasks.process_supporthog_event",
ignore_result=True,
@@ -61,16 +202,18 @@ def _is_duplicate_supporthog_event(event_id: str) -> bool:
default_retry_delay=5,
)
@skip_team_scope_audit
-def process_supporthog_event(event: dict[str, Any], slack_team_id: str, event_id: str | None = None) -> None:
+def process_supporthog_event(
+ event: dict[str, Any] | None = None,
+ slack_team_id: str = "",
+ event_id: str | None = None,
+) -> None:
+ if not event:
+ return
if event_id and _is_duplicate_supporthog_event(event_id):
logger.info("supporthog_event_duplicate_skipped", event_id=event_id)
return
- config = (
- TeamConversationsSlackConfig.objects.filter(slack_team_id=slack_team_id, slack_bot_token__isnull=False)
- .select_related("team")
- .first()
- )
+ config = _slack_config_for_workspace(slack_team_id)
if not config:
logger.warning("supporthog_no_team", slack_team_id=slack_team_id)
return
@@ -85,22 +228,12 @@ def process_supporthog_event(event: dict[str, Any], slack_team_id: str, event_id
)
return
- event_type = event.get("type")
try:
- if event_type == "message":
- handle_support_message(event, team, slack_team_id)
- elif event_type == "app_mention":
- handle_support_mention(event, team, slack_team_id)
- elif event_type == "reaction_added":
- handle_support_reaction(event, team, slack_team_id)
- elif event_type == "member_joined_channel":
- handle_member_joined_channel(event, team, slack_team_id)
- elif event_type == "member_left_channel":
- handle_member_left_channel(event, team, slack_team_id)
+ _handle_supporthog_event(event, team, slack_team_id)
except Exception as e:
logger.exception(
"supporthog_event_handler_failed",
- event_type=event_type,
+ event_type=event.get("type"),
error=str(e),
)
raise cast(Any, process_supporthog_event).retry(exc=e)
@@ -119,15 +252,21 @@ def _delete_supporthog_prompt(team: Team, channel: str, message_ts: str) -> None
logger.warning("supporthog_interactivity_prompt_delete_failed", exc_info=True)
-def _update_supporthog_prompt(team: Team, channel: str, message_ts: str, text: str) -> bool:
+def _slack_api_error_code(exc: Exception) -> str | None:
+ if not isinstance(exc, SlackApiError) or exc.response is None:
+ return None
+ error = exc.response.get("error")
+ return error if isinstance(error, str) else None
+
+
+def _update_supporthog_prompt(team: Team, channel: str, message_ts: str, text: str) -> PromptUpdateResult:
"""Replace the "open a ticket?" prompt in place with a new status line (buttons removed).
- Never raises — a failure here must not block the ticket creation that already ran —
- but reports success so callers can retry updates that must not be lost (the final
- confirmation/error state, as opposed to the best-effort progress placeholder).
+ Never raises. Callers retry only a ``transient`` result. A missing or deleted prompt
+ cannot recover, so those must not sit in the inbound retry queue.
"""
if not channel or not message_ts:
- return False
+ return "missing"
try:
get_slack_client(team).chat_update(
channel=channel,
@@ -135,10 +274,13 @@ def _update_supporthog_prompt(team: Team, channel: str, message_ts: str, text: s
text=text,
blocks=[{"type": "section", "text": {"type": "mrkdwn", "text": text}}],
)
- return True
- except Exception:
+ return "updated"
+ except Exception as exc:
logger.warning("supporthog_interactivity_prompt_update_failed", exc_info=True)
- return False
+ error_code = _slack_api_error_code(exc)
+ if error_code in _PERMANENT_PROMPT_UPDATE_ERROR_CODES:
+ return "permanent"
+ return "transient"
def _post_dismiss_acknowledgment(team: Team, channel: str, user: str, thread_ts: str) -> None:
@@ -163,31 +305,32 @@ def _post_dismiss_acknowledgment(team: Team, channel: str, user: str, thread_ts:
logger.warning("supporthog_interactivity_dismiss_ack_failed", exc_info=True)
-@shared_task(
- name="products.conversations.backend.tasks.process_supporthog_interactivity",
- ignore_result=True,
- max_retries=3,
- default_retry_delay=5,
-)
-@skip_team_scope_audit
-def process_supporthog_interactivity(payload: dict[str, Any], slack_team_id: str) -> None:
+def _raise_if_retry_allowed(allow_retry: bool) -> None:
+ if allow_retry:
+ raise TransientInboundError
+
+
+def _handle_supporthog_interactivity(
+ payload: dict[str, Any],
+ slack_team_id: str,
+ *,
+ is_retry: bool,
+ allow_retry: bool,
+ receipt_team_id: int | None = None,
+) -> bool:
"""Handle a button click from the opt-in "open a ticket?" confirmation prompt."""
- config = (
- TeamConversationsSlackConfig.objects.filter(slack_team_id=slack_team_id, slack_bot_token__isnull=False)
- .select_related("team")
- .first()
- )
+ config = _slack_config_for_workspace(slack_team_id, receipt_team_id=receipt_team_id)
if not config:
logger.warning("supporthog_interactivity_no_team", slack_team_id=slack_team_id)
- return
+ return receipt_team_id is None
team = config.team
support_settings = team.conversations_settings or {}
if not support_settings.get("slack_enabled"):
- return
+ return True
if payload.get("type") != "block_actions":
- return
+ return True
# The prompt message to delete: where the button was clicked.
container = payload.get("container") or {}
@@ -222,7 +365,7 @@ def process_supporthog_interactivity(payload: dict[str, Any], slack_team_id: str
if clicker:
suppress_nudge(team.pk, prompt_channel, clicker, NUDGE_DISMISS_TTL)
capture_nudge_event(team, "support nudge dismissed", click_properties)
- return
+ return True
if action_id == TICKET_CONFIRM_ACTION_OPEN:
ticket = None
if source_channel and source_message_ts:
@@ -231,7 +374,6 @@ def process_supporthog_interactivity(payload: dict[str, Any], slack_team_id: str
# a progress line right away so the click visibly landed and repeat clicks
# stop. First attempt only, and only while no sibling delivery has already
# resolved the prompt (a stale placeholder must not overwrite a confirmation).
- is_retry = bool(getattr(cast(Any, process_supporthog_interactivity).request, "retries", 0))
ticket_already_open = Ticket.objects.filter(
team=team, slack_channel_id=source_channel, slack_thread_ts=source_message_ts
).exists()
@@ -246,28 +388,15 @@ def process_supporthog_interactivity(payload: dict[str, Any], slack_team_id: str
slack_channel_id=source_channel,
message_ts=source_message_ts,
)
- if ticket is None:
- # A duplicate delivery (double click or webhook retry) can lose the
- # per-thread create lock to a concurrent sibling and see None while
- # the sibling's ticket is mid-create. Retry instead of reporting a
- # false failure — the re-run resolves to the committed ticket via
- # the existing-ticket check in create_ticket_from_confirmation.
- # Genuine failures exhaust retries into the error update below.
- raise cast(Any, process_supporthog_interactivity).retry()
- except Retry:
- raise
- except MaxRetriesExceededError:
- pass
+ except SlackConfirmationNeedsRetry:
+ _raise_if_retry_allowed(allow_retry)
except Exception as e:
logger.exception("supporthog_interactivity_create_failed", error=str(e))
- # Retry transient failures — the retried run redoes the whole handler,
+ # Retry transient failures. The retried run redoes the whole handler,
# so the prompt still resolves on eventual success. Once retries are
# exhausted, fall through to the error update below rather than leaving
# the user staring at live buttons forever.
- try:
- raise cast(Any, process_supporthog_interactivity).retry(exc=e)
- except MaxRetriesExceededError:
- pass
+ _raise_if_retry_allowed(allow_retry)
# Replace the prompt in place: a confirmation when we have a ticket (created or
# already open), or an explicit error so a failed open never reads as success.
# post_confirmation=False above means no separate confirmation was posted.
@@ -276,16 +405,12 @@ def process_supporthog_interactivity(payload: dict[str, Any], slack_team_id: str
else:
emoji = get_safe_ticket_emoji(support_settings)
text = f":warning: Couldn't open a ticket — react with :{emoji}: or @mention us to try again."
- final_update_ok = _update_supporthog_prompt(team, prompt_channel, prompt_ts, text)
- if not final_update_ok and prompt_channel and prompt_ts:
- # The progress placeholder must never be the prompt's last word — if the
- # final update fails transiently, retry the task (creation is idempotent,
- # the re-run re-attempts just this update). Once retries are exhausted,
- # fall through so the funnel event still records the outcome.
- try:
- raise cast(Any, process_supporthog_interactivity).retry()
- except MaxRetriesExceededError:
- pass
+ final_update = _update_supporthog_prompt(team, prompt_channel, prompt_ts, text)
+ prompt_can_be_updated = bool(prompt_channel and prompt_ts)
+ if final_update == "transient" and prompt_can_be_updated:
+ # The progress placeholder must never be the prompt's last word. Retry a
+ # transient Slack failure. A deleted or unauthorized prompt cannot recover.
+ _raise_if_retry_allowed(allow_retry)
# Captured after all retry exits (each retry re-raise leaves the task first),
# so the event fires once with the final outcome.
capture_nudge_event(
@@ -297,7 +422,115 @@ def process_supporthog_interactivity(payload: dict[str, Any], slack_team_id: str
"ticket_id": str(ticket.id) if ticket else None,
},
)
- return
+ return ticket is not None
+ return True
+
+
+def _process_interactivity_from_receipt(inbound_event_id: str) -> None:
+ claim = claim_inbound_event(inbound_event_id)
+ if claim is None:
+ return
+ payload = claim.event.payload
+ if not isinstance(payload, dict):
+ fail_inbound_event(
+ claim, error_code="poison_payload", error="inbound interactivity payload is missing or not an object"
+ )
+ return
+ config = _slack_config_for_workspace(
+ claim.event.provider_account_id,
+ receipt_team_id=claim.event.team_id,
+ )
+ if not config:
+ _retry_inbound_claim(claim, error_code="no_team", error="slack workspace is not connected")
+ return
+ try:
+ resolved = _handle_supporthog_interactivity(
+ payload,
+ claim.event.provider_account_id,
+ is_retry=claim.event.attempts > 1,
+ allow_retry=claim.allow_retry,
+ receipt_team_id=claim.event.team_id,
+ )
+ if resolved:
+ complete_inbound_event(claim)
+ else:
+ fail_inbound_event(
+ claim,
+ error_code="interactivity_failed",
+ error="Slack interactivity could not be completed",
+ )
+ except TransientInboundError:
+ _retry_inbound_claim(claim, error_code="transient", error="interactivity work needs another attempt")
+ except Exception as exc:
+ logger.exception("supporthog_interactivity_handler_failed", inbound_event_id=inbound_event_id, error=str(exc))
+ _retry_inbound_claim(claim, error_code="handler_failed", error=str(exc)[:INBOUND_ERROR_MAX_LENGTH])
+
+
+@shared_task(
+ name="products.conversations.backend.tasks.process_supporthog_interactivity_receipt",
+ ignore_result=True,
+)
+@skip_team_scope_audit
+def process_supporthog_interactivity_receipt(inbound_event_id: str) -> None:
+ _process_interactivity_from_receipt(inbound_event_id)
+
+
+@shared_task(
+ name="products.conversations.backend.tasks.process_supporthog_interactivity",
+ ignore_result=True,
+ max_retries=3,
+ default_retry_delay=5,
+)
+@skip_team_scope_audit
+def process_supporthog_interactivity(
+ payload: dict[str, Any] | None = None,
+ slack_team_id: str = "",
+) -> None:
+ """Handle a button click from the opt-in "open a ticket?" confirmation prompt."""
+ if not payload:
+ return
+ celery_retries = int(getattr(cast(Any, process_supporthog_interactivity).request, "retries", 0) or 0)
+ try:
+ _handle_supporthog_interactivity(
+ payload,
+ slack_team_id,
+ is_retry=celery_retries > 0,
+ allow_retry=True,
+ )
+ except TransientInboundError as exc:
+ try:
+ raise cast(Any, process_supporthog_interactivity).retry() from exc
+ except MaxRetriesExceededError:
+ _handle_supporthog_interactivity(payload, slack_team_id, is_retry=True, allow_retry=False)
+
+
+@shared_task(
+ name="products.conversations.backend.tasks.sweep_inbound_events",
+ ignore_result=True,
+)
+@skip_team_scope_audit
+def sweep_inbound_events() -> None:
+ """Re-drive due Slack receipts and expire payloads. Celery is only a wake-up hint."""
+ now = timezone.now()
+ due_rows = due_inbound_event_ids(limit=INBOUND_SWEEP_BATCH_SIZE, now=now)
+ dispatched = 0
+ for inbound_event_id, source in due_rows:
+ if wake_inbound_event(ConversationInboundEvent(id=inbound_event_id, source=source)):
+ dispatched += 1
+
+ payload_gc_count = drain_inbound_retention(cleanup_inbound_payloads, now)
+ tombstone_delete_count = drain_inbound_retention(delete_inbound_tombstones, now)
+ queue_metrics = record_inbound_queue_metrics(now)
+ if dispatched or payload_gc_count or tombstone_delete_count:
+ logger.info(
+ "sweep_inbound_events_completed",
+ dispatched=dispatched,
+ payload_gc_count=payload_gc_count,
+ tombstone_delete_count=tombstone_delete_count,
+ pending_count=queue_metrics.pending_count,
+ processing_count=queue_metrics.processing_count,
+ oldest_ready_age_seconds=queue_metrics.oldest_ready_age_seconds,
+ )
@shared_task(
diff --git a/products/conversations/backend/tests/test_inbound_event_processing.py b/products/conversations/backend/tests/test_inbound_event_processing.py
new file mode 100644
index 000000000000..02e318543bd3
--- /dev/null
+++ b/products/conversations/backend/tests/test_inbound_event_processing.py
@@ -0,0 +1,428 @@
+from collections.abc import Iterator
+from contextlib import contextmanager
+from datetime import timedelta
+from typing import Any
+from uuid import uuid4
+
+from freezegun import freeze_time
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.db import IntegrityError
+from django.test import RequestFactory, SimpleTestCase
+from django.utils import timezone
+
+from prometheus_client import REGISTRY, CollectorRegistry
+
+from posthog.metrics import pushed_metrics_registry
+from posthog.models.team import Team
+
+from products.conversations.backend.models import (
+ ConversationInboundEvent,
+ ConversationInboundEventSource,
+ TeamConversationsSlackConfig,
+)
+from products.conversations.backend.models.inbound_event import INBOUND_PAYLOAD_TTL, INBOUND_TOMBSTONE_TTL
+from products.conversations.backend.services.inbound_events import (
+ INBOUND_MAX_ATTEMPTS,
+ INBOUND_SWEEP_BATCH_SIZE,
+ INBOUND_SWEEP_MAX_ROUNDS,
+ accept_inbound_event,
+ claim_inbound_event,
+ complete_inbound_event,
+ drain_inbound_retention,
+ persist_inbound_event,
+ schedule_inbound_retry,
+ slack_events_source_id,
+ slack_interactivity_source_id,
+ slack_retry_metadata,
+)
+from products.conversations.backend.slack import TICKET_CONFIRM_ACTION_OPEN
+from products.conversations.backend.tasks.slack import (
+ process_supporthog_event_receipt,
+ process_supporthog_interactivity_receipt,
+ sweep_inbound_events,
+ wake_inbound_event,
+)
+
+
+@contextmanager
+def capture_pushed_registries() -> Iterator[list[CollectorRegistry]]:
+ captured: list[CollectorRegistry] = []
+
+ @contextmanager
+ def wrapper(job_name: str) -> Iterator[CollectorRegistry]:
+ with pushed_metrics_registry(job_name) as registry:
+ captured.append(registry)
+ yield registry
+
+ with patch("products.conversations.backend.services.inbound_events.pushed_metrics_registry", wrapper):
+ yield captured
+
+
+class TestInboundEventSourceId(SimpleTestCase):
+ def test_events_prefer_slack_event_id(self) -> None:
+ assert slack_events_source_id(event_id="Ev123", signed_body=b'{"x":1}') == "Ev123"
+
+ def test_events_hash_body_when_event_id_missing(self) -> None:
+ first = slack_events_source_id(event_id=None, signed_body=b'{"a":1}')
+ second = slack_events_source_id(event_id=None, signed_body=b'{"a":2}')
+ assert first != second
+ assert len(first) == 64
+
+ def test_interactivity_uses_trigger_and_container(self) -> None:
+ payload = {
+ "trigger_id": "trig.abc",
+ "actions": [{"action_id": "open_ticket"}],
+ "container": {"type": "message", "message_ts": "1.2", "channel_id": "C1", "thread_ts": "1.1"},
+ }
+ assert slack_interactivity_source_id(payload=payload, signed_body=b"ignored") == (
+ "trig.abc:open_ticket:message:1.2:C1:1.1"
+ )
+
+ def test_interactivity_hashes_signed_body_without_trigger_id(self) -> None:
+ payload = {"actions": [{"action_id": "open_ticket"}]}
+ assert slack_interactivity_source_id(payload=payload, signed_body=b"form-a") != slack_interactivity_source_id(
+ payload=payload, signed_body=b"form-b"
+ )
+
+
+class TestSlackRetryMetadata(SimpleTestCase):
+ def test_parses_retry_headers(self) -> None:
+ request = RequestFactory().post("/", HTTP_X_SLACK_RETRY_NUM="2", HTTP_X_SLACK_RETRY_REASON="http_timeout")
+ assert slack_retry_metadata(request) == (2, "http_timeout")
+
+ def test_invalid_retry_num_is_ignored(self) -> None:
+ request = RequestFactory().post("/", HTTP_X_SLACK_RETRY_NUM="nope", HTTP_X_SLACK_RETRY_REASON="http_timeout")
+ assert slack_retry_metadata(request) == (None, "http_timeout")
+
+ def test_negative_retry_num_is_ignored(self) -> None:
+ request = RequestFactory().post("/", HTTP_X_SLACK_RETRY_NUM="-1")
+ assert slack_retry_metadata(request) == (None, "")
+
+
+class TestWakeInboundEvent(SimpleTestCase):
+ @patch.object(process_supporthog_event_receipt, "apply_async")
+ def test_wake_does_not_retry_broker_publish(self, mock_apply: MagicMock) -> None:
+ row = ConversationInboundEvent(id=uuid4(), source=ConversationInboundEventSource.SLACK_EVENTS)
+ assert wake_inbound_event(row) is True
+ mock_apply.assert_called_once_with(kwargs={"inbound_event_id": str(row.id)}, retry=False)
+
+ @patch.object(process_supporthog_event_receipt, "apply_async", side_effect=ConnectionError("broker down"))
+ def test_wake_returns_false_when_broker_publish_fails(self, mock_apply: MagicMock) -> None:
+ row = ConversationInboundEvent(id=uuid4(), source=ConversationInboundEventSource.SLACK_EVENTS)
+ assert wake_inbound_event(row) is False
+ mock_apply.assert_called_once()
+
+
+class TestDrainInboundRetention(SimpleTestCase):
+ def test_stops_on_short_batch(self) -> None:
+ calls = {"n": 0}
+
+ def cleanup(_now: object) -> int:
+ calls["n"] += 1
+ return INBOUND_SWEEP_BATCH_SIZE if calls["n"] == 1 else 3
+
+ assert drain_inbound_retention(cleanup, timezone.now()) == INBOUND_SWEEP_BATCH_SIZE + 3
+ assert calls["n"] == 2
+
+ def test_caps_rounds(self) -> None:
+ def cleanup(_now: object) -> int:
+ return INBOUND_SWEEP_BATCH_SIZE
+
+ assert drain_inbound_retention(cleanup, timezone.now()) == INBOUND_SWEEP_BATCH_SIZE * INBOUND_SWEEP_MAX_ROUNDS
+
+
+class TestInboundEventProcessing(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.team.conversations_enabled = True
+ self.team.conversations_settings = {"slack_enabled": True}
+ self.team.save()
+ TeamConversationsSlackConfig.objects.update_or_create(
+ team=self.team,
+ defaults={"slack_team_id": "T123", "slack_bot_token": "xoxb-test"},
+ )
+
+ def _create_pending(
+ self,
+ *,
+ source: str = ConversationInboundEventSource.SLACK_EVENTS,
+ source_id: str = "Ev1",
+ **kwargs: Any,
+ ) -> ConversationInboundEvent:
+ payload = kwargs.pop("payload", {"type": "event_callback", "event": {"type": "message", "channel": "C1"}})
+ return ConversationInboundEvent.objects.for_team(self.team.id).create(
+ team=self.team,
+ source=source,
+ source_id=source_id,
+ provider_account_id="T123",
+ payload=payload,
+ **kwargs,
+ )
+
+ @patch("products.conversations.backend.tasks.slack.handle_support_message")
+ def test_provider_retry_after_worker_failure(self, mock_handle: MagicMock) -> None:
+ row = self._create_pending()
+ mock_handle.side_effect = [RuntimeError("slack timeout"), None]
+
+ with patch(
+ "products.conversations.backend.services.inbound_events.retry_delay_seconds",
+ return_value=5,
+ ):
+ process_supporthog_event_receipt(inbound_event_id=str(row.id))
+ row.refresh_from_db()
+ assert row.status == ConversationInboundEvent.Status.PENDING
+ assert row.attempts == 1
+
+ row.due_at = timezone.now()
+ row.save(update_fields=["due_at", "updated_at"])
+ process_supporthog_event_receipt(inbound_event_id=str(row.id))
+ row.refresh_from_db()
+ assert row.status == ConversationInboundEvent.Status.PROCESSED
+ assert mock_handle.call_count == 2
+
+ def test_expired_lease_fencing_ignores_stale_complete(self) -> None:
+ row = self._create_pending()
+ first = claim_inbound_event(str(row.id))
+ assert first is not None
+
+ ConversationInboundEvent.objects.unscoped().filter(id=row.id).update(
+ lease_expires_at=timezone.now() - timedelta(seconds=1),
+ updated_at=timezone.now(),
+ )
+ second = claim_inbound_event(str(row.id))
+ assert second is not None
+ assert second.event.fencing_token != first.event.fencing_token
+ assert second.expired_reclaim is True
+
+ assert complete_inbound_event(first) is False
+ second.event.refresh_from_db()
+ assert second.event.status == ConversationInboundEvent.Status.PROCESSING
+ assert complete_inbound_event(second) is True
+ second.event.refresh_from_db()
+ assert second.event.status == ConversationInboundEvent.Status.PROCESSED
+
+ def test_complete_after_scheduled_retry_is_ignored(self) -> None:
+ row = self._create_pending()
+ claim = claim_inbound_event(str(row.id))
+ assert claim is not None
+ assert schedule_inbound_retry(claim, error_code="handler_failed", error="timeout") is not None
+ assert complete_inbound_event(claim) is False
+ row.refresh_from_db()
+ assert row.status == ConversationInboundEvent.Status.PENDING
+
+ def test_expired_receipt_is_failed_after_max_attempts(self) -> None:
+ row = self._create_pending(
+ status=ConversationInboundEvent.Status.PROCESSING,
+ attempts=INBOUND_MAX_ATTEMPTS,
+ lease_expires_at=timezone.now() - timedelta(seconds=1),
+ )
+
+ assert claim_inbound_event(str(row.id)) is None
+
+ row.refresh_from_db()
+ assert row.status == ConversationInboundEvent.Status.FAILED
+ assert row.last_error_code == "max_attempts"
+ assert row.terminal_at is not None
+
+ def test_persist_check_violation_is_not_treated_as_duplicate(self) -> None:
+ with self.assertRaises(IntegrityError):
+ persist_inbound_event(
+ team=self.team,
+ source=ConversationInboundEventSource.SLACK_EVENTS,
+ source_id="",
+ provider_account_id="T123",
+ payload={"type": "event_callback"},
+ provider_retry_num=None,
+ provider_retry_reason="",
+ )
+
+ def test_accept_does_not_wake_before_due(self) -> None:
+ self._create_pending()
+ ConversationInboundEvent.objects.unscoped().filter(source_id="Ev1").update(
+ due_at=timezone.now() + timedelta(minutes=5),
+ updated_at=timezone.now(),
+ )
+ wake = MagicMock()
+ with self.captureOnCommitCallbacks(execute=True):
+ accept_inbound_event(
+ team=self.team,
+ source=ConversationInboundEventSource.SLACK_EVENTS,
+ source_id="Ev1",
+ provider_account_id="T123",
+ payload={"type": "event_callback", "event": {"type": "message"}},
+ provider_retry_num=2,
+ provider_retry_reason="http_timeout",
+ wake=wake,
+ )
+ wake.assert_not_called()
+
+ @patch("products.conversations.backend.tasks.slack.handle_support_message")
+ def test_duplicate_claim_of_processed_row_is_noop(self, mock_handle: MagicMock) -> None:
+ row = self._create_pending()
+ process_supporthog_event_receipt(inbound_event_id=str(row.id))
+ process_supporthog_event_receipt(inbound_event_id=str(row.id))
+ row.refresh_from_db()
+ assert row.status == ConversationInboundEvent.Status.PROCESSED
+ mock_handle.assert_called_once()
+
+ @patch("products.conversations.backend.tasks.slack.cache.add")
+ @patch("products.conversations.backend.tasks.slack.handle_support_message")
+ def test_receipt_does_not_use_redis_dedupe(self, mock_handle: MagicMock, mock_cache_add: MagicMock) -> None:
+ row = self._create_pending()
+ process_supporthog_event_receipt(inbound_event_id=str(row.id))
+ mock_cache_add.assert_not_called()
+ mock_handle.assert_called_once()
+
+ @patch("products.conversations.backend.tasks.slack.handle_support_message")
+ def test_receipt_uses_workspace_config_from_child_environment(self, mock_handle: MagicMock) -> None:
+ TeamConversationsSlackConfig.objects.filter(team=self.team).update(slack_team_id=None)
+ child_team = Team.objects.create(
+ organization=self.organization,
+ project=self.project,
+ parent_team=self.team,
+ name="Child environment",
+ conversations_settings={"slack_enabled": True},
+ )
+ TeamConversationsSlackConfig.objects.update_or_create(
+ team=child_team,
+ defaults={"slack_team_id": "T123", "slack_bot_token": "xoxb-child"},
+ )
+ row = self._create_pending()
+
+ process_supporthog_event_receipt(inbound_event_id=str(row.id))
+
+ row.refresh_from_db()
+ assert row.status == ConversationInboundEvent.Status.PROCESSED
+ mock_handle.assert_called_once_with(
+ {"type": "message", "channel": "C1"},
+ child_team,
+ "T123",
+ )
+
+ @patch("products.conversations.backend.tasks.slack.handle_support_message")
+ def test_receipt_is_not_processed_after_workspace_moves_to_another_team(self, mock_handle: MagicMock) -> None:
+ row = self._create_pending()
+ TeamConversationsSlackConfig.objects.filter(team=self.team).update(slack_team_id=None)
+ other_team = Team.objects.create_with_data(organization=self.organization, initiating_user=self.user)
+ TeamConversationsSlackConfig.objects.update_or_create(
+ team=other_team,
+ defaults={"slack_team_id": "T123", "slack_bot_token": "xoxb-other"},
+ )
+
+ process_supporthog_event_receipt(inbound_event_id=str(row.id))
+
+ row.refresh_from_db()
+ assert row.status == ConversationInboundEvent.Status.PENDING
+ assert row.last_error_code == "no_team"
+ mock_handle.assert_not_called()
+
+ @patch("products.conversations.backend.tasks.slack._update_supporthog_prompt", return_value="updated")
+ @patch("products.conversations.backend.tasks.slack.create_ticket_from_confirmation", return_value=None)
+ def test_exhausted_interactivity_is_failed(self, mock_create: MagicMock, mock_update: MagicMock) -> None:
+ row = self._create_pending(
+ source=ConversationInboundEventSource.SLACK_INTERACTIVITY,
+ attempts=INBOUND_MAX_ATTEMPTS - 1,
+ payload={
+ "type": "block_actions",
+ "team": {"id": "T123"},
+ "container": {"channel_id": "C1", "message_ts": "1.0"},
+ "actions": [
+ {
+ "action_id": TICKET_CONFIRM_ACTION_OPEN,
+ "value": '{"channel": "C1", "message_ts": "1.0"}',
+ }
+ ],
+ },
+ )
+
+ process_supporthog_interactivity_receipt(inbound_event_id=str(row.id))
+
+ row.refresh_from_db()
+ assert row.status == ConversationInboundEvent.Status.FAILED
+ assert row.last_error_code == "interactivity_failed"
+ mock_create.assert_called_once()
+ mock_update.assert_called_once()
+
+ @patch("products.conversations.backend.tasks.slack.handle_support_message")
+ def test_poison_payload_is_terminal(self, mock_handle: MagicMock) -> None:
+ row = self._create_pending(payload=["not", "an", "object"])
+ process_supporthog_event_receipt(inbound_event_id=str(row.id))
+ row.refresh_from_db()
+ assert row.status == ConversationInboundEvent.Status.FAILED
+ assert row.last_error_code == "poison_payload"
+ mock_handle.assert_not_called()
+
+ @patch("products.conversations.backend.tasks.slack.wake_inbound_event")
+ def test_sweeper_redrives_due_work_and_cleans_payloads(self, mock_wake: MagicMock) -> None:
+ due = self._create_pending(source_id="Ev-due")
+ future = self._create_pending(source_id="Ev-later")
+ ConversationInboundEvent.objects.unscoped().filter(id=future.id).update(
+ due_at=timezone.now() + timedelta(hours=1),
+ updated_at=timezone.now(),
+ )
+ terminal = self._create_pending(
+ source_id="Ev-old",
+ status=ConversationInboundEvent.Status.PROCESSED,
+ terminal_at=timezone.now() - INBOUND_PAYLOAD_TTL - timedelta(minutes=1),
+ payload={"event": {"type": "message"}},
+ )
+
+ sweep_inbound_events()
+
+ mock_wake.assert_called_once()
+ assert str(mock_wake.call_args.args[0].id) == str(due.id)
+ terminal.refresh_from_db()
+ assert terminal.payload is None
+ future.refresh_from_db()
+ assert future.status == ConversationInboundEvent.Status.PENDING
+
+ def test_sweeper_deletes_expired_tombstones(self) -> None:
+ row = self._create_pending(
+ source_id="Ev-tombstone",
+ status=ConversationInboundEvent.Status.FAILED,
+ terminal_at=timezone.now() - INBOUND_TOMBSTONE_TTL - timedelta(minutes=1),
+ payload=None,
+ )
+ sweep_inbound_events()
+ assert not ConversationInboundEvent.objects.unscoped().filter(id=row.id).exists()
+
+ def test_sweeper_drains_more_than_one_tombstone_batch(self) -> None:
+ cutoff = timezone.now() - INBOUND_TOMBSTONE_TTL - timedelta(minutes=1)
+ ConversationInboundEvent.objects.for_team(self.team.id).bulk_create(
+ [
+ ConversationInboundEvent(
+ team=self.team,
+ source=ConversationInboundEventSource.SLACK_EVENTS,
+ source_id=f"Ev-tombstone-{i}",
+ provider_account_id="T123",
+ status=ConversationInboundEvent.Status.FAILED,
+ terminal_at=cutoff,
+ payload=None,
+ )
+ for i in range(INBOUND_SWEEP_BATCH_SIZE + 1)
+ ]
+ )
+
+ sweep_inbound_events()
+
+ assert ConversationInboundEvent.objects.unscoped().filter(source_id__startswith="Ev-tombstone-").count() == 0
+
+ @patch("products.conversations.backend.tasks.slack.wake_inbound_event")
+ def test_sweeper_measures_expired_lease_age_from_lease_expiry(self, mock_wake: MagicMock) -> None:
+ with freeze_time("2026-09-10 12:00:00"):
+ self._create_pending(source_id="Ev-old-ready")
+ ConversationInboundEvent.objects.unscoped().filter(source_id="Ev-old-ready").update(
+ status=ConversationInboundEvent.Status.PROCESSING,
+ due_at=timezone.now() - timedelta(days=1),
+ lease_expires_at=timezone.now() - timedelta(minutes=3),
+ updated_at=timezone.now(),
+ )
+ with capture_pushed_registries() as registries:
+ sweep_inbound_events()
+ age = registries[0].get_sample_value("posthog_conversations_inbound_oldest_ready_age_seconds")
+ assert age == 180
+ last_sweep = registries[0].get_sample_value("posthog_conversations_inbound_last_sweep_timestamp_seconds")
+ assert last_sweep is not None
+ assert REGISTRY.get_sample_value("posthog_conversations_inbound_oldest_ready_age_seconds") is None
diff --git a/products/conversations/backend/tests/test_task_registration.py b/products/conversations/backend/tests/test_task_registration.py
index aeeb582b335a..a08aef1d9b2e 100644
--- a/products/conversations/backend/tests/test_task_registration.py
+++ b/products/conversations/backend/tests/test_task_registration.py
@@ -6,7 +6,10 @@ from posthog.celery import app
# a submodule import would leave queued messages and Beat entries unresolved.
EXPECTED_TASK_NAMES = {
"products.conversations.backend.tasks.process_supporthog_event",
+ "products.conversations.backend.tasks.process_supporthog_event_receipt",
"products.conversations.backend.tasks.process_supporthog_interactivity",
+ "products.conversations.backend.tasks.process_supporthog_interactivity_receipt",
+ "products.conversations.backend.tasks.sweep_inbound_events",
"products.conversations.backend.tasks.post_reply_to_slack",
"products.conversations.backend.tasks.send_email_reply",
"products.conversations.backend.tasks.flush_pending_email_replies",