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 3 missing tables to the YouTube Analytics source (#118266)

Tom Owersc9e21253d88d
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 7821c3a5a764..f50876963a37 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
@@ -13413,10 +13413,10 @@ Today (10): `channel_daily`, `demographics`, `device_types`, `geography`, `opera
Diffed against: <https://developers.google.com/youtube/analytics/channel_reports>
-- [ ] `Videos (GET /youtube/v3/videos, part=snippet,contentDetails)` — resolve video IDs in top_videos to titles, publication dates, durations, and content categories (high)
+- [x] `Videos (GET /youtube/v3/videos, part=snippet,contentDetails)` — resolve video IDs in top_videos to titles, publication dates, durations, and content categories (high)
- [ ] `Estimated revenue reports (GET /v2/reports, metrics=estimatedRevenue,estimatedAdRevenue,estimatedRedPartnerRevenue)` — measure channel earnings and revenue trends that the existing viewing reports cannot produce (high)
-- [ ] `Audience retention (GET /v2/reports, dimensions=elapsedVideoTimeRatio)` — identify where viewers leave or replay each video, beyond its average viewing duration (high)
-- [ ] `Traffic source detail (GET /v2/reports, dimensions=insightTrafficSourceDetail)` — identify search terms, referring sites, and related videos behind broad traffic source totals (medium)
+- [x] `Audience retention (GET /v2/reports, dimensions=elapsedVideoTimeRatio)` — identify where viewers leave or replay each video, beyond its average viewing duration (high)
+- [x] `Traffic source detail (GET /v2/reports, dimensions=insightTrafficSourceDetail)` — identify search terms, referring sites, and related videos behind broad traffic source totals (medium)
- [ ] `Playlist reports (GET /v2/reports, filters=playlist=={playlist_id})` — measure playlist starts, viewing time, and views per start to compare playlist performance (medium)
- [ ] `Ad performance by ad type (GET /v2/reports, dimensions=adType)` — compare advertising impressions, gross revenue, and CPM across ad formats (medium)
- [ ] `Concurrent viewers (GET /v2/reports, dimensions=livestreamPosition)` — analyze live audience peaks and viewing patterns during each broadcast (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/canonical_descriptions.py
index aee7795445f6..9c115648682d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/canonical_descriptions.py
@@ -2,6 +2,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
CanonicalDescriptions,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.settings import (
+ AUDIENCE_RETENTION,
CHANNEL_DAILY,
DEMOGRAPHICS,
DEVICE_TYPES,
@@ -11,11 +12,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_an
SHARING_SERVICES,
SUBSCRIBED_STATUS,
TOP_VIDEOS,
+ TRAFFIC_SOURCE_DETAILS,
TRAFFIC_SOURCES,
+ VIDEOS,
)
_METRICS_DOCS_URL = "https://developers.google.com/youtube/analytics/metrics"
_DIMENSIONS_DOCS_URL = "https://developers.google.com/youtube/analytics/dimensions"
+_VIDEOS_DOCS_URL = "https://developers.google.com/youtube/v3/docs/videos"
_DAY = "The date the activity occurred, as UTC midnight."
_VIEWS = "The number of times the channel's videos were viewed."
@@ -152,4 +156,51 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"estimatedMinutesWatched": _ESTIMATED_MINUTES_WATCHED,
},
},
+ TRAFFIC_SOURCE_DETAILS: {
+ "description": (
+ "Daily top referrers within each traffic source type, such as the search terms, websites or "
+ "related videos that sent the most views. Up to 25 referrers per type per day."
+ ),
+ "docs_url": _DIMENSIONS_DOCS_URL,
+ "columns": {
+ "day": _DAY,
+ "insightTrafficSourceType": "The traffic source type the referrer belongs to, such as YT_SEARCH or EXT_URL.",
+ "insightTrafficSourceDetail": (
+ "The referrer within the traffic source type, such as a search term, a web page or a video ID."
+ ),
+ "views": _VIEWS,
+ "estimatedMinutesWatched": _ESTIMATED_MINUTES_WATCHED,
+ },
+ },
+ VIDEOS: {
+ "description": "Every video in the channel's uploads, with its metadata, content details and lifetime statistics.",
+ "docs_url": _VIDEOS_DOCS_URL,
+ "columns": {
+ "id": "The ID that YouTube uses to uniquely identify the video.",
+ "snippet": "Basic details about the video, such as its title, description, publish date and category.",
+ "contentDetails": "Information about the video content, such as its duration and definition.",
+ "statistics": "Lifetime statistics for the video, such as its view, like and comment counts.",
+ "status": "The upload, processing and privacy status of the video.",
+ },
+ },
+ AUDIENCE_RETENTION: {
+ "description": (
+ "Audience retention curves for the channel's top videos by views in the sync window, with "
+ "100 points per video."
+ ),
+ "docs_url": _METRICS_DOCS_URL,
+ "columns": {
+ "video": "The ID of the video the retention curve describes.",
+ "elapsedVideoTimeRatio": "The elapsed portion of the video, from 0.01 to 1.0, that the metrics describe.",
+ "audienceWatchRatio": (
+ "The number of times this portion of the video was watched, divided by the total views of the video."
+ ),
+ "relativeRetentionPerformance": (
+ "How well the video retains viewers at this point compared to YouTube videos of similar length, from 0 to 1."
+ ),
+ "startedWatching": "The number of times this segment was the first segment seen during a playback.",
+ "stoppedWatching": "The number of times this segment was the last segment seen during a playback.",
+ "totalSegmentImpressions": "The number of times this segment of the video was viewed.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/settings.py
index 22c06e029393..0cd7881793a2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/settings.py
@@ -5,7 +5,7 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
# The YouTube Analytics API is a single global host; `reports.query` is the only endpoint we call.
YOUTUBE_ANALYTICS_HOST = "https://youtubeanalytics.googleapis.com"
-# The YouTube Data API, used only to list the channels the connected account owns.
+# The YouTube Data API, used to list the channels the connected account owns and the channel's uploads.
YOUTUBE_DATA_HOST = "https://www.googleapis.com/youtube/v3"
# Scopes the connected Google account must grant. `yt-analytics-monetary.readonly` is deliberately
@@ -21,6 +21,14 @@ MAX_RESULTS_PER_PAGE = 200
# an ordinary Google account, so the API's page maximum covers the list without paging.
MAX_CHANNELS_PER_PAGE = 50
+# `playlistItems.list` pages at most 50 items, and `videos.list` takes at most 50 IDs per request.
+MAX_VIDEOS_PER_PAGE = 50
+VIDEO_PARTS = "snippet,contentDetails,statistics,status"
+
+# Audience retention needs one request per video, so it covers only the channel's top videos by views
+# in the sync window. 200 is the most the top-videos report returns in one request.
+MAX_RETENTION_VIDEOS = 200
+
# YouTube keeps revising the most recent days for a while, and the current day is always
# partial, so the sync stops short of today and re-reads a trailing window every run.
DATA_LATENCY_DAYS = 1
@@ -48,6 +56,9 @@ GEOGRAPHY = "geography"
DEMOGRAPHICS = "demographics"
SHARING_SERVICES = "sharing_services"
SUBSCRIBED_STATUS = "subscribed_status"
+TRAFFIC_SOURCE_DETAILS = "traffic_source_details"
+VIDEOS = "videos"
+AUDIENCE_RETENTION = "audience_retention"
# Every row carries the day it describes, either from the report's own `day` dimension or
# stamped from the one-day query window.
@@ -67,10 +78,17 @@ class YouTubeAnalyticsReportConfig:
# `video`-keyed reports are "top N" reports: YouTube caps them at 200 rows and requires
# an explicit sort, so we take the single page rather than paging into a cap.
single_page: bool = False
+ max_results: int = MAX_RESULTS_PER_PAGE
+ # Reports that require a single-value filter are queried once per value, and each row is
+ # stamped with the value it was filtered on.
+ filter_dimension: str | None = None
+ filter_values: tuple[str, ...] = ()
+ should_sync_default: bool = True
@property
def primary_keys(self) -> list[str]:
- return [DAY_FIELD, *self.dimensions]
+ filter_keys = [self.filter_dimension] if self.filter_dimension else []
+ return [DAY_FIELD, *filter_keys, *self.dimensions]
YOUTUBE_ANALYTICS_REPORTS: dict[str, YouTubeAnalyticsReportConfig] = {
@@ -161,9 +179,50 @@ YOUTUBE_ANALYTICS_REPORTS: dict[str, YouTubeAnalyticsReportConfig] = {
dimensions=("subscribedStatus",),
metrics=("views", "estimatedMinutesWatched"),
),
+ TRAFFIC_SOURCE_DETAILS: YouTubeAnalyticsReportConfig(
+ name=TRAFFIC_SOURCE_DETAILS,
+ dimensions=("insightTrafficSourceDetail",),
+ metrics=("views", "estimatedMinutesWatched"),
+ # The report requires an explicit sort and caps a response at 25 rows.
+ sort="-views",
+ single_page=True,
+ max_results=25,
+ # One request per traffic source type per day makes the backfill heavy, so it is opt-in.
+ should_sync_default=False,
+ filter_dimension="insightTrafficSourceType",
+ # Only the traffic source types the API documents a detail breakdown for. The channel
+ # reports reference lists END_SCREEN, NOTIFICATION, CAMPAIGN_CARD and VIDEO_REMIXES as
+ # unsupported, so they are left out.
+ filter_values=(
+ "ADVERTISING",
+ "EXT_URL",
+ "HASHTAGS",
+ "RELATED_VIDEO",
+ "SOUND_PAGE",
+ "SUBSCRIBER",
+ "YT_CHANNEL",
+ "YT_OTHER_PAGE",
+ "YT_SEARCH",
+ ),
+ ),
+}
+
+RETENTION_DIMENSION = "elapsedVideoTimeRatio"
+RETENTION_METRICS = (
+ "audienceWatchRatio",
+ "relativeRetentionPerformance",
+ "startedWatching",
+ "stoppedWatching",
+ "totalSegmentImpressions",
+)
+
+# Tables with no day grain. They have no server-side change filter, so they only full refresh.
+FULL_REFRESH_PRIMARY_KEYS: dict[str, list[str]] = {
+ VIDEOS: ["id"],
+ AUDIENCE_RETENTION: ["video", RETENTION_DIMENSION],
}
-ENDPOINTS = tuple(YOUTUBE_ANALYTICS_REPORTS.keys())
+ENDPOINTS = (*YOUTUBE_ANALYTICS_REPORTS.keys(), *FULL_REFRESH_PRIMARY_KEYS.keys())
# Every report is filtered server-side by `startDate`/`endDate`, so the day is a real
# incremental cursor for all of them.
@@ -176,4 +235,7 @@ DAY_INCREMENTAL_FIELDS: list[IncrementalField] = [
}
]
-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = dict.fromkeys(ENDPOINTS, DAY_INCREMENTAL_FIELDS)
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ **dict.fromkeys(YOUTUBE_ANALYTICS_REPORTS, DAY_INCREMENTAL_FIELDS),
+ **dict.fromkeys(FULL_REFRESH_PRIMARY_KEYS, []),
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/source.py
index 9b3f2d1dca7e..d8b86c02fb78 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/source.py
@@ -32,6 +32,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.settings import (
DAY_INCREMENTAL_FIELDS,
+ FULL_REFRESH_PRIMARY_KEYS,
REQUIRED_SCOPES,
REVISION_LOOKBACK_SECONDS,
YOUTUBE_ANALYTICS_REPORTS,
@@ -175,8 +176,18 @@ class YouTubeAnalyticsSource(ResumableSource[YouTubeAnalyticsSourceConfig, YouTu
# every incremental run instead of freezing a day at its first-imported value.
default_incremental_lookback_seconds=REVISION_LOOKBACK_SECONDS,
detected_primary_keys=report.primary_keys,
+ should_sync_default=report.should_sync_default,
)
for report in YOUTUBE_ANALYTICS_REPORTS.values()
+ ] + [
+ SourceSchema(
+ name=name,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ detected_primary_keys=primary_keys,
+ )
+ for name, primary_keys in FULL_REFRESH_PRIMARY_KEYS.items()
]
if names is not None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics.py
index abe42892c503..a56061c3227f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics.py
@@ -14,17 +14,22 @@ 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.youtubeanalytics import (
YouTubeAnalyticsSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.settings import (
+ AUDIENCE_RETENTION,
CHANNEL_DAILY,
DEMOGRAPHICS,
GEOGRAPHY,
MAX_RESULTS_PER_PAGE,
TOP_VIDEOS,
+ TRAFFIC_SOURCE_DETAILS,
+ VIDEOS,
+ YOUTUBE_ANALYTICS_REPORTS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.source import (
YouTubeAnalyticsSource,
@@ -59,8 +64,10 @@ def _connected_account() -> Iterator[None]:
yield
-def _driver(start_date: str | None = None) -> SourceDriver:
- config = YouTubeAnalyticsSourceConfig(channel_id="", youtube_analytics_integration_id=1, start_date=start_date)
+def _driver(start_date: str | None = None, channel_id: str = "") -> SourceDriver:
+ config = YouTubeAnalyticsSourceConfig(
+ channel_id=channel_id, youtube_analytics_integration_id=1, start_date=start_date
+ )
return SourceDriver(YouTubeAnalyticsSource(), config)
@@ -68,6 +75,24 @@ def _result(headers: list[str], rows: list[list[Any]]) -> dict[str, Any]:
return {"columnHeaders": [{"name": name} for name in headers], "rows": rows}
+def _channel(uploads: str | None = "UU123") -> ScriptedResponse:
+ items = [{"id": "UC123", "contentDetails": {"relatedPlaylists": {"uploads": uploads}}}] if uploads else []
+ return ScriptedResponse(json={"items": items})
+
+
+def _playlist_page(video_ids: list[str], next_page_token: str | None = None) -> ScriptedResponse:
+ body: dict[str, Any] = {"items": [{"contentDetails": {"videoId": video_id}} for video_id in video_ids]}
+ if next_page_token:
+ body["nextPageToken"] = next_page_token
+ return ScriptedResponse(json=body)
+
+
+def _videos(video_ids: list[str]) -> ScriptedResponse:
+ return ScriptedResponse(
+ json={"items": [{"id": video_id, "snippet": {"title": f"Video {video_id}"}} for video_id in video_ids]}
+ )
+
+
class TestChannelIdsParam:
@parameterized.expand(
[
@@ -222,6 +247,122 @@ class TestGetRows:
assert result.params("startIndex") == ["1", str(MAX_RESULTS_PER_PAGE + 1)]
assert len(result.items[0]) == MAX_RESULTS_PER_PAGE + 1
+ @parameterized.expand(
+ [
+ ("with_referrers", [["example.com", 4]], 9),
+ ("no_referrers", [], 0),
+ ]
+ )
+ def test_traffic_source_details_queries_each_traffic_source_type_per_day(
+ self, _name: str, rows: list[list[Any]], expected_batches: int
+ ) -> None:
+ report = YOUTUBE_ANALYTICS_REPORTS[TRAFFIC_SOURCE_DETAILS]
+
+ result = _driver(start_date="2026-07-24").run(
+ TRAFFIC_SOURCE_DETAILS,
+ always(ScriptedResponse(json=_result(["insightTrafficSourceDetail", "views"], rows))),
+ )
+
+ assert result.raised is None
+ # The report rejects a request without exactly one traffic source type, a sort, or a cap of 25.
+ assert result.params("filters") == [f"insightTrafficSourceType=={value}" for value in report.filter_values] * 2
+ assert result.params("startDate") == ["2026-07-24"] * 9 + ["2026-07-25"] * 9
+ assert set(result.params("sort")) == {"-views"}
+ assert set(result.params("maxResults")) == {"25"}
+ assert set(result.params("dimensions")) == {"insightTrafficSourceDetail"}
+ assert len(result.items) == expected_batches * 2
+ if rows:
+ assert result.items[0] == [
+ {
+ "insightTrafficSourceDetail": "example.com",
+ "views": 4,
+ "insightTrafficSourceType": "ADVERTISING",
+ "day": datetime(2026, 7, 24, tzinfo=UTC),
+ }
+ ]
+
+ @parameterized.expand([("pinned_channel", "UC123", "id", "UC123"), ("blank_channel", "", "mine", "true")])
+ def test_videos_walks_the_uploads_playlist_and_resolves_each_page(
+ self, _name: str, channel_id: str, channel_param: str, channel_value: str
+ ) -> None:
+ script = route(
+ {
+ "/channels": [_channel()],
+ "/playlistItems": [
+ _playlist_page(["vid-a", "vid-b"], next_page_token="page-2"),
+ # A video uploaded mid-walk pushes vid-b onto the next page as well.
+ _playlist_page(["vid-b", "vid-c"]),
+ ],
+ "/videos": [_videos(["vid-a", "vid-b"]), _videos(["vid-c"])],
+ }
+ )
+
+ result = _driver(channel_id=channel_id).run(VIDEOS, script)
+
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["vid-a", "vid-b", "vid-c"]
+ channel_request, *rest = result.requests
+ assert channel_request.param(channel_param) == channel_value
+ assert [(r.path.rsplit("/", 1)[-1], r.param("pageToken"), r.param("id")) for r in rest] == [
+ ("playlistItems", None, None),
+ ("videos", None, "vid-a,vid-b"),
+ ("playlistItems", "page-2", None),
+ ("videos", None, "vid-c"),
+ ]
+ assert {r.param("playlistId") for r in rest if r.path.endswith("playlistItems")} == {"UU123"}
+
+ @parameterized.expand(
+ [
+ ("channel_not_found", {"/channels": [_channel(uploads=None)]}, 1),
+ ("never_uploaded", {"/channels": [_channel()], "/playlistItems": [ScriptedResponse(status=404)]}, 2),
+ ("empty_playlist", {"/channels": [_channel()], "/playlistItems": [_playlist_page([])]}, 2),
+ ]
+ )
+ def test_videos_syncs_nothing_for_a_channel_without_uploads(
+ self, _name: str, table: dict[str, list[ScriptedResponse]], expected_requests: int
+ ) -> None:
+ result = _driver().run(VIDEOS, route(table))
+
+ assert result.raised is None
+ assert result.rows == []
+ assert len(result.requests) == expected_requests
+
+ def test_videos_raises_when_a_later_playlist_page_is_missing(self) -> None:
+ # Only a first-page 404 means "no uploads"; a later one would silently truncate the table.
+ script = route(
+ {
+ "/channels": [_channel()],
+ "/playlistItems": [_playlist_page(["vid-a"], next_page_token="page-2"), ScriptedResponse(status=404)],
+ "/videos": [_videos(["vid-a"])],
+ }
+ )
+
+ result = _driver().run(VIDEOS, script)
+
+ assert isinstance(result.raised, requests.HTTPError)
+
+ def test_audience_retention_fetches_one_curve_per_top_video(self) -> None:
+ script = [
+ ScriptedResponse(json=_result(["video", "views"], [["vid-a", 10], ["vid-b", 5]])),
+ ScriptedResponse(json=_result(["elapsedVideoTimeRatio", "audienceWatchRatio"], [[0.01, 1.2], [0.02, 0.9]])),
+ ScriptedResponse(json=_result(["elapsedVideoTimeRatio", "audienceWatchRatio"], [])),
+ ]
+
+ result = _driver(start_date="2026-07-01").run(
+ AUDIENCE_RETENTION, script, should_use_incremental_field=True, db_incremental_field_last_value="2026-07-20"
+ )
+
+ assert result.raised is None
+ assert result.params("filters") == [None, "video==vid-a", "video==vid-b"]
+ assert result.params("dimensions") == ["video", "elapsedVideoTimeRatio", "elapsedVideoTimeRatio"]
+ # Retention covers the whole sync window, never a watermark slice of it.
+ assert set(result.params("startDate")) == {"2026-07-01"}
+ assert set(result.params("endDate")) == {"2026-07-25"}
+ assert result.rows == [
+ {"elapsedVideoTimeRatio": 0.01, "audienceWatchRatio": 1.2, "video": "vid-a"},
+ {"elapsedVideoTimeRatio": 0.02, "audienceWatchRatio": 0.9, "video": "vid-a"},
+ ]
+
def test_resumes_from_saved_state_instead_of_the_configured_start(self) -> None:
result = _driver(start_date="2026-01-01").run(
GEOGRAPHY,
@@ -288,6 +429,9 @@ class TestYouTubeAnalyticsSourceResponse:
(CHANNEL_DAILY, ["day"]),
(TOP_VIDEOS, ["day", "video"]),
(DEMOGRAPHICS, ["day", "ageGroup", "gender"]),
+ (TRAFFIC_SOURCE_DETAILS, ["day", "insightTrafficSourceType", "insightTrafficSourceDetail"]),
+ (VIDEOS, ["id"]),
+ (AUDIENCE_RETENTION, ["video", "elapsedVideoTimeRatio"]),
]
)
def test_primary_keys_are_unique_table_wide(self, endpoint: str, expected: list[str]) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics_source.py
index 31111b622fe3..2febabbb12f6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics_source.py
@@ -23,9 +23,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.settings import (
CHANNEL_DAILY,
DEMOGRAPHICS,
- ENDPOINTS,
+ FULL_REFRESH_PRIMARY_KEYS,
REVISION_LOOKBACK_SECONDS,
TOP_VIDEOS,
+ TRAFFIC_SOURCE_DETAILS,
+ YOUTUBE_ANALYTICS_REPORTS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.source import (
YouTubeAnalyticsSource,
@@ -82,7 +84,7 @@ class TestYouTubeAnalyticsSource:
assert self.source.default_version == "v2"
assert (self.source.api_docs_url or "").startswith("https://")
- @parameterized.expand([(name,) for name in ENDPOINTS])
+ @parameterized.expand([(name,) for name in YOUTUBE_ANALYTICS_REPORTS])
def test_every_report_is_incremental_on_day(self, endpoint: str) -> None:
schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
@@ -92,11 +94,20 @@ class TestYouTubeAnalyticsSource:
# YouTube restates recent days, so incremental runs must re-read a trailing window.
assert schema.default_incremental_lookback_seconds == REVISION_LOOKBACK_SECONDS
+ @parameterized.expand([(name,) for name in FULL_REFRESH_PRIMARY_KEYS])
+ def test_tables_without_a_day_grain_only_full_refresh(self, endpoint: str) -> None:
+ # Their rows carry no `day`, so an incremental sync on it would have no cursor to read.
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+
@parameterized.expand(
[
(CHANNEL_DAILY, ["day"]),
(TOP_VIDEOS, ["day", "video"]),
(DEMOGRAPHICS, ["day", "ageGroup", "gender"]),
+ (TRAFFIC_SOURCE_DETAILS, ["day", "insightTrafficSourceType", "insightTrafficSourceDetail"]),
]
)
def test_primary_keys_include_every_breakdown_dimension(self, endpoint: str, expected: list[str]) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/youtube_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/youtube_analytics.py
index aa8da01042a2..614a1ee89cd1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/youtube_analytics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/youtube_analytics.py
@@ -12,13 +12,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.settings import (
+ AUDIENCE_RETENTION,
DATA_LATENCY_DAYS,
DAY_DIMENSION_WINDOW_DAYS,
DAY_FIELD,
DEFAULT_LOOKBACK_DAYS,
+ FULL_REFRESH_PRIMARY_KEYS,
MAX_CHANNELS_PER_PAGE,
- MAX_RESULTS_PER_PAGE,
+ MAX_RETENTION_VIDEOS,
+ MAX_VIDEOS_PER_PAGE,
MIN_START_DATE,
+ RETENTION_DIMENSION,
+ RETENTION_METRICS,
+ VIDEO_PARTS,
+ VIDEOS,
YOUTUBE_ANALYTICS_HOST,
YOUTUBE_ANALYTICS_REPORTS,
YOUTUBE_DATA_HOST,
@@ -71,7 +78,7 @@ def rows_from_result(body: dict[str, Any]) -> list[dict[str, Any]]:
class YouTubeAnalyticsClient:
- """Queries `reports.query` with the connected Google account's access token."""
+ """Queries `reports.query` and the YouTube Data API with the connected Google account's access token."""
def __init__(
self,
@@ -95,8 +102,9 @@ class YouTubeAnalyticsClient:
return f"{YOUTUBE_ANALYTICS_HOST}/{self._api_version}/reports"
def query(self, params: dict[str, str]) -> dict[str, Any]:
- url = f"{self.reports_url}?{urlencode(params)}"
+ return self.get_json(f"{self.reports_url}?{urlencode(params)}")
+ def get_json(self, url: str) -> dict[str, Any]:
def _get(token: str) -> requests.Response:
return self._session.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)
@@ -222,6 +230,7 @@ def _fetch_window(
ids: str,
window_start: date,
window_end: date,
+ filter_value: str | None = None,
) -> list[dict[str, Any]]:
dimensions = ((DAY_FIELD,) if report.day_is_dimension else ()) + report.dimensions
stamped_day = coerce_day(window_start)
@@ -234,20 +243,24 @@ def _fetch_window(
"startDate": window_start.isoformat(),
"endDate": window_end.isoformat(),
"metrics": ",".join(report.metrics),
- "maxResults": str(MAX_RESULTS_PER_PAGE),
+ "maxResults": str(report.max_results),
"startIndex": str(start_index),
}
if dimensions:
params["dimensions"] = ",".join(dimensions)
if report.sort:
params["sort"] = report.sort
+ if report.filter_dimension and filter_value is not None:
+ params["filters"] = f"{report.filter_dimension}=={filter_value}"
rows = rows_from_result(client.query(params))
for row in rows:
row[DAY_FIELD] = coerce_day(row.get(DAY_FIELD)) if report.day_is_dimension else stamped_day
+ if report.filter_dimension and filter_value is not None:
+ row[report.filter_dimension] = filter_value
collected.extend(rows)
- if report.single_page or len(rows) < MAX_RESULTS_PER_PAGE:
+ if report.single_page or len(rows) < report.max_results:
break
start_index += len(rows)
@@ -291,9 +304,14 @@ def get_rows(
else:
window_end = cursor
- rows = _fetch_window(client, report, ids, cursor, window_end)
- if rows:
- yield rows
+ filter_values: tuple[str | None, ...] = report.filter_values or (None,)
+ for filter_value in filter_values:
+ rows = _fetch_window(client, report, ids, cursor, window_end, filter_value)
+ if rows:
+ yield rows
+ else:
+ # The staged cursor is this window's start, so a hand-off here re-reads only this window.
+ resumable_source_manager.safe_point()
cursor = window_end + timedelta(days=1)
# Saved after the window is yielded: a crash re-yields the last window and the merge
@@ -303,6 +321,126 @@ def get_rows(
resumable_source_manager.clear_state()
+def _uploads_playlist_id(client: YouTubeAnalyticsClient, channel_id: str | None) -> str | None:
+ params = {"part": "contentDetails", "maxResults": "1"}
+ cleaned = (channel_id or "").strip()
+ if cleaned:
+ params["id"] = cleaned
+ else:
+ params["mine"] = "true"
+ body = client.get_json(f"{YOUTUBE_DATA_HOST}/channels?{urlencode(params)}")
+ for item in body.get("items") or []:
+ uploads = ((item.get("contentDetails") or {}).get("relatedPlaylists") or {}).get("uploads")
+ if uploads:
+ return uploads
+ return None
+
+
+def get_video_rows(
+ access_token: str,
+ refresh_access_token: AccessTokenRefresher | None,
+ channel_id: str | None,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[YouTubeAnalyticsResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Every video in the channel's uploads playlist, with its metadata and lifetime statistics."""
+ client = YouTubeAnalyticsClient(access_token, refresh_access_token=refresh_access_token, logger=logger)
+
+ playlist_id = _uploads_playlist_id(client, channel_id)
+ if playlist_id is None:
+ logger.warning("YouTube Analytics: the channel has no uploads playlist, so no videos to sync")
+ return
+
+ seen: set[str] = set()
+ page_token: str | None = None
+ while True:
+ params = {"part": "contentDetails", "playlistId": playlist_id, "maxResults": str(MAX_VIDEOS_PER_PAGE)}
+ if page_token:
+ params["pageToken"] = page_token
+ try:
+ page = client.get_json(f"{YOUTUBE_DATA_HOST}/playlistItems?{urlencode(params)}")
+ except requests.HTTPError as e:
+ # A channel that never uploaded has no readable uploads playlist.
+ if page_token is None and e.response is not None and e.response.status_code == 404:
+ return
+ raise
+
+ # A video uploaded mid-walk shifts the playlist, which can repeat a video on the next page.
+ video_ids = []
+ for item in page.get("items") or []:
+ video_id = (item.get("contentDetails") or {}).get("videoId")
+ if video_id and video_id not in seen:
+ seen.add(video_id)
+ video_ids.append(video_id)
+
+ rows: list[dict[str, Any]] = []
+ if video_ids:
+ video_params = {"part": VIDEO_PARTS, "id": ",".join(video_ids), "maxResults": str(MAX_VIDEOS_PER_PAGE)}
+ rows = client.get_json(f"{YOUTUBE_DATA_HOST}/videos?{urlencode(video_params)}").get("items") or []
+ if rows:
+ yield rows
+ else:
+ resumable_source_manager.safe_point()
+
+ page_token = page.get("nextPageToken")
+ if not page_token:
+ break
+
+
+def get_audience_retention_rows(
+ access_token: str,
+ refresh_access_token: AccessTokenRefresher | None,
+ channel_id: str | None,
+ start_date: str | None,
+ api_version: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[YouTubeAnalyticsResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Retention curves over the sync window for the channel's top videos by views in that window."""
+ client = YouTubeAnalyticsClient(
+ access_token, refresh_access_token=refresh_access_token, api_version=api_version, logger=logger
+ )
+ today = datetime.now(UTC).date()
+ end_day = today - timedelta(days=DATA_LATENCY_DAYS)
+ start_day = resolve_start_day(start_date, False, None, today)
+ if start_day > end_day:
+ return
+
+ window = {"ids": channel_ids_param(channel_id), "startDate": start_day.isoformat(), "endDate": end_day.isoformat()}
+ top_videos = rows_from_result(
+ client.query(
+ {
+ **window,
+ "dimensions": "video",
+ "metrics": "views",
+ "sort": "-views",
+ "maxResults": str(MAX_RETENTION_VIDEOS),
+ }
+ )
+ )
+
+ for video_id in [row.get("video") for row in top_videos]:
+ if not video_id:
+ continue
+ # The report accepts exactly one video per request.
+ rows = rows_from_result(
+ client.query(
+ {
+ **window,
+ "dimensions": RETENTION_DIMENSION,
+ "metrics": ",".join(RETENTION_METRICS),
+ "filters": f"video=={video_id}",
+ }
+ )
+ )
+ for row in rows:
+ row["video"] = video_id
+ if rows:
+ yield rows
+ else:
+ resumable_source_manager.safe_point()
+
+
def youtube_analytics_source(
access_token: str,
refresh_access_token: AccessTokenRefresher | None,
@@ -315,6 +453,34 @@ def youtube_analytics_source(
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
+ if endpoint == VIDEOS:
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_video_rows(
+ access_token=access_token,
+ refresh_access_token=refresh_access_token,
+ channel_id=channel_id,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=FULL_REFRESH_PRIMARY_KEYS[VIDEOS],
+ )
+
+ if endpoint == AUDIENCE_RETENTION:
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_audience_retention_rows(
+ access_token=access_token,
+ refresh_access_token=refresh_access_token,
+ channel_id=channel_id,
+ start_date=start_date,
+ api_version=api_version,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=FULL_REFRESH_PRIMARY_KEYS[AUDIENCE_RETENTION],
+ )
+
report = YOUTUBE_ANALYTICS_REPORTS[endpoint]
return SourceResponse(