Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement plaid import source (#62946)

Tom Owers2aea3d0bd1c6
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 4aafa5b14961..49636d19fdd0 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -131,6 +131,7 @@ the row lists both.
| pipedrive | HTTP | requests | ✅ |
| plain | HTTP | requests | ✅ |
| polar | HTTP | requests | ✅ |
+| plaid | HTTP | requests | ✅ |
| postgres | DB protocol | psycopg | ➖ |
| postmark | HTTP | requests | ✅ |
| productboard | HTTP | requests | ✅ |
@@ -280,7 +281,6 @@ doesn't conflict with concurrent PRs.
- paylocity
- paypal
- pendo
-- plaid
- planetscale
- qualtrics
- quickbooks
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 8c1e64b3afb3..f0b30c59e8be 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -1015,7 +1015,10 @@ class PipedriveSourceConfig(config.Config):
@config.config
class PlaidSourceConfig(config.Config):
- pass
+ client_id: str
+ secret: str
+ access_token: str
+ environment: Literal["production", "sandbox"] = config.value(default="production")
@config.config
diff --git a/posthog/temporal/data_imports/sources/plaid/plaid.py b/posthog/temporal/data_imports/sources/plaid/plaid.py
new file mode 100644
index 000000000000..4254b96750e8
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/plaid/plaid.py
@@ -0,0 +1,194 @@
+import time
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+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 posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.plaid.settings import PLAID_ENDPOINTS
+
+PLAID_HOSTS = {
+ "production": "https://production.plaid.com",
+ "sandbox": "https://sandbox.plaid.com",
+}
+# /transactions/get pages cap at 500.
+PAGE_SIZE = 500
+# Plaid has no data before this; full transaction pulls start here.
+DEFAULT_START_DATE = "2000-01-01"
+# /transactions/get is limited to 30 req/min per Item — space requests out.
+REQUEST_INTERVAL_SECONDS = 2.1
+REQUEST_TIMEOUT_SECONDS = 120
+MAX_RETRY_ATTEMPTS = 5
+
+
+class PlaidRetryableError(Exception):
+ pass
+
+
+class PlaidResumeConfig:
+ # /transactions/get paginates with options.offset; static body parts are
+ # rebuilt deterministically from job inputs on resume.
+ offset: int
+
+
+def _get_session(secret: str, access_token: str) -> requests.Session:
+ return make_tracked_session(redact_values=(secret, access_token))
+
+
+def _base_url(environment: str) -> str:
+ host = PLAID_HOSTS.get(environment)
+ if host is None:
+ raise ValueError(f"Invalid Plaid environment: {environment}")
+ return host
+
+
+def _format_date(value: Any) -> str:
+ """Format an incremental cursor for Plaid's start_date filter (YYYY-MM-DD)."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%d")
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%d")
+ return str(value)[:10]
+
+
+def _today() -> str:
+ return datetime.now(UTC).strftime("%Y-%m-%d")
+
+
+def validate_credentials(environment: str, client_id: str, secret: str, access_token: str) -> bool:
+ """Confirm the credential triple is valid with a cheap /item/get probe."""
+ try:
+ response = _get_session(secret, access_token).post(
+ f"{_base_url(environment)}/item/get",
+ json={"client_id": client_id, "secret": secret, "access_token": access_token},
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ environment: str,
+ client_id: str,
+ secret: str,
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PlaidResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ session = _get_session(secret, access_token)
+ base_url = _base_url(environment)
+ credentials = {"client_id": client_id, "secret": secret, "access_token": access_token}
+
+ @retry(
+ retry=retry_if_exception_type((PlaidRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=5, max=120),
+ reraise=True,
+ )
+ def post(path: str, body: dict[str, Any]) -> dict[str, Any]:
+ # Stay under the 30 req/min per-Item budget.
+ time.sleep(REQUEST_INTERVAL_SECONDS)
+ url = f"{base_url}{path}"
+ response = session.post(url, json={**credentials, **body}, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise PlaidRetryableError(f"Plaid API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Plaid API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ if endpoint == "accounts":
+ data = post("/accounts/get", {})
+ items = data.get("accounts", []) or []
+ if items:
+ yield items
+ return
+
+ # transactions
+ start_date = (
+ _format_date(db_incremental_field_last_value)
+ if should_use_incremental_field and db_incremental_field_last_value is not None
+ else DEFAULT_START_DATE
+ )
+ end_date = _today()
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume_config.offset if resume_config is not None else 0
+ if resume_config is not None:
+ logger.debug(f"Plaid: resuming transactions from offset {offset}")
+
+ while True:
+ data = post(
+ "/transactions/get",
+ {
+ "start_date": start_date,
+ "end_date": end_date,
+ "options": {"count": PAGE_SIZE, "offset": offset},
+ },
+ )
+ items = data.get("transactions", []) or []
+
+ if items:
+ yield items
+
+ total = data.get("total_transactions")
+ offset += len(items)
+ if not items or (isinstance(total, int) and offset >= total):
+ break
+
+ # Save state AFTER yielding the page so a crash re-yields the last page
+ # (merge dedupes on primary key) rather than skipping it.
+ resumable_source_manager.save_state(PlaidResumeConfig(offset=offset))
+
+
+def plaid_source(
+ environment: str,
+ client_id: str,
+ secret: str,
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PlaidResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = PLAID_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ environment=environment,
+ client_id=client_id,
+ secret=secret,
+ access_token=access_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=[config.primary_key],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint == "transactions" else None,
+ partition_format="month" if endpoint == "transactions" else None,
+ partition_keys=["date"] if endpoint == "transactions" else None,
+ # /transactions/get returns newest-first; the pipeline commits desc
+ # watermarks only when a run completes.
+ sort_mode="desc" if endpoint == "transactions" else "asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/plaid/settings.py b/posthog/temporal/data_imports/sources/plaid/settings.py
new file mode 100644
index 000000000000..2085ac70f757
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/plaid/settings.py
@@ -0,0 +1,40 @@
+from dataclasses import dataclass, field
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class PlaidEndpointConfig:
+ name: str
+ primary_key: str
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+
+# One PostHog source connects one Plaid Item (the access token the user
+# obtained via Plaid Link). Transactions use /transactions/get with the
+# server-side start_date filter — /transactions/sync's opaque cursor can't be
+# expressed as a row-field watermark in this framework.
+PLAID_ENDPOINTS: dict[str, PlaidEndpointConfig] = {
+ "accounts": PlaidEndpointConfig(
+ name="accounts",
+ primary_key="account_id",
+ ),
+ "transactions": PlaidEndpointConfig(
+ name="transactions",
+ primary_key="transaction_id",
+ incremental_fields=[
+ {
+ "label": "date",
+ "type": IncrementalFieldType.Date,
+ "field": "date",
+ "field_type": IncrementalFieldType.Date,
+ },
+ ],
+ ),
+}
+
+ENDPOINTS = tuple(PLAID_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in PLAID_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/posthog/temporal/data_imports/sources/plaid/source.py b/posthog/temporal/data_imports/sources/plaid/source.py
index d67bc9a24be2..62b1b4f39086 100644
--- a/posthog/temporal/data_imports/sources/plaid/source.py
+++ b/posthog/temporal/data_imports/sources/plaid/source.py
@@ -1,29 +1,148 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import PlaidSourceConfig
+from posthog.temporal.data_imports.sources.plaid.plaid import (
+ PlaidResumeConfig,
+ plaid_source,
+ validate_credentials as validate_plaid_credentials,
+)
+from posthog.temporal.data_imports.sources.plaid.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PlaidSource(SimpleSource[PlaidSourceConfig]):
+class PlaidSource(ResumableSource[PlaidSourceConfig, PlaidResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.PLAID
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://production.plaid.com": "Plaid authentication failed. Please check your client ID, secret, and access token.",
+ "401 Client Error: Unauthorized for url: https://sandbox.plaid.com": "Plaid authentication failed. Please check your client ID, secret, and access token (and that they match the selected environment).",
+ "400 Client Error: Bad Request for url: https://production.plaid.com": "Plaid rejected the request. Your access token may be invalid, expired, or for a different environment, or the request may have been rejected for another reason (e.g. the product isn't enabled on your plan or the Item needs re-linking).",
+ "400 Client Error: Bad Request for url: https://sandbox.plaid.com": "Plaid rejected the request. Your access token may be invalid, expired, or for a different environment, or the request may have been rejected for another reason (e.g. the product isn't enabled on your plan or the Item needs re-linking).",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.PLAID,
label="Plaid",
+ caption="""Connect a Plaid Item to pull its accounts and transactions into the PostHog Data warehouse.
+
+You can find your client ID and secret in the [Plaid dashboard](https://dashboard.plaid.com/developers/keys). The access token identifies one linked Item (institution connection), obtained when a user completes Plaid Link — add one source per Item.""",
iconPath="/static/services/plaid.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/plaid",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="environment",
+ label="Environment",
+ required=True,
+ defaultValue="production",
+ options=[
+ SourceFieldSelectConfigOption(label="Production", value="production"),
+ SourceFieldSelectConfigOption(label="Sandbox", value="sandbox"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="client_id",
+ label="Client ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="secret",
+ label="Secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="access-production-...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: PlaidSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: PlaidSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_plaid_credentials(config.environment, config.client_id, config.secret, config.access_token):
+ return True, None
+
+ return False, "Invalid Plaid credentials"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PlaidResumeConfig]:
+ return ResumableSourceManager[PlaidResumeConfig](inputs, PlaidResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: PlaidSourceConfig,
+ resumable_source_manager: ResumableSourceManager[PlaidResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return plaid_source(
+ environment=config.environment,
+ client_id=config.client_id,
+ secret=config.secret,
+ access_token=config.access_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/posthog/temporal/data_imports/sources/plaid/tests/test_plaid.py b/posthog/temporal/data_imports/sources/plaid/tests/test_plaid.py
new file mode 100644
index 000000000000..bf3a5290a832
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/plaid/tests/test_plaid.py
@@ -0,0 +1,209 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.plaid.plaid import (
+ DEFAULT_START_DATE,
+ PAGE_SIZE,
+ PlaidResumeConfig,
+ _base_url,
+ _format_date,
+ get_rows,
+ plaid_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.plaid.settings import ENDPOINTS, PLAID_ENDPOINTS
+
+_MODULE = "posthog.temporal.data_imports.sources.plaid.plaid"
+
+
+def _make_manager(resume_state: PlaidResumeConfig | 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 _response(body: dict[str, Any], status: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = body
+ resp.status_code = status
+ resp.ok = status < 400
+ return resp
+
+
[email protected](autouse=True)
+def _no_sleep():
+ with mock.patch(f"{_MODULE}.time.sleep"):
+ yield
+
+
+class TestBaseUrl:
+ @pytest.mark.parametrize(
+ "environment, expected",
+ [
+ ("production", "https://production.plaid.com"),
+ ("sandbox", "https://sandbox.plaid.com"),
+ ],
+ )
+ def test_known_environments_return_correct_host(self, environment, expected):
+ assert _base_url(environment) == expected
+
+ def test_invalid_environment_raises(self):
+ with pytest.raises(ValueError):
+ _base_url("evil")
+
+
+class TestFormatDate:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02"),
+ (date(2024, 1, 2), "2024-01-02"),
+ ("2024-01-02", "2024-01-02"),
+ ("2024-01-02T03:04:05Z", "2024-01-02"),
+ ],
+ )
+ def test_format_values(self, value, expected):
+ assert _format_date(value) == expected
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ (400, False),
+ (401, False),
+ ],
+ )
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):
+ mock_session.return_value.post.return_value = _response({}, status=status_code)
+
+ assert validate_credentials("production", "cid", "sec", "tok") is expected
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_validate_posts_credentials_to_item_get(self, mock_session):
+ mock_session.return_value.post.return_value = _response({})
+
+ validate_credentials("production", "cid", "sec", "tok")
+
+ call = mock_session.return_value.post.call_args
+ assert call.args[0] == "https://production.plaid.com/item/get"
+ assert call.kwargs["json"] == {"client_id": "cid", "secret": "sec", "access_token": "tok"}
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_validate_credentials_swallows_exceptions(self, mock_session):
+ mock_session.return_value.post.side_effect = Exception("boom")
+ assert validate_credentials("production", "cid", "sec", "tok") is False
+
+
+class TestGetRowsAccounts:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_accounts_single_fetch(self, mock_session):
+ mock_session.return_value.post.return_value = _response({"accounts": [{"account_id": "a1"}]})
+
+ manager = _make_manager()
+ batches = list(get_rows("production", "cid", "sec", "tok", "accounts", mock.MagicMock(), manager))
+
+ assert batches == [[{"account_id": "a1"}]]
+ call = mock_session.return_value.post.call_args
+ assert call.args[0].endswith("/accounts/get")
+
+
+class TestGetRowsTransactions:
+ @mock.patch(f"{_MODULE}._today")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_paginates_via_offset_until_total(self, mock_session, mock_today):
+ mock_today.return_value = "2024-06-01"
+ full_page = [{"transaction_id": str(i), "date": "2024-01-01"} for i in range(PAGE_SIZE)]
+ mock_session.return_value.post.side_effect = [
+ _response({"transactions": full_page, "total_transactions": PAGE_SIZE + 1}),
+ _response(
+ {
+ "transactions": [{"transaction_id": "last", "date": "2024-01-02"}],
+ "total_transactions": PAGE_SIZE + 1,
+ }
+ ),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("production", "cid", "sec", "tok", "transactions", mock.MagicMock(), manager))
+
+ assert len(batches) == 2
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0].offset == PAGE_SIZE
+ bodies = [call.kwargs["json"] for call in mock_session.return_value.post.call_args_list]
+ assert bodies[0]["options"] == {"count": PAGE_SIZE, "offset": 0}
+ assert bodies[1]["options"] == {"count": PAGE_SIZE, "offset": PAGE_SIZE}
+ assert bodies[0]["start_date"] == DEFAULT_START_DATE
+ assert bodies[0]["end_date"] == "2024-06-01"
+
+ @mock.patch(f"{_MODULE}._today")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_incremental_uses_watermark_as_start_date(self, mock_session, mock_today):
+ mock_today.return_value = "2024-06-01"
+ mock_session.return_value.post.return_value = _response({"transactions": [], "total_transactions": 0})
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "production",
+ "cid",
+ "sec",
+ "tok",
+ "transactions",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2024, 5, 1),
+ )
+ )
+
+ body = mock_session.return_value.post.call_args.kwargs["json"]
+ assert body["start_date"] == "2024-05-01"
+
+ @mock.patch(f"{_MODULE}._today")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resumes_from_saved_offset(self, mock_session, mock_today):
+ mock_today.return_value = "2024-06-01"
+ mock_session.return_value.post.return_value = _response({"transactions": [], "total_transactions": 0})
+
+ manager = _make_manager(PlaidResumeConfig(offset=1500))
+ list(get_rows("production", "cid", "sec", "tok", "transactions", mock.MagicMock(), manager))
+
+ body = mock_session.return_value.post.call_args.kwargs["json"]
+ assert body["options"]["offset"] == 1500
+
+ @mock.patch(f"{_MODULE}._today")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_empty_response_stops_without_saving_state(self, mock_session, mock_today):
+ mock_today.return_value = "2024-06-01"
+ mock_session.return_value.post.return_value = _response({"transactions": [], "total_transactions": 0})
+
+ manager = _make_manager()
+ batches = list(get_rows("production", "cid", "sec", "tok", "transactions", mock.MagicMock(), manager))
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+
+class TestPlaidSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = PLAID_ENDPOINTS[endpoint]
+ response = plaid_source("production", "cid", "sec", "tok", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == [config.primary_key]
+ if endpoint == "transactions":
+ # Newest-first ordering — watermark commits only at run end.
+ assert response.sort_mode == "desc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["date"]
+ else:
+ assert response.sort_mode == "asc"
+ assert response.partition_mode is None
diff --git a/posthog/temporal/data_imports/sources/plaid/tests/test_plaid_source.py b/posthog/temporal/data_imports/sources/plaid/tests/test_plaid_source.py
new file mode 100644
index 000000000000..d29336aa5f61
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/plaid/tests/test_plaid_source.py
@@ -0,0 +1,151 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import PlaidSourceConfig
+from posthog.temporal.data_imports.sources.plaid.plaid import PlaidResumeConfig
+from posthog.temporal.data_imports.sources.plaid.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.plaid.source import PlaidSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestPlaidSource:
+ def setup_method(self):
+ self.source = PlaidSource()
+ self.team_id = 123
+ self.config = PlaidSourceConfig(environment="production", client_id="cid", secret="sec", access_token="tok")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.PLAID
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Plaid"
+ assert config.label == "Plaid"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/plaid.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["environment", "client_id", "secret", "access_token"]
+
+ def test_environment_field_is_a_select_with_default(self):
+ config = self.source.get_source_config
+ env_field = next(f for f in config.fields if f.name == "environment")
+ assert isinstance(env_field, SourceFieldSelectConfig)
+ assert env_field.defaultValue == "production"
+ assert {option.value for option in env_field.options} == {"production", "sandbox"}
+
+ @pytest.mark.parametrize("field_name", ["secret", "access_token"])
+ def test_secret_fields_are_secret_passwords(self, field_name):
+ config = self.source.get_source_config
+ secret_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == field_name)
+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD
+ assert secret_field.secret is True
+ assert secret_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://production.plaid.com/transactions/get",
+ "400 Client Error: Bad Request for url: https://sandbox.plaid.com/accounts/get",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://production.plaid.com/transactions/get",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Only transactions have a server-side date filter.
+ assert incremental == {"transactions"}
+
+ def test_incremental_schemas_advertise_their_fields(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["transactions"].incremental_fields == INCREMENTAL_FIELDS["transactions"]
+ assert [f["field"] for f in schemas["transactions"].incremental_fields] == ["date"]
+ assert schemas["accounts"].incremental_fields == []
+ assert schemas["accounts"].supports_append is False
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["transactions"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "transactions"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Plaid credentials"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.plaid.source.validate_plaid_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with("production", "cid", "sec", "tok")
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is PlaidResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.plaid.source.plaid_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_plaid_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "transactions"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-05-01"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_plaid_source.assert_called_once()
+ kwargs = mock_plaid_source.call_args.kwargs
+ assert kwargs["environment"] == "production"
+ assert kwargs["client_id"] == "cid"
+ assert kwargs["secret"] == "sec"
+ assert kwargs["access_token"] == "tok"
+ assert kwargs["endpoint"] == "transactions"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-05-01"
+
+ @mock.patch("posthog.temporal.data_imports.sources.plaid.source.plaid_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_plaid_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "accounts"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-05-01"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_plaid_source.call_args.kwargs["db_incremental_field_last_value"] is None