:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement wikipedia_pageviews import source (#72633)
Tom Owers2f3a1a7ee433
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 4ddbb19df9ce..0ecf5e19da4b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -589,6 +589,7 @@ the row lists both.| watchmode | HTTP | requests + `rest_source.RESTClient` | ✅ || webflow | HTTP | requests | ✅ || weights_and_biases | HTTP (GraphQL) | requests | ✅ |+| wikipedia_pageviews | HTTP | requests | ✅ || windmill | HTTP | requests | ✅ || woocommerce | HTTP | requests + `rest_source.RESTClient` | ✅ || wordpress | HTTP | requests | ✅ |@@ -994,7 +995,6 @@ doesn't conflict with concurrent PRs.- wasabi- watchmode- when_i_work-- wikipedia_pageviews- workday- workflowmax- workrampdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/wikipediapageviews.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/wikipediapageviews.pyindex 38957a815a0f..50e1ae203e12 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/wikipediapageviews.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/wikipediapageviews.py@@ -1,9 +1,15 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass WikipediaPageviewsSourceConfig(config.Config):- pass+ project: str+ access: Literal["all-access", "desktop", "mobile-app", "mobile-web"] = config.value(default="all-access")+ agent: Literal["user", "all-agents", "spider", "automated"] = config.value(default="user")+ article_names: str | None = None+ start_date: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/canonical_descriptions.pynew file mode 100644index 000000000000..761021566394--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/canonical_descriptions.py@@ -0,0 +1,53 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://doc.wikimedia.org/generated-data-platform/aqs/analytics-api/reference/page-views.html"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "pageviews": {+ "description": "Daily total pageview counts for the configured Wikimedia project, "+ "filtered by access method and agent type.",+ "docs_url": _DOCS_URL,+ "columns": {+ "project": "Wikimedia project the counts belong to (e.g. en.wikipedia).",+ "access": "Access method the views came from: all-access, desktop, mobile-app, or mobile-web.",+ "agent": "Agent type that generated the views: all-agents, user, spider, or automated.",+ "granularity": "Time bucket of the count; always daily for this source.",+ "timestamp": "Day of the count in YYYYMMDDHH format, as returned by the API.",+ "date": "Day of the count as a timestamp, parsed from the API's timestamp field.",+ "views": "Number of pageviews counted on the day.",+ },+ },+ "article_pageviews": {+ "description": "Daily pageview counts for each configured article title, "+ "filtered by access method and agent type.",+ "docs_url": _DOCS_URL,+ "columns": {+ "project": "Wikimedia project the article belongs to (e.g. en.wikipedia).",+ "article": "Article title in URL form (spaces as underscores).",+ "access": "Access method the views came from: all-access, desktop, mobile-app, or mobile-web.",+ "agent": "Agent type that generated the views: all-agents, user, spider, or automated.",+ "granularity": "Time bucket of the count; always daily for this source.",+ "timestamp": "Day of the count in YYYYMMDDHH format, as returned by the API.",+ "date": "Day of the count as a timestamp, parsed from the API's timestamp field.",+ "views": "Number of pageviews the article received on the day.",+ },+ },+ "top_articles": {+ "description": "The 1000 most-viewed articles on the configured Wikimedia project for each day, "+ "with view counts and ranks.",+ "docs_url": _DOCS_URL,+ "columns": {+ "project": "Wikimedia project the ranking belongs to (e.g. en.wikipedia).",+ "access": "Access method the ranking covers: all-access, desktop, mobile-app, or mobile-web.",+ "year": "Year of the ranking day, as returned by the API (e.g. 2024).",+ "month": "Zero-padded month of the ranking day (e.g. 01).",+ "day": "Zero-padded day of month of the ranking day (e.g. 01).",+ "date": "Ranking day as a timestamp, parsed from the year/month/day fields.",+ "article": "Article title in URL form (spaces as underscores).",+ "views": "Number of pageviews the article received on the day.",+ "rank": "Rank of the article among the day's most-viewed articles, starting at 1.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/settings.pynew file mode 100644index 000000000000..8ab508b2b42a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/settings.py@@ -0,0 +1,81 @@+from dataclasses import dataclass, field+from datetime import date++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++BASE_URL = "https://wikimedia.org/api/rest_v1/metrics"++# Wikimedia policy requires a descriptive User-Agent; clients without one are throttled to a+# fraction of the normal per-minute request budget.+USER_AGENT = "PostHog Data Warehouse (https://posthog.com; [email protected])"++# Pageview data begins 2015-07-01; earlier windows always 404.+DATA_START_DATE = date(2015, 7, 1)++# Days per aggregate/per-article request. The API accepts arbitrary ranges in the URL path;+# chunking keeps responses bounded and gives us resume checkpoints.+WINDOW_DAYS = 366+# The top endpoint serves one day per request; batch this many days per yield/checkpoint.+TOP_WINDOW_DAYS = 7++# Each article title costs one request per window, so an unbounded list fans out into an+# unbounded number of outbound requests. Cap the number of titles synced per source.+MAX_ARTICLES = 100++PAGEVIEWS_ENDPOINT = "pageviews"+ARTICLE_PAGEVIEWS_ENDPOINT = "article_pageviews"+TOP_ARTICLES_ENDPOINT = "top_articles"++ACCESS_OPTIONS = (+ ("all-access", "All access methods"),+ ("desktop", "Desktop"),+ ("mobile-app", "Mobile app"),+ ("mobile-web", "Mobile web"),+)++AGENT_OPTIONS = (+ ("user", "User (human traffic)"),+ ("all-agents", "All agents"),+ ("spider", "Spider (crawlers)"),+ ("automated", "Automated (bots)"),+)+++@dataclass+class WikipediaPageviewsEndpointConfig:+ name: str+ primary_keys: list[str]+ description: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # `date` is derived from the API's day identifier, which never changes for a given row —+ # stable, so partitions don't rewrite on later syncs.+ partition_key: str = "date"+++WIKIPEDIA_PAGEVIEWS_ENDPOINTS: dict[str, WikipediaPageviewsEndpointConfig] = {+ PAGEVIEWS_ENDPOINT: WikipediaPageviewsEndpointConfig(+ name=PAGEVIEWS_ENDPOINT,+ primary_keys=["project", "access", "agent", "timestamp"],+ description="Daily total pageviews for the whole project",+ incremental_fields=[incremental_field("date")],+ ),+ ARTICLE_PAGEVIEWS_ENDPOINT: WikipediaPageviewsEndpointConfig(+ name=ARTICLE_PAGEVIEWS_ENDPOINT,+ primary_keys=["project", "access", "agent", "article", "timestamp"],+ description="Daily pageviews per configured article title",+ incremental_fields=[incremental_field("date")],+ ),+ TOP_ARTICLES_ENDPOINT: WikipediaPageviewsEndpointConfig(+ name=TOP_ARTICLES_ENDPOINT,+ primary_keys=["project", "access", "year", "month", "day", "article"],+ description="The 1000 most-viewed articles per day",+ incremental_fields=[incremental_field("date")],+ ),+}++ENDPOINTS = tuple(WIKIPEDIA_PAGEVIEWS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in WIKIPEDIA_PAGEVIEWS_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/source.pyindex f616a243a579..ecf457256a59 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/source.py@@ -1,32 +1,203 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.wikipediapageviews import (WikipediaPageviewsSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.wikipedia_pageviews.settings import (+ ACCESS_OPTIONS,+ AGENT_OPTIONS,+ ARTICLE_PAGEVIEWS_ENDPOINT,+ DATA_START_DATE,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ MAX_ARTICLES,+ WIKIPEDIA_PAGEVIEWS_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.wikipedia_pageviews.wikipedia_pageviews import (+ NO_ARTICLES_ERROR,+ WikipediaPageviewsResumeConfig,+ _coerce_date,+ _parse_articles,+ validate_project,+ wikipedia_pageviews_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class WikipediaPageviewsSource(SimpleSource[WikipediaPageviewsSourceConfig]):+class WikipediaPageviewsSource(ResumableSource[WikipediaPageviewsSourceConfig, WikipediaPageviewsResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # `rest_v1` is the version segment of the Wikimedia REST API base path this source calls.+ supported_versions = ("rest_v1",)+ default_version = "rest_v1"+ api_docs_url = "https://doc.wikimedia.org/generated-data-platform/aqs/analytics-api/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.WIKIPEDIAPAGEVIEWS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ NO_ARTICLES_ERROR: (+ "Add one or more article titles in the source settings to sync the article_pageviews table."+ ),+ "400 Client Error": (+ "The Wikimedia API rejected the request. Check the project domain, access method, "+ "and agent type settings."+ ),+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.wikipedia_pageviews.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: WikipediaPageviewsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ descriptions={name: endpoint.description for name, endpoint in WIKIPEDIA_PAGEVIEWS_ENDPOINTS.items()},+ # The per-article table needs article titles configured; don't default-enable a+ # table whose sync would immediately fail.+ should_sync_default={ARTICLE_PAGEVIEWS_ENDPOINT: bool(_parse_articles(config.article_names))},+ )++ def validate_credentials(+ self, config: WikipediaPageviewsSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if config.start_date and _coerce_date(config.start_date) is None:+ return False, "Start date must be in YYYY-MM-DD format."+ articles = _parse_articles(config.article_names)+ if schema_name == ARTICLE_PAGEVIEWS_ENDPOINT and not articles:+ return False, "Add one or more article titles in the source settings to sync this table."+ if len(articles) > MAX_ARTICLES:+ return False, f"Too many article titles. List at most {MAX_ARTICLES}."+ return validate_project(config.project, config.access, config.agent)++ def get_resumable_source_manager(+ self, inputs: SourceInputs+ ) -> ResumableSourceManager[WikipediaPageviewsResumeConfig]:+ return ResumableSourceManager[WikipediaPageviewsResumeConfig](inputs, WikipediaPageviewsResumeConfig)++ def source_for_pipeline(+ self,+ config: WikipediaPageviewsSourceConfig,+ resumable_source_manager: ResumableSourceManager[WikipediaPageviewsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return wikipedia_pageviews_source(+ project=config.project,+ access=config.access,+ agent=config.agent,+ article_names=config.article_names,+ start_date=config.start_date,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.WIKIPEDIA_PAGEVIEWS,category=DataWarehouseSourceCategory.ANALYTICS,label="Wikipedia Pageviews",+ keywords=["wikimedia", "wiki", "pageviews"],+ caption=(+ "Sync pageview statistics for any Wikimedia project (Wikipedia, Wiktionary, Commons, and more) "+ "from the public Wikimedia Analytics API. No credentials are required.\n\n"+ "Data is available from July 2015 onward and lands with a delay of about a day. "+ "To sync the `article_pageviews` table, list the article titles to track."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/wikipedia-pageviews",iconPath="/static/services/wikipedia_pageviews.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="project",+ label="Project domain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="en.wikipedia.org",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="access",+ label="Access method",+ required=True,+ defaultValue="all-access",+ options=[+ SourceFieldSelectConfigOption(label=label, value=value) for value, label in ACCESS_OPTIONS+ ],+ ),+ SourceFieldSelectConfig(+ name="agent",+ label="Agent type",+ required=True,+ defaultValue="user",+ options=[+ SourceFieldSelectConfigOption(label=label, value=value) for value, label in AGENT_OPTIONS+ ],+ ),+ SourceFieldInputConfig(+ name="article_names",+ label="Article titles",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="Albert Einstein, Marie Curie",+ secret=False,+ caption="Comma-separated list of article titles for the article_pageviews table.",+ ),+ SourceFieldInputConfig(+ name="start_date",+ label="Start date",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder=DATA_START_DATE.isoformat(),+ secret=False,+ caption=f"Earliest day to sync (YYYY-MM-DD). Defaults to {DATA_START_DATE.isoformat()}, when Wikimedia pageview data begins.",+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/tests/test_wikipedia_pageviews.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/tests/test_wikipedia_pageviews.pynew file mode 100644index 000000000000..f81a480ddde1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/tests/test_wikipedia_pageviews.py@@ -0,0 +1,405 @@+import re+from datetime import UTC, date, datetime+from typing import Any, Optional++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.wikipedia_pageviews.settings import (+ ARTICLE_PAGEVIEWS_ENDPOINT,+ DATA_START_DATE,+ MAX_ARTICLES,+ PAGEVIEWS_ENDPOINT,+ TOP_ARTICLES_ENDPOINT,+ WIKIPEDIA_PAGEVIEWS_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.wikipedia_pageviews.wikipedia_pageviews import (+ NO_ARTICLES_ERROR,+ WikipediaPageviewsResumeConfig,+ _coerce_date,+ _get_rows,+ _normalize_project,+ _parse_articles,+ validate_project,+ wikipedia_pageviews_source,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.wikipedia_pageviews.wikipedia_pageviews"+++def _response(status: int = 200, json_body: Any = None, text: str = "") -> mock.MagicMock:+ response = mock.MagicMock(spec=requests.Response)+ response.status_code = status+ response.ok = 200 <= status < 300+ response.text = text+ response.json.return_value = json_body if json_body is not None else {}+ return response+++def _aggregate_item(timestamp: str, views: int = 100) -> dict[str, Any]:+ return {+ "project": "en.wikipedia",+ "access": "all-access",+ "agent": "user",+ "granularity": "daily",+ "timestamp": timestamp,+ "views": views,+ }+++def _manager(resume_state: Optional[WikipediaPageviewsResumeConfig] = None) -> mock.MagicMock:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _run(+ endpoint: str,+ session: mock.MagicMock,+ manager: Optional[mock.MagicMock] = None,+ article_names: Optional[str] = None,+ start_date: Optional[str] = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> list[list[dict[str, Any]]]:+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ return list(+ _get_rows(+ project="en.wikipedia.org",+ access="all-access",+ agent="user",+ article_names=article_names,+ start_date=start_date,+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=manager if manager is not None else _manager(),+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ )+++def _requested_ranges(session: mock.MagicMock) -> list[tuple[str, str]]:+ ranges = []+ for call in session.get.call_args_list:+ match = re.search(r"/daily/(\d+)/(\d+)$", call.args[0])+ assert match is not None+ ranges.append((match.group(1), match.group(2)))+ return ranges+++class TestHelpers:+ @parameterized.expand(+ [+ ("plain", "en.wikipedia.org", "en.wikipedia.org"),+ ("scheme_and_slash", "https://en.wikipedia.org/", "en.wikipedia.org"),+ ("mixed_case_padded", " EN.Wikipedia.org ", "en.wikipedia.org"),+ ]+ )+ def test_normalize_project(self, _name, value, expected):+ assert _normalize_project(value) == expected++ @parameterized.expand(+ [+ ("none", None, []),+ ("empty", "", []),+ ("commas_and_spaces", "Albert Einstein, Ada Lovelace", ["Albert_Einstein", "Ada_Lovelace"]),+ ("newlines_and_blanks", "Albert Einstein\n\nMarie Curie,", ["Albert_Einstein", "Marie_Curie"]),+ ("dedupes_repeats", "Cat, Cat, Dog, Cat", ["Cat", "Dog"]),+ ]+ )+ def test_parse_articles(self, _name, value, expected):+ assert _parse_articles(value) == expected++ @parameterized.expand(+ [+ ("datetime", datetime(2026, 7, 1, 5, tzinfo=UTC), date(2026, 7, 1)),+ ("date", date(2026, 7, 1), date(2026, 7, 1)),+ ("iso", "2026-07-01", date(2026, 7, 1)),+ ("iso_datetime", "2026-07-01T00:00:00+00:00", date(2026, 7, 1)),+ ("api_hourly", "2026070100", date(2026, 7, 1)),+ ("api_daily", "20260701", date(2026, 7, 1)),+ ("garbage", "not-a-date", None),+ ("none", None, None),+ ]+ )+ def test_coerce_date(self, _name, value, expected):+ assert _coerce_date(value) == expected+++class TestPageviews:+ @freeze_time("2026-07-21")+ def test_single_window_rows_get_typed_date_and_state_saved_after_yield(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(json_body={"items": [_aggregate_item("2026071800", views=42)]})+ manager = _manager()++ batches = _run(PAGEVIEWS_ENDPOINT, session, manager, start_date="2026-07-18")++ url = session.get.call_args.args[0]+ assert url == (+ "https://wikimedia.org/api/rest_v1/metrics/pageviews/aggregate/en.wikipedia.org"+ "/all-access/user/daily/2026071800/2026072100"+ )+ assert len(batches) == 1+ row = batches[0][0]+ assert row["views"] == 42+ assert row["date"] == datetime(2026, 7, 18, tzinfo=UTC)++ saved = [call.args[0].next_start for call in manager.save_state.call_args_list]+ assert saved == ["2026-07-22"]++ @freeze_time("2026-07-21")+ def test_long_ranges_are_chunked_into_contiguous_windows(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(json_body={"items": [_aggregate_item("2024070100")]})+ manager = _manager()++ _run(PAGEVIEWS_ENDPOINT, session, manager, start_date="2024-07-01")++ assert _requested_ranges(session) == [+ ("2024070100", "2025070100"),+ ("2025070200", "2026070200"),+ ("2026070300", "2026072100"),+ ]+ saved = [call.args[0].next_start for call in manager.save_state.call_args_list]+ assert saved == ["2025-07-02", "2026-07-03", "2026-07-22"]++ @freeze_time("2026-07-21")+ def test_start_date_before_data_start_is_clamped(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(json_body={"items": []})++ _run(PAGEVIEWS_ENDPOINT, session, start_date="0001-01-01")++ # A pathological early start must not fan out before pageview data exists; the first+ # requested window begins at DATA_START_DATE.+ first_start, _ = _requested_ranges(session)[0]+ assert first_start == f"{DATA_START_DATE:%Y%m%d}00"++ @freeze_time("2026-07-21")+ def test_404_window_is_skipped_and_iteration_continues(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.side_effect = [+ _response(status=404),+ _response(json_body={"items": [_aggregate_item("2025070200")]}),+ _response(status=404),+ ]++ batches = _run(PAGEVIEWS_ENDPOINT, session, start_date="2024-07-01")++ assert session.get.call_count == 3+ assert len(batches) == 1+ assert batches[0][0]["timestamp"] == "2025070200"++ @freeze_time("2026-07-21")+ def test_incremental_starts_at_watermark_day(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(json_body={"items": []})++ _run(+ PAGEVIEWS_ENDPOINT,+ session,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 7, 15, tzinfo=UTC),+ )++ # The watermark day itself is re-fetched (merge dedupes) to pick up late revisions.+ assert _requested_ranges(session) == [("2026071500", "2026072100")]++ @freeze_time("2026-07-21")+ def test_resume_state_takes_precedence_over_incremental_value(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(json_body={"items": []})+ manager = _manager(resume_state=WikipediaPageviewsResumeConfig(next_start="2026-07-19"))++ _run(+ PAGEVIEWS_ENDPOINT,+ session,+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 7, 1, tzinfo=UTC),+ )++ assert _requested_ranges(session) == [("2026071900", "2026072100")]++ @freeze_time("2026-07-21")+ def test_non_ok_status_raises(self):+ response = _response(status=500, text="server error")+ response.raise_for_status.side_effect = requests.HTTPError+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = response++ with pytest.raises(requests.HTTPError):+ _run(PAGEVIEWS_ENDPOINT, session, start_date="2026-07-18")+++class TestArticlePageviews:+ @freeze_time("2026-07-21")+ def test_fans_out_per_article_with_encoded_titles(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.side_effect = [+ _response(+ json_body={+ "items": [+ {"project": "en.wikipedia", "article": "Albert_Einstein", "timestamp": "2026071800", "views": 5}+ ]+ }+ ),+ _response(+ json_body={+ "items": [{"project": "en.wikipedia", "article": "AC%2FDC", "timestamp": "2026071800", "views": 7}]+ }+ ),+ ]++ batches = _run(+ ARTICLE_PAGEVIEWS_ENDPOINT,+ session,+ article_names="Albert Einstein, AC/DC",+ start_date="2026-07-18",+ )++ urls = [call.args[0] for call in session.get.call_args_list]+ assert urls == [+ "https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org"+ "/all-access/user/Albert_Einstein/daily/20260718/20260721",+ "https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org"+ "/all-access/user/AC%2FDC/daily/20260718/20260721",+ ]+ # Both articles' rows land in the same window batch, so the per-batch watermark+ # never advances past a window an article hasn't been fetched for.+ assert len(batches) == 1+ assert [row["views"] for row in batches[0]] == [5, 7]+ assert batches[0][0]["date"] == datetime(2026, 7, 18, tzinfo=UTC)++ def test_raises_without_configured_articles(self):+ with pytest.raises(ValueError, match=NO_ARTICLES_ERROR):+ _run(ARTICLE_PAGEVIEWS_ENDPOINT, mock.MagicMock(spec=requests.Session), article_names=" , ")++ @freeze_time("2026-07-21")+ def test_article_titles_capped_at_max_at_runtime(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(json_body={"items": []})+ # Single window (start within a year of now), so one request per article — a config+ # stored past the cap must still not fan out beyond MAX_ARTICLES.+ names = ",".join(f"Article_{i}" for i in range(MAX_ARTICLES + 5))++ _run(ARTICLE_PAGEVIEWS_ENDPOINT, session, article_names=names, start_date="2026-07-20")++ assert session.get.call_count == MAX_ARTICLES+++class TestTopArticles:+ @freeze_time("2026-07-21")+ def test_flattens_daily_rankings_into_rows(self):+ def day_response(url: str, timeout: int = 0) -> mock.MagicMock:+ match = re.search(r"/top/en\.wikipedia\.org/all-access/(\d{4})/(\d{2})/(\d{2})$", url)+ assert match is not None+ year, month, day = match.groups()+ return _response(+ json_body={+ "items": [+ {+ "project": "en.wikipedia",+ "access": "all-access",+ "year": year,+ "month": month,+ "day": day,+ "articles": [+ {"article": "Main_Page", "views": 1000, "rank": 1},+ {"article": "Albert_Einstein", "views": 500, "rank": 2},+ ],+ }+ ]+ }+ )++ session = mock.MagicMock(spec=requests.Session)+ session.get.side_effect = day_response+ manager = _manager()++ batches = _run(TOP_ARTICLES_ENDPOINT, session, manager, start_date="2026-07-19")++ # One request per day, all days of the window batched into a single yield.+ assert session.get.call_count == 3+ assert len(batches) == 1+ assert len(batches[0]) == 6++ first = batches[0][0]+ assert first == {+ "project": "en.wikipedia",+ "access": "all-access",+ "year": "2026",+ "month": "07",+ "day": "19",+ "date": datetime(2026, 7, 19, tzinfo=UTC),+ "article": "Main_Page",+ "views": 1000,+ "rank": 1,+ }+ saved = [call.args[0].next_start for call in manager.save_state.call_args_list]+ assert saved == ["2026-07-22"]+++class TestValidateProject:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("not_found", 404, False),+ ("server_error", 500, False),+ ]+ )+ def test_status_mapping(self, _name, status, expected_valid):+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ make_session.return_value.get.return_value = _response(status=status)+ is_valid, message = validate_project("en.wikipedia.org", "all-access", "user")++ assert is_valid is expected_valid+ if expected_valid:+ assert message is None+ else:+ assert message is not None++ def test_empty_project_is_invalid_without_network(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ is_valid, message = validate_project(" ", "all-access", "user")++ assert is_valid is False+ assert message is not None+ make_session.return_value.get.assert_not_called()++ def test_network_error_is_not_valid(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ make_session.return_value.get.side_effect = requests.ConnectionError("boom")+ is_valid, message = validate_project("en.wikipedia.org", "all-access", "user")++ assert is_valid is False+ assert message is not None+++class TestSourceResponseMetadata:+ @parameterized.expand([(name,) for name in WIKIPEDIA_PAGEVIEWS_ENDPOINTS])+ def test_primary_keys_and_partitioning_per_endpoint(self, endpoint):+ response = wikipedia_pageviews_source(+ project="en.wikipedia.org",+ access="all-access",+ agent="user",+ article_names=None,+ start_date=None,+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(spec=ResumableSourceManager),+ )++ assert response.name == endpoint+ assert response.primary_keys == WIKIPEDIA_PAGEVIEWS_ENDPOINTS[endpoint].primary_keys+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["date"]+ assert response.sort_mode == "asc"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/tests/test_wikipedia_pageviews_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/tests/test_wikipedia_pageviews_source.pynew file mode 100644index 000000000000..9fcee6e3817c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/tests/test_wikipedia_pageviews_source.py@@ -0,0 +1,185 @@+from types import SimpleNamespace+from typing import cast++from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.wikipediapageviews import (+ WikipediaPageviewsSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.wikipedia_pageviews.settings import (+ ARTICLE_PAGEVIEWS_ENDPOINT,+ ENDPOINTS,+ MAX_ARTICLES,+ PAGEVIEWS_ENDPOINT,+ WIKIPEDIA_PAGEVIEWS_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.wikipedia_pageviews.source import (+ WikipediaPageviewsSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.wikipedia_pageviews.wikipedia_pageviews import (+ NO_ARTICLES_ERROR,+ WikipediaPageviewsResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.wikipedia_pageviews.source"+++class TestWikipediaPageviewsSource:+ def setup_method(self):+ self.source = WikipediaPageviewsSource()+ self.team_id = 123+ self.config = WikipediaPageviewsSourceConfig(project="en.wikipedia.org")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.WIKIPEDIAPAGEVIEWS++ def test_get_source_config_is_released(self):+ config = self.source.get_source_config++ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.name.value == "WikipediaPageviews"+ assert config.iconPath == "/static/services/wikipedia_pageviews.png"++ fields_by_name = {field.name: field for field in config.fields}+ assert set(fields_by_name) == {"project", "access", "agent", "article_names", "start_date"}++ project = fields_by_name["project"]+ assert isinstance(project, SourceFieldInputConfig)+ assert project.required is True++ access = fields_by_name["access"]+ assert isinstance(access, SourceFieldSelectConfig)+ assert access.defaultValue == "all-access"++ agent = fields_by_name["agent"]+ assert isinstance(agent, SourceFieldSelectConfig)+ assert agent.defaultValue == "user"++ assert cast(SourceFieldInputConfig, fields_by_name["article_names"]).required is False+ assert cast(SourceFieldInputConfig, fields_by_name["start_date"]).required is False++ def test_get_schemas_returns_every_endpoint_with_incremental_date(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ for schema in schemas:+ assert schema.supports_incremental is True+ assert {field["field"] for field in schema.incremental_fields} == {"date"}++ @parameterized.expand(+ [+ ("no_articles", None, False),+ ("with_articles", "Albert Einstein", True),+ ]+ )+ def test_article_pageviews_default_sync_requires_articles(self, _name, article_names, expected_default):+ config = WikipediaPageviewsSourceConfig(project="en.wikipedia.org", article_names=article_names)+ schema = next(s for s in self.source.get_schemas(config, self.team_id) if s.name == ARTICLE_PAGEVIEWS_ENDPOINT)+ assert schema.should_sync_default is expected_default++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=[PAGEVIEWS_ENDPOINT])+ assert [schema.name for schema in schemas] == [PAGEVIEWS_ENDPOINT]++ def test_non_retryable_errors_cover_missing_articles(self):+ assert NO_ARTICLES_ERROR in self.source.get_non_retryable_errors()++ def test_validate_credentials_rejects_bad_start_date(self):+ config = WikipediaPageviewsSourceConfig(project="en.wikipedia.org", start_date="not-a-date")+ is_valid, message = self.source.validate_credentials(config, self.team_id)+ assert is_valid is False+ assert message is not None and "YYYY-MM-DD" in message++ def test_validate_credentials_rejects_too_many_articles(self):+ names = ",".join(f"Article_{i}" for i in range(MAX_ARTICLES + 1))+ config = WikipediaPageviewsSourceConfig(project="en.wikipedia.org", article_names=names)+ is_valid, message = self.source.validate_credentials(config, self.team_id)+ assert is_valid is False+ assert message is not None and str(MAX_ARTICLES) in message++ def test_validate_credentials_rejects_article_schema_without_articles(self):+ is_valid, message = self.source.validate_credentials(+ self.config, self.team_id, schema_name=ARTICLE_PAGEVIEWS_ENDPOINT+ )+ assert is_valid is False+ assert message is not None and "article" in message.lower()++ @mock.patch(f"{MODULE}.validate_project")+ def test_validate_credentials_plumbs_to_validate_project(self, mock_validate):+ mock_validate.return_value = (True, None)++ is_valid, message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is True+ assert message is None+ mock_validate.assert_called_once_with("en.wikipedia.org", "all-access", "user")++ def test_get_resumable_source_manager_is_bound_to_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is WikipediaPageviewsResumeConfig++ @mock.patch(f"{MODULE}.wikipedia_pageviews_source")+ def test_source_for_pipeline_plumbs_inputs(self, mock_source):+ mock_source.return_value = SimpleNamespace(name=PAGEVIEWS_ENDPOINT)+ manager = mock.MagicMock(spec=ResumableSourceManager)+ logger = mock.MagicMock()+ inputs = SimpleNamespace(+ schema_name=PAGEVIEWS_ENDPOINT,+ team_id=self.team_id,+ job_id="job-1",+ logger=logger,+ should_use_incremental_field=True,+ incremental_field="date",+ db_incremental_field_last_value="2026-07-01",+ )++ response = self.source.source_for_pipeline(self.config, manager, cast(SourceInputs, inputs))++ mock_source.assert_called_once_with(+ project="en.wikipedia.org",+ access="all-access",+ agent="user",+ article_names=None,+ start_date=None,+ endpoint=PAGEVIEWS_ENDPOINT,+ logger=logger,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-01",+ )+ assert response is mock_source.return_value++ @mock.patch(f"{MODULE}.wikipedia_pageviews_source")+ def test_source_for_pipeline_drops_last_value_on_full_refresh(self, mock_source):+ mock_source.return_value = SimpleNamespace(name=PAGEVIEWS_ENDPOINT)+ inputs = SimpleNamespace(+ schema_name=PAGEVIEWS_ENDPOINT,+ team_id=self.team_id,+ job_id="job-2",+ logger=mock.MagicMock(),+ should_use_incremental_field=False,+ incremental_field=None,+ db_incremental_field_last_value="2026-07-01",+ )++ self.source.source_for_pipeline(+ self.config, mock.MagicMock(spec=ResumableSourceManager), cast(SourceInputs, inputs)+ )++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_documented_tables_render_without_credentials(self):+ tables = self.source.get_documented_tables()+ assert {table["name"] for table in tables} == set(WIKIPEDIA_PAGEVIEWS_ENDPOINTS)+ for table in tables:+ assert table["description"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/wikipedia_pageviews.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/wikipedia_pageviews.pynew file mode 100644index 000000000000..cc89dbc690f7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/wikipedia_pageviews.py@@ -0,0 +1,319 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import quote++import requests+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.wikipedia_pageviews.settings import (+ ARTICLE_PAGEVIEWS_ENDPOINT,+ BASE_URL,+ DATA_START_DATE,+ MAX_ARTICLES,+ TOP_ARTICLES_ENDPOINT,+ TOP_WINDOW_DAYS,+ USER_AGENT,+ WIKIPEDIA_PAGEVIEWS_ENDPOINTS,+ WINDOW_DAYS,+)++REQUEST_TIMEOUT_SECONDS = 60++NO_ARTICLES_ERROR = "No article titles configured for the article_pageviews table"+++class WikipediaPageviewsResumeConfig:+ # ISO date (YYYY-MM-DD) of the first day the next window should fetch.+ next_start: str+++def _normalize_project(project: str) -> str:+ project = project.strip().lower()+ project = re.sub(r"^https?://", "", project)+ return project.strip("/")+++def _parse_articles(article_names: Optional[str]) -> list[str]:+ if not article_names:+ return []+ articles: list[str] = []+ seen: set[str] = set()+ for raw in re.split(r"[,\n]", article_names):+ # The API identifies articles in URL form, with underscores instead of spaces.+ article = raw.strip().replace(" ", "_")+ # Dedupe so a repeated title doesn't refetch the same per-article window.+ if article and article not in seen:+ seen.add(article)+ articles.append(article)+ return articles+++def _coerce_date(value: Any) -> Optional[date]:+ if isinstance(value, datetime):+ return value.date()+ if isinstance(value, date):+ return value+ if isinstance(value, str):+ stripped = value.strip()+ # API day identifiers: YYYYMMDD or YYYYMMDDHH.+ if re.fullmatch(r"\d{8}(\d{2})?", stripped):+ try:+ return datetime.strptime(stripped[:8], "%Y%m%d").date()+ except ValueError:+ return None+ try:+ return datetime.fromisoformat(stripped).date()+ except ValueError:+ return None+ return None+++def _timestamp_to_datetime(timestamp: str) -> datetime:+ return datetime.strptime(timestamp, "%Y%m%d%H").replace(tzinfo=UTC)+++def _with_date(item: dict[str, Any]) -> dict[str, Any]:+ """Attach a parsed `date` column, the typed cursor/partition field for the row's day."""+ timestamp = item.get("timestamp")+ if isinstance(timestamp, str):+ try:+ item["date"] = _timestamp_to_datetime(timestamp)+ except ValueError:+ pass+ return item+++def _get_items(session: requests.Session, url: str, logger: FilteringBoundLogger) -> list[dict[str, Any]]:+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ # The API 404s windows with no data — normal for days newer than the ~1-day ingestion lag+ # or older than the project's history. An unknown project 404s identically, but project+ # validity is checked at source creation, so here a 404 is just an empty window.+ if response.status_code == 404:+ logger.debug(f"Wikipedia Pageviews: no data for {url}")+ return []++ if not response.ok:+ logger.error(+ f"Wikipedia Pageviews API error: status={response.status_code}, body={response.text[:500]}, url={url}"+ )+ response.raise_for_status()++ items = response.json().get("items", [])+ return items if isinstance(items, list) else []+++def _aggregate_rows(+ session: requests.Session,+ project: str,+ access: str,+ agent: str,+ window_start: date,+ window_end: date,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ url = (+ f"{BASE_URL}/pageviews/aggregate/{quote(project, safe='')}/{access}/{agent}"+ f"/daily/{window_start:%Y%m%d}00/{window_end:%Y%m%d}00"+ )+ return [_with_date(item) for item in _get_items(session, url, logger)]+++def _article_rows(+ session: requests.Session,+ project: str,+ access: str,+ agent: str,+ articles: list[str],+ window_start: date,+ window_end: date,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ for article in articles:+ url = (+ f"{BASE_URL}/pageviews/per-article/{quote(project, safe='')}/{access}/{agent}"+ f"/{quote(article, safe='')}/daily/{window_start:%Y%m%d}/{window_end:%Y%m%d}"+ )+ rows.extend(_with_date(item) for item in _get_items(session, url, logger))+ return rows+++def _top_rows(+ session: requests.Session,+ project: str,+ access: str,+ day: date,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ url = f"{BASE_URL}/pageviews/top/{quote(project, safe='')}/{access}/{day:%Y}/{day:%m}/{day:%d}"+ rows: list[dict[str, Any]] = []+ for item in _get_items(session, url, logger):+ for article in item.get("articles") or []:+ rows.append(+ {+ "project": item.get("project"),+ "access": item.get("access"),+ "year": item.get("year"),+ "month": item.get("month"),+ "day": item.get("day"),+ "date": datetime(day.year, day.month, day.day, tzinfo=UTC),+ "article": article.get("article"),+ "views": article.get("views"),+ "rank": article.get("rank"),+ }+ )+ return rows+++def _get_rows(+ project: str,+ access: str,+ agent: str,+ article_names: Optional[str],+ start_date: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[WikipediaPageviewsResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ normalized_project = _normalize_project(project)+ session = make_tracked_session(headers={"User-Agent": USER_AGENT})++ articles: list[str] = []+ if endpoint == ARTICLE_PAGEVIEWS_ENDPOINT:+ articles = _parse_articles(article_names)+ if not articles:+ raise ValueError(NO_ARTICLES_ERROR)+ # Runtime cap as well as setup validation, so a config stored before the limit+ # existed (or one that bypassed validation) can't fan out past MAX_ARTICLES.+ if len(articles) > MAX_ARTICLES:+ logger.warning(+ f"Wikipedia Pageviews: {len(articles)} article titles configured, syncing only the first {MAX_ARTICLES}"+ )+ articles = articles[:MAX_ARTICLES]++ # The API truncates ranges at the newest loaded day and 404s fully-empty windows (treated+ # as empty above), so today is a safe end boundary despite the ~1-day ingestion lag.+ end_boundary = datetime.now(UTC).date()++ # Clamp to the first day data exists: a stored start_date like 0001-01-01 parses fine but+ # would otherwise fan out into hundreds of thousands of empty daily requests (the top+ # endpoint serves one day per request).+ start = max(_coerce_date(start_date) or DATA_START_DATE, DATA_START_DATE)+ if should_use_incremental_field:+ last_value = _coerce_date(db_incremental_field_last_value)+ if last_value is not None:+ # Restart at the watermark day itself, not the day after: the newest loaded days+ # can be revised while ingestion settles, and merge dedupes on the primary key.+ start = max(start, last_value)++ # A persisted resume cursor takes precedence so a heartbeat-timed-out activity picks up at+ # the window it was processing rather than recomputing from the incremental value.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None:+ resumed = _coerce_date(resume.next_start)+ if resumed is not None:+ start = resumed+ logger.debug(f"Wikipedia Pageviews: resuming {endpoint} from {start.isoformat()}")++ window_days = TOP_WINDOW_DAYS if endpoint == TOP_ARTICLES_ENDPOINT else WINDOW_DAYS++ cursor = start+ while cursor <= end_boundary:+ window_end = min(cursor + timedelta(days=window_days - 1), end_boundary)++ if endpoint == TOP_ARTICLES_ENDPOINT:+ rows = []+ day = cursor+ while day <= window_end:+ rows.extend(_top_rows(session, normalized_project, access, day, logger))+ day += timedelta(days=1)+ elif endpoint == ARTICLE_PAGEVIEWS_ENDPOINT:+ rows = _article_rows(session, normalized_project, access, agent, articles, cursor, window_end, logger)+ else:+ rows = _aggregate_rows(session, normalized_project, access, agent, cursor, window_end, logger)++ if rows:+ yield rows++ cursor = window_end + timedelta(days=1)+ # Save AFTER yielding so a crash re-fetches (and merge dedupes) the last window+ # instead of skipping it.+ resumable_source_manager.save_state(WikipediaPageviewsResumeConfig(next_start=cursor.isoformat()))+++def wikipedia_pageviews_source(+ project: str,+ access: str,+ agent: str,+ article_names: Optional[str],+ start_date: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[WikipediaPageviewsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = WIKIPEDIA_PAGEVIEWS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: _get_rows(+ project=project,+ access=access,+ agent=agent,+ article_names=article_names,+ start_date=start_date,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[config.partition_key],+ sort_mode="asc",+ )+++def validate_project(project: str, access: str, agent: str) -> tuple[bool, Optional[str]]:+ normalized_project = _normalize_project(project)+ if not normalized_project:+ return False, "Enter a Wikimedia project domain (e.g. en.wikipedia.org)."++ session = make_tracked_session(headers={"User-Agent": USER_AGENT})+ # Probe a window that ends before the ~1-2 day ingestion lag, so a valid project can't 404+ # just because the newest days aren't loaded yet.+ probe_end = datetime.now(UTC).date() - timedelta(days=3)+ probe_start = probe_end - timedelta(days=7)+ url = (+ f"{BASE_URL}/pageviews/aggregate/{quote(normalized_project, safe='')}/{access}/{agent}"+ f"/daily/{probe_start:%Y%m%d}00/{probe_end:%Y%m%d}00"+ )+ try:+ response = session.get(url, timeout=30)+ except Exception as e:+ return False, f"Could not reach the Wikimedia API ({e}). Please retry."++ if response.status_code == 200:+ return True, None+ if response.status_code == 404:+ return (+ False,+ f"No pageview data found for project '{normalized_project}'. "+ "Check the project domain (e.g. en.wikipedia.org).",+ )+ return False, f"Unexpected response from the Wikimedia API (status {response.status_code})."