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.

chore(user-interviews): verify the Vapi webhook through ingress (#100892)

Julian Bez8d9721f70b49
diff --git a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml
index 984399394b95..6da7b75dee26 100644
--- a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml
+++ b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml
@@ -118,5 +118,4 @@ rules:
- /ee/partners/stripe/api/provisioning/signature.py
- /posthog/models/integration/slack.py
- /products/conversations/backend/mailgun.py
- - /products/user_interviews/backend/presentation/webhooks.py
- /products/workflows/backend/api/ses_events_webhook.py
diff --git a/posthog/ingress/vapi/README.md b/posthog/ingress/vapi/README.md
index 6ccb02be082a..d9bc6e209511 100644
--- a/posthog/ingress/vapi/README.md
+++ b/posthog/ingress/vapi/README.md
@@ -32,8 +32,18 @@ The secret is the Django setting `VAPI_WEBHOOK_SECRET`.
A bad signature answers 401 and an unconfigured instance answers 503.
The public interview surface already relies on both codes.
+A delivery a consumer did not accept answers 500 rather than the 202 receipt, because Vapi sends the delivery again after a 5xx.
+The report is the only copy of an interview, so losing it to a receipt costs the transcript.
+
## Consumers
-No product registers a Vapi consumer yet.
-The user interviews endpoint moves to ingress in its own PR.
+One consumer, `user_interviews_vapi`, declared in `products/user_interviews/backend/webhook_consumers.py`.
+
+It enqueues a Celery task and returns, so the request does not wait on persistence.
+The enqueue is the only work on the request path, so a failure there is what the 500 above answers.
+The task persists the end-of-call report and retries a transient database error, so a lost connection does not lose the transcript.
+It acknowledges late, so a worker that dies mid-task gives the report back to the broker.
+The handler is idempotent on the call id, which is what makes both the retry and the redelivery safe.
+
+The product keeps a per-IP throttle in front of the endpoint, because the endpoint is public and Vapi calls it a small number of times per interview.
See the [Endpoints table](../README.md#endpoints).
diff --git a/posthog/ingress/vapi/provider.py b/posthog/ingress/vapi/provider.py
index f307f251ff57..39d1168bf80e 100644
--- a/posthog/ingress/vapi/provider.py
+++ b/posthog/ingress/vapi/provider.py
@@ -34,6 +34,10 @@ class VapiProvider(WebhookProvider):
app = "default"
invalid_signature_status = 401
unconfigured_status = 503
+ # Vapi sends the delivery again after a 5xx, and its report is the only copy: nothing else
+ # replays an interview. The consumer hands the report to a queue and does no other work, so a
+ # consumer failure means the report reached no queue at all, and a receipt would drop it.
+ retry_status = 500
def __init__(self) -> None:
self._scheme = HmacSha256(
diff --git a/products/user_interviews/backend/facade/api.py b/products/user_interviews/backend/facade/api.py
index fb2835623035..e19b1b86dc7d 100644
--- a/products/user_interviews/backend/facade/api.py
+++ b/products/user_interviews/backend/facade/api.py
@@ -17,13 +17,20 @@ Do NOT:
from uuid import UUID
+import structlog
+
+from posthog.ingress.contracts import WebhookDelivery
+
from products.user_interviews.backend import logic
from products.user_interviews.backend.classification import derive_auto_classifications
from products.user_interviews.backend.facade.contracts import IntervieweeIdentity
+logger = structlog.get_logger(__name__)
+
__all__ = [
"SHARED_INTERVIEWEE_IDENTIFIER",
"IntervieweeIdentity",
+ "accept_vapi_event",
"derive_auto_classifications",
"has_replied",
"is_shared_interviewee_context",
@@ -57,3 +64,54 @@ def has_replied(*, team_id: int, topic_id: UUID, interviewee_identifier: str) ->
topic_id=topic_id,
interviewee_identifier=interviewee_identifier,
)
+
+
+def accept_vapi_event(delivery: WebhookDelivery) -> None:
+ """Resolve the share this delivery belongs to, and hand the work to a queue.
+
+ The token is resolved here, in the request, because the answer expires: a share that the
+ team disables, or a token that leaves its rotation grace period, while the work waits in
+ the queue would make the worker find nothing and drop a report the endpoint has already
+ accepted. So does the share row itself, which the cleanup command deletes once the token is
+ past its grace period. What crosses the broker is the team, the topic and the interviewee
+ context the share names, and nothing removes those with the share.
+
+ A token nothing answers enqueues nothing. ingress ignores what a consumer returns, so there
+ is no status to refuse the delivery with, and queueing work for a share nobody can name only
+ moves the dead end into a worker. A database failure raises instead, which costs the request
+ its receipt and makes Vapi send the report again.
+ """
+ # Deferred: keeps the Celery app off the facade import path.
+ from products.user_interviews.backend.tasks.tasks import handle_vapi_webhook # noqa: PLC0415
+
+ call_id = delivery.context.get("call_id")
+ access_token = logic.vapi_access_token(delivery.payload)
+ if not access_token:
+ logger.warning(
+ "user_interviews_vapi_webhook_missing_access_token",
+ event_type=delivery.event_type,
+ call_id=call_id,
+ )
+ return
+
+ share = logic.vapi_share_identity(access_token)
+ if share is None:
+ logger.warning(
+ "user_interviews_vapi_webhook_unknown_access_token",
+ event_type=delivery.event_type,
+ call_id=call_id,
+ )
+ return
+
+ handle_vapi_webhook.delay(
+ payload=dict(delivery.payload),
+ event_type=delivery.event_type,
+ team_id=share.team_id,
+ topic_id=share.topic_id,
+ interviewee_context_id=share.interviewee_context_id,
+ interviewee_identifier=share.interviewee_identifier,
+ # The lifecycle analytics events are timestamped with this, not with the moment the worker
+ # runs, so a delayed or retried task cannot report a call as started after it ended. Sent
+ # as a string because the broker carries JSON, which has no datetime.
+ received_at=delivery.received_at.isoformat(),
+ )
diff --git a/products/user_interviews/backend/logic.py b/products/user_interviews/backend/logic.py
index 233cc8fbfbbc..1ead70330124 100644
--- a/products/user_interviews/backend/logic.py
+++ b/products/user_interviews/backend/logic.py
@@ -8,9 +8,12 @@ products must keep going through the facade.
import re
import uuid
+from collections.abc import Mapping
from typing import Any
from uuid import UUID, uuid4
+from posthog.dataclasses import frozen
+from posthog.ingress.dispatch.database import bounded_statement_timeout
from posthog.models.sharing_configuration import SharingConfiguration
from products.user_interviews.backend.facade.contracts import IntervieweeIdentity
@@ -114,7 +117,8 @@ def shared_interviewee_identifier(respondent_key: str) -> str:
def resolve_share(access_token: str) -> SharingConfiguration | None:
- """Resolve a share token to its `SharingConfiguration`.
+ """Resolve a share token to its `SharingConfiguration`, with the rows the public interview
+ page reads off it already joined.
Uses the same enabled/expiry predicate as `SharingViewerPageViewSet.get_object()`, so a
rotated token past its grace period is dead here exactly when it is dead on the public viewer.
@@ -126,7 +130,6 @@ def resolve_share(access_token: str) -> SharingConfiguration | None:
"team__organization",
"interviewee_context",
"interviewee_context__topic",
- "interviewee_context__topic__created_by",
)
.filter(SharingConfiguration.tokens_active_q())
.get(access_token=access_token)
@@ -135,6 +138,80 @@ def resolve_share(access_token: str) -> SharingConfiguration | None:
return None
+def vapi_access_token(payload: Mapping[str, Any]) -> str:
+ """The share token Vapi echoes back from the metadata `start_call` set on the call.
+
+ Vapi surfaces that metadata in two places on the Call object: `call.metadata` for some
+ message types, and nested under `call.assistantOverrides.metadata` on others. Empirically
+ the end-of-call report comes through with the nested form, so both are read.
+ """
+ message: dict[str, Any] = payload.get("message") or {}
+ call: dict[str, Any] = message.get("call") or {}
+ overrides_metadata: dict[str, Any] = (call.get("assistantOverrides") or {}).get("metadata") or {}
+ top_metadata: dict[str, Any] = call.get("metadata") or {}
+ token = (
+ top_metadata.get("sharing_access_token")
+ or top_metadata.get("access_token")
+ or overrides_metadata.get("sharing_access_token")
+ or overrides_metadata.get("access_token")
+ )
+ return str(token) if token else ""
+
+
+# The token lookup runs inside the ingress request budget, so it is capped rather than left to
+# stall the delivery on a slow shared connection pool. See posthog/ingress/README.md, "The
+# delivery budget".
+SHARE_LOOKUP_TIMEOUT_MS = 1_000
+
+
+@frozen
+class VapiShareIdentity:
+ """What a queued Vapi report needs from the share the delivery arrived on.
+
+ The share row is not durable. `cleanup_expired_sharing_configs` deletes every configuration
+ that is past its `expires_at`, so a token rotated during a call can lose its row while the
+ report still waits in the queue or between retries. Nothing deletes the team, the topic or
+ the interviewee context with it, so these ids still say where the report belongs.
+
+ The ids are strings because the broker carries JSON, which has no UUID.
+ """
+
+ team_id: int
+ topic_id: str
+ interviewee_context_id: str
+ interviewee_identifier: str
+
+
+def vapi_share_identity(access_token: str) -> VapiShareIdentity | None:
+ """The identity behind a Vapi delivery's token, or None when no interview share answers it.
+
+ Asks the same enabled/expiry question as `resolve_share`, and reads only the ids and the
+ identifier a worker needs, because the caller hands the answer to a queue rather than to a
+ page.
+ """
+ with bounded_statement_timeout(SHARE_LOOKUP_TIMEOUT_MS, models=[SharingConfiguration]):
+ identity = (
+ SharingConfiguration.objects.filter(SharingConfiguration.tokens_active_q())
+ .filter(access_token=access_token, interviewee_context__isnull=False)
+ .values_list(
+ "team_id",
+ "interviewee_context__topic_id",
+ "interviewee_context_id",
+ "interviewee_context__interviewee_identifier",
+ )
+ .first()
+ )
+ if identity is None:
+ return None
+ team_id, topic_id, interviewee_context_id, interviewee_identifier = identity
+ return VapiShareIdentity(
+ team_id=team_id,
+ topic_id=str(topic_id),
+ interviewee_context_id=str(interviewee_context_id),
+ interviewee_identifier=interviewee_identifier,
+ )
+
+
def parse_interviewee_identifier(identifier: str) -> IntervieweeIdentity:
"""Split an interviewee identifier into a display name and (optional) email.
diff --git a/products/user_interviews/backend/presentation/webhooks.py b/products/user_interviews/backend/presentation/webhooks.py
index 0131e03cf7c2..1986bbc31d41 100644
--- a/products/user_interviews/backend/presentation/webhooks.py
+++ b/products/user_interviews/backend/presentation/webhooks.py
@@ -4,19 +4,20 @@ Two surfaces live here, both keyed on a SharingConfiguration access token:
* ``start_call`` — called by the public interview page when the recipient clicks
Start. Creates one Vapi web call server-side and returns only its join payload.
-* ``vapi_webhook`` — called by Vapi at end-of-call. Persists a UserInterview row
- attributed to the topic creator. Signature-verified; idempotent on ``call.id``.
+* ``vapi_webhook`` — the endpoint Vapi calls during and after a call. Verification and
+ fan-out are the ingress vapi incarnation's, and the consumer it dispatches to lives in
+ ``backend/webhook_consumers.py``.
"""
-import re
-import hmac
import json
+import math
import string
import hashlib
from typing import Any
from django.conf import settings
-from django.db import transaction
+from django.http import HttpRequest, HttpResponse
+from django.views.decorators.csrf import csrf_exempt
import requests
import structlog
@@ -29,12 +30,14 @@ from rest_framework.throttling import SimpleRateThrottle
from posthog.constants import AvailableFeature
from posthog.egress.vapi import vapi_request
+from posthog.ingress.vapi.provider import build_vapi_provider
+from posthog.ingress.views import build_webhook_view
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.team import Team
from posthog.rate_limit import IPThrottle
from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
-from ..facade.api import derive_auto_classifications, is_shared_interviewee_context, valid_distinct_id, valid_session_id
+from ..facade.api import is_shared_interviewee_context, valid_distinct_id, valid_session_id
from ..logic import (
RESPONDENT_KEY_MAX_CHARS,
RESPONDENT_NAME_MAX_CHARS,
@@ -42,8 +45,6 @@ from ..logic import (
resolve_share,
shared_interviewee_identifier,
)
-from ..models import UserInterview, UserInterviewClassification
-from ..vapi_events import capture_user_interview_event, collapse_abandoned_partials, emit_interview_embeddings
logger = structlog.get_logger(__name__)
@@ -147,11 +148,6 @@ class InterviewStartCallRespondentThrottle(_RateLimitMetricsMixin):
return self.cache_format % {"scope": self.scope, "ident": ident}
-# Vapi's HMAC-SHA256 hex digest is exactly 64 lowercase hex chars; reject other shapes
-# pre-HMAC so casual probes can't drive log/CPU load.
-_VAPI_SIGNATURE_RE = re.compile(r"^[0-9a-f]{64}$")
-
-
def _public_sharing_disabled_for_org(sharing_config: SharingConfiguration) -> bool:
"""Mirror of `SharingViewerPageViewSet.retrieve()`'s org-level kill switch."""
organization = sharing_config.team.organization
@@ -419,219 +415,22 @@ def start_call(request: Request, access_token: str) -> Response:
return Response({"web_call": web_call})
-@api_view(["POST"])
-@authentication_classes([])
-@permission_classes([AllowAny])
-@throttle_classes([VapiWebhookIPThrottle])
-def vapi_webhook(request: Request) -> Response:
- """Receive a Vapi ``end-of-call-report`` and persist it as a UserInterview.
+# Built once per process: the provider holds a secret getter, and reads the secret per request.
+_vapi_ingress_view = build_webhook_view(build_vapi_provider())
- Fail-closed: if ``VAPI_WEBHOOK_SECRET`` is not configured we refuse to accept any
- request — treating an unconfigured deployment as inert rather than insecure.
- With the secret set, the request body is HMAC-SHA256 verified.
- Idempotent: Vapi retries on 5xx and transient errors, so we de-duplicate by
- ``call.id`` (stored in ``call_metadata.id``). A repeat delivery returns the
- existing interview's id instead of creating a second row.
- """
- if not settings.VAPI_WEBHOOK_SECRET:
- logger.warning("user_interviews_vapi_webhook_secret_missing")
- return Response(
- {"error": "Vapi webhook secret is not configured on this PostHog instance."},
- status=status.HTTP_503_SERVICE_UNAVAILABLE,
- )
- provided = request.headers.get("X-Vapi-Signature")
- # Pre-HMAC shape gate: Vapi's HMAC-SHA256 hex digest is exactly 64 lowercase hex chars.
- # Anything else can't possibly be a valid signature, so reject before we compute the
- # HMAC over the body — saves CPU and stops casual probes from filling diagnostic logs.
- if not provided or not _VAPI_SIGNATURE_RE.match(provided):
- return Response({"error": "missing or malformed signature"}, status=status.HTTP_401_UNAUTHORIZED)
- expected = hmac.new(settings.VAPI_WEBHOOK_SECRET.encode(), request.body, hashlib.sha256).hexdigest()
- logger.info(
- "user_interviews_vapi_webhook_received",
- header_keys=sorted(request.headers.keys()),
- has_provided_signature=bool(provided),
- body_bytes=len(request.body),
- )
- if not (provided and expected and hmac.compare_digest(provided, expected)):
- # TODO: REMOVE — temporary diagnostic dump of the raw body and the
- # provided signature so we can locally reproduce Vapi's HMAC and find
- # the byte-level mismatch that's causing 100% signature_failed. Safe
- # only because user_interviews is not yet shipped to real users.
- logger.warning(
- "user_interviews_vapi_webhook_signature_failed",
- has_provided_signature=bool(provided),
- expected_prefix=expected[:8] if expected else None,
- provided_prefix=provided[:8] if provided else None,
- provided_length=len(provided) if provided else 0,
- body_bytes=len(request.body),
- provided_signature=provided,
- raw_body=request.body.decode("utf-8", errors="replace"),
- )
- return Response({"error": "invalid signature"}, status=status.HTTP_401_UNAUTHORIZED)
-
- payload = request.data if isinstance(request.data, dict) else {}
- message: dict[str, Any] = payload.get("message", {})
- message_type = message.get("type")
- 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 {}
- access_token = (
- top_metadata.get("sharing_access_token")
- or top_metadata.get("access_token")
- or overrides_metadata.get("sharing_access_token")
- or overrides_metadata.get("access_token")
- )
- # Shared-link respondent fields (set in start_call's metadata, echoed back by Vapi). Merge with
- # top-level precedence, mirroring the access_token resolution above.
- merged_metadata: dict[str, Any] = {**overrides_metadata, **top_metadata}
- call_id = call.get("id")
-
- if message_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" and access_token:
- sharing_config = resolve_share(access_token)
- if sharing_config is not None and sharing_config.interviewee_context is not None:
- capture_user_interview_event(
- "user_interview_conversation_started",
- sharing_config=sharing_config,
- call_id=call_id,
- 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 Response({"status": "ok"})
+@csrf_exempt
+def vapi_webhook(request: HttpRequest) -> HttpResponse:
+ """The ingress Vapi endpoint, behind the per-IP cap this endpoint has always carried.
- if message_type != "end-of-call-report":
- # Other event types (transcripts mid-call, speech-update, etc.) shouldn't reach us —
- # start_call's `serverMessages` override scopes Vapi to status-update + end-of-call-report.
- # Anything else here means the assistant config drifted; log it so we notice.
- logger.info(
- "user_interviews_vapi_webhook_ignored_message_type",
- message_type=message_type,
- )
- return Response({"status": "ignored"})
-
- if not access_token:
- logger.warning(
- "user_interviews_vapi_webhook_missing_access_token",
- call_id=call_id,
- )
- return Response(
- {"error": "missing sharing_access_token in call.metadata"},
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- sharing_config = resolve_share(access_token)
- if sharing_config is None:
- logger.warning(
- "user_interviews_vapi_webhook_unknown_access_token",
- call_id=call_id,
- )
- return Response({"error": "unknown access_token"}, status=status.HTTP_404_NOT_FOUND)
-
- interviewee_context = sharing_config.interviewee_context
- if interviewee_context is None:
- logger.warning(
- "user_interviews_vapi_webhook_wrong_share_type",
- team_id=sharing_config.team_id,
- call_id=call_id,
- )
- return Response(
- {"error": "access_token does not belong to a user interview share"},
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- if call_id:
- existing = UserInterview.objects.filter(team=sharing_config.team, call_metadata__id=call_id).first()
- if existing is not None:
- logger.info(
- "user_interviews_vapi_webhook_duplicate",
- team_id=sharing_config.team_id,
- interview_id=str(existing.id),
- call_id=call_id,
- )
- return Response({"status": "duplicate", "interview_id": str(existing.id)}, status=status.HTTP_200_OK)
-
- recording_url = (message.get("recording") or {}).get("url", "") or message.get("recordingUrl", "") or ""
- transcript = message.get("transcript", "") or ""
- classifications = derive_auto_classifications(transcript)
- topic = interviewee_context.topic
-
- if is_shared_interviewee_context(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.
- interviewee_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:
- interviewee_identifier = interviewee_context.interviewee_identifier
- interviewee_emails = [interviewee_identifier] if "@" in interviewee_identifier else []
- respondent_name = respondent_key = ""
- distinct_id = ""
- session_id = ""
-
- with transaction.atomic():
- interview = UserInterview.objects.create(
- team=sharing_config.team,
- topic=topic,
- interviewee_identifier=interviewee_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=sharing_config.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",
- sharing_config=sharing_config,
- call_id=call_id,
- 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=sharing_config.team_id,
- topic_id=str(topic.id),
- interview_id=str(interview.id),
- )
- return Response({"status": "created", "interview_id": str(interview.id)}, status=status.HTTP_201_CREATED)
+ ingress has no throttle lane, and the endpoint is public and unauthenticated, so the cap
+ stays in front of the view rather than being dropped on the way in.
+ """
+ throttle = VapiWebhookIPThrottle()
+ if not throttle.allow_request(Request(request), None):
+ throttled = HttpResponse(status=status.HTTP_429_TOO_MANY_REQUESTS)
+ wait = throttle.wait()
+ if wait:
+ throttled["Retry-After"] = str(math.ceil(wait))
+ return throttled
+ return _vapi_ingress_view(request)
diff --git a/products/user_interviews/backend/routes.py b/products/user_interviews/backend/routes.py
index b6c32fe58e94..3e038c78cebb 100644
--- a/products/user_interviews/backend/routes.py
+++ b/products/user_interviews/backend/routes.py
@@ -1,5 +1,4 @@
from django.urls import URLPattern, path
-from django.views.decorators.csrf import csrf_exempt
from posthog.api.routing import RouterRegistry
@@ -13,7 +12,7 @@ from products.user_interviews.backend.presentation.webhooks import vapi_webhook
urlpatterns: list[URLPattern] = [
path(
"api/user_interviews/vapi_webhook/",
- csrf_exempt(vapi_webhook),
+ vapi_webhook,
name="user_interviews_vapi_webhook",
),
]
diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.py
index 098c03697d0b..ca9940c86f97 100644
--- a/products/user_interviews/backend/test_interview_sharing.py
+++ b/products/user_interviews/backend/test_interview_sharing.py
@@ -4,6 +4,7 @@ import hmac
import json
import hashlib
import datetime
+from collections.abc import Callable
from typing import Any
import unittest
@@ -11,10 +12,14 @@ import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import Mock, patch
+from django.db import InterfaceError, OperationalError, connection
+from django.db.models import QuerySet
from django.template.loader import get_template
from django.test import SimpleTestCase, override_settings
+from django.test.utils import CaptureQueriesContext
from django.utils import timezone
+import kombu.exceptions
from parameterized import parameterized
from rest_framework import status
from rest_framework.exceptions import PermissionDenied
@@ -31,6 +36,7 @@ from products.user_interviews.backend.presentation.webhooks import (
_create_vapi_web_call,
_resolve_first_message_template,
)
+from products.user_interviews.backend.tasks.tasks import handle_vapi_webhook
from products.user_interviews.backend.vapi_events import EMBEDDING_CONTENT_MAX_BYTES
@@ -722,7 +728,7 @@ class TestVapiWebhook(APIBaseTest):
"topsecret",
self._end_of_call_payload(share.access_token, metadata_path=metadata_path),
)
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
interview = UserInterview.objects.get(team=self.team)
assert share.interviewee_context is not None
self.assertEqual(interview.topic, share.interviewee_context.topic)
@@ -730,6 +736,131 @@ class TestVapiWebhook(APIBaseTest):
self.assertEqual(interview.recording_url, "https://vapi.example/recording.mp3")
self.assertEqual(interview.transcript, "Hi! ...")
+ @time_machine.travel("2026-05-14 12:00:00", tick=False)
+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
+ @patch("products.user_interviews.backend.tasks.tasks.handle_vapi_webhook.delay")
+ def test_webhook_hands_the_report_to_a_task(self, mock_delay):
+ share = self._create_share()
+ self.client.logout()
+ payload = self._end_of_call_payload(share.access_token)
+ response = self._signed_post("topsecret", payload)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
+ assert share.interviewee_context is not None
+ mock_delay.assert_called_once_with(
+ payload=payload,
+ event_type="end-of-call-report",
+ team_id=self.team.pk,
+ topic_id=str(share.interviewee_context.topic_id),
+ interviewee_context_id=str(share.interviewee_context_id),
+ interviewee_identifier="[email protected]",
+ received_at=timezone.now().isoformat(),
+ )
+ self.assertEqual(UserInterview.objects.count(), 0)
+
+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
+ def test_webhook_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.
+ share = self._create_share()
+ self.client.logout()
+ with CaptureQueriesContext(connection) as queries:
+ response = self._signed_post("topsecret", self._end_of_call_payload(share.access_token, call_id="call_xyz"))
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
+
+ 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])
+
+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
+ @patch("products.user_interviews.backend.vapi_events.ph_scoped_capture")
+ @patch("products.user_interviews.backend.tasks.tasks.handle_vapi_webhook.delay")
+ def test_lifecycle_event_carries_the_delivery_time_not_the_run_time(self, mock_delay, mock_scoped_capture):
+ mock_capture = mock_scoped_capture.return_value.__enter__.return_value
+ share = self._create_share()
+ self.client.logout()
+ received_at = datetime.datetime(2026, 5, 14, 12, 0, tzinfo=datetime.UTC)
+ with time_machine.travel(received_at, tick=False) as clock:
+ accepted = self._signed_post(
+ "topsecret",
+ {
+ "message": {
+ "type": "status-update",
+ "status": "in-progress",
+ "call": {"id": "call_xyz", "metadata": {"sharing_access_token": share.access_token}},
+ }
+ },
+ )
+ self.assertEqual(accepted.status_code, status.HTTP_202_ACCEPTED, accepted.content)
+ clock.move_to(received_at + datetime.timedelta(minutes=10))
+ handle_vapi_webhook(**mock_delay.call_args.kwargs)
+
+ mock_capture.assert_called_once()
+ self.assertEqual(mock_capture.call_args.kwargs["timestamp"], received_at.isoformat())
+
+ @parameterized.expand(
+ [
+ ("share_disabled", lambda shares: shares.update(enabled=False)),
+ (
+ "token_past_its_grace_period",
+ lambda shares: shares.update(expires_at=timezone.now() - datetime.timedelta(minutes=1)),
+ ),
+ ("share_row_deleted", lambda shares: shares.delete()),
+ ]
+ )
+ @time_machine.travel("2026-05-14 12:00:00", tick=False)
+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
+ @patch("products.user_interviews.backend.tasks.tasks.handle_vapi_webhook.delay")
+ def test_report_is_stored_when_the_share_stops_answering_after_the_endpoint_accepted_it(
+ self, _name: str, revoke: Callable[[QuerySet[SharingConfiguration]], Any], mock_delay
+ ):
+ share = self._create_share()
+ self.client.logout()
+ accepted = self._signed_post("topsecret", self._end_of_call_payload(share.access_token))
+ self.assertEqual(accepted.status_code, status.HTTP_202_ACCEPTED, accepted.content)
+
+ # revoke is a callable so the expiry it writes is computed here, under the frozen clock
+ # above, instead of at parameterized.expand's module-import time. Deleting the row is what
+ # cleanup_expired_sharing_configs does to a share once its token is past the grace period.
+ revoke(SharingConfiguration.objects.filter(pk=share.pk, team_id=self.team.pk))
+ handle_vapi_webhook(**mock_delay.call_args.kwargs)
+
+ self.assertEqual(UserInterview.objects.filter(team=self.team).count(), 1)
+
+ def test_report_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)
+
+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
+ @patch("products.user_interviews.backend.tasks.tasks.handle_vapi_webhook.delay")
+ def test_webhook_asks_for_a_resend_when_the_report_reaches_no_queue(self, mock_delay):
+ share = self._create_share()
+ self.client.logout()
+ payload = self._end_of_call_payload(share.access_token)
+
+ mock_delay.side_effect = kombu.exceptions.OperationalError("broker unreachable")
+ refused = self._signed_post("topsecret", payload)
+ self.assertEqual(refused.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR, refused.content)
+ self.assertEqual(UserInterview.objects.count(), 0)
+
+ mock_delay.side_effect = lambda **kwargs: handle_vapi_webhook(**kwargs)
+ resent = self._signed_post("topsecret", payload)
+ self.assertEqual(resent.status_code, status.HTTP_202_ACCEPTED, resent.content)
+ self.assertEqual(UserInterview.objects.count(), 1)
+
@override_settings(VAPI_WEBHOOK_SECRET="")
def test_webhook_fails_closed_when_secret_unset(self):
share = self._create_share()
@@ -743,10 +874,14 @@ class TestVapiWebhook(APIBaseTest):
self.assertEqual(UserInterview.objects.count(), 0)
@override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- def test_webhook_rejects_unknown_token(self):
+ @patch("products.user_interviews.backend.tasks.tasks.handle_vapi_webhook.delay")
+ def test_webhook_rejects_unknown_token(self, mock_delay):
self.client.logout()
response = self._signed_post("topsecret", self._end_of_call_payload("does-not-exist"))
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ # The receipt is the transport's, so an unknown token is only observable as nothing stored.
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
+ self.assertEqual(UserInterview.objects.count(), 0)
+ mock_delay.assert_not_called()
@override_settings(VAPI_WEBHOOK_SECRET="topsecret")
def test_webhook_requires_valid_signature(self):
@@ -786,12 +921,13 @@ class TestVapiWebhook(APIBaseTest):
def test_webhook_ignores_unknown_message_types(self):
self.client.logout()
response = self._signed_post("topsecret", {"message": {"type": "speech-update"}})
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["status"], "ignored")
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
+ self.assertEqual(UserInterview.objects.count(), 0)
@override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.posthoganalytics.capture")
- def test_webhook_status_update_in_progress_captures_started_event(self, mock_capture):
+ @patch("products.user_interviews.backend.vapi_events.ph_scoped_capture")
+ def test_webhook_status_update_in_progress_captures_started_event(self, mock_scoped_capture):
+ mock_capture = mock_scoped_capture.return_value.__enter__.return_value
share = self._create_share()
self.client.logout()
response = self._signed_post(
@@ -804,7 +940,7 @@ class TestVapiWebhook(APIBaseTest):
}
},
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
mock_capture.assert_called_once()
kwargs = mock_capture.call_args.kwargs
self.assertEqual(kwargs["event"], "user_interview_conversation_started")
@@ -817,12 +953,13 @@ class TestVapiWebhook(APIBaseTest):
self.assertEqual(kwargs["properties"]["call_id"], "call_xyz")
@override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.posthoganalytics.capture")
- def test_webhook_status_update_duplicate_in_progress_emits_same_insert_id(self, mock_capture):
+ @patch("products.user_interviews.backend.vapi_events.ph_scoped_capture")
+ def test_webhook_status_update_duplicate_in_progress_emits_same_insert_id(self, mock_scoped_capture):
# Vapi re-fires `status-update / in-progress` on transient drops + warm-transfer flows.
# We tag every started event with `$insert_id` = "user_interview_conversation_started:<call_id>"
# so PostHog dedupes the second delivery at ingest. Both captures fire here (we don't
# de-dup client-side); the contract is that they share an insert_id.
+ mock_capture = mock_scoped_capture.return_value.__enter__.return_value
share = self._create_share()
self.client.logout()
payload = {
@@ -840,8 +977,9 @@ class TestVapiWebhook(APIBaseTest):
@parameterized.expand([("ringing",), ("ended",), ("queued",), ("forwarding",), ("scheduled",)])
@override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.posthoganalytics.capture")
- def test_webhook_status_update_other_statuses_do_not_capture(self, call_status: str, mock_capture):
+ @patch("products.user_interviews.backend.vapi_events.ph_scoped_capture")
+ def test_webhook_status_update_other_statuses_do_not_capture(self, call_status: str, mock_scoped_capture):
+ mock_capture = mock_scoped_capture.return_value.__enter__.return_value
share = self._create_share()
self.client.logout()
response = self._signed_post(
@@ -854,16 +992,17 @@ class TestVapiWebhook(APIBaseTest):
}
},
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
mock_capture.assert_not_called()
@override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.posthoganalytics.capture")
- def test_webhook_end_of_call_report_captures_ended_event(self, mock_capture):
+ @patch("products.user_interviews.backend.vapi_events.ph_scoped_capture")
+ def test_webhook_end_of_call_report_captures_ended_event(self, mock_scoped_capture):
+ mock_capture = mock_scoped_capture.return_value.__enter__.return_value
share = self._create_share()
self.client.logout()
response = self._signed_post("topsecret", self._end_of_call_payload(share.access_token))
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
mock_capture.assert_called_once()
kwargs = mock_capture.call_args.kwargs
self.assertEqual(kwargs["event"], "user_interview_conversation_ended")
@@ -879,12 +1018,13 @@ class TestVapiWebhook(APIBaseTest):
self.client.logout()
payload = self._end_of_call_payload(share.access_token, call_id="call_xyz")
first = self._signed_post("topsecret", payload)
- self.assertEqual(first.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(first.status_code, status.HTTP_202_ACCEPTED)
+ stored_id = UserInterview.objects.get(team=self.team).id
second = self._signed_post("topsecret", payload)
- self.assertEqual(second.status_code, status.HTTP_200_OK)
- self.assertEqual(second.json()["status"], "duplicate")
- self.assertEqual(first.json()["interview_id"], second.json()["interview_id"])
+ self.assertEqual(second.status_code, status.HTTP_202_ACCEPTED)
+ # The row the second delivery must not duplicate or replace.
self.assertEqual(UserInterview.objects.filter(team=self.team).count(), 1)
+ self.assertEqual(UserInterview.objects.get(team=self.team).id, stored_id)
@override_settings(VAPI_WEBHOOK_SECRET="topsecret")
@patch("products.user_interviews.backend.vapi_events.emit_embedding_request")
@@ -893,7 +1033,7 @@ class TestVapiWebhook(APIBaseTest):
self.client.logout()
with self.captureOnCommitCallbacks(execute=True):
response = self._signed_post("topsecret", self._end_of_call_payload(share.access_token))
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
interview = UserInterview.objects.get(team=self.team)
assert share.interviewee_context is not None
@@ -933,7 +1073,7 @@ class TestVapiWebhook(APIBaseTest):
with self.captureOnCommitCallbacks(execute=True):
response = self._signed_post("topsecret", payload)
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
emitted_types = {kwargs["document_type"] for _, kwargs in mock_emit.call_args_list}
self.assertEqual(emitted_types, expected_types)
@@ -952,8 +1092,8 @@ class TestVapiWebhook(APIBaseTest):
first_call_count = mock_emit.call_count
with self.captureOnCommitCallbacks(execute=True):
- second = self._signed_post("topsecret", payload)
- self.assertEqual(second.json()["status"], "duplicate")
+ self._signed_post("topsecret", payload)
+ self.assertEqual(UserInterview.objects.filter(team=self.team).count(), 1)
self.assertEqual(mock_emit.call_count, first_call_count)
@override_settings(VAPI_WEBHOOK_SECRET="topsecret")
@@ -966,7 +1106,7 @@ class TestVapiWebhook(APIBaseTest):
self.client.logout()
with self.captureOnCommitCallbacks(execute=True):
response = self._signed_post("topsecret", self._end_of_call_payload(share.access_token))
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
self.assertEqual(UserInterview.objects.filter(team=self.team).count(), 1)
@parameterized.expand(
@@ -993,7 +1133,7 @@ class TestVapiWebhook(APIBaseTest):
with self.captureOnCommitCallbacks(execute=True):
response = self._signed_post("topsecret", payload)
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
emitted = {kwargs["document_type"]: kwargs for _, kwargs in mock_emit.call_args_list}
diff --git a/products/user_interviews/backend/test_shared_interview_link.py b/products/user_interviews/backend/test_shared_interview_link.py
index 87114987e46e..4c62641285f4 100644
--- a/products/user_interviews/backend/test_shared_interview_link.py
+++ b/products/user_interviews/backend/test_shared_interview_link.py
@@ -356,7 +356,7 @@ class TestSharedVapiWebhook(APIBaseTest):
"topsecret",
self._payload(config.access_token, call_id="call_1", respondent_key="resp-1", transcript="a real answer"),
)
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
interview = UserInterview.objects.get(team=self.team)
assert config.interviewee_context is not None
assert interview.topic_id == config.interviewee_context.topic_id
@@ -368,17 +368,18 @@ class TestSharedVapiWebhook(APIBaseTest):
assert interview.interviewee_emails == []
@override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- @patch("products.user_interviews.backend.vapi_events.posthoganalytics.capture")
- def test_session_id_rides_on_the_lifecycle_event(self, mock_capture) -> None:
+ @patch("products.user_interviews.backend.vapi_events.ph_scoped_capture")
+ def test_session_id_rides_on_the_lifecycle_event(self, mock_scoped_capture) -> None:
# session_id isn't persisted on the model — it's attached to the conversation event as
# $session_id so the interview associates with the session recording.
+ mock_capture = mock_scoped_capture.return_value.__enter__.return_value
config = self._shared_config()
self.client.logout()
response = self._signed_post(
"topsecret",
self._payload(config.access_token, call_id="call_s", respondent_key="resp-s", transcript="hi"),
)
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
ended = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "user_interview_conversation_ended"]
assert ended, "expected a conversation_ended event"
assert ended[0].kwargs["properties"]["$session_id"] == "018f0b7a-0000-7000-8000-000000000000"
@@ -404,7 +405,7 @@ class TestSharedVapiWebhook(APIBaseTest):
payload["message"]["call"]["metadata"]["distinct_id"] = "[email protected]"
self.client.logout()
response = self._signed_post("topsecret", payload)
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
interview = UserInterview.objects.get(team=self.team)
# Stored under a namespaced shared identity, never the targeted invitee's; the forged linkage
@@ -435,7 +436,7 @@ class TestSharedVapiWebhook(APIBaseTest):
"topsecret",
self._payload(config.access_token, call_id="call_2", respondent_key="resp-1", transcript="a full answer"),
)
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
# The abandoned partial is gone; only the completed response remains for this respondent.
assert not UserInterview.objects.filter(pk=abandoned.pk).exists()
remaining = UserInterview.objects.filter(team=self.team, respondent_key="resp-1")
@@ -464,7 +465,7 @@ class TestSharedVapiWebhook(APIBaseTest):
"topsecret",
self._payload(config.access_token, call_id="call_9", respondent_key="resp-9", transcript="a full answer"),
)
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)
# The mislabeled real response is preserved (it has interviewee turns, so it doesn't re-derive
# as abandoned); only genuine AI-only partials are collapsed.
assert UserInterview.objects.filter(pk=real.pk).exists()
diff --git a/products/user_interviews/backend/test_vapi_task.py b/products/user_interviews/backend/test_vapi_task.py
index a32f3927c9ac..0cebc71d186e 100644
--- a/products/user_interviews/backend/test_vapi_task.py
+++ b/products/user_interviews/backend/test_vapi_task.py
@@ -92,6 +92,9 @@ class TestVapiWebhookTask(APIBaseTest):
self.assertEqual(interview.interviewee_identifier, "[email protected]")
self.assertEqual(interview.transcript, "Hi! ...")
self.assertEqual(interview.recording_url, "https://vapi.example/recording.mp3")
+ # The report can wait in the queue through an outage, so the interview keeps the time the
+ # endpoint accepted it rather than the time the worker got to it.
+ self.assertEqual(interview.created_at.isoformat(), "2026-05-14T12:00:00+00:00")
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
diff --git a/products/user_interviews/backend/vapi_events.py b/products/user_interviews/backend/vapi_events.py
index 447eee6b688e..69848b8bd77a 100644
--- a/products/user_interviews/backend/vapi_events.py
+++ b/products/user_interviews/backend/vapi_events.py
@@ -1,27 +1,22 @@
"""User interviews' handling of the inbound Vapi webhook.
-The endpoint in ``presentation/webhooks.py`` calls in here once a delivery is verified. The
-persistence side of the webhook lives beside ``logic.py`` rather than in the view file, so the
-view 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``.
+``handle_vapi_webhook_delivery`` runs in the Celery task that the ingress vapi consumer
+enqueues through ``facade.api.accept_vapi_event``. It persists a UserInterview row attributed
+to the topic creator, idempotent on ``call.id``.
"""
-from collections.abc import Callable, Mapping
+from collections.abc import Mapping
+from datetime import datetime
from typing import Any
from django.db import connection, transaction
import structlog
-import posthoganalytics
from posthog.schema import EmbeddingModelName
from posthog.api.embedding_worker import emit_embedding_request
from posthog.event_usage import groups
-from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.team import Team
from posthog.ph_client import ph_scoped_capture
@@ -48,7 +43,7 @@ _EMBEDDING_MODELS = [m.value for m in EmbeddingModelName]
EMBEDDING_CONTENT_MAX_BYTES = 750_000
-def emit_interview_embeddings(interview: UserInterview, topic: UserInterviewTopic) -> None:
+def _emit_interview_embeddings(interview: UserInterview, topic: UserInterviewTopic) -> None:
"""Emit transcript and summary as two separate embedding documents so each can be
searched independently. Failures are logged but never propagated: Vapi retries are
idempotent on call.id, so a re-delivery would skip creation and never re-emit —
@@ -91,7 +86,7 @@ def emit_interview_embeddings(interview: UserInterview, topic: UserInterviewTopi
)
-def collapse_abandoned_partials(*, team: Team, topic: UserInterviewTopic, respondent_key: str, keep_pk: Any) -> None:
+def _collapse_abandoned_partials(*, team: Team, topic: UserInterviewTopic, respondent_key: str, keep_pk: Any) -> None:
"""Delete the abandoned partial an accidental mid-call refresh leaves behind, when the same
respondent (same ``respondent_key``) comes back and finishes — so the topic shows one response
per respondent instead of a junk trail.
@@ -131,17 +126,33 @@ def collapse_abandoned_partials(*, team: Team, topic: UserInterviewTopic, respon
)
-def _capture_interview_event(
+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 _capture_user_interview_event(
event: str,
*,
- capture: Callable[..., Any],
team: Team,
topic_id: str,
interviewee_context_id: str,
call_id: str | None,
- timestamp: str | None,
- session_id: str,
- extra_properties: dict[str, Any] | None,
+ received_at: str | None,
+ session_id: str = "",
+ extra_properties: dict[str, Any] | None = None,
) -> None:
"""Fire a PostHog event for a user-interview lifecycle moment (conversation started/ended).
Failures never propagate — analytics never blocks a webhook delivery.
@@ -151,6 +162,10 @@ def _capture_interview_event(
until we ack. Set `$insert_id` to `<event>:<call_id>` so PostHog dedupes the second
delivery at ingest — funnels see one start and one end per call.
+ 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.
+
When a shared-link respondent supplied a valid session_id, it's attached as `$session_id` so
the event (and thus the interview) associates with that session recording — this is how the
session is linked without a dedicated DB column.
@@ -171,13 +186,17 @@ def _capture_interview_event(
if extra_properties:
properties.update(extra_properties)
try:
- capture(
- distinct_id=f"user_interview:{interviewee_context_id}",
- event=event,
- properties=properties,
- timestamp=timestamp,
- groups=groups(organization=team.organization, team=team),
- )
+ # This runs in the Celery task, where the global client's background flush may never run
+ # before the worker exits, so the event is lost without a word. The scoped client flushes
+ # when the context exits. A run emits at most one event, so the client is opened once.
+ with ph_scoped_capture() as capture:
+ capture(
+ distinct_id=f"user_interview:{interviewee_context_id}",
+ event=event,
+ properties=properties,
+ timestamp=received_at,
+ groups=groups(organization=team.organization, team=team),
+ )
except Exception:
logger.exception(
"user_interviews_event_capture_failed",
@@ -187,86 +206,17 @@ def _capture_interview_event(
)
-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:
+def _backdate_to_receipt(interview: UserInterview, received_at: str | None) -> None:
+ """Stamp the interview with the time the endpoint accepted the report, not the worker's."""
+ if not received_at:
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,
- )
+ try:
+ accepted_at = datetime.fromisoformat(received_at)
+ except ValueError:
+ return
+ # created_at is auto_now_add, so the row must be updated after the insert.
+ UserInterview.objects.filter(pk=interview.pk).update(created_at=accepted_at)
+ interview.created_at = accepted_at
def handle_vapi_webhook_delivery(
@@ -404,17 +354,18 @@ def handle_vapi_webhook_delivery(
created_by=topic.created_by,
classifications=classifications,
)
+ _backdate_to_receipt(interview, received_at)
# 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(
+ _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))
+ transaction.on_commit(lambda: _emit_interview_embeddings(interview, topic))
_capture_user_interview_event(
"user_interview_conversation_ended",
diff --git a/products/user_interviews/backend/webhook_consumers.py b/products/user_interviews/backend/webhook_consumers.py
new file mode 100644
index 000000000000..666028d95bf4
--- /dev/null
+++ b/products/user_interviews/backend/webhook_consumers.py
@@ -0,0 +1,23 @@
+"""User interviews' consumer on the Vapi endpoint."""
+
+from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery
+from posthog.ingress.vapi.provider import VAPI_EVENT_TYPES
+
+
+def _queue_interview_storage(delivery: WebhookDelivery) -> None:
+ from products.user_interviews.backend.facade.api import ( # noqa: PLC0415 - keeps the product's models and the Celery app off the registry's import path
+ accept_vapi_event,
+ )
+
+ accept_vapi_event(delivery)
+
+
+WEBHOOK_CONSUMERS = (
+ WebhookConsumer(
+ name="user_interviews_vapi",
+ provider="vapi",
+ app="default",
+ event_types=VAPI_EVENT_TYPES,
+ handler=_queue_interview_storage,
+ ),
+)
diff --git a/pyproject.toml b/pyproject.toml
index 88a02006e8df..31e484924b44 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -622,10 +622,6 @@ ignore_imports = [
# respondent-field helpers from logic directly. A facade read would have to hand back the
# SharingConfiguration, which §5 forbids.
"products.user_interviews.backend.presentation.webhooks -> products.user_interviews.backend.logic",
- "products.user_interviews.backend.presentation.webhooks -> products.user_interviews.backend.models",
- # The webhook view still holds the request handling for the Vapi delivery, so it calls the
- # event module directly. The line goes when the handling moves off the request path.
- "products.user_interviews.backend.presentation.webhooks -> products.user_interviews.backend.vapi_events",
# logs presentation isolation (temporary): the moved viewsets still reach in-product
# internals directly. Removed by the follow-up that thins each viewset to go through
# the facade.