:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(conversations): add durable inbound event receipts (#97306)
Alex V526809c3a4e6
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex d6493d7b76ce..78d1994043ab 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -115,6 +115,7 @@ rules:|ContentAutopilotRun|ContentAutopilotSiteProfile|Conversation+ |ConversationInboundEvent|ConversationRestoreToken|CoreMemory|CustomerJourney@@ -521,6 +522,7 @@ rules:|ContentAutopilotRun|ContentAutopilotSiteProfile|Conversation+ |ConversationInboundEvent|ConversationRestoreToken|CoreMemory|CustomerJourneydiff --git a/docs/internal/conversations-reliability.md b/docs/internal/conversations-reliability.mdnew file mode 100644index 000000000000..530368aec86c--- /dev/null+++ b/docs/internal/conversations-reliability.md@@ -0,0 +1,72 @@+# Conversations delivery reliability++How Conversations stores inbound callbacks and outbound delivery state.+This is the control-plane contract for Slack, email, and the widget.+It is not a product-facing runbook.++## Boundaries++**PostgreSQL is authoritative.**+Accepted inbound work, idempotency keys, leases, retry schedules, provider correlation, delivery state, and manual redrive live in Postgres.+A 2xx to Slack (or a returned widget message id) means a Postgres row committed, not that a Celery task ran.++**Redis is optional.**+It may be a fast-path lock or cache.+Losing Redis must not lose work or permanently suppress a callback.++**Celery is a wake-up hint.**+`on_commit` dispatch is the low-latency path.+A periodic Postgres sweeper is the durability backstop when the broker drops the hint.++**ClickHouse is derived history only.**+It never controls acknowledgement, retries, or delivery state.+Live operations use Postgres and Prometheus.+ClickHouse may receive sanitized batch-level lifecycle metrics, not payloads, leases, or provider secrets.++**Kafka / WarpStream is not in this design yet.**+Do not dual-write Postgres and Kafka in one request.+Revisit only when a region sustains the triggers in the program plan: claim-query p95 above one second after doubling workers, ingress above a few hundred durable rows per second that consumes material primary write capacity, a second consumer that needs ordered replay past Postgres retention, or the need to ack Slack while the owning Postgres region is down.+Until then, scale indexed sweepers.+If Kafka is added later, it is a wake-up relay from the Postgres outbox, not a second source of truth.+Widget writes stay synchronous in Postgres because the API must return ticket and message ids.++## Inbound receipts (`ConversationInboundEvent`)++One row per accepted provider callback, keyed by `(team, source, source_id)`.+`team` is the canonical root team used for scoping and deduplication.+Required `provider_account_id` preserves the Slack workspace or other provider account so workers can resolve the environment-owned configuration after payload cleanup.++- Slack Events API uses Slack `event_id`.+- Slack interactivity uses `trigger_id` plus action/container identity (signed-body hash as fallback).+- Mailgun delivery callbacks can reuse this table later, with Mailgun's event id as `source_id`.++The row holds bounded Slack JSON (`payload`, max 256 KiB), the latest provider retry metadata, lease and fencing fields, attempt count, due time, bounded error fields, and optional ticket/comment UUIDs.+Those UUIDs are not foreign keys: they must not take locks on `posthog_comment` or `posthog_conversations_ticket`.++Retention:++- If a callback exceeds the payload limit, ingress persists the receipt without `payload`, records `payload_too_large`, and acknowledges it. Ingress must catch `InboundPayloadTooLargeError` to distinguish this case from an unexpected failure.+- After a row is terminal, null `payload` after 24 hours.+- Keep the compact `(team, source, source_id)` tombstone for 30 days so provider retries stay idempotent.+- Attachment bytes stay in existing uploaded-media / object-storage paths. They do not enter this table.++The table is fail-closed (`TeamScopedRootMixin`).+Cross-team sweepers must use `objects.unscoped()`.+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.++## Outbound email (already in Postgres)++`EmailOutboxMessage` remains the outbound email outbox.+Do not rename or replace it.+Uncertain Mailgun sends and delivery-event correlation are additive columns on that table, not a new store.++## What must not happen++- Acknowledging Slack before the owning-region Postgres commit.+- Treating a Redis SET as the dedupe record.+- Retrying an already-accepted Slack body because an image upload failed (that is a delivery-part problem, not an ingress-row problem).+- Emitting raw Slack JSON or email bodies to ClickHouse.diff --git a/products/conversations/backend/migrations/0067_conversationinboundevent.py b/products/conversations/backend/migrations/0067_conversationinboundevent.pynew file mode 100644index 000000000000..f1997e14216f--- /dev/null+++ b/products/conversations/backend/migrations/0067_conversationinboundevent.py@@ -0,0 +1,136 @@+# Generated by Django 5.2.17 on 2026-09-09 10:36++import django.utils.timezone+import django.db.models.lookups+import django.db.models.deletion+import django.db.models.functions.comparison+from django.db import migrations, models++import posthog.uuidt++import products.conversations.backend.models.inbound_event+++class Migration(migrations.Migration):+ dependencies = [+ ("conversations", "0066_squash_2026_09_07_schema_addons"),+ ("posthog", "1346_untrack_organization_is_hipaa"),+ ]++ operations = [+ migrations.CreateModel(+ name="ConversationInboundEvent",+ fields=[+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ (+ "source",+ models.CharField(+ choices=products.conversations.backend.models.inbound_event.conversation_inbound_event_source_choices,+ max_length=32,+ ),+ ),+ ("source_id", models.CharField(max_length=512)),+ ("provider_account_id", models.CharField(max_length=255)),+ ("provider_retry_num", models.PositiveIntegerField(blank=True, null=True)),+ ("provider_retry_reason", models.CharField(blank=True, default="", max_length=64)),+ (+ "status",+ models.CharField(+ choices=[+ ("pending", "Pending"),+ ("processing", "Processing"),+ ("processed", "Processed"),+ ("failed", "Failed"),+ ],+ default="pending",+ max_length=32,+ ),+ ),+ ("attempts", models.PositiveIntegerField(default=0)),+ ("due_at", models.DateTimeField(default=django.utils.timezone.now)),+ ("lease_expires_at", models.DateTimeField(blank=True, null=True)),+ ("fencing_token", models.PositiveBigIntegerField(default=0)),+ ("last_error_code", models.CharField(blank=True, default="", max_length=64)),+ ("last_error", models.CharField(blank=True, default="", max_length=1024)),+ ("ticket_id", models.UUIDField(blank=True, null=True)),+ ("comment_id", models.UUIDField(blank=True, null=True)),+ ("payload", models.JSONField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ("terminal_at", models.DateTimeField(blank=True, null=True)),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ db_index=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "posthog_conversations_inbound_event",+ "indexes": [+ models.Index(+ condition=models.Q(("status", "pending")), fields=["due_at"], name="conv_inbound_pending_idx"+ ),+ models.Index(+ condition=models.Q(("status", "processing")),+ fields=["lease_expires_at"],+ name="conv_inbound_lease_idx",+ ),+ models.Index(+ condition=models.Q(("status__in", ["processed", "failed"])),+ fields=["terminal_at"],+ name="conv_inbound_terminal_idx",+ ),+ models.Index(+ condition=models.Q(("payload__isnull", False), ("status__in", ["processed", "failed"])),+ fields=["terminal_at"],+ name="conv_inbound_payload_gc_idx",+ ),+ ],+ "constraints": [+ models.UniqueConstraint(+ fields=("team", "source", "source_id"), name="unique_inbound_event_per_source"+ ),+ models.CheckConstraint(+ condition=models.Q(("source_id", ""), _negated=True), name="inbound_event_source_id_not_empty"+ ),+ models.CheckConstraint(+ condition=models.Q(("provider_account_id", ""), _negated=True),+ name="inbound_event_provider_id_not_empty",+ ),+ models.CheckConstraint(+ condition=models.Q(+ ("payload__isnull", True),+ django.db.models.lookups.LessThanOrEqual(+ models.Func(+ django.db.models.functions.comparison.Cast(+ models.F("payload"), output_field=models.TextField()+ ),+ function="octet_length",+ output_field=models.IntegerField(),+ ),+ models.Value(262144),+ ),+ _connector="OR",+ ),+ name="inbound_event_payload_size",+ ),+ models.CheckConstraint(+ condition=models.Q(+ models.Q(("status__in", ["processed", "failed"]), ("terminal_at__isnull", False)),+ models.Q(("status__in", ["pending", "processing"]), ("terminal_at__isnull", True)),+ _connector="OR",+ ),+ name="inbound_event_terminal_at",+ ),+ ],+ },+ ),+ ]diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txtindex 90e3a4c39792..ef37a6fc064c 100644--- a/products/conversations/backend/migrations/max_migration.txt+++ b/products/conversations/backend/migrations/max_migration.txt@@ -1 +1 @@-0066_squash_2026_09_07_schema_addons+0067_conversationinboundeventdiff --git a/products/conversations/backend/models/__init__.py b/products/conversations/backend/models/__init__.pyindex dc2ad77f8e4b..a54df0ce0347 100644--- a/products/conversations/backend/models/__init__.py+++ b/products/conversations/backend/models/__init__.py@@ -14,6 +14,7 @@ from .email_thread import (EmailThreadParticipantKind,)from .github_comment_mapping import GithubCommentMapping+from .inbound_event import ConversationInboundEvent, ConversationInboundEventSource, InboundPayloadTooLargeErrorfrom .restore_token import ConversationRestoreTokenfrom .signing_secret import SigningSecretfrom .team_conversations_email_config import EmailChannel, EmailChannelConnectionStatus, EmailChannelKind@@ -28,6 +29,8 @@ from .zendesk_import_job import ZendeskImportJob__all__ = ["Channel","ChannelDetail",+ "ConversationInboundEvent",+ "ConversationInboundEventSource","ConversationRestoreToken","EmailChannel","EmailChannelConnectionStatus",@@ -45,6 +48,7 @@ __all__ = ["EmailThreadParticipant","EmailThreadParticipantKind","GithubCommentMapping",+ "InboundPayloadTooLargeError","Priority","RuleType","SigningSecret",diff --git a/products/conversations/backend/models/inbound_event.py b/products/conversations/backend/models/inbound_event.pynew file mode 100644index 000000000000..e89b664626e7--- /dev/null+++ b/products/conversations/backend/models/inbound_event.py@@ -0,0 +1,183 @@+from __future__ import annotations++import json+from datetime import timedelta+from typing import Any++from django.db import models+from django.db.models.functions import Cast+from django.db.models.lookups import LessThanOrEqual+from django.utils import timezone+from django.utils.functional import Promise++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel++INBOUND_PAYLOAD_MAX_BYTES = 256 * 1024+INBOUND_ERROR_MAX_LENGTH = 1024+# Terminal rows drop payload after this interval and remain as compact dedupe keys.+INBOUND_PAYLOAD_TTL = timedelta(hours=24)+INBOUND_TOMBSTONE_TTL = timedelta(days=30)+++class InboundPayloadTooLargeError(ValueError):+ def __init__(self, payload_bytes: int) -> None:+ self.payload_bytes = payload_bytes+ super().__init__(+ f"Inbound event payload is {payload_bytes} bytes; max is {INBOUND_PAYLOAD_MAX_BYTES}",+ )+++class ConversationInboundEventSource(models.TextChoices):+ SLACK_EVENTS = "slack_events", "Slack Events API"+ SLACK_INTERACTIVITY = "slack_interactivity", "Slack interactivity"+++def conversation_inbound_event_source_choices() -> list[tuple[str, str | Promise]]:+ return list(ConversationInboundEventSource.choices)+++def reject_oversized_inbound_payload(payload: object | None) -> None:+ if payload is None:+ return+ encoded = json.dumps(payload, ensure_ascii=False).encode("utf-8")+ if len(encoded) > INBOUND_PAYLOAD_MAX_BYTES:+ raise InboundPayloadTooLargeError(len(encoded))+++class ConversationInboundEvent(TeamScopedRootMixin, UUIDModel):+ """Durable receipt for an accepted inbound provider callback.++ PostgreSQL is the acknowledgement and retry control plane. ClickHouse is not.+ ``team`` is the canonical root team used for scoping and deduplication.+ ``provider_account_id`` preserves the provider workspace or account identity.+ Sweepers and other work outside a request must use ``objects.unscoped()`` or+ ``objects.for_team(...)``; bare ``objects.all()`` raises ``TeamScopeError``.+ Database constraints keep payload and terminal timestamps valid on bulk writes.+ """++ class Status(models.TextChoices):+ PENDING = "pending", "Pending"+ PROCESSING = "processing", "Processing"+ PROCESSED = "processed", "Processed"+ FAILED = "failed", "Failed"++ TERMINAL_STATUSES = (Status.PROCESSED, Status.FAILED)++ # db_constraint=False: a real FK constraint would take SHARE ROW EXCLUSIVE on the+ # hot posthog_team table on CreateModel. App-level enforcement is enough here.+ team = models.ForeignKey(+ "posthog.Team",+ on_delete=models.CASCADE,+ db_constraint=False,+ db_index=False,+ related_name="+",+ )+ source = models.CharField(max_length=32, choices=conversation_inbound_event_source_choices)+ source_id = models.CharField(max_length=512)+ provider_account_id = models.CharField(max_length=255)+ provider_retry_num = models.PositiveIntegerField(null=True, blank=True)+ provider_retry_reason = models.CharField(max_length=64, blank=True, default="")+ status = models.CharField(max_length=32, choices=Status, default=Status.PENDING)+ attempts = models.PositiveIntegerField(default=0)+ due_at = models.DateTimeField(default=timezone.now)+ lease_expires_at = models.DateTimeField(null=True, blank=True)+ fencing_token = models.PositiveBigIntegerField(default=0)+ last_error_code = models.CharField(max_length=64, blank=True, default="")+ last_error = models.CharField(max_length=INBOUND_ERROR_MAX_LENGTH, blank=True, default="")+ ticket_id = models.UUIDField(null=True, blank=True)+ comment_id = models.UUIDField(null=True, blank=True)+ payload = models.JSONField(null=True, blank=True)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)+ terminal_at = models.DateTimeField(null=True, blank=True)++ class Meta:+ db_table = "posthog_conversations_inbound_event"+ constraints = [+ models.UniqueConstraint(+ fields=["team", "source", "source_id"],+ name="unique_inbound_event_per_source",+ ),+ models.CheckConstraint(+ condition=~models.Q(source_id=""),+ name="inbound_event_source_id_not_empty",+ ),+ models.CheckConstraint(+ condition=~models.Q(provider_account_id=""),+ name="inbound_event_provider_id_not_empty",+ ),+ models.CheckConstraint(+ condition=models.Q(payload__isnull=True)+ | models.Q(+ LessThanOrEqual(+ models.Func(+ Cast(models.F("payload"), output_field=models.TextField()),+ function="octet_length",+ output_field=models.IntegerField(),+ ),+ models.Value(INBOUND_PAYLOAD_MAX_BYTES),+ ),+ ),+ name="inbound_event_payload_size",+ ),+ models.CheckConstraint(+ condition=models.Q(+ status__in=["processed", "failed"],+ terminal_at__isnull=False,+ )+ | models.Q(+ status__in=["pending", "processing"],+ terminal_at__isnull=True,+ ),+ name="inbound_event_terminal_at",+ ),+ ]+ indexes = [+ models.Index(+ fields=["due_at"],+ name="conv_inbound_pending_idx",+ condition=models.Q(status="pending"),+ ),+ models.Index(+ fields=["lease_expires_at"],+ name="conv_inbound_lease_idx",+ condition=models.Q(status="processing"),+ ),+ models.Index(+ fields=["terminal_at"],+ name="conv_inbound_terminal_idx",+ condition=models.Q(status__in=["processed", "failed"]),+ ),+ models.Index(+ fields=["terminal_at"],+ name="conv_inbound_payload_gc_idx",+ condition=models.Q(+ status__in=["processed", "failed"],+ payload__isnull=False,+ ),+ ),+ ]++ def save(self, *args: Any, **kwargs: Any) -> None:+ update_fields = kwargs.get("update_fields")+ if update_fields is not None:+ update_fields = {*update_fields, "updated_at"}+ kwargs["update_fields"] = update_fields+ terminal_at_changed = False+ if self.status in self.TERMINAL_STATUSES and self.terminal_at is None:+ self.terminal_at = timezone.now()+ terminal_at_changed = True+ elif self.status not in self.TERMINAL_STATUSES and self.terminal_at is not None:+ self.terminal_at = None+ terminal_at_changed = True+ if terminal_at_changed and update_fields is not None:+ kwargs["update_fields"] = {*update_fields, "terminal_at"}+ if self.last_error:+ self.last_error = self.last_error[:INBOUND_ERROR_MAX_LENGTH]+ if update_fields is None or "payload" in update_fields:+ reject_oversized_inbound_payload(self.payload)+ super().save(*args, **kwargs)++ def __str__(self) -> str:+ return f"ConversationInboundEvent({self.source}:{self.source_id} status={self.status})"diff --git a/products/conversations/backend/tests/test_inbound_event.py b/products/conversations/backend/tests/test_inbound_event.pynew file mode 100644index 000000000000..cc133ae1728f--- /dev/null+++ b/products/conversations/backend/tests/test_inbound_event.py@@ -0,0 +1,141 @@+from datetime import datetime++from posthog.test.base import BaseTest++from django.db import IntegrityError, transaction++from parameterized import parameterized++from posthog.models.scoping.manager import TeamScopeError+from posthog.models.team import Team++from products.conversations.backend.models import (+ ConversationInboundEvent,+ ConversationInboundEventSource,+ InboundPayloadTooLargeError,+)+from products.conversations.backend.models.inbound_event import INBOUND_ERROR_MAX_LENGTH, INBOUND_PAYLOAD_MAX_BYTES+++class TestConversationInboundEvent(BaseTest):+ def _create(+ self,+ *,+ team: Team | None = None,+ source: str = ConversationInboundEventSource.SLACK_EVENTS,+ source_id: str = "Ev00000001",+ provider_account_id: str = "T00000001",+ status: str = ConversationInboundEvent.Status.PENDING,+ payload: dict[str, str] | None = None,+ last_error: str = "",+ terminal_at: datetime | None = None,+ ) -> ConversationInboundEvent:+ team = team or self.team+ return ConversationInboundEvent.objects.for_team(team.id).create(+ team=team,+ source=source,+ source_id=source_id,+ provider_account_id=provider_account_id,+ status=status,+ payload=payload,+ last_error=last_error,+ terminal_at=terminal_at,+ )++ def test_queryset_without_team_context_raises(self) -> None:+ # Bare objects.all() must not return every team's receipts.+ self._create()+ with self.assertRaises(TeamScopeError):+ list(ConversationInboundEvent.objects.all())++ def test_for_team_excludes_other_teams_rows(self) -> None:+ other_team = Team.objects.create_with_data(organization=self.organization, initiating_user=self.user)+ mine = self._create(source_id="Ev-mine")+ self._create(team=other_team, source_id="Ev-other")++ results = list(ConversationInboundEvent.objects.for_team(self.team.id))+ self.assertEqual(results, [mine])++ def test_duplicate_source_id_for_same_team_and_source_rejected(self) -> None:+ # Slack retries reuse event_id; without this unique key they would double-process.+ self._create()+ with self.assertRaises(IntegrityError), transaction.atomic():+ self._create()++ def test_child_environment_keeps_provider_identity_under_canonical_team(self) -> None:+ child_team = Team.objects.create(+ organization=self.organization,+ project=self.project,+ parent_team=self.team,+ name="Child environment",+ )+ row = self._create(team=child_team, provider_account_id="T-child")++ self.assertEqual(row.team_id, self.team.id)+ self.assertEqual(row.provider_account_id, "T-child")+ with self.assertRaises(IntegrityError), transaction.atomic():+ self._create(source_id=row.source_id)++ def test_empty_source_id_rejected(self) -> None:+ with self.assertRaises(IntegrityError), transaction.atomic():+ self._create(source_id="")++ def test_empty_provider_account_id_rejected(self) -> None:+ with self.assertRaises(IntegrityError), transaction.atomic():+ self._create(provider_account_id="")++ @parameterized.expand(+ [+ ("other_team", True, ConversationInboundEventSource.SLACK_EVENTS),+ ("other_source", False, ConversationInboundEventSource.SLACK_INTERACTIVITY),+ ]+ )+ def test_source_id_can_repeat_across_teams_or_sources(self, _name: str, other_team: bool, source: str) -> None:+ first = self._create()+ team = (+ Team.objects.create_with_data(organization=self.organization, initiating_user=self.user)+ if other_team+ else self.team+ )+ second = self._create(team=team, source=source)+ self.assertNotEqual(first.id, second.id)+ self.assertEqual(+ ConversationInboundEvent.objects.unscoped().filter(source_id=first.source_id).count(),+ 2,+ )++ def test_oversized_payload_rejected_on_save(self) -> None:+ payload = {"text": "x" * (INBOUND_PAYLOAD_MAX_BYTES + 1)}+ with self.assertRaises(InboundPayloadTooLargeError):+ self._create(payload=payload)+ self.assertFalse(ConversationInboundEvent.objects.for_team(self.team.id).exists())++ def test_oversized_payload_rejected_on_queryset_update(self) -> None:+ row = self._create(payload={"text": "small"})+ payload = {"text": "x" * (INBOUND_PAYLOAD_MAX_BYTES + 1)}++ with self.assertRaises(IntegrityError), transaction.atomic():+ ConversationInboundEvent.objects.for_team(self.team.id).filter(id=row.id).update(payload=payload)++ def test_last_error_is_truncated_on_save(self) -> None:+ row = self._create(last_error="e" * (INBOUND_ERROR_MAX_LENGTH + 50))+ row.refresh_from_db()+ self.assertEqual(len(row.last_error), INBOUND_ERROR_MAX_LENGTH)++ def test_save_sets_terminal_timestamp(self) -> None:+ row = self._create(status=ConversationInboundEvent.Status.PROCESSED)+ self.assertIsNotNone(row.terminal_at)++ def test_queryset_update_requires_terminal_timestamp(self) -> None:+ row = self._create()+ with self.assertRaises(IntegrityError), transaction.atomic():+ ConversationInboundEvent.objects.for_team(self.team.id).filter(id=row.id).update(+ status=ConversationInboundEvent.Status.FAILED+ )++ def test_queryset_update_requires_clearing_terminal_timestamp_on_redrive(self) -> None:+ row = self._create(status=ConversationInboundEvent.Status.FAILED)+ with self.assertRaises(IntegrityError), transaction.atomic():+ ConversationInboundEvent.objects.for_team(self.team.id).filter(id=row.id).update(+ status=ConversationInboundEvent.Status.PENDING+ )