: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(warehouse-sources): add persona inquiry template versions table (#112588)
Tom Owers50347141b43b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 0a44448ac3f0..c25bc1851995 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -6545,6 +6545,8 @@ Diffed against: <https://docs.withpersona.com/2025-12-08/llms.txt>- [ ] `GET /reports/{report-id}/history (List Report history)` — continuous-monitoring state history per report (low)- [ ] `GET /lists (List all Lists)` — blocklist/allowlist definitions referenced by inquiry and verification outcomes (low)- [ ] `GET /user-audit-logs` — reviewer action log for measuring manual review throughput (low)+- [x] `GET /inquiry-template-versions` — published and draft versions of each inquiry template already synced (low)+- [ ] `GET /workflow-versions` — workflow version history; needs `filter[workflow-id]` and Persona has no list-workflows endpoint to enumerate ids (low)Note: Persona's own repo note (products/warehouse_sources/backend/temporal/data_imports/sources/persona/api_inventory.md) documents the 6 synced endpoints. Only resources with a genuine list endpoint are reported: Verifications, Documents, Account Types, Case Templates and Transaction Types are retrieve-by-ID only in the reference, so they are not syncable as standalone tables despite being useful joins - I deliberately left them out rather than invent list routes.diff --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.mdindex d7203bfbd509..86ef71e67274 100644--- 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.md@@ -14,18 +14,19 @@ Reference: <https://docs.withpersona.com/reference> · Base URL: `https://api.wi## Endpoints synced-| Endpoint | Path | Sync mode | Primary key | Partition key |-| ------------------- | --------------------------------------- | ------------ | ----------- | -------------------- |-| `inquiries` | `/inquiries` | Incremental | `id` | `created_at` |-| `verifications` | `/inquiries/{id}?include=verifications` | Incremental | `id` | `inquiry_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` | — |+| Endpoint | Path | Sync mode | Primary key | Partition key |+| --------------------------- | ------------------------------------------------------------- | ------------ | ----------- | -------------------- |+| `inquiries` | `/inquiries` | Incremental | `id` | `created_at` |+| `verifications` | `/inquiries/{id}?include=verifications` | Incremental | `id` | `inquiry_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` | — |+| `inquiry_template_versions` | `/inquiry-template-versions?filter[inquiry-template-id]={id}` | Full refresh | `id` | — |Object ids are globally unique and type-prefixed (`inq_`, `ver_`, `acc_`, `case_`, `txn_`, `evt_`,-`itmpl_`), so `id` is a safe standalone primary key. Persona kebab-case attributes (`created-at`)+`itmpl_`, `itmplv_`), so `id` is a safe standalone primary key. Persona kebab-case attributes (`created-at`)normalize to the snake_case warehouse columns (`created_at`).## Verifications are a fan-out, not a list endpoint@@ -47,6 +48,19 @@ timestamp would skip inquiries created before the watermark that gained a verifiRetries added to an already-synced inquiry are therefore picked up on a full refresh, consistent withhow this source treats updates elsewhere.+## Inquiry template versions are a per-template list++`GET /inquiry-template-versions` requires `filter[inquiry-template-id]` and returns the published+versions and the current draft of that one template+([reference](https://docs.withpersona.com/api-reference/inquiry-templates/list-all-inquiry-template-versions)).+So `inquiry_template_versions` walks `/inquiry-templates` and pages through the versions of each+template, copying the template id onto every row as `inquiry_template_id`. The endpoint has no+created-at filter, so the table is full refresh only. Persona does not serve template versions to+sandbox API keys, so the table is off by default.++`GET /workflow-versions` is not synced. It requires `filter[workflow-id]`, and Persona has no+endpoint that lists workflows, so there is no set of workflow ids to fan out over.+## Verification noteEndpoint paths and semantics are taken from the public Persona docs and the OpenAPI-derived API indexdiff --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.pyindex 55167f03a5bc..d9f8467baa14 100644--- 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.py@@ -86,4 +86,21 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updated_at": "Timestamp when the template was last updated.",},},+ "inquiry_template_versions": {+ "description": "A published or draft version of an inquiry template. Each publish of a template creates a new version.",+ "docs_url": "https://docs.withpersona.com/api-reference/inquiry-templates/list-all-inquiry-template-versions",+ "columns": {+ "id": "Unique identifier for the inquiry template version (prefixed `itmplv_`).",+ "inquiry_template_id": "The inquiry template this version belongs to (prefixed `itmpl_`).",+ "name_display": "The display name of the template in this version.",+ "description": "A description of the changes in this version.",+ "status": "Whether the version is `published` or a `draft`.",+ "live": "Whether this is the template's current live published version.",+ "last_updater": "The email address of the user who last updated this version.",+ "enabled_locales": "The locales enabled in this version.",+ "created_at": "Timestamp when the version was created.",+ "updated_at": "Timestamp when the version was last updated.",+ "published_at": "Timestamp when the version was published. Null for drafts.",+ },+ },}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.pyindex 9b31031c2ac8..01b8c0b2bda2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/persona/persona.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/persona.py@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.persona.settings import (PERSONA_ENDPOINTS,+ PersonaChildList,PersonaEndpointConfig,PersonaFanout,)@@ -204,6 +205,42 @@ def _rows_for_parent(return rows+def _child_list_rows(+ session: requests.Session,+ child_list: PersonaChildList,+ parent: dict[str, Any],+ headers: dict[str, str],+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ """Page through one parent's child list and return its rows, tagged with the parent id."""+ parent_id = parent["id"]+ rows: list[dict[str, Any]] = []+ after: str | None = None+ while True:+ params: dict[str, Any] = {f"filter[{child_list.parent_filter}]": parent_id, "page[size]": PAGE_SIZE}+ if after is not None:+ params["page[after]"] = after+ url = _build_url(f"{PERSONA_BASE_URL}{child_list.path}", params)+ try:+ data = _fetch_page(session, url, headers, logger)+ except requests.HTTPError as e:+ if e.response is not None and e.response.status_code == 404:+ # The parent can be deleted between the list page and this call.+ logger.warning(f"Persona: {child_list.path} for {parent_id} returned 404, skipping")+ return rows+ raise++ items = data.get("data") or []+ for item in items:+ row = _flatten_item(item)+ row[child_list.parent_key] = parent_id+ rows.append(row)++ if not items or not data.get("links", {}).get("next"):+ return rows+ after = items[-1]["id"]++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:@@ -266,11 +303,12 @@ def get_rows(stop = Truebreak- rows = (- _rows_for_parent(session, config.path, config.fanout, item, headers, logger)- if config.fanout is not None- else [_flatten_item(item)]- )+ if config.fanout is not None:+ rows = _rows_for_parent(session, config.path, config.fanout, item, headers, logger)+ elif config.child_list is not None:+ rows = _child_list_rows(session, config.child_list, item, headers, logger)+ else:+ rows = [_flatten_item(item)]for row in rows:batcher.batch(row)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.pyindex a3f31af9f079..21857866f364 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/persona/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persona/settings.py@@ -41,7 +41,19 @@ class PersonaFanout:parent_key_prefix: str-@dataclass+@dataclass(frozen=True, kw_only=True)+class PersonaChildList:+ """A list endpoint Persona only serves for one parent at a time, via a required parent filter.++ Each parent from the list walk gets its own paginated `GET {path}?filter[{parent_filter}]=<id>`.+ """++ path: str+ parent_filter: str+ parent_key: str+++@dataclass(frozen=True, kw_only=True)class PersonaEndpointConfig:name: str# For a fan-out endpoint this is the parent's list path, not the child's.@@ -58,6 +70,7 @@ class PersonaEndpointConfig:should_sync_default: bool = True# Set when the rows come from hydrating each parent rather than from the list response itself.fanout: Optional[PersonaFanout] = None+ child_list: Optional[PersonaChildList] = NonePERSONA_ENDPOINTS: dict[str, PersonaEndpointConfig] = {@@ -110,6 +123,21 @@ PERSONA_ENDPOINTS: dict[str, PersonaEndpointConfig] = {supports_incremental=False,partition_key=None,),+ # Persona has no cross-template list of versions, so this walks the templates and lists each+ # one's versions. The endpoint takes no created-at window, so it is full refresh only. It is off+ # by default because Persona does not serve template versions to sandbox API keys.+ "inquiry_template_versions": PersonaEndpointConfig(+ name="inquiry_template_versions",+ path="/inquiry-templates",+ child_list=PersonaChildList(+ path="/inquiry-template-versions",+ parent_filter="inquiry-template-id",+ parent_key="inquiry-template-id",+ ),+ supports_incremental=False,+ partition_key=None,+ should_sync_default=False,+ ),}ENDPOINTS = tuple(PERSONA_ENDPOINTS.keys())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.pyindex 2d3eefd73ae7..9ea7fd09ef23 100644--- 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.py@@ -473,6 +473,72 @@ class TestVerificationsFanout:)+def _template_page(*ids: str) -> dict:+ return {+ "data": [{"type": "inquiry-template", "id": tid, "attributes": {"status": "active"}} for tid in ids],+ "links": {"next": None},+ }+++def _template_version(vid: str, status: str = "published") -> dict:+ return {"type": "inquiry-template-version", "id": vid, "attributes": {"status": status}}+++class TestInquiryTemplateVersionsFanout:+ def test_pages_each_templates_versions_and_tags_rows_with_the_template(self, monkeypatch: Any) -> None:+ pages = [+ _template_page("itmpl_a", "itmpl_b"),+ {+ "data": [_template_version("itmplv_a1", "draft"), _template_version("itmplv_a2")],+ "links": {"next": "/api/v1/inquiry-template-versions?page[after]=itmplv_a2"},+ },+ {"data": [_template_version("itmplv_a3")], "links": {"next": None}},+ {"data": [_template_version("itmplv_b1")], "links": {"next": None}},+ ]+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, pages, endpoint="inquiry_template_versions")++ assert [(r["id"], r["inquiry-template-id"]) for r in rows] == [+ ("itmplv_a1", "itmpl_a"),+ ("itmplv_a2", "itmpl_a"),+ ("itmplv_a3", "itmpl_a"),+ ("itmplv_b1", "itmpl_b"),+ ]+ assert manager.fetched_urls == [ # type: ignore[attr-defined]+ "https://api.withpersona.com/api/v1/inquiry-templates?page[size]=100",+ "https://api.withpersona.com/api/v1/inquiry-template-versions?filter[inquiry-template-id]=itmpl_a&page[size]=100",+ "https://api.withpersona.com/api/v1/inquiry-template-versions?filter[inquiry-template-id]=itmpl_a&page[size]=100&page[after]=itmplv_a2",+ "https://api.withpersona.com/api/v1/inquiry-template-versions?filter[inquiry-template-id]=itmpl_b&page[size]=100",+ ]++ @parameterized.expand([("gone_template_is_skipped", 404, None), ("server_error_aborts", 500, requests.HTTPError)])+ def test_version_list_error_handling(self, _name: str, status: int, expected_error: type[Exception] | None) -> None:+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ if "itmpl_gone" in url:+ response = requests.Response()+ response.status_code = status+ raise requests.HTTPError(response=response)+ if "itmpl_ok" in url:+ return {"data": [_template_version("itmplv_ok")], "links": {"next": None}}+ return _template_page("itmpl_gone", "itmpl_ok")++ manager = _FakeResumableManager()+ with patch.object(persona, "_fetch_page", fake_fetch):+ rows_iter = get_rows(+ api_key="persona_test",+ endpoint="inquiry_template_versions",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ )+ if expected_error is not None:+ with pytest.raises(expected_error):+ list(rows_iter)+ return+ rows = [row for table in rows_iter for row in table.to_pylist()]++ assert [r["id"] for r in rows] == ["itmplv_ok"]++class TestPersonaSourceResponse:@parameterized.expand([("inquiries", "created_at"), ("events", "created_at"), ("verifications", "inquiry_created_at")]@@ -492,10 +558,11 @@ class TestPersonaSourceResponse:assert response.partition_keys == [partition_key]assert response.partition_mode == "datetime"- def test_full_refresh_endpoint_has_no_partitioning(self) -> None:+ @parameterized.expand([("inquiry_templates",), ("inquiry_template_versions",)])+ def test_full_refresh_endpoint_has_no_partitioning(self, endpoint: str) -> None:response = persona_source(api_key="persona_test",- endpoint="inquiry_templates",+ endpoint=endpoint,logger=MagicMock(),resumable_source_manager=MagicMock(),)diff --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.pyindex ff9c6cdd1cd0..bc9426c1056b 100644--- 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.py@@ -19,8 +19,8 @@ class TestPersonaGetSchemas:("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),+ ("inquiry_template_versions", False, False),])def test_endpoint_sync_capabilities(self, endpoint: str, incremental: bool, append: bool) -> None:@@ -33,12 +33,9 @@ class TestPersonaGetSchemas:schemas = PersonaSource().get_schemas(MagicMock(), team_id=1, names=["cases"])assert [s.name for s in schemas] == ["cases"]- def test_verifications_is_not_preselected(self) -> None:- # Verifications cost one extra request per inquiry, so they're opt-in while everything else- # stays pre-selected.- schemas = {s.name: s for s in PersonaSource().get_schemas(MagicMock(), team_id=1)}- assert schemas["verifications"].should_sync_default is False- assert all(s.should_sync_default for name, s in schemas.items() if name != "verifications")+ def test_only_opt_in_endpoints_are_not_preselected(self) -> None:+ schemas = PersonaSource().get_schemas(MagicMock(), team_id=1)+ assert {s.name for s in schemas if not s.should_sync_default} == {"verifications", "inquiry_template_versions"}def test_lists_tables_without_credentials(self) -> None:# Static endpoint catalog (no I/O), so the public docs render the table list.@@ -52,6 +49,7 @@ class TestPersonaGetSchemas:"transactions","events","inquiry_templates",+ "inquiry_template_versions",}