: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 elevenlabs import source (#70040)
Tom Owers160ca9d3fc4a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/canonical_descriptions.pyindex 37799d3b4bb7..9cb152d4710a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/canonical_descriptions.py@@ -1,127 +1,65 @@-"""Canonical, documentation-sourced descriptions for ElevenLabs endpoints and columns.--Sourced from the official ElevenLabs API reference (https://elevenlabs.io/docs/api-reference)-and the published OpenAPI spec (https://api.elevenlabs.io/openapi.json). Keyed by the endpoint-names in `settings.py` `ELEVENLABS_ENDPOINTS`, which match the `ExternalDataSchema.name` of a-synced ElevenLabs table. Columns absent here fall back to LLM enrichment.-"""-from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"history": {- "description": "A single speech generation (text-to-speech, speech-to-speech, or other audio product) with the input text, the voice and model used, and its character cost.",+ "description": "Text-to-speech and speech-to-speech generation history. One row per generated audio item.","docs_url": "https://elevenlabs.io/docs/api-reference/history/list","columns": {- "history_item_id": "Unique identifier for the history item.",- "request_id": "The ID of the request that produced this item.",- "voice_id": "The ID of the voice used for the generation.",- "voice_name": "The name of the voice used for the generation.",- "voice_category": "The category of the voice: premade, cloned, generated, or professional.",- "model_id": "The ID of the model used for the generation.",- "text": "The text used to generate the audio item.",- "date_unix": "Unix timestamp (seconds) of when the item was created.",- "character_count_change_from": "The account's character count before this generation.",- "character_count_change_to": "The account's character count after this generation; the difference is the character cost of the item.",- "content_type": "The content type of the generated item.",- "state": "The state of the history item.",- "settings": "The voice settings used for the generation.",- "feedback": "Feedback associated with the generated item, null if none was provided.",- "share_link_id": "The ID of the share link for the item, if shared.",- "source": "The product that generated the item: TTS (text to speech), STS (speech to speech), Projects, AN (audio native), and others.",- "alignments": "Character alignment timing data for the generated audio.",- "dialogue": "The voice and text pairs used to generate the audio when the item was created via dialogue mode.",- "output_format": "The output format the audio was originally generated in.",+ "history_item_id": "Unique identifier for the generated audio item.",+ "request_id": "Identifier of the request that produced this item.",+ "voice_id": "Identifier of the voice used for the generation.",+ "voice_name": "Display name of the voice used for the generation.",+ "model_id": "Identifier of the model used for the generation.",+ "text": "The text that was synthesized into audio.",+ "date_unix": "Creation time of the item, in Unix seconds.",+ "character_count_change_from": "Character quota counter before this generation.",+ "character_count_change_to": "Character quota counter after this generation.",+ "content_type": "MIME type of the generated audio.",+ "state": "Processing state of the history item.",+ "source": "How the item was generated (TTS, STS, or Flows).",},},"conversations": {- "description": "A conversational AI conversation summary: which agent handled the call, when it started, how long it lasted, its status, and evaluation results.",+ "description": "Conversational AI calls handled by your agents. One row per conversation.","docs_url": "https://elevenlabs.io/docs/api-reference/conversations/list","columns": {"conversation_id": "Unique identifier for the conversation.",- "agent_id": "The ID of the agent that handled the conversation.",- "agent_name": "The name of the agent that handled the conversation.",- "branch_id": "The ID of the agent branch used for the conversation.",- "version_id": "The ID of the agent version used for the conversation.",- "start_time_unix_secs": "Unix timestamp (seconds) of when the conversation started.",- "call_duration_secs": "Duration of the call in seconds.",+ "agent_id": "Identifier of the agent that handled the conversation.",+ "agent_name": "Display name of the agent that handled the conversation.",+ "start_time_unix_secs": "Start time of the call, in Unix seconds.",+ "call_duration_secs": "Duration of the call, in seconds.","message_count": "Number of messages exchanged in the conversation.",- "status": "Processing status of the conversation (e.g. initiated, in-progress, processing, done, failed).",- "termination_reason": "Why the conversation ended.",- "call_successful": "Result of the agent's success evaluation for the call: success, failure, or unknown.",- "call_success_score": "Numeric success score assigned to the call.",- "transcript_summary": "Generated summary of the conversation transcript.",- "call_summary_title": "Short generated title summarizing the call.",- "main_language": "Detected main language of the conversation (language code).",- "conversation_initiation_source": "The surface the conversation was initiated from (e.g. phone, widget).",- "tool_names": "Names of the tools the agent used during the call.",- "direction": "Telephony direction of the call: inbound or outbound.",- "rating": "Overall user rating of the conversation (1-5).",- "sentiment_analysis": "Sentiment analysis results for the conversation.",+ "status": "Lifecycle status of the conversation (initiated, in-progress, processing, done, failed).",+ "call_successful": "Whether the call was evaluated as successful (success, failure, unknown).",+ "transcript_summary": "Model-generated summary of the conversation transcript.",+ "direction": "Whether the call was inbound or outbound.",+ "sentiment_analysis": "Aggregate sentiment and frustration scores for the conversation.",},},"agents": {- "description": "A conversational AI agent configured in the workspace, with its tags, creation time, and access information.",+ "description": "Conversational AI agent configurations in your workspace. One row per agent.","docs_url": "https://elevenlabs.io/docs/api-reference/agents/list","columns": {"agent_id": "Unique identifier for the agent.",- "name": "The name of the agent.",- "tags": "Agent tags used to categorize the agent.",- "created_at_unix_secs": "Unix timestamp (seconds) of when the agent was created.",- "access_info": "The access information of the agent (creator, role).",- "last_call_time_unix_secs": "Unix timestamp (seconds) of the agent's most recent call, null if no calls have been made.",- "archived": "Whether the agent is archived.",+ "name": "Display name of the agent.",+ "tags": "Tags used to categorize the agent.",+ "created_at_unix_secs": "Creation time of the agent, in Unix seconds.",+ "last_call_time_unix_secs": "Time of the agent's most recent call, in Unix seconds.",+ "access_info": "Ownership and access metadata for the agent.",},},"voices": {- "description": "A voice available to the workspace: premade, cloned, generated, or professional, with its settings, labels, and sharing state.",+ "description": "Voices available in your workspace, including cloned, generated, and premade voices.","docs_url": "https://elevenlabs.io/docs/api-reference/voices/search","columns": {"voice_id": "Unique identifier for the voice.",- "name": "The name of the voice.",- "category": "The category of the voice: premade, cloned, generated, or professional.",- "description": "The description of the voice.",- "labels": "Labels associated with the voice (e.g. accent, age, gender).",- "samples": "List of audio samples associated with the voice.",- "settings": "The default generation settings of the voice.",- "sharing": "The sharing information of the voice.",- "fine_tuning": "Fine-tuning state and information for the voice.",- "preview_url": "URL of a preview audio clip for the voice.",- "available_for_tiers": "The subscription tiers the voice is available for.",- "high_quality_base_model_ids": "The base model IDs for high-quality renditions of this voice.",- "verified_languages": "The verified languages of the voice.",- "collection_ids": "The IDs of collections this voice belongs to.",- "is_owner": "Whether the voice is owned by the authenticated user.",- "is_legacy": "Whether the voice is a legacy voice.",- "is_mixed": "Whether the voice is a mixed voice.",- "created_at_unix": "Unix timestamp (seconds) of when the voice was created, null for older voices.",- "favorited_at_unix": "Unix timestamp (seconds) of when the voice was marked as favorite.",- "permission_on_resource": "The authenticated user's permission on the voice resource.",- },- },- "models": {- "description": "A speech model available on the account, with its capabilities, language support, and cost factor.",- "docs_url": "https://elevenlabs.io/docs/api-reference/models/list",- "columns": {- "model_id": "Unique identifier for the model.",- "name": "The name of the model.",- "description": "The description of the model.",- "can_be_finetuned": "Whether the model can be fine-tuned.",- "can_do_text_to_speech": "Whether the model can do text-to-speech.",- "can_do_voice_conversion": "Whether the model can do voice conversion.",- "can_use_style": "Whether the model supports style exaggeration.",- "can_use_speaker_boost": "Whether the model supports speaker boost.",- "serves_pro_voices": "Whether the model serves professional voices.",- "token_cost_factor": "The credit cost factor for the model.",- "requires_alpha_access": "Whether the model requires alpha access.",- "max_characters_request_free_user": "The maximum number of characters a free user can request per generation.",- "max_characters_request_subscribed_user": "The maximum number of characters a subscribed user can request per generation.",- "maximum_text_length_per_request": "The maximum length of text that can be requested for this model.",- "languages": "The languages supported by the model.",- "model_rates": "The billing rates for the model.",- "concurrency_group": "The concurrency group the model belongs to for rate limiting.",+ "name": "Display name of the voice.",+ "category": "Voice category (generated, cloned, premade, professional, famous, high_quality).",+ "created_at_unix": "Creation time of the voice, in Unix seconds (may be null for older voices).",+ "labels": "Descriptive labels attached to the voice (accent, age, gender, use case).",+ "description": "Free-text description of the voice.",},},}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/elevenlabs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/elevenlabs.pyindex 3adbc6e47e51..39ef448a1db5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/elevenlabs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/elevenlabs.py@@ -2,7 +2,6 @@ import dataclassesfrom collections.abc import Iteratorfrom datetime import UTC, date, datetimefrom typing import Any, Optional-from urllib.parse import urlencodeimport requestsfrom structlog.types import FilteringBoundLogger@@ -17,20 +16,21 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs)ELEVENLABS_BASE_URL = "https://api.elevenlabs.io"+REQUEST_TIMEOUT_SECONDS = 60-MAX_RETRIES = 5class ElevenLabsRetryableError(Exception):+ """Raised for 429 / 5xx responses so tenacity retries them; credential/4xx errors are not wrapped."""+pass@dataclasses.dataclassclass ElevenLabsResumeConfig:- # Opaque pagination cursor of the next page to fetch. Only the cursor is persisted — the- # request URL is rebuilt locally from the endpoint catalog, so tampered resume state can't- # redirect the credential-bearing request to another host.- cursor: str+ # Next-page cursor for whichever endpoint this job syncs. Only one endpoint runs per job, so a+ # single opaque cursor slot is enough; each endpoint sends it under its own cursor param.+ cursor: str | None = Nonedef _get_headers(api_key: str) -> dict[str, str]:@@ -40,87 +40,111 @@ def _get_headers(api_key: str) -> dict[str, str]:}-def _to_epoch(value: Any) -> Optional[int]:- """Coerce an incremental cursor value to a UNIX timestamp for ElevenLabs' time filters.+def _to_unix_seconds(value: Any) -> int:+ """Coerce an incremental watermark to Unix seconds for the API's `*_after_unix` filters.- ElevenLabs stores and filters timestamps as epoch seconds, so the persisted watermark is- already an int in the common case; datetimes are accepted defensively.+ The incremental field is declared as an integer (Unix seconds), so the pipeline normally hands+ back an int; datetime/date are handled defensively in case a stored value was coerced upstream."""- if value is None:- return None- if isinstance(value, bool):- return None- if isinstance(value, int):- return value- if isinstance(value, float):- return int(value)if isinstance(value, datetime):- dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)- return int(dt.timestamp())+ # A naive datetime's timestamp() would assume the server's local timezone, so pin it to UTC+ # to keep incremental boundaries identical across environments.+ if value.tzinfo is None:+ value = value.replace(tzinfo=UTC)+ return int(value.timestamp())if isinstance(value, date):- return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())- try:- return int(value)- except (TypeError, ValueError):- return None+ return int(datetime(value.year, value.month, value.day, tzinfo=UTC).timestamp())+ return int(value)-def _build_params(config: ElevenLabsEndpointConfig, watermark: Optional[int], cursor: Optional[str]) -> dict[str, Any]:- params: dict[str, Any] = {}- if config.page_size is not None:- params["page_size"] = config.page_size+def _build_params(+ config: ElevenLabsEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, Any]:+ """Build the constant per-request query params (page size, sort, server-side incremental filter).++ The cursor is added per page by the caller. The incremental filter is applied on every page (the+ API keeps the time-window filter alongside the cursor), so pagination terminates at `has_more`+ rather than re-walking full history each incremental run.+ """+ params: dict[str, Any] = {"page_size": config.page_size}params.update(config.extra_params)- if watermark is not None and config.incremental_param is not None:- params[config.incremental_param] = watermark- if cursor and config.cursor_param is not None:- params[config.cursor_param] = cursor- return params+ if (+ should_use_incremental_field+ and config.incremental_param+ and db_incremental_field_last_value is not None+ # `incremental_field` is the user's chosen cursor column; each endpoint exposes exactly one, so+ # only apply the server filter when it matches (or the caller didn't pin one).+ and (incremental_field is None or incremental_field == config.incremental_field)+ ):+ params[config.incremental_param] = _to_unix_seconds(db_incremental_field_last_value)++ return params-def _build_url(config: ElevenLabsEndpointConfig, params: dict[str, Any]) -> str:- if not params:- return f"{ELEVENLABS_BASE_URL}{config.path}"- return f"{ELEVENLABS_BASE_URL}{config.path}?{urlencode(params)}"+def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:+ """Probe the API key. 200 => valid. 401 => invalid key. 403 => valid key missing a scope.-def validate_credentials(api_key: str) -> bool:- """Confirm the API key is genuine with one cheap probe against /v1/user.+ At source-create (`schema_name=None`) a 403 is accepted: users may grant only the scopes for the+ endpoints they want, so a missing scope must not block connecting. When probing a specific schema+ a 403 is a genuine per-table scope error and is surfaced. Sync-time 403s are handled separately by+ `get_non_retryable_errors`.- ElevenLabs keys carry granular endpoint permissions and return 401 both for a fake key- (detail.status == "invalid_api_key") and for a real key missing the probed endpoint's- permission (detail.status == "missing_permissions"). A scoped-but-genuine key must pass- source-create — users may only grant the endpoints they intend to sync — so only an- invalid/unparseable 401 rejects.+ Any other status (429, 5xx, or an unexpected code) means the key was never actually verified, so+ validation fails rather than saving an unverified key as valid — the user can retry a transient blip."""+ config = ELEVENLABS_ENDPOINTS.get(schema_name) if schema_name else None+ probe_path = config.path if config else "/v1/user"+ url = f"{ELEVENLABS_BASE_URL}{probe_path}"+ params: dict[str, Any] = {"page_size": 1} if config else {}+try:- response = make_tracked_session(redact_values=(api_key,)).get(- f"{ELEVENLABS_BASE_URL}/v1/user", headers=_get_headers(api_key), timeout=10+ response = make_tracked_session(redact_values=(api_key,), allow_redirects=False).get(+ url, headers=_get_headers(api_key), params=params, timeout=10)- if response.status_code == 200:- return True- if response.status_code == 401:- try:- detail = response.json().get("detail", {})- except ValueError:- return False- status_text = detail.get("status") if isinstance(detail, dict) else None- return status_text == "missing_permissions"- return Falseexcept Exception:- return False+ return False, "Could not reach the ElevenLabs API. Please try again."++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid ElevenLabs API key"+ if response.status_code == 403:+ if schema_name is None:+ return True, None+ return False, f"Your ElevenLabs API key is missing the permission required to sync `{schema_name}`."+ # A 429/5xx/unexpected status leaves the key unverified. Don't accept it — surface it so the user+ # can retry, rather than saving a source that only fails on its first sync.+ return False, f"Could not verify the ElevenLabs API key (status {response.status_code}). Please try again."@retry(- retry=retry_if_exception_type((ElevenLabsRetryableError, requests.ReadTimeout, requests.ConnectionError)),- stop=stop_after_attempt(MAX_RETRIES),+ retry=retry_if_exception_type(+ (+ ElevenLabsRetryableError,+ 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, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:- response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)+def _fetch_page(+ session: requests.Session,+ url: str,+ params: dict[str, Any],+ headers: dict[str, str],+ logger: FilteringBoundLogger,+) -> dict:+ response = session.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)- # ElevenLabs rate limiting is concurrency-based per plan tier; a 429 clears as soon as- # in-flight requests drain, so exponential backoff is sufficient.+ # ElevenLabs rate limiting is concurrency-based per plan; a 429 clears once in-flight requests+ # drain, so back off and retry. 5xx are transient server faults.if response.status_code == 429 or response.status_code >= 500:raise ElevenLabsRetryableError(f"ElevenLabs API error (retryable): status={response.status_code}, url={url}")@@ -142,53 +166,42 @@ def get_rows() -> Iterator[list[dict[str, Any]]]:config = ELEVENLABS_ENDPOINTS[endpoint]headers = _get_headers(api_key)- # One session reused across every page so urllib3 keeps the connection alive instead of- # re-handshaking per request.- session = make_tracked_session(redact_values=(api_key,))+ # One session reused across pages so urllib3 keeps the connection alive instead of re-handshaking.+ # Redact the key so it can't leak into captured HTTP samples or logged URLs. Don't follow redirects:+ # requests preserves the custom `xi-api-key` header across a cross-origin 3xx, so a redirect off the+ # fixed API host could replay the key to another origin — fail the request instead.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)+ url = f"{ELEVENLABS_BASE_URL}{config.path}"- watermark = _to_epoch(db_incremental_field_last_value) if should_use_incremental_field else None- guard_field = incremental_field or (config.incremental_fields[0]["field"] if config.incremental_fields else None)+ params = _build_params(config, should_use_incremental_field, db_incremental_field_last_value, incremental_field)resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None- cursor: str | None = resume.cursor if resume is not None else None+ cursor = resume.cursor if resume is not None else Noneif cursor:- logger.debug(f"ElevenLabs: resuming {endpoint} from cursor: {cursor}")+ logger.debug(f"ElevenLabs: resuming {endpoint} from cursor")while True:- url = _build_url(config, _build_params(config, watermark, cursor))- data = _fetch(session, url, headers, logger)-- items = data if config.data_key is None else (data.get(config.data_key) or [])- if not items:- break+ page_params = dict(params)+ if cursor:+ page_params[config.cursor_param] = cursor- yield items+ data = _fetch_page(session, url, page_params, headers, logger)- if config.data_key is None or config.cursor_param is None:- # The whole collection arrives in one response (models) — nothing to paginate.- break+ items = data.get(config.items_key) or []+ if items:+ # Yield the rows in the shape the API returns them; the pipeline batches and merges on the+ # endpoint's primary key.+ yield itemsnext_cursor = data.get(config.cursor_response_key)- if not data.get("has_more") or not next_cursor:+ has_more = bool(data.get("has_more"))+ if not has_more or not next_cursor:break- # Belt-and-braces stop for descending incremental endpoints: the server-side time- # filter is documented but couldn't be smoke-tested without credentials. If it were- # silently ignored, cursor pagination would otherwise walk the full history on every- # incremental sync — so stop once an entire page predates the watermark. (Never applied- # to ascending endpoints, where old rows arrive first by design.)- if watermark is not None and config.sort_mode == "desc" and guard_field is not None:- page_max = max(- (ts for ts in (_to_epoch(item.get(guard_field)) for item in items) if ts is not None),- default=None,- )- if page_max is not None and page_max < watermark:- break-- # Save AFTER yielding the page so a crash re-yields the just-finished page rather than- # skipping it — merge dedupes on the primary key. Resume picks up at the next page.- cursor = next_cursor+ # Save state AFTER yielding so a crash re-yields the last page rather than skipping it; merge+ # dedupes the re-pulled rows on the primary key.resumable_source_manager.save_state(ElevenLabsResumeConfig(cursor=next_cursor))+ cursor = next_cursordef elevenlabs_source(@@ -213,11 +226,11 @@ def elevenlabs_source(db_incremental_field_last_value=db_incremental_field_last_value,incremental_field=incremental_field,),- primary_keys=[config.primary_key],+ primary_keys=config.primary_keys,+ sort_mode=config.sort_mode, # type: ignore[arg-type]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,- sort_mode=config.sort_mode,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[config.partition_key],)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/settings.pyindex 93d1bfe39c6e..34fcff01725e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/settings.py@@ -1,134 +1,119 @@from dataclasses import dataclass, fieldfrom typing import Optional-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SortModefrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType@dataclassclass ElevenLabsEndpointConfig:name: str- # List endpoint path, relative to the API base URL.+ # Path appended to ELEVENLABS_BASE_URL, including the API version (v1/v2 differ per endpoint).path: str- # Key the list of objects is nested under in the response body (e.g. {"history": [...]}).- # None means the response body itself is the list (models).- data_key: Optional[str]- primary_key: str- # ElevenLabs mixes three cursor styles across endpoint families, so both sides of the- # cursor round-trip are declared per endpoint: the request query param we send the cursor- # in, and the response body key the next cursor comes back under. None = no pagination.- cursor_param: Optional[str] = None- cursor_response_key: Optional[str] = None- page_size: Optional[int] = None- # Server-side incremental filter query param, taking a unix-seconds timestamp. None means- # the endpoint has no server-side timestamp filter and syncs as full refresh only.+ # Top-level array key in the JSON response body (differs per endpoint: history/conversations/...).+ items_key: str+ # Query param used to request the next page, and the response field that carries the next cursor.+ # ElevenLabs uses three different cursor styles across endpoint families.+ cursor_param: str+ cursor_response_key: str+ primary_keys: list[str]+ page_size: int+ partition_key: str+ # Stable, monotonic incremental column and the server-side filter param that bounds it. Both None+ # for full-refresh endpoints (agents/voices expose no updated-since filter).+ incremental_field: Optional[str] = Noneincremental_param: Optional[str] = None- # Static query params sent on every request (e.g. an explicit sort direction).+ # "asc" checkpoints the watermark after every batch; "desc" defers it to successful job end. Must+ # match the order rows actually arrive in for the endpoint.+ sort_mode: str = "asc"+ # Conversations are mutable (status/summary/sentiment fill in after the call), so they must merge+ # rather than append; immutable history items may append.+ supports_append: bool = False+ should_sync_default: bool = True+ # Constant query params merged into every request (sort direction, summary mode, ...).extra_params: dict[str, str] = field(default_factory=dict)- sort_mode: SortMode = "desc"- # Field used to partition the warehouse table. Must be a stable creation timestamp,- # never an updated_at-style field that rewrites partitions on every sync.- partition_key: Optional[str] = None- incremental_fields: list[IncrementalField] = field(default_factory=list)- schema_description: Optional[str] = None-# ElevenLabs timestamps are UNIX epoch seconds, so candidate incremental fields are stored as-# integers even though the UI presents them as datetimes. Incremental sync is only enabled-# where the API documents a server-side timestamp filter that lines up with a stable field on-# the returned rows (history -> date_after_unix filters on date_unix, conversations ->-# call_start_after_unix filters on start_time_unix_secs). Everything else is full refresh.-#-# The timestamp filters are taken from the published OpenAPI spec (date_after_unix is-# documented inclusive); they could not be smoke-tested against the live API without-# credentials, so the descending endpoints also carry a client-side watermark stop in the-# transport as a belt-and-braces guard (see elevenlabs.py).+def _int_incremental_field(name: str) -> list[IncrementalField]:+ return [+ {+ "label": name,+ "type": IncrementalFieldType.Integer,+ "field": name,+ "field_type": IncrementalFieldType.Integer,+ }+ ]++ELEVENLABS_ENDPOINTS: dict[str, ElevenLabsEndpointConfig] = {+ # Text-to-speech / speech-to-speech generation history. Immutable per-generation records, filtered+ # server-side by `date_after_unix` (inclusive) and returned ascending via `sort_direction=asc`."history": ElevenLabsEndpointConfig(name="history",path="/v1/history",- data_key="history",- primary_key="history_item_id",+ items_key="history",cursor_param="start_after_history_item_id",cursor_response_key="last_history_item_id",+ primary_keys=["history_item_id"],page_size=1000,+ partition_key="date_unix",+ incremental_field="date_unix",incremental_param="date_after_unix",- # Ascending creation order keeps already-fetched pages stable and lets the incremental- # watermark advance monotonically as pages are yielded.- extra_params={"sort_direction": "asc"},sort_mode="asc",- partition_key="date_unix",- incremental_fields=[- {- "label": "date_unix",- "type": IncrementalFieldType.DateTime,- "field": "date_unix",- "field_type": IncrementalFieldType.Integer,- },- ],- schema_description="Speech generation history items: the text, voice, model, and character cost of each generation.",+ supports_append=True,+ extra_params={"sort_direction": "asc"},),+ # Conversational AI calls. Mutable (status transitions, transcript summary and sentiment land after+ # the call completes) so they merge, never append. Cursor pagination exposes no sort param; the+ # default is newest-first, so we report "desc" and let the server-side `call_start_after_unix`+ # filter bound the set on incremental runs. `summary_mode=include` pulls the summary/sentiment."conversations": ElevenLabsEndpointConfig(name="conversations",path="/v1/convai/conversations",- data_key="conversations",- primary_key="conversation_id",+ items_key="conversations",cursor_param="cursor",cursor_response_key="next_cursor",+ primary_keys=["conversation_id"],page_size=100,+ partition_key="start_time_unix_secs",+ incremental_field="start_time_unix_secs",incremental_param="call_start_after_unix",- # The conversations list has no sort parameter and returns newest-first.sort_mode="desc",- partition_key="start_time_unix_secs",- incremental_fields=[- {- "label": "start_time_unix_secs",- "type": IncrementalFieldType.DateTime,- "field": "start_time_unix_secs",- "field_type": IncrementalFieldType.Integer,- },- ],- schema_description="Conversational AI conversations: duration, status, call success, message counts, and summaries.",+ supports_append=False,+ extra_params={"summary_mode": "include"},),+ # Conversational AI agent configs. Small, mutable table with no updated-since filter, so full+ # refresh only. Ordered ascending by creation for stable pagination."agents": ElevenLabsEndpointConfig(name="agents",path="/v1/convai/agents",- data_key="agents",- primary_key="agent_id",+ items_key="agents",cursor_param="cursor",cursor_response_key="next_cursor",+ primary_keys=["agent_id"],page_size=100,- # No server-side timestamp filter — full refresh only. Newest-first by default.- sort_mode="desc",partition_key="created_at_unix_secs",- schema_description="Conversational AI agents configured in the workspace.",+ sort_mode="asc",+ extra_params={"sort_by": "created_at", "sort_direction": "asc"},),+ # Voice library. Small, mutable table with no updated-since filter, so full refresh only. v2 uses a+ # `next_page_token` cursor; `created_at_unix` may be null for older voices (bucketed as epoch 0)."voices": ElevenLabsEndpointConfig(name="voices",path="/v2/voices",- data_key="voices",- primary_key="voice_id",+ items_key="voices",cursor_param="next_page_token",cursor_response_key="next_page_token",+ primary_keys=["voice_id"],page_size=100,- # No server-side timestamp filter — full refresh only. created_at_unix is nullable on- # older/premade voices, so the table is not partitioned on it.- sort_mode="desc",- schema_description="Voices available to the workspace, including cloned and professional voices.",- ),- "models": ElevenLabsEndpointConfig(- name="models",- path="/v1/models",- data_key=None,- primary_key="model_id",- # Small static catalog returned as a bare list in a single response — no pagination.- sort_mode="desc",- schema_description="Speech models available on the account, with capabilities and cost factors.",+ partition_key="created_at_unix",+ sort_mode="asc",+ extra_params={"sort": "created_at_unix", "sort_direction": "asc"},),}ENDPOINTS = tuple(ELEVENLABS_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {- name: config.incremental_fields for name, config in ELEVENLABS_ENDPOINTS.items() if config.incremental_fields+ name: (_int_incremental_field(config.incremental_field) if config.incremental_field else [])+ for name, config in ELEVENLABS_ENDPOINTS.items()}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/source.pyindex 9f37d1cde4a7..f20ad312e17a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/source.py@@ -21,7 +21,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.regfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.elevenlabs import (- ELEVENLABS_BASE_URL,ElevenLabsResumeConfig,elevenlabs_source,validate_credentials as validate_elevenlabs_credentials,@@ -50,13 +49,15 @@ class ElevenLabsSource(ResumableSource[ElevenLabsSourceConfig, ElevenLabsResumeCcategory=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="ElevenLabs",releaseStatus=ReleaseStatus.ALPHA,- caption=(- "Enter your ElevenLabs API key to sync your speech generation history, conversational AI "- "conversations and agents, voices, and models into the PostHog Data warehouse. Create a key under "- "[Profile → API keys](https://elevenlabs.io/app/settings/api-keys).\n\n"- "If the key uses restricted permissions, grant read access to the endpoints you want to sync: "- "**History**, **Conversational AI**, **Voices**, **Models**, and **User** (used to verify the key)."- ),+ caption="""Enter your ElevenLabs API key to sync your ElevenLabs data into the PostHog Data warehouse.++You can create an API key in your [ElevenLabs account settings](https://elevenlabs.io/app/settings/api-keys).++Grant the following read permissions when creating the key:+- **History** (text-to-speech generation history)+- **Conversational AI** (conversations and agents)+- **Voices**+""",iconPath="/static/services/elevenlabs.svg",docsUrl="https://posthog.com/docs/cdp/sources/elevenlabs",keywords=["ai", "voice", "audio", "text-to-speech", "conversational ai"],@@ -68,7 +69,7 @@ class ElevenLabsSource(ResumableSource[ElevenLabsSourceConfig, ElevenLabsResumeClabel="API key",type=SourceFieldInputConfigType.PASSWORD,required=True,- placeholder="",+ placeholder="sk_...",secret=True,),],@@ -84,55 +85,49 @@ class ElevenLabsSource(ResumableSource[ElevenLabsSourceConfig, ElevenLabsResumeCdef get_non_retryable_errors(self) -> dict[str, str | None]:return {- f"401 Client Error: Unauthorized for url: {ELEVENLABS_BASE_URL}": (- "Your ElevenLabs API key is invalid, has been revoked, or lacks the permission for this endpoint. "- "Check the key's permissions under Profile → API keys in ElevenLabs, then reconnect."- ),- f"403 Client Error: Forbidden for url: {ELEVENLABS_BASE_URL}": (- "Your ElevenLabs API key does not have access to this endpoint. "- "Check the key's permissions under Profile → API keys in ElevenLabs, then reconnect."- ),+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.+ # Retrying can never satisfy a credential/permission problem, so fail the sync. Match the+ # stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.elevenlabs.io": "Your ElevenLabs API key is invalid or has been revoked. Create a new key in your ElevenLabs account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.elevenlabs.io": "Your ElevenLabs API key is missing the read permissions needed to sync this data. Grant the required read scopes in your ElevenLabs account settings, then reconnect.",}def get_schemas(self,- config: ElevenLabsSourceConfig,+ config: "ElevenLabsSourceConfig",team_id: int,with_counts: bool = False,names: list[str] | None = None,force_refresh: bool = False,) -> list[SourceSchema]:- schemas = [- SourceSchema(+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = ELEVENLABS_ENDPOINTS[endpoint]+ has_incremental = endpoint_config.incremental_param is not None+ return SourceSchema(name=endpoint,- supports_incremental=ELEVENLABS_ENDPOINTS[endpoint].incremental_param is not None,- supports_append=ELEVENLABS_ENDPOINTS[endpoint].incremental_param is not None,+ supports_incremental=has_incremental,+ supports_append=endpoint_config.supports_append,incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),- description=ELEVENLABS_ENDPOINTS[endpoint].schema_description,+ should_sync_default=endpoint_config.should_sync_default,)- for endpoint in ENDPOINTS- ]+ 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 schemasdef validate_credentials(- self, config: ElevenLabsSourceConfig, team_id: int, schema_name: Optional[str] = None+ self, config: "ElevenLabsSourceConfig", team_id: int, schema_name: Optional[str] = None) -> tuple[bool, str | None]:- if validate_elevenlabs_credentials(config.api_key):- return True, None-- return False, "Invalid ElevenLabs API key"+ return validate_elevenlabs_credentials(config.api_key, schema_name)def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ElevenLabsResumeConfig]:return ResumableSourceManager[ElevenLabsResumeConfig](inputs, ElevenLabsResumeConfig)def source_for_pipeline(self,- config: ElevenLabsSourceConfig,+ config: "ElevenLabsSourceConfig",resumable_source_manager: ResumableSourceManager[ElevenLabsResumeConfig],inputs: SourceInputs,) -> SourceResponse:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/tests/test_elevenlabs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/tests/test_elevenlabs.pyindex 60f46d0eabb3..e2038fdc61bb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/tests/test_elevenlabs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/tests/test_elevenlabs.py@@ -1,358 +1,260 @@+import os+import timefrom datetime import UTC, date, datetimefrom typing import Any-from urllib.parse import parse_qs, urlsplit-from unittest import mock+import pytest+from unittest.mock import MagicMock, patch+import requestsfrom parameterized import parameterized+from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs import elevenlabsfrom products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.elevenlabs import (ElevenLabsResumeConfig,- _to_epoch,+ _build_params,+ _to_unix_seconds,elevenlabs_source,get_rows,validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.settings import ENDPOINTS--TRACKED_SESSION_PATH = (- "products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.elevenlabs.make_tracked_session"-)+from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.settings import ELEVENLABS_ENDPOINTS-def _make_manager(resume_state: ElevenLabsResumeConfig | None = None) -> mock.MagicMock:- manager = mock.MagicMock()- manager.can_resume.return_value = resume_state is not None- manager.load_state.return_value = resume_state- return manager+class _FakeResumableManager:+ def __init__(self, state: ElevenLabsResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[ElevenLabsResumeConfig] = []+ def can_resume(self) -> bool:+ return self._state is not None-def _resp(json_body: Any, status: int = 200) -> mock.MagicMock:- resp = mock.MagicMock()- resp.json.return_value = json_body- resp.status_code = status- resp.ok = status < 400- return resp+ def load_state(self) -> ElevenLabsResumeConfig | None:+ return self._state+ def save_state(self, data: ElevenLabsResumeConfig) -> None:+ self.saved.append(data)-def _requests(mock_session: mock.MagicMock) -> list[tuple[str, dict[str, list[str]]]]:- """Return (path, parsed query params) for every GET the transport issued."""- calls = []- for call in mock_session.return_value.get.call_args_list:- url = call.args[0]- parts = urlsplit(url)- calls.append((parts.path, parse_qs(parts.query)))- return calls--class TestToEpoch:+class TestToUnixSeconds:@parameterized.expand([- ("none", None, None),- ("bool_true", True, None),- ("int", 1700000000, 1700000000),- ("float", 1700000000.9, 1700000000),+ ("int_passthrough", 1700000000, 1700000000),+ ("datetime", datetime(2024, 1, 1, tzinfo=UTC), 1704067200),("numeric_string", "1700000000", 1700000000),- ("non_numeric_string", "not-a-number", None),- ("aware_datetime", datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000),- ("date", date(2023, 11, 14), 1699920000),])- def test_to_epoch(self, _name: str, value: Any, expected: int | None) -> None:- assert _to_epoch(value) == expected---class TestValidateCredentials:+ def test_to_unix_seconds(self, _name: str, value: Any, expected: int) -> None:+ assert _to_unix_seconds(value) == expected++ def test_naive_values_are_interpreted_as_utc_regardless_of_server_tz(self) -> None:+ # A local-time interpretation would shift the incremental watermark by the server's UTC offset,+ # so the same date would sync different windows on different machines. Force a non-UTC zone and+ # assert both a `date` and a naive `datetime` still resolve to the UTC epoch.+ original_tz = os.environ.get("TZ")+ os.environ["TZ"] = "America/New_York"+ time.tzset()+ try:+ assert _to_unix_seconds(date(2024, 1, 1)) == 1704067200+ assert _to_unix_seconds(datetime(2024, 1, 1)) == 1704067200+ finally:+ if original_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = original_tz+ time.tzset()+++class TestBuildParams:+ def test_history_incremental_sets_date_after_unix_and_asc_sort(self) -> None:+ # Wrong param name / dropped filter would silently turn every incremental sync into a full refresh.+ params = _build_params(ELEVENLABS_ENDPOINTS["history"], True, 1700000000, "date_unix")+ assert params["date_after_unix"] == 1700000000+ assert params["sort_direction"] == "asc"+ assert params["page_size"] == 1000++ def test_first_sync_applies_no_incremental_filter(self) -> None:+ # A None watermark must not build date_after_unix=None; first sync pulls full history.+ params = _build_params(ELEVENLABS_ENDPOINTS["history"], True, None, "date_unix")+ assert "date_after_unix" not in params++ def test_conversations_incremental_uses_call_start_after_unix_with_summary(self) -> None:+ params = _build_params(ELEVENLABS_ENDPOINTS["conversations"], True, 1700000000, "start_time_unix_secs")+ assert params["call_start_after_unix"] == 1700000000+ assert params["summary_mode"] == "include"++ @parameterized.expand([("agents",), ("voices",)])+ def test_full_refresh_endpoints_never_send_a_time_filter(self, endpoint: str) -> None:+ # Full-refresh endpoints have no server-side updated-since filter; sending one would 4xx.+ params = _build_params(ELEVENLABS_ENDPOINTS[endpoint], True, 1700000000, "created_at_unix")+ assert not any("after_unix" in key for key in params)++ def test_mismatched_incremental_field_does_not_filter(self) -> None:+ # The user's chosen cursor column must gate the filter, not the endpoint default.+ params = _build_params(ELEVENLABS_ENDPOINTS["history"], True, 1700000000, "something_else")+ assert "date_after_unix" not in params+++class TestFetchPageRetries:@parameterized.expand([- ("ok_200", 200, {}, True),- # A genuine key that merely lacks the user_read permission must pass source-create.- ("missing_permissions", 401, {"detail": {"status": "missing_permissions", "message": "..."}}, True),- ("invalid_api_key", 401, {"detail": {"status": "invalid_api_key", "message": "..."}}, False),- ("unexpected_detail_shape", 401, {"detail": "unexpected shape"}, False),- ("forbidden", 403, {}, False),- ("server_error", 500, {}, False),+ ("rate_limited", 429),+ ("server_error", 500),+ ("bad_gateway", 502),])- @mock.patch(TRACKED_SESSION_PATH)- def test_status_mapping(- self, _name: str, status_code: int, body: dict[str, Any], expected: bool, mock_session: mock.MagicMock- ) -> None:- mock_session.return_value.get.return_value = _resp(body, status=status_code)- assert validate_credentials("key") is expected+ def test_retryable_status_codes_are_retried(self, _name: str, status_code: int) -> None:+ retryable = MagicMock(status_code=status_code, ok=False)+ good = MagicMock(status_code=200, ok=True)+ good.json.return_value = {"history": []}+ session = MagicMock()+ session.get.side_effect = [retryable, good]- @mock.patch(TRACKED_SESSION_PATH)- def test_swallows_exceptions(self, mock_session: mock.MagicMock) -> None:- mock_session.return_value.get.side_effect = Exception("boom")- assert validate_credentials("key") is False+ with patch.object(elevenlabs._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = elevenlabs._fetch_page(session, "https://api.elevenlabs.io/v1/history", {}, {}, MagicMock())- @mock.patch(TRACKED_SESSION_PATH)- def test_non_json_401_is_invalid(self, mock_session: mock.MagicMock) -> None:- resp = _resp({}, status=401)- resp.json.side_effect = ValueError("not json")- mock_session.return_value.get.return_value = resp- assert validate_credentials("key") is False+ assert result == {"history": []}+ assert session.get.call_count == 2--class TestGetRowsPagination:@parameterized.expand([- (- "history",- "history",- "start_after_history_item_id",- {"history": [{"history_item_id": "h2"}], "last_history_item_id": "h2", "has_more": False},- ),- (- "conversations",- "conversations",- "cursor",- {"conversations": [{"conversation_id": "c2"}], "next_cursor": None, "has_more": False},- ),- (- "agents",- "agents",- "cursor",- {"agents": [{"agent_id": "a2"}], "next_cursor": None, "has_more": False},- ),- (- "voices",- "voices",- "next_page_token",- {"voices": [{"voice_id": "v2"}], "next_page_token": None, "has_more": False},- ),+ ("read_timeout", requests.ReadTimeout("Read timed out.")),+ ("connection_error", requests.ConnectionError("Connection reset by peer")),+ ("chunked", requests.exceptions.ChunkedEncodingError("Connection broken")),])- @mock.patch(TRACKED_SESSION_PATH)- def test_each_cursor_style_paginates_with_its_own_params(- self,- endpoint: str,- data_key: str,- cursor_param: str,- page_two_body: dict[str, Any],- mock_session: mock.MagicMock,- ) -> None:- cursor_response_key = {- "history": "last_history_item_id",- "conversations": "next_cursor",- "agents": "next_cursor",- "voices": "next_page_token",- }[endpoint]- page_one = {data_key: [{"id": "first"}], cursor_response_key: "cursor-1", "has_more": True}- mock_session.return_value.get.side_effect = [_resp(page_one), _resp(page_two_body)]-- manager = _make_manager()- batches = list(get_rows("key", endpoint, mock.MagicMock(), manager))-- assert len(batches) == 2- requests = _requests(mock_session)- # First request carries no cursor; the second passes the returned cursor back in the- # endpoint family's own query param.- assert cursor_param not in requests[0][1]- assert requests[1][1][cursor_param] == ["cursor-1"]- # State is saved once, after the first page was yielded, pointing at page two.- manager.save_state.assert_called_once()- assert manager.save_state.call_args.args[0].cursor == "cursor-1"-- @mock.patch(TRACKED_SESSION_PATH)- def test_models_bare_list_single_fetch(self, mock_session: mock.MagicMock) -> None:- mock_session.return_value.get.return_value = _resp([{"model_id": "eleven_v3"}])-- manager = _make_manager()- batches = list(get_rows("key", "models", mock.MagicMock(), manager))-- assert batches == [[{"model_id": "eleven_v3"}]]- assert mock_session.return_value.get.call_count == 1- manager.save_state.assert_not_called()-- @mock.patch(TRACKED_SESSION_PATH)- def test_stops_when_has_more_false_even_with_cursor_present(self, mock_session: mock.MagicMock) -> None:- # /v1/history always echoes last_history_item_id; without the has_more check the- # transport would refetch the last page forever.- body = {"history": [{"history_item_id": "h1"}], "last_history_item_id": "h1", "has_more": False}- mock_session.return_value.get.return_value = _resp(body)-- batches = list(get_rows("key", "history", mock.MagicMock(), _make_manager()))-- assert len(batches) == 1- assert mock_session.return_value.get.call_count == 1-- @mock.patch(TRACKED_SESSION_PATH)- def test_empty_page_yields_nothing(self, mock_session: mock.MagicMock) -> None:- mock_session.return_value.get.return_value = _resp({"history": [], "has_more": False})-- batches = list(get_rows("key", "history", mock.MagicMock(), _make_manager()))-- assert batches == []-- @mock.patch(TRACKED_SESSION_PATH)- def test_resumes_from_saved_cursor(self, mock_session: mock.MagicMock) -> None:- body = {"conversations": [{"conversation_id": "c9"}], "next_cursor": None, "has_more": False}- mock_session.return_value.get.return_value = _resp(body)-- manager = _make_manager(ElevenLabsResumeConfig(cursor="saved-cursor"))- batches = list(get_rows("key", "conversations", mock.MagicMock(), manager))-- assert [row["conversation_id"] for batch in batches for row in batch] == ["c9"]- requests = _requests(mock_session)- assert requests[0][1]["cursor"] == ["saved-cursor"]---class TestGetRowsIncremental:- @mock.patch(TRACKED_SESSION_PATH)- def test_history_passes_server_side_filter_and_ascending_sort(self, mock_session: mock.MagicMock) -> None:- body = {"history": [{"history_item_id": "h1", "date_unix": 1700000100}], "has_more": False}- mock_session.return_value.get.return_value = _resp(body)-- list(- get_rows(- "key",- "history",- mock.MagicMock(),- _make_manager(),- should_use_incremental_field=True,- db_incremental_field_last_value=1700000000,- incremental_field="date_unix",- )+ def test_transient_network_errors_are_retried(self, _name: str, transient: Exception) -> None:+ good = MagicMock(status_code=200, ok=True)+ good.json.return_value = {"history": []}+ session = MagicMock()+ session.get.side_effect = [transient, good]++ with patch.object(elevenlabs._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = elevenlabs._fetch_page(session, "https://api.elevenlabs.io/v1/history", {}, {}, MagicMock())++ assert result == {"history": []}+ assert session.get.call_count == 2++ def test_credential_error_raises_without_retry(self) -> None:+ # 401 is a credential problem; retrying wastes the whole retry budget on a doomed request.+ resp = MagicMock(status_code=401, ok=False, text="unauthorized")+ resp.raise_for_status.side_effect = requests.HTTPError(+ "401 Client Error: Unauthorized for url: https://api.elevenlabs.io/v1/history", response=resp)+ session = MagicMock()+ session.get.return_value = resp++ with pytest.raises(requests.HTTPError):+ elevenlabs._fetch_page(session, "https://api.elevenlabs.io/v1/history", {}, {}, MagicMock())++ assert session.get.call_count == 1- _, params = _requests(mock_session)[0]- assert params["date_after_unix"] == ["1700000000"]- assert params["sort_direction"] == ["asc"]-- @mock.patch(TRACKED_SESSION_PATH)- def test_conversations_passes_call_start_after_unix(self, mock_session: mock.MagicMock) -> None:- body = {"conversations": [], "has_more": False}- mock_session.return_value.get.return_value = _resp(body)-- list(- get_rows(- "key",- "conversations",- mock.MagicMock(),- _make_manager(),- should_use_incremental_field=True,- db_incremental_field_last_value=1700000000,- incremental_field="start_time_unix_secs",- )- )- _, params = _requests(mock_session)[0]- assert params["call_start_after_unix"] == ["1700000000"]-- @mock.patch(TRACKED_SESSION_PATH)- def test_descending_pagination_stops_once_page_predates_watermark(self, mock_session: mock.MagicMock) -> None:- # If ElevenLabs silently ignored call_start_after_unix, cursor pagination would walk the- # full conversation history on every incremental sync. The client-side guard must stop- # after the first page that is entirely older than the watermark.- stale_page = {- "conversations": [{"conversation_id": "old", "start_time_unix_secs": 1600000000}],- "next_cursor": "more",- "has_more": True,+class TestGetRowsPagination:+ @staticmethod+ def _run(manager: _FakeResumableManager, pages: dict[Any, dict], **incremental: Any) -> list[dict]:+ def fake_fetch(session: Any, url: str, params: dict, headers: dict, logger: Any) -> dict:+ return pages[params.get("start_after_history_item_id")]++ with patch.object(elevenlabs, "_fetch_page", fake_fetch):+ return [+ row+ for batch in get_rows("k", "history", MagicMock(), manager, **incremental) # type: ignore[arg-type]+ for row in batch+ ]++ def test_walks_cursor_pages_and_saves_state_after_each_yield(self) -> None:+ pages = {+ None: {"history": [{"history_item_id": "a"}], "has_more": True, "last_history_item_id": "a"},+ "a": {"history": [{"history_item_id": "b"}], "has_more": False, "last_history_item_id": "b"},}- mock_session.return_value.get.return_value = _resp(stale_page)-- batches = list(- get_rows(- "key",- "conversations",- mock.MagicMock(),- _make_manager(),- should_use_incremental_field=True,- db_incremental_field_last_value=1700000000,- incremental_field="start_time_unix_secs",- )- )+ manager = _FakeResumableManager()+ rows = self._run(manager, pages)- # The stale page is still yielded (merge dedupes it) but pagination stops there.- assert len(batches) == 1- assert mock_session.return_value.get.call_count == 1-- @mock.patch(TRACKED_SESSION_PATH)- def test_descending_pagination_keeps_walking_without_watermark(self, mock_session: mock.MagicMock) -> None:- pages = [- _resp(- {- "conversations": [{"conversation_id": "new", "start_time_unix_secs": 1700000000}],- "next_cursor": "c1",- "has_more": True,- }- ),- _resp(- {- "conversations": [{"conversation_id": "old", "start_time_unix_secs": 1600000000}],- "next_cursor": None,- "has_more": False,- }- ),- ]- mock_session.return_value.get.side_effect = pages-- batches = list(get_rows("key", "conversations", mock.MagicMock(), _make_manager()))-- assert len(batches) == 2-- @mock.patch(TRACKED_SESSION_PATH)- def test_ascending_history_never_triggers_watermark_stop(self, mock_session: mock.MagicMock) -> None:- # date_after_unix is inclusive, so page one re-includes the boundary row whose value- # equals the watermark. An asc endpoint must never be cut short by the desc guard.- pages = [- _resp(- {- "history": [{"history_item_id": "boundary", "date_unix": 1700000000}],- "last_history_item_id": "boundary",- "has_more": True,- }- ),- _resp(- {- "history": [{"history_item_id": "newer", "date_unix": 1700000500}],- "last_history_item_id": "newer",- "has_more": False,- }- ),- ]- mock_session.return_value.get.side_effect = pages-- batches = list(- get_rows(- "key",- "history",- mock.MagicMock(),- _make_manager(),- should_use_incremental_field=True,- db_incremental_field_last_value=1700000000,- incremental_field="date_unix",- )- )+ assert rows == [{"history_item_id": "a"}, {"history_item_id": "b"}]+ # Saved only once (after page 1, since page 2 is terminal) so a crash re-yields the last page.+ assert [s.cursor for s in manager.saved] == ["a"]++ def test_terminates_when_has_more_false_even_with_a_cursor(self) -> None:+ # A stale next cursor with has_more=False must not loop forever.+ pages = {None: {"history": [{"history_item_id": "a"}], "has_more": False, "last_history_item_id": "a"}}+ rows = self._run(_FakeResumableManager(), pages)+ assert rows == [{"history_item_id": "a"}]++ def test_resumes_from_saved_cursor(self) -> None:+ def fake_fetch(session: Any, url: str, params: dict, headers: dict, logger: Any) -> dict:+ assert params["cursor"] == "C1"+ return {"conversations": [{"conversation_id": "x"}], "has_more": False, "next_cursor": None}- assert len(batches) == 2+ manager = _FakeResumableManager(ElevenLabsResumeConfig(cursor="C1"))+ with patch.object(elevenlabs, "_fetch_page", fake_fetch):+ rows = [row for batch in get_rows("k", "conversations", MagicMock(), manager) for row in batch] # type: ignore[arg-type]+ assert rows == [{"conversation_id": "x"}]-class TestElevenLabsSource:- def test_endpoints_inventory(self) -> None:- assert ENDPOINTS == ("history", "conversations", "agents", "voices", "models")+class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", 200, None, True),+ ("bad_key", 401, None, False),+ ("missing_scope_at_create", 403, None, True),+ ("missing_scope_at_schema", 403, "history", False),+ # An unverified key (transient 429/5xx) must not be saved as valid at create time.+ ("rate_limited_at_create", 429, None, False),+ ("server_error_at_create", 500, None, False),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, schema_name: str | None, expected_ok: bool) -> None:+ resp = MagicMock(status_code=status)+ with patch.object(elevenlabs, "make_tracked_session") as mts:+ mts.return_value.get.return_value = resp+ ok, _msg = validate_credentials("k", schema_name)+ assert ok is expected_ok++ def test_network_error_is_not_valid(self) -> None:+ with patch.object(elevenlabs, "make_tracked_session") as mts:+ mts.return_value.get.side_effect = requests.ConnectionError("boom")+ ok, msg = validate_credentials("k")+ assert ok is False+ assert msg is not None++ def test_session_does_not_follow_redirects(self) -> None:+ # requests keeps the custom xi-api-key header across a cross-origin 3xx; following one would+ # replay the key to the redirect target, so the credentialed session must refuse redirects.+ with patch.object(elevenlabs, "make_tracked_session") as mts:+ mts.return_value.get.return_value = MagicMock(status_code=200)+ validate_credentials("k")+ assert mts.call_args.kwargs["allow_redirects"] is False+++class TestGetRowsSecurity:+ def test_session_does_not_follow_redirects(self) -> None:+ # Same key-leak boundary as validation: the sync session must not forward xi-api-key on a 3xx.+ page = {"history": [], "has_more": False, "last_history_item_id": None}+ with (+ patch.object(elevenlabs, "make_tracked_session") as mts,+ patch.object(elevenlabs, "_fetch_page", lambda *_a, **_k: page),+ ):+ list(get_rows("k", "history", MagicMock(), _FakeResumableManager())) # type: ignore[arg-type]+ assert mts.call_args.kwargs["allow_redirects"] is False+++class TestSourceResponse:@parameterized.expand([- ("history", "history_item_id", "date_unix", "asc"),- ("conversations", "conversation_id", "start_time_unix_secs", "desc"),- ("agents", "agent_id", "created_at_unix_secs", "desc"),- ("voices", "voice_id", None, "desc"),- ("models", "model_id", None, "desc"),+ ("history", ["history_item_id"], "asc", "date_unix"),+ ("conversations", ["conversation_id"], "desc", "start_time_unix_secs"),+ ("agents", ["agent_id"], "asc", "created_at_unix_secs"),+ ("voices", ["voice_id"], "asc", "created_at_unix"),])- def test_source_response_shape(- self, endpoint: str, primary_key: str, partition_key: str | None, sort_mode: str+ def test_response_shape_per_endpoint(+ self, endpoint: str, primary_keys: list[str], sort_mode: str, partition_key: str) -> None:- response = elevenlabs_source("key", endpoint, mock.MagicMock(), _make_manager())-- assert response.name == endpoint- assert response.primary_keys == [primary_key]+ # sort_mode="asc" on a newest-first endpoint corrupts the watermark; the pk must be table-unique.+ response = elevenlabs_source("k", endpoint, MagicMock(), MagicMock())+ assert response.primary_keys == primary_keysassert response.sort_mode == sort_mode- if partition_key is None:- assert response.partition_mode is None- assert response.partition_keys is None- else:- assert response.partition_mode == "datetime"- assert response.partition_keys == [partition_key]+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/tests/test_elevenlabs_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/tests/test_elevenlabs_source.pyindex bb3043683067..c02a738f84fa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/tests/test_elevenlabs_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/tests/test_elevenlabs_source.py@@ -1,152 +1,128 @@-import pytest-from unittest import mock--from posthog.schema import (- DataWarehouseSourceCategory,- ReleaseStatus,- SourceFieldInputConfig,- SourceFieldInputConfigType,-)+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs import source as source_modulefrom products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.elevenlabs import (ElevenLabsResumeConfig,)-from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.settings import (- ENDPOINTS,- INCREMENTAL_FIELDS,-)from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.source import ElevenLabsSource-from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ElevenLabsSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType-class TestElevenLabsSource:- def setup_method(self):- self.source = ElevenLabsSource()- self.team_id = 123- self.config = ElevenLabsSourceConfig(api_key="key")-- def test_source_type(self):- assert self.source.source_type == ExternalDataSourceType.ELEVENLABS+class TestElevenLabsSourceConfig:+ def test_source_type(self) -> None:+ assert ElevenLabsSource().source_type == ExternalDataSourceType.ELEVENLABS- def test_get_source_config(self):- config = self.source.get_source_config-- assert config.name.value == "ElevenLabs"- assert config.label == "ElevenLabs"- assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING- assert config.releaseStatus == ReleaseStatus.ALPHA- assert config.iconPath == "/static/services/elevenlabs.svg"+ def test_config_exposes_api_key_password_field(self) -> None:+ config = ElevenLabsSource().get_source_config+ fields = {f.name: f for f in config.fields}+ assert "api_key" in fields+ api_key_field = fields["api_key"]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.type == "password"+ assert api_key_field.required is Trueassert config.docsUrl == "https://posthog.com/docs/cdp/sources/elevenlabs"- def test_source_config_fields(self):- config = self.source.get_source_config- assert [f.name for f in config.fields] == ["api_key"]-- api_key = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig))- assert api_key.type == SourceFieldInputConfigType.PASSWORD- assert api_key.secret is True- assert api_key.required is True- def test_lists_tables_without_credentials(self):- # get_schemas iterates a static endpoint catalog with no I/O, so the public docs catalog renders.- assert self.source.lists_tables_without_credentials is True- documented = self.source.get_documented_tables()- assert [t["name"] for t in documented] == list(ENDPOINTS)-- @pytest.mark.parametrize(- "endpoint, supports_incremental",+class TestElevenLabsSchemas:+ @parameterized.expand([- ("history", True),- ("conversations", True),- ("agents", False),- ("voices", False),- ("models", False),- ],+ # history/conversations have real server-side time filters; agents/voices do not.+ ("history", True, True),+ ("conversations", True, False),+ ("agents", False, False),+ ("voices", False, False),+ ])- def test_get_schemas_incremental_support(self, endpoint, supports_incremental):- schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}-- assert set(schemas) == set(ENDPOINTS)- schema = schemas[endpoint]- assert schema.supports_incremental is supports_incremental- assert schema.supports_append is supports_incremental- assert schema.incremental_fields == INCREMENTAL_FIELDS.get(endpoint, [])-- def test_get_schemas_filtered_by_names(self):- assert [s.name for s in self.source.get_schemas(self.config, self.team_id, names=["history"])] == ["history"]- assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []-- @pytest.mark.parametrize(- "observed_error",- [- "401 Client Error: Unauthorized for url: https://api.elevenlabs.io/v1/history?page_size=1000",- "403 Client Error: Forbidden for url: https://api.elevenlabs.io/v1/convai/conversations?page_size=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)-- @pytest.mark.parametrize(- "other_error",+ def test_schema_sync_capabilities(self, endpoint: str, incremental: bool, append: bool) -> None:+ # Marking conversations appendable would materialize post-call mutations (status/summary) as+ # duplicate rows; marking agents/voices incremental would break sync (no filter to honor).+ schemas = {s.name: s for s in ElevenLabsSource().get_schemas(MagicMock(), team_id=1)}+ assert schemas[endpoint].supports_incremental is incremental+ assert schemas[endpoint].supports_append is append++ def test_incremental_fields_are_unix_integers(self) -> None:+ schemas = {s.name: s for s in ElevenLabsSource().get_schemas(MagicMock(), team_id=1)}+ history = schemas["history"]+ assert [f["field"] for f in history.incremental_fields] == ["date_unix"]++ def test_names_filter_limits_returned_schemas(self) -> None:+ schemas = ElevenLabsSource().get_schemas(MagicMock(), team_id=1, names=["voices"])+ assert [s.name for s in schemas] == ["voices"]++ def test_documented_tables_render_for_public_docs(self) -> None:+ # lists_tables_without_credentials must stay on so the posthog.com Supported tables section renders.+ tables = ElevenLabsSource().get_documented_tables()+ assert {t["name"] for t in tables} == {"history", "conversations", "agents", "voices"}+++class TestElevenLabsNonRetryableErrors:+ @parameterized.expand([- "500 Server Error: Internal Server Error for url: https://api.elevenlabs.io/v1/history",- "429 Client Error: Too Many Requests for url: https://api.elevenlabs.io/v1/history",- "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",- ],+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.elevenlabs.io/v1/history"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.elevenlabs.io/v1/convai/conversations"),+ ])- def test_non_retryable_errors_does_not_match_transient_or_unrelated(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_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:+ errors = ElevenLabsSource().get_non_retryable_errors()+ assert any(key in observed for key in errors)- @pytest.mark.parametrize(- "mock_return, expected_valid, expected_message",+ @parameterized.expand([- (True, True, None),- (False, False, "Invalid ElevenLabs API key"),- ],- )- @mock.patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.source.validate_elevenlabs_credentials"+ ("read_timeout", "HTTPSConnectionPool(host='api.elevenlabs.io', port=443): Read timed out."),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.elevenlabs.io/v1/history"),+ ])- def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):- 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(self.config.api_key)+ def test_transient_errors_stay_retryable(self, _name: str, observed: str) -> None:+ errors = ElevenLabsSource().get_non_retryable_errors()+ assert not any(key in observed for key in errors)- def test_get_resumable_source_manager_binds_resume_config(self):- manager = self.source.get_resumable_source_manager(mock.MagicMock())- assert isinstance(manager, ResumableSourceManager)+class TestElevenLabsPipelinePlumbing:+ def test_resumable_manager_bound_to_resume_config(self) -> None:+ inputs = MagicMock()+ manager = ElevenLabsSource().get_resumable_source_manager(inputs)assert manager._data_class is ElevenLabsResumeConfig- @pytest.mark.parametrize("should_use_incremental_field", [True, False])- @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.source.elevenlabs_source")- def test_source_for_pipeline_plumbs_arguments(self, mock_elevenlabs_source, should_use_incremental_field):- inputs = mock.MagicMock()- inputs.schema_name = "history"- inputs.should_use_incremental_field = should_use_incremental_field- inputs.db_incremental_field_last_value = 1700000000- inputs.incremental_field = "date_unix"- manager = mock.MagicMock()-- self.source.source_for_pipeline(self.config, manager, inputs)-- mock_elevenlabs_source.assert_called_once()- kwargs = mock_elevenlabs_source.call_args.kwargs- assert kwargs["api_key"] == "key"+ def test_source_for_pipeline_forwards_incremental_inputs(self) -> None:+ config = MagicMock(api_key="sk_test")+ manager = MagicMock()+ inputs = MagicMock(+ schema_name="history",+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ incremental_field="date_unix",+ )+ with patch.object(source_module, "elevenlabs_source") as mocked:+ ElevenLabsSource().source_for_pipeline(config, manager, inputs)++ _args, kwargs = mocked.call_argsassert kwargs["endpoint"] == "history"- assert kwargs["resumable_source_manager"] is manager- assert kwargs["should_use_incremental_field"] is should_use_incremental_field- # The stored watermark must never leak into a full-refresh run.- assert kwargs["db_incremental_field_last_value"] == (1700000000 if should_use_incremental_field else None)-- def test_canonical_descriptions_keyed_by_endpoint(self):- descriptions = self.source.get_canonical_descriptions()- assert set(descriptions).issubset(set(ENDPOINTS))+ assert kwargs["api_key"] == "sk_test"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == 1700000000+ assert kwargs["incremental_field"] == "date_unix"++ def test_source_for_pipeline_drops_watermark_on_full_refresh(self) -> None:+ # When incremental is off, the stored watermark must not leak into the request as a filter.+ inputs = MagicMock(+ schema_name="agents",+ should_use_incremental_field=False,+ db_incremental_field_last_value=1700000000,+ incremental_field=None,+ )+ with patch.object(source_module, "elevenlabs_source") as mocked:+ ElevenLabsSource().source_for_pipeline(MagicMock(api_key="sk_test"), MagicMock(), inputs)++ _args, kwargs = mocked.call_args+ assert kwargs["db_incremental_field_last_value"] is None+++def test_validate_credentials_delegates_to_transport() -> None:+ with patch.object(source_module, "validate_elevenlabs_credentials", return_value=(True, None)) as mocked:+ result = ElevenLabsSource().validate_credentials(MagicMock(api_key="sk_test"), team_id=1, schema_name="history")+ assert result == (True, None)+ assert mocked.call_args[0] == ("sk_test", "history")