: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
chore(user_interviews): register the Vapi transcript task before it is published (#102766)
Julian Bez85cb0c59950d
diff --git a/products/user_interviews/backend/tasks/__init__.py b/products/user_interviews/backend/tasks/__init__.pynew file mode 100644index 000000000000..3375607ab701--- /dev/null+++ b/products/user_interviews/backend/tasks/__init__.py@@ -0,0 +1,2 @@+# Re-exported so Celery autodiscovery registers the task when it imports `<app>.tasks`.+from products.user_interviews.backend.tasks.tasks import handle_vapi_webhook # noqa: F401diff --git a/products/user_interviews/backend/tasks/tasks.py b/products/user_interviews/backend/tasks/tasks.pynew file mode 100644index 000000000000..f4b48be2b610--- /dev/null+++ b/products/user_interviews/backend/tasks/tasks.py@@ -0,0 +1,89 @@+"""Celery tasks for user_interviews.++``handle_vapi_webhook`` is the durable side of the inbound Vapi webhook. Ingress answers the+request with a transport receipt that never reflects consumer work, so Vapi does not resend+when persistence fails. The retry therefore has to live in something that outlives the request.+"""++from typing import Any++from django.db import InterfaceError, OperationalError++import structlog+from celery import Task, shared_task++logger = structlog.get_logger(__name__)+++def _call_id(payload: dict[str, Any]) -> str | None:+ call: dict[str, Any] = (payload.get("message") or {}).get("call") or {}+ return call.get("id")+++@shared_task(+ bind=True,+ name="products.user_interviews.backend.tasks.handle_vapi_webhook",+ ignore_result=True,+ # autoretry_for is load-bearing: bare max_retries without it is silently inert.+ autoretry_for=(OperationalError, InterfaceError),+ # Sized for a database outage, which lasts minutes to hours, while the default backoff is+ # spent in a few seconds. Vapi holds its receipt by the time the task runs and nothing else+ # replays an interview, so every attempt this policy does not make is a report lost. Each+ # attempt waits twice as long as the one before it, capped at ten minutes, which spans about+ # two and a half hours over all the attempts. Jitter spreads the workers that failed at the+ # same moment, and halves that span on average.+ retry_backoff=10,+ retry_backoff_max=600,+ retry_jitter=True,+ max_retries=20,+ # The report is the only copy of the interview, and by the time the task runs Vapi already+ # holds its receipt. A worker that dies after reserving the message would drop the report with+ # the default early acknowledgement, so the message is acknowledged after the run instead and+ # given back to the broker when the worker is lost. The handler is idempotent on the call id,+ # so the redelivered message creates nothing a second time.+ acks_late=True,+ reject_on_worker_lost=True,+)+def handle_vapi_webhook(+ self: Task,+ payload: dict[str, Any],+ event_type: str,+ team_id: int,+ topic_id: str,+ interviewee_context_id: str,+ interviewee_identifier: str,+ received_at: str | None = None,+) -> None:+ """Store one verified Vapi delivery, outside the request that accepted it.++ ``received_at`` is the ISO time the endpoint received the delivery, and it timestamps the+ lifecycle analytics events. It has a default so that a message queued without it still runs;+ those events then carry the worker's clock instead.+ """+ from products.user_interviews.backend import ( # noqa: PLC0415 - keeps posthog.schema and the embedding worker off the task module's import path+ vapi_events,+ )++ try:+ vapi_events.handle_vapi_webhook_delivery(+ payload,+ event_type,+ team_id=team_id,+ topic_id=topic_id,+ interviewee_context_id=interviewee_context_id,+ interviewee_identifier=interviewee_identifier,+ received_at=received_at,+ )+ except (OperationalError, InterfaceError):+ # autoretry_for re-raises the original error once the retries run out, which reads like any+ # other failed attempt. The last attempt says that the report is now lost, and names the+ # call so the interview can be traced in Vapi.+ if self.request.retries >= self.max_retries:+ logger.exception(+ "user_interviews_vapi_webhook_retries_exhausted",+ event_type=event_type,+ call_id=_call_id(payload),+ team_id=team_id,+ topic_id=topic_id,+ )+ raisediff --git a/products/user_interviews/backend/test_vapi_task.py b/products/user_interviews/backend/test_vapi_task.pynew file mode 100644index 000000000000..a32f3927c9ac--- /dev/null+++ b/products/user_interviews/backend/test_vapi_task.py@@ -0,0 +1,117 @@+from typing import Any++from posthog.test.base import APIBaseTest++from django.db import InterfaceError, OperationalError, connection+from django.test.utils import CaptureQueriesContext++from parameterized import parameterized++from posthog.celery import app as celery_app++from products.user_interviews.backend.models import IntervieweeContext, UserInterview, UserInterviewTopic+from products.user_interviews.backend.tasks.tasks import handle_vapi_webhook++TASK_NAME = "products.user_interviews.backend.tasks.handle_vapi_webhook"+++class TestVapiWebhookTask(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.topic = UserInterviewTopic.objects.create(+ team=self.team,+ created_by=self.user,+ interviewee_emails=["[email protected]"],+ topic="Replay adoption",+ agent_context="ctx",+ questions=[],+ )+ self.interviewee_context = IntervieweeContext.objects.create(+ team=self.team,+ topic=self.topic,+ interviewee_identifier="[email protected]",+ agent_context="",+ created_by=self.user,+ )++ def _report(self, call_id: str = "call_abc") -> dict[str, Any]:+ return {+ "message": {+ "type": "end-of-call-report",+ "call": {"id": call_id, "duration": 120},+ "transcript": "Hi! ...",+ "summary": "User talked about replay.",+ "recording": {"url": "https://vapi.example/recording.mp3"},+ }+ }++ def _run(self, payload: dict[str, Any]) -> None:+ handle_vapi_webhook(+ payload=payload,+ event_type="end-of-call-report",+ team_id=self.team.pk,+ topic_id=str(self.topic.pk),+ interviewee_context_id=str(self.interviewee_context.pk),+ interviewee_identifier="[email protected]",+ received_at="2026-05-14T12:00:00+00:00",+ )++ def test_task_is_registered_under_the_name_a_publisher_sends(self):+ # The name is the contract between the web pod that publishes and the worker that runs the+ # task. A worker that does not know the name drops the message, and Vapi never resends.+ self.assertIn(TASK_NAME, celery_app.tasks)++ def test_task_survives_a_database_error_and_a_lost_worker(self):+ # Both settings are silently inert when missing: max_retries without autoretry_for never+ # retries, and the default early acknowledgement drops the report when the worker dies.+ self.assertEqual(handle_vapi_webhook.autoretry_for, (OperationalError, InterfaceError))+ self.assertTrue(handle_vapi_webhook.acks_late)+ self.assertTrue(handle_vapi_webhook.reject_on_worker_lost)+ # The default backoff spends every attempt within seconds, which is shorter than any+ # database outage worth retrying through, and Vapi never resends the report.+ window_seconds = sum(+ min(handle_vapi_webhook.retry_backoff * 2**attempt, handle_vapi_webhook.retry_backoff_max)+ for attempt in range(handle_vapi_webhook.max_retries)+ )+ self.assertGreater(window_seconds, 60 * 60)++ @parameterized.expand([("null_message", {"message": None}), ("null_call", {"message": {"call": None}})])+ def test_task_survives_a_null_message_or_call(self, _name: str, payload: dict[str, Any]) -> None:+ # A JSON null where the message or call object goes must not raise: an AttributeError is+ # outside the task's retry list. Without a call id there is no idempotency either, so the+ # report must not become a blank interview on every redelivery.+ self._run(payload)++ self.assertFalse(UserInterview.objects.filter(team=self.team).exists())++ def test_task_stores_the_report(self):+ self._run(self._report())++ interview = UserInterview.objects.get(team=self.team)+ self.assertEqual(interview.topic, self.topic)+ self.assertEqual(interview.interviewee_identifier, "[email protected]")+ self.assertEqual(interview.transcript, "Hi! ...")+ self.assertEqual(interview.recording_url, "https://vapi.example/recording.mp3")++ def test_task_serializes_persistence_per_call_id(self):+ # No unique constraint keeps a call to one row, so two runs that overlap have to queue+ # behind an advisory lock on the call id instead of both passing the existence check.+ with CaptureQueriesContext(connection) as queries:+ self._run(self._report(call_id="call_xyz"))++ statements = [query["sql"] for query in queries.captured_queries]+ locks = [index for index, sql in enumerate(statements) if "pg_advisory_xact_lock" in sql]+ inserts = [index for index, sql in enumerate(statements) if "INSERT INTO" in sql and "userinterview" in sql]+ self.assertEqual(len(locks), 1)+ self.assertIn(f"user_interviews_vapi_call:{self.team.id}:call_xyz", statements[locks[0]])+ self.assertTrue(inserts)+ self.assertLess(locks[0], inserts[0])++ def test_a_second_run_of_the_same_call_stores_nothing(self):+ # The task acknowledges late and retries a transient database error, so one call can+ # reach two runs.+ payload = self._report()+ self._run(payload)+ self._run(payload)++ self.assertEqual(UserInterview.objects.filter(team=self.team).count(), 1)diff --git a/products/user_interviews/backend/vapi_events.py b/products/user_interviews/backend/vapi_events.pyindex c4781b253627..447eee6b688e 100644--- a/products/user_interviews/backend/vapi_events.py+++ b/products/user_interviews/backend/vapi_events.py@@ -3,10 +3,17 @@The endpoint in ``presentation/webhooks.py`` calls in here once a delivery is verified. Thepersistence side of the webhook lives beside ``logic.py`` rather than in the view file, so theview holds the HTTP surfaces and this module holds what the product does with a call.++``handle_vapi_webhook_delivery`` is the same work off the request path: it takes the ids a caller+already resolved instead of a share row, and persists a UserInterview attributed to the topic+creator, idempotent on ``call.id``."""+from collections.abc import Callable, Mappingfrom typing import Any+from django.db import connection, transaction+import structlogimport posthoganalytics@@ -16,8 +23,18 @@ from posthog.api.embedding_worker import emit_embedding_requestfrom posthog.event_usage import groupsfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.team import Team+from posthog.ph_client import ph_scoped_capturefrom products.user_interviews.backend.classification import derive_auto_classifications+from products.user_interviews.backend.logic import (+ RESPONDENT_KEY_MAX_CHARS,+ RESPONDENT_NAME_MAX_CHARS,+ clean_field,+ is_shared_interviewee_context,+ shared_interviewee_identifier,+ valid_distinct_id,+ valid_session_id,+)from products.user_interviews.backend.models import UserInterview, UserInterviewClassification, UserInterviewTopiclogger = structlog.get_logger(__name__)@@ -114,13 +131,17 @@ def collapse_abandoned_partials(*, team: Team, topic: UserInterviewTopic, respon)-def capture_user_interview_event(+def _capture_interview_event(event: str,*,- sharing_config: SharingConfiguration,+ capture: Callable[..., Any],+ team: Team,+ topic_id: str,+ interviewee_context_id: str,call_id: str | None,- session_id: str = "",- extra_properties: dict[str, Any] | None = None,+ timestamp: str | None,+ session_id: str,+ extra_properties: dict[str, Any] | None,) -> None:"""Fire a PostHog event for a user-interview lifecycle moment (conversation started/ended).Failures never propagate — analytics never blocks a webhook delivery.@@ -138,12 +159,9 @@ def capture_user_interview_event(email/distinct_id — so these feature-usage events never create person profiles for thethird-party interviewees themselves. The events report on the user_interviews feature, notthe people being interviewed."""- interviewee_context = sharing_config.interviewee_context- if interviewee_context is None:- returnproperties: dict[str, Any] = {- "topic_id": str(interviewee_context.topic_id),- "team_id": sharing_config.team_id,+ "topic_id": topic_id,+ "team_id": team.id,"call_id": call_id,}if session_id:@@ -153,16 +171,269 @@ def capture_user_interview_event(if extra_properties:properties.update(extra_properties)try:- posthoganalytics.capture(- distinct_id=f"user_interview:{interviewee_context.id}",+ capture(+ distinct_id=f"user_interview:{interviewee_context_id}",event=event,properties=properties,- groups=groups(organization=sharing_config.team.organization, team=sharing_config.team),+ timestamp=timestamp,+ groups=groups(organization=team.organization, team=team),)except Exception:logger.exception("user_interviews_event_capture_failed",event=event,- team_id=sharing_config.team_id,+ team_id=team.id,+ call_id=call_id,+ )+++def capture_user_interview_event(+ event: str,+ *,+ sharing_config: SharingConfiguration,+ call_id: str | None,+ session_id: str = "",+ extra_properties: dict[str, Any] | None = None,+) -> None:+ """The lifecycle event from the request that the delivery arrived on."""+ interviewee_context = sharing_config.interviewee_context+ if interviewee_context is None:+ return+ _capture_interview_event(+ event,+ capture=posthoganalytics.capture,+ team=sharing_config.team,+ topic_id=str(interviewee_context.topic_id),+ interviewee_context_id=str(interviewee_context.id),+ call_id=call_id,+ timestamp=None,+ session_id=session_id,+ extra_properties=extra_properties,+ )+++def _lock_call(team_id: int, call_id: str) -> None:+ """Hold the sole right to store this call's report until the transaction ends.++ Nothing in the schema stops a second row for one call. Vapi resends a report whose receipt it+ lost, the endpoint asks for a resend when the enqueue fails, and the task is acknowledged after+ the run, so two runs for one call can be in flight together. Without this lock both pass the+ existence check and both insert, which gives the topic two interviews for one call and emits+ the embeddings twice. The run that loses waits here until the winner commits, and its next read+ then sees the row.+ """+ with connection.cursor() as cursor:+ cursor.execute(+ "SELECT pg_advisory_xact_lock(hashtext(%s))",+ [f"user_interviews_vapi_call:{team_id}:{call_id}"],+ )+++def _scoped_capture(**kwargs: Any) -> None:+ """Capture through a client that flushes before the caller moves on.++ The global client's background flush may never run before a Celery worker exits, so the event+ is lost without a word. A run emits at most one event, so the client is opened once.+ """+ with ph_scoped_capture() as capture:+ capture(**kwargs)+++def _capture_user_interview_event(+ event: str,+ *,+ team: Team,+ topic_id: str,+ interviewee_context_id: str,+ call_id: str | None,+ received_at: str | None,+ session_id: str = "",+ extra_properties: dict[str, Any] | None = None,+) -> None:+ """The lifecycle event from the worker that runs after the request.++ The event carries the moment the endpoint received the delivery, not the moment this ran. The+ worker runs after the request, and later again on a retry, so the run time would put+ "conversation started" after "conversation ended" for the same call.+ """+ _capture_interview_event(+ event,+ capture=_scoped_capture,+ team=team,+ topic_id=topic_id,+ interviewee_context_id=interviewee_context_id,+ call_id=call_id,+ timestamp=received_at,+ session_id=session_id,+ extra_properties=extra_properties,+ )+++def handle_vapi_webhook_delivery(+ payload: Mapping[str, Any],+ event_type: str,+ *,+ team_id: int,+ topic_id: str,+ interviewee_context_id: str,+ interviewee_identifier: str,+ received_at: str | None,+) -> None:+ """Act on one verified Vapi delivery: the lifecycle event, and the end-of-call report.++ The share is not read here. ``accept_vapi_event`` resolved the token in the request, before+ the endpoint accepted the delivery, and took out of the share everything this needs. The+ share row does not survive the wait: the team can disable it, its token can leave the+ rotation grace period, and ``cleanup_expired_sharing_configs`` then deletes the row itself.+ Each of those would turn an accepted report into nothing. The topic and the interviewee+ context the share names outlive it.++ Idempotent on ``call.id`` (stored in ``call_metadata.id``). Vapi repeats that id across the+ status update and the end-of-call report, so ingress cannot dedup on it and this does+ instead: a repeat delivery of a report already stored creates nothing. The idempotency also+ covers the Celery retry that persistence rides on, and an advisory lock holds it when two of+ those runs overlap.+ """+ message: dict[str, Any] = payload.get("message") or {}+ call: dict[str, Any] = message.get("call") or {}+ # Vapi can surface our `assistant_overrides.metadata` (set in `start_call`) in two+ # places on the Call object: `call.metadata` for some message types, and nested under+ # `call.assistantOverrides.metadata` on others. Empirically end-of-call-report comes+ # through with the nested form, so try both.+ overrides_metadata: dict[str, Any] = (call.get("assistantOverrides") or {}).get("metadata") or {}+ top_metadata: dict[str, Any] = call.get("metadata") or {}+ # Shared-link respondent fields (set in start_call's metadata, echoed back by Vapi). Merge with+ # top-level precedence, mirroring how the access token is resolved when the delivery arrives.+ merged_metadata: dict[str, Any] = {**overrides_metadata, **top_metadata}+ call_id = call.get("id")+ if event_type == "end-of-call-report" and not call_id:+ # The call id is what makes a report idempotent, so a report without one would create a+ # blank interview on every redelivery.+ logger.warning("user_interviews_vapi_webhook_missing_call_id", team_id=team_id, topic_id=topic_id)+ return++ topic = (+ UserInterviewTopic.objects.select_related("team", "team__organization", "created_by")+ .filter(team_id=team_id, id=topic_id)+ .first()+ )+ if topic is None:+ # The team deleted the topic while the report waited in the queue, so there is nothing+ # left to file the report under. Say so, because the alternative reads like a delivery+ # that never arrived.+ logger.warning(+ "user_interviews_vapi_webhook_topic_gone",+ team_id=team_id,+ topic_id=topic_id,call_id=call_id,)+ return++ if event_type == "status-update":+ # Lifecycle ping. We only act on `in-progress` (call started) — the `ended` status+ # is followed by a separate `end-of-call-report` with the full transcript, so we+ # capture the ended event from that branch where we already have the interview row.+ call_status = message.get("status")+ if call_status == "in-progress":+ _capture_user_interview_event(+ "user_interview_conversation_started",+ team=topic.team,+ topic_id=topic_id,+ interviewee_context_id=interviewee_context_id,+ call_id=call_id,+ received_at=received_at,+ session_id=valid_session_id(merged_metadata.get("session_id")),+ )+ logger.info(+ "user_interviews_vapi_webhook_status_update",+ call_status=call_status,+ call_id=call_id,+ )+ return++ # The consumer registers for status-update and end-of-call-report only, so the registry+ # drops every other message type before this runs and the rest is the end-of-call report.+ recording_url = (message.get("recording") or {}).get("url", "") or message.get("recordingUrl", "") or ""+ transcript = message.get("transcript", "") or ""+ classifications = derive_auto_classifications(transcript)++ if is_shared_interviewee_context(interviewee_identifier):+ respondent_name = clean_field(merged_metadata.get("respondent_name"), RESPONDENT_NAME_MAX_CHARS)+ respondent_key = clean_field(merged_metadata.get("respondent_key"), RESPONDENT_KEY_MAX_CHARS)+ # Recompute the identifier from respondent_key rather than trusting the echoed metadata, so it+ # is always a namespaced shared marker and can never be steered onto a targeted invitee.+ stored_identifier = shared_interviewee_identifier(respondent_key)+ interviewee_emails = []+ # Best-effort, untrusted person linkage. Re-validated here (defense in depth) and stored in its+ # own column — never as the interviewee_identifier, so it can't forge attribution.+ distinct_id = valid_distinct_id(merged_metadata.get("distinct_id"))+ # session_id isn't persisted — it rides on the lifecycle event below. Re-validated here+ # (defense in depth) so only a well-formed UUIDv7 reaches the event.+ session_id = valid_session_id(merged_metadata.get("session_id"))+ else:+ stored_identifier = interviewee_identifier+ interviewee_emails = [stored_identifier] if "@" in stored_identifier else []+ respondent_name = respondent_key = ""+ distinct_id = ""+ session_id = ""++ with transaction.atomic():+ if call_id:+ _lock_call(team_id, call_id)+ existing = UserInterview.objects.filter(team_id=team_id, call_metadata__id=call_id).first()+ if existing is not None:+ logger.info(+ "user_interviews_vapi_webhook_duplicate",+ team_id=team_id,+ interview_id=str(existing.id),+ call_id=call_id,+ )+ return+ interview = UserInterview.objects.create(+ team=topic.team,+ topic=topic,+ interviewee_identifier=stored_identifier,+ interviewee_emails=interviewee_emails,+ respondent_name=respondent_name,+ respondent_key=respondent_key,+ distinct_id=distinct_id,+ transcript=transcript,+ summary=message.get("summary", "") or "",+ recording_url=recording_url,+ call_metadata=call,+ created_by=topic.created_by,+ classifications=classifications,+ )+ # Collapse the abandoned partial an accidental refresh leaves behind: when a shared-link+ # respondent comes back (same respondent_key) and finishes, drop their earlier abandoned+ # rows so the topic shows one response per respondent instead of a junk trail.+ if respondent_key and UserInterviewClassification.ABANDONED not in classifications:+ collapse_abandoned_partials(+ team=topic.team,+ topic=topic,+ respondent_key=respondent_key,+ keep_pk=interview.pk,+ )+ transaction.on_commit(lambda: emit_interview_embeddings(interview, topic))++ _capture_user_interview_event(+ "user_interview_conversation_ended",+ team=topic.team,+ topic_id=topic_id,+ interviewee_context_id=interviewee_context_id,+ call_id=call_id,+ received_at=received_at,+ session_id=session_id,+ extra_properties={+ "interview_id": str(interview.id),+ "had_transcript": bool(interview.transcript),+ "had_summary": bool(interview.summary),+ },+ )++ logger.info(+ "user_interviews_vapi_webhook_stored",+ team_id=team_id,+ topic_id=topic_id,+ interview_id=str(interview.id),+ )