: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 twelve_labs import source (#70013)
Tom Owers23615dc1f661
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 644eccf9a4a4..37a4cc6cb7bb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -398,6 +398,7 @@ the row lists both.| trello | HTTP | requests | ✅ || tremendous | HTTP | requests | ✅ || trigger_dev | HTTP | requests | ✅ |+| twelve_labs | HTTP | requests | ✅ || twilio | HTTP | requests | ✅ || typeform | HTTP | requests + `rest_source.RESTClient` | ✅ || ubidots | HTTP | requests | ✅ |@@ -827,7 +828,6 @@ doesn't conflict with concurrent PRs.- turso- tvmaze- twelve_data-- twelve_labs- twenty- twitter_adsdiff --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 aa342e7f5d17..3eeec3362884 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@@ -3851,7 +3851,7 @@ class TwelveDataSourceConfig(config.Config):@config.configclass TwelveLabsSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/canonical_descriptions.pynew file mode 100644index 000000000000..45f7d220e447--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/canonical_descriptions.py@@ -0,0 +1,48 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Twelve Labs v1.3 API docs (https://docs.twelvelabs.io/v1.3/api-reference).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "indexes": {+ "description": "An index groups one or more uploaded videos stored as vectors, together with the models used to process them.",+ "docs_url": "https://docs.twelvelabs.io/v1.3/api-reference/indexes",+ "columns": {+ "_id": "Unique identifier of the index, assigned by the platform.",+ "index_name": "Name of the index.",+ "created_at": "Date and time, in RFC 3339 format, the index was created.",+ "updated_at": "Date and time, in RFC 3339 format, the index was last updated.",+ "expires_at": "Date and time the index expires (null on plans without expiry).",+ "total_duration": "Total duration, in seconds, of all videos in the index.",+ "video_count": "Number of videos uploaded to the index.",+ "models": "Video understanding models enabled for the index, each with model_name and model_options.",+ "addons": "Add-ons enabled for the index.",+ },+ },+ "tasks": {+ "description": "A video indexing task tracks the upload and indexing lifecycle of a single video.",+ "docs_url": "https://docs.twelvelabs.io/v1.3/api-reference/tasks",+ "columns": {+ "_id": "Unique identifier of the video indexing task.",+ "index_id": "Identifier of the index the video is being uploaded to.",+ "video_id": "Identifier of the resulting video once indexing completes.",+ "status": "Task status: ready, uploading, validating, pending, queued, indexing, or failed.",+ "created_at": "Date and time, in RFC 3339 format, the task was created.",+ "updated_at": "Date and time, in RFC 3339 format, the task was last updated.",+ "system_metadata": "Platform-derived metadata about the video (filename, duration, width, height).",+ },+ },+ "videos": {+ "description": "A video is an indexed asset within an index, searchable and available for analysis.",+ "docs_url": "https://docs.twelvelabs.io/v1.3/api-reference/videos",+ "columns": {+ "_id": "Unique identifier of the video, assigned by the platform.",+ "index_id": "Identifier of the index the video belongs to (injected during fan-out).",+ "asset_id": "Identifier of the underlying asset associated with the video.",+ "created_at": "Date and time, in RFC 3339 format, the indexing task was created.",+ "updated_at": "Date and time, in RFC 3339 format, the video object was last updated.",+ "indexed_at": "Date and time, in RFC 3339 format, indexing completed.",+ "system_metadata": "Platform-derived metadata about the video (filename, duration, fps, width, height, size).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/settings.pynew file mode 100644index 000000000000..d1e790a44d5b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/settings.py@@ -0,0 +1,71 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++def _datetime_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++@dataclass+class TwelveLabsEndpointConfig:+ name: str+ # `path` may contain a `{index_id}` placeholder for fan-out endpoints.+ path: str+ incremental_fields: list[IncrementalField]+ # Field to partition by. Must be a STABLE creation-time field so partitions don't rewrite+ # on every sync (never `updated_at`).+ partition_key: Optional[str] = "created_at"+ primary_keys: list[str] = field(default_factory=lambda: ["_id"])+ should_sync_default: bool = True+ # Fan out one paginated request per index (used by the videos endpoint, which is nested+ # under an index). When True, `path` is a template with an `{index_id}` placeholder and the+ # parent index id is injected into every row.+ fan_out_over_indexes: bool = False+++# Twelve Labs list endpoints all use page-number pagination (page + page_limit, max 50) and expose+# `created_at` / `updated_at` RFC 3339 filters with `sort_by` + `sort_option`. See+# https://docs.twelvelabs.io/v1.3/api-reference for the current (v1.3) API.+TWELVE_LABS_ENDPOINTS: dict[str, TwelveLabsEndpointConfig] = {+ # Indexes group uploaded videos and carry the model config, video_count and total_duration.+ # `updated_at` bumps whenever an index or its contents change, so it is a reliable incremental+ # cursor.+ "indexes": TwelveLabsEndpointConfig(+ name="indexes",+ path="/indexes",+ incremental_fields=[_datetime_field("updated_at"), _datetime_field("created_at")],+ ),+ # Video indexing tasks track the upload/indexing lifecycle (pending/indexing/ready/failed).+ # `updated_at` advances on each status transition, so incremental sync picks up progress.+ "tasks": TwelveLabsEndpointConfig(+ name="tasks",+ path="/tasks",+ incremental_fields=[_datetime_field("updated_at"), _datetime_field("created_at")],+ ),+ # Videos are nested under an index, so this fans out one paginated request per index. Shipped as+ # full refresh: the `updated_at` filter only advances for videos edited via the PUT method (per+ # the API docs), so it can't be trusted as an incremental cursor for a fan-out we cannot+ # curl-verify. Full refresh re-pulls every index's videos each sync; merge replaces on the+ # [index_id, _id] key. Off by default to avoid the extra per-index API cost on free plans.+ "videos": TwelveLabsEndpointConfig(+ name="videos",+ path="/indexes/{index_id}/videos",+ incremental_fields=[],+ primary_keys=["index_id", "_id"],+ should_sync_default=False,+ fan_out_over_indexes=True,+ ),+}++ENDPOINTS = tuple(TWELVE_LABS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in TWELVE_LABS_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/source.pyindex 71e353fda93c..f0869414689c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/source.py@@ -1,19 +1,43 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import TwelveLabsSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_labs.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ TWELVE_LABS_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_labs.twelve_labs import (+ TwelveLabsResumeConfig,+ twelve_labs_source,+ validate_credentials as validate_twelve_labs_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class TwelveLabsSource(SimpleSource[TwelveLabsSourceConfig]):+class TwelveLabsSource(ResumableSource[TwelveLabsSourceConfig, TwelveLabsResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TWELVELABS@@ -24,8 +48,100 @@ class TwelveLabsSource(SimpleSource[TwelveLabsSourceConfig]):name=SchemaExternalDataSourceType.TWELVE_LABS,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Twelve Labs",+ releaseStatus=ReleaseStatus.ALPHA,+ unreleasedSource=True,+ caption="""Enter your Twelve Labs API key to sync your video understanding library into the PostHog Data warehouse.++You can create an API key in your [Twelve Labs dashboard](https://playground.twelvelabs.io/dashboard/api-key).""",iconPath="/static/services/twelve_labs.png",+ docsUrl="https://posthog.com/docs/cdp/sources/twelve-labs",keywords=["video", "ai", "video understanding", "indexing"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="tlk_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_labs.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A missing, invalid, or revoked API key surfaces as an 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.+ "401 Client Error: Unauthorized for url: https://api.twelvelabs.io": "Your Twelve Labs API key is invalid or has been revoked. Create a new API key in your Twelve Labs dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.twelvelabs.io": "Your Twelve Labs API key does not have permission to access this data. Check the key's permissions in your Twelve Labs dashboard, then reconnect.",+ }++ def get_schemas(+ self,+ config: TwelveLabsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = TWELVE_LABS_ENDPOINTS[endpoint]+ has_incremental = len(endpoint_config.incremental_fields) > 0+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: TwelveLabsSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ ok, status_code = validate_twelve_labs_credentials(config.api_key)+ if ok:+ return True, None++ # Only a 401/403 means the key is genuinely bad. A 429/5xx or transport error is transient,+ # so tell the user to retry rather than telling them to replace a key that may be valid.+ if status_code in (401, 403):+ return False, "Invalid Twelve Labs API key"+ return False, "Could not connect to Twelve Labs. Check your connection and try again."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TwelveLabsResumeConfig]:+ return ResumableSourceManager[TwelveLabsResumeConfig](inputs, TwelveLabsResumeConfig)++ def source_for_pipeline(+ self,+ config: TwelveLabsSourceConfig,+ resumable_source_manager: ResumableSourceManager[TwelveLabsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return twelve_labs_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/tests/test_twelve_labs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/tests/test_twelve_labs.pynew file mode 100644index 000000000000..2db061a9398c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/tests/test_twelve_labs.py@@ -0,0 +1,225 @@+from datetime import UTC, date, datetime+from typing import Any++from unittest.mock import MagicMock, patch++import structlog+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_labs import twelve_labs+from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_labs.settings import TWELVE_LABS_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_labs.twelve_labs import (+ TwelveLabsResumeConfig,+ _build_params,+ _format_incremental_value,+ get_rows,+ twelve_labs_source,+ validate_credentials,+)++logger = structlog.get_logger()+++class FakeResumableManager:+ """Minimal ResumableSourceManager stand-in that records saved state in memory."""++ def __init__(self, initial: TwelveLabsResumeConfig | None = None) -> None:+ self.state = initial+ self.saved: list[TwelveLabsResumeConfig] = []++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> TwelveLabsResumeConfig | None:+ return self.state++ def save_state(self, data: TwelveLabsResumeConfig) -> None:+ self.saved.append(data)+++def _page(rows: list[dict[str, Any]], page: int, total_page: int) -> dict[str, Any]:+ return {"data": rows, "page_info": {"page": page, "total_page": total_page, "limit_per_page": 50}}+++def _mock_response(payload: dict[str, Any], status_code: int = 200) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.json.return_value = payload+ response.text = ""+ return response+++def _session_returning(pages: list[dict[str, Any]]) -> MagicMock:+ session = MagicMock()+ session.get.side_effect = [_mock_response(p) for p in pages]+ return session+++class TestFormatIncrementalValue:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),+ ("string_passthrough", "2026-03-04T00:00:00Z", "2026-03-04T00:00:00Z"),+ ]+ )+ def test_format(self, _name: str, value: object, expected: str) -> None:+ # A wrong RFC 3339 shape (e.g. a +00:00 offset) breaks the server-side created_at/updated_at+ # filter, so the exact string matters.+ assert _format_incremental_value(value) == expected++ def test_no_plus_zero_offset(self) -> None:+ assert "+00:00" not in _format_incremental_value(datetime(2026, 3, 4, tzinfo=UTC))+++class TestBuildParams:+ def test_incremental_sets_filter_and_ascending_sort(self) -> None:+ params = _build_params(+ TWELVE_LABS_ENDPOINTS["indexes"],+ page=1,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ incremental_field="updated_at",+ )+ assert params["sort_by"] == "updated_at"+ assert params["sort_option"] == "asc"+ assert params["updated_at"] == "2026-03-04T00:00:00.000Z"+ assert params["page_limit"] == twelve_labs.PAGE_LIMIT++ def test_incremental_first_sync_has_no_filter_value(self) -> None:+ # No watermark yet: sort ascending but don't emit a filter param, else we'd send an empty value.+ params = _build_params(+ TWELVE_LABS_ENDPOINTS["tasks"],+ page=1,+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ incremental_field="updated_at",+ )+ assert params["sort_by"] == "updated_at"+ assert "updated_at" not in params++ def test_full_refresh_sorts_by_stable_creation_field(self) -> None:+ # Full refresh must still pass an explicit ascending sort on a stable field so page+ # boundaries don't skip or duplicate rows if the library grows mid-sync.+ params = _build_params(+ TWELVE_LABS_ENDPOINTS["videos"],+ page=1,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ incremental_field=None,+ )+ assert params["sort_by"] == "created_at"+ assert params["sort_option"] == "asc"+ assert not any(k in params for k in ("created_at", "updated_at"))+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_status_mapping(self, _name: str, status_code: int, expected: bool) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response({}, status_code=status_code)+ with patch.object(twelve_labs, "make_tracked_session", return_value=session):+ ok, returned_status = validate_credentials("tlk_key")+ assert ok is expected+ # The caller relies on the status code to tell a rejected key from a transient outage.+ assert returned_status == status_code++ def test_network_error_reports_no_status(self) -> None:+ session = MagicMock()+ session.get.side_effect = Exception("boom")+ with patch.object(twelve_labs, "make_tracked_session", return_value=session):+ ok, returned_status = validate_credentials("tlk_key")+ assert ok is False+ assert returned_status is None++ def test_credentialed_session_redacts_key_and_refuses_redirects(self) -> None:+ # The x-api-key value must never reach tracked telemetry, and a 30x must not replay it to+ # another host, so validation builds the session with both guards on.+ session = MagicMock()+ session.get.return_value = _mock_response({}, status_code=200)+ with patch.object(twelve_labs, "make_tracked_session", return_value=session) as make_session:+ validate_credentials("tlk_key")+ make_session.assert_called_once_with(redact_values=("tlk_key",), allow_redirects=False)+++class TestGetRowsPagination:+ def test_walks_pages_until_total_page(self) -> None:+ pages = [+ _page([{"_id": "a"}], page=1, total_page=2),+ _page([{"_id": "b"}], page=2, total_page=2),+ ]+ session = _session_returning(pages)+ manager = FakeResumableManager()+ with patch.object(twelve_labs, "make_tracked_session", return_value=session):+ batches = list(get_rows("tlk", "indexes", logger, manager)) # type: ignore[arg-type]++ assert [row["_id"] for batch in batches for row in batch] == ["a", "b"]+ assert session.get.call_count == 2++ def test_saves_resume_state_after_each_page_but_not_on_last(self) -> None:+ # State is saved after yielding a page (so a crash re-yields, not skips) and only while more+ # pages remain, so we never bookmark past the end of the list.+ pages = [+ _page([{"_id": "a"}], page=1, total_page=2),+ _page([{"_id": "b"}], page=2, total_page=2),+ ]+ session = _session_returning(pages)+ manager = FakeResumableManager()+ with patch.object(twelve_labs, "make_tracked_session", return_value=session):+ list(get_rows("tlk", "indexes", logger, manager)) # type: ignore[arg-type]++ assert [s.next_page for s in manager.saved] == [2]++ def test_resumes_from_saved_page(self) -> None:+ session = _session_returning([_page([{"_id": "b"}], page=2, total_page=2)])+ manager = FakeResumableManager(TwelveLabsResumeConfig(next_page=2))+ with patch.object(twelve_labs, "make_tracked_session", return_value=session):+ list(get_rows("tlk", "indexes", logger, manager)) # type: ignore[arg-type]++ # Only page 2 is fetched — the resume skips page 1.+ requested_url = session.get.call_args_list[0].args[0]+ assert "page=2" in requested_url+ assert session.get.call_count == 1+++class TestFanOut:+ def test_injects_parent_index_id_into_every_video_row(self) -> None:+ # /indexes returns two indexes, each with one video page. The parent index_id must land on+ # every row so the [index_id, _id] primary key stays unique table-wide.+ pages = [+ _page([{"_id": "idx1"}, {"_id": "idx2"}], page=1, total_page=1), # /indexes+ _page([{"_id": "v1"}], page=1, total_page=1), # idx1 videos+ _page([{"_id": "v2"}], page=1, total_page=1), # idx2 videos+ ]+ session = _session_returning(pages)+ manager = FakeResumableManager()+ with patch.object(twelve_labs, "make_tracked_session", return_value=session):+ batches = list(get_rows("tlk", "videos", logger, manager)) # type: ignore[arg-type]++ rows = [row for batch in batches for row in batch]+ assert {(r["index_id"], r["_id"]) for r in rows} == {("idx1", "v1"), ("idx2", "v2")}++ def test_resumes_into_bookmarked_index(self) -> None:+ # Bookmarked on idx2: idx1's videos must not be re-fetched.+ pages = [+ _page([{"_id": "idx1"}, {"_id": "idx2"}], page=1, total_page=1), # /indexes+ _page([{"_id": "v2"}], page=1, total_page=1), # idx2 videos+ ]+ session = _session_returning(pages)+ manager = FakeResumableManager(TwelveLabsResumeConfig(next_page=1, index_id="idx2"))+ with patch.object(twelve_labs, "make_tracked_session", return_value=session):+ batches = list(get_rows("tlk", "videos", logger, manager)) # type: ignore[arg-type]++ rows = [row for batch in batches for row in batch]+ assert {r["index_id"] for r in rows} == {"idx2"}+++class TestTwelveLabsSourceResponse:+ @parameterized.expand([("indexes", ["_id"]), ("tasks", ["_id"]), ("videos", ["index_id", "_id"])])+ def test_primary_keys(self, endpoint: str, expected_keys: list[str]) -> None:+ response = twelve_labs_source("tlk", endpoint, logger, FakeResumableManager()) # type: ignore[arg-type]+ assert response.primary_keys == expected_keys+ assert response.sort_mode == "asc"+ assert response.partition_keys == ["created_at"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/tests/test_twelve_labs_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/tests/test_twelve_labs_source.pynew file mode 100644index 000000000000..3b9e45f0b8e1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/tests/test_twelve_labs_source.py@@ -0,0 +1,139 @@+from unittest.mock import patch++import structlog+from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+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 TwelveLabsSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_labs import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_labs.source import TwelveLabsSource+from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_labs.twelve_labs import (+ TwelveLabsResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _inputs(schema_name: str, last_value: object = None, should_use_incremental: bool = False) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=1,+ should_use_incremental_field=should_use_incremental,+ db_incremental_field_last_value=last_value,+ db_incremental_field_earliest_value=None,+ incremental_field="updated_at",+ incremental_field_type=None,+ job_id="job-1",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestTwelveLabsSource:+ def setup_method(self) -> None:+ self.source = TwelveLabsSource()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.TWELVELABS++ def test_api_key_field_is_secret_password(self) -> None:+ fields = self.source.get_source_config.fields+ assert len(fields) == 1+ api_key = fields[0]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert api_key.name == "api_key"+ assert api_key.required is True+ assert api_key.secret is True++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O — required so the public docs render the table list.+ assert self.source.lists_tables_without_credentials is True++ @parameterized.expand(+ [+ ("indexes", True, True),+ ("tasks", True, True),+ ("videos", False, False),+ ]+ )+ def test_schema_incremental_support(self, name: str, supports_incremental: bool, supports_append: bool) -> None:+ # Only endpoints with a genuine server-side timestamp filter are incremental; videos+ # (fan-out, unverifiable updated_at filter) ships full-refresh only.+ schema = next(+ s for s in self.source.get_schemas(TwelveLabsSourceConfig(api_key="x"), team_id=1) if s.name == name+ )+ assert schema.supports_incremental is supports_incremental+ assert schema.supports_append is supports_append++ def test_videos_not_synced_by_default(self) -> None:+ # Per-index fan-out is expensive on free plans, so videos is opt-in.+ videos = next(+ s for s in self.source.get_schemas(TwelveLabsSourceConfig(api_key="x"), team_id=1) if s.name == "videos"+ )+ assert videos.should_sync_default is False++ def test_get_schemas_filters_by_name(self) -> None:+ schemas = self.source.get_schemas(TwelveLabsSourceConfig(api_key="x"), team_id=1, names=["tasks"])+ assert [s.name for s in schemas] == ["tasks"]++ @parameterized.expand(+ [+ ("valid", (True, 200), True, None),+ ("rejected_key", (False, 401), False, "Invalid Twelve Labs API key"),+ ("forbidden_key", (False, 403), False, "Invalid Twelve Labs API key"),+ # A transient outage must not be reported as a bad key, or a user gets told to replace a+ # key that is actually valid.+ (+ "rate_limited",+ (False, 429),+ False,+ "Could not connect to Twelve Labs. Check your connection and try again.",+ ),+ (+ "server_error",+ (False, 500),+ False,+ "Could not connect to Twelve Labs. Check your connection and try again.",+ ),+ (+ "network_error",+ (False, None),+ False,+ "Could not connect to Twelve Labs. Check your connection and try again.",+ ),+ ]+ )+ def test_validate_credentials(+ self, _name: str, api_result: tuple[bool, int | None], expected_ok: bool, expected_err: str | None+ ) -> None:+ with patch.object(source_module, "validate_twelve_labs_credentials", return_value=api_result):+ ok, err = self.source.validate_credentials(TwelveLabsSourceConfig(api_key="x"), team_id=1)+ assert ok is expected_ok+ assert err == expected_err++ def test_resumable_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_inputs("indexes"))+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is TwelveLabsResumeConfig++ def test_source_for_pipeline_passes_endpoint_and_gates_incremental_value(self) -> None:+ # The last-value must only reach the transport when incremental sync is active, otherwise a+ # stale watermark would filter a full refresh.+ captured: dict[str, object] = {}++ def _fake_source(**kwargs: object) -> str:+ captured.update(kwargs)+ return "resp"++ inputs = _inputs("indexes", last_value="2026-01-01", should_use_incremental=False)+ with patch.object(source_module, "twelve_labs_source", side_effect=_fake_source):+ self.source.source_for_pipeline(TwelveLabsSourceConfig(api_key="k"), manager_stub := object(), inputs) # type: ignore[arg-type]++ assert captured["endpoint"] == "indexes"+ assert captured["db_incremental_field_last_value"] is None+ assert captured["api_key"] == "k"+ assert manager_stub is captured["resumable_source_manager"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/twelve-labs.md b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/twelve-labs.mdnew file mode 100644index 000000000000..3abdfe4a5db0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/twelve-labs.md@@ -0,0 +1,57 @@+---+title: Linking Twelve Labs as a source+sidebar: Docs+showTitle: true+availability: { free: full, selfServe: full, enterprise: full }+sourceId: TwelveLabs+---++import SourceSetupIntro from "../\_snippets/source-setup-intro.mdx"+import SyncModes from "../\_snippets/sync-modes.mdx"+import TroubleshootingLink from "../\_snippets/dw-troubleshooting-link.mdx"+import AlphaRelease from "../\_snippets/alpha-release.mdx"++<AlphaRelease />++Sync your [Twelve Labs](https://www.twelvelabs.io) video understanding library into PostHog. This+connector imports your indexes, the videos in each index, and the video indexing tasks that track the+upload and indexing lifecycle, so you can analyze library growth, indexing throughput, and indexing+failures alongside the rest of your data.++## Prerequisites++You need a Twelve Labs account and an API key. Any plan tier works, but be aware that free plans have+daily request caps that can slow the sync of very large libraries.++## Adding a data source++<SourceSetupIntro />++You need your **Twelve Labs API key**. You can create one from the+[API key page](https://playground.twelvelabs.io/dashboard/api-key) in your Twelve Labs dashboard. Paste+it into the API key field when connecting the source.++## Sync modes++<SyncModes />++`indexes` and `tasks` support incremental sync (via the server-side `updated_at` filter) and are+recommended for ongoing syncs. `videos` is nested per index and syncs by full refresh; it is disabled+by default because fanning out one request per index can consume a meaningful share of a free plan's+daily request quota. Enable it when you need per-video metadata.++## Configuration++<SourceParameters />++## Supported tables++<SourceTables />++## Troubleshooting++If the connection fails with an authorization error, confirm your API key is active in the Twelve Labs+dashboard and has not been revoked. If a large library syncs slowly, it is most likely being throttled+by your plan's daily request cap; syncing fewer tables or upgrading your plan will help.++<TroubleshootingLink />diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/twelve_labs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/twelve_labs.pynew file mode 100644index 000000000000..2ccbf2961ceb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/twelve_labs.py@@ -0,0 +1,293 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++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.twelve_labs.settings import (+ TWELVE_LABS_ENDPOINTS,+ TwelveLabsEndpointConfig,+)++TWELVE_LABS_BASE_URL = "https://api.twelvelabs.io/v1.3"++# Max page size the API allows; larger values are rejected.+PAGE_LIMIT = 50++REQUEST_TIMEOUT_SECONDS = 60+++class TwelveLabsRetryableError(Exception):+ pass+++class TwelveLabsResumeConfig:+ # Next page number to request (1-based). None means "start at page 1".+ next_page: int | None = None+ # The index currently being processed by the videos fan-out. A stable index-id bookmark (not a+ # positional slice) so indexes added/removed between a crash and the retry can't resume us into+ # the wrong index. None for the standard (non-fan-out) endpoints.+ index_id: str | None = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {"x-api-key": api_key, "Accept": "application/json"}+++def _format_incremental_value(value: Any) -> str:+ """Format an incremental cursor as an RFC 3339 timestamp with a Z suffix."""+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+ return str(value)+++def _build_params(+ config: TwelveLabsEndpointConfig,+ page: int,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, Any]:+ """Build query params for a single page request.++ Page-number pagination means the `created_at` / `updated_at` filter can be applied on every+ page (unlike cursor APIs that only window the first page), so incremental syncs stay bounded+ without any client-side watermark termination.+ """+ params: dict[str, Any] = {"page": page, "page_limit": PAGE_LIMIT}++ # `sort_by` defaults to the endpoint's advertised cursor field but always honors the user's+ # selection. Ascending sort makes the pipeline watermark advance correctly (sort_mode="asc").+ filter_field = incremental_field or (config.incremental_fields[0]["field"] if config.incremental_fields else None)++ if should_use_incremental_field and filter_field:+ params["sort_by"] = filter_field+ params["sort_option"] = "asc"+ if db_incremental_field_last_value:+ # `created_at` / `updated_at` filter at-or-after the given value; the boundary row is+ # re-fetched each sync and merge dedupes it on the primary key.+ params[filter_field] = _format_incremental_value(db_incremental_field_last_value)+ else:+ # Full refresh: sort ascending on the stable creation field so page boundaries don't skip+ # or duplicate rows if the library grows mid-sync.+ params["sort_by"] = config.partition_key or "created_at"+ params["sort_option"] = "asc"++ return params+++def _build_url(path: str, params: dict[str, Any]) -> str:+ return f"{TWELVE_LABS_BASE_URL}{path}?{urlencode(params)}"+++@retry(+ retry=retry_if_exception_type(+ (+ TwelveLabsRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ # 429 (per-category rate limit) and transient 5xx are retryable; the API exposes X-RateLimit-*+ # headers but exponential jitter backoff is enough to stay under the window.+ if response.status_code == 429 or response.status_code >= 500:+ raise TwelveLabsRetryableError(f"Twelve Labs API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Twelve Labs API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str) -> tuple[bool, int | None]:+ """Probe /indexes to confirm the API key is genuine.++ Returns ``(ok, status_code)``. ``status_code`` is ``None`` on a transport error so the caller+ can tell a rejected key (401/403) apart from a transient outage (429/5xx/network) and avoid+ reporting a valid key as invalid during a rate-limit or downtime window.+ """+ url = _build_url("/indexes", {"page": 1, "page_limit": 1})+ try:+ # Redact the key from tracked telemetry and refuse redirects so a 30x can never replay the+ # `x-api-key` header to another origin.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)+ response = session.get(url, headers=_get_headers(api_key), timeout=10)+ except Exception:+ return False, None+ return response.status_code == 200, response.status_code+++def _iter_index_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> Iterator[str]:+ """Page through /indexes and yield each index id, for the videos fan-out."""+ page = 1+ while True:+ data = _fetch_page(session, _build_url("/indexes", {"page": page, "page_limit": PAGE_LIMIT}), headers, logger)+ for item in data.get("data", []):+ yield item["_id"]++ page_info = data.get("page_info", {})+ total_page = page_info.get("total_page", page)+ if page >= total_page:+ break+ page += 1+++def _iter_pages(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ path: str,+ base_params: dict[str, Any],+ start_page: int,+) -> Iterator[tuple[list[dict[str, Any]], int | None]]:+ """Yield ``(rows, next_page)`` for each page, following page_info.total_page.++ ``next_page`` is None on the final page so the caller knows not to persist resume state past+ the end of the list.+ """+ page = start_page+ while True:+ params = {**base_params, "page": page}+ data = _fetch_page(session, _build_url(path, params), headers, logger)++ rows = data.get("data", [])+ page_info = data.get("page_info", {})+ total_page = page_info.get("total_page", page)+ next_page = page + 1 if page < total_page else None++ yield rows, next_page++ if next_page is None:+ break+ page = next_page+++def _get_fan_out_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TwelveLabsResumeConfig],+ config: TwelveLabsEndpointConfig,+ base_params: dict[str, Any],+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every index, yielding that index's videos with the parent ``index_id`` injected.++ The [index_id, _id] primary key keeps rows unique table-wide, so videos from different indexes+ never collide and merge dedupes cleanly.+ """+ index_ids = list(_iter_index_ids(session, headers, logger))++ # Resolve the saved index-id bookmark to the slice still to process. If the bookmarked index no+ # longer exists (deleted between runs), start over from the first index — full refresh replaces+ # on the primary key anyway.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = index_ids+ resume_page = 1+ if resume is not None and resume.index_id is not None and resume.index_id in index_ids:+ remaining = index_ids[index_ids.index(resume.index_id) :]+ resume_page = resume.next_page or 1+ logger.debug(f"Twelve Labs: resuming videos from index_id={resume.index_id}, page={resume_page}")++ for position, index_id in enumerate(remaining):+ path = config.path.format(index_id=index_id)+ start_page = resume_page if position == 0 else 1++ for rows, next_page in _iter_pages(session, headers, logger, path, base_params, start_page):+ yield [{**row, "index_id": index_id} for row in rows]++ # Save AFTER yielding so a crash re-yields the last page rather than skipping it.+ if next_page is not None:+ resumable_source_manager.save_state(TwelveLabsResumeConfig(next_page=next_page, index_id=index_id))++ # Advance the bookmark to the next index so a crash between indexes resumes correctly.+ if position + 1 < len(remaining):+ resumable_source_manager.save_state(TwelveLabsResumeConfig(next_page=1, index_id=remaining[position + 1]))+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TwelveLabsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = TWELVE_LABS_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # One session reused across every page (and, for fan-out, every index) so urllib3 keeps the+ # connection alive instead of re-handshaking per request. The key is redacted from tracked+ # telemetry and redirects are refused so a 30x can't replay `x-api-key` to another origin.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)++ base_params = _build_params(+ config, 1, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )+ base_params.pop("page", None)++ if config.fan_out_over_indexes:+ yield from _get_fan_out_rows(session, headers, logger, resumable_source_manager, config, base_params)+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_page = resume.next_page if resume is not None and resume.next_page else 1++ for rows, next_page in _iter_pages(session, headers, logger, config.path, base_params, start_page):+ yield rows++ if next_page is not None:+ resumable_source_manager.save_state(TwelveLabsResumeConfig(next_page=next_page))+++def twelve_labs_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TwelveLabsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = TWELVE_LABS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ # Every list endpoint is requested with sort_option=asc, so rows arrive oldest-first and the+ # pipeline can checkpoint the incremental watermark after each batch.+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )