: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 phyllo import source (#69363)
Tom Owers4108f84cb471
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 95db6dae8a39..b9501d3f1267 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -270,6 +270,7 @@ the row lists both.| persona | HTTP | requests | ✅ || personio | HTTP | requests | ✅ || pexels | HTTP | requests | ✅ |+| phyllo | HTTP | requests | ✅ || picqer | HTTP | requests | ✅ || pingdom | HTTP | requests | ✅ || pinterest_ads | HTTP | requests | ✅ |@@ -605,7 +606,6 @@ doesn't conflict with concurrent PRs.- perk- persona- pexels-- phyllo- pipeliner- pivotal_tracker- piwikdiff --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 ca4e08b8d104..4b4e8ff2d5bb 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@@ -2487,7 +2487,9 @@ class PgAnalyzeSourceConfig(config.Config):@config.configclass PhylloSourceConfig(config.Config):- pass+ client_id: str+ client_secret: str+ environment: Literal["production", "sandbox"] = config.value(default="production")@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/canonical_descriptions.pynew file mode 100644index 000000000000..3b0e12091579--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/canonical_descriptions.py@@ -0,0 +1,125 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Phyllo API reference (https://docs.getphyllo.com).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "work_platforms": {+ "description": "A platform Phyllo can pull creator data from, such as YouTube, Instagram, TikTok, Twitch, or Spotify.",+ "docs_url": "https://docs.getphyllo.com",+ "columns": {+ "id": "The unique ID of the work platform.",+ "name": "The name of the work platform.",+ "logo_url": "URL of the platform's logo image.",+ "category": "The category of the platform (e.g. MEDIA, EDUCATION).",+ "status": "Whether the platform integration is active on Phyllo.",+ "url": "The website URL of the platform.",+ "products": "Which Phyllo products (identity, engagement, income, etc.) the platform supports.",+ "created_at": "When the work platform was added to Phyllo.",+ "updated_at": "When the work platform record was last updated.",+ },+ },+ "users": {+ "description": "A creator registered in your Phyllo workspace, identified by your own external ID, who links platform accounts via Phyllo Connect.",+ "docs_url": "https://docs.getphyllo.com",+ "columns": {+ "id": "The unique ID of the user.",+ "name": "The display name of the user.",+ "external_id": "Your own identifier for the user, supplied when the user was created.",+ "status": "The current status of the user.",+ "created_at": "When the user was created.",+ "updated_at": "When the user was last updated.",+ },+ },+ "accounts": {+ "description": "A platform account (e.g. a YouTube channel or Instagram account) a creator has connected through Phyllo Connect.",+ "docs_url": "https://docs.getphyllo.com",+ "columns": {+ "id": "The unique ID of the connected account.",+ "user": "The Phyllo user the account belongs to.",+ "work_platform": "The platform the account lives on.",+ "platform_username": "The creator's username on the platform.",+ "status": "The connection status of the account (e.g. CONNECTED, NOT_CONNECTED, SESSION_EXPIRED).",+ "data": "Per-product (identity, engagement, income) data availability and sync status for the account.",+ "created_at": "When the account was connected.",+ "updated_at": "When the account was last updated.",+ },+ },+ "profiles": {+ "description": "The identity profile of a connected account: name, contact details, audience reputation, and platform metadata.",+ "docs_url": "https://docs.getphyllo.com",+ "columns": {+ "id": "The unique ID of the profile.",+ "account": "The connected account the profile belongs to.",+ "user": "The Phyllo user the profile belongs to.",+ "work_platform": "The platform the profile lives on.",+ "username": "The creator's username on the platform.",+ "full_name": "The creator's full name.",+ "url": "URL of the creator's profile page on the platform.",+ "image_url": "URL of the creator's profile image.",+ "reputation": "Audience reputation metrics such as follower and subscriber counts.",+ "is_verified": "Whether the platform has verified the profile.",+ "is_business": "Whether the profile is a business account.",+ "created_at": "When the profile record was created in Phyllo.",+ "updated_at": "When the profile record was last updated.",+ },+ },+ "social_contents": {+ "description": "A content item published by a connected account — videos, posts, stories, tweets, or tracks — with its engagement metrics.",+ "docs_url": "https://docs.getphyllo.com",+ "columns": {+ "id": "The unique ID of the content item.",+ "account": "The connected account that published the content.",+ "user": "The Phyllo user the content belongs to.",+ "work_platform": "The platform the content was published on.",+ "external_id": "The platform's own identifier for the content item.",+ "title": "The title of the content item.",+ "format": "The media format of the content (e.g. VIDEO, IMAGE, AUDIO).",+ "type": "The platform-specific content type (e.g. POST, STORY, REEL, TWEET).",+ "url": "URL of the content on the platform.",+ "description": "The description or caption of the content.",+ "visibility": "The visibility of the content (e.g. PUBLIC, PRIVATE).",+ "engagement": "Engagement metrics such as like, comment, view, and share counts.",+ "published_at": "When the content was published on the platform.",+ "created_at": "When the content record was created in Phyllo.",+ "updated_at": "When the content record was last updated.",+ },+ },+ "income_transactions": {+ "description": "An earnings transaction of a connected account, such as ad revenue, subscription payments, tips, or royalties.",+ "docs_url": "https://docs.getphyllo.com",+ "columns": {+ "id": "The unique ID of the transaction.",+ "account": "The connected account the transaction belongs to.",+ "user": "The Phyllo user the transaction belongs to.",+ "work_platform": "The platform the transaction occurred on.",+ "external_id": "The platform's own identifier for the transaction.",+ "amount": "The monetary amount of the transaction.",+ "currency": "The currency of the transaction amount.",+ "type": "The earnings type of the transaction (e.g. AD_REVENUE, SUBSCRIPTION, TIP).",+ "status": "The status of the transaction.",+ "transaction_at": "When the transaction occurred on the platform.",+ "created_at": "When the transaction record was created in Phyllo.",+ "updated_at": "When the transaction record was last updated.",+ },+ },+ "income_payouts": {+ "description": "A payout made by a platform to a connected account's bank account or payment method.",+ "docs_url": "https://docs.getphyllo.com",+ "columns": {+ "id": "The unique ID of the payout.",+ "account": "The connected account the payout belongs to.",+ "user": "The Phyllo user the payout belongs to.",+ "work_platform": "The platform that made the payout.",+ "external_id": "The platform's own identifier for the payout.",+ "amount": "The monetary amount of the payout.",+ "currency": "The currency of the payout amount.",+ "status": "The status of the payout.",+ "payout_interval": "How often the platform pays out (e.g. MONTHLY).",+ "payout_at": "When the payout was made.",+ "created_at": "When the payout record was created in Phyllo.",+ "updated_at": "When the payout record was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/phyllo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/phyllo.pynew file mode 100644index 000000000000..8b750247ccae--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/phyllo.py@@ -0,0 +1,263 @@+import time+import base64+import dataclasses+from bisect import bisect_left+from collections.abc import Iterator+from typing import Any, Optional++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.phyllo.settings import PHYLLO_ENDPOINTS++# Credentials are environment-specific: a sandbox client ID/secret pair only authenticates against+# the sandbox host, so the environment select on the source form picks the base URL.+PHYLLO_BASE_URLS: dict[str, str] = {+ "production": "https://api.getphyllo.com",+ "sandbox": "https://api.sandbox.getphyllo.com",+}+# Documented maximum page size for Phyllo list endpoints.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Phyllo rate-limits at 10 requests/second per developer account and returns a Retry-After header+# on 429; cap how long we honor it before exponential backoff takes over.+MAX_RETRY_AFTER_SECONDS = 60+ACCOUNTS_PATH = "/v1/accounts"+# Cheap list endpoint used to confirm a client ID/secret pair is genuine. Phyllo credentials are+# environment-wide, so one probe validates access to every endpoint.+DEFAULT_PROBE_PATH = "/v1/work-platforms"+++class PhylloRetryableError(Exception):+ pass+++class PhylloResumeConfig:+ # Offset of the next page within the current stream. Limit-offset pagination is deterministic,+ # so a crashed sync resumes from the page after the last one yielded; merge dedupes the+ # re-pulled page on `id`.+ offset: int = 0+ # For per-account fan-out endpoints: the account whose rows were being fetched when state was+ # last saved. None for top-level endpoints.+ account_id: str | None = None+++def get_base_url(environment: str) -> str:+ return PHYLLO_BASE_URLS.get(environment, PHYLLO_BASE_URLS["production"])+++def _headers(client_id: str, client_secret: str) -> dict[str, str]:+ token = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode("ascii")+ return {"Authorization": f"Basic {token}", "Accept": "application/json"}+++def _parse_retry_after(value: str | None) -> float | None:+ if not value:+ return None+ try:+ seconds = float(value)+ except ValueError:+ return None+ return seconds if seconds > 0 else None+++@retry(+ retry=retry_if_exception_type((PhylloRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ url: str,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ if response.status_code == 429:+ retry_after = _parse_retry_after(response.headers.get("Retry-After"))+ if retry_after is not None:+ time.sleep(min(retry_after, MAX_RETRY_AFTER_SECONDS))+ raise PhylloRetryableError(f"Phyllo API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Phyllo API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ data = response.json()+ # Phyllo list endpoints wrap results in {"data": [...], "metadata": {...}}.+ if not isinstance(data, dict) or not isinstance(data.get("data"), list):+ raise PhylloRetryableError(f"Phyllo returned an unexpected payload for {url}: {type(data).__name__}")++ return data["data"]+++def _list_account_ids(+ session: requests.Session,+ base_url: str,+ logger: FilteringBoundLogger,+) -> list[str]:+ """Collect every connected account id, sorted so fan-out iteration order is deterministic."""+ account_ids: list[str] = []+ offset = 0+ while True:+ items = _fetch_page(session, f"{base_url}{ACCOUNTS_PATH}", {"limit": PAGE_SIZE, "offset": offset}, logger)+ # `id` is the primary key of an account record — index it directly so a malformed record+ # fails the sync loudly instead of silently dropping the account's child rows.+ account_ids.extend(item["id"] for item in items)+ if len(items) < PAGE_SIZE:+ break+ offset += len(items)+ return sorted(account_ids)+++def _get_top_level_rows(+ session: requests.Session,+ url: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PhylloResumeConfig],+ resume: PhylloResumeConfig | None,+) -> Iterator[list[dict[str, Any]]]:+ offset = resume.offset if resume else 0++ while True:+ items = _fetch_page(session, url, {"limit": PAGE_SIZE, "offset": offset}, logger)+ if items:+ yield items++ # A short page marks the end of the collection.+ if len(items) < PAGE_SIZE:+ break++ offset += len(items)+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(PhylloResumeConfig(offset=offset))+++def _get_fan_out_rows(+ session: requests.Session,+ base_url: str,+ url: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PhylloResumeConfig],+ resume: PhylloResumeConfig | None,+) -> Iterator[list[dict[str, Any]]]:+ account_ids = _list_account_ids(session, base_url, logger)++ start_index = 0+ offset = 0+ if resume and resume.account_id is not None:+ # Accounts iterate in sorted order, so resume skips straight to the saved account. If it+ # has since been disconnected we continue from the next account after it.+ start_index = bisect_left(account_ids, resume.account_id)+ if start_index < len(account_ids) and account_ids[start_index] == resume.account_id:+ offset = resume.offset++ for index in range(start_index, len(account_ids)):+ account_id = account_ids[index]++ while True:+ items = _fetch_page(session, url, {"account_id": account_id, "limit": PAGE_SIZE, "offset": offset}, logger)+ if items:+ yield items++ if len(items) < PAGE_SIZE:+ break++ offset += len(items)+ resumable_source_manager.save_state(PhylloResumeConfig(offset=offset, account_id=account_id))++ offset = 0+ if index + 1 < len(account_ids):+ # Advance the checkpoint past the completed account so a crash before the next+ # account's first save doesn't replay the account we just finished.+ resumable_source_manager.save_state(PhylloResumeConfig(offset=0, account_id=account_ids[index + 1]))+++def get_rows(+ client_id: str,+ client_secret: str,+ environment: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PhylloResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = PHYLLO_ENDPOINTS[endpoint]+ base_url = get_base_url(environment)+ session = make_tracked_session(headers=_headers(client_id, client_secret), redact_values=(client_secret,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume:+ logger.debug(f"Phyllo: resuming {endpoint} from account_id={resume.account_id}, offset={resume.offset}")++ url = f"{base_url}{config.path}"+ if config.fan_out_by_account:+ yield from _get_fan_out_rows(session, base_url, url, logger, resumable_source_manager, resume)+ else:+ yield from _get_top_level_rows(session, url, logger, resumable_source_manager, resume)+++def phyllo_source(+ client_id: str,+ client_secret: str,+ environment: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PhylloResumeConfig],+) -> SourceResponse:+ config = PHYLLO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ client_id=client_id,+ client_secret=client_secret,+ environment=environment,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(+ client_id: str, client_secret: str, environment: str, path: str = DEFAULT_PROBE_PATH+) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the client ID/secret pair.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(client_id, client_secret), redact_values=(client_secret,))+ try:+ response = session.get(f"{get_base_url(environment)}{path}", params={"limit": 1, "offset": 0}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Phyllo: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Phyllo returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(client_id: str, client_secret: str, environment: str) -> tuple[bool, str | None]:+ status, message = check_access(client_id, client_secret, environment)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Phyllo client ID or secret for the selected environment"+ return False, message or "Could not validate Phyllo credentials"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/settings.pynew file mode 100644index 000000000000..09c81c32bbd0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/settings.py@@ -0,0 +1,36 @@+from dataclasses import dataclass, field+++@dataclass+class PhylloEndpointConfig:+ name: str+ path: str+ # Endpoints keyed off a linked creator account require an `account_id` query param, so we fan+ # out over the accounts listing and pull each account's rows in turn.+ fan_out_by_account: bool = False+ # Phyllo object identifiers are platform-generated UUIDs unique across the system (a content+ # item, transaction, or payout belongs to exactly one account), so `id` is a safe table-wide key.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# Phyllo v1 REST list endpoints (https://docs.getphyllo.com). All are full refresh only: the+# content and income endpoints document from_date/to_date filters, but we could not verify that+# they are honored server-side (and no endpoint documents an updated-after cursor), so we+# conservatively re-pull each stream every sync (see the implementing-warehouse-sources skill).+PHYLLO_ENDPOINTS: dict[str, PhylloEndpointConfig] = {+ "work_platforms": PhylloEndpointConfig(name="work_platforms", path="/v1/work-platforms"),+ "users": PhylloEndpointConfig(name="users", path="/v1/users"),+ "accounts": PhylloEndpointConfig(name="accounts", path="/v1/accounts"),+ "profiles": PhylloEndpointConfig(name="profiles", path="/v1/profiles"),+ "social_contents": PhylloEndpointConfig(+ name="social_contents", path="/v1/social/contents", fan_out_by_account=True+ ),+ "income_transactions": PhylloEndpointConfig(+ name="income_transactions", path="/v1/income/transactions", fan_out_by_account=True+ ),+ "income_payouts": PhylloEndpointConfig(name="income_payouts", path="/v1/income/payouts", fan_out_by_account=True),+}++ENDPOINTS = tuple(PHYLLO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/source.pyindex 5d057d58d808..936206e21eec 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/source.py@@ -1,19 +1,41 @@-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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PhylloSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.phyllo.phyllo import (+ PhylloResumeConfig,+ phyllo_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.phyllo.settings import ENDPOINTS, PHYLLO_ENDPOINTSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PhylloSource(SimpleSource[PhylloSourceConfig]):+class PhylloSource(ResumableSource[PhylloSourceConfig, PhylloResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PHYLLO@@ -22,9 +44,113 @@ class PhylloSource(SimpleSource[PhylloSourceConfig]):def get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.PHYLLO,- category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,+ category=DataWarehouseSourceCategory.ANALYTICS,label="Phyllo",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Phyllo API credentials to pull creator accounts, profiles, content, and income data into the PostHog Data warehouse.++You can find your client ID and secret in the [Phyllo developer dashboard](https://dashboard.getphyllo.com) under **API credentials**. Credentials are environment-specific — sandbox credentials only authenticate against the sandbox environment.+""",iconPath="/static/services/phyllo.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/phyllo",+ keywords=["creator", "getphyllo"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="environment",+ label="Environment",+ required=True,+ defaultValue="production",+ options=[+ SourceFieldSelectConfigOption(label="Production", value="production"),+ SourceFieldSelectConfigOption(label="Sandbox", value="sandbox"),+ ],+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.phyllo.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ message = "Your Phyllo client ID or secret is invalid for the selected environment. Check the credentials in the Phyllo developer dashboard, then reconnect."+ return {+ "401 Client Error: Unauthorized for url: https://api.getphyllo.com": message,+ "401 Client Error: Unauthorized for url: https://api.sandbox.getphyllo.com": message,+ "403 Client Error: Forbidden for url: https://api.getphyllo.com": message,+ "403 Client Error: Forbidden for url: https://api.sandbox.getphyllo.com": message,+ }++ def get_schemas(+ self,+ config: PhylloSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — see the note in settings.py on the unverified+ # from_date/to_date filters.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: PhylloSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # Credentials are environment-wide, so a single probe validates access to every schema.+ return validate_credentials(config.client_id, config.client_secret, config.environment)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PhylloResumeConfig]:+ return ResumableSourceManager[PhylloResumeConfig](inputs, PhylloResumeConfig)++ def source_for_pipeline(+ self,+ config: PhylloSourceConfig,+ resumable_source_manager: ResumableSourceManager[PhylloResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in PHYLLO_ENDPOINTS:+ raise ValueError(f"Unknown Phyllo schema '{inputs.schema_name}'")++ return phyllo_source(+ client_id=config.client_id,+ client_secret=config.client_secret,+ environment=config.environment,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/tests/test_phyllo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/tests/test_phyllo.pynew file mode 100644index 000000000000..9ecd4f97c799--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/tests/test_phyllo.py@@ -0,0 +1,323 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.phyllo import phyllo+from products.warehouse_sources.backend.temporal.data_imports.sources.phyllo.phyllo import (+ PAGE_SIZE,+ PhylloResumeConfig,+ PhylloRetryableError,+ check_access,+ get_base_url,+ get_rows,+ phyllo_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.phyllo.settings import ENDPOINTS, PHYLLO_ENDPOINTS++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = phyllo._fetch_page.__wrapped__ # type: ignore[attr-defined]++PROD_URL = "https://api.getphyllo.com"+++class _FakeResumableManager:+ def __init__(self, state: PhylloResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[PhylloResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> PhylloResumeConfig | None:+ return self._state++ def save_state(self, data: PhylloResumeConfig) -> None:+ self.saved.append(data)+++def _page_of(count: int, prefix: str) -> list[dict]:+ return [{"id": f"{prefix}{i}"} for i in range(count)]+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[tuple[str, str | None, int], list[dict]],+ endpoint: str,+ ) -> list[dict]:+ def fake_fetch(session: Any, url: str, params: dict[str, Any], logger: Any) -> list[dict]:+ return pages[(url, params.get("account_id"), params["offset"])]++ monkeypatch.setattr(phyllo, "_fetch_page", fake_fetch)+ monkeypatch.setattr(phyllo, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ client_id="cid",+ client_secret="cs",+ environment="production",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_short_page_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ url = f"{PROD_URL}/v1/users"+ rows = self._collect(manager, monkeypatch, {(url, None, 0): [{"id": "a"}, {"id": "b"}]}, "users")+ assert rows == [{"id": "a"}, {"id": "b"}]+ # A short page ends the sync without persisting resume state.+ assert manager.saved == []++ def test_advances_offset_until_short_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ url = f"{PROD_URL}/v1/users"+ first = _page_of(PAGE_SIZE, "a")+ pages: dict[tuple[str, str | None, int], list[dict]] = {+ (url, None, 0): first,+ (url, None, PAGE_SIZE): [{"id": "z"}],+ }+ rows = self._collect(manager, monkeypatch, pages, "users")+ assert rows == [*first, {"id": "z"}]+ # State is saved once — after the full first page, pointing at the next offset — then we stop.+ assert [s.offset for s in manager.saved] == [PAGE_SIZE]+ assert manager.saved[0].account_id is None++ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(PhylloResumeConfig(offset=PAGE_SIZE))+ url = f"{PROD_URL}/v1/users"+ # Offset 0 must never be fetched on resume.+ pages: dict[tuple[str, str | None, int], list[dict]] = {(url, None, PAGE_SIZE): [{"id": "z"}]}+ rows = self._collect(manager, monkeypatch, pages, "users")+ assert rows == [{"id": "z"}]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ url = f"{PROD_URL}/v1/users"+ rows = self._collect(manager, monkeypatch, {(url, None, 0): []}, "users")+ assert rows == []+ assert manager.saved == []+++class TestFanOutRows:+ ACCOUNTS_URL = f"{PROD_URL}/v1/accounts"+ CONTENTS_URL = f"{PROD_URL}/v1/social/contents"++ def _accounts_page(self, ids: list[str]) -> list[dict]:+ return [{"id": account_id} for account_id in ids]++ def test_iterates_accounts_in_sorted_order(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ (self.ACCOUNTS_URL, None, 0): self._accounts_page(["acc_b", "acc_a"]),+ (self.CONTENTS_URL, "acc_a", 0): [{"id": "c1"}],+ (self.CONTENTS_URL, "acc_b", 0): [{"id": "c2"}],+ }+ rows = TestGetRows._collect(manager, monkeypatch, pages, "social_contents")+ # Accounts are fetched in sorted order regardless of API listing order.+ assert rows == [{"id": "c1"}, {"id": "c2"}]+ # Finishing acc_a checkpoints past it so a crash doesn't replay it.+ assert [(s.account_id, s.offset) for s in manager.saved] == [("acc_b", 0)]++ def test_saves_state_after_each_full_page_within_account(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ full = _page_of(PAGE_SIZE, "c")+ pages = {+ (self.ACCOUNTS_URL, None, 0): self._accounts_page(["acc_a"]),+ (self.CONTENTS_URL, "acc_a", 0): full,+ (self.CONTENTS_URL, "acc_a", PAGE_SIZE): [{"id": "last"}],+ }+ rows = TestGetRows._collect(manager, monkeypatch, pages, "social_contents")+ assert rows == [*full, {"id": "last"}]+ assert [(s.account_id, s.offset) for s in manager.saved] == [("acc_a", PAGE_SIZE)]++ def test_resumes_mid_account_and_skips_earlier_accounts(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(PhylloResumeConfig(offset=PAGE_SIZE, account_id="acc_b"))+ pages = {+ (self.ACCOUNTS_URL, None, 0): self._accounts_page(["acc_a", "acc_b", "acc_c"]),+ # acc_a must be skipped entirely; acc_b starts at the saved offset.+ (self.CONTENTS_URL, "acc_b", PAGE_SIZE): [{"id": "b2"}],+ (self.CONTENTS_URL, "acc_c", 0): [{"id": "c1"}],+ }+ rows = TestGetRows._collect(manager, monkeypatch, pages, "social_contents")+ assert rows == [{"id": "b2"}, {"id": "c1"}]++ def test_resume_with_disconnected_account_continues_from_next(self, monkeypatch: Any) -> None:+ # The saved account was disconnected between runs; the saved offset must not leak into the+ # next account's pagination.+ manager = _FakeResumableManager(PhylloResumeConfig(offset=PAGE_SIZE, account_id="acc_b"))+ pages = {+ (self.ACCOUNTS_URL, None, 0): self._accounts_page(["acc_a", "acc_c"]),+ (self.CONTENTS_URL, "acc_c", 0): [{"id": "c1"}],+ }+ rows = TestGetRows._collect(manager, monkeypatch, pages, "social_contents")+ assert rows == [{"id": "c1"}]++ def test_paginates_accounts_listing_itself(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ first_accounts = self._accounts_page([f"acc_{i:03d}" for i in range(PAGE_SIZE)])+ pages: dict[tuple[str, str | None, int], list[dict]] = {+ (self.ACCOUNTS_URL, None, 0): first_accounts,+ (self.ACCOUNTS_URL, None, PAGE_SIZE): self._accounts_page(["acc_zzz"]),+ }+ for account in [*first_accounts, {"id": "acc_zzz"}]:+ pages[(self.CONTENTS_URL, account["id"], 0)] = [{"id": f"content_{account['id']}"}]+ rows = TestGetRows._collect(manager, monkeypatch, pages, "social_contents")+ assert len(rows) == PAGE_SIZE + 1+++class TestFetchPage:+ def _session_returning(+ self, status_code: int, body: Any = None, headers: dict[str, str] | None = None+ ) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else {"data": [], "metadata": {}}+ response.text = ""+ response.headers = headers or {}+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(PhylloRetryableError):+ _fetch_page_unwrapped(session, f"{PROD_URL}/v1/users", {"limit": PAGE_SIZE, "offset": 0}, MagicMock())++ def test_rate_limit_honors_retry_after_header(self) -> None:+ session = self._session_returning(429, headers={"Retry-After": "2"})+ with patch.object(phyllo.time, "sleep") as mock_sleep:+ with pytest.raises(PhylloRetryableError):+ _fetch_page_unwrapped(session, f"{PROD_URL}/v1/users", {"limit": PAGE_SIZE, "offset": 0}, MagicMock())+ mock_sleep.assert_called_once_with(2.0)++ @parameterized.expand([("missing", None), ("malformed", "soon"), ("negative", "-1")])+ def test_unusable_retry_after_skips_sleep(self, _name: str, header_value: str | None) -> None:+ headers = {"Retry-After": header_value} if header_value is not None else {}+ session = self._session_returning(429, headers=headers)+ with patch.object(phyllo.time, "sleep") as mock_sleep:+ with pytest.raises(PhylloRetryableError):+ _fetch_page_unwrapped(session, f"{PROD_URL}/v1/users", {"limit": PAGE_SIZE, "offset": 0}, MagicMock())+ mock_sleep.assert_not_called()++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, f"{PROD_URL}/v1/users", {"limit": PAGE_SIZE, "offset": 0}, MagicMock())++ def test_success_returns_data_list(self) -> None:+ body = {"data": [{"id": "a"}], "metadata": {"offset": 0, "limit": 100}}+ session = self._session_returning(200, body)+ rows = _fetch_page_unwrapped(session, f"{PROD_URL}/v1/users", {"limit": PAGE_SIZE, "offset": 0}, MagicMock())+ assert rows == [{"id": "a"}]++ @parameterized.expand([("bare_list", [{"id": "a"}]), ("missing_data", {"metadata": {}})])+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:+ session = self._session_returning(200, body)+ with pytest.raises(PhylloRetryableError):+ _fetch_page_unwrapped(session, f"{PROD_URL}/v1/users", {"limit": PAGE_SIZE, "offset": 0}, MagicMock())+++class TestCheckAccess:+ def _session(self, response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "Phyllo returned HTTP 500"),+ ]+ )+ def test_status_mapping(+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ with patch.object(phyllo, "make_tracked_session", return_value=self._session(response)):+ assert check_access("cid", "cs", "production") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self) -> None:+ session = self._session(requests.ConnectionError("boom"))+ with patch.object(phyllo, "make_tracked_session", return_value=session):+ status, message = check_access("cid", "cs", "production")+ assert status == 0+ assert message is not None and "boom" in message++ def test_sandbox_environment_probes_sandbox_host(self) -> None:+ response = MagicMock()+ response.status_code = 200+ response.ok = True+ session = self._session(response)+ with patch.object(phyllo, "make_tracked_session", return_value=session):+ check_access("cid", "cs", "sandbox")+ assert session.get.call_args.args[0].startswith("https://api.sandbox.getphyllo.com")++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Phyllo client ID or secret for the selected environment"),+ ("forbidden", 403, False, "Invalid Phyllo client ID or secret for the selected environment"),+ ("server_error", 500, False, "Phyllo returned HTTP 500"),+ ]+ )+ def test_validate_credentials(+ self, _name: str, status: int, expected_valid: bool, expected_message: str | None+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ with patch.object(phyllo, "make_tracked_session", return_value=self._session(response)):+ assert validate_credentials("cid", "cs", "production") == (expected_valid, expected_message)+++class TestPhylloSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = phyllo_source(+ client_id="cid",+ client_secret="cs",+ environment="production",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # Phyllo doesn't guarantee ordering or a stable creation timestamp on every object, so we+ # don't partition.+ assert response.partition_mode is None++ def test_fan_out_endpoints_are_account_scoped(self) -> None:+ # These endpoints require an account_id query param; a config regression here would 400 on+ # every page.+ fan_out = {name for name, config in PHYLLO_ENDPOINTS.items() if config.fan_out_by_account}+ assert fan_out == {"social_contents", "income_transactions", "income_payouts"}++ @parameterized.expand(+ [("production", "https://api.getphyllo.com"), ("sandbox", "https://api.sandbox.getphyllo.com")]+ )+ def test_get_base_url(self, environment: str, expected: str) -> None:+ assert get_base_url(environment) == expecteddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/tests/test_phyllo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/tests/test_phyllo_source.pynew file mode 100644index 000000000000..263faab7e68f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/phyllo/tests/test_phyllo_source.py@@ -0,0 +1,129 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++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 PhylloSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.phyllo.phyllo import PhylloResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.phyllo.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.phyllo.source import PhylloSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestPhylloSource:+ def setup_method(self) -> None:+ self.source = PhylloSource()+ self.team_id = 123+ self.config = PhylloSourceConfig(client_id="cid", client_secret="cs-secret", environment="production")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.PHYLLO++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Phyllo"+ assert config.label == "Phyllo"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/phyllo"++ field_names = [f.name for f in config.fields]+ assert field_names == ["client_id", "client_secret", "environment"]++ def test_client_secret_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "client_secret")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_environment_select_defaults_to_production(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig) and f.name == "environment")+ assert field.defaultValue == "production"+ assert {o.value for o in field.options} == {"production", "sandbox"}++ def test_no_connection_host_fields(self) -> None:+ # The environment select only chooses between two Phyllo-controlled hosts, so an editor+ # can't retarget the preserved secret at a server they control.+ assert self.source.connection_host_fields == []++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["accounts"])+ assert len(schemas) == 1+ assert schemas[0].name == "accounts"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.getphyllo.com/v1/users?limit=100&offset=0",),+ ("401 Client Error: Unauthorized for url: https://api.sandbox.getphyllo.com/v1/accounts",),+ ("403 Client Error: Forbidden for url: https://api.getphyllo.com/v1/social/contents",),+ ("403 Client Error: Forbidden for url: https://api.sandbox.getphyllo.com/v1/income/payouts",),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("500 Server Error: Internal Server Error for url: https://api.getphyllo.com/v1/users",),+ ("429 Client Error: Too Many Requests for url: https://api.getphyllo.com/v1/social/contents",),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.phyllo.source.validate_credentials")+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:+ # The source method forwards the credentials and environment to the shared validator and+ # returns its result verbatim.+ mock_validate.return_value = (False, "Invalid Phyllo client ID or secret for the selected environment")+ result = self.source.validate_credentials(self.config, self.team_id)+ assert result == (False, "Invalid Phyllo client ID or secret for the selected environment")+ mock_validate.assert_called_once_with("cid", "cs-secret", "production")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PhylloResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.phyllo.source.phyllo_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "social_contents"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["client_id"] == "cid"+ assert kwargs["client_secret"] == "cs-secret"+ assert kwargs["environment"] == "production"+ assert kwargs["endpoint"] == "social_contents"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Phyllo schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)