: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 new_york_times import source (#67797)
Tom Owers376a240dcf38
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 8c53c68c66bf..956f30ab33b0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -204,6 +204,7 @@ the row lists both.| mssql | DB protocol | pyodbc / pymssql | ➖ || mux | HTTP | requests | ✅ || mysql | DB protocol | pymysql | ➖ |+| new_york_times | HTTP | requests | ✅ || okta | HTTP | requests | ✅ || notion | HTTP | requests | ✅ || omnisend | HTTP | requests | ✅ |@@ -526,7 +527,6 @@ doesn't conflict with concurrent PRs.- neon- netsuite- new_relic-- new_york_times- news_api- newsdata- nexiopaydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex bd153c77ec9a..00ae99a579ea 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -2124,7 +2124,8 @@ class NewRelicSourceConfig(config.Config):@config.configclass NewYorkTimesSourceConfig(config.Config):- pass+ api_key: str+ article_search_query: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/canonical_descriptions.pynew file mode 100644index 000000000000..25af73744799--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/canonical_descriptions.py@@ -0,0 +1,89 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_MOST_POPULAR_COLUMNS = {+ "uri": "Stable New York Times asset identifier (e.g. nyt://article/...). Unique per article.",+ "url": "Canonical web URL of the article.",+ "id": "Numeric asset id assigned by NYT.",+ "asset_id": "Numeric asset id assigned by NYT.",+ "source": "Publication source of the article (e.g. New York Times).",+ "published_date": "Date the article was first published (YYYY-MM-DD).",+ "updated": "Timestamp the article was last updated.",+ "section": "Top-level NYT section the article belongs to (e.g. World, Business).",+ "subsection": "Subsection the article belongs to, when present.",+ "byline": "Author byline for the article.",+ "title": "Headline of the article.",+ "abstract": "Short summary of the article.",+ "adx_keywords": "Semicolon-separated list of keywords associated with the article.",+ "des_facet": "Descriptive subject keywords tagged on the article.",+ "org_facet": "Organizations mentioned in the article.",+ "per_facet": "People mentioned in the article.",+ "geo_facet": "Geographic locations mentioned in the article.",+ "media": "Associated media (images) for the article.",+ "type": "Asset type (e.g. Article).",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "article_search": {+ "description": "Articles matching a query and/or date window from the NYT Article Search API. "+ "Windowed by publication date and capped at 1000 results per query.",+ "docs_url": "https://developer.nytimes.com/docs/articlesearch-product/1/overview",+ "columns": {+ "_id": "Unique article identifier assigned by NYT.",+ "uri": "Stable New York Times asset identifier (e.g. nyt://article/...).",+ "web_url": "Canonical web URL of the article.",+ "snippet": "Short excerpt from the article.",+ "abstract": "Summary of the article.",+ "lead_paragraph": "Opening paragraph of the article.",+ "pub_date": "Publication timestamp of the article (ISO 8601).",+ "headline": "Structured headline object (main, kicker, print headline, etc.).",+ "byline": "Structured byline object for the article's authors.",+ "keywords": "List of subject/person/organization/location keywords tagged on the article.",+ "document_type": "Type of document (e.g. article, multimedia).",+ "news_desk": "NYT news desk that produced the article.",+ "section_name": "Section the article was published in.",+ "type_of_material": "Editorial material type (e.g. News, Op-Ed, Review).",+ "word_count": "Approximate word count of the article.",+ "multimedia": "Associated images and media assets.",+ },+ },+ "most_popular_viewed": {+ "description": "The most viewed New York Times articles over the last 7 days. Point-in-time snapshot.",+ "docs_url": "https://developer.nytimes.com/docs/most-popular-product/1/overview",+ "columns": _MOST_POPULAR_COLUMNS,+ },+ "most_popular_emailed": {+ "description": "The most emailed New York Times articles over the last 7 days. Point-in-time snapshot.",+ "docs_url": "https://developer.nytimes.com/docs/most-popular-product/1/overview",+ "columns": _MOST_POPULAR_COLUMNS,+ },+ "most_popular_shared": {+ "description": "The most shared New York Times articles over the last 7 days. Point-in-time snapshot.",+ "docs_url": "https://developer.nytimes.com/docs/most-popular-product/1/overview",+ "columns": _MOST_POPULAR_COLUMNS,+ },+ "top_stories": {+ "description": "The current top stories on the New York Times home section. Point-in-time snapshot.",+ "docs_url": "https://developer.nytimes.com/docs/top-stories-product/1/overview",+ "columns": {+ "uri": "Stable New York Times asset identifier (e.g. nyt://article/...). Unique per story.",+ "url": "Canonical web URL of the story.",+ "title": "Headline of the story.",+ "abstract": "Short summary of the story.",+ "section": "Top-level NYT section the story belongs to.",+ "subsection": "Subsection the story belongs to, when present.",+ "byline": "Author byline for the story.",+ "item_type": "Type of item (e.g. Article).",+ "created_date": "Timestamp the story was created (stable).",+ "published_date": "Timestamp the story was published.",+ "updated_date": "Timestamp the story was last updated.",+ "kicker": "Short label displayed above the headline.",+ "des_facet": "Descriptive subject keywords tagged on the story.",+ "org_facet": "Organizations mentioned in the story.",+ "per_facet": "People mentioned in the story.",+ "geo_facet": "Geographic locations mentioned in the story.",+ "multimedia": "Associated images and media assets.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/new_york_times.py b/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/new_york_times.pynew file mode 100644index 000000000000..773ab3211f60--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/new_york_times.py@@ -0,0 +1,266 @@+import time+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.new_york_times.settings import (+ NEW_YORK_TIMES_ENDPOINTS,+ NewYorkTimesEndpointConfig,+)++NEW_YORK_TIMES_BASE_URL = "https://api.nytimes.com"++# Article Search returns 10 results per page and hard-caps at 100 pages (1000 results) per query.+ARTICLE_SEARCH_PAGE_SIZE = 10+ARTICLE_SEARCH_MAX_PAGES = 100++# NYT rate limits are tight (≈10 requests/minute) and Article Search 429s aggressively. NYT explicitly+# recommends sleeping several seconds between calls, so we throttle paging politely and let the retry+# handler absorb any 429s that still slip through.+ARTICLE_SEARCH_PAGE_DELAY_SECONDS = 6.0+++class NewYorkTimesRetryableError(Exception):+ pass+++class NewYorkTimesResumeConfig:+ # Zero-based Article Search page index to fetch next. Snapshot endpoints never populate this.+ page: int = 0+ # The begin_date (YYYYMMDD) window this run is paging through. Persisted so a resume continues the+ # exact same window rather than recomputing `now - lookback`, which would drift over a long sync.+ begin_date: str | None = None+++def _get_headers() -> dict[str, str]:+ return {"Accept": "application/json"}+++def _format_begin_date(value: Any) -> str:+ """Format an incremental cursor value as the YYYYMMDD string Article Search's begin_date expects."""+ if isinstance(value, datetime):+ return value.astimezone(UTC).strftime("%Y%m%d") if value.tzinfo else value.strftime("%Y%m%d")+ if isinstance(value, date):+ return value.strftime("%Y%m%d")+ # A pre-formatted string cursor — trust it as-is.+ return str(value)+++def _resolve_begin_date(+ config: NewYorkTimesEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> str | None:+ """Pick the begin_date window for an Article Search run.++ Uses the incremental watermark when we have one, otherwise falls back to a recent lookback window so+ the first sync (and full refreshes) stay inside NYT's 1000-result cap instead of trying to page all+ of history back to 1851.+ """+ if should_use_incremental_field and db_incremental_field_last_value:+ return _format_begin_date(db_incremental_field_last_value)+ if config.default_lookback_days is not None:+ return (datetime.now(UTC) - timedelta(days=config.default_lookback_days)).strftime("%Y%m%d")+ return None+++def _build_url(path: str, api_key: str, params: dict[str, Any]) -> str:+ query = {**params, "api-key": api_key}+ return f"{NEW_YORK_TIMES_BASE_URL}{path}?{urlencode(query)}"+++def _sanitize_url(url: str) -> str:+ """Drop the query string so the api-key (passed as a query param) never lands in logs or errors."""+ return url.split("?", 1)[0]+++@retry(+ retry=retry_if_exception_type(+ (+ NewYorkTimesRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=2, max=60),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ raise NewYorkTimesRetryableError(f"New York Times API error (retryable): status={response.status_code}")++ if not response.ok:+ # The api-key rides in the query string, so never surface the raw URL. Raise an HTTPError whose+ # message matches the non-retryable-error keys (status + base host) without leaking the key.+ safe_url = _sanitize_url(url)+ logger.error(f"New York Times API error: status={response.status_code}, url={safe_url}")+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {safe_url}", response=response+ )++ return response.json()+++def validate_credentials(api_key: str) -> bool:+ # Probe a cheap endpoint. A 401 means the key itself is bad or missing; anything else — including a+ # 403 from an app that has this particular API disabled — means the key is genuine. Users may enable+ # only the APIs they intend to sync, so a 403 must not block source creation.+ url = _build_url("/svc/mostpopular/v2/viewed/1.json", api_key, {})+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_get_headers(), timeout=10)+ return response.status_code != 401+ except Exception:+ return False+++def _select_rows(config: NewYorkTimesEndpointConfig, data: dict[str, Any]) -> list[dict[str, Any]]:+ if config.paginated:+ # Article Search nests its docs under `response`.+ return data.get("response", {}).get(config.data_selector, []) or []+ return data.get(config.data_selector, []) or []+++def _get_snapshot_rows(+ session: requests.Session,+ config: NewYorkTimesEndpointConfig,+ api_key: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ url = _build_url(config.path, api_key, {})+ data = _fetch_page(session, url, _get_headers(), logger)+ rows = _select_rows(config, data)+ if rows:+ yield rows+++def _get_article_search_rows(+ session: requests.Session,+ config: NewYorkTimesEndpointConfig,+ api_key: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NewYorkTimesResumeConfig],+ query: str | None,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ begin_date: str | None+ if resume is not None and resume.begin_date is not None:+ begin_date = resume.begin_date+ page = resume.page+ logger.debug(f"New York Times: resuming article_search from page={page}, begin_date={begin_date}")+ else:+ begin_date = _resolve_begin_date(config, should_use_incremental_field, db_incremental_field_last_value)+ page = 0++ while page < ARTICLE_SEARCH_MAX_PAGES:+ params: dict[str, Any] = {"page": page, "sort": "oldest"}+ if begin_date:+ params["begin_date"] = begin_date+ if query:+ params["q"] = query++ url = _build_url(config.path, api_key, params)+ data = _fetch_page(session, url, _get_headers(), logger)+ rows = _select_rows(config, data)++ if not rows:+ break++ yield rows++ page += 1+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge dedupes+ # on `_id`.+ resumable_source_manager.save_state(NewYorkTimesResumeConfig(page=page, begin_date=begin_date))++ if len(rows) < ARTICLE_SEARCH_PAGE_SIZE:+ break++ if page >= ARTICLE_SEARCH_MAX_PAGES:+ logger.info(+ "New York Times: article_search hit the 100-page (1000-result) cap; remaining results in "+ "this window will be picked up by the next incremental sync"+ )+ break++ time.sleep(ARTICLE_SEARCH_PAGE_DELAY_SECONDS)+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NewYorkTimesResumeConfig],+ query: str | None = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = NEW_YORK_TIMES_ENDPOINTS[endpoint]+ # Redact the api-key (carried as a query param) from the tracked transport's logged URLs.+ session = make_tracked_session(redact_values=(api_key,))++ if config.paginated:+ yield from _get_article_search_rows(+ session,+ config,+ api_key,+ logger,+ resumable_source_manager,+ query,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ else:+ yield from _get_snapshot_rows(session, config, api_key, logger)+++def new_york_times_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NewYorkTimesResumeConfig],+ query: str | None = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> SourceResponse:+ config = NEW_YORK_TIMES_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ query=query,+ 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" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Article Search is paged sort=oldest (ascending pub_date); snapshots are single-batch so order is+ # immaterial. Ascending keeps the incremental watermark advancing correctly.+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/settings.pynew file mode 100644index 000000000000..8ad1b89487d1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/settings.py@@ -0,0 +1,91 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class NewYorkTimesEndpointConfig:+ name: str+ path: str+ # Key in the JSON response holding the row list. Snapshot endpoints (Most Popular, Top Stories)+ # nest their rows under "results"; Article Search nests them under "response" -> "docs".+ data_selector: str+ primary_keys: list[str] = field(default_factory=lambda: ["uri"])+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Only True where NYT exposes a genuine server-side timestamp filter (Article Search's begin_date).+ supports_incremental: bool = False+ # True for Article Search, which pages via a `page` query param (10 results/page, capped at 100 pages).+ # Snapshot endpoints return a single fixed-size list with no pagination.+ paginated: bool = False+ # First-sync / full-refresh window for the paginated Article Search endpoint. NYT hard-caps Article+ # Search at 1000 results per query, so an unbounded pull is impossible — window it to a recent range+ # and let successive incremental syncs walk forward.+ default_lookback_days: Optional[int] = None+ should_sync_default: bool = True+++_PUB_DATE_INCREMENTAL: list[IncrementalField] = [+ {+ "label": "pub_date",+ "type": IncrementalFieldType.DateTime,+ "field": "pub_date",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++NEW_YORK_TIMES_ENDPOINTS: dict[str, NewYorkTimesEndpointConfig] = {+ # Article Search — the flagship NYT API. Server-side date windowing via begin_date (YYYYMMDD) plus+ # sort=oldest gives a genuine ascending incremental pull, deduped on the stable `_id`.+ "article_search": NewYorkTimesEndpointConfig(+ name="article_search",+ path="/svc/search/v2/articlesearch.json",+ data_selector="docs",+ primary_keys=["_id"],+ partition_key="pub_date",+ incremental_fields=_PUB_DATE_INCREMENTAL,+ supports_incremental=True,+ paginated=True,+ default_lookback_days=30,+ ),+ # Most Popular — point-in-time snapshots (most viewed/emailed/shared over the last 7 days). No+ # server-side updated-since cursor, so these are full refresh; merge dedupes on `uri`.+ "most_popular_viewed": NewYorkTimesEndpointConfig(+ name="most_popular_viewed",+ path="/svc/mostpopular/v2/viewed/7.json",+ data_selector="results",+ primary_keys=["uri"],+ partition_key="published_date",+ ),+ "most_popular_emailed": NewYorkTimesEndpointConfig(+ name="most_popular_emailed",+ path="/svc/mostpopular/v2/emailed/7.json",+ data_selector="results",+ primary_keys=["uri"],+ partition_key="published_date",+ ),+ "most_popular_shared": NewYorkTimesEndpointConfig(+ name="most_popular_shared",+ path="/svc/mostpopular/v2/shared/7.json",+ data_selector="results",+ primary_keys=["uri"],+ partition_key="published_date",+ ),+ # Top Stories — a snapshot of the current stories on the home section. Full refresh; `created_date`+ # is stable so it's the partition key (never `updated_date`).+ "top_stories": NewYorkTimesEndpointConfig(+ name="top_stories",+ path="/svc/topstories/v2/home.json",+ data_selector="results",+ primary_keys=["uri"],+ partition_key="created_date",+ ),+}++ENDPOINTS = tuple(NEW_YORK_TIMES_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in NEW_YORK_TIMES_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/source.pyindex fa61ede8ecc3..93a8a8054de3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/source.py@@ -1,19 +1,43 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import NewYorkTimesSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.new_york_times.new_york_times import (+ NewYorkTimesResumeConfig,+ new_york_times_source,+ validate_credentials as validate_nyt_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.new_york_times.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ NEW_YORK_TIMES_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class NewYorkTimesSource(SimpleSource[NewYorkTimesSourceConfig]):+class NewYorkTimesSource(ResumableSource[NewYorkTimesSourceConfig, NewYorkTimesResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.NEWYORKTIMES@@ -24,7 +48,107 @@ class NewYorkTimesSource(SimpleSource[NewYorkTimesSourceConfig]):name=SchemaExternalDataSourceType.NEW_YORK_TIMES,category=DataWarehouseSourceCategory.ANALYTICS,label="New York Times",- iconPath="/static/services/new_york_times.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption=(+ "Enter your New York Times API key to pull New York Times content into the PostHog Data warehouse.\n\n"+ "Create a free developer account and register an app at the "+ "[NYT Developer Network](https://developer.nytimes.com/), then enable the APIs you want to sync "+ "(Article Search, Most Popular, Top Stories) on your app to get an API key.\n\n"+ "Note: NYT enforces tight rate limits (≈10 requests/minute, 4,000/day), so syncs — especially "+ "Article Search — are intentionally throttled."+ ),+ iconPath="/static/services/new_york_times.png",+ docsUrl="https://posthog.com/docs/cdp/sources/new-york-times",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="article_search_query",+ label="Article Search query (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="e.g. climate",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.new_york_times.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or unauthorized API key surfaces as an HTTPError from `_fetch_page`. Retrying can+ # never satisfy a credential problem, so stop the sync. Match the stable status text and base+ # host, not the per-request path/query (which is stripped to avoid leaking the api-key).+ "401 Client Error: Unauthorized for url: https://api.nytimes.com": "Your New York Times API key is invalid or unauthorized. Create a new key in the NYT Developer Network and reconnect.",+ "403 Client Error: Forbidden for url: https://api.nytimes.com": "Your New York Times API key does not have access to this API. Enable the required API on your app in the NYT Developer Network, then reconnect.",+ }++ def get_schemas(+ self,+ config: NewYorkTimesSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = NEW_YORK_TIMES_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ detected_primary_keys=endpoint_config.primary_keys,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: NewYorkTimesSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_nyt_credentials(config.api_key):+ return True, None++ return False, "Invalid New York Times API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[NewYorkTimesResumeConfig]:+ return ResumableSourceManager[NewYorkTimesResumeConfig](inputs, NewYorkTimesResumeConfig)++ def source_for_pipeline(+ self,+ config: NewYorkTimesSourceConfig,+ resumable_source_manager: ResumableSourceManager[NewYorkTimesResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return new_york_times_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ query=config.article_search_query or None,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/tests/test_new_york_times.py b/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/tests/test_new_york_times.pynew file mode 100644index 000000000000..600195e4088c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/tests/test_new_york_times.py@@ -0,0 +1,306 @@+from datetime import UTC, date, datetime++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.new_york_times import new_york_times+from products.warehouse_sources.backend.temporal.data_imports.sources.new_york_times.new_york_times import (+ ARTICLE_SEARCH_MAX_PAGES,+ NewYorkTimesResumeConfig,+ _build_url,+ _format_begin_date,+ _resolve_begin_date,+ _select_rows,+ get_rows,+ new_york_times_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.new_york_times.settings import (+ NEW_YORK_TIMES_ENDPOINTS,+)+++class _FakeResumableManager:+ def __init__(self, state: NewYorkTimesResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[NewYorkTimesResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> NewYorkTimesResumeConfig | None:+ return self._state++ def save_state(self, data: NewYorkTimesResumeConfig) -> None:+ self.saved.append(data)+++class TestFormatBeginDate:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "20260304"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "20260304"),+ ("date_value", date(2026, 1, 15), "20260115"),+ ("string_passthrough", "20250101", "20250101"),+ ]+ )+ def test_format_begin_date(self, _name: str, value: object, expected: str) -> None:+ assert _format_begin_date(value) == expected+++class TestResolveBeginDate:+ @freeze_time("2026-07-02")+ def test_uses_watermark_when_incremental(self) -> None:+ config = NEW_YORK_TIMES_ENDPOINTS["article_search"]+ assert _resolve_begin_date(config, True, datetime(2026, 6, 1, tzinfo=UTC)) == "20260601"++ @freeze_time("2026-07-02")+ def test_falls_back_to_lookback_without_watermark(self) -> None:+ # First incremental sync (no watermark) must window to the lookback range, not all of history.+ config = NEW_YORK_TIMES_ENDPOINTS["article_search"]+ assert _resolve_begin_date(config, True, None) == "20260602"++ @freeze_time("2026-07-02")+ def test_full_refresh_uses_lookback(self) -> None:+ config = NEW_YORK_TIMES_ENDPOINTS["article_search"]+ assert _resolve_begin_date(config, False, None) == "20260602"+++class TestSelectRows:+ def test_article_search_reads_nested_docs(self) -> None:+ config = NEW_YORK_TIMES_ENDPOINTS["article_search"]+ data = {"response": {"docs": [{"_id": "a"}, {"_id": "b"}]}}+ assert _select_rows(config, data) == [{"_id": "a"}, {"_id": "b"}]++ def test_snapshot_reads_results(self) -> None:+ config = NEW_YORK_TIMES_ENDPOINTS["top_stories"]+ data = {"results": [{"uri": "x"}]}+ assert _select_rows(config, data) == [{"uri": "x"}]++ def test_missing_key_returns_empty(self) -> None:+ config = NEW_YORK_TIMES_ENDPOINTS["article_search"]+ assert _select_rows(config, {"response": {}}) == []+++class TestBuildUrl:+ def test_includes_api_key_and_encodes_params(self) -> None:+ url = _build_url("/svc/search/v2/articlesearch.json", "KEY", {"q": "a b", "page": 0})+ assert url.startswith("https://api.nytimes.com/svc/search/v2/articlesearch.json?")+ assert "q=a+b" in url+ assert "page=0" in url+ assert "api-key=KEY" in url+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("unauthorized", 401, False),+ # A 403 means the key is genuine but the app hasn't enabled this API — must not block create.+ ("forbidden", 403, True),+ ("rate_limited", 429, True),+ ]+ )+ def test_status_mapping(self, _name: str, status_code: int, expected: bool) -> None:+ response = MagicMock()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response+ with patch.object(new_york_times, "make_tracked_session", return_value=session):+ assert validate_credentials("KEY") is expected++ def test_network_error_is_invalid(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(new_york_times, "make_tracked_session", return_value=session):+ assert validate_credentials("KEY") is False+++def _mock_response(status_code: int, body: dict) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.json.return_value = body+ return response+++class TestGetRowsSnapshot:+ def test_single_request_yields_results(self) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response(200, {"results": [{"uri": "u1"}, {"uri": "u2"}]})+ with patch.object(new_york_times, "make_tracked_session", return_value=session):+ batches = list(+ get_rows("KEY", "top_stories", MagicMock(), _FakeResumableManager()) # type: ignore[arg-type]+ )+ assert batches == [[{"uri": "u1"}, {"uri": "u2"}]]+ assert session.get.call_count == 1++ def test_empty_results_yields_nothing(self) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response(200, {"results": []})+ with patch.object(new_york_times, "make_tracked_session", return_value=session):+ batches = list(+ get_rows("KEY", "most_popular_viewed", MagicMock(), _FakeResumableManager()) # type: ignore[arg-type]+ )+ assert batches == []+++class TestGetRowsArticleSearch:+ @staticmethod+ def _docs(n: int, start: int = 0) -> dict:+ return {"response": {"docs": [{"_id": f"a{start + i}"} for i in range(n)]}}++ def test_pages_until_short_page_and_saves_state(self) -> None:+ # A full page (10) then a short page (2) → two fetches, then stop.+ session = MagicMock()+ session.get.side_effect = [+ _mock_response(200, self._docs(10, 0)),+ _mock_response(200, self._docs(2, 10)),+ ]+ manager = _FakeResumableManager()+ with (+ patch.object(new_york_times, "make_tracked_session", return_value=session),+ patch.object(new_york_times.time, "sleep"),+ freeze_time("2026-07-02"),+ ):+ batches = list(+ get_rows("KEY", "article_search", MagicMock(), manager) # type: ignore[arg-type]+ )+ assert len(batches) == 2+ assert len(batches[0]) == 10+ assert len(batches[1]) == 2+ # State saved after each yielded page, advancing the page cursor with a stable begin_date.+ assert [s.page for s in manager.saved] == [1, 2]+ assert all(s.begin_date == "20260602" for s in manager.saved)++ def test_stops_on_empty_first_page(self) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response(200, {"response": {"docs": []}})+ with (+ patch.object(new_york_times, "make_tracked_session", return_value=session),+ patch.object(new_york_times.time, "sleep"),+ freeze_time("2026-07-02"),+ ):+ batches = list(+ get_rows("KEY", "article_search", MagicMock(), _FakeResumableManager()) # type: ignore[arg-type]+ )+ assert batches == []+ assert session.get.call_count == 1++ def test_respects_page_cap(self) -> None:+ # Always-full pages must stop at the 100-page hard cap rather than loop forever.+ session = MagicMock()+ session.get.return_value = _mock_response(200, self._docs(10, 0))+ with (+ patch.object(new_york_times, "make_tracked_session", return_value=session),+ patch.object(new_york_times.time, "sleep"),+ freeze_time("2026-07-02"),+ ):+ batches = list(+ get_rows("KEY", "article_search", MagicMock(), _FakeResumableManager()) # type: ignore[arg-type]+ )+ assert len(batches) == ARTICLE_SEARCH_MAX_PAGES+ assert session.get.call_count == ARTICLE_SEARCH_MAX_PAGES++ def test_resumes_from_saved_page_and_window(self) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response(200, {"response": {"docs": []}})+ manager = _FakeResumableManager(NewYorkTimesResumeConfig(page=7, begin_date="20250101"))+ with (+ patch.object(new_york_times, "make_tracked_session", return_value=session),+ patch.object(new_york_times.time, "sleep"),+ ):+ list(get_rows("KEY", "article_search", MagicMock(), manager)) # type: ignore[arg-type]+ called_url = session.get.call_args_list[0].args[0]+ assert "page=7" in called_url+ assert "begin_date=20250101" in called_url++ def test_passes_query_and_sort(self) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response(200, {"response": {"docs": []}})+ with (+ patch.object(new_york_times, "make_tracked_session", return_value=session),+ patch.object(new_york_times.time, "sleep"),+ freeze_time("2026-07-02"),+ ):+ list(+ get_rows(+ "KEY",+ "article_search",+ MagicMock(),+ _FakeResumableManager(), # type: ignore[arg-type]+ query="climate",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),+ )+ )+ called_url = session.get.call_args_list[0].args[0]+ assert "sort=oldest" in called_url+ assert "q=climate" in called_url+ assert "begin_date=20260601" in called_url+++class TestFetchPageRetry:+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])+ def test_retryable_statuses_retry(self, _name: str, status_code: int) -> None:+ bad = _mock_response(status_code, {})+ good = _mock_response(200, {"results": []})+ session = MagicMock()+ session.get.side_effect = [bad, good]+ with patch.object(new_york_times._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = new_york_times._fetch_page(session, "https://api.nytimes.com/x", {}, MagicMock())+ assert result == {"results": []}+ assert session.get.call_count == 2++ def test_client_error_raises_without_leaking_api_key(self) -> None:+ # The api-key rides in the query string; a client-error must never surface it in the raised+ # message (it's stored on the schema and shown to users). The message must still start with the+ # non-retryable-error key prefix so the sync stops instead of retrying forever.+ session = MagicMock()+ response = requests.Response()+ response.status_code = 401+ response.reason = "Unauthorized"+ session.get.return_value = response+ url = new_york_times._build_url("/svc/mostpopular/v2/viewed/7.json", "SECRETKEY", {})+ with pytest.raises(requests.HTTPError) as exc_info:+ new_york_times._fetch_page(session, url, {}, MagicMock())+ message = str(exc_info.value)+ assert "SECRETKEY" not in message+ assert message.startswith("401 Client Error: Unauthorized for url: https://api.nytimes.com")+++class TestSourceResponse:+ @parameterized.expand(+ [+ ("article_search", ["_id"], "pub_date"),+ ("most_popular_viewed", ["uri"], "published_date"),+ ("most_popular_emailed", ["uri"], "published_date"),+ ("most_popular_shared", ["uri"], "published_date"),+ ("top_stories", ["uri"], "created_date"),+ ]+ )+ def test_response_metadata(self, endpoint: str, primary_keys: list[str], partition_key: str) -> None:+ response = new_york_times_source("KEY", endpoint, MagicMock(), _FakeResumableManager()) # type: ignore[arg-type]+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"+ assert response.sort_mode == "asc"++ def test_items_callable_is_lazy(self) -> None:+ # Building the SourceResponse must not make any HTTP calls — only iterating `items` does.+ with patch.object(new_york_times, "make_tracked_session") as mocked:+ response = new_york_times_source("KEY", "top_stories", MagicMock(), _FakeResumableManager()) # type: ignore[arg-type]+ assert mocked.call_count == 0+ assert callable(response.items)++[email protected]("endpoint", list(NEW_YORK_TIMES_ENDPOINTS.keys()))+def test_every_endpoint_declares_primary_keys(endpoint: str) -> None:+ config = NEW_YORK_TIMES_ENDPOINTS[endpoint]+ assert config.primary_keys, f"{endpoint} must declare primary keys"+ assert config.data_selector in {"docs", "results"}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/tests/test_new_york_times_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/tests/test_new_york_times_source.pynew file mode 100644index 000000000000..41295a451e99--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/tests/test_new_york_times_source.py@@ -0,0 +1,135 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import NewYorkTimesSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.new_york_times import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.new_york_times.new_york_times import (+ NewYorkTimesResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.new_york_times.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.new_york_times.source import NewYorkTimesSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(api_key: str = "KEY", article_search_query: str | None = None) -> NewYorkTimesSourceConfig:+ return NewYorkTimesSourceConfig(api_key=api_key, article_search_query=article_search_query)+++class TestNewYorkTimesSource:+ def setup_method(self) -> None:+ self.source = NewYorkTimesSource()+ self.team_id = 123++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.NEWYORKTIMES++ def test_source_config_shape(self) -> None:+ config = self.source.get_source_config+ assert config.label == "New York Times"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/new-york-times"+ assert config.iconPath.endswith(".png")+ fields = {f.name: f for f in config.fields}+ assert set(fields) == {"api_key", "article_search_query"}+ api_key_field = fields["api_key"]+ query_field = fields["article_search_query"]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert isinstance(query_field, SourceFieldInputConfig)+ assert api_key_field.required is True+ assert query_field.required is False++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas iterates a static catalog with no I/O, so the public docs table list is safe.+ assert self.source.lists_tables_without_credentials is True++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert any(expected_key in key for key in self.source.get_non_retryable_errors())++ def test_get_schemas_covers_every_endpoint(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=self.team_id)}+ assert set(schemas) == set(ENDPOINTS)++ def test_only_article_search_is_incremental(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=self.team_id)}+ assert schemas["article_search"].supports_incremental is True+ assert [f["field"] for f in schemas["article_search"].incremental_fields] == ["pub_date"]+ for snapshot in ("most_popular_viewed", "most_popular_emailed", "most_popular_shared", "top_stories"):+ assert schemas[snapshot].supports_incremental is False+ assert schemas[snapshot].incremental_fields == []++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(_config(), team_id=self.team_id, names=["top_stories"])+ assert [s.name for s in schemas] == ["top_stories"]++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ names = {t["name"] for t in tables}+ assert set(ENDPOINTS) <= names+ article_search = next(t for t in tables if t["name"] == "article_search")+ assert "Incremental" in article_search["sync_methods"]+ assert article_search["primary_keys"] == ["_id"]++ @pytest.mark.parametrize("valid", [True, False])+ def test_validate_credentials(self, valid: bool) -> None:+ with patch.object(source_module, "validate_nyt_credentials", return_value=valid):+ ok, error = self.source.validate_credentials(_config(), team_id=self.team_id)+ assert ok is valid+ assert (error is None) is valid++ def test_get_resumable_source_manager_binds_data_class(self) -> None:+ inputs = MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is NewYorkTimesResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "article_search"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-06-01"+ manager = MagicMock()+ captured: dict[str, Any] = {}++ sentinel = MagicMock()++ def fake_source(**kwargs: Any) -> Any:+ captured.update(kwargs)+ return sentinel++ with patch.object(source_module, "new_york_times_source", side_effect=fake_source):+ result = self.source.source_for_pipeline(_config(article_search_query="climate"), manager, inputs)++ assert result is sentinel+ assert captured["endpoint"] == "article_search"+ assert captured["query"] == "climate"+ assert captured["should_use_incremental_field"] is True+ assert captured["db_incremental_field_last_value"] == "2026-06-01"++ def test_source_for_pipeline_drops_watermark_when_full_refresh(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "top_stories"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-06-01"+ captured: dict[str, Any] = {}++ with patch.object(source_module, "new_york_times_source", side_effect=lambda **kw: captured.update(kw)):+ self.source.source_for_pipeline(_config(), MagicMock(), inputs)++ assert captured["db_incremental_field_last_value"] is None++ def test_empty_query_becomes_none(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "article_search"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = None+ captured: dict[str, Any] = {}++ with patch.object(source_module, "new_york_times_source", side_effect=lambda **kw: captured.update(kw)):+ self.source.source_for_pipeline(_config(article_search_query=""), MagicMock(), inputs)++ assert captured["query"] is None