: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 tavus import source (#68558)
Tom Owers494358db4d35
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex b7b0d2c11111..93290629cee5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -324,6 +324,7 @@ the row lists both.| surveymonkey | HTTP | requests | ✅ || svix | HTTP | requests | ✅ || taboola | HTTP | requests | ✅ |+| tavus | HTTP | requests | ✅ || teamtailor | HTTP | requests | ✅ || teamwork | HTTP | requests | ✅ || temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ |@@ -687,7 +688,6 @@ doesn't conflict with concurrent PRs.- survicate- svix- systeme-- tavus- tawk_to- teachable- tempodiff --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 5fdfb78af8da..bdee3df512b9 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@@ -3245,7 +3245,7 @@ class TalkwalkerSourceConfig(config.Config):@config.configclass TavusSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/canonical_descriptions.pynew file mode 100644index 000000000000..0e883b59c446--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/canonical_descriptions.py@@ -0,0 +1,69 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Tavus API docs (https://docs.tavus.io/api-reference).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "videos": {+ "description": "A Tavus generated video — a rendered talking-head video produced from a script and a replica.",+ "docs_url": "https://docs.tavus.io/api-reference/video-request/get-videos",+ "columns": {+ "video_id": "The unique ID of the video.",+ "video_name": "The name given to the video.",+ "status": "The generation status of the video (e.g. queued, generating, ready, error).",+ "data": "The rendering data associated with the video, including scripts and settings.",+ "download_url": "The URL to download the rendered video, when ready.",+ "stream_url": "The URL to stream the rendered video, when ready.",+ "hosted_url": "The Tavus-hosted page URL for the video.",+ "status_details": "Additional detail about the current status, such as an error reason.",+ "created_at": "The timestamp when the video was created.",+ "updated_at": "The timestamp when the video was last updated.",+ },+ },+ "replicas": {+ "description": "A Tavus replica — a trained digital likeness used to generate personalized videos.",+ "docs_url": "https://docs.tavus.io/api-reference/replica-model/get-replicas",+ "columns": {+ "replica_id": "The unique ID of the replica.",+ "replica_name": "The name given to the replica.",+ "status": "The training status of the replica (e.g. started, training, ready, error).",+ "thumbnail_video_url": "The URL of a thumbnail preview video for the replica.",+ "training_progress": "The training progress of the replica.",+ "replica_type": "The type of replica (e.g. user, system).",+ "model_name": "The underlying model used for the replica.",+ "error_message": "The error message if replica training failed.",+ "created_at": "The timestamp when the replica was created.",+ "updated_at": "The timestamp when the replica was last updated.",+ },+ },+ "personas": {+ "description": "A Tavus persona — the conversational configuration (system prompt, layers, replica) for a CVI agent.",+ "docs_url": "https://docs.tavus.io/api-reference/personas/get-personas",+ "columns": {+ "persona_id": "The unique ID of the persona.",+ "persona_name": "The name given to the persona.",+ "system_prompt": "The system prompt that defines the persona's behavior.",+ "context": "The background context provided to the persona.",+ "default_replica_id": "The ID of the replica used by default for this persona.",+ "layers": "The configured conversational layers (e.g. transport, perception, STT, LLM).",+ "created_at": "The timestamp when the persona was created.",+ "updated_at": "The timestamp when the persona was last updated.",+ },+ },+ "conversations": {+ "description": "A Tavus conversation — a real-time Conversational Video Interface (CVI) session with a replica.",+ "docs_url": "https://docs.tavus.io/api-reference/conversations/get-conversations",+ "columns": {+ "conversation_id": "The unique ID of the conversation.",+ "conversation_name": "The name given to the conversation.",+ "status": "The status of the conversation (e.g. active, ended).",+ "conversation_url": "The URL used to join the conversation.",+ "callback_url": "The webhook URL that receives conversation event callbacks.",+ "replica_id": "The ID of the replica used in the conversation.",+ "persona_id": "The ID of the persona used in the conversation.",+ "created_at": "The timestamp when the conversation was created.",+ "updated_at": "The timestamp when the conversation was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/settings.pynew file mode 100644index 000000000000..122ba71b9565--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/settings.py@@ -0,0 +1,28 @@+from dataclasses import dataclass, field+from typing import Optional+++@dataclass+class TavusEndpointConfig:+ name: str+ path: str+ # Each Tavus resource exposes its own typed id field (video_id, replica_id, ...), so the+ # primary key is set per endpoint rather than shared.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # A stable (never-rewritten) creation timestamp to partition by. Left unset because the+ # Tavus list envelopes cannot be curl-verified for a guaranteed creation field.+ partition_key: Optional[str] = None+++# Tavus v2 list endpoints. All are full-refresh only: the list endpoints expose no server-side+# created_after/updated_after filter, so there is no genuine incremental cursor to advance.+TAVUS_ENDPOINTS: dict[str, TavusEndpointConfig] = {+ "videos": TavusEndpointConfig(name="videos", path="/videos", primary_keys=["video_id"]),+ "replicas": TavusEndpointConfig(name="replicas", path="/replicas", primary_keys=["replica_id"]),+ "personas": TavusEndpointConfig(name="personas", path="/personas", primary_keys=["persona_id"]),+ "conversations": TavusEndpointConfig(name="conversations", path="/conversations", primary_keys=["conversation_id"]),+}++ENDPOINTS = tuple(TAVUS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/source.pyindex c7d08ac69301..77ffad34d94d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/source.py@@ -1,19 +1,39 @@-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 TavusSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.tavus.settings import ENDPOINTS, TAVUS_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.tavus.tavus import (+ TavusResumeConfig,+ check_access,+ tavus_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class TavusSource(SimpleSource[TavusSourceConfig]):+class TavusSource(ResumableSource[TavusSourceConfig, TavusResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TAVUS@@ -24,7 +44,95 @@ class TavusSource(SimpleSource[TavusSourceConfig]):name=SchemaExternalDataSourceType.TAVUS,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Tavus",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Tavus API key to pull your Tavus data into the PostHog Data warehouse.++You can generate an API key in the [Tavus Developer Portal](https://platform.tavus.io/api-keys). This single key grants read access to your videos, replicas, personas, and conversations.+""",iconPath="/static/services/tavus.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/tavus",+ 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.tavus.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked API key surfaces as a requests HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the sync.+ # Match the stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://tavusapi.com": "Your Tavus API key is invalid or has been revoked. Generate a new key in the Tavus Developer Portal, then reconnect.",+ "403 Client Error: Forbidden for url: https://tavusapi.com": "Your Tavus API key does not have access to this data. Check the key's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: TavusSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — Tavus's list endpoints expose no server-side+ # timestamp filter, so there is no incremental cursor to advance.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: TavusSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key is account-wide, so a single probe validates access to every schema; there is+ # no per-endpoint scope to check.+ status, message = check_access(config.api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Tavus API key"+ return False, message or "Could not validate Tavus API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TavusResumeConfig]:+ return ResumableSourceManager[TavusResumeConfig](inputs, TavusResumeConfig)++ def source_for_pipeline(+ self,+ config: TavusSourceConfig,+ resumable_source_manager: ResumableSourceManager[TavusResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in TAVUS_ENDPOINTS:+ raise ValueError(f"Unknown Tavus schema '{inputs.schema_name}'")++ return tavus_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/tavus.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/tavus.pynew file mode 100644index 000000000000..6cb75e9593bd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/tavus.py@@ -0,0 +1,152 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++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.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.tavus.settings import TAVUS_ENDPOINTS++TAVUS_BASE_URL = "https://tavusapi.com/v2"+# Tavus list endpoints paginate with `page` (0-indexed) and `limit`; a large limit minimises round+# trips for the typically small video/replica/persona/conversation tables.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm an API key is genuine. The key is account-wide, so one probe+# validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/replicas"+++class TavusRetryableError(Exception):+ pass+++class TavusResumeConfig:+ # Next page to fetch (0-indexed). Page-number pagination is deterministic, so a crashed+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on the id.+ next_page: int = 0+++def _headers(api_key: str) -> dict[str, str]:+ return {"x-api-key": api_key, "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((TavusRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ path: str,+ page: int,+ limit: int,+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.get(+ f"{TAVUS_BASE_URL}{path}",+ params={"page": page, "limit": limit},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise TavusRetryableError(f"Tavus API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"Tavus API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TavusResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = TAVUS_ENDPOINTS[endpoint]+ # `redact_values` masks the API key in logged URLs and captured samples.+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.next_page if resume else 0+ if resume and resume.next_page > 0:+ logger.debug(f"Tavus: resuming {endpoint} from page {page}")++ seen = 0+ while True:+ data = _fetch_page(session, config.path, page, PAGE_SIZE, logger)++ # `data` is always present in the list envelope ({data, total_count}); missing it means a+ # malformed response, so fail loudly rather than silently advancing past lost rows.+ rows = data["data"]+ if rows:+ yield rows+ seen += len(rows)++ total_count = data.get("total_count")++ # A short/empty page means the last page has been reached. Also stop once the running count+ # reaches the reported total, guarding against an off-by-one extra request.+ if len(rows) < PAGE_SIZE:+ break+ if total_count is not None and seen >= total_count:+ break++ page += 1+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(TavusResumeConfig(next_page=page))+++def tavus_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TavusResumeConfig],+) -> SourceResponse:+ config = TAVUS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single list endpoint to validate the API key.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))+ try:+ response = session.get(f"{TAVUS_BASE_URL}{path}", params={"page": 0, "limit": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Tavus: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Tavus returned HTTP {response.status_code}"++ return 200, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/tests/test_tavus.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/tests/test_tavus.pynew file mode 100644index 000000000000..53522850158e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/tests/test_tavus.py@@ -0,0 +1,227 @@+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.tavus import tavus+from products.warehouse_sources.backend.temporal.data_imports.sources.tavus.settings import ENDPOINTS, TAVUS_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.tavus.tavus import (+ TavusResumeConfig,+ TavusRetryableError,+ check_access,+ get_rows,+ tavus_source,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = tavus._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: TavusResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[TavusResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> TavusResumeConfig | None:+ return self._state++ def save_state(self, data: TavusResumeConfig) -> None:+ self.saved.append(data)+++def _page(items: list[dict], total_count: Optional[int] = None) -> dict[str, Any]:+ return {"data": items, "total_count": total_count if total_count is not None else len(items)}+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[int, dict],+ endpoint: str = "videos",+ page_size: int = 2,+ ) -> list[dict]:+ def fake_fetch(session: Any, path: str, page: int, limit: int, logger: Any) -> dict:+ return pages[page]++ # Shrink the page size so small fixtures exercise multi-page pagination and short-page termination.+ monkeypatch.setattr(tavus, "PAGE_SIZE", page_size)+ monkeypatch.setattr(tavus, "_fetch_page", fake_fetch)+ monkeypatch.setattr(tavus, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="tavus-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_short_page_yields_items_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {0: _page([{"video_id": "a"}], total_count=1)})+ assert rows == [{"video_id": "a"}]+ # A short page ends the sync, so no resume state is persisted.+ assert manager.saved == []++ def test_follows_pagination_until_short_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ 0: _page([{"video_id": "a"}, {"video_id": "b"}], total_count=5),+ 1: _page([{"video_id": "c"}, {"video_id": "d"}], total_count=5),+ 2: _page([{"video_id": "e"}], total_count=5),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert [r["video_id"] for r in rows] == ["a", "b", "c", "d", "e"]++ def test_stops_when_running_count_reaches_total(self, monkeypatch: Any) -> None:+ # Final page is full (== PAGE_SIZE), so termination relies on total_count, not a short page.+ manager = _FakeResumableManager()+ pages = {+ 0: _page([{"video_id": "a"}, {"video_id": "b"}], total_count=4),+ 1: _page([{"video_id": "c"}, {"video_id": "d"}], total_count=4),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert [r["video_id"] for r in rows] == ["a", "b", "c", "d"]+ # Page 2 must never be requested; state is only saved once (after page 0).+ assert [s.next_page for s in manager.saved] == [1]++ def test_saves_next_page_after_yielding_each_batch(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ 0: _page([{"video_id": "a"}, {"video_id": "b"}], total_count=3),+ 1: _page([{"video_id": "c"}], total_count=3),+ }+ self._collect(manager, monkeypatch, pages)+ # State is saved AFTER page 0 is yielded (pointing at page 1), and never for the final page.+ assert [s.next_page for s in manager.saved] == [1]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(TavusResumeConfig(next_page=1))+ pages = {+ # Page 0 must never be fetched on resume.+ 1: _page([{"video_id": "c"}, {"video_id": "d"}], total_count=3),+ 2: _page([{"video_id": "e"}], total_count=3),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert [r["video_id"] for r in rows] == ["c", "d", "e"]++ def test_empty_data_does_not_yield(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {0: _page([], total_count=0)})+ assert rows == []+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: dict | None = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body or {}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(TavusRetryableError):+ _fetch_page_unwrapped(session, "/videos", 0, 100, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "/videos", 0, 100, MagicMock())++ def test_success_returns_json_body(self) -> None:+ body = _page([{"video_id": "a"}], total_count=1)+ session = self._session_returning(200, body)+ result = _fetch_page_unwrapped(session, "/videos", 0, 100, MagicMock())+ assert result == body++ def test_request_uses_page_and_limit_params(self) -> None:+ session = self._session_returning(200, _page([], total_count=0))+ _fetch_page_unwrapped(session, "/replicas", 3, 100, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"page": 3, "limit": 100}+++class TestCheckAccess:+ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ monkeypatch.setattr(tavus, "make_tracked_session", lambda **kwargs: session)+ return session++ @parameterized.expand(+ [+ (200, True, 200, None),+ (401, False, 401, None),+ (403, False, 403, None),+ (500, False, 500, "Tavus returned HTTP 500"),+ ]+ )+ def test_status_mapping(self, status: int, ok: bool, expected_status: int, expected_message: str | None) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ session = MagicMock()+ session.get.return_value = response+ # parameterized.expand can't receive pytest fixtures, so patch directly instead of monkeypatch.+ with patch.object(tavus, "make_tracked_session", lambda **kwargs: session):+ assert check_access("tavus-key") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))+ status, message = check_access("tavus-key")+ assert status == 0+ assert message is not None and "boom" in message+++class TestTavusSourceResponse:+ @parameterized.expand(+ [+ ("videos", "video_id"),+ ("replicas", "replica_id"),+ ("personas", "persona_id"),+ ("conversations", "conversation_id"),+ ]+ )+ def test_primary_key_matches_endpoint_config(self, endpoint: str, primary_key: str) -> None:+ response = tavus_source(+ api_key="tavus-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == [primary_key]+ # No endpoint exposes a curl-verified creation field, so none partition.+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_every_endpoint_uses_a_resource_specific_primary_key(self) -> None:+ assert {name: cfg.primary_keys for name, cfg in TAVUS_ENDPOINTS.items()} == {+ "videos": ["video_id"],+ "replicas": ["replica_id"],+ "personas": ["persona_id"],+ "conversations": ["conversation_id"],+ }+ assert set(TAVUS_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/tests/test_tavus_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/tests/test_tavus_source.pynew file mode 100644index 000000000000..b82824eb1c59--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tavus/tests/test_tavus_source.py@@ -0,0 +1,153 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import TavusSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.tavus.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.tavus.source import TavusSource+from products.warehouse_sources.backend.temporal.data_imports.sources.tavus.tavus import TavusResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestTavusSource:+ def setup_method(self) -> None:+ self.source = TavusSource()+ self.team_id = 123+ self.config = TavusSourceConfig(api_key="tavus-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.TAVUS++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Tavus"+ assert config.label == "Tavus"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible — it must not carry the scaffolding flag.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/tavus"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret `api_key` itself; the base URL is hardcoded and the account+ # is implicit in the key. There is no non-secret field that retargets where the key is sent.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas is a static catalog with no I/O, so the public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # Tavus's list endpoints have no server-side timestamp filter, so every schema is full refresh.+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["replicas"])+ assert len(schemas) == 1+ assert schemas[0].name == "replicas"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ # Exercises the credential-free catalog path used by the posthog.com docs.+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://tavusapi.com/videos?page=0&limit=100",),+ ("403 Client Error: Forbidden for url: https://tavusapi.com/replicas?page=1&limit=100",),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("500 Server Error: Internal Server Error for url: https://tavusapi.com/videos",),+ ("HTTPSConnectionPool(host='tavusapi.com', port=443): Read timed out.",),+ ("429 Client Error: Too Many Requests for url: https://tavusapi.com/personas",),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @parameterized.expand(+ [+ (200, True, None),+ (401, False, "Invalid Tavus API key"),+ (403, False, "Invalid Tavus API key"),+ (500, False, "Tavus returned HTTP 500"),+ (0, False, "Could not connect to Tavus: boom"),+ ]+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.tavus.source.check_access")+ def test_validate_credentials(+ self,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_check: mock.MagicMock,+ ) -> None:+ message = (+ "Tavus returned HTTP 500"+ if status == 500+ else ("Could not connect to Tavus: boom" if status == 0 else None)+ )+ mock_check.return_value = (status, message)+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)+ assert is_valid is expected_valid+ assert returned == expected_message++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.tavus.source.check_access")+ def test_validate_credentials_probes_the_api_key(self, mock_check: mock.MagicMock) -> None:+ # The API key is account-wide, so validation probes the key, not a per-schema scope.+ mock_check.return_value = (200, None)+ self.source.validate_credentials(self.config, self.team_id, schema_name="replicas")+ mock_check.assert_called_once_with("tavus-key")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is TavusResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.tavus.source.tavus_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_tavus_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "videos"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_tavus_source.assert_called_once()+ kwargs = mock_tavus_source.call_args.kwargs+ assert kwargs["api_key"] == "tavus-key"+ assert kwargs["endpoint"] == "videos"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Tavus schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)