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): add 9 missing tables to the TMDb source (#116966)

Tom Owers9d40187a7891
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index a2c71227e1d0..dec3d8c30bb0 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -1156,8 +1156,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/tiktok_ads.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/tinyemail/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/tmdb.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/todoist/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/todoist/todoist.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/settings.py
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index c6ed73145db6..7c682b9b10c9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -12319,10 +12319,10 @@ Today (16): `countries`, `languages`, `movie_genres`, `movie_now_playing`, `movi
Diffed against: <https://developer.themoviedb.org/reference/movie-details>
-- [ ] `GET /3/discover/movie and /3/discover/tv` — The workhorse catalog query - lets a user pull arbitrary filtered slices instead of only the four curated popularity lists (high)
-- [ ] `GET /3/movie/{movie_id}/credits and /3/tv/{series_id}/aggregate_credits` — Cast and crew membership joining the movies/tv and people tables we already sync - the single most-wanted relation (high)
-- [ ] `GET /3/tv/{series_id}/season/{season_number} (seasons and episodes)` — Seasons and episodes are the child objects of every synced TV row; without them tv\_\* tables cannot be analyzed at episode grain (high)
-- [ ] `GET /3/watch/providers/movie, /3/watch/providers/tv, /3/watch/providers/regions` — Streaming-provider lookup tables that resolve the provider IDs returned by the per-title watch/providers endpoints (high)
+- [x] `GET /3/discover/movie and /3/discover/tv` — The workhorse catalog query - lets a user pull arbitrary filtered slices instead of only the four curated popularity lists (high)
+- [x] `GET /3/movie/{movie_id}/credits and /3/tv/{series_id}/aggregate_credits` — Cast and crew membership joining the movies/tv and people tables we already sync - the single most-wanted relation (high)
+- [x] `GET /3/tv/{series_id}/season/{season_number} (seasons and episodes)` — Seasons and episodes are the child objects of every synced TV row; without them tv\_\* tables cannot be analyzed at episode grain (high)
+- [x] `GET /3/watch/providers/movie, /3/watch/providers/tv, /3/watch/providers/regions` — Streaming-provider lookup tables that resolve the provider IDs returned by the per-title watch/providers endpoints (high)
- [ ] `GET /3/company/{company_id}` — Lookup table resolving the production_companies IDs already embedded in synced movie and tv rows (medium)
- [ ] `GET /3/network/{network_id}` — Lookup table resolving the network IDs on synced TV series rows (medium)
- [ ] `GET /3/certification/movie/list and /3/certification/tv/list` — Lookup tables of age/content certifications per country, needed to decode release_dates and content_ratings (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
index 9d774ac16fbe..fafdf92f6859 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
@@ -668,23 +668,25 @@ class RESTClient:
)
raise error
- response_hooks = hooks.get("response", [])
- if response_hooks:
- for hook in response_hooks:
- hook(response, request=request)
- else:
- # Redact any secret the URL carries (e.g. an api_key query param) out of the raised
- # HTTPError message before it propagates into a user-visible ``latest_error``.
- try:
+ # Redact any secret the URL carries (e.g. an api_key query param) out of the raised
+ # HTTPError message before it propagates into a user-visible ``latest_error``. Response
+ # hooks (``response_actions``) fall back to ``raise_for_status`` for unmatched 4xx, so they
+ # are covered too.
+ try:
+ response_hooks = hooks.get("response", [])
+ if response_hooks:
+ for hook in response_hooks:
+ hook(response, request=request)
+ else:
response.raise_for_status()
- except HTTPError as e:
- message = str(e)
- # Appended after the stock message, so non-retryable-error patterns — which match
- # the message as a substring — keep matching.
- identity = _error_identity(response)
- if identity:
- message = f"{message} | api error: {identity}"
- raise HTTPError(self._redact(message), response=e.response, request=e.request) from None
+ except HTTPError as e:
+ message = str(e)
+ # Appended after the stock message, so non-retryable-error patterns — which match
+ # the message as a substring — keep matching.
+ identity = _error_identity(response)
+ if identity:
+ message = f"{message} | api error: {identity}"
+ raise HTTPError(self._redact(message), response=e.response, request=e.request) from None
# Parse inside the retry so a truncated/partial body is reissued like a 429/5xx
# instead of bubbling up uncaught and failing the import.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_exception_redaction.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_exception_redaction.py
index 517658f4621e..34455df9d75a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_exception_redaction.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_exception_redaction.py
@@ -9,6 +9,9 @@ from requests import Response
from requests.exceptions import ConnectionError as RequestsConnectionError
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import (
+ create_response_hooks,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
RESTClient,
RESTClientRetryableError,
@@ -88,6 +91,25 @@ class TestExceptionRedaction:
assert "***" in message
assert "400" in message
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_client_error_raised_by_response_hook_masks_secret(self, MockSession) -> None:
+ # A response hook (response_actions) falls back to raise_for_status for unmatched 4xx; that
+ # error must be redacted just like the no-hook path.
+ mock_session = _make_client(SECRET, MockSession)
+ mock_session.send.return_value = _make_response(400, SECRET, reason="Bad Request")
+ client = RESTClient(
+ base_url="https://api.example.com",
+ auth=APIKeyAuth(api_key=SECRET, name="api_key", location="query"),
+ max_retry_attempts=1,
+ )
+ hooks = create_response_hooks([{"status_code": 404, "action": "ignore"}])
+ with pytest.raises(Exception) as excinfo:
+ list(client.paginate(path="/items", hooks=hooks))
+ message = str(excinfo.value)
+ assert SECRET not in message
+ assert "***" in message
+ assert "400" in message
+
@parameterized.expand(
[
# Twilio's shape: the code and the docs link are what name the cause.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/api_inventory.md
index ecb3d9e68fc0..92e45e19e7d3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/api_inventory.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/api_inventory.md
@@ -23,24 +23,50 @@ 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 |
+| 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 |
+| discover_movies | /discover/movie | paginated `results` | id |
+| discover_tv | /discover/tv | paginated `results` | id |
+| movie_watch_providers | /watch/providers/movie | single, `results` | provider_id |
+| tv_watch_providers | /watch/providers/tv | single, `results` | provider_id |
+| watch_provider_regions | /watch/providers/regions | single, `results` | iso_3166_1 |
+
+Both discover tables send `sort_by=vote_count.desc` and `include_adult=false`. Vote counts change
+slowly, so the same 10,000 titles (the 500-page cap) stay in the table from one sync to the next.
+
+## Per-title endpoints (fan-out)
+
+These endpoints run once for each row of their parent. They start disabled because each sync makes
+one request per discover title (up to 10,000), plus one per season for `tv_episodes`. A 404 for one
+title (removed after the listing) is skipped.
+
+| Schema | Path | Parent | Row | Primary key |
+| -------------------- | -------------------------------------- | --------------- | ------------------------ | -------------------- |
+| movie_credits | /movie/{movie_id}/credits | discover_movies | one per cast/crew credit | movie_id, credit_id |
+| tv_aggregate_credits | /tv/{series_id}/aggregate_credits | discover_tv | one per role or job | series_id, credit_id |
+| tv_seasons | /tv/{series_id} (`seasons`) | discover_tv | one per season | series_id, id |
+| tv_episodes | /tv/{series_id}/season/{season_number} | tv_seasons | one per episode | show_id, id |
+
+`tv_seasons` reads the season list from the series details, because that is one request per show
+instead of one per season. `tv_episodes` is a two-level fan-out (discover → series details →
+season), which the shared framework cannot checkpoint, so a retry restarts it. The single-level
+fan-outs resume by parent path.
## Rate limiting
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/canonical_descriptions.py
index 8871dc4be730..c22c13cfa352 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/canonical_descriptions.py
@@ -51,6 +51,14 @@ _GENRE_COLUMNS = {
"name": "Human-readable genre name.",
}
+_WATCH_PROVIDER_COLUMNS = {
+ "provider_id": "TMDB's unique identifier for the watch provider (primary key).",
+ "provider_name": "Display name of the provider.",
+ "logo_path": "Relative path to the provider logo image.",
+ "display_priority": "Default sort position of the provider.",
+ "display_priorities": "Sort position of the provider per country, keyed by ISO 3166-1 code.",
+}
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"movie_popular": {
"description": "Movies ordered by TMDB popularity.",
@@ -140,4 +148,104 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"native_name": "Country name in its native language.",
},
},
+ "discover_movies": {
+ "description": "Up to 10,000 movies from TMDB's discover endpoint, ordered by vote count (most-voted first).",
+ "docs_url": "https://developer.themoviedb.org/reference/discover-movie",
+ "columns": _MOVIE_COLUMNS,
+ },
+ "discover_tv": {
+ "description": "Up to 10,000 TV shows from TMDB's discover endpoint, ordered by vote count (most-voted first).",
+ "docs_url": "https://developer.themoviedb.org/reference/discover-tv",
+ "columns": _TV_COLUMNS,
+ },
+ "movie_credits": {
+ "description": "Cast and crew credits for each movie in discover_movies, one row per credit.",
+ "docs_url": "https://developer.themoviedb.org/reference/movie-credits",
+ "columns": {
+ "movie_id": "TMDB ID of the movie the credit belongs to (join against the movie tables).",
+ "credit_id": "TMDB's unique identifier for the credit.",
+ "credit_type": "Either 'cast' or 'crew'.",
+ "id": "TMDB ID of the person credited (join against the people tables).",
+ "name": "Person's name.",
+ "original_name": "Person's name in its original script.",
+ "known_for_department": "Department the person is best known for.",
+ "character": "Character played. Cast credits only.",
+ "cast_id": "Position identifier of the cast entry. Cast credits only.",
+ "order": "Billing order of the cast member, starting at 0. Cast credits only.",
+ "department": "Department of the crew job, e.g. Directing. Crew credits only.",
+ "job": "Crew job title, e.g. Director. Crew credits only.",
+ },
+ },
+ "tv_aggregate_credits": {
+ "description": "Cast and crew credits across all seasons of each TV show in discover_tv, one row per role or job.",
+ "docs_url": "https://developer.themoviedb.org/reference/tv-series-aggregate-credits",
+ "columns": {
+ "series_id": "TMDB ID of the TV show the credit belongs to (join against the TV tables).",
+ "credit_id": "TMDB's unique identifier for the role or job.",
+ "credit_type": "Either 'cast' or 'crew'.",
+ "id": "TMDB ID of the person credited (join against the people tables).",
+ "name": "Person's name.",
+ "character": "Character played in this role. Cast credits only.",
+ "job": "Crew job title. Crew credits only.",
+ "department": "Department of the crew job. Crew credits only.",
+ "episode_count": "Number of episodes the person has in this role or job.",
+ "total_episode_count": "Number of episodes the person has across all roles or jobs.",
+ "order": "Billing order of the cast member. Cast credits only.",
+ },
+ },
+ "tv_seasons": {
+ "description": "Seasons of each TV show in discover_tv, from the show's details.",
+ "docs_url": "https://developer.themoviedb.org/reference/tv-series-details",
+ "columns": {
+ "series_id": "TMDB ID of the TV show the season belongs to.",
+ "id": "TMDB's unique identifier for the season.",
+ "season_number": "Season number. Season 0 holds specials.",
+ "name": "Season name.",
+ "overview": "Season summary.",
+ "air_date": "Date the season first aired (YYYY-MM-DD).",
+ "episode_count": "Number of episodes in the season.",
+ "vote_average": "Mean user rating on a 0–10 scale.",
+ "poster_path": "Relative path to the season poster image.",
+ },
+ },
+ "tv_episodes": {
+ "description": "Episodes of every season of each TV show in discover_tv.",
+ "docs_url": "https://developer.themoviedb.org/reference/tv-season-details",
+ "columns": {
+ "id": "TMDB's unique identifier for the episode.",
+ "show_id": "TMDB ID of the TV show the episode belongs to.",
+ "season_number": "Season number of the episode.",
+ "episode_number": "Episode number within the season.",
+ "episode_type": "Episode type, e.g. standard or finale.",
+ "name": "Episode title.",
+ "overview": "Episode summary.",
+ "air_date": "Date the episode aired (YYYY-MM-DD).",
+ "runtime": "Runtime in minutes.",
+ "production_code": "Production code of the episode.",
+ "vote_average": "Mean user rating on a 0–10 scale.",
+ "vote_count": "Number of user votes contributing to vote_average.",
+ "still_path": "Relative path to the episode still image.",
+ "crew": "List of crew members credited on the episode.",
+ "guest_stars": "List of guest stars credited on the episode.",
+ },
+ },
+ "movie_watch_providers": {
+ "description": "Streaming, rental and purchase providers TMDB lists for movies.",
+ "docs_url": "https://developer.themoviedb.org/reference/watch-providers-movie-list",
+ "columns": _WATCH_PROVIDER_COLUMNS,
+ },
+ "tv_watch_providers": {
+ "description": "Streaming, rental and purchase providers TMDB lists for TV shows.",
+ "docs_url": "https://developer.themoviedb.org/reference/watch-provider-tv-list",
+ "columns": _WATCH_PROVIDER_COLUMNS,
+ },
+ "watch_provider_regions": {
+ "description": "Countries that TMDB has watch provider data for.",
+ "docs_url": "https://developer.themoviedb.org/reference/watch-providers-available-regions",
+ "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/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/settings.py
index 66d67d3b126c..25ec1364ead3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/settings.py
@@ -1,10 +1,10 @@
from dataclasses import dataclass, field
-from typing import Optional
+from typing import Any, Optional
from products.warehouse_sources.backend.types import IncrementalField
-@dataclass
+@dataclass(frozen=False)
class TMDbEndpointConfig:
path: str
# Key in the JSON response holding the list of rows. "results" for the paginated list/trending
@@ -19,6 +19,16 @@ class TMDbEndpointConfig:
# 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
+ params: dict[str, Any] = field(default_factory=dict)
+ # Set for endpoints that run once per row of another endpoint. `parent` names that endpoint, and
+ # `resolve_fields` maps each `{placeholder}` in `path` to the parent row field that fills it.
+ parent: Optional[str] = None
+ resolve_fields: dict[str, str] = field(default_factory=dict)
+
+
+# Discover returns at most 500 pages like the curated lists. Vote count changes slowly, so this
+# order keeps the same titles in the table, and in the per-title tables below, from one sync to the next.
+DISCOVER_PARAMS: dict[str, Any] = {"sort_by": "vote_count.desc", "include_adult": "false"}
TMDB_ENDPOINTS: dict[str, TMDbEndpointConfig] = {
@@ -38,6 +48,46 @@ TMDB_ENDPOINTS: dict[str, TMDbEndpointConfig] = {
"trending_movies": TMDbEndpointConfig(path="/trending/movie/day"),
"trending_tv": TMDbEndpointConfig(path="/trending/tv/day"),
"trending_people": TMDbEndpointConfig(path="/trending/person/day"),
+ # Discover
+ "discover_movies": TMDbEndpointConfig(path="/discover/movie", params=DISCOVER_PARAMS),
+ "discover_tv": TMDbEndpointConfig(path="/discover/tv", params=DISCOVER_PARAMS),
+ # Per-title tables. Each one makes a request for every discover title, so they start disabled.
+ "movie_credits": TMDbEndpointConfig(
+ path="/movie/{movie_id}/credits",
+ data_key=None,
+ paginated=False,
+ primary_keys=["movie_id", "credit_id"],
+ should_sync_default=False,
+ parent="discover_movies",
+ resolve_fields={"movie_id": "id"},
+ ),
+ "tv_aggregate_credits": TMDbEndpointConfig(
+ path="/tv/{series_id}/aggregate_credits",
+ data_key=None,
+ paginated=False,
+ primary_keys=["series_id", "credit_id"],
+ should_sync_default=False,
+ parent="discover_tv",
+ resolve_fields={"series_id": "id"},
+ ),
+ "tv_seasons": TMDbEndpointConfig(
+ path="/tv/{series_id}",
+ data_key=None,
+ paginated=False,
+ primary_keys=["series_id", "id"],
+ should_sync_default=False,
+ parent="discover_tv",
+ resolve_fields={"series_id": "id"},
+ ),
+ "tv_episodes": TMDbEndpointConfig(
+ path="/tv/{series_id}/season/{season_number}",
+ data_key=None,
+ paginated=False,
+ primary_keys=["show_id", "id"],
+ should_sync_default=False,
+ parent="tv_seasons",
+ resolve_fields={"series_id": "series_id", "season_number": "season_number"},
+ ),
# 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),
@@ -53,6 +103,13 @@ TMDB_ENDPOINTS: dict[str, TMDbEndpointConfig] = {
paginated=False,
primary_keys=["iso_3166_1"],
),
+ "movie_watch_providers": TMDbEndpointConfig(
+ path="/watch/providers/movie", paginated=False, primary_keys=["provider_id"]
+ ),
+ "tv_watch_providers": TMDbEndpointConfig(path="/watch/providers/tv", paginated=False, primary_keys=["provider_id"]),
+ "watch_provider_regions": TMDbEndpointConfig(
+ path="/watch/providers/regions", paginated=False, primary_keys=["iso_3166_1"]
+ ),
}
ENDPOINTS = tuple(TMDB_ENDPOINTS.keys())
@@ -60,3 +117,5 @@ ENDPOINTS = tuple(TMDB_ENDPOINTS.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
name: config.incremental_fields for name, config in TMDB_ENDPOINTS.items()
}
+
+SHOULD_SYNC_DEFAULT: dict[str, bool] = {name: config.should_sync_default for name, config in TMDB_ENDPOINTS.items()}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/source.py
index 37db82b4338d..a3fc8ec96390 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/source.py
@@ -19,9 +19,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.tmdb import TMDbSourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.tmdb.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from products.warehouse_sources.backend.temporal.data_imports.sources.tmdb.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ SHOULD_SYNC_DEFAULT,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.tmdb.tmdb import (
TMDbResumeConfig,
+ endpoint_supports_resume,
tmdb_source,
validate_credentials as validate_tmdb_credentials,
)
@@ -38,6 +43,16 @@ class TMDbSource(ResumableSource[TMDbSourceConfig, TMDbResumeConfig]):
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TMDB
+ def resume_covers_run(
+ self,
+ *,
+ incremental_or_append: bool,
+ schema_name: str | None = None,
+ ) -> bool:
+ # An endpoint that cannot checkpoint restarts from the first title on every attempt, so the
+ # larger resumable retry budget would only repeat the whole fan-out.
+ return schema_name is None or schema_name not in ENDPOINTS or endpoint_supports_resume(schema_name)
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
@@ -84,7 +99,7 @@ Create a free API key (v3 auth) in your [TMDB account settings](https://www.them
) -> list[SourceSchema]:
# TMDB v3 list endpoints expose no server-side updated-after filter, so every endpoint has
# empty incremental fields and is full refresh only.
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, should_sync_default=SHOULD_SYNC_DEFAULT)
def validate_credentials(
self, config: TMDbSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/tests/test_tmdb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/tests/test_tmdb.py
index 8ecd7870b3c2..8539e6e1bae5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/tests/test_tmdb.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/tests/test_tmdb.py
@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tes
ScriptedResponse,
SourceDriver,
always,
+ route,
scripted_network,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.tmdb import TMDbSourceConfig
@@ -29,10 +30,22 @@ def _source(endpoint: str, script: Script, resume: TMDbResumeConfig | None = Non
return driver.run(endpoint, script, resume_state=resume)
+def _not_found() -> ScriptedResponse:
+ return ScriptedResponse(status=404, json={"status_code": 34, "success": False})
+
+
class TestPagination:
- def test_paginates_until_total_pages_and_saves_state(self) -> None:
+ @pytest.mark.parametrize(
+ "endpoint, expected_sort_by",
+ [
+ ("movie_popular", None),
+ ("discover_movies", "vote_count.desc"),
+ ("discover_tv", "vote_count.desc"),
+ ],
+ )
+ def test_paginates_until_total_pages_and_saves_state(self, endpoint: str, expected_sort_by: str | None) -> None:
result = _source(
- "movie_popular",
+ endpoint,
[
_page_response([{"id": 1}], page=1, total_pages=2),
_page_response([{"id": 2}], page=2, total_pages=2),
@@ -42,6 +55,7 @@ class TestPagination:
assert result.rows == [{"id": 1}, {"id": 2}]
assert result.params("page") == ["1", "2"]
assert result.requests[0].param("language") == "en-US"
+ assert result.params("sort_by") == [expected_sort_by, expected_sort_by]
# State saved after the first page only (the last page has nothing more to resume to).
assert result.saved_states == [TMDbResumeConfig(next_page=2)]
@@ -66,6 +80,191 @@ class TestNonPaginatedEndpoints:
assert result.saved_states == []
+class TestPerTitleEndpoints:
+ @pytest.mark.parametrize(
+ "endpoint, parent_path, child_body, expected_rows",
+ [
+ (
+ "movie_credits",
+ "/discover/movie",
+ {
+ "id": 1,
+ "cast": [{"id": 10, "credit_id": "c1", "character": "Pilot", "order": 0}],
+ "crew": [{"id": 11, "credit_id": "c2", "department": "Directing", "job": "Director"}],
+ },
+ [
+ {
+ "id": 10,
+ "credit_id": "c1",
+ "character": "Pilot",
+ "order": 0,
+ "movie_id": 1,
+ "credit_type": "cast",
+ },
+ {
+ "id": 11,
+ "credit_id": "c2",
+ "department": "Directing",
+ "job": "Director",
+ "movie_id": 1,
+ "credit_type": "crew",
+ },
+ ],
+ ),
+ ("movie_credits", "/discover/movie", {"id": 1, "cast": [], "crew": None}, []),
+ (
+ "tv_aggregate_credits",
+ "/discover/tv",
+ {
+ "id": 1,
+ "cast": [
+ {
+ "id": 10,
+ "name": "Actor A",
+ "total_episode_count": 5,
+ "roles": [
+ {"credit_id": "r1", "character": "Captain", "episode_count": 3},
+ {"credit_id": "r2", "character": "Twin", "episode_count": 2},
+ ],
+ },
+ {"id": 12, "name": "Actor B", "roles": []},
+ ],
+ "crew": [
+ {
+ "id": 11,
+ "department": "Writing",
+ "jobs": [{"credit_id": "j1", "job": "Writer", "episode_count": 4}],
+ }
+ ],
+ },
+ [
+ {
+ "id": 10,
+ "name": "Actor A",
+ "total_episode_count": 5,
+ "credit_id": "r1",
+ "character": "Captain",
+ "episode_count": 3,
+ "series_id": 1,
+ "credit_type": "cast",
+ },
+ {
+ "id": 10,
+ "name": "Actor A",
+ "total_episode_count": 5,
+ "credit_id": "r2",
+ "character": "Twin",
+ "episode_count": 2,
+ "series_id": 1,
+ "credit_type": "cast",
+ },
+ {
+ "id": 11,
+ "department": "Writing",
+ "credit_id": "j1",
+ "job": "Writer",
+ "episode_count": 4,
+ "series_id": 1,
+ "credit_type": "crew",
+ },
+ ],
+ ),
+ (
+ "tv_seasons",
+ "/discover/tv",
+ {
+ "id": 1,
+ "name": "Series",
+ "seasons": [{"id": 100, "season_number": 0}, {"id": 101, "season_number": 1}],
+ },
+ [{"id": 100, "season_number": 0, "series_id": 1}, {"id": 101, "season_number": 1, "series_id": 1}],
+ ),
+ ("tv_seasons", "/discover/tv", {"id": 1, "name": "Series"}, []),
+ ],
+ )
+ def test_fans_out_over_discover_and_flattens_rows(
+ self,
+ endpoint: str,
+ parent_path: str,
+ child_body: dict[str, Any],
+ expected_rows: list[dict[str, Any]],
+ ) -> None:
+ # Title 2 left the catalog after the listing; its 404 must not fail the sync.
+ result = _source(
+ endpoint,
+ route(
+ {
+ parent_path: [_page_response([{"id": 1}, {"id": 2}], page=1, total_pages=1)],
+ "/1/credits": [ScriptedResponse(json=child_body)],
+ "/1/aggregate_credits": [ScriptedResponse(json=child_body)],
+ "/tv/1": [ScriptedResponse(json=child_body)],
+ "/2/credits": [_not_found()],
+ "/2/aggregate_credits": [_not_found()],
+ "/tv/2": [_not_found()],
+ }
+ ),
+ )
+
+ assert result.raised is None
+ assert result.rows == expected_rows
+ assert result.paths[0] == f"/3{parent_path}"
+ assert result.params("sort_by")[0] == "vote_count.desc"
+ assert len(result.paths) == 3
+ assert result.saved_states[-1].completed is not None
+ assert len(result.saved_states[-1].completed) == 2
+
+ def test_resumes_fan_out_after_completed_titles(self) -> None:
+ result = _source(
+ "movie_credits",
+ route(
+ {
+ "/discover/movie": [_page_response([{"id": 1}, {"id": 2}], page=1, total_pages=1)],
+ "/movie/2/credits": [ScriptedResponse(json={"id": 2, "cast": [{"credit_id": "c9"}]})],
+ }
+ ),
+ resume=TMDbResumeConfig(completed=["/movie/1/credits"]),
+ )
+
+ assert result.raised is None
+ assert result.paths == ["/3/discover/movie", "/3/movie/2/credits"]
+ assert result.rows == [{"credit_id": "c9", "movie_id": 2, "credit_type": "cast"}]
+
+ def test_episodes_fan_out_over_every_season_of_every_series(self) -> None:
+ result = _source(
+ "tv_episodes",
+ route(
+ {
+ "/discover/tv": [_page_response([{"id": 1}, {"id": 2}], page=1, total_pages=1)],
+ "/tv/1": [
+ ScriptedResponse(json={"id": 1, "seasons": [{"season_number": 0}, {"season_number": 1}]})
+ ],
+ "/tv/2": [_not_found()],
+ "/tv/1/season/0": [ScriptedResponse(json={"id": 50, "episodes": []})],
+ "/tv/1/season/1": [
+ ScriptedResponse(
+ json={
+ "id": 51,
+ "episodes": [
+ {"id": 500, "show_id": 1, "season_number": 1, "episode_number": 1},
+ {"id": 501, "show_id": 1, "season_number": 1, "episode_number": 2},
+ ],
+ }
+ )
+ ],
+ }
+ ),
+ )
+
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == [500, 501]
+ assert sorted(result.paths) == sorted(
+ ["/3/discover/tv", "/3/tv/1", "/3/tv/2", "/3/tv/1/season/0", "/3/tv/1/season/1"]
+ )
+ assert result.response is not None
+ assert result.response.supports_resume is False
+ assert result.saved_states == []
+
+
class TestErrorRedaction:
def test_401_scrubs_api_key_but_preserves_host(self) -> None:
# The api_key rides in the query string; a 4xx must not leak it into the propagated error,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/tests/test_tmdb_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/tests/test_tmdb_source.py
index 11827cf4f12b..8a48e412f5e3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/tests/test_tmdb_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/tests/test_tmdb_source.py
@@ -1,5 +1,5 @@
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.tmdb import TMDbSourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.tmdb.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.tmdb.settings import ENDPOINTS, TMDB_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.tmdb.source import TMDbSource
@@ -16,6 +16,15 @@ class TestTMDbSource:
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)
+ # Per-title tables make one request per discover title, so a new source must not enable them.
+ assert all(s.should_sync_default is (TMDB_ENDPOINTS[s.name].parent is None) for s in schemas)
+
+ def test_resume_covers_run_excludes_endpoints_that_cannot_checkpoint(self) -> None:
+ # tv_episodes fans out two levels, which the framework cannot checkpoint, so it must not get
+ # the resumable retry budget.
+ assert self.source.resume_covers_run(incremental_or_append=False, schema_name="tv_episodes") is False
+ assert self.source.resume_covers_run(incremental_or_append=False, schema_name="movie_credits") is True
+ assert self.source.resume_covers_run(incremental_or_append=False, schema_name="discover_movies") is True
def test_canonical_descriptions_keyed_by_known_endpoints(self) -> None:
descriptions = self.source.get_canonical_descriptions()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/tmdb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/tmdb.py
index 967d145f7fef..b76fe582a27c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/tmdb.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tmdb/tmdb.py
@@ -1,16 +1,21 @@
import dataclasses
+from collections.abc import Callable
from typing import Any, Optional
from urllib.parse import urlencode
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.rest_source import (
RESTAPIConfig,
- rest_api_resource,
+ rest_api_resources,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
PageNumberPaginator,
SinglePagePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ Endpoint,
+ EndpointResource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -23,20 +28,58 @@ TMDB_BASE_URL = "https://api.themoviedb.org/3"
MAX_PAGES = 500
[email protected](frozen=False)
class TMDbResumeConfig:
# Next page number to fetch. Page-number pagination means a single integer is enough to resume.
- next_page: int
+ next_page: int | None = None
+ # Per-title endpoints resume by parent: the child paths already synced, the one in progress, and
+ # its paginator state. See `common.rest_source.__init__._make_paginate_dependent_resource`.
+ completed: list[str] | None = None
+ current: str | None = None
+ child_state: dict[str, Any] | None = None
-def tmdb_source(
- api_key: str,
- endpoint: str,
- team_id: int,
- job_id: str,
- resumable_source_manager: ResumableSourceManager[TMDbResumeConfig],
-) -> SourceResponse:
- config = TMDB_ENDPOINTS[endpoint]
+RowMapper = Callable[[dict[str, Any]], list[dict[str, Any]]]
+
+
+def _movie_credit_rows(body: dict[str, Any]) -> list[dict[str, Any]]:
+ return [
+ {**credit, "movie_id": body.get("id"), "credit_type": credit_type}
+ for credit_type in ("cast", "crew")
+ for credit in body.get(credit_type) or []
+ ]
+
+
+def _tv_aggregate_credit_rows(body: dict[str, Any]) -> list[dict[str, Any]]:
+ # Aggregate credits nest one entry per role (cast) or job (crew) under each person. One row per
+ # role or job gives every row its own credit_id, like the movie credits table.
+ rows = []
+ for credit_type, nested_key in (("cast", "roles"), ("crew", "jobs")):
+ for person in body.get(credit_type) or []:
+ person_fields = {key: value for key, value in person.items() if key != nested_key}
+ for credit in person.get(nested_key) or []:
+ rows.append({**person_fields, **credit, "series_id": body.get("id"), "credit_type": credit_type})
+ return rows
+
+
+def _tv_season_rows(body: dict[str, Any]) -> list[dict[str, Any]]:
+ return [{**season, "series_id": body.get("id")} for season in body.get("seasons") or []]
+
+
+def _tv_episode_rows(body: dict[str, Any]) -> list[dict[str, Any]]:
+ return list(body.get("episodes") or [])
+
+
+ROW_MAPPERS: dict[str, RowMapper] = {
+ "movie_credits": _movie_credit_rows,
+ "tv_aggregate_credits": _tv_aggregate_credit_rows,
+ "tv_seasons": _tv_season_rows,
+ "tv_episodes": _tv_episode_rows,
+}
+
+
+def _resource(name: str) -> EndpointResource:
+ config = TMDB_ENDPOINTS[name]
if config.paginated:
# TMDB list/trending endpoints paginate with `page` / `total_pages`; stop after the last page
@@ -49,10 +92,70 @@ def tmdb_source(
)
# Only paginated requests carry `language`; the reference endpoints omit it, matching the
# previous hand-rolled URL builder exactly.
- params: dict[str, Any] = {"language": "en-US"}
+ params: dict[str, Any] = {"language": "en-US", **config.params}
else:
paginator = SinglePagePaginator()
- params = {}
+ params = dict(config.params)
+
+ for path_param, parent_field in config.resolve_fields.items():
+ params[path_param] = {"type": "resolve", "resource": config.parent, "field": parent_field}
+
+ endpoint: Endpoint = {
+ "path": config.path,
+ "params": params,
+ # None for the bare-list configuration endpoints (languages/countries) and the per-title
+ # objects; "results" or "genres" otherwise. Not marked required: a malformed body degrades
+ # to empty rows rather than failing loud, matching the previous behavior.
+ "data_selector": config.data_key,
+ "paginator": paginator,
+ }
+ if config.parent is not None:
+ # A title can leave the catalog between the discover listing and its own request.
+ endpoint["response_actions"] = [{"status_code": 404, "action": "ignore"}]
+
+ resource: EndpointResource = {"name": name, "endpoint": endpoint}
+ row_mapper = ROW_MAPPERS.get(name)
+ if row_mapper is not None:
+ resource["data_map"] = row_mapper
+ return resource
+
+
+def _resource_chain(endpoint: str) -> list[EndpointResource]:
+ """The endpoint and every parent it fans out over, root first."""
+ chain: list[EndpointResource] = []
+ name: Optional[str] = endpoint
+ while name is not None:
+ chain.insert(0, _resource(name))
+ name = TMDB_ENDPOINTS[name].parent
+ return chain
+
+
+def _fanout_depth(endpoint: str) -> int:
+ depth = 0
+ parent = TMDB_ENDPOINTS[endpoint].parent
+ while parent is not None:
+ depth += 1
+ parent = TMDB_ENDPOINTS[parent].parent
+ return depth
+
+
+def endpoint_supports_resume(endpoint: str) -> bool:
+ # The framework cannot checkpoint a fan-out of two or more levels (tv_episodes), so a retry of
+ # that table starts again from the first title.
+ return _fanout_depth(endpoint) <= 1
+
+
+def tmdb_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[TMDbResumeConfig],
+) -> SourceResponse:
+ config = TMDB_ENDPOINTS[endpoint]
+ resources = _resource_chain(endpoint)
+ fanout_depth = len(resources) - 1
+ supports_resume = endpoint_supports_resume(endpoint)
rest_config: RESTAPIConfig = {
"client": {
@@ -63,47 +166,53 @@ def tmdb_source(
"auth": {"type": "api_key", "api_key": api_key, "name": "api_key", "location": "query"},
},
"resource_defaults": {},
- "resources": [
- {
- "name": endpoint,
- "endpoint": {
- "path": config.path,
- "params": params,
- # None for the bare-list configuration endpoints (languages/countries); "results"
- # or "genres" otherwise. Not marked required: a malformed body degrades to empty
- # rows rather than failing loud, matching the previous behavior.
- "data_selector": config.data_key,
- "paginator": paginator,
- },
- }
- ],
+ "resources": [*resources],
}
initial_paginator_state: Optional[dict[str, Any]] = None
- if config.paginated and resumable_source_manager.can_resume():
+ if supports_resume and resumable_source_manager.can_resume():
resume = resumable_source_manager.load_state()
if resume is not None:
- initial_paginator_state = {"page": resume.next_page}
+ if fanout_depth == 0 and config.paginated and resume.next_page is not None:
+ initial_paginator_state = {"page": resume.next_page}
+ elif fanout_depth == 1 and (resume.completed or resume.current):
+ initial_paginator_state = {
+ "completed": resume.completed or [],
+ "current": resume.current,
+ "child_state": resume.child_state,
+ }
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if not state:
+ return
+ if fanout_depth == 1:
+ resumable_source_manager.save_state(
+ TMDbResumeConfig(
+ completed=state.get("completed"),
+ current=state.get("current"),
+ child_state=state.get("child_state"),
+ )
+ )
# Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields the
# last page (merge dedupes on the primary key) rather than skipping it.
- if state and state.get("page") is not None:
+ elif state.get("page") is not None:
resumable_source_manager.save_state(TMDbResumeConfig(next_page=int(state["page"])))
- resource = rest_api_resource(
+ built = rest_api_resources(
rest_config,
team_id,
job_id,
None, # every TMDB endpoint is full refresh — no server-side updated-after filter
- resume_hook=save_checkpoint,
+ resume_hook=save_checkpoint if supports_resume else None,
initial_paginator_state=initial_paginator_state,
)
+ resource = next(r for r in built if r.name == endpoint)
return SourceResponse(
name=endpoint,
items=lambda: resource,
primary_keys=config.primary_keys,
+ supports_resume=supports_resume,
# 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,