: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 persona import source (#67835)
Tom Owers1c8d7bf8fe98
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 289f9ace7682..20c4d6b4235c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -245,6 +245,7 @@ the row lists both.| papersign | HTTP | requests | ✅ || paystack | HTTP | requests + `rest_source.RESTClient` | ✅ || pendo | HTTP | requests | ✅ |+| persona | HTTP | requests | ✅ || personio | HTTP | requests | ✅ || pexels | HTTP | requests | ✅ || pingdom | HTTP | requests | ✅ |@@ -577,6 +578,7 @@ doesn't conflict with concurrent PRs.- perk- persistiq- persona+- pexels- phyllo- picqer- pipelinerdiff --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 a0b9f49a5a70..e7999de961e6 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@@ -2440,7 +2440,7 @@ class PersistIqSourceConfig(config.Config):@config.configclass PersonaSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/persona/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/api_inventory.mdnew file mode 100644index 000000000000..70991b04b705--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/api_inventory.md@@ -0,0 +1,37 @@+# Persona API inventory++Reference: <https://docs.withpersona.com/reference> · Base URL: `https://api.withpersona.com/api/v1`++- **Auth:** `Authorization: Bearer <api_key>`. Sandbox and production use separate keys.+- **Format:** JSON:API — each record is `{ "type", "id", "attributes": {...} }`; lists wrap rows in `data`+ with a `links.next` cursor URL (null on the last page).+- **Pagination:** cursor via `page[after]=<object id>`, `page[size]` 1–100 (default 10).+- **Ordering:** reverse-chronological (newest first) on `created-at` → we sync with `sort_mode="desc"`.+- **Incremental:** server-side `filter[created-at-start]` / `filter[created-at-end]` on the immutable+ `created-at`. No `updated-at` filter exists, so only `created_at` is advertised as an incremental cursor+ (updates to existing records are captured on full refresh, not incrementally).+- **Rate limit:** 300 req/min; `429` with reset headers on excess (handled by retry + backoff).++## Endpoints synced++| Endpoint | Path | Sync mode | Primary key | Partition key |+| ------------------- | -------------------- | ------------ | ----------- | ------------- |+| `inquiries` | `/inquiries` | Incremental | `id` | `created_at` |+| `accounts` | `/accounts` | Incremental | `id` | `created_at` |+| `cases` | `/cases` | Incremental | `id` | `created_at` |+| `transactions` | `/transactions` | Incremental | `id` | `created_at` |+| `events` | `/events` | Append only | `id` | `created_at` |+| `inquiry_templates` | `/inquiry-templates` | Full refresh | `id` | — |++Object ids are globally unique and type-prefixed (`inq_`, `acc_`, `case_`, `txn_`, `evt_`, `itmpl_`), so+`id` is a safe standalone primary key. Persona kebab-case attributes (`created-at`) normalize to the+snake_case warehouse columns (`created_at`).++## Verification note++Endpoint paths and semantics are taken from the public Persona docs. They could **not** be curl-verified+against the live API because Persona's auth middleware returns `401` for every request (including bogus+paths) without a valid key, so route existence and the cross-page behavior of `filter[created-at-start]`+were not confirmed empirically. As a safeguard the paginator stops client-side once rows predate the+incremental watermark (newest-first ordering), so even if the created-at filter failed to persist past+page one we would not re-walk full history on every sync.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/persona/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/canonical_descriptions.pynew file mode 100644index 000000000000..77caa355efc2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/canonical_descriptions.py@@ -0,0 +1,74 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Curated from the public Persona API docs (https://docs.withpersona.com/reference). Column names use+# the snake_case form the warehouse stores after normalizing Persona's kebab-case attributes.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "inquiries": {+ "description": "An individual identity verification session a person goes through, tracking its status from creation to approval or decline.",+ "docs_url": "https://docs.withpersona.com/reference/inquiries",+ "columns": {+ "id": "Unique identifier for the inquiry (prefixed `inq_`).",+ "status": "Current state of the inquiry (e.g. created, pending, completed, approved, declined, expired).",+ "reference_id": "Your own identifier for the person, set when the inquiry was created.",+ "created_at": "Timestamp when the inquiry was created.",+ "started_at": "Timestamp when the person began the inquiry flow.",+ "completed_at": "Timestamp when the person completed the inquiry flow.",+ "expired_at": "Timestamp when the inquiry expired, if it did.",+ "name_first": "First name collected or verified during the inquiry.",+ "name_last": "Last name collected or verified during the inquiry.",+ "birthdate": "Date of birth collected or verified during the inquiry.",+ },+ },+ "accounts": {+ "description": "A persistent record of an individual, grouping all of their inquiries, verifications, and other activity over time.",+ "docs_url": "https://docs.withpersona.com/reference/accounts",+ "columns": {+ "id": "Unique identifier for the account (prefixed `acc_`).",+ "reference_id": "Your own identifier associated with this account.",+ "created_at": "Timestamp when the account was created.",+ "updated_at": "Timestamp when the account was last updated.",+ },+ },+ "cases": {+ "description": "A manual review workflow used to investigate and resolve flagged inquiries, accounts, or transactions.",+ "docs_url": "https://docs.withpersona.com/reference/cases",+ "columns": {+ "id": "Unique identifier for the case (prefixed `case_`).",+ "status": "Current state of the case (e.g. open, in progress, resolved).",+ "created_at": "Timestamp when the case was created.",+ "updated_at": "Timestamp when the case was last updated.",+ "resolved_at": "Timestamp when the case was resolved, if it was.",+ },+ },+ "transactions": {+ "description": "A record of a transaction evaluated by Persona, used for transaction monitoring and fraud/AML analysis.",+ "docs_url": "https://docs.withpersona.com/reference/transactions",+ "columns": {+ "id": "Unique identifier for the transaction (prefixed `txn_`).",+ "status": "Current state of the transaction.",+ "created_at": "Timestamp when the transaction was created.",+ "updated_at": "Timestamp when the transaction was last updated.",+ },+ },+ "events": {+ "description": "An append-only audit log of everything that happened in your Persona account (inquiry created, verification passed, case resolved, etc.).",+ "docs_url": "https://docs.withpersona.com/reference/events",+ "columns": {+ "id": "Unique identifier for the event (prefixed `evt_`).",+ "name": "The event type (e.g. inquiry.created, verification.passed).",+ "created_at": "Timestamp when the event occurred.",+ },+ },+ "inquiry_templates": {+ "description": "A reusable configuration that defines the steps, checks, and branding of an inquiry flow.",+ "docs_url": "https://docs.withpersona.com/reference/inquiry-templates",+ "columns": {+ "id": "Unique identifier for the inquiry template (prefixed `itmpl_`).",+ "status": "Whether the template is active or archived.",+ "created_at": "Timestamp when the template was created.",+ "updated_at": "Timestamp when the template was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/persona/persona.py b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/persona.pynew file mode 100644index 000000000000..1a53408e3755--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/persona.py@@ -0,0 +1,250 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional++import requests+from dateutil import parser as date_parser+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.batcher import Batcher+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.persona.settings import (+ PERSONA_ENDPOINTS,+ PersonaEndpointConfig,+)++PERSONA_BASE_URL = "https://api.withpersona.com/api/v1"++# Persona's default rate limit is 300 req/min; it returns 429 with a reset header on excess.+PAGE_SIZE = 100 # Persona caps page[size] at 100 (default 10).+++class PersonaRetryableError(Exception):+ pass+++class PersonaResumeConfig:+ # `page[after]` cursor (the id of the last object we durably yielded). On resume we re-window the+ # request with the same created-at filter and continue from this object. `None` starts at page one.+ after: str | None = None+++def _get_headers(api_key: str) -> dict[str, str]:+ # No `Persona-Version` header is sent: omitting it applies the account's dashboard-configured+ # default API version, which is always valid. Pinning a version we can't test risks a 400 if the+ # value predates a field or is rejected. The attributes we read (`created-at`, `id`) are stable+ # across versions.+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++def _build_url(base_url: str, params: dict[str, Any]) -> str:+ """Build a Persona URL with literal brackets in the query string.++ Persona uses JSON:API-style bracketed params (`page[size]`, `page[after]`,+ `filter[created-at-start]`). Every key and value here is internally constructed from object ids,+ integers, and `Z`-suffixed ISO timestamps — none contain characters that need percent-encoding.+ """+ if not params:+ return base_url+ parts = [f"{key}={value}" for key, value in params.items()]+ return f"{base_url}?{'&'.join(parts)}"+++def _format_datetime_z(dt: datetime) -> str:+ """Format a datetime as RFC 3339 with millisecond precision and a Z suffix (Persona's format)."""+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+++def _to_datetime(value: Any) -> Optional[datetime]:+ """Coerce a stored watermark or a record's `created-at` string to an aware UTC datetime.++ Returns None when the value can't be parsed, so callers skip the comparison rather than crash.+ """+ if value is None:+ return None+ if isinstance(value, datetime):+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ try:+ parsed = date_parser.parse(str(value))+ except (ValueError, OverflowError, TypeError):+ return None+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)+++def _clamp_future_to_now(dt: datetime) -> datetime:+ """Cap a future cursor at now. A future `created-at-start` returns nothing anyway; capping keeps+ the request sensible and avoids ever wedging on a future-dated record."""+ now = datetime.now(UTC)+ return now if dt > now else dt+++def _flatten_item(item: dict[str, Any]) -> dict[str, Any]:+ """Lift the JSON:API `attributes` object into the row root, keeping `id`/`type` at top level.++ Attribute keys stay in Persona's kebab-case (e.g. `created-at`); the pipeline snake-cases column+ names downstream, so `created-at` lands as the `created_at` warehouse column.+ """+ if "attributes" in item and isinstance(item["attributes"], dict):+ attributes = item.pop("attributes")+ item.update(attributes)+ return item+++def validate_credentials(api_key: str) -> int:+ """Probe the cheapest core list endpoint and return the HTTP status (0 on network error).++ Callers map the status: 200 = valid, 401 = bad key, 403 = valid key missing a scope.+ """+ url = _build_url(f"{PERSONA_BASE_URL}/inquiries", {"page[size]": 1})+ try:+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10)+ return response.status_code+ except Exception:+ return 0+++@retry(+ retry=retry_if_exception_type(+ (+ PersonaRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, page_url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict:+ response = session.get(page_url, headers=headers, timeout=60)++ # 429 (rate limit) and 5xx are transient — retry with backoff. Persona sends rate-limit reset+ # headers on 429; exponential jitter is a safe fallback that respects the 300 req/min budget.+ if response.status_code == 429 or response.status_code >= 500:+ raise PersonaRetryableError(f"Persona API error (retryable): status={response.status_code}, url={page_url}")++ if not response.ok:+ logger.error(f"Persona API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()+++def _build_params(config: PersonaEndpointConfig, watermark: Optional[datetime], after: str | None) -> dict[str, Any]:+ params: dict[str, Any] = {"page[size]": PAGE_SIZE}+ if watermark is not None:+ # Server-side incremental window on the immutable created-at timestamp (inclusive start).+ params["filter[created-at-start]"] = _format_datetime_z(watermark)+ if after is not None:+ params["page[after]"] = after+ return params+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PersonaResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[Any]:+ config = PERSONA_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ # One session reused across every page so urllib3 keeps the connection alive.+ session = make_tracked_session()++ use_incremental = should_use_incremental_field and config.supports_incremental+ watermark = _to_datetime(db_incremental_field_last_value) if use_incremental else None+ if watermark is not None:+ watermark = _clamp_future_to_now(watermark)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ after = resume.after if resume else None+ if after is not None:+ logger.debug(f"Persona: resuming {endpoint} from page[after]={after}")++ stop = False+ while not stop:+ url = _build_url(f"{PERSONA_BASE_URL}{config.path}", _build_params(config, watermark, after))+ data = _fetch_page(session, url, headers, logger)++ items = data.get("data", [])+ if not items:+ break++ has_next = bool(data.get("links", {}).get("next"))++ for item in items:+ # Client-side watermark guard. Persona filters server-side, but if a future API change+ # were to drop the created-at window past page one, the newest-first ordering lets us stop+ # as soon as we cross below the watermark instead of re-walking full history every sync.+ if watermark is not None:+ created = _to_datetime(item.get("attributes", {}).get("created-at"))+ if created is not None and created < watermark:+ stop = True+ break++ batcher.batch(_flatten_item(item))++ while batcher.should_yield():+ py_table = batcher.get_table()+ yield py_table+ # Save AFTER yielding so a crash re-yields the last batch (merge dedupes on the+ # primary key) rather than skipping it. Only checkpoint while more pages remain.+ if has_next:+ last_id = py_table.column("id")[-1].as_py()+ resumable_source_manager.save_state(PersonaResumeConfig(after=last_id))++ if stop or not has_next:+ break+ after = items[-1]["id"]++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def persona_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PersonaResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = PERSONA_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ # Persona returns records newest-first; the pipeline defers the watermark advance to end-of-sync+ # for desc sources, and resumption is handled by the saved page[after] cursor.+ sort_mode="desc",+ 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,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/persona/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/settings.pynew file mode 100644index 000000000000..e3439891e850--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/settings.py@@ -0,0 +1,83 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Persona's list endpoints return records newest-first (reverse-chronological on created-at) and are+# paginated with a `page[after]=<object id>` cursor. Incremental endpoints expose a server-side+# `filter[created-at-start]` window on the immutable `created-at` timestamp; there is no `updated-at`+# filter, so the only advertised incremental cursor is `created_at`. Object ids are globally unique+# and type-prefixed (e.g. `inq_...`, `acc_...`), so `id` is a safe standalone primary key.+++def _created_at_incremental_fields() -> list[IncrementalField]:+ # Persona attribute `created-at` normalizes to the `created_at` warehouse column (the pipeline+ # snake-cases identifiers), so both the advertised incremental field and the partition key use it.+ return [+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ]+++@dataclass+class PersonaEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # A stable created-at column to partition on. Kept in the normalized (snake_case) form the+ # pipeline sees after column-name normalization. `None` disables partitioning.+ partition_key: Optional[str] = "created_at"+ # True only when the list endpoint exposes the server-side `filter[created-at-start]` window.+ supports_incremental: bool = True+ # Append-only immutable log (e.g. events) — synced with append semantics, never merged.+ append_only: bool = False+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+++PERSONA_ENDPOINTS: dict[str, PersonaEndpointConfig] = {+ "inquiries": PersonaEndpointConfig(+ name="inquiries",+ path="/inquiries",+ incremental_fields=_created_at_incremental_fields(),+ ),+ "accounts": PersonaEndpointConfig(+ name="accounts",+ path="/accounts",+ incremental_fields=_created_at_incremental_fields(),+ ),+ "cases": PersonaEndpointConfig(+ name="cases",+ path="/cases",+ incremental_fields=_created_at_incremental_fields(),+ ),+ "transactions": PersonaEndpointConfig(+ name="transactions",+ path="/transactions",+ incremental_fields=_created_at_incremental_fields(),+ ),+ "events": PersonaEndpointConfig(+ name="events",+ path="/events",+ incremental_fields=_created_at_incremental_fields(),+ append_only=True,+ ),+ # Inquiry templates are configuration objects (small, low churn). We don't rely on a created-at+ # window here — full refresh keeps the catalog complete and simple.+ "inquiry_templates": PersonaEndpointConfig(+ name="inquiry_templates",+ path="/inquiry-templates",+ supports_incremental=False,+ partition_key=None,+ ),+}++ENDPOINTS = tuple(PERSONA_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in PERSONA_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/persona/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/source.pyindex 0d78ec2008d0..d5a632864032 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/persona/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/source.py@@ -1,19 +1,43 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PersonaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.persona.persona import (+ PersonaResumeConfig,+ persona_source,+ validate_credentials as validate_persona_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.persona.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ PERSONA_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PersonaSource(SimpleSource[PersonaSourceConfig]):+class PersonaSource(ResumableSource[PersonaSourceConfig, PersonaResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PERSONA@@ -24,7 +48,108 @@ class PersonaSource(SimpleSource[PersonaSourceConfig]):name=SchemaExternalDataSourceType.PERSONA,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Persona",- iconPath="/static/services/persona.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Persona API key to automatically pull your Persona data into the PostHog Data warehouse.++Create an API key in your Persona dashboard under **Settings → API Keys**. The key needs read access to the resources you want to sync (inquiries, accounts, cases, transactions, events).++Sandbox and production environments use separate API keys — use the one for the environment whose data you want to import.+""",+ iconPath="/static/services/persona.png",+ docsUrl="https://posthog.com/docs/cdp/sources/persona",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="persona_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.persona.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A revoked or invalid key surfaces as an HTTPError when `_fetch_page` raises for status.+ # Retrying can't fix a credential problem, so fail the sync. Match the stable status text+ # and base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://api.withpersona.com": "Your Persona API key is invalid or has been revoked. Create a new API key in your Persona dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.withpersona.com": "Your Persona API key is missing the read permissions needed to sync this data. Grant the required access in your Persona dashboard, then reconnect.",+ }++ def get_schemas(+ self,+ config: PersonaSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = PERSONA_ENDPOINTS[endpoint]+ has_incremental = endpoint_config.supports_incremental and bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ # Events are an immutable audit log — append-only, never merged.+ supports_incremental=has_incremental and not endpoint_config.append_only,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: PersonaSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ status = validate_persona_credentials(config.api_key)+ if status == 200:+ return True, None+ if status == 401:+ return False, "Invalid Persona API key"+ # A 403 means the key is genuine but lacks a scope. At source-create (schema_name is None) we+ # accept it — the user may only intend to grant scopes for the tables they sync. Per-table+ # scope problems surface later as non-retryable sync errors.+ if status == 403:+ if schema_name is None:+ return True, None+ return False, "Your Persona API key is missing permissions for this resource"+ if status == 0:+ return False, "Could not reach Persona to validate your API key. Please try again."+ return False, f"Could not validate Persona credentials (HTTP {status})"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PersonaResumeConfig]:+ return ResumableSourceManager[PersonaResumeConfig](inputs, PersonaResumeConfig)++ def source_for_pipeline(+ self,+ config: PersonaSourceConfig,+ resumable_source_manager: ResumableSourceManager[PersonaResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return persona_source(+ api_key=config.api_key,+ 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/products/warehouse_sources/backend/temporal/data_imports/sources/persona/tests/test_persona.py b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/tests/test_persona.pynew file mode 100644index 000000000000..5904fc062bd7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/tests/test_persona.py@@ -0,0 +1,253 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.persona import persona+from products.warehouse_sources.backend.temporal.data_imports.sources.persona.persona import (+ PersonaResumeConfig,+ PersonaRetryableError,+ _build_params,+ _flatten_item,+ _format_datetime_z,+ _to_datetime,+ get_rows,+ persona_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.persona.settings import PERSONA_ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: PersonaResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[PersonaResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> PersonaResumeConfig | None:+ return self._state++ def save_state(self, data: PersonaResumeConfig) -> None:+ self.saved.append(data)+++class TestFormatDatetimeZ:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),+ ("microseconds", datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC), "2026-01-15T10:30:45.123Z"),+ ("naive_treated_as_utc", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),+ ]+ )+ def test_format(self, _name: str, value: datetime, expected: str) -> None:+ assert _format_datetime_z(value) == expected++ def test_no_plus_offset(self) -> None:+ # Persona expects the Z suffix, not the +00:00 offset isoformat() produces.+ assert "+00:00" not in _format_datetime_z(datetime(2026, 3, 4, tzinfo=UTC))+++class TestToDatetime:+ @parameterized.expand(+ [+ ("iso_z_string", "2026-01-15T10:30:45.000Z", datetime(2026, 1, 15, 10, 30, 45, tzinfo=UTC)),+ ("aware_datetime", datetime(2026, 1, 15, tzinfo=UTC), datetime(2026, 1, 15, tzinfo=UTC)),+ ("date_value", date(2026, 1, 15), datetime(2026, 1, 15, tzinfo=UTC)),+ ]+ )+ def test_parses(self, _name: str, value: Any, expected: datetime) -> None:+ assert _to_datetime(value) == expected++ def test_naive_string_becomes_utc_aware(self) -> None:+ result = _to_datetime("2026-01-15T10:30:45")+ assert result is not None and result.tzinfo is not None++ @parameterized.expand([("none", None), ("garbage", "not-a-date")])+ def test_unparseable_returns_none(self, _name: str, value: Any) -> None:+ assert _to_datetime(value) is None+++class TestBuildParams:+ def test_full_refresh_only_page_size(self) -> None:+ params = _build_params(PERSONA_ENDPOINTS["inquiries"], watermark=None, after=None)+ assert params == {"page[size]": persona.PAGE_SIZE}++ def test_watermark_sets_created_at_start_filter(self) -> None:+ params = _build_params(PERSONA_ENDPOINTS["inquiries"], watermark=datetime(2026, 1, 15, tzinfo=UTC), after=None)+ assert params["filter[created-at-start]"] == "2026-01-15T00:00:00.000Z"++ def test_after_sets_cursor(self) -> None:+ params = _build_params(PERSONA_ENDPOINTS["inquiries"], watermark=None, after="inq_123")+ assert params["page[after]"] == "inq_123"+++class TestFlattenItem:+ def test_lifts_attributes_and_keeps_id(self) -> None:+ row = _flatten_item(+ {"type": "inquiry", "id": "inq_1", "attributes": {"status": "completed", "created-at": "2026-01-01"}}+ )+ assert row["id"] == "inq_1"+ assert row["status"] == "completed"+ assert row["created-at"] == "2026-01-01"+ assert "attributes" not in row+++class TestFetchPageRetryClassification:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ # 429 / 5xx are transient — they must raise the retryable type so tenacity retries them.+ response = MagicMock()+ response.status_code = status+ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(PersonaRetryableError):+ persona._fetch_page(session, "https://api.withpersona.com/api/v1/inquiries", {}, MagicMock())+ # tenacity retries 5 times before giving up.+ assert session.get.call_count == 5++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_immediately(self, _name: str, status: int) -> None:+ # Auth/permission errors can never be fixed by retrying, so they must surface at once.+ response = requests.Response()+ response.status_code = status+ response.url = "https://api.withpersona.com/api/v1/inquiries"+ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(requests.HTTPError):+ persona._fetch_page(session, "https://api.withpersona.com/api/v1/inquiries", {}, MagicMock())+ assert session.get.call_count == 1+++def _collect(manager: _FakeResumableManager, monkeypatch: Any, pages: list[dict], **kwargs: Any) -> list[dict]:+ """Feed canned pages to get_rows in order and return the flattened rows."""+ calls: list[str] = []+ iterator = iter(pages)++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ calls.append(url)+ return next(iterator)++ monkeypatch.setattr(persona, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for table in get_rows(+ api_key="persona_test",+ endpoint="inquiries",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(table.to_pylist())+ manager.fetched_urls = calls # type: ignore[attr-defined]+ return rows+++class TestPagination:+ def test_follows_cursor_until_links_next_is_null(self, monkeypatch: Any) -> None:+ pages = [+ {+ "data": [+ {"type": "inquiry", "id": "inq_1", "attributes": {"created-at": "2026-01-03T00:00:00.000Z"}},+ {"type": "inquiry", "id": "inq_2", "attributes": {"created-at": "2026-01-02T00:00:00.000Z"}},+ ],+ "links": {"next": "/api/v1/inquiries?page[after]=inq_2"},+ },+ {+ "data": [+ {"type": "inquiry", "id": "inq_3", "attributes": {"created-at": "2026-01-01T00:00:00.000Z"}},+ ],+ "links": {"next": None},+ },+ ]+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, pages)++ assert [r["id"] for r in rows] == ["inq_1", "inq_2", "inq_3"]+ # Second request must advance the cursor to the last id of page one.+ assert "page[after]=inq_2" in manager.fetched_urls[1] # type: ignore[attr-defined]++ def test_stops_on_empty_first_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, [{"data": [], "links": {"next": None}}])+ assert rows == []+++class TestIncrementalWatermarkGuard:+ def test_stops_once_rows_predate_watermark(self, monkeypatch: Any) -> None:+ # Guards against re-walking full history: even though links.next is present, once a row older+ # than the watermark appears (newest-first ordering) we stop and never fetch the next page.+ pages = [+ {+ "data": [+ {"type": "inquiry", "id": "inq_new", "attributes": {"created-at": "2026-01-20T00:00:00.000Z"}},+ {"type": "inquiry", "id": "inq_old", "attributes": {"created-at": "2026-01-05T00:00:00.000Z"}},+ ],+ "links": {"next": "/api/v1/inquiries?page[after]=inq_old"},+ },+ {"data": [{"type": "inquiry", "id": "inq_never"}], "links": {"next": None}},+ ]+ manager = _FakeResumableManager()+ rows = _collect(+ manager,+ monkeypatch,+ pages,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 10, tzinfo=UTC),+ )++ assert [r["id"] for r in rows] == ["inq_new"]+ assert len(manager.fetched_urls) == 1 # type: ignore[attr-defined]++ def test_first_page_windowed_by_watermark(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ _collect(+ manager,+ monkeypatch,+ [{"data": [], "links": {"next": None}}],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 10, tzinfo=UTC),+ )+ assert "filter[created-at-start]=2026-01-10T00:00:00.000Z" in manager.fetched_urls[0] # type: ignore[attr-defined]+++class TestResume:+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(state=PersonaResumeConfig(after="inq_saved"))+ _collect(manager, monkeypatch, [{"data": [], "links": {"next": None}}])+ # First request on resume must carry the saved page[after] cursor.+ assert "page[after]=inq_saved" in manager.fetched_urls[0] # type: ignore[attr-defined]+++class TestPersonaSourceResponse:+ @parameterized.expand([("inquiries", "created_at"), ("events", "created_at")])+ def test_incremental_endpoint_partitions_on_created_at_desc(self, endpoint: str, partition_key: str) -> None:+ response = persona_source(+ api_key="persona_test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # sort_mode must be desc — Persona returns newest-first, and the pipeline relies on this to+ # defer the incremental watermark advance to end-of-sync.+ assert response.sort_mode == "desc"+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"++ def test_full_refresh_endpoint_has_no_partitioning(self) -> None:+ response = persona_source(+ api_key="persona_test",+ endpoint="inquiry_templates",+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/persona/tests/test_persona_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/tests/test_persona_source.pynew file mode 100644index 000000000000..4c65bd872b60--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/tests/test_persona_source.py@@ -0,0 +1,138 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import 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 import PersonaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.persona.persona import PersonaResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.persona.source import PersonaSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestPersonaSourceConfig:+ def test_source_type(self) -> None:+ assert PersonaSource().source_type == ExternalDataSourceType.PERSONA++ def test_config_is_alpha_and_unreleased(self) -> None:+ config = PersonaSource().get_source_config+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True++ def test_api_key_field_is_a_secret_password(self) -> None:+ fields = PersonaSource().get_source_config.fields+ assert fields is not None+ api_key = next(f for f in fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key.type == SourceFieldInputConfigType.PASSWORD+ assert api_key.required is True+ assert api_key.secret is True+++class TestPersonaGetSchemas:+ @parameterized.expand(+ [+ # (endpoint, supports_incremental, supports_append)+ ("inquiries", True, True),+ ("accounts", True, True),+ ("cases", True, True),+ ("transactions", True, True),+ # Events are an immutable audit log — append only, never merged.+ ("events", False, True),+ # Inquiry templates are config data with no created-at window — full refresh only.+ ("inquiry_templates", False, False),+ ]+ )+ def test_endpoint_sync_capabilities(self, endpoint: str, incremental: bool, append: bool) -> None:+ schemas = {s.name: s for s in PersonaSource().get_schemas(MagicMock(), team_id=1)}+ schema = schemas[endpoint]+ assert schema.supports_incremental is incremental+ assert schema.supports_append is append++ def test_names_filter(self) -> None:+ schemas = PersonaSource().get_schemas(MagicMock(), team_id=1, names=["cases"])+ assert [s.name for s in schemas] == ["cases"]++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog (no I/O), so the public docs render the table list.+ assert PersonaSource.lists_tables_without_credentials is True+ tables = PersonaSource().get_documented_tables()+ assert {t["name"] for t in tables} == {+ "inquiries",+ "accounts",+ "cases",+ "transactions",+ "events",+ "inquiry_templates",+ }+++class TestPersonaValidateCredentials:+ @parameterized.expand(+ [+ # (http_status, schema_name, expected_ok)+ ("valid_key", 200, None, True),+ ("bad_key", 401, None, False),+ # 403 at source-create is accepted (key valid, may just lack a scope for one resource).+ ("missing_scope_at_create", 403, None, True),+ # 403 for a specific schema means the key can't sync that resource.+ ("missing_scope_for_schema", 403, "inquiries", False),+ ("network_error", 0, None, False),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, schema_name: str | None, expected_ok: bool) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.persona.source.validate_persona_credentials",+ return_value=status,+ ):+ ok, _msg = PersonaSource().validate_credentials(+ PersonaSourceConfig(api_key="persona_test"), team_id=1, schema_name=schema_name+ )+ assert ok is expected_ok+++class TestPersonaNonRetryableErrors:+ def test_auth_errors_are_non_retryable(self) -> None:+ errors = PersonaSource().get_non_retryable_errors()+ assert any("401" in key and "api.withpersona.com" in key for key in errors)+ assert any("403" in key and "api.withpersona.com" in key for key in errors)+++class TestPersonaResumableWiring:+ def test_resumable_manager_bound_to_persona_resume_config(self) -> None:+ manager = PersonaSource().get_resumable_source_manager(MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PersonaResumeConfig++ def test_source_for_pipeline_passes_schema_name_and_api_key(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "cases"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00.000Z"+ inputs.incremental_field = "created_at"++ manager = MagicMock()+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.persona.source.persona_source"+ ) as mock_source:+ PersonaSource().source_for_pipeline(PersonaSourceConfig(api_key="persona_test"), manager, inputs)++ _args, kwargs = mock_source.call_args+ assert kwargs["api_key"] == "persona_test"+ assert kwargs["endpoint"] == "cases"+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00.000Z"++ def test_source_for_pipeline_drops_watermark_when_not_incremental(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "inquiry_templates"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00.000Z"+ inputs.incremental_field = None++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.persona.source.persona_source"+ ) as mock_source:+ PersonaSource().source_for_pipeline(PersonaSourceConfig(api_key="persona_test"), MagicMock(), inputs)++ _args, kwargs = mock_source.call_args+ assert kwargs["db_incremental_field_last_value"] is None