: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 papersign import source (#67791)
Tom Owers5548001c5be9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex a7da497d3c52..12b30d9db31a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -212,6 +212,7 @@ the row lists both.| optimizely | HTTP | requests | ✅ || pagerduty | HTTP | requests | ✅ || pandadoc | HTTP | requests | ✅ |+| papersign | HTTP | requests | ✅ || paystack | HTTP | requests + `rest_source.RESTClient` | ✅ || pendo | HTTP | requests | ✅ || personio | HTTP | requests | ✅ |@@ -557,7 +558,6 @@ doesn't conflict with concurrent PRs.- pabbly_subscriptions_billing- pagerduty- paperform-- papersign- pardot- partnerize- partnerstackdiff --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 3456aae0a0a8..0cdc29c4fab6 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@@ -2350,7 +2350,7 @@ class PaperformSourceConfig(config.Config):@config.configclass PapersignSourceConfig(config.Config):- pass+ api_token: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/canonical_descriptions.pynew file mode 100644index 000000000000..7fb518c3a4c6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/canonical_descriptions.py@@ -0,0 +1,46 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions are taken from the Paperform/Papersign API docs+# (https://paperform.readme.io/reference/papersign). Partial coverage is fine — any column not+# listed here falls back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "documents": {+ "description": "A Papersign e-signature document, tracking its signers, status, and lifecycle timestamps.",+ "docs_url": "https://paperform.readme.io/reference/listpapersigndocuments",+ "columns": {+ "id": "Unique identifier of the document.",+ "name": "Name of the document.",+ "status": "Lifecycle status of the document (draft, in_progress, completed, canceled, expired, or rejected).",+ "folder": "The Papersign folder the document belongs to (nested object with id, name, parent_id, space_id).",+ "space": "The Papersign space the document belongs to (nested object with id, name, root_folder_id, allow_team_access).",+ "signers": "List of signers on the document.",+ "variables": "List of Papersign variables (merge fields) defined on the document.",+ "created_at_utc": "Timestamp the document was created (UTC).",+ "updated_at_utc": "Timestamp the document was last updated (UTC).",+ "sent_at_utc": "Timestamp the document was sent to signers (UTC), or null.",+ "completed_at_utc": "Timestamp all signers completed the document (UTC), or null.",+ },+ },+ "folders": {+ "description": "A folder that organises Papersign documents within a space.",+ "docs_url": "https://paperform.readme.io/reference/listpapersignfolders",+ "columns": {+ "id": "Unique identifier of the folder.",+ "name": "Name of the folder.",+ "parent_id": "Identifier of the parent folder, or null for a top-level folder.",+ "space_id": "Identifier of the space the folder belongs to.",+ },+ },+ "spaces": {+ "description": "A Papersign space — a top-level workspace grouping folders and documents.",+ "docs_url": "https://paperform.readme.io/reference/listpapersignspaces",+ "columns": {+ "id": "Unique identifier of the space.",+ "name": "Name of the space.",+ "root_folder_id": "Identifier of the space's root folder.",+ "allow_team_access": "Whether team members can access this space.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/papersign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/papersign.pynew file mode 100644index 000000000000..3b5fa7613fc9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/papersign.py@@ -0,0 +1,179 @@+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.papersign.settings import (+ PAPERSIGN_ENDPOINTS,+ PapersignEndpointConfig,+)++# Papersign shares Paperform's single-host REST API. There is no per-account subdomain.+BASE_URL = "https://api.paperform.co/v1"++# `limit` is capped server-side at 100; the default is 20. We request the max to minimise round trips.+PAGE_SIZE = 100++REQUEST_TIMEOUT_SECONDS = 60+++class PapersignRetryableError(Exception):+ pass+++class PapersignResumeConfig:+ # The `skip` (offset) of the page we're currently streaming. We persist *this* page's offset+ # (not the next one) so a crash mid-page resumes by re-fetching the same page rather than+ # skipping past rows still buffered but not yet merged — merge dedupes the re-pulled rows on+ # the primary key. `0` means "start from the first page".+ skip: int = 0+++def _get_session(api_token: str) -> requests.Session:+ # `redact_values` masks the bearer token in logged URLs and captured HTTP samples, so an+ # operator-enabled capture never persists a customer's API key.+ return make_tracked_session(+ headers={"Authorization": f"Bearer {api_token}", "Accept": "application/json"},+ redact_values=(api_token,),+ )+++def _build_url(path: str, params: dict[str, Any]) -> str:+ if not params:+ return f"{BASE_URL}{path}"+ return f"{BASE_URL}{path}?{urlencode(params, doseq=True)}"+++def validate_credentials(api_token: str) -> tuple[bool, str | None]:+ """Confirm the API token is genuine with one cheap, low-limit list request.++ Paperform issues a single account-wide token (no per-resource scopes), so probing any Papersign+ list endpoint is sufficient. A 401 means the token is wrong; a 403 means the token is valid but+ the plan doesn't include Papersign API access. Anything else reachable counts as valid.+ """+ url = _build_url("/papersign/spaces", {"limit": 1})+ try:+ response = _get_session(api_token).get(url, timeout=10)+ except Exception:+ return False, "Could not reach Paperform. Check your network and try again."++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid Paperform API key. Create a new key on your Paperform account page and reconnect."+ if response.status_code == 403:+ return (+ False,+ "This Paperform API key does not have Papersign API access. The Papersign API requires a paid "+ "Paperform plan — upgrade the plan, then reconnect.",+ )+ return False, f"Paperform API returned an unexpected status ({response.status_code}) while validating credentials."+++@retry(+ retry=retry_if_exception_type((PapersignRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ # Paperform is rate limited per minute and returns 429 with a Retry-After header when exceeded.+ # The exact threshold is undocumented, so we back off exponentially rather than trusting the+ # header. 5xx are transient too.+ if response.status_code == 429 or response.status_code >= 500:+ raise PapersignRetryableError(f"Paperform API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Paperform API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PapersignResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = PAPERSIGN_ENDPOINTS[endpoint]+ # One session reused across every page so urllib3 keeps the connection alive.+ session = _get_session(api_token)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ skip: int = resume.skip if resume is not None else 0+ if resume is not None:+ logger.debug(f"Papersign: resuming {endpoint} from skip={skip}")++ while True:+ params: dict[str, Any] = {"limit": PAGE_SIZE, "skip": skip}+ if config.supports_sort:+ # Ascending by created_at keeps offset pagination stable: rows created during the sync+ # append at the end rather than shifting the offsets of pages we've already read.+ params["sort"] = "ASC"++ data = _fetch_page(session, _build_url(config.path, params), logger)+ # Index strictly rather than `.get(..., [])`: `results` and its resource key are required+ # fields of the documented response. A malformed 200 (e.g. during an upstream incident) must+ # raise KeyError and fail the sync loudly, not silently yield zero rows — on a full-refresh+ # table that would replace all previously synced data with an empty table.+ rows = data["results"][config.results_key]+ if not rows:+ break++ yield rows+ # Save the offset of the page we just yielded (not the next one) AFTER yielding, so a crash+ # re-fetches this page rather than skipping rows still buffered. Merge dedupes on the+ # primary key.+ resumable_source_manager.save_state(PapersignResumeConfig(skip=skip))++ # `has_more` is the authoritative end-of-list signal. The short-page check is a defensive+ # backstop for the folders/spaces endpoints, whose pagination is undocumented: if one ignores+ # `skip` yet still reports `has_more=true`, a full-page loop could otherwise never terminate.+ # A page shorter than the limit is always the last one.+ if not data.get("has_more") or len(rows) < PAGE_SIZE:+ break+ skip += len(rows)+++def papersign_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PapersignResumeConfig],+) -> SourceResponse:+ endpoint_config: PapersignEndpointConfig = PAPERSIGN_ENDPOINTS[endpoint]++ partition_kwargs: dict[str, Any] = {}+ if endpoint_config.partition_key is not None:+ partition_kwargs = {+ "partition_count": 1,+ "partition_size": 1,+ "partition_mode": "datetime",+ "partition_format": "month",+ "partition_keys": [endpoint_config.partition_key],+ }++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Documents arrive ascending (we request `sort=ASC`); folders/spaces are small full scans.+ sort_mode="asc",+ **partition_kwargs,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/settings.pynew file mode 100644index 000000000000..4dcfce2fd7b3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/settings.py@@ -0,0 +1,55 @@+from dataclasses import dataclass, field+++@dataclass+class PapersignEndpointConfig:+ name: str+ # Path appended to the API base (https://api.paperform.co/v1).+ path: str+ # Key inside the response `results` object holding the row array+ # (e.g. `{"results": {"documents": [...]}}`).+ results_key: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # A stable, lifetime-constant datetime field used as the datetime partition key, or `None`+ # when the resource carries no such field. Papersign documents expose `created_at_utc`+ # (fixed at creation); folders and spaces have no timestamp at all, so they aren't partitioned.+ # `updated_at_utc` is never used — it shifts on every edit and would rewrite partitions each sync.+ partition_key: str | None = None+ # Whether the list endpoint accepts `?sort=ASC|DESC` (only documents does). We request `ASC`+ # so offset pagination stays stable: rows created mid-sync append at the end (a larger+ # `created_at`), leaving already-paged offsets untouched.+ supports_sort: bool = False+ should_sync_default: bool = True+++# Papersign (Paperform's e-signature product) exposes three readable list endpoints. Each returns+# `{"status": "ok", "results": {"<resource>": [...]}, "total": N, "has_more": bool, "limit": 20,+# "skip": 0}` and is paginated by limit/skip offset (see papersign.py).+#+# Every table is full refresh. Documents advertise `after_date`/`before_date` filters on+# `created_at`, but (1) their documented semantics are inverted relative to their names and we could+# not curl-verify them, and (2) documents mutate over their lifetime (a document walks+# draft -> in_progress -> completed / canceled / expired / rejected), so a creation-time incremental+# sync would only ever capture new documents and silently miss those status transitions. Folders and+# spaces expose no timestamp filter at all. This mirrors the sibling e-signature source DocuSeal.+PAPERSIGN_ENDPOINTS: dict[str, PapersignEndpointConfig] = {+ "documents": PapersignEndpointConfig(+ name="documents",+ path="/papersign/documents",+ results_key="documents",+ partition_key="created_at_utc",+ supports_sort=True,+ ),+ "folders": PapersignEndpointConfig(+ name="folders",+ path="/papersign/folders",+ results_key="folders",+ ),+ "spaces": PapersignEndpointConfig(+ name="spaces",+ path="/papersign/spaces",+ results_key="spaces",+ ),+}++ENDPOINTS = tuple(PAPERSIGN_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/source.pyindex 568ea9c75479..aa7602d03a68 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/source.py@@ -3,17 +3,40 @@ from typing import 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 PapersignSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.papersign.papersign import (+ PapersignResumeConfig,+ papersign_source,+ validate_credentials as validate_papersign_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.papersign.settings import (+ ENDPOINTS,+ PAPERSIGN_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PapersignSource(SimpleSource[PapersignSourceConfig]):+class PapersignSource(ResumableSource[PapersignSourceConfig, PapersignResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PAPERSIGN@@ -24,7 +47,90 @@ class PapersignSource(SimpleSource[PapersignSourceConfig]):name=SchemaExternalDataSourceType.PAPERSIGN,category=DataWarehouseSourceCategory.SALES,label="Papersign",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Paperform API key to sync your Papersign documents, folders, and spaces into the PostHog Data warehouse.++Create an API key on your [Paperform account page](https://paperform.co/account/developer/api-keys). The key has full account access — Paperform does not offer per-resource scopes.++The Papersign API requires a paid Paperform plan (Standard or Business tier).""",iconPath="/static/services/papersign.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/papersign",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Paperform API key",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.papersign.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A 401 means the token is missing/invalid/revoked; retrying can never fix a credential+ # problem, so stop the sync and surface an actionable message.+ "401 Client Error: Unauthorized for url: https://api.paperform.co": "Your Paperform API key is invalid or has been revoked. Create a new key on your Paperform account page, then reconnect.",+ # A 403 at sync time means the token is valid but the plan no longer includes Papersign+ # API access.+ "403 Client Error: Forbidden for url: https://api.paperform.co": "Your Paperform API key does not have Papersign API access. The Papersign API requires a paid Paperform plan — upgrade the plan, then reconnect.",+ }++ def get_schemas(+ self,+ config: PapersignSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Full refresh only: Papersign documents mutate over their lifetime (status transitions) and+ # its timestamp filters could not be curl-verified, while folders and spaces expose no filter+ # at all. See settings.py for the full reasoning.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ should_sync_default=PAPERSIGN_ENDPOINTS[endpoint].should_sync_default,+ detected_primary_keys=PAPERSIGN_ENDPOINTS[endpoint].primary_keys,+ )+ 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: PapersignSourceConfig, team_id: int, schema_name: str | None = None+ ) -> tuple[bool, str | None]:+ return validate_papersign_credentials(config.api_token)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PapersignResumeConfig]:+ return ResumableSourceManager[PapersignResumeConfig](inputs, PapersignResumeConfig)++ def source_for_pipeline(+ self,+ config: PapersignSourceConfig,+ resumable_source_manager: ResumableSourceManager[PapersignResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return papersign_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/tests/test_papersign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/tests/test_papersign.pynew file mode 100644index 000000000000..bb1cedad591e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/tests/test_papersign.py@@ -0,0 +1,251 @@+from typing import Any+from urllib.parse import parse_qs, urlparse++from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.papersign import papersign+from products.warehouse_sources.backend.temporal.data_imports.sources.papersign.papersign import (+ BASE_URL,+ PAGE_SIZE,+ PapersignResumeConfig,+ _build_url,+ get_rows,+ papersign_source,+ validate_credentials,+)+++def _ok_json_response(payload: dict | None = None, status_code: int = 200) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.json.return_value = payload if payload is not None else {}+ response.raise_for_status = MagicMock()+ return response+++class _FakeResumableManager:+ def __init__(self, state: PapersignResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[PapersignResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> PapersignResumeConfig | None:+ return self._state++ def save_state(self, data: PapersignResumeConfig) -> None:+ self.saved.append(data)+++def _page(results_key: str, rows: list[dict[str, Any]], has_more: bool) -> dict[str, Any]:+ return {+ "status": "ok",+ "results": {results_key: rows},+ "total": len(rows),+ "has_more": has_more,+ "limit": PAGE_SIZE,+ "skip": 0,+ }+++def _docs(count: int, start: int = 0) -> list[dict[str, Any]]:+ return [{"id": f"doc-{start + i}", "created_at_utc": "2026-01-01T00:00:00Z"} for i in range(count)]+++class TestBuildUrl:+ def test_no_params(self) -> None:+ assert _build_url("/papersign/spaces", {}) == f"{BASE_URL}/papersign/spaces"++ def test_with_params_is_urlencoded(self) -> None:+ url = _build_url("/papersign/documents", {"limit": 100, "skip": 200, "sort": "ASC"})+ assert url == f"{BASE_URL}/papersign/documents?limit=100&skip=200&sort=ASC"+++class TestValidateCredentials:+ @patch.object(papersign, "make_tracked_session")+ def test_returns_true_on_200(self, mock_session: MagicMock) -> None:+ mock_session.return_value.get.return_value = _ok_json_response({"results": {"spaces": []}})++ success, error = validate_credentials("tok")++ assert success is True+ assert error is None+ called_url = mock_session.return_value.get.call_args.args[0]+ assert called_url == f"{BASE_URL}/papersign/spaces?limit=1"++ @parameterized.expand(+ [+ (401, "invalid"),+ (403, "papersign api access"),+ (500, "unexpected status"),+ ]+ )+ @patch.object(papersign, "make_tracked_session")+ def test_returns_false_on_http_status(+ self, status_code: int, expected_substring: str, mock_session: MagicMock+ ) -> None:+ mock_session.return_value.get.return_value = _ok_json_response(status_code=status_code)++ success, error = validate_credentials("tok")++ assert success is False+ assert error is not None+ assert expected_substring.lower() in error.lower()++ @patch.object(papersign, "make_tracked_session")+ def test_redacts_token_in_tracked_session(self, mock_session: MagicMock) -> None:+ # The bearer token must be passed to redact_values so it's masked in logged URLs and captured+ # HTTP samples. Dropping this would leak customers' API keys into the capture pipeline.+ mock_session.return_value.get.return_value = _ok_json_response({"results": {"spaces": []}})+ validate_credentials("secret-token")+ assert mock_session.call_args.kwargs.get("redact_values") == ("secret-token",)++ @patch.object(papersign, "make_tracked_session")+ def test_returns_false_on_network_error(self, mock_session: MagicMock) -> None:+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")++ success, error = validate_credentials("tok")++ assert success is False+ assert error is not None+ assert "could not reach paperform" in error.lower()+++class TestGetRows:+ @staticmethod+ def _run(+ manager: _FakeResumableManager,+ pages: list[dict[str, Any]],+ endpoint: str = "documents",+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+ """Drive get_rows against a queue of page responses. Returns (rows, recorded_requests)."""+ queue = list(pages)+ recorded: list[dict[str, Any]] = []++ def fake_fetch(session: Any, url: str, logger: Any) -> dict[str, Any]:+ query = parse_qs(urlparse(url).query)+ recorded.append(+ {+ "url": url,+ "skip": int(query["skip"][0]) if "skip" in query else None,+ "limit": int(query["limit"][0]) if "limit" in query else None,+ "sort": query["sort"][0] if "sort" in query else None,+ }+ )+ return queue.pop(0)++ with patch.object(papersign, "_fetch_page", side_effect=fake_fetch):+ rows: list[dict[str, Any]] = []+ for page in get_rows(+ api_token="tok",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(page)+ return rows, recorded++ def test_single_page_terminates_when_has_more_false(self) -> None:+ manager = _FakeResumableManager()+ rows, recorded = self._run(manager, [_page("documents", _docs(3), has_more=False)])++ assert [r["id"] for r in rows] == ["doc-0", "doc-1", "doc-2"]+ assert len(recorded) == 1+ assert recorded[0]["skip"] == 0+ assert recorded[0]["limit"] == PAGE_SIZE+ # Documents are the only endpoint that gets an explicit ascending sort.+ assert recorded[0]["sort"] == "ASC"++ def test_walks_pages_incrementing_skip(self) -> None:+ manager = _FakeResumableManager()+ pages = [+ _page("documents", _docs(PAGE_SIZE, start=0), has_more=True),+ _page("documents", _docs(PAGE_SIZE, start=PAGE_SIZE), has_more=True),+ _page("documents", _docs(50, start=2 * PAGE_SIZE), has_more=False),+ ]+ rows, recorded = self._run(manager, pages)++ assert len(rows) == 2 * PAGE_SIZE + 50+ # skip advances by the number of rows actually returned on each page.+ assert [r["skip"] for r in recorded] == [0, PAGE_SIZE, 2 * PAGE_SIZE]++ def test_short_page_terminates_even_if_has_more_true(self) -> None:+ # Guards the folders/spaces infinite-loop case: an endpoint that ignores `skip` but keeps+ # reporting has_more=true must still stop once a page comes back shorter than the limit.+ manager = _FakeResumableManager()+ rows, recorded = self._run(+ manager, [_page("folders", [{"id": i} for i in range(3)], has_more=True)], endpoint="folders"+ )+ assert len(rows) == 3+ assert len(recorded) == 1++ def test_stops_when_results_empty(self) -> None:+ manager = _FakeResumableManager()+ # has_more lies (True) but the page is empty — we must still terminate, not loop forever.+ rows, recorded = self._run(manager, [_page("documents", [], has_more=True)])++ assert rows == []+ assert len(recorded) == 1++ def test_folders_endpoint_sends_no_sort(self) -> None:+ manager = _FakeResumableManager()+ _rows, recorded = self._run(+ manager, [_page("folders", [{"id": 1, "name": "F"}], has_more=False)], endpoint="folders"+ )+ assert recorded[0]["sort"] is None++ def test_resume_uses_saved_skip(self) -> None:+ manager = _FakeResumableManager(PapersignResumeConfig(skip=200))+ _rows, recorded = self._run(manager, [_page("documents", _docs(2, start=200), has_more=False)])++ # First request must continue from the saved offset, not restart at 0.+ assert recorded[0]["skip"] == 200++ def test_saves_only_already_fetched_offsets_after_yield(self) -> None:+ # The "save current page, not next" invariant: every persisted offset must be one we've+ # already fetched, so a crash re-fetches (merge dedupes) rather than skipping buffered rows.+ manager = _FakeResumableManager()+ pages = [+ _page("documents", _docs(PAGE_SIZE, start=0), has_more=True),+ _page("documents", _docs(PAGE_SIZE, start=PAGE_SIZE), has_more=True),+ _page("documents", _docs(10, start=2 * PAGE_SIZE), has_more=False),+ ]+ _rows, recorded = self._run(manager, pages)++ fetched_skips = {r["skip"] for r in recorded}+ assert manager.saved, "expected a save after each yielded page"+ assert all(saved.skip in fetched_skips for saved in manager.saved)+++class TestPapersignSourceResponse:+ def test_documents_partitions_on_created_at(self) -> None:+ response = papersign_source(+ api_token="tok",+ endpoint="documents",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ assert response.name == "documents"+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at_utc"]++ @parameterized.expand(["folders", "spaces"])+ def test_untimestamped_endpoints_are_not_partitioned(self, endpoint: str) -> None:+ # folders and spaces carry no stable datetime field, so they must not declare a datetime+ # partition (partitioning on a missing column would break the sync).+ response = papersign_source(+ api_token="tok",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/tests/test_papersign_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/tests/test_papersign_source.pynew file mode 100644index 000000000000..219b09dc8f58--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/papersign/tests/test_papersign_source.py@@ -0,0 +1,147 @@+from typing import cast++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PapersignSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.papersign import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.papersign.papersign import PapersignResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.papersign.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.papersign.source import PapersignSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(api_token: str = "tok") -> PapersignSourceConfig:+ return PapersignSourceConfig(api_token=api_token)+++class TestPapersignSourceConfig:+ def test_source_type(self) -> None:+ assert PapersignSource().source_type == ExternalDataSourceType.PAPERSIGN++ def test_visible_and_alpha(self) -> None:+ cfg = PapersignSource().get_source_config+ assert cfg.unreleasedSource is None+ assert cfg.releaseStatus == ReleaseStatus.ALPHA+ assert cfg.category == DataWarehouseSourceCategory.SALES+ assert cfg.docsUrl == "https://posthog.com/docs/cdp/sources/papersign"++ def test_exposes_api_token_field(self) -> None:+ cfg = PapersignSource().get_source_config+ names = {f.name for f in cfg.fields}+ assert names == {"api_token"}++ api_token_field = next(f for f in cfg.fields if f.name == "api_token")+ assert isinstance(api_token_field, SourceFieldInputConfig)+ assert api_token_field.required is True+ assert api_token_field.secret is True+ assert api_token_field.type == SourceFieldInputConfigType.PASSWORD+++class TestPapersignSchemas:+ def test_lists_all_endpoints_as_full_refresh(self) -> None:+ schemas = {s.name: s for s in PapersignSource().get_schemas(_config(), team_id=1)}+ assert set(schemas) == set(ENDPOINTS)+ for schema in schemas.values():+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []+ assert schema.detected_primary_keys == ["id"]++ def test_names_filter_subsets_schemas(self) -> None:+ schemas = PapersignSource().get_schemas(_config(), team_id=1, names=["documents"])+ assert [s.name for s in schemas] == ["documents"]++ def test_lists_tables_without_credentials_for_docs(self) -> None:+ source = PapersignSource()+ assert source.lists_tables_without_credentials is True+ tables = source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ for table in tables:+ assert table["sync_methods"] == ["Full refresh"]++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = PapersignSource().get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)+++class TestPapersignCredentials:+ @patch.object(source_module, "validate_papersign_credentials", return_value=(True, None))+ def test_delegates_to_transport(self, mock_validate: MagicMock) -> None:+ ok, error = PapersignSource().validate_credentials(_config(api_token="abc"), team_id=1)+ assert ok is True+ assert error is None+ mock_validate.assert_called_once_with("abc")++ @patch.object(source_module, "validate_papersign_credentials", return_value=(False, "Invalid Paperform API key."))+ def test_propagates_failure(self, _mock_validate: MagicMock) -> None:+ ok, error = PapersignSource().validate_credentials(_config(), team_id=1)+ assert ok is False+ assert error == "Invalid Paperform API key."+++class TestPapersignNonRetryableErrors:+ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.paperform.co/v1/papersign/documents"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.paperform.co/v1/papersign/spaces"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = PapersignSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.paperform.co/v1/papersign/documents",+ ),+ (+ "rate_limit",+ "429 Client Error: Too Many Requests for url: https://api.paperform.co/v1/papersign/folders",+ ),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = PapersignSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestPapersignPipelineWiring:+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = PapersignSource().get_resumable_source_manager(MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PapersignResumeConfig++ def test_source_for_pipeline_plumbs_inputs(self) -> None:+ captured: dict[str, object] = {}++ def fake_source(**kwargs: object) -> object:+ captured.update(kwargs)+ return "sentinel"++ inputs = MagicMock()+ inputs.schema_name = "documents"+ manager = MagicMock()+ logger = MagicMock()+ inputs.logger = logger++ with patch.object(source_module, "papersign_source", side_effect=fake_source) as mock_source:+ result = PapersignSource().source_for_pipeline(_config(api_token="abc"), manager, inputs)++ assert cast(object, result) == "sentinel"+ mock_source.assert_called_once()+ assert captured["api_token"] == "abc"+ assert captured["endpoint"] == "documents"+ assert captured["resumable_source_manager"] is manager+ assert captured["logger"] is logger