Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement tmdb import source (#65617)

Tom Owers613b9a98af30
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 5df2725c0aec..f8618055d5af 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -216,6 +216,7 @@ the row lists both.
| temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ |
| thinkific | HTTP | requests | ✅ |
| tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| tmdb | HTTP | requests | ✅ |
| todoist | HTTP | requests | ✅ |
| trello | HTTP | requests | ✅ |
| twilio | HTTP | requests | ✅ |
@@ -665,7 +666,6 @@ doesn't conflict with concurrent PRs.
- tile38
- timely
- tinyemail
-- tmdb
- toggl
- track_pms
- tremendous
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index af40cc9b8e5a..4ddb325a2029 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -3054,7 +3054,7 @@ class SystemeSourceConfig(config.Config):
@config.config
class TMDbSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/tmdb/api_inventory.md b/posthog/temporal/data_imports/sources/tmdb/api_inventory.md
new file mode 100644
index 000000000000..ecb3d9e68fc0
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/tmdb/api_inventory.md
@@ -0,0 +1,56 @@
+# TMDB (The Movie Database) — API inventory
+
+REST/JSON v3 API. Base URL `https://api.themoviedb.org/3`.
+
+## Auth
+
+`api_key` query parameter (v3 API key). A v4 Bearer "API Read Access Token" also works on these
+endpoints, but the connector ships only the simpler `api_key` query-param path. The key is sent in
+the query string, so the tracked session is created with `redact_values=(api_key,)`.
+
+## Pagination
+
+Page-number pagination: `?page=N`. The list/trending responses carry `page`, `results`,
+`total_pages`, `total_results`. ~20 results per page. Server caps paging at **500 pages**
+(`MAX_PAGES`), so the paginator stops at `min(total_pages, 500)`.
+
+## Incremental
+
+None of the v3 list endpoints expose a server-side updated-after filter, so **every endpoint is full
+refresh only** (`supports_incremental=False`). The `/movie|tv|person/changes` endpoints could feed an
+ID-based incremental flow, but they are 14-day-windowed and require per-ID detail fetches — out of
+scope for this connector.
+
+## Endpoints
+
+| Schema | Path | Shape | Primary key |
+| ----------------- | ------------------------ | ------------------- | ----------- |
+| movie_popular | /movie/popular | paginated `results` | id |
+| movie_top_rated | /movie/top_rated | paginated `results` | id |
+| movie_now_playing | /movie/now_playing | paginated `results` | id |
+| movie_upcoming | /movie/upcoming | paginated `results` | id |
+| tv_popular | /tv/popular | paginated `results` | id |
+| tv_top_rated | /tv/top_rated | paginated `results` | id |
+| tv_on_the_air | /tv/on_the_air | paginated `results` | id |
+| tv_airing_today | /tv/airing_today | paginated `results` | id |
+| person_popular | /person/popular | paginated `results` | id |
+| trending_movies | /trending/movie/day | paginated `results` | id |
+| trending_tv | /trending/tv/day | paginated `results` | id |
+| trending_people | /trending/person/day | paginated `results` | id |
+| movie_genres | /genre/movie/list | single, `genres` | id |
+| tv_genres | /genre/tv/list | single, `genres` | id |
+| languages | /configuration/languages | single, bare list | iso_639_1 |
+| countries | /configuration/countries | single, bare list | iso_3166_1 |
+
+## Rate limiting
+
+The documented 40 req / 10s limit was disabled in 2019; an undocumented ~50 req/s ceiling deters bulk
+scraping and can block abusive IPs. We stay well under it with a small inter-request delay
+(`THROTTLE_SECONDS`) plus tenacity backoff on 429 / 5xx.
+
+## Verification note
+
+Endpoint shapes here are taken from the current public TMDB v3 docs. They were **not** curl-verified
+against the live API during implementation because a valid TMDB API key was not available in the
+environment (unauthenticated requests return `401 {"status_code":7}`). Parsing is kept conservative
+(`_extract_rows` degrades to an empty list on unexpected payload shapes rather than raising).
diff --git a/posthog/temporal/data_imports/sources/tmdb/canonical_descriptions.py b/posthog/temporal/data_imports/sources/tmdb/canonical_descriptions.py
new file mode 100644
index 000000000000..dac63d546c80
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/tmdb/canonical_descriptions.py
@@ -0,0 +1,141 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+_MOVIE_COLUMNS = {
+ "id": "TMDB's unique identifier for the movie.",
+ "title": "Localized display title of the movie.",
+ "original_title": "Title in the movie's original language.",
+ "original_language": "ISO 639-1 code of the movie's original language.",
+ "overview": "Plot summary / synopsis.",
+ "release_date": "Theatrical release date (YYYY-MM-DD); may be empty for unreleased titles.",
+ "popularity": "TMDB popularity score, recomputed daily.",
+ "vote_average": "Mean user rating on a 0–10 scale.",
+ "vote_count": "Number of user votes contributing to vote_average.",
+ "genre_ids": "List of TMDB genre IDs (join against movie_genres).",
+ "poster_path": "Relative path to the poster image, appended to the TMDB image base URL.",
+ "backdrop_path": "Relative path to the backdrop image, appended to the TMDB image base URL.",
+ "adult": "Whether the title is flagged as adult content.",
+ "video": "Whether the entry represents a video (e.g. a direct-to-video release).",
+}
+
+_TV_COLUMNS = {
+ "id": "TMDB's unique identifier for the TV show.",
+ "name": "Localized display name of the show.",
+ "original_name": "Name in the show's original language.",
+ "original_language": "ISO 639-1 code of the show's original language.",
+ "overview": "Plot summary / synopsis.",
+ "first_air_date": "Date the show first aired (YYYY-MM-DD); may be empty for unreleased shows.",
+ "origin_country": "List of ISO 3166-1 country codes where the show originated.",
+ "popularity": "TMDB popularity score, recomputed daily.",
+ "vote_average": "Mean user rating on a 0–10 scale.",
+ "vote_count": "Number of user votes contributing to vote_average.",
+ "genre_ids": "List of TMDB genre IDs (join against tv_genres).",
+ "poster_path": "Relative path to the poster image, appended to the TMDB image base URL.",
+ "backdrop_path": "Relative path to the backdrop image, appended to the TMDB image base URL.",
+}
+
+_PERSON_COLUMNS = {
+ "id": "TMDB's unique identifier for the person.",
+ "name": "Person's name.",
+ "known_for_department": "Department the person is best known for (e.g. Acting, Directing).",
+ "popularity": "TMDB popularity score, recomputed daily.",
+ "gender": "Gender code (0 unknown, 1 female, 2 male, 3 non-binary).",
+ "profile_path": "Relative path to the profile image, appended to the TMDB image base URL.",
+ "adult": "Whether the person is flagged as adult-content related.",
+ "known_for": "List of the movies/TV shows the person is best known for.",
+}
+
+_GENRE_COLUMNS = {
+ "id": "TMDB genre identifier, referenced by genre_ids on movies/TV shows.",
+ "name": "Human-readable genre name.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "movie_popular": {
+ "description": "Movies ordered by TMDB popularity.",
+ "docs_url": "https://developer.themoviedb.org/reference/movie-popular-list",
+ "columns": _MOVIE_COLUMNS,
+ },
+ "movie_top_rated": {
+ "description": "Top rated movies on TMDB.",
+ "docs_url": "https://developer.themoviedb.org/reference/movie-top-rated-list",
+ "columns": _MOVIE_COLUMNS,
+ },
+ "movie_now_playing": {
+ "description": "Movies currently playing in theaters.",
+ "docs_url": "https://developer.themoviedb.org/reference/movie-now-playing-list",
+ "columns": _MOVIE_COLUMNS,
+ },
+ "movie_upcoming": {
+ "description": "Movies releasing in theaters soon.",
+ "docs_url": "https://developer.themoviedb.org/reference/movie-upcoming-list",
+ "columns": _MOVIE_COLUMNS,
+ },
+ "tv_popular": {
+ "description": "TV shows ordered by TMDB popularity.",
+ "docs_url": "https://developer.themoviedb.org/reference/tv-series-popular-list",
+ "columns": _TV_COLUMNS,
+ },
+ "tv_top_rated": {
+ "description": "Top rated TV shows on TMDB.",
+ "docs_url": "https://developer.themoviedb.org/reference/tv-series-top-rated-list",
+ "columns": _TV_COLUMNS,
+ },
+ "tv_on_the_air": {
+ "description": "TV shows airing in the next 7 days.",
+ "docs_url": "https://developer.themoviedb.org/reference/tv-series-on-the-air-list",
+ "columns": _TV_COLUMNS,
+ },
+ "tv_airing_today": {
+ "description": "TV shows airing today.",
+ "docs_url": "https://developer.themoviedb.org/reference/tv-series-airing-today-list",
+ "columns": _TV_COLUMNS,
+ },
+ "person_popular": {
+ "description": "People ordered by TMDB popularity.",
+ "docs_url": "https://developer.themoviedb.org/reference/person-popular-list",
+ "columns": _PERSON_COLUMNS,
+ },
+ "trending_movies": {
+ "description": "Movies trending on TMDB over the last day.",
+ "docs_url": "https://developer.themoviedb.org/reference/trending-movies",
+ "columns": _MOVIE_COLUMNS,
+ },
+ "trending_tv": {
+ "description": "TV shows trending on TMDB over the last day.",
+ "docs_url": "https://developer.themoviedb.org/reference/trending-tv",
+ "columns": _TV_COLUMNS,
+ },
+ "trending_people": {
+ "description": "People trending on TMDB over the last day.",
+ "docs_url": "https://developer.themoviedb.org/reference/trending-people",
+ "columns": _PERSON_COLUMNS,
+ },
+ "movie_genres": {
+ "description": "Official list of movie genres and their IDs.",
+ "docs_url": "https://developer.themoviedb.org/reference/genre-movie-list",
+ "columns": _GENRE_COLUMNS,
+ },
+ "tv_genres": {
+ "description": "Official list of TV genres and their IDs.",
+ "docs_url": "https://developer.themoviedb.org/reference/genre-tv-list",
+ "columns": _GENRE_COLUMNS,
+ },
+ "languages": {
+ "description": "Languages TMDB supports, keyed by ISO 639-1 code.",
+ "docs_url": "https://developer.themoviedb.org/reference/configuration-languages",
+ "columns": {
+ "iso_639_1": "ISO 639-1 two-letter language code (primary key).",
+ "english_name": "Language name in English.",
+ "name": "Language name in its own language.",
+ },
+ },
+ "countries": {
+ "description": "Countries TMDB supports, keyed by ISO 3166-1 code.",
+ "docs_url": "https://developer.themoviedb.org/reference/configuration-countries",
+ "columns": {
+ "iso_3166_1": "ISO 3166-1 two-letter country code (primary key).",
+ "english_name": "Country name in English.",
+ "native_name": "Country name in its native language.",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/tmdb/settings.py b/posthog/temporal/data_imports/sources/tmdb/settings.py
new file mode 100644
index 000000000000..e1cf1dcc3e36
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/tmdb/settings.py
@@ -0,0 +1,62 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField
+
+
+@dataclass
+class TMDbEndpointConfig:
+ path: str
+ # Key in the JSON response holding the list of rows. "results" for the paginated list/trending
+ # endpoints, "genres" for the genre lists, and None when the response body is itself a bare list
+ # (the configuration languages/countries endpoints).
+ data_key: Optional[str] = "results"
+ # Paginated endpoints expose `page` / `total_pages` and accept a `page` query param. The reference
+ # endpoints (genres, languages, countries) return everything in a single response.
+ paginated: bool = True
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # No TMDB v3 list endpoint exposes a server-side updated-after filter, so every endpoint is full
+ # refresh only. Kept for parity with other sources and in case the changes API is wired up later.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ should_sync_default: bool = True
+
+
+TMDB_ENDPOINTS: dict[str, TMDbEndpointConfig] = {
+ # Movies
+ "movie_popular": TMDbEndpointConfig(path="/movie/popular"),
+ "movie_top_rated": TMDbEndpointConfig(path="/movie/top_rated"),
+ "movie_now_playing": TMDbEndpointConfig(path="/movie/now_playing"),
+ "movie_upcoming": TMDbEndpointConfig(path="/movie/upcoming"),
+ # TV
+ "tv_popular": TMDbEndpointConfig(path="/tv/popular"),
+ "tv_top_rated": TMDbEndpointConfig(path="/tv/top_rated"),
+ "tv_on_the_air": TMDbEndpointConfig(path="/tv/on_the_air"),
+ "tv_airing_today": TMDbEndpointConfig(path="/tv/airing_today"),
+ # People
+ "person_popular": TMDbEndpointConfig(path="/person/popular"),
+ # Trending (daily window)
+ "trending_movies": TMDbEndpointConfig(path="/trending/movie/day"),
+ "trending_tv": TMDbEndpointConfig(path="/trending/tv/day"),
+ "trending_people": TMDbEndpointConfig(path="/trending/person/day"),
+ # Reference data — single response, no pagination
+ "movie_genres": TMDbEndpointConfig(path="/genre/movie/list", data_key="genres", paginated=False),
+ "tv_genres": TMDbEndpointConfig(path="/genre/tv/list", data_key="genres", paginated=False),
+ "languages": TMDbEndpointConfig(
+ path="/configuration/languages",
+ data_key=None,
+ paginated=False,
+ primary_keys=["iso_639_1"],
+ ),
+ "countries": TMDbEndpointConfig(
+ path="/configuration/countries",
+ data_key=None,
+ paginated=False,
+ primary_keys=["iso_3166_1"],
+ ),
+}
+
+ENDPOINTS = tuple(TMDB_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in TMDB_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/tmdb/source.py b/posthog/temporal/data_imports/sources/tmdb/source.py
index 371a22950f9f..1b8a0f96f3b0 100644
--- a/posthog/temporal/data_imports/sources/tmdb/source.py
+++ b/posthog/temporal/data_imports/sources/tmdb/source.py
@@ -1,20 +1,33 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import TMDbSourceConfig
+from posthog.temporal.data_imports.sources.tmdb.settings import ENDPOINTS, INCREMENTAL_FIELDS, TMDB_ENDPOINTS
+from posthog.temporal.data_imports.sources.tmdb.tmdb import (
+ TMDbResumeConfig,
+ tmdb_source,
+ validate_credentials as validate_tmdb_credentials,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class TMDbSource(SimpleSource[TMDbSourceConfig]):
+class TMDbSource(ResumableSource[TMDbSourceConfig, TMDbResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TMDB
@@ -25,7 +38,82 @@ class TMDbSource(SimpleSource[TMDbSourceConfig]):
name=SchemaExternalDataSourceType.TM_DB,
category=DataWarehouseSourceCategory.ANALYTICS,
label="TMDb",
+ caption="""Enter your TMDB API key to pull movie, TV, and people catalog data into the PostHog Data warehouse.
+
+Create a free API key (v3 auth) in your [TMDB account settings](https://www.themoviedb.org/settings/api). Commercial use requires a separate license from TMDB.""",
iconPath="/static/services/tmdb.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/tmdb",
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked TMDB API key surfaces as a 401 when `_fetch` calls
+ # `raise_for_status()`. Retrying can't fix a credential problem, so stop the sync.
+ "401 Client Error: Unauthorized for url: https://api.themoviedb.org": "Your TMDB API key is invalid or has been revoked. Create a new key in your TMDB account settings, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: TMDbSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ # TMDB v3 list endpoints expose no server-side updated-after filter, so every table is
+ # full refresh only.
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=TMDB_ENDPOINTS[endpoint].should_sync_default,
+ )
+ 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: TMDbSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_tmdb_credentials(config.api_key)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from posthog.temporal.data_imports.sources.tmdb.canonical_descriptions import CANONICAL_DESCRIPTIONS
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TMDbResumeConfig]:
+ return ResumableSourceManager[TMDbResumeConfig](inputs, TMDbResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: TMDbSourceConfig,
+ resumable_source_manager: ResumableSourceManager[TMDbResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return tmdb_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/posthog/temporal/data_imports/sources/tmdb/tests/test_tmdb.py b/posthog/temporal/data_imports/sources/tmdb/tests/test_tmdb.py
new file mode 100644
index 000000000000..cac648748cb1
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/tmdb/tests/test_tmdb.py
@@ -0,0 +1,205 @@
+import json
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import requests
+
+from posthog.temporal.data_imports.sources.tmdb import tmdb as tmdb_module
+from posthog.temporal.data_imports.sources.tmdb.settings import TMDB_ENDPOINTS
+from posthog.temporal.data_imports.sources.tmdb.tmdb import (
+ TMDbResumeConfig,
+ _build_url,
+ _extract_rows,
+ get_rows,
+ tmdb_source,
+ validate_credentials,
+)
+
+
+def _make_response(status_code: int, body: Any) -> requests.Response:
+ # A real Response so .json(), .ok, and .raise_for_status() behave exactly like production.
+ response = requests.Response()
+ response.status_code = status_code
+ response.url = "https://api.themoviedb.org/3/x"
+ response._content = json.dumps(body).encode()
+ return response
+
+
+def _fake_session(responses: list[requests.Response]) -> mock.MagicMock:
+ session = mock.MagicMock()
+ session.get.side_effect = responses
+ return session
+
+
+def _make_manager(resume: TMDbResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
[email protected](autouse=True)
+def _no_throttle(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(tmdb_module, "THROTTLE_SECONDS", 0)
+
+
+class TestExtractRows:
+ @pytest.mark.parametrize(
+ "endpoint, body, expected",
+ [
+ ("movie_popular", {"page": 1, "results": [{"id": 1}], "total_pages": 1}, [{"id": 1}]),
+ ("movie_genres", {"genres": [{"id": 28, "name": "Action"}]}, [{"id": 28, "name": "Action"}]),
+ ("languages", [{"iso_639_1": "en", "name": "English"}], [{"iso_639_1": "en", "name": "English"}]),
+ # Defensive: wrong-typed payloads degrade to empty rather than raising.
+ ("movie_popular", {"results": None}, []),
+ ("languages", {"unexpected": "object"}, []),
+ ],
+ )
+ def test_extract_rows(self, endpoint: str, body: Any, expected: list) -> None:
+ assert _extract_rows(body, TMDB_ENDPOINTS[endpoint]) == expected
+
+
+class TestBuildUrl:
+ def test_paginated_url_includes_page_and_language(self) -> None:
+ url = _build_url("/movie/popular", "secret", page=3)
+ assert url.startswith("https://api.themoviedb.org/3/movie/popular?")
+ assert "api_key=secret" in url
+ assert "page=3" in url
+ assert "language=en-US" in url
+
+ def test_non_paginated_url_omits_page(self) -> None:
+ url = _build_url("/configuration/languages", "secret")
+ assert "page=" not in url
+ assert "api_key=secret" in url
+
+
+class TestGetRows:
+ def test_paginates_until_total_pages_and_saves_state(self) -> None:
+ responses = [
+ _make_response(200, {"page": 1, "results": [{"id": 1}], "total_pages": 2}),
+ _make_response(200, {"page": 2, "results": [{"id": 2}], "total_pages": 2}),
+ ]
+ manager = _make_manager()
+ with mock.patch.object(tmdb_module, "make_tracked_session", return_value=_fake_session(responses)):
+ batches = list(get_rows("k", "movie_popular", mock.MagicMock(), manager))
+
+ assert batches == [[{"id": 1}], [{"id": 2}]]
+ # State saved after the first page only (the last page has nothing more to resume to).
+ manager.save_state.assert_called_once_with(TMDbResumeConfig(next_page=2))
+
+ def test_resumes_from_saved_page(self) -> None:
+ responses = [_make_response(200, {"page": 5, "results": [{"id": 5}], "total_pages": 5})]
+ manager = _make_manager(resume=TMDbResumeConfig(next_page=5))
+ session = _fake_session(responses)
+ with mock.patch.object(tmdb_module, "make_tracked_session", return_value=session):
+ batches = list(get_rows("k", "movie_popular", mock.MagicMock(), manager))
+
+ assert batches == [[{"id": 5}]]
+ # Picks up at page 5, not page 1.
+ assert "page=5" in session.get.call_args_list[0].args[0]
+ manager.save_state.assert_not_called()
+
+ def test_non_paginated_endpoint_yields_single_batch(self) -> None:
+ responses = [_make_response(200, {"genres": [{"id": 28, "name": "Action"}]})]
+ manager = _make_manager()
+ with mock.patch.object(tmdb_module, "make_tracked_session", return_value=_fake_session(responses)):
+ batches = list(get_rows("k", "movie_genres", mock.MagicMock(), manager))
+
+ assert batches == [[{"id": 28, "name": "Action"}]]
+ manager.save_state.assert_not_called()
+
+ def test_empty_results_first_page_yields_nothing(self) -> None:
+ responses = [_make_response(200, {"page": 1, "results": [], "total_pages": 0})]
+ manager = _make_manager()
+ with mock.patch.object(tmdb_module, "make_tracked_session", return_value=_fake_session(responses)):
+ batches = list(get_rows("k", "movie_popular", mock.MagicMock(), manager))
+
+ assert batches == []
+
+ def test_stops_at_max_pages(self) -> None:
+ # total_pages larger than the cap: page count must be bounded by MAX_PAGES, not total_pages.
+ responses = [
+ _make_response(200, {"page": p, "results": [{"id": p}], "total_pages": 10_000})
+ for p in range(1, tmdb_module.MAX_PAGES + 1)
+ ]
+ manager = _make_manager()
+ with mock.patch.object(tmdb_module, "make_tracked_session", return_value=_fake_session(responses)):
+ batches = list(get_rows("k", "movie_popular", mock.MagicMock(), manager))
+
+ assert len(batches) == tmdb_module.MAX_PAGES
+
+
+class TestRetry:
+ @pytest.mark.parametrize("status", [429, 500, 503])
+ def test_retryable_statuses_raise_retryable_error(self, status: int) -> None:
+ session = _fake_session([_make_response(status, {})])
+ # Call the undecorated fetch directly to assert the classification without backoff sleeps.
+ with pytest.raises(tmdb_module.TMDbRetryableError):
+ tmdb_module._do_fetch(session, "https://api.themoviedb.org/3/x", mock.MagicMock())
+
+ def test_client_error_raises_for_status(self) -> None:
+ session = _fake_session([_make_response(404, {})])
+ with pytest.raises(requests.HTTPError):
+ tmdb_module._do_fetch(session, "https://api.themoviedb.org/3/x", mock.MagicMock())
+
+ def test_error_message_scrubs_api_key_from_url(self) -> None:
+ # The api_key rides in the query string; a 4xx must not leak it into the propagated error.
+ response = _make_response(401, {"status_code": 7})
+ response.url = "https://api.themoviedb.org/3/configuration?api_key=supersecret&page=1"
+ session = _fake_session([response])
+ with pytest.raises(requests.HTTPError) as exc:
+ tmdb_module._do_fetch(session, "x", mock.MagicMock())
+ message = str(exc.value)
+ assert "supersecret" not in message
+ # Base host/path is preserved so get_non_retryable_errors() can still match on it.
+ assert "https://api.themoviedb.org/3/configuration" in message
+
+
+class TestValidateCredentials:
+ def test_valid_key_returns_no_message(self) -> None:
+ session = _fake_session([_make_response(200, {})])
+ with mock.patch.object(tmdb_module, "make_tracked_session", return_value=session):
+ assert validate_credentials("k") == (True, None)
+
+ def test_401_reports_invalid_key(self) -> None:
+ session = _fake_session([_make_response(401, {})])
+ with mock.patch.object(tmdb_module, "make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials("k")
+ assert is_valid is False
+ assert message == "Invalid TMDB API key"
+
+ @pytest.mark.parametrize("status", [404, 429, 500, 503])
+ def test_non_401_failure_does_not_claim_invalid_key(self, status: int) -> None:
+ # A transient/service-side failure must not be reported as an invalid credential.
+ session = _fake_session([_make_response(status, {})])
+ with mock.patch.object(tmdb_module, "make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials("k")
+ assert is_valid is False
+ assert message is not None
+ assert message != "Invalid TMDB API key"
+
+ def test_network_error_does_not_claim_invalid_key(self) -> None:
+ session = mock.MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with mock.patch.object(tmdb_module, "make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials("k")
+ assert is_valid is False
+ assert message is not None
+ assert message != "Invalid TMDB API key"
+
+
+class TestTMDbSource:
+ @pytest.mark.parametrize(
+ "endpoint, expected_keys",
+ [
+ ("movie_popular", ["id"]),
+ ("languages", ["iso_639_1"]),
+ ("countries", ["iso_3166_1"]),
+ ],
+ )
+ def test_source_response_primary_keys(self, endpoint: str, expected_keys: list[str]) -> None:
+ response = tmdb_source("k", endpoint, mock.MagicMock(), _make_manager())
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
diff --git a/posthog/temporal/data_imports/sources/tmdb/tests/test_tmdb_source.py b/posthog/temporal/data_imports/sources/tmdb/tests/test_tmdb_source.py
new file mode 100644
index 000000000000..939b52e2bac3
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/tmdb/tests/test_tmdb_source.py
@@ -0,0 +1,121 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import TMDbSourceConfig
+from posthog.temporal.data_imports.sources.tmdb.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.tmdb.source import TMDbSource
+from posthog.temporal.data_imports.sources.tmdb.tmdb import TMDbResumeConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestTMDbSource:
+ def setup_method(self) -> None:
+ self.source = TMDbSource()
+ self.team_id = 123
+ self.config = TMDbSourceConfig(api_key="tmdb-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.TMDB
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "TMDb"
+ assert config.label == "TMDb"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/tmdb.png"
+
+ 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_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)
+ # TMDB v3 exposes no server-side updated-after 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=["movie_popular"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "movie_popular"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ 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.themoviedb.org/3/movie/popular?api_key=x&page=1",
+ "401 Client Error: Unauthorized for url: https://api.themoviedb.org/3/configuration",
+ ],
+ )
+ 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)
+
+ @pytest.mark.parametrize(
+ "unrelated_error",
+ [
+ "500 Server Error for url: https://api.themoviedb.org/3/movie/popular",
+ "404 Client Error: Not Found for url: https://api.themoviedb.org/3/movie/0",
+ ],
+ )
+ def test_non_retryable_errors_ignore_unrelated(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)
+
+ @pytest.mark.parametrize(
+ "validate_result",
+ [
+ (True, None),
+ (False, "Invalid TMDB API key"),
+ (False, "Could not reach TMDB to validate your API key. Check your connection and try again."),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.tmdb.source.validate_tmdb_credentials")
+ def test_validate_credentials_passes_result_through(
+ self,
+ mock_validate: mock.MagicMock,
+ validate_result: tuple[bool, str | None],
+ ) -> None:
+ mock_validate.return_value = validate_result
+ assert self.source.validate_credentials(self.config, self.team_id) == validate_result
+ mock_validate.assert_called_once_with("tmdb-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 TMDbResumeConfig
+
+ def test_canonical_descriptions_keyed_by_known_endpoints(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ # Only documents endpoints that actually exist; partial coverage is allowed.
+ assert set(descriptions).issubset(set(ENDPOINTS))
+ assert "movie_popular" in descriptions
+
+ @mock.patch("posthog.temporal.data_imports.sources.tmdb.source.tmdb_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_tmdb_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "movie_popular"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_tmdb_source.assert_called_once()
+ kwargs = mock_tmdb_source.call_args.kwargs
+ assert kwargs["api_key"] == "tmdb-key"
+ assert kwargs["endpoint"] == "movie_popular"
+ assert kwargs["resumable_source_manager"] is manager
diff --git a/posthog/temporal/data_imports/sources/tmdb/tmdb.py b/posthog/temporal/data_imports/sources/tmdb/tmdb.py
new file mode 100644
index 000000000000..a649d41c47ea
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/tmdb/tmdb.py
@@ -0,0 +1,182 @@
+import time
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode, urlsplit, urlunsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.tmdb.settings import TMDB_ENDPOINTS, TMDbEndpointConfig
+
+TMDB_BASE_URL = "https://api.themoviedb.org/3"
+
+# TMDB list endpoints (popular/top_rated/...) and /discover are hard-capped at 500 pages server-side,
+# so there's no point requesting beyond that — it 422s.
+MAX_PAGES = 500
+
+# TMDB disabled its documented 40 req / 10s limit in 2019 but enforces an undocumented upper bound
+# (~50 req/s) to deter bulk scraping, blocking abusive IPs. A small inter-request delay keeps us well
+# under that ceiling. Patched to 0 in tests.
+THROTTLE_SECONDS = 0.05
+
+
+class TMDbRetryableError(Exception):
+ pass
+
+
+class TMDbResumeConfig:
+ # Next page number to fetch. Page-number pagination means a single integer is enough to resume.
+ next_page: int
+
+
+def _get_headers() -> dict[str, str]:
+ return {"Accept": "application/json"}
+
+
+def _build_url(path: str, api_key: str, page: int | None = None) -> str:
+ params: dict[str, Any] = {"api_key": api_key}
+ if page is not None:
+ params["page"] = page
+ params["language"] = "en-US"
+ return f"{TMDB_BASE_URL}{path}?{urlencode(params)}"
+
+
+def _scrub_url(url: str | None) -> str:
+ # The api_key rides in the query string, so strip the query before the URL reaches any error
+ # message or log line — otherwise a non-2xx response would leak the credential into job errors.
+ if not url:
+ return TMDB_BASE_URL
+ parts = urlsplit(url)
+ return urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))
+
+
+def _do_fetch(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict | list:
+ response = session.get(url, headers=_get_headers(), timeout=60)
+
+ # 429 carries a Retry-After header; tenacity's backoff handles the wait deterministically.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise TMDbRetryableError(f"TMDB API error (retryable): status={response.status_code}")
+
+ if not response.ok:
+ logger.error(f"TMDB API error: status={response.status_code}, body={response.text}")
+ # Raise with the api_key scrubbed from the URL rather than calling raise_for_status(), whose
+ # message embeds the full credential-bearing URL. The base host stays intact so
+ # `get_non_retryable_errors()` can still match on it.
+ raise requests.HTTPError(
+ f"{response.status_code} Client Error: {response.reason} for url: {_scrub_url(response.url)}",
+ response=response,
+ )
+
+ return response.json()
+
+
+# Wrap the bare fetch in tenacity retries. Kept as a separate assignment (rather than a decorator) so
+# tests can exercise the status-code classification in `_do_fetch` without driving the backoff loop.
+_fetch = retry(
+ retry=retry_if_exception_type((TMDbRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)(_do_fetch)
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ # /configuration is a cheap call that 200s for any valid key and 401s for an invalid one. Only a
+ # 401 means the key is wrong — a transient failure (5xx, network error, timeout) must not be
+ # reported as an invalid key, or a user with a perfectly valid key during a brief TMDB outage
+ # would be told to regenerate it.
+ url = _build_url("/configuration", api_key)
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_get_headers(), timeout=10)
+ except Exception:
+ return False, "Could not reach TMDB to validate your API key. Check your connection and try again."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid TMDB API key"
+ return (
+ False,
+ f"TMDB returned an unexpected response (status {response.status_code}) while validating your API key. Please try again.",
+ )
+
+
+def _extract_rows(data: dict | list, config: TMDbEndpointConfig) -> list[dict]:
+ if config.data_key is None:
+ # Bare-list endpoints (languages, countries).
+ return data if isinstance(data, list) else []
+ if isinstance(data, dict):
+ rows = data.get(config.data_key, [])
+ return rows if isinstance(rows, list) else []
+ return []
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TMDbResumeConfig],
+) -> Iterator[list[dict]]:
+ config = TMDB_ENDPOINTS[endpoint]
+ # One session reused across pages so urllib3 keeps the connection alive. The api_key lives in the
+ # query string, so redact it from logged URLs and captured samples.
+ session = make_tracked_session(redact_values=(api_key,))
+
+ if not config.paginated:
+ data = _fetch(session, _build_url(config.path, api_key), logger)
+ rows = _extract_rows(data, config)
+ if rows:
+ yield rows
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.next_page if resume else 1
+
+ while page <= MAX_PAGES:
+ data = _fetch(session, _build_url(config.path, api_key, page=page), logger)
+ rows = _extract_rows(data, config)
+ if rows:
+ yield rows
+
+ total_pages = data.get("total_pages", 0) if isinstance(data, dict) else 0
+ if page >= total_pages:
+ break
+
+ next_page = page + 1
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge
+ # dedupes on the primary key.
+ resumable_source_manager.save_state(TMDbResumeConfig(next_page=next_page))
+ page = next_page
+
+ if THROTTLE_SECONDS:
+ time.sleep(THROTTLE_SECONDS)
+
+
+def tmdb_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TMDbResumeConfig],
+) -> SourceResponse:
+ endpoint_config = TMDB_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=endpoint_config.primary_keys,
+ # Full refresh (replace) on small, bounded ranking/reference datasets whose date fields can be
+ # empty, so datetime partitioning isn't worthwhile here.
+ partition_count=1,
+ partition_size=1,
+ )