: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(data-warehouse): implement vapi import source (#69611)
Tom Owerse1c47b2c54e4
diff --git a/frontend/public/services/vapi.png b/frontend/public/services/vapi.pngnew file mode 100644index 000000000000..0b976420b016Binary files /dev/null and b/frontend/public/services/vapi.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 43746c7b546e..04c7c176069c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -422,6 +422,7 @@ the row lists both.| unleash | HTTP | requests | ✅ || upstash | HTTP | requests | ✅ || vantage | HTTP | requests | ✅ |+| vapi | HTTP | requests | ✅ || vellum | HTTP | requests | ✅ || vercel | HTTP | requests | ✅ || vitally | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -839,7 +840,6 @@ doesn't conflict with concurrent PRs.- uptick- us_census- uservoice-- vapi- veeqo- vespa- visma_economicdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 348ff2cdf072..49711dd54d47 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -3953,7 +3953,7 @@ class VantageSourceConfig(config.Config):@config.configclass VapiSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/canonical_descriptions.pynew file mode 100644index 000000000000..edaaf6d07a6c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/canonical_descriptions.py@@ -0,0 +1,180 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the official Vapi API reference (https://docs.vapi.ai/api-reference)+# and the OpenAPI spec served at https://api.vapi.ai/api-json.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "calls": {+ "description": "Phone and web calls handled by Vapi voice assistants, squads, or workflows, including transcript artifacts, analysis, ended reason, and per-component cost breakdown.",+ "docs_url": "https://docs.vapi.ai/api-reference/calls/list",+ "columns": {+ "id": "Unique identifier for the call.",+ "orgId": "Unique identifier for the org that this call belongs to.",+ "type": "Type of call (e.g. inboundPhoneCall, outboundPhoneCall, webCall).",+ "status": "Current status of the call (e.g. queued, ringing, in-progress, ended).",+ "endedReason": "Explanation for how the call ended.",+ "endedMessage": "Message adding more context to the ended reason, such as error messages or warnings.",+ "createdAt": "ISO 8601 date-time string of when the call was created.",+ "updatedAt": "ISO 8601 date-time string of when the call was last updated.",+ "startedAt": "ISO 8601 date-time string of when the call was started.",+ "endedAt": "ISO 8601 date-time string of when the call was ended.",+ "cost": "Total cost of the call in USD.",+ "costs": "Costs of the individual components of the call in USD.",+ "costBreakdown": "Breakdown of the call cost in USD by component (transport, STT, LLM, TTS, Vapi fees).",+ "analysis": "Analysis of the call (summary, structured data, success evaluation), configured via the assistant's analysisPlan.",+ "artifact": "Artifacts created from the call, such as recordings and transcripts.",+ "phoneCallProvider": "Provider of the phone call (e.g. twilio, vonage, vapi).",+ "phoneCallProviderId": "ID of the call as provided by the phone number service (e.g. callSid in Twilio).",+ "phoneCallTransport": "Transport of the phone call (e.g. sip, pstn).",+ "assistantId": "ID of the assistant used for the call.",+ "squadId": "ID of the squad used for the call.",+ "workflowId": "ID of the workflow used for the call.",+ "phoneNumberId": "ID of the phone number used for the call.",+ "customerId": "ID of the customer that was called.",+ "customer": "Customer contact details for the call.",+ "campaignId": "ID of the campaign that the call belongs to.",+ "name": "User-defined name of the call, for reference only.",+ },+ },+ "assistants": {+ "description": "Configured Vapi voice assistants: transcriber, LLM, and voice settings plus call behavior, analysis, and artifact plans.",+ "docs_url": "https://docs.vapi.ai/api-reference/assistants/list",+ "columns": {+ "id": "Unique identifier for the assistant.",+ "orgId": "Unique identifier for the org that this assistant belongs to.",+ "name": "Name of the assistant.",+ "createdAt": "ISO 8601 date-time string of when the assistant was created.",+ "updatedAt": "ISO 8601 date-time string of when the assistant was last updated.",+ "transcriber": "Options for the assistant's speech-to-text transcriber.",+ "model": "Options for the assistant's LLM (provider, model, messages, tools).",+ "voice": "Options for the assistant's text-to-speech voice.",+ "firstMessage": "First message the assistant says on a call.",+ "firstMessageMode": "Mode for the first message (default 'assistant-speaks-first').",+ "maxDurationSeconds": "Maximum number of seconds a call with this assistant can last.",+ "analysisPlan": "Plan for analyzing the assistant's calls, stored in call.analysis.",+ "artifactPlan": "Plan for artifacts generated during the assistant's calls, stored in call.artifact.",+ "server": "Server URL and settings where Vapi sends this assistant's webhooks.",+ "metadata": "Arbitrary metadata stored on the assistant.",+ },+ },+ "phone_numbers": {+ "description": "Phone numbers attached to the org, either provisioned through Vapi or brought from providers like Twilio, Vonage, or Telnyx.",+ "docs_url": "https://docs.vapi.ai/api-reference/phone-numbers/list",+ "columns": {+ "id": "Unique identifier for the phone number.",+ "orgId": "Unique identifier for the org that this phone number belongs to.",+ "provider": "Provider of the phone number (e.g. twilio, vonage, telnyx, byo-phone-number, vapi).",+ "number": "The phone number in E.164 format.",+ "name": "User-defined name of the phone number, for reference only.",+ "status": "Status of the phone number.",+ "assistantId": "ID of the assistant that answers inbound calls to this number.",+ "squadId": "ID of the squad that answers inbound calls to this number.",+ "workflowId": "ID of the workflow that answers inbound calls to this number.",+ "createdAt": "ISO 8601 date-time string of when the phone number was created.",+ "updatedAt": "ISO 8601 date-time string of when the phone number was last updated.",+ },+ },+ "squads": {+ "description": "Squads group multiple assistants so calls can be transferred between them mid-conversation.",+ "docs_url": "https://docs.vapi.ai/api-reference/squads/list",+ "columns": {+ "id": "Unique identifier for the squad.",+ "orgId": "Unique identifier for the org that this squad belongs to.",+ "name": "Name of the squad.",+ "members": "Assistants that make up the squad, with per-member destinations for transfers.",+ "membersOverrides": "Overrides applied to all members of the squad.",+ "createdAt": "ISO 8601 date-time string of when the squad was created.",+ "updatedAt": "ISO 8601 date-time string of when the squad was last updated.",+ },+ },+ "tools": {+ "description": "Tools that assistants can invoke during calls, such as API requests, call transfers, or external integrations.",+ "docs_url": "https://docs.vapi.ai/api-reference/tools/list",+ "columns": {+ "id": "Unique identifier for the tool.",+ "orgId": "Unique identifier for the org that this tool belongs to.",+ "type": "Type of the tool (e.g. apiRequest, transferCall, function).",+ "function": "Function definition (name, description, parameters) the LLM sees for this tool.",+ "createdAt": "ISO 8601 date-time string of when the tool was created.",+ "updatedAt": "ISO 8601 date-time string of when the tool was last updated.",+ },+ },+ "files": {+ "description": "Files uploaded to Vapi, typically used as knowledge-base sources for assistants.",+ "docs_url": "https://docs.vapi.ai/api-reference/files/list",+ "columns": {+ "id": "Unique identifier for the file.",+ "orgId": "Unique identifier for the org that this file belongs to.",+ "name": "User-defined name of the file, for reference only.",+ "originalName": "Original name of the uploaded file.",+ "bytes": "Size of the file in bytes.",+ "purpose": "Purpose of the file.",+ "mimetype": "MIME type of the file.",+ "status": "Processing status of the file.",+ "url": "URL where the file is hosted.",+ "createdAt": "ISO 8601 date-time string of when the file was created.",+ "updatedAt": "ISO 8601 date-time string of when the file was last updated.",+ },+ },+ "chats": {+ "description": "Text-based chat interactions with assistants, including input, output messages, and cost.",+ "docs_url": "https://docs.vapi.ai/api-reference/chats/list",+ "columns": {+ "id": "Unique identifier for the chat.",+ "orgId": "Unique identifier for the org that this chat belongs to.",+ "assistantId": "ID of the assistant used for the chat.",+ "sessionId": "ID of the session the chat belongs to.",+ "previousChatId": "ID of the chat used as context for this chat.",+ "name": "User-defined name of the chat, for reference only.",+ "input": "Input text for the chat.",+ "messages": "Messages used as context for the chat.",+ "output": "Output messages generated by the system in response to the input.",+ "cost": "Cost of the chat in USD.",+ "costs": "Costs of the individual components of the chat in USD.",+ "createdAt": "ISO 8601 date-time string of when the chat was created.",+ "updatedAt": "ISO 8601 date-time string of when the chat was last updated.",+ },+ },+ "sessions": {+ "description": "Sessions group related chats and calls into one continuous conversation context.",+ "docs_url": "https://docs.vapi.ai/api-reference/sessions/list",+ "columns": {+ "id": "Unique identifier for the session.",+ "orgId": "Unique identifier for the organization that owns this session.",+ "name": "User-defined name for the session.",+ "status": "Current status of the session ('active' or 'completed').",+ "expirationSeconds": "Session expiration time in seconds (default 24 hours).",+ "assistantId": "ID of the assistant associated with this session.",+ "squadId": "ID of the squad associated with this session.",+ "messages": "Message history for the session.",+ "cost": "Cost of the session in USD.",+ "costs": "Costs of the individual components of the session in USD.",+ "createdAt": "ISO 8601 timestamp indicating when the session was created.",+ "updatedAt": "ISO 8601 timestamp indicating when the session was last updated.",+ },+ },+ "campaigns": {+ "description": "Outbound call campaigns that dial a list of customers with an assistant or workflow, with live progress counters.",+ "docs_url": "https://docs.vapi.ai/api-reference/campaigns/list",+ "columns": {+ "id": "Unique identifier for the campaign.",+ "orgId": "Unique identifier for the org that this campaign belongs to.",+ "name": "Name of the campaign.",+ "status": "Status of the campaign (e.g. scheduled, in-progress, ended).",+ "endedReason": "Explanation for how the campaign ended.",+ "assistantId": "ID of the assistant used for the campaign's calls.",+ "workflowId": "ID of the workflow used for the campaign's calls.",+ "phoneNumberId": "ID of the phone number the campaign dials from.",+ "customers": "Customers the campaign will call.",+ "schedulePlan": "Schedule plan for when the campaign's calls are placed.",+ "callsCounterScheduled": "Number of campaign calls currently scheduled.",+ "callsCounterQueued": "Number of campaign calls currently queued.",+ "callsCounterInProgress": "Number of campaign calls currently in progress.",+ "callsCounterEndedVoicemail": "Number of campaign calls that ended in voicemail.",+ "callsCounterEnded": "Number of campaign calls that have ended.",+ "createdAt": "ISO 8601 date-time string of when the campaign was created.",+ "updatedAt": "ISO 8601 date-time string of when the campaign was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/settings.pynew file mode 100644index 000000000000..80e53d499b7d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/settings.py@@ -0,0 +1,112 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++VAPI_BASE_URL = "https://api.vapi.ai"++# Vapi caps `limit` at 1000 (default 100). Call/chat objects can be large (full transcripts,+# message arrays, cost breakdowns), so keep pages at 100 rows to bound per-request memory.+DEFAULT_PAGE_LIMIT = 100++# How the endpoint paginates:+# - "created_at_cursor": returns a bare array in createdAt-descending order; the next page is+# requested with `createdAtLt=<oldest createdAt of the previous page>`.+# - "page": returns a `{results, metadata}` envelope with `page`/`sortOrder`/`sortBy` params.+# - "none": returns the full collection in a single unpaginated array.+VapiPaginationStyle = Literal["created_at_cursor", "page", "none"]+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++@dataclass+class VapiEndpointConfig:+ name: str+ path: str+ pagination: VapiPaginationStyle+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable datetime field used for partitioning. None disables partitioning.+ partition_key: Optional[str] = "createdAt"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+++VAPI_ENDPOINTS: dict[str, VapiEndpointConfig] = {+ # Calls is the flagship stream: transcripts, analysis, ended reasons, durations, and cost+ # breakdowns. createdAt is the safe default cursor; updatedAt also has a server-side filter+ # (`updatedAtGt`) and re-syncs calls whose analysis/artifacts were attached after the call ended.+ "calls": VapiEndpointConfig(+ name="calls",+ path="/call",+ pagination="created_at_cursor",+ incremental_fields=[+ _datetime_incremental_field("createdAt"),+ _datetime_incremental_field("updatedAt"),+ ],+ ),+ # Assistants/phone numbers/squads/tools are small config tables that mutate in place, so a+ # createdAt watermark would go stale immediately; full refresh keeps them correct and cheap.+ "assistants": VapiEndpointConfig(+ name="assistants",+ path="/assistant",+ pagination="created_at_cursor",+ ),+ "phone_numbers": VapiEndpointConfig(+ name="phone_numbers",+ path="/phone-number",+ pagination="created_at_cursor",+ ),+ "squads": VapiEndpointConfig(+ name="squads",+ path="/squad",+ pagination="created_at_cursor",+ ),+ "tools": VapiEndpointConfig(+ name="tools",+ path="/tool",+ pagination="created_at_cursor",+ ),+ # GET /file takes no pagination params at all — single unpaginated array.+ "files": VapiEndpointConfig(+ name="files",+ path="/file",+ pagination="none",+ partition_key=None,+ ),+ # Page-based endpoints are requested with sortOrder=ASC&sortBy=createdAt so rows arrive in+ # ascending createdAt order. Only createdAt is offered as an incremental field: the API can't+ # sort by updatedAt, and an updatedAt watermark over createdAt-ordered pages would checkpoint+ # values that later pages can undercut, losing rows on the next sync.+ "chats": VapiEndpointConfig(+ name="chats",+ path="/chat",+ pagination="page",+ incremental_fields=[_datetime_incremental_field("createdAt")],+ ),+ "sessions": VapiEndpointConfig(+ name="sessions",+ path="/session",+ pagination="page",+ incremental_fields=[_datetime_incremental_field("createdAt")],+ ),+ # Campaigns mutate heavily (status plus per-call counters), so createdAt-incremental would go+ # stale immediately; the table is small, so full refresh only.+ "campaigns": VapiEndpointConfig(+ name="campaigns",+ path="/campaign",+ pagination="page",+ ),+}++ENDPOINTS = tuple(VAPI_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in VAPI_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/source.pyindex 7a7add5e560d..584f9d5c513e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/source.py@@ -1,19 +1,43 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import VapiSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.vapi.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ VAPI_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.vapi.vapi import (+ VapiResumeConfig,+ validate_credentials as validate_vapi_credentials,+ vapi_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class VapiSource(SimpleSource[VapiSourceConfig]):+class VapiSource(ResumableSource[VapiSourceConfig, VapiResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.VAPI@@ -24,8 +48,98 @@ class VapiSource(SimpleSource[VapiSourceConfig]):name=SchemaExternalDataSourceType.VAPI,category=DataWarehouseSourceCategory.COMMUNICATION,label="Vapi",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Vapi private API key to automatically pull your Vapi voice agent data into the PostHog Data warehouse.++You can find your private API key in the [Vapi dashboard](https://dashboard.vapi.ai) under **Organization settings** → **API keys**.+""",iconPath="/static/services/vapi.png",+ docsUrl="https://posthog.com/docs/cdp/sources/vapi",keywords=["voice", "ai agent", "calls", "telephony"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.vapi.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # An invalid or revoked Vapi API key surfaces as a requests HTTPError from+ # `raise_for_status()`. Match the stable status text and base host, not the+ # per-request path/query.+ return {+ "401 Client Error: Unauthorized for url: https://api.vapi.ai": "Your Vapi API key is invalid or has been revoked. Create a new private API key in the Vapi dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.vapi.ai": "Your Vapi API key does not have permission to read this data. Check the key's permissions in the Vapi dashboard, then reconnect.",+ }++ def get_schemas(+ self,+ config: VapiSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = VAPI_ENDPOINTS[endpoint]+ has_incremental = len(endpoint_config.incremental_fields) > 0+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: VapiSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_vapi_credentials(config.api_key):+ return True, None++ return False, "Invalid Vapi API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[VapiResumeConfig]:+ return ResumableSourceManager[VapiResumeConfig](inputs, VapiResumeConfig)++ def source_for_pipeline(+ self,+ config: VapiSourceConfig,+ resumable_source_manager: ResumableSourceManager[VapiResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return vapi_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ db_incremental_field_earliest_value=inputs.db_incremental_field_earliest_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/tests/test_vapi.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/tests/test_vapi.pynew file mode 100644index 000000000000..ce7625bcf14a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/tests/test_vapi.py@@ -0,0 +1,309 @@+import json+from datetime import UTC, date, datetime+from typing import Any++from unittest.mock import MagicMock++import pyarrow as pa+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.vapi import vapi+from products.warehouse_sources.backend.temporal.data_imports.sources.vapi.vapi import (+ VapiResumeConfig,+ _format_datetime_param,+ get_rows,+ vapi_source,+)+++class TestFormatDatetimeParam:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, 123000, tzinfo=UTC), "2026-03-04T02:58:14.123Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),+ ("string_passthrough", "2026-03-04T02:58:14.123Z", "2026-03-04T02:58:14.123Z"),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str) -> None:+ result = _format_datetime_param(value)+ assert result == expected+ assert "+00:00" not in result+++class _FakeResumableManager:+ def __init__(self, state: VapiResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[VapiResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> VapiResumeConfig | None:+ return self._state++ def save_state(self, data: VapiResumeConfig) -> None:+ self.saved.append(data)+++class _FakeBatcher:+ """Yields one table per batched page so save-after-yield behavior is observable without 2000+ rows."""++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ self._rows: list[dict] = []++ def batch(self, rows: list[dict]) -> None:+ self._rows.extend(rows)++ def should_yield(self, include_incomplete_chunk: bool = False) -> bool:+ return len(self._rows) > 0++ def get_table(self) -> pa.Table:+ table = table_from_py_list(self._rows)+ self._rows = []+ return table+++def _patch_fetch(monkeypatch: Any, pages: dict[str, Any]) -> list[str]:+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, logger: Any) -> Any:+ fetched.append(url)+ return pages[url]++ monkeypatch.setattr(vapi, "_fetch", fake_fetch)+ monkeypatch.setattr(vapi, "_make_session", lambda api_key: MagicMock())+ return fetched+++def _collect(monkeypatch: Any, manager: _FakeResumableManager, **kwargs: Any) -> list[dict]:+ monkeypatch.setattr(vapi, "Batcher", _FakeBatcher)+ monkeypatch.setattr(vapi, "DEFAULT_PAGE_LIMIT", 2)+ rows: list[dict] = []+ for table in get_rows(+ api_key="key",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(table.to_pylist())+ return rows+++class TestCreatedAtCursorEndpoints:+ def test_paginates_with_created_at_lt_until_short_page(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.vapi.ai/call?limit=2": [+ {"id": "3", "createdAt": "2026-01-03T00:00:00.000Z"},+ {"id": "2", "createdAt": "2026-01-02T00:00:00.000Z"},+ ],+ "https://api.vapi.ai/call?limit=2&createdAtLt=2026-01-02T00%3A00%3A00.000Z": [+ {"id": "1", "createdAt": "2026-01-01T00:00:00.000Z"},+ ],+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="calls")++ assert [r["id"] for r in rows] == ["3", "2", "1"]+ assert fetched == list(pages)++ def test_saves_cursor_of_last_yielded_row(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.vapi.ai/call?limit=2": [+ {"id": "3", "createdAt": "2026-01-03T00:00:00.000Z"},+ {"id": "2", "createdAt": "2026-01-02T00:00:00.000Z"},+ ],+ "https://api.vapi.ai/call?limit=2&createdAtLt=2026-01-02T00%3A00%3A00.000Z": [],+ }+ _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager()+ _collect(monkeypatch, manager, endpoint="calls")++ assert manager.saved[-1] == VapiResumeConfig(created_at_cursor="2026-01-02T00:00:00.000Z")++ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.vapi.ai/call?limit=2&createdAtLt=2026-01-02T00%3A00%3A00.000Z": [+ {"id": "1", "createdAt": "2026-01-01T00:00:00.000Z"},+ ],+ }+ fetched = _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager(VapiResumeConfig(created_at_cursor="2026-01-02T00:00:00.000Z"))+ rows = _collect(monkeypatch, manager, endpoint="calls")++ assert [r["id"] for r in rows] == ["1"]+ assert fetched == list(pages)++ def test_incremental_fetches_backfill_then_newer_rows(self, monkeypatch: Any) -> None:+ pages = {+ # Backfill leg: rows older than the earliest value already synced.+ "https://api.vapi.ai/call?createdAtLt=2026-01-01T00%3A00%3A00.000Z&limit=2": [+ {"id": "0", "createdAt": "2025-12-31T00:00:00.000Z"},+ ],+ # Newer leg: rows past the watermark.+ "https://api.vapi.ai/call?createdAtGt=2026-01-05T00%3A00%3A00.000Z&limit=2": [+ {"id": "6", "createdAt": "2026-01-06T00:00:00.000Z"},+ ],+ }+ fetched = _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager()+ rows = _collect(+ monkeypatch,+ manager,+ endpoint="calls",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 5, tzinfo=UTC),+ db_incremental_field_earliest_value=datetime(2026, 1, 1, tzinfo=UTC),+ incremental_field="createdAt",+ )++ assert [r["id"] for r in rows] == ["0", "6"]+ assert fetched == list(pages)+ # Incremental legs are bounded windows; a retry re-fetches them, so no resume state.+ assert manager.saved == []++ def test_incremental_on_updated_at_uses_updated_at_filters(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.vapi.ai/call?updatedAtGt=2026-01-05T00%3A00%3A00.000Z&limit=2": [+ {"id": "6", "createdAt": "2026-01-06T00:00:00.000Z", "updatedAt": "2026-01-06T00:00:00.000Z"},+ ],+ }+ fetched = _patch_fetch(monkeypatch, pages)+ _collect(+ monkeypatch,+ _FakeResumableManager(),+ endpoint="calls",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 5, tzinfo=UTC),+ incremental_field="updatedAt",+ )+ assert fetched == list(pages)+++class TestPageEndpoints:+ def test_walks_ascending_pages_until_has_next_page_false(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.vapi.ai/chat?limit=2&page=1&sortOrder=ASC&sortBy=createdAt": {+ "results": [+ {"id": "1", "createdAt": "2026-01-01T00:00:00.000Z"},+ {"id": "2", "createdAt": "2026-01-02T00:00:00.000Z"},+ ],+ "metadata": {"hasNextPage": True},+ },+ "https://api.vapi.ai/chat?limit=2&page=2&sortOrder=ASC&sortBy=createdAt": {+ "results": [{"id": "3", "createdAt": "2026-01-03T00:00:00.000Z"}],+ "metadata": {"hasNextPage": False},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="chats")++ assert [r["id"] for r in rows] == ["1", "2", "3"]+ assert fetched == list(pages)++ def test_resume_cursor_narrows_window_and_restarts_at_page_one(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.vapi.ai/chat?createdAtGt=2026-01-02T00%3A00%3A00.000Z&limit=2&page=1&sortOrder=ASC&sortBy=createdAt": {+ "results": [{"id": "3", "createdAt": "2026-01-03T00:00:00.000Z"}],+ "metadata": {"hasNextPage": False},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager(VapiResumeConfig(created_at_cursor="2026-01-02T00:00:00.000Z"))+ rows = _collect(monkeypatch, manager, endpoint="chats")++ assert [r["id"] for r in rows] == ["3"]+ assert fetched == list(pages)++ def test_incremental_watermark_becomes_created_at_gt(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.vapi.ai/session?createdAtGt=2026-01-05T00%3A00%3A00.000Z&limit=2&page=1&sortOrder=ASC&sortBy=createdAt": {+ "results": [{"id": "6", "createdAt": "2026-01-06T00:00:00.000Z"}],+ "metadata": {"hasNextPage": False},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ _collect(+ monkeypatch,+ _FakeResumableManager(),+ endpoint="sessions",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 5, tzinfo=UTC),+ incremental_field="createdAt",+ )+ assert fetched == list(pages)+++class TestSensitiveValueScrubbing:+ def test_auth_material_redacted_before_batching(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.vapi.ai/assistant?limit=2": [+ {+ "id": "a1",+ "createdAt": "2026-01-01T00:00:00.000Z",+ "credentials": [{"provider": "openai", "apiKey": "sk-live"}],+ "credentialIds": ["550e8400"],+ "server": {"url": "https://example.com/hook", "secret": "hook-secret", "headers": {"x": "y"}},+ "model": {"provider": "openai", "model": "gpt-4o"},+ },+ ],+ }+ _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="assistants")++ row = rows[0]+ # Nested objects come back JSON-encoded after the Arrow round trip.+ server = json.loads(row["server"]) if isinstance(row["server"], str) else row["server"]+ model = json.loads(row["model"]) if isinstance(row["model"], str) else row["model"]+ credential_ids = (+ json.loads(row["credentialIds"]) if isinstance(row["credentialIds"], str) else row["credentialIds"]+ )++ assert row["credentials"] == "[REDACTED]"+ assert server["secret"] == "[REDACTED]"+ assert server["headers"] == "[REDACTED]"+ # No secret survives anywhere in the row, however it was serialized.+ assert "sk-live" not in str(row)+ assert "hook-secret" not in str(row)+ # Non-secret data survives untouched, including credential ID references.+ assert credential_ids == ["550e8400"]+ assert server["url"] == "https://example.com/hook"+ assert model == {"provider": "openai", "model": "gpt-4o"}+++class TestUnpaginatedEndpoints:+ def test_files_fetched_in_single_unparameterized_request(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.vapi.ai/file": [{"id": "f1", "createdAt": "2026-01-01T00:00:00.000Z"}],+ }+ fetched = _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager()+ rows = _collect(monkeypatch, manager, endpoint="files")++ assert [r["id"] for r in rows] == ["f1"]+ assert fetched == list(pages)+ assert manager.saved == []+++class TestVapiSourceResponse:+ @parameterized.expand(+ [+ ("calls_descending", "calls", "desc", ["createdAt"]),+ ("chats_ascending", "chats", "asc", ["createdAt"]),+ ("files_unpartitioned", "files", "asc", None),+ ]+ )+ def test_sort_mode_and_partitioning(+ self, _name: str, endpoint: str, expected_sort_mode: str, expected_partition_keys: list[str] | None+ ) -> None:+ response = vapi_source(+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == expected_sort_mode+ assert response.partition_keys == expected_partition_keysdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/tests/test_vapi_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/tests/test_vapi_source.pynew file mode 100644index 000000000000..6d577a4e3b62--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/tests/test_vapi_source.py@@ -0,0 +1,148 @@+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import VapiSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.vapi.settings import ENDPOINTS, VAPI_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.vapi.source import VapiSource+from products.warehouse_sources.backend.temporal.data_imports.sources.vapi.vapi import VapiResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++# Endpoints whose Vapi list action exposes a server-side timestamp filter usable with the+# endpoint's ordering guarantees; the rest are full refresh only.+_INCREMENTAL_ENDPOINTS = {"calls", "chats", "sessions"}+_FULL_REFRESH_ENDPOINTS = set(ENDPOINTS) - _INCREMENTAL_ENDPOINTS+++class TestVapiSource:+ def setup_method(self):+ self.source = VapiSource()+ self.team_id = 123+ self.config = VapiSourceConfig(api_key="key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.VAPI++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Vapi"+ assert config.label == "Vapi"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/vapi.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/vapi"++ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ @parameterized.expand(+ [+ "401 Client Error: Unauthorized for url: https://api.vapi.ai/call?limit=100",+ "403 Client Error: Forbidden for url: https://api.vapi.ai/assistant?limit=100",+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @parameterized.expand(+ [+ "429 Client Error: Too Many Requests for url: https://api.vapi.ai/call",+ "500 Server Error: Internal Server Error for url: https://api.vapi.ai/call",+ "HTTPSConnectionPool(host='api.vapi.ai', port=443): Read timed out.",+ ]+ )+ def test_non_retryable_errors_do_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for name in _INCREMENTAL_ENDPOINTS:+ assert schemas[name].supports_incremental is True+ assert schemas[name].supports_append is True+ assert "createdAt" in [f["field"] for f in schemas[name].incremental_fields]+ for name in _FULL_REFRESH_ENDPOINTS:+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False+ assert schemas[name].incremental_fields == []++ def test_calls_offers_updated_at_incremental_field(self):+ # updatedAt re-syncs calls whose analysis/artifacts land after the call ends.+ schemas = self.source.get_schemas(self.config, self.team_id, names=["calls"])+ assert [f["field"] for f in schemas[0].incremental_fields] == ["createdAt", "updatedAt"]++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["calls"])+ assert [s.name for s in schemas] == ["calls"]++ def test_lists_tables_without_credentials_publishes_catalog(self):+ # Static endpoint catalog (no I/O) — the public docs table list should render.+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(VAPI_ENDPOINTS)++ @parameterized.expand(+ [+ (True, True, None),+ (False, False, "Invalid Vapi API key"),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.vapi.source.validate_vapi_credentials"+ )+ def test_validate_credentials(self, mock_return, expected_valid, expected_message, mock_validate):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("key")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is VapiResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.vapi.source.vapi_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_vapi_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "calls"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00.000Z"+ inputs.db_incremental_field_earliest_value = "2025-01-01T00:00:00.000Z"+ inputs.incremental_field = "createdAt"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_vapi_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "calls"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00.000Z"+ assert kwargs["db_incremental_field_earliest_value"] == "2025-01-01T00:00:00.000Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.vapi.source.vapi_source")+ def test_source_for_pipeline_omits_cursors_when_not_incremental(self, mock_vapi_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "assistants"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00.000Z"+ inputs.db_incremental_field_earliest_value = "2025-01-01T00:00:00.000Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_vapi_source.call_args.kwargs["db_incremental_field_last_value"] is None+ assert mock_vapi_source.call_args.kwargs["db_incremental_field_earliest_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/vapi.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/vapi.pynew file mode 100644index 000000000000..d206cc06baa5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vapi/vapi.py@@ -0,0 +1,326 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import pyarrow as pa+import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.vapi.settings import (+ DEFAULT_PAGE_LIMIT,+ VAPI_BASE_URL,+ VAPI_ENDPOINTS,+ VapiEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60++REDACTED_VALUE = "[REDACTED]"++# Vapi list responses embed auth material inside otherwise-analytical rows: assistant/call+# `credentials` arrays (provider API keys), tool and server `headers` (commonly Authorization),+# webhook `secret`s, and Twilio auth fields on phone numbers. Redact them by key before rows+# reach the warehouse — anyone with warehouse read access can query synced columns. Bare+# `credentialId`/`credentialIds` are UUID references, not secrets, and are kept.+_SENSITIVE_EXACT_KEYS = frozenset({"credentials", "headers"})+_SENSITIVE_KEY_SUBSTRINGS = ("secret", "password", "authtoken", "apikey")+++def _is_sensitive_key(key: str) -> bool:+ lowered = key.lower()+ return lowered in _SENSITIVE_EXACT_KEYS or any(part in lowered for part in _SENSITIVE_KEY_SUBSTRINGS)+++def _scrub_sensitive_values(value: Any) -> Any:+ if isinstance(value, dict):+ return {k: REDACTED_VALUE if _is_sensitive_key(k) else _scrub_sensitive_values(v) for k, v in value.items()}+ if isinstance(value, list):+ return [_scrub_sensitive_values(item) for item in value]+ return value+++class VapiRetryableError(Exception):+ pass+++class VapiResumeConfig:+ # createdAt of the last row already yielded downstream. On resume, descending endpoints+ # request `createdAtLt=<cursor>` and ascending page endpoints restart at page 1 with+ # `createdAtGt=<cursor>` — both skip exactly the rows already delivered. A distinct row+ # sharing the boundary's millisecond timestamp would be skipped too; Vapi timestamps have+ # millisecond precision so collisions are vanishingly rare.+ created_at_cursor: str | None = None+++def _format_datetime_param(value: Any) -> str:+ """Format an incremental cursor as the ISO 8601 Z-suffixed string Vapi returns and accepts."""+ if isinstance(value, datetime):+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+ if isinstance(value, date):+ return _format_datetime_param(datetime.combine(value, datetime.min.time(), tzinfo=UTC))+ return str(value)+++def _make_session(api_key: str) -> requests.Session:+ # capture=False: Vapi response bodies carry secrets under names the sample-capture+ # scrubbers don't recognise (`credentials` arrays, `twilioAuthToken`, webhook `secret`,+ # header maps) — see `_scrub_sensitive_values`, which only protects the warehouse path.+ return make_tracked_session(+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ redact_values=(api_key,),+ capture=False,+ )+++@retry(+ retry=retry_if_exception_type(+ (+ VapiRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(session: requests.Session, url: str, logger: FilteringBoundLogger) -> Any:+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise VapiRetryableError(f"Vapi API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Vapi API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str) -> bool:+ url = f"{VAPI_BASE_URL}/assistant?{urlencode({'limit': 1})}"+ try:+ response = _make_session(api_key).get(url, timeout=REQUEST_TIMEOUT_SECONDS)+ return response.status_code == 200+ except Exception:+ return False+++def _last_created_at(table: pa.Table) -> str | None:+ if "createdAt" not in table.column_names:+ return None+ value = table.column("createdAt")[-1].as_py()+ return value if isinstance(value, str) else None+++def _fetch_created_at_desc_pages(+ session: requests.Session,+ config: VapiEndpointConfig,+ logger: FilteringBoundLogger,+ base_params: dict[str, Any],+ created_at_lt: str | None,+) -> Iterator[list[dict[str, Any]]]:+ """Walk a createdAt-descending array endpoint, cursoring with `createdAtLt`."""+ cursor = created_at_lt++ while True:+ params: dict[str, Any] = {**base_params, "limit": DEFAULT_PAGE_LIMIT}+ if cursor:+ # Overrides any createdAtLt in base_params: the cursor only ever moves further back.+ params["createdAtLt"] = cursor+ url = f"{VAPI_BASE_URL}{config.path}?{urlencode(params)}"++ rows = _fetch(session, url, logger)+ if not isinstance(rows, list) or len(rows) == 0:+ return++ yield rows++ if len(rows) < DEFAULT_PAGE_LIMIT:+ return++ cursor = rows[-1].get("createdAt")+ if not cursor:+ logger.warning(f"Vapi: {config.name} row missing createdAt, stopping pagination")+ return+++def _fetch_ascending_pages(+ session: requests.Session,+ config: VapiEndpointConfig,+ logger: FilteringBoundLogger,+ base_params: dict[str, Any],+) -> Iterator[list[dict[str, Any]]]:+ """Walk a `{results, metadata}` endpoint page by page in ascending createdAt order.++ ASC ordering keeps page boundaries stable under concurrent inserts (new rows land after the+ pages already read); rows deleted mid-sync can still shift a boundary, which merge tolerates.+ """+ page = 1++ while True:+ params: dict[str, Any] = {+ **base_params,+ "limit": DEFAULT_PAGE_LIMIT,+ "page": page,+ "sortOrder": "ASC",+ "sortBy": "createdAt",+ }+ url = f"{VAPI_BASE_URL}{config.path}?{urlencode(params)}"++ data = _fetch(session, url, logger)+ rows = data.get("results", []) if isinstance(data, dict) else data+ if not isinstance(rows, list) or len(rows) == 0:+ return++ yield rows++ metadata = data.get("metadata", {}) if isinstance(data, dict) else {}+ has_next = metadata.get("hasNextPage") if isinstance(metadata, dict) else None+ if has_next is False or (has_next is None and len(rows) < DEFAULT_PAGE_LIMIT):+ return++ page += 1+++def _drain(+ batcher: Batcher,+ resumable_source_manager: ResumableSourceManager[VapiResumeConfig],+ save_resume_state: bool,+ include_incomplete_chunk: bool = False,+) -> Iterator[pa.Table]:+ while batcher.should_yield(include_incomplete_chunk=include_incomplete_chunk):+ table = batcher.get_table()+ yield table++ # Save AFTER yielding, keyed to the last row actually delivered, so a crash re-yields+ # from the exact boundary instead of skipping rows still buffered in the batcher.+ if save_resume_state:+ cursor = _last_created_at(table)+ if cursor:+ resumable_source_manager.save_state(VapiResumeConfig(created_at_cursor=cursor))+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[VapiResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ db_incremental_field_earliest_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> Iterator[pa.Table]:+ config = VAPI_ENDPOINTS[endpoint]+ session = _make_session(api_key)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ resume_cursor = resume.created_at_cursor if resume is not None else None++ if config.pagination == "none":+ rows = _fetch(session, f"{VAPI_BASE_URL}{config.path}", logger)+ if isinstance(rows, list) and rows:+ batcher.batch(_scrub_sensitive_values(rows))+ yield from _drain(batcher, resumable_source_manager, save_resume_state=False, include_incomplete_chunk=True)+ return++ advertised_fields = {f["field"] for f in config.incremental_fields}+ cursor_field = incremental_field if incremental_field in advertised_fields else "createdAt"+ incremental_active = (+ should_use_incremental_field+ and bool(advertised_fields)+ and (db_incremental_field_last_value is not None or db_incremental_field_earliest_value is not None)+ )++ if config.pagination == "created_at_cursor":+ if not incremental_active:+ # Full walk (initial sync or full refresh) — resumable via the createdAtLt cursor.+ for rows in _fetch_created_at_desc_pages(session, config, logger, {}, resume_cursor):+ batcher.batch(_scrub_sensitive_values(rows))+ yield from _drain(batcher, resumable_source_manager, save_resume_state=True)+ yield from _drain(batcher, resumable_source_manager, save_resume_state=True, include_incomplete_chunk=True)+ return++ # Incremental on a descending source (Stripe-style): first finish any historical backfill+ # (rows older than the earliest value seen), then fetch rows newer than the watermark.+ # Both legs are bounded windows, so a retry just re-fetches them and merge dedupes —+ # no resume state is saved or honored here.+ if db_incremental_field_earliest_value is not None:+ earliest = _format_datetime_param(db_incremental_field_earliest_value)+ logger.debug(f"Vapi: {endpoint} backfilling {cursor_field}Lt={earliest}")+ for rows in _fetch_created_at_desc_pages(session, config, logger, {f"{cursor_field}Lt": earliest}, None):+ batcher.batch(_scrub_sensitive_values(rows))+ yield from _drain(batcher, resumable_source_manager, save_resume_state=False)++ if db_incremental_field_last_value is not None:+ last = _format_datetime_param(db_incremental_field_last_value)+ logger.debug(f"Vapi: {endpoint} fetching {cursor_field}Gt={last}")+ for rows in _fetch_created_at_desc_pages(session, config, logger, {f"{cursor_field}Gt": last}, None):+ batcher.batch(_scrub_sensitive_values(rows))+ yield from _drain(batcher, resumable_source_manager, save_resume_state=False)++ yield from _drain(batcher, resumable_source_manager, save_resume_state=False, include_incomplete_chunk=True)+ return++ # Page-number endpoints, walked in ascending createdAt order. The resume cursor (createdAt of+ # the last row yielded) narrows the window with `createdAtGt` and restarts at page 1, which is+ # exact regardless of how many pages the batcher had buffered. An incremental watermark uses+ # the same mechanism; the cursor always supersedes it since it can only be newer.+ base_params: dict[str, Any] = {}+ effective_gt = resume_cursor+ if effective_gt is None and incremental_active and db_incremental_field_last_value is not None:+ effective_gt = _format_datetime_param(db_incremental_field_last_value)+ if effective_gt:+ base_params["createdAtGt"] = effective_gt++ for rows in _fetch_ascending_pages(session, config, logger, base_params):+ batcher.batch(_scrub_sensitive_values(rows))+ yield from _drain(batcher, resumable_source_manager, save_resume_state=True)+ yield from _drain(batcher, resumable_source_manager, save_resume_state=True, include_incomplete_chunk=True)+++def vapi_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[VapiResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ db_incremental_field_earliest_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = VAPI_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ db_incremental_field_earliest_value=db_incremental_field_earliest_value,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ # created_at_cursor endpoints return newest-first, so the pipeline must track the+ # earliest/latest watermarks the Stripe way; page endpoints are requested ascending.+ sort_mode="desc" if config.pagination == "created_at_cursor" else "asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )