:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(conversations): renew inbound leases during backfill (#98999)
Alex V8e79e2d2258c
diff --git a/docs/internal/conversations-reliability.md b/docs/internal/conversations-reliability.mdindex 98596961aadf..9abc7bed4440 100644--- a/docs/internal/conversations-reliability.md+++ b/docs/internal/conversations-reliability.md@@ -67,7 +67,7 @@ Celery `on_commit` dispatch is a wake-up hint with `apply_async(..., retry=FalseWorkers 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.+Completes, fails, retries, and lease renewals 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.@@ -76,6 +76,11 @@ Keep the legacy task names registered until payload tasks from the old endpointLive queue gauges (backlog, oldest ready age, last-sweep timestamp) are pushed through `pushed_metrics_registry`.Do not emit a ClickHouse event for each sweep.+Slack thread backfill paginates `conversations.replies`, up to 25 pages (5,000 replies).+Workers call `renew_inbound_lease` between pages, once more before comment writes, and every 25 replies during comment construction.+A failed renewal (fencing miss or database error) is logged. The worker finishes the backfill anyway: the replacement worker skips backfill once the ticket exists, so aborting would drop the rest of the thread.+Fencing still stops the stale worker settling the receipt.+## Outbound email (already in Postgres)`EmailOutboxMessage` remains the outbound email outbox.diff --git a/products/conversations/backend/api/tests/test_reaction_backfill.py b/products/conversations/backend/api/tests/test_reaction_backfill.pyindex b49619b0a699..39df4b68b402 100644--- a/products/conversations/backend/api/tests/test_reaction_backfill.py+++ b/products/conversations/backend/api/tests/test_reaction_backfill.py@@ -1,15 +1,24 @@+from datetime import timedeltafrom typing import Any+from uuid import uuid4from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, call, patch+from django.utils import timezone+from parameterized import parameterizedfrom posthog.models.comment import Commentfrom products.conversations.backend.cache import slack_ticket_create_lock-from products.conversations.backend.models import Ticket+from products.conversations.backend.models import ConversationInboundEvent, ConversationInboundEventSource, Ticketfrom products.conversations.backend.models.constants import Channel, ChannelDetail+from products.conversations.backend.services.inbound_events import (+ InboundClaim,+ claim_inbound_event,+ complete_inbound_event,+)from products.conversations.backend.slack import (_backfill_thread_replies,create_or_update_slack_ticket,@@ -50,6 +59,18 @@ class TestBackfillThreadReplies(BaseTest):client.conversations_replies.return_value = {"messages": replies}return client+ def _claimed_receipt(self) -> InboundClaim:+ row = ConversationInboundEvent.objects.for_team(self.team.id).create(+ team=self.team,+ source=ConversationInboundEventSource.SLACK_EVENTS,+ source_id=f"Ev-backfill-{uuid4().hex}",+ provider_account_id="T123",+ payload={"event": {"type": "reaction_added"}},+ )+ claim = claim_inbound_event(str(row.id))+ assert claim is not None+ return claim+@patch(f"{MODULE}.get_bot_user_id", return_value="U_OWN_BOT")@patch(f"{MODULE}.resolve_slack_user", return_value={"name": "Alice", "email": "[email protected]", "avatar": None})@patch(f"{MODULE}.extract_slack_files", return_value=[])@@ -253,6 +274,137 @@ class TestBackfillThreadReplies(BaseTest):self.ticket.refresh_from_db()assert self.ticket.unread_team_count == 1+ @patch(f"{MODULE}.get_bot_user_id", return_value="U_OWN_BOT")+ @patch(f"{MODULE}.resolve_slack_user", return_value={"name": "Alice", "email": "[email protected]", "avatar": None})+ @patch(f"{MODULE}.extract_slack_files", return_value=[])+ def test_paginates_conversations_replies(self, _mock_files, _mock_user, _mock_bot):+ client = MagicMock()+ client.conversations_replies.side_effect = [+ {+ "messages": [+ _make_slack_reply(PARENT_TS, text="parent"),+ _make_slack_reply("1700000000.000200", text="first"),+ ],+ "response_metadata": {"next_cursor": "c1"},+ },+ {"messages": [_make_slack_reply("1700000000.000300", text="second")]},+ ]++ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")++ assert client.conversations_replies.call_args_list == [+ call(channel=CHANNEL, ts=PARENT_TS, limit=200),+ call(channel=CHANNEL, ts=PARENT_TS, limit=200, cursor="c1"),+ ]+ comments = Comment.objects.filter(item_id=str(self.ticket.id)).order_by("created_at")+ assert [comment.content for comment in comments] == ["first", "second"]++ @patch(f"{MODULE}.get_bot_user_id", return_value="U_OWN_BOT")+ @patch(f"{MODULE}.resolve_slack_user", return_value={"name": "Alice", "email": "[email protected]", "avatar": None})+ @patch(f"{MODULE}.extract_slack_files", return_value=[])+ def test_keeps_earlier_pages_when_a_later_page_fails(self, _mock_files, _mock_user, _mock_bot):+ client = MagicMock()+ client.conversations_replies.side_effect = [+ {+ "messages": [+ _make_slack_reply(PARENT_TS, text="parent"),+ _make_slack_reply("1700000000.000200", text="first"),+ ],+ "response_metadata": {"next_cursor": "c1"},+ },+ Exception("Slack API error"),+ ]++ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")++ comments = Comment.objects.filter(item_id=str(self.ticket.id))+ assert [comment.content for comment in comments] == ["first"]++ @patch(f"{MODULE}.get_bot_user_id", return_value="U_OWN_BOT")+ @patch(f"{MODULE}.resolve_slack_user", return_value={"name": "Alice", "email": "[email protected]", "avatar": None})+ @patch(f"{MODULE}.extract_slack_files", return_value=[])+ def test_backfill_finishes_after_lease_is_lost(self, _mock_files, _mock_user, _mock_bot):+ first = self._claimed_receipt()+ ConversationInboundEvent.objects.unscoped().filter(id=first.event.id).update(+ lease_expires_at=timezone.now() - timedelta(seconds=1),+ updated_at=timezone.now(),+ )+ second = claim_inbound_event(str(first.event.id))+ assert second is not None++ client = MagicMock()+ client.conversations_replies.side_effect = [+ {+ "messages": [+ _make_slack_reply(PARENT_TS, text="parent"),+ _make_slack_reply("1700000000.000200", text="first"),+ ],+ "response_metadata": {"next_cursor": "c1"},+ },+ {"messages": [_make_slack_reply("1700000000.000300", text="second")]},+ ]++ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123", claim=first)++ assert client.conversations_replies.call_count == 2+ comments = Comment.objects.filter(item_id=str(self.ticket.id)).order_by("created_at")+ assert [comment.content for comment in comments] == ["first", "second"]+ self.ticket.refresh_from_db()+ assert self.ticket.unread_team_count == 3+ assert complete_inbound_event(first) is False+ assert complete_inbound_event(second) is True++ @patch(f"{MODULE}.renew_inbound_lease", side_effect=Exception("db down"))+ @patch(f"{MODULE}.get_bot_user_id", return_value="U_OWN_BOT")+ @patch(f"{MODULE}.resolve_slack_user", return_value={"name": "Alice", "email": "[email protected]", "avatar": None})+ @patch(f"{MODULE}.extract_slack_files", return_value=[])+ def test_backfill_finishes_when_lease_renew_raises(self, _mock_files, _mock_user, _mock_bot, _mock_renew):+ claim = self._claimed_receipt()+ client = MagicMock()+ client.conversations_replies.side_effect = [+ {+ "messages": [+ _make_slack_reply(PARENT_TS, text="parent"),+ _make_slack_reply("1700000000.000200", text="first"),+ ],+ "response_metadata": {"next_cursor": "c1"},+ },+ {"messages": [_make_slack_reply("1700000000.000300", text="second")]},+ ]++ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123", claim=claim)++ assert client.conversations_replies.call_count == 2+ comments = Comment.objects.filter(item_id=str(self.ticket.id)).order_by("created_at")+ assert [comment.content for comment in comments] == ["first", "second"]++ @patch(f"{MODULE}.BACKFILL_THREAD_MAX_PAGES", 2)+ @patch(f"{MODULE}.get_bot_user_id", return_value="U_OWN_BOT")+ @patch(f"{MODULE}.resolve_slack_user", return_value={"name": "Alice", "email": "[email protected]", "avatar": None})+ @patch(f"{MODULE}.extract_slack_files", return_value=[])+ def test_stops_at_page_cap_and_keeps_fetched_replies(self, _mock_files, _mock_user, _mock_bot):+ client = MagicMock()+ client.conversations_replies.side_effect = [+ {+ "messages": [+ _make_slack_reply(PARENT_TS, text="parent"),+ _make_slack_reply("1700000000.000200", text="first"),+ ],+ "response_metadata": {"next_cursor": "c1"},+ },+ {+ "messages": [_make_slack_reply("1700000000.000300", text="second")],+ "response_metadata": {"next_cursor": "c2"},+ },+ {"messages": [_make_slack_reply("1700000000.000400", text="third")]},+ ]++ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")++ assert client.conversations_replies.call_count == 2+ comments = Comment.objects.filter(item_id=str(self.ticket.id)).order_by("created_at")+ assert [comment.content for comment in comments] == ["first", "second"]+@patch(f"{MODULE}.get_bot_user_id", return_value="U_OWN_BOT")@patch(f"{MODULE}.resolve_slack_user", return_value={"name": "Bob", "email": "[email protected]", "avatar": "http://av"})@patch(f"{MODULE}.extract_slack_files", return_value=[])diff --git a/products/conversations/backend/metrics.py b/products/conversations/backend/metrics.pyindex 4bde635ebb75..fa9359b8043b 100644--- a/products/conversations/backend/metrics.py+++ b/products/conversations/backend/metrics.py@@ -24,5 +24,5 @@ INBOUND_ATTEMPTS_TOTAL = Counter(INBOUND_LEASES_TOTAL = Counter("posthog_conversations_inbound_leases_total","Inbound receipt lease outcomes",- labelnames=["result"], # claimed | expired_reclaim | busy+ labelnames=["result"], # claimed | expired_reclaim | busy | renewed | renew_rejected)diff --git a/products/conversations/backend/services/inbound_events.py b/products/conversations/backend/services/inbound_events.pyindex 32bfd9702f7b..a6dda4a57f22 100644--- a/products/conversations/backend/services/inbound_events.py+++ b/products/conversations/backend/services/inbound_events.py@@ -2,7 +2,9 @@ from __future__ import annotationsimport randomimport hashlib-from collections.abc import Callable+from collections.abc import Callable, Iterator+from contextlib import contextmanager+from contextvars import ContextVarfrom datetime import datetime, timedeltafrom typing import Any, castfrom uuid import UUID@@ -32,8 +34,12 @@ from products.conversations.backend.models.inbound_event import (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.+# is reclaim latency, not a handler wall-clock. Backfill renews the same lease so a live+# worker is not reclaimed mid-page.INBOUND_LEASE_SECONDS = 20 * 60+# Slack pages are 200 replies. Renewing every 25 keeps the lease alive through user+# lookups and file downloads without a write per message.+INBOUND_LEASE_RENEW_EVERY_REPLIES = 25INBOUND_MAX_ATTEMPTS = 20INBOUND_BACKOFF_BASE_SECONDS = 15INBOUND_BACKOFF_MAX_SECONDS = 15 * 60@@ -56,6 +62,22 @@ class InboundClaim:expired_reclaim: bool+_current_inbound_claim: ContextVar[InboundClaim | None] = ContextVar("conversations_inbound_claim", default=None)+++@contextmanager+def inbound_claim_scope(claim: InboundClaim) -> Iterator[None]:+ token = _current_inbound_claim.set(claim)+ try:+ yield+ finally:+ _current_inbound_claim.reset(token)+++def get_current_inbound_claim() -> InboundClaim | None:+ return _current_inbound_claim.get()++@frozenclass InboundQueueMetrics:pending_count: int@@ -299,6 +321,19 @@ def _fenced(claim: InboundClaim) -> QuerySet[ConversationInboundEvent]:)+def renew_inbound_lease(claim: InboundClaim) -> bool:+ now = timezone.now()+ updated = _fenced(claim).update(+ lease_expires_at=now + timedelta(seconds=INBOUND_LEASE_SECONDS),+ updated_at=now,+ )+ if updated:+ INBOUND_LEASES_TOTAL.labels(result="renewed").inc()+ return True+ INBOUND_LEASES_TOTAL.labels(result="renew_rejected").inc()+ return False++def complete_inbound_event(claim: InboundClaim, *, error_code: str = "", error: str = "") -> bool:now = timezone.now()updated = _fenced(claim).update(diff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.pyindex 021f142c1a87..818d1adfb510 100644--- a/products/conversations/backend/slack.py+++ b/products/conversations/backend/slack.py@@ -55,6 +55,12 @@ from .services.attachments import (sanitize_attachment_filename,save_file_to_uploaded_media,)+from .services.inbound_events import (+ INBOUND_LEASE_RENEW_EVERY_REPLIES,+ InboundClaim,+ get_current_inbound_claim,+ renew_inbound_lease,+)from .support_slack import (SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES,SUPPORT_SLACK_FILE_READ_SCOPE,@@ -66,6 +72,8 @@ from .support_slack import (logger = structlog.get_logger(__name__)SLACK_DOWNLOAD_TIMEOUT_SECONDS = 10MAX_REDIRECTS = 5+# 200 replies per page. Stop so a runaway next_cursor cannot hold the worker.+BACKFILL_THREAD_MAX_PAGES = 25# Slack message subtypes that carry real, user-authored content and may open or update a# ticket. A normal message has no subtype at all; these few subtypes also count as content@@ -1284,6 +1292,37 @@ def handle_support_mention(event: dict, team: Team, slack_team_id: str) -> None:)+def _renew_backfill_lease(claim: InboundClaim | None) -> InboundClaim | None:+ """Extend the inbound lease. On fencing failure or renew error return None and keep going.++ create_or_update_slack_ticket returns None to losers so they do not backfill.+ This worker already created the ticket, so aborting here would drop the rest of+ the thread permanently. Fencing still stops this worker settling the receipt.+ """+ if claim is None:+ return None+ try:+ if renew_inbound_lease(claim):+ return claim+ except Exception as exc:+ capture_exception(+ exc,+ {"inbound_event_id": str(claim.event.id), "fencing_token": claim.event.fencing_token},+ )+ logger.warning(+ "inbound_event_lease_renew_error",+ inbound_event_id=str(claim.event.id),+ fencing_token=claim.event.fencing_token,+ )+ return None+ logger.warning(+ "inbound_event_lease_renew_rejected",+ inbound_event_id=str(claim.event.id),+ fencing_token=claim.event.fencing_token,+ )+ return None++def _backfill_thread_replies(client: WebClient,team: Team,@@ -1293,6 +1332,7 @@ def _backfill_thread_replies(*,slack_team_id: str | None,after_ts: str | None = None,+ claim: InboundClaim | None = None,) -> None:"""Fetch existing thread replies and add them as comments on the ticket.@@ -1301,12 +1341,31 @@ def _backfill_thread_replies(isn't pulled in. Slack ts values are lexicographically ordered, so string comparison issafe."""- try:- result = client.conversations_replies(channel=channel, ts=thread_ts, limit=200)- replies: list[dict] = result.get("messages", [])- except Exception:- logger.warning("slack_support_reaction_backfill_failed", channel=channel, thread_ts=thread_ts)- return+ active_claim = claim if claim is not None else get_current_inbound_claim()+ replies: list[dict] = []+ cursor: str | None = None+ for _ in range(BACKFILL_THREAD_MAX_PAGES):+ kwargs: dict[str, Any] = {"channel": channel, "ts": thread_ts, "limit": 200}+ if cursor is not None:+ kwargs["cursor"] = cursor+ try:+ result = client.conversations_replies(**kwargs)+ except Exception:+ logger.warning("slack_support_reaction_backfill_failed", channel=channel, thread_ts=thread_ts)+ break+ replies.extend(result.get("messages") or [])+ next_cursor = ((result.get("response_metadata") or {}).get("next_cursor")) or None+ if not next_cursor or next_cursor == cursor:+ break+ cursor = next_cursor+ active_claim = _renew_backfill_lease(active_claim)+ else:+ logger.warning(+ "slack_support_reaction_backfill_page_cap",+ channel=channel,+ thread_ts=thread_ts,+ max_pages=BACKFILL_THREAD_MAX_PAGES,+ )thread_replies = [r for r in replies if r.get("ts") != thread_ts and (after_ts is None or (r.get("ts") or "") > after_ts)@@ -1322,6 +1381,8 @@ def _backfill_thread_replies(thread_reply_count=len(thread_replies),)+ active_claim = _renew_backfill_lease(active_claim)+own_bot_user_id = get_bot_user_id(client)user_cache: dict[str, dict] = {}posthog_user_cache: dict[str, User | None] = {}@@ -1329,7 +1390,9 @@ def _backfill_thread_replies(customer_message_count = 0team_message_count = 0- for reply in thread_replies:+ for reply_index, reply in enumerate(thread_replies, start=1):+ if reply_index % INBOUND_LEASE_RENEW_EVERY_REPLIES == 0:+ active_claim = _renew_backfill_lease(active_claim)reply_is_bot = bool(reply.get("bot_id") or reply.get("subtype") == "bot_message")if not _is_ticketable_message(reply, is_bot=reply_is_bot):continuediff --git a/products/conversations/backend/tasks/slack.py b/products/conversations/backend/tasks/slack.pyindex 8b1abc1d2ff5..74d392fcc1b2 100644--- a/products/conversations/backend/tasks/slack.py+++ b/products/conversations/backend/tasks/slack.py@@ -41,6 +41,7 @@ from products.conversations.backend.services.inbound_events import (drain_inbound_retention,due_inbound_event_ids,fail_inbound_event,+ inbound_claim_scope,inbound_event_payload_event,record_inbound_queue_metrics,schedule_inbound_retry,@@ -174,7 +175,8 @@ def _process_event_from_receipt(inbound_event_id: str) -> None:complete_inbound_event(claim)returntry:- _handle_supporthog_event(event, team, claim.event.provider_account_id)+ with inbound_claim_scope(claim):+ _handle_supporthog_event(event, team, claim.event.provider_account_id)complete_inbound_event(claim)except Exception as exc:logger.exception(@@ -444,13 +446,14 @@ def _process_interactivity_from_receipt(inbound_event_id: str) -> None:_retry_inbound_claim(claim, error_code="no_team", error="slack workspace is not connected")returntry:- 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,- )+ with inbound_claim_scope(claim):+ 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:diff --git a/products/conversations/backend/tests/test_inbound_event_processing.py b/products/conversations/backend/tests/test_inbound_event_processing.pyindex a2b3680cc6ee..1222a6e62978 100644--- a/products/conversations/backend/tests/test_inbound_event_processing.py+++ b/products/conversations/backend/tests/test_inbound_event_processing.py@@ -24,6 +24,7 @@ from products.conversations.backend.models import ()from products.conversations.backend.models.inbound_event import INBOUND_PAYLOAD_TTL, INBOUND_TOMBSTONE_TTLfrom products.conversations.backend.services.inbound_events import (+ INBOUND_LEASE_SECONDS,INBOUND_MAX_ATTEMPTS,INBOUND_SWEEP_BATCH_SIZE,INBOUND_SWEEP_MAX_ROUNDS,@@ -31,7 +32,9 @@ from products.conversations.backend.services.inbound_events import (claim_inbound_event,complete_inbound_event,drain_inbound_retention,+ get_current_inbound_claim,persist_inbound_event,+ renew_inbound_lease,schedule_inbound_retry,slack_events_source_id,slack_interactivity_source_id,@@ -203,6 +206,51 @@ class TestInboundEventProcessing(BaseTest):second.event.refresh_from_db()assert second.event.status == ConversationInboundEvent.Status.PROCESSED+ def test_renew_inbound_lease_extends_expiry(self) -> None:+ with time_machine.travel("2026-09-11 12:00:00", tick=False):+ row = self._create_pending()+ claim = claim_inbound_event(str(row.id))+ assert claim is not None+ fencing_token = claim.event.fencing_token+ with time_machine.travel("2026-09-11 12:10:00", tick=False):+ assert renew_inbound_lease(claim) is True+ claim.event.refresh_from_db()+ assert claim.event.lease_expires_at == timezone.now() + timedelta(seconds=INBOUND_LEASE_SECONDS)+ assert claim.event.fencing_token == fencing_token+ assert claim.event.status == ConversationInboundEvent.Status.PROCESSING++ def test_renew_inbound_lease_rejected_after_reclaim(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+ second_expiry = second.event.lease_expires_at++ assert renew_inbound_lease(first) is False+ second.event.refresh_from_db()+ assert second.event.lease_expires_at == second_expiry+ assert second.event.fencing_token != first.event.fencing_token+ assert complete_inbound_event(first) is False+ assert complete_inbound_event(second) is True++ @patch("products.conversations.backend.tasks.slack._handle_supporthog_event")+ def test_receipt_handler_runs_inside_claim_scope(self, mock_handle: MagicMock) -> None:+ row = self._create_pending()+ seen: list = []++ def capture(*_args: object, **_kwargs: object) -> None:+ seen.append(get_current_inbound_claim())++ mock_handle.side_effect = capture+ process_supporthog_event_receipt(inbound_event_id=str(row.id))+ assert seen[0] is not None+ assert seen[0].event.id == row.id+def test_complete_after_scheduled_retry_is_ignored(self) -> None:row = self._create_pending()claim = claim_inbound_event(str(row.id))