: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 perigon import source (#72660)
Tom Owers646e3421a0d2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 0fa044e1ca5a..e0c6a669b041 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -411,6 +411,7 @@ the row lists both.| payfit | HTTP | requests | ✅ || paystack | HTTP | requests + `rest_source.RESTClient` | ✅ || pendo | HTTP | requests | ✅ |+| perigon | HTTP | requests + `rest_source.RESTClient` | ✅ || persistiq | HTTP | requests | ✅ || persona | HTTP | requests | ✅ || personio | HTTP | requests | ✅ |@@ -861,7 +862,6 @@ doesn't conflict with concurrent PRs.- peec_ai- pendo- pennylane-- perigon- perk- pexels- phyllodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/perigon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/perigon.pyindex 101f78052542..781c86525826 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/perigon.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/perigon.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass PerigonSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/canonical_descriptions.pynew file mode 100644index 000000000000..e768744153e2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/canonical_descriptions.py@@ -0,0 +1,126 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "articles": {+ "description": "News articles enriched by Perigon with categories, entities, sentiment, and source metadata.",+ "docs_url": "https://docs.perigon.io/reference/all-news",+ "columns": {+ "articleId": "Unique identifier for the article.",+ "clusterId": "Identifier of the story cluster the article belongs to.",+ "url": "Canonical URL of the article.",+ "title": "Article headline.",+ "description": "Short description of the article.",+ "content": "Full article body text, where licensing allows.",+ "summary": "Perigon-generated summary of the article.",+ "pubDate": "When the article was published by its source.",+ "addDate": "When the article was added to Perigon's system.",+ "refreshDate": "When the article was last refreshed in Perigon's system.",+ "language": "Detected language of the article.",+ "source": "Publishing source metadata, including its domain.",+ "sentiment": "Positive, negative, and neutral sentiment scores for the article.",+ "keywords": "Keywords extracted from the article.",+ "categories": "News categories assigned to the article.",+ "entities": "Named entities detected in the article.",+ "companies": "Companies detected in the article.",+ "people": "People detected in the article.",+ "matchedAuthors": "Journalists matched to the article's byline.",+ "reprint": "Whether the article is a reprint of another article.",+ "reprintGroupId": "Identifier grouping reprints of the same original article.",+ },+ },+ "stories": {+ "description": "Story clusters that group related articles covering the same news event, with aggregate summaries and stats.",+ "docs_url": "https://docs.perigon.io/reference/stories",+ "columns": {+ "id": "Unique identifier for the story cluster.",+ "name": "Name assigned to the story once it has enough unique articles.",+ "summary": "Perigon-generated summary of the story.",+ "shortSummary": "Condensed summary of the story.",+ "keyPoints": "Key points extracted from the story's coverage.",+ "createdAt": "When the story cluster was created.",+ "updatedAt": "When the story cluster last received new articles.",+ "initializedAt": "When the story cluster was first initialized.",+ "uniqueCount": "Number of unique articles in the cluster.",+ "uniqueSources": "Number of unique sources covering the story.",+ "sentiment": "Aggregate sentiment scores across the story's articles.",+ "topCountries": "Countries most represented in the story's coverage.",+ "duplicateOf": "Identifier of the original cluster when this story was deduplicated into it.",+ },+ },+ "journalists": {+ "description": "Journalist profiles tracked by Perigon, with beats, outlets, and social links.",+ "docs_url": "https://docs.perigon.io/reference/journalists",+ "columns": {+ "id": "Unique identifier for the journalist.",+ "name": "Journalist's full name.",+ "title": "Journalist's title or role.",+ "headline": "Short professional headline for the journalist.",+ "topSources": "Sources the journalist most frequently publishes with.",+ "topics": "Topics the journalist most frequently covers.",+ "locations": "Locations associated with the journalist.",+ "twitterHandle": "Journalist's X (Twitter) handle.",+ "updatedAt": "When the journalist profile was last updated.",+ },+ },+ "sources": {+ "description": "Media sources monitored by Perigon, with reach, bias, and paywall metadata.",+ "docs_url": "https://docs.perigon.io/reference/sources",+ "columns": {+ "id": "Unique identifier for the source.",+ "domain": "Primary domain of the source.",+ "name": "Display name of the source.",+ "description": "Description of the source.",+ "globalRank": "Global traffic rank of the source's website.",+ "monthlyVisits": "Estimated monthly visits to the source's website.",+ "avgBiasRating": "Average political bias rating for the source.",+ "paywall": "Whether the source sits behind a paywall.",+ "topCategories": "Categories the source most frequently publishes in.",+ "updatedAt": "When the source record was last updated.",+ },+ },+ "people": {+ "description": "Public figures tracked by Perigon for entity matching in news coverage, keyed by Wikidata id.",+ "docs_url": "https://docs.perigon.io/reference/people",+ "columns": {+ "wikidataId": "Wikidata identifier for the person.",+ "name": "Person's full name.",+ "abstract": "Short biography of the person.",+ "description": "One-line description of the person.",+ "occupation": "The person's occupations.",+ "position": "Positions the person has held.",+ "politicalParty": "Political party affiliations, where applicable.",+ "dateOfBirth": "The person's date of birth.",+ "updatedAt": "When the person record was last updated.",+ },+ },+ "companies": {+ "description": "Companies tracked by Perigon for entity matching in news coverage, with identifiers and firmographics.",+ "docs_url": "https://docs.perigon.io/reference/companies",+ "columns": {+ "id": "Unique identifier for the company.",+ "name": "Company name.",+ "altNames": "Alternate names the company is known by.",+ "domains": "Web domains associated with the company.",+ "symbols": "Stock ticker symbols for the company.",+ "isin": "International Securities Identification Number.",+ "ceo": "The company's CEO.",+ "industry": "Industry the company operates in.",+ "country": "Country the company is headquartered in.",+ "numEmployees": "Number of employees.",+ "updatedAt": "When the company record was last updated.",+ },+ },+ "topics": {+ "description": "Topics Perigon assigns to articles and stories, usable as filters in article search.",+ "docs_url": "https://docs.perigon.io/reference/topics",+ "columns": {+ "id": "Unique identifier for the topic.",+ "name": "Topic name.",+ "labels": "Category and subcategory labels for the topic.",+ "createdAt": "When the topic was created.",+ "updatedAt": "When the topic was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/perigon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/perigon.pynew file mode 100644index 000000000000..47905fb05147--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/perigon.py@@ -0,0 +1,218 @@+import dataclasses+from datetime import UTC, date, datetime+from typing import Any, Optional++from requests import Response+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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.perigon.settings import PERIGON_ENDPOINTS++# Current canonical host; api.goperigon.com is the legacy alias and serves the same API.+PERIGON_BASE_URL = "https://api.perigon.io"++PAGE_SIZE = 100+# Perigon caps the search result window at 10,000 rows (page * size), so with size=100 the+# last reachable page index is 99. Incremental syncs self-heal past the cap: the watermark+# advances with every batch, so the next run picks up where the capped one stopped.+MAX_PAGE = 99+++class PerigonResumeConfig:+ # Next zero-based page to fetch, as reported by the framework paginator state.+ page: int+++class PerigonPaginator(PageNumberPaginator):+ """Zero-based page/`size` pagination over Perigon's wrapped list responses.++ Perigon exposes no total-pages field, so a page shorter than the requested size is the+ last page; stopping on it avoids the extra empty-page request. The page cap mirrors the+ API's 10,000-row search window — a full page at the cap is logged since rows may remain.+ """++ def __init__(self, page_size: int, endpoint: str, logger: Optional[FilteringBoundLogger] = None) -> None:+ super().__init__(base_page=0, page_param="page", maximum_page=MAX_PAGE)+ self._page_size = page_size+ self._endpoint = endpoint+ self._logger = logger++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ if self._has_next_page and data is not None and len(data) < self._page_size:+ self._has_next_page = False+ return+ if (+ not self._has_next_page+ and data is not None+ and len(data) >= self._page_size+ and self.page > (self.maximum_page or 0)+ and self._logger is not None+ ):+ self._logger.warning(+ "Perigon pagination depth cap reached; remaining rows are deferred to later syncs",+ endpoint=self._endpoint,+ page=self.page,+ )+++def _format_datetime(value: Any) -> str:+ """Format a datetime/date cursor as `yyyy-MM-ddThh:mm:ssZ` (ISO 8601, UTC) for Perigon's+ date filters."""+ if isinstance(value, datetime):+ dt = value+ elif isinstance(value, date):+ dt = datetime.combine(value, datetime.min.time())+ else:+ # Already a string (e.g. an ISO timestamp persisted as the cursor) — pass through.+ return str(value)+ dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _clamp_future_value_to_now(value: Any) -> Any:+ """Cap a future datetime cursor at now — a future-dated lower-bound filter would silently+ match nothing and stall the incremental sync."""+ now = datetime.now(UTC)+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return now if aware > now else value+ if isinstance(value, date):+ return now.date() if value > now.date() else value+ if isinstance(value, str):+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return value+ aware = parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)+ return now if aware > now else value+ return value+++def get_resource(+ endpoint: str,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+ logger: Optional[FilteringBoundLogger] = None,+) -> EndpointResource:+ config = PERIGON_ENDPOINTS[endpoint]++ params: dict[str, Any] = {"size": PAGE_SIZE}+ # Incremental runs must walk the cursor field even before a watermark exists so the+ # pipeline's ordering assumption (sort_mode) holds from the first sync.+ sort_by = (+ config.incremental_sort_by+ if should_use_incremental_field and config.incremental_sort_by+ else config.full_refresh_sort_by+ )+ if sort_by:+ params["sortBy"] = sort_by++ endpoint_config: Endpoint = {+ "path": config.path,+ "params": params,+ "data_selector": config.data_selector,+ "data_selector_required": True,+ "paginator": PerigonPaginator(PAGE_SIZE, endpoint, logger),+ }++ # Only filter server-side once a watermark exists; the first incremental sync reads from+ # the beginning of what the account can access.+ if should_use_incremental_field and config.incremental_param and db_incremental_field_last_value is not None:+ endpoint_config["incremental"] = {+ "start_param": config.incremental_param,+ "cursor_path": config.incremental_fields[0]["field"],+ "convert": lambda value: _format_datetime(_clamp_future_value_to_now(value)),+ }++ return {+ "name": endpoint,+ "table_name": endpoint,+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def perigon_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[PerigonResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ logger: Optional[FilteringBoundLogger] = None,+) -> SourceResponse:+ config = PERIGON_ENDPOINTS[endpoint]++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": PERIGON_BASE_URL,+ "auth": {"type": "bearer", "token": api_key},+ "headers": {"Accept": "application/json"},+ },+ "resource_defaults": {},+ "resources": [get_resource(endpoint, should_use_incremental_field, db_incremental_field_last_value, logger)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_paginator_state = {"page": resume.page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Save AFTER a page is yielded so a crash re-yields the last page (merge dedupes)+ # rather than skipping it. A None state means no page remains — nothing to persist.+ if state is not None and state.get("page") is not None:+ resumable_source_manager.save_state(PerigonResumeConfig(page=int(state["page"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ sort_mode=config.sort_mode,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def validate_credentials(api_key: str, path: Optional[str] = None) -> tuple[bool, int | None]:+ """Probe one cheap endpoint and report (is_valid, status_code).++ Defaults to the articles endpoint (Perigon's core dataset); pass a specific endpoint+ path to confirm the key's plan covers that dataset.+ """+ probe_path = path or PERIGON_ENDPOINTS["articles"].path+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{PERIGON_BASE_URL}{probe_path}?size=1",+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/settings.pynew file mode 100644index 000000000000..7fed1c6c7742--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/settings.py@@ -0,0 +1,118 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class PerigonEndpointConfig:+ name: str+ path: str+ # JSON key holding the row list in the response wrapper (`articles`, `results`, or `data`).+ data_selector: str+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Query param for the server-side lower-bound timestamp filter, when the endpoint has one.+ incremental_param: Optional[str] = None+ # `sortBy` value used on incremental runs so pagination walks the cursor field.+ incremental_sort_by: Optional[str] = None+ # `sortBy` value used on full-refresh runs for stable page boundaries; None = API default.+ full_refresh_sort_by: Optional[str] = None+ # Stable creation-style field used to partition the Delta table. Never an `updatedAt`+ # style field — those rewrite partitions on every sync.+ partition_key: Optional[str] = None+ sort_mode: Literal["asc", "desc"] = "asc"+++_ARTICLE_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "pubDate",+ "type": IncrementalFieldType.DateTime,+ "field": "pubDate",+ "field_type": IncrementalFieldType.DateTime,+ },+]++_STORY_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "updatedAt",+ "type": IncrementalFieldType.DateTime,+ "field": "updatedAt",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++PERIGON_ENDPOINTS: dict[str, PerigonEndpointConfig] = {+ # News articles. `from` filters on publication date and `sortBy=reverseDate` is the+ # documented ascending-publication-date sort, so the incremental watermark advances+ # safely batch by batch.+ "articles": PerigonEndpointConfig(+ name="articles",+ path="/v1/articles/all",+ data_selector="articles",+ primary_keys=["articleId"],+ incremental_fields=_ARTICLE_INCREMENTAL_FIELDS,+ incremental_param="from",+ incremental_sort_by="reverseDate",+ # addDate ascending = insertion order, so rows added mid-sync append after the+ # current page instead of shifting earlier page boundaries.+ full_refresh_sort_by="reverseAddDate",+ partition_key="pubDate",+ sort_mode="asc",+ ),+ # Story clusters. `updatedFrom` filters on the cluster's last-update time, which also+ # catches clusters that gained new articles. Perigon documents no ascending sort for+ # stories, so the sort is the cursor field newest-first and sort_mode is "desc" (the+ # watermark is only finalized at the end of the sync).+ "stories": PerigonEndpointConfig(+ name="stories",+ path="/v1/stories/all",+ data_selector="results",+ primary_keys=["id"],+ incremental_fields=_STORY_INCREMENTAL_FIELDS,+ incremental_param="updatedFrom",+ incremental_sort_by="updatedAt",+ full_refresh_sort_by="createdAt",+ partition_key="createdAt",+ sort_mode="desc",+ ),+ # Reference datasets below have no verified server-side timestamp filter, so they sync+ # as full refresh only.+ "journalists": PerigonEndpointConfig(+ name="journalists",+ path="/v1/journalists/all",+ data_selector="results",+ primary_keys=["id"],+ ),+ "sources": PerigonEndpointConfig(+ name="sources",+ path="/v1/sources/all",+ data_selector="results",+ primary_keys=["id"],+ ),+ "people": PerigonEndpointConfig(+ name="people",+ path="/v1/people/all",+ data_selector="results",+ primary_keys=["wikidataId"],+ ),+ "companies": PerigonEndpointConfig(+ name="companies",+ path="/v1/companies/all",+ data_selector="results",+ primary_keys=["id"],+ ),+ "topics": PerigonEndpointConfig(+ name="topics",+ path="/v1/topics/all",+ data_selector="data",+ primary_keys=["id"],+ ),+}++ENDPOINTS = tuple(PERIGON_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in PERIGON_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/source.pyindex 557cc797c4bf..9fad09dad960 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/source.py@@ -1,21 +1,49 @@-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 (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.perigon import (PerigonSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.perigon.perigon import (+ PerigonResumeConfig,+ perigon_source,+ validate_credentials as validate_perigon_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.perigon.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ PERIGON_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PerigonSource(SimpleSource[PerigonSourceConfig]):+class PerigonSource(ResumableSource[PerigonSourceConfig, PerigonResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://docs.perigon.io/docs/overview"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PERIGON@@ -26,7 +54,93 @@ class PerigonSource(SimpleSource[PerigonSourceConfig]):name=SchemaExternalDataSourceType.PERIGON,category=DataWarehouseSourceCategory.ANALYTICS,label="Perigon",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["news", "media", "goperigon"],+ caption="""Enter your Perigon API key to sync news articles, story clusters, journalists, sources, people, companies, and topics into the PostHog Data warehouse.++You can find your API key on your [Perigon account dashboard](https://www.perigon.io/).++Datasets available to sync depend on your Perigon plan. Perigon caps each search to 10,000 results, so incremental syncs on articles and stories catch up across runs.""",iconPath="/static/services/perigon.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/perigon",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # An invalid/revoked key (401) or a dataset outside the plan (403) surfaces as a+ # requests HTTPError; match the stable status text and base host, not the+ # per-request path/query.+ return {+ "401 Client Error: Unauthorized for url: https://api.perigon.io": "Your Perigon API key is invalid or has been revoked. Generate a new key on your Perigon account dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.perigon.io": "Your Perigon plan does not include access to this dataset. Deselect the table or upgrade your Perigon plan, then try again.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.perigon.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: PerigonSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Only articles and stories have a documented server-side timestamp filter; the+ # reference datasets are full refresh.+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self, config: PerigonSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ endpoint = PERIGON_ENDPOINTS.get(schema_name) if schema_name else None+ ok, status = validate_perigon_credentials(config.api_key, path=endpoint.path if endpoint else None)+ if ok:+ return True, None+ if status == 403:+ if schema_name is None:+ # The key is genuine; a plan may simply not include every dataset. Sync-time+ # 403s on specific tables are handled by get_non_retryable_errors.+ return True, None+ return False, f"Your Perigon plan does not include access to {schema_name}"+ if status == 401:+ return False, "Perigon API key is invalid or has been revoked"+ return False, "Could not validate Perigon credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PerigonResumeConfig]:+ return ResumableSourceManager[PerigonResumeConfig](inputs, PerigonResumeConfig)++ def source_for_pipeline(+ self,+ config: PerigonSourceConfig,+ resumable_source_manager: ResumableSourceManager[PerigonResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return perigon_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ 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,+ logger=inputs.logger,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/tests/test_perigon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/tests/test_perigon.pynew file mode 100644index 000000000000..3b747676ba39--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/tests/test_perigon.py@@ -0,0 +1,309 @@+import json+from datetime import UTC, date, datetime+from typing import Any++import pytest+from freezegun import freeze_time+from unittest import mock++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.perigon.perigon import (+ MAX_PAGE,+ PERIGON_BASE_URL,+ PerigonPaginator,+ PerigonResumeConfig,+ _clamp_future_value_to_now,+ _format_datetime,+ perigon_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.perigon.settings import PERIGON_ENDPOINTS++# RESTClient builds its session via make_tracked_session in the rest_client module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+# validate_credentials builds its own tracked session in the perigon module.+PERIGON_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.perigon.perigon.make_tracked_session"+)+++def _response(body: Any) -> Response:+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps(body).encode()+ return resp+++def _make_manager(resume_state: PerigonResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[tuple[str, dict[str, Any]]]:+ """Wire a mock session; capture each request's (url, params) AT SEND TIME.++ ``request.params`` is one dict mutated in place across pages, so snapshot a copy when each+ request is prepared instead of inspecting it after the run.+ """+ session.headers = {}+ snapshots: list[tuple[str, dict[str, Any]]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append((request.url, dict(request.params or {})))+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):+ return perigon_source(+ api_key="key", endpoint=endpoint, team_id=1, job_id="j", resumable_source_manager=manager, **kwargs+ )+++class TestFormatDatetime:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("string_passthrough", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str) -> None:+ assert _format_datetime(value) == expected+++class TestClampFutureValueToNow:+ @parameterized.expand(+ [+ ("future_datetime", datetime(2027, 2, 5, tzinfo=UTC), datetime(2026, 6, 15, 12, tzinfo=UTC)),+ ("past_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)),+ ("non_iso_string_passthrough", "cursor", "cursor"),+ ("future_iso_string", "2030-01-01T00:00:00Z", datetime(2026, 6, 15, 12, tzinfo=UTC)),+ ]+ )+ @freeze_time("2026-06-15T12:00:00Z")+ def test_clamp(self, _name: str, value: Any, expected: Any) -> None:+ assert _clamp_future_value_to_now(value) == expected+++class TestPaginator:+ def _paginator(self, logger: mock.MagicMock | None = None) -> PerigonPaginator:+ paginator = PerigonPaginator(page_size=2, endpoint="articles", logger=logger)+ request = mock.MagicMock()+ request.params = {}+ paginator.init_request(request)+ assert request.params == {"page": 0}+ return paginator++ def test_full_page_advances_to_next_page(self) -> None:+ paginator = self._paginator()+ paginator.update_state(_response({"articles": []}), [{"a": 1}, {"a": 2}])+ assert paginator.has_next_page is True+ request = mock.MagicMock()+ request.params = {}+ paginator.update_request(request)+ assert request.params == {"page": 1}++ @parameterized.expand([("short_page", [{"a": 1}]), ("empty_page", [])])+ def test_short_or_empty_page_terminates(self, _name: str, data: list[dict[str, Any]]) -> None:+ paginator = self._paginator()+ paginator.update_state(_response({"articles": []}), data)+ assert paginator.has_next_page is False++ def test_depth_cap_stops_and_logs(self) -> None:+ # Perigon rejects pagination past its 10,000-row search window; running past the cap+ # would fail every large sync mid-way.+ logger = mock.MagicMock()+ paginator = self._paginator(logger)+ paginator.page = MAX_PAGE+ paginator.update_state(_response({"articles": []}), [{"a": 1}, {"a": 2}])+ assert paginator.has_next_page is False+ logger.warning.assert_called_once()++ def test_no_cap_log_below_cap(self) -> None:+ logger = mock.MagicMock()+ paginator = self._paginator(logger)+ paginator.update_state(_response({"articles": []}), [{"a": 1}, {"a": 2}])+ assert paginator.has_next_page is True+ logger.warning.assert_not_called()+++class TestEndpointRequests:+ @parameterized.expand([(name, cfg.data_selector) for name, cfg in PERIGON_ENDPOINTS.items()])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_rows_extracted_from_wrapper(self, endpoint: str, selector: str, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({selector: [{"k": "v"}]})])++ rows = _rows(_source(endpoint, _make_manager()))++ assert rows == [{"k": "v"}]+ url, params = snapshots[0]+ assert url == f"{PERIGON_BASE_URL}{PERIGON_ENDPOINTS[endpoint].path}"+ assert params["page"] == 0+ assert params["size"] == 100++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_missing_wrapper_key_fails_loud(self, MockSession) -> None:+ session = MockSession.return_value+ # A 200 body without the expected wrapper key means the response shape changed —+ # fail loud, not 0 rows.+ _wire(session, [_response({"unexpected": []})])++ with pytest.raises(ValueError):+ _rows(_source("articles", _make_manager()))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_pagination_walks_pages_until_short_page(self, MockSession) -> None:+ session = MockSession.return_value+ full_page = [{"articleId": str(i)} for i in range(100)]+ snapshots = _wire(session, [_response({"articles": full_page}), _response({"articles": [{"articleId": "x"}]})])++ rows = _rows(_source("articles", _make_manager()))++ assert len(rows) == 101+ assert [params["page"] for _, params in snapshots] == [0, 1]+++class TestIncrementalParams:+ @parameterized.expand(+ [+ ("articles", "from", "reverseDate"),+ ("stories", "updatedFrom", "updatedAt"),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_watermark_passed_as_server_side_filter(self, endpoint: str, param: str, sort_by: str, MockSession) -> None:+ session = MockSession.return_value+ selector = PERIGON_ENDPOINTS[endpoint].data_selector+ snapshots = _wire(session, [_response({selector: []})])++ _rows(+ _source(+ endpoint,+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ )++ params = snapshots[0][1]+ assert params[param] == "2026-03-04T02:58:14Z"+ assert params["sortBy"] == sort_by++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_without_watermark_sorts_but_does_not_filter(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"articles": []})])++ _rows(_source("articles", _make_manager(), should_use_incremental_field=True))++ params = snapshots[0][1]+ assert "from" not in params+ # The cursor-field sort must apply from the first incremental sync so sort_mode holds.+ assert params["sortBy"] == "reverseDate"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_full_refresh_uses_stable_sort_and_no_filter(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"articles": []})])++ _rows(_source("articles", _make_manager(), should_use_incremental_field=False))++ params = snapshots[0][1]+ assert "from" not in params+ assert params["sortBy"] == "reverseAddDate"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_full_refresh_reference_endpoint_passes_no_sort(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"results": []})])++ _rows(_source("journalists", _make_manager()))++ assert "sortBy" not in snapshots[0][1]+++class TestResume:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resume_starts_from_saved_page(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"articles": []})])++ _rows(_source("articles", _make_manager(PerigonResumeConfig(page=7))))++ assert snapshots[0][1]["page"] == 7++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_state_saved_after_each_full_page(self, MockSession) -> None:+ session = MockSession.return_value+ full_page = [{"articleId": str(i)} for i in range(100)]+ _wire(session, [_response({"articles": full_page}), _response({"articles": []})])+ manager = _make_manager()++ _rows(_source("articles", manager))++ assert manager.save_state.called+ saved = manager.save_state.call_args.args[0]+ assert isinstance(saved, PerigonResumeConfig)+ assert saved.page == 1+++class TestPerigonSourceResponse:+ @parameterized.expand([(name,) for name in PERIGON_ENDPOINTS])+ def test_primary_keys_and_sort_mode_match_config(self, endpoint: str) -> None:+ response = _source(endpoint, _make_manager())+ config = PERIGON_ENDPOINTS[endpoint]+ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == config.sort_mode++ def test_articles_partitioned_on_stable_pub_date(self) -> None:+ response = _source("articles", _make_manager())+ assert response.partition_keys == ["pubDate"]+ assert response.partition_mode == "datetime"++ def test_stories_partitioned_on_created_at_not_updated_at(self) -> None:+ # updatedAt changes on every new article in the cluster — partitioning on it would+ # rewrite partitions each sync.+ response = _source("stories", _make_manager())+ assert response.partition_keys == ["createdAt"]++ def test_full_refresh_endpoint_has_no_partition(self) -> None:+ response = _source("topics", _make_manager())+ assert response.partition_keys is None+ assert response.partition_mode is None+++class TestValidateCredentials:+ @pytest.mark.parametrize("status,expected", [(200, True), (401, False), (403, False)])+ def test_status_maps_to_validity(self, status: int, expected: bool) -> None:+ with mock.patch(PERIGON_SESSION_PATCH) as mock_session:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status)+ ok, returned_status = validate_credentials("key")+ assert ok is expected+ assert returned_status == status++ def test_network_error_is_invalid(self) -> None:+ with mock.patch(PERIGON_SESSION_PATCH) as mock_session:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("key") == (False, None)++ def test_schema_probe_hits_that_endpoint(self) -> None:+ with mock.patch(PERIGON_SESSION_PATCH) as mock_session:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("key", path=PERIGON_ENDPOINTS["stories"].path)+ url = mock_session.return_value.get.call_args.args[0]+ assert url.startswith(f"{PERIGON_BASE_URL}/v1/stories/all")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/tests/test_perigon_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/tests/test_perigon_source.pynew file mode 100644index 000000000000..5dd4987ab6e6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/tests/test_perigon_source.py@@ -0,0 +1,151 @@+from typing import Any++import pytest+from unittest.mock import MagicMock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.perigon import (+ PerigonSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.perigon.perigon import PerigonResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.perigon.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.perigon.source import PerigonSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++VALIDATE_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.perigon.source.validate_perigon_credentials"+)+++class TestPerigonSource:+ def setup_method(self) -> None:+ self.source = PerigonSource()+ self.team_id = 123++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.PERIGON++ def test_source_config_is_released_alpha(self) -> None:+ config = self.source.get_source_config+ assert config.label == "Perigon"+ assert config.category == DataWarehouseSourceCategory.ANALYTICS+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # unreleasedSource hides the connector from every user — a finished source must not set it.+ assert not config.unreleasedSource++ def test_source_config_has_secret_api_key_field(self) -> None:+ fields = self.source.get_source_config.fields+ assert len(fields) == 1+ api_key_field = fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+ assert api_key_field.secret is True++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_only_articles_and_stories_support_incremental(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(MagicMock(), team_id=self.team_id)}+ for name, schema in schemas.items():+ expected = name in ("articles", "stories")+ assert schema.supports_incremental is expected+ assert schema.supports_append is expected++ @pytest.mark.parametrize("endpoint,field", [("articles", "pubDate"), ("stories", "updatedAt")])+ def test_incremental_fields(self, endpoint: str, field: str) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(MagicMock(), team_id=self.team_id)}+ assert [f["field"] for f in schemas[endpoint].incremental_fields] == [field]++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id, names=["articles", "topics"])+ assert {s.name for s in schemas} == {"articles", "topics"}++ def test_non_retryable_error_keys_match_perigon_host(self) -> None:+ # The observed HTTPError message embeds the request URL; the key must match the base host.+ observed = "401 Client Error: Unauthorized for url: https://api.perigon.io/v1/articles/all?size=100"+ assert any(key in observed for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "probe_result,schema_name,expected_valid",+ [+ ((True, 200), None, True),+ ((False, 401), None, False),+ # 403 at source-create means the key is genuine but the plan lacks some dataset.+ ((False, 403), None, True),+ # 403 while probing a specific schema means that dataset is out of plan.+ ((False, 403), "stories", False),+ ((False, None), None, False),+ ],+ )+ def test_validate_credentials_status_mapping(+ self, monkeypatch: Any, probe_result: tuple[bool, int | None], schema_name: str | None, expected_valid: bool+ ) -> None:+ monkeypatch.setattr(VALIDATE_PATCH, lambda api_key, path=None: probe_result)+ config = PerigonSourceConfig(api_key="key")+ valid, error = self.source.validate_credentials(config, self.team_id, schema_name=schema_name)+ assert valid is expected_valid+ if not expected_valid:+ assert error is not None++ def test_validate_credentials_probes_schema_endpoint(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_validate(api_key: str, path: str | None = None) -> tuple[bool, int | None]:+ captured["path"] = path+ return True, 200++ monkeypatch.setattr(VALIDATE_PATCH, fake_validate)+ self.source.validate_credentials(PerigonSourceConfig(api_key="key"), self.team_id, schema_name="companies")+ assert captured["path"] == "/v1/companies/all"++ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PerigonResumeConfig++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)++ def test_source_for_pipeline_plumbs_endpoint_and_incremental(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}+ monkeypatch.setattr(+ "products.warehouse_sources.backend.temporal.data_imports.sources.perigon.source.perigon_source",+ lambda **kwargs: captured.update(kwargs),+ )++ inputs = MagicMock()+ inputs.schema_name = "articles"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-03-04T00:00:00Z"++ self.source.source_for_pipeline(PerigonSourceConfig(api_key="key"), MagicMock(), inputs)+ assert captured["api_key"] == "key"+ assert captured["endpoint"] == "articles"+ assert captured["should_use_incremental_field"] is True+ assert captured["db_incremental_field_last_value"] == "2026-03-04T00:00:00Z"++ def test_source_for_pipeline_drops_incremental_value_when_full_refresh(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}+ monkeypatch.setattr(+ "products.warehouse_sources.backend.temporal.data_imports.sources.perigon.source.perigon_source",+ lambda **kwargs: captured.update(kwargs),+ )++ inputs = MagicMock()+ inputs.schema_name = "topics"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "ignored"++ self.source.source_for_pipeline(PerigonSourceConfig(api_key="key"), MagicMock(), inputs)+ assert captured["db_incremental_field_last_value"] is None