: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 capsule_crm import source (#66746)
Tom Owers70a959f1fb97
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 386724c72cdb..a10a96541534 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -86,6 +86,7 @@ the row lists both.| campaign_monitor | HTTP | requests | ✅ || campayn | HTTP | requests | ✅ || canny | HTTP | requests | ✅ |+| capsule_crm | HTTP | requests | ✅ || care_quality_commission | HTTP | requests | ✅ || chameleon | HTTP | requests | ✅ || chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -346,7 +347,6 @@ doesn't conflict with concurrent PRs.- breezy_hr- cal_com- campaign_manager_360-- capsule_crm- captain_data- cart_com- castor_edcdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/canonical_descriptions.pynew file mode 100644index 000000000000..0e66468110bb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/canonical_descriptions.py@@ -0,0 +1,154 @@+"""Canonical, documentation-sourced descriptions for Capsule CRM endpoints and columns.++Sourced from the official Capsule CRM API reference (https://developer.capsulecrm.com/v2/overview/introduction).+Keyed by the endpoint names in `settings.py` `CAPSULE_CRM_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Capsule table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "parties": {+ "description": "A person or organisation in your Capsule account (a contact). The `type` field distinguishes people from organisations.",+ "docs_url": "https://developer.capsulecrm.com/v2/operations/Party",+ "columns": {+ "id": "Unique identifier for the party.",+ "type": "Whether the party is a 'person' or an 'organisation'.",+ "firstName": "First name (people only).",+ "lastName": "Last name (people only).",+ "title": "Honorific title such as Mr or Ms (people only).",+ "jobTitle": "The person's job title.",+ "name": "Organisation name (organisations only).",+ "about": "Free-text description of the party.",+ "organisation": "The organisation a person belongs to.",+ "owner": "The user who owns this party.",+ "team": "The team this party is assigned to.",+ "addresses": "Postal addresses associated with the party.",+ "phoneNumbers": "Phone numbers associated with the party.",+ "emailAddresses": "Email addresses associated with the party.",+ "websites": "Websites and social profiles associated with the party.",+ "tags": "Tags applied to the party (when embedded).",+ "fields": "Custom field values for the party (when embedded).",+ "pictureURL": "URL of the party's profile picture.",+ "lastContactedAt": "Time the party was last contacted.",+ "createdAt": "Time the party was created.",+ "updatedAt": "Time the party was last updated.",+ },+ },+ "opportunities": {+ "description": "A potential sale (deal) tracked in your sales pipeline, linked to a party.",+ "docs_url": "https://developer.capsulecrm.com/v2/operations/Opportunity",+ "columns": {+ "id": "Unique identifier for the opportunity.",+ "name": "The opportunity's name.",+ "description": "Free-text description of the opportunity.",+ "party": "The party (contact) this opportunity is associated with.",+ "milestone": "The current pipeline milestone of the opportunity.",+ "pipeline": "The sales pipeline this opportunity belongs to.",+ "value": "The monetary value of the opportunity, with amount and currency.",+ "probability": "Estimated probability of winning, as a percentage.",+ "durationBasis": "The unit the duration is measured in (e.g. DAY, MONTH).",+ "duration": "The expected duration of the opportunity.",+ "owner": "The user who owns this opportunity.",+ "team": "The team this opportunity is assigned to.",+ "expectedCloseOn": "The date the opportunity is expected to close.",+ "closedOn": "The date the opportunity was closed.",+ "lostReason": "The reason the opportunity was lost, if applicable.",+ "tags": "Tags applied to the opportunity (when embedded).",+ "fields": "Custom field values for the opportunity (when embedded).",+ "lastContactedAt": "Time the opportunity's party was last contacted.",+ "createdAt": "Time the opportunity was created.",+ "updatedAt": "Time the opportunity was last updated.",+ },+ },+ "kases": {+ "description": "A project (historically called a case) used to organise ongoing work for a party.",+ "docs_url": "https://developer.capsulecrm.com/v2/operations/Project",+ "columns": {+ "id": "Unique identifier for the project.",+ "name": "The project's name.",+ "description": "Free-text description of the project.",+ "status": "Whether the project is OPEN or CLOSED.",+ "party": "The party (contact) this project is associated with.",+ "owner": "The user who owns this project.",+ "team": "The team this project is assigned to.",+ "stage": "The current stage of the project.",+ "expectedCloseOn": "The date the project is expected to close.",+ "closedOn": "The date the project was closed.",+ "lastContactedAt": "Time the project's party was last contacted.",+ "tags": "Tags applied to the project (when embedded).",+ "fields": "Custom field values for the project (when embedded).",+ "createdAt": "Time the project was created.",+ "updatedAt": "Time the project was last updated.",+ },+ },+ "tasks": {+ "description": "A to-do item, optionally linked to a party, opportunity, or project.",+ "docs_url": "https://developer.capsulecrm.com/v2/operations/Task",+ "columns": {+ "id": "Unique identifier for the task.",+ "description": "The task's title/description.",+ "detail": "Additional detail about the task.",+ "status": "The task status (e.g. OPEN, COMPLETED).",+ "category": "The category the task belongs to.",+ "party": "The party (contact) the task relates to.",+ "opportunity": "The opportunity the task relates to.",+ "kase": "The project the task relates to.",+ "owner": "The user the task is assigned to.",+ "dueOn": "The date the task is due.",+ "dueTime": "The time of day the task is due.",+ "completedAt": "Time the task was completed.",+ "createdAt": "Time the task was created.",+ "updatedAt": "Time the task was last updated.",+ },+ },+ "users": {+ "description": "A user of your Capsule account.",+ "docs_url": "https://developer.capsulecrm.com/v2/operations/User",+ "columns": {+ "id": "Unique identifier for the user.",+ "username": "The user's username.",+ "name": "The user's display name.",+ "status": "Whether the user is active.",+ },+ },+ "milestones": {+ "description": "A stage in a sales pipeline that opportunities progress through.",+ "docs_url": "https://developer.capsulecrm.com/v2/operations/Milestone",+ "columns": {+ "id": "Unique identifier for the milestone.",+ "name": "The milestone's name.",+ "description": "Free-text description of the milestone.",+ "probability": "Default win probability associated with this milestone.",+ "complete": "Whether reaching this milestone marks the opportunity as won.",+ },+ },+ "pipelines": {+ "description": "A sales pipeline that groups a set of milestones.",+ "docs_url": "https://developer.capsulecrm.com/v2/operations/Pipeline",+ "columns": {+ "id": "Unique identifier for the pipeline.",+ "name": "The pipeline's name.",+ "milestones": "The milestones that make up the pipeline.",+ },+ },+ "categories": {+ "description": "A category used to classify tasks.",+ "docs_url": "https://developer.capsulecrm.com/v2/operations/Category",+ "columns": {+ "id": "Unique identifier for the category.",+ "name": "The category's name.",+ "colour": "The display colour of the category.",+ },+ },+ "lost_reasons": {+ "description": "A predefined reason for marking an opportunity as lost.",+ "docs_url": "https://developer.capsulecrm.com/v2/operations/LostReason",+ "columns": {+ "id": "Unique identifier for the lost reason.",+ "name": "The lost reason's text.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/capsule-crm.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/capsule-crm.mdxnew file mode 100644index 000000000000..f24a87155d7f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/capsule-crm.mdx@@ -0,0 +1,55 @@+---+title: Linking Capsule CRM as a source+sidebar: Docs+showTitle: true+availability: { free: full, selfServe: full, enterprise: full }+sourceId: CapsuleCRM+---++import SourceSetupIntro from '../_snippets/source-setup-intro.mdx'+import SyncModes from '../_snippets/sync-modes.mdx'+import SourceParameters from '../_snippets/source-parameters.mdx'+import SourceTables from '../_snippets/source-tables.mdx'+import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'+import AlphaRelease from '../_snippets/alpha-release.mdx'++<AlphaRelease />++Capsule CRM is a CRM for small and medium businesses covering contacts, the sales pipeline, and project management. This connector syncs your Capsule contacts, opportunities, projects, tasks, and supporting reference data into the PostHog data warehouse so you can join CRM records with your product and revenue data.++## Prerequisites++To connect Capsule CRM, you need a Capsule account and a **Personal Access Token**. The token inherits the permissions of the user that created it, so make sure that user can see the records you want to sync.++## Adding a data source++<SourceSetupIntro />++You'll need a Capsule CRM Personal Access Token:++1. Sign in to Capsule and open **My Preferences → API Authentication Tokens**.+2. Generate a new token and copy it.+3. Paste the token into the **Personal Access Token** field in PostHog.++Capsule's API is rate limited to roughly 4,000 requests per hour per user, so very large initial syncs may take some time to complete.++## Sync modes++<SyncModes />++Parties, opportunities, and projects support **incremental** syncs using Capsule's `since` change filter (tracked on `updatedAt`), so ongoing syncs only pull records that changed since the last run. The remaining tables (tasks, users, milestones, pipelines, categories, and lost reasons) are full refresh only, since Capsule does not expose a server-side change filter for them.++## Configuration++<SourceParameters />++## Supported tables++<SourceTables />++## Troubleshooting++- **Invalid Personal Access Token** — if the connection fails to validate, regenerate the token in **My Preferences → API Authentication Tokens** and reconnect. A revoked or mistyped token returns a `401 Unauthorized`.+- **A table fails to sync with a permission error** — the token can only read what its owning user can see. Make sure that user has access to the records (parties, opportunities, projects, tasks) you're trying to sync.++<TroubleshootingLink />diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/capsule_crm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/capsule_crm.pynew file mode 100644index 000000000000..b1d8926f4e93--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/capsule_crm.py@@ -0,0 +1,223 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urlsplit++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.capsule_crm.settings import (+ CAPSULE_CRM_ENDPOINTS,+ CapsuleCRMEndpointConfig,+)+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++CAPSULE_CRM_BASE_URL = "https://api.capsulecrm.com/api/v2"+CAPSULE_CRM_HOST = "api.capsulecrm.com"+CAPSULE_CRM_PATH_PREFIX = "/api/v2/"++# Capsule caps perPage at 100; always request the max to minimize round-trips.+PAGE_SIZE = 100++REQUEST_TIMEOUT_SECONDS = 60+++class CapsuleCRMRetryableError(Exception):+ pass+++class CapsuleCRMUntrustedURLError(Exception):+ """A pagination URL (resumed or upstream) pointed somewhere other than the Capsule CRM API."""+++def _validate_pagination_url(url: str) -> str:+ """Pin every authenticated request to the Capsule CRM API origin.++ Both resumed `next_url` values (loaded from Redis) and upstream `Link` header URLs are followed+ verbatim with the customer's bearer token. Validating the scheme, host, and `/api/v2/` path prefix+ keeps a poisoned resume state or a hostile upstream response from retargeting the request at another+ host and leaking the token (SSRF). Returns the URL unchanged when it is trusted.+ """+ parts = urlsplit(url)+ is_trusted = (+ parts.scheme == "https" and parts.netloc == CAPSULE_CRM_HOST and parts.path.startswith(CAPSULE_CRM_PATH_PREFIX)+ )+ if not is_trusted:+ raise CapsuleCRMUntrustedURLError(f"Refusing to follow pagination URL outside {CAPSULE_CRM_BASE_URL}/")+ return url+++class CapsuleCRMResumeConfig:+ # Absolute URL of the next page (from the RFC 5988 Link header). Capsule echoes the original+ # query params — perPage, embed and `since` — into this URL, so resuming from it preserves the+ # incremental window without recomputing it. None means "start from the first page".+ next_url: str | None = None+++def _get_headers(access_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {access_token}",+ "Accept": "application/json",+ }+++def _format_since_value(value: Any) -> str:+ """Format a cursor value as the ISO 8601 `Z`-suffixed UTC string Capsule's `since` expects."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def _clamp_future_value_to_now(value: Any) -> Any:+ """Cap a future datetime/date cursor at now.++ If bad source data pushes the `updatedAt` cursor past now, every later sync would ask Capsule+ for changes since a future date and get nothing back, wedging the table until real data catches+ up. Asking for changes newer than now is a no-op anyway, so clamping lets the sync self-heal.+ """+ now = datetime.now(UTC)+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return now if aware > now else value+ if isinstance(value, date):+ return now.date() if value > now.date() else value+ return value+++def _build_initial_url(+ config: CapsuleCRMEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> str:+ params: dict[str, Any] = {"perPage": PAGE_SIZE}+ if config.embed:+ params["embed"] = config.embed++ if config.supports_since and should_use_incremental_field and db_incremental_field_last_value is not None:+ params["since"] = _format_since_value(_clamp_future_value_to_now(db_incremental_field_last_value))++ return f"{CAPSULE_CRM_BASE_URL}{config.path}?{urlencode(params)}"+++@retry(+ retry=retry_if_exception_type((CapsuleCRMRetryableError, 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, headers: dict[str, str], logger: FilteringBoundLogger+) -> tuple[dict, str | None]:+ """Fetch one page, returning the parsed body and the next-page URL from the Link header.++ Capsule signals pagination via the RFC 5988 `Link` header (rel="next"), not the body, so the+ caller follows the returned URL rather than building its own.+ """+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise CapsuleCRMRetryableError(f"Capsule CRM API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Capsule CRM API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ next_url = response.links.get("next", {}).get("url")+ return response.json(), next_url+++def get_rows(+ access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CapsuleCRMResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict]]:+ config = CAPSULE_CRM_ENDPOINTS[endpoint]+ headers = _get_headers(access_token)+ # One session reused across every page so urllib3 keeps the connection alive. `redact_values`+ # masks the bearer token in logged URLs and captured request samples. `allow_redirects=False`+ # stops a redirect response from sending the bearer token to another host. `retry=Retry(total=0)`+ # disables the adapter's built-in retries — `_fetch_page` already retries 429/5xx via tenacity, so+ # the adapter default would stack a second retry layer.+ session = make_tracked_session(redact_values=(access_token,), allow_redirects=False, retry=Retry(total=0))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ # Resume state comes from Redis — validate before sending the token to it.+ url = _validate_pagination_url(resume.next_url)+ logger.debug(f"Capsule CRM: resuming from URL: {url}")+ else:+ url = _build_initial_url(config, should_use_incremental_field, db_incremental_field_last_value)++ while True:+ data, next_url = _fetch_page(session, url, headers, logger)+ items = data.get(config.data_key, [])+ if items:+ yield items++ if not next_url:+ break++ # The upstream-supplied next-page URL is followed verbatim with the bearer token — pin it to+ # the Capsule CRM API so a hostile response can't retarget the authenticated request.+ next_url = _validate_pagination_url(next_url)++ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last page+ # rather than skipping it — merge dedupes on the primary key.+ resumable_source_manager.save_state(CapsuleCRMResumeConfig(next_url=next_url))+ url = next_url+++def validate_credentials(access_token: str) -> bool:+ """Probe a cheap, always-available endpoint to confirm the access token is genuine."""+ url = f"{CAPSULE_CRM_BASE_URL}/users?perPage=1"+ try:+ session = make_tracked_session(redact_values=(access_token,), allow_redirects=False, retry=Retry(total=0))+ response = session.get(url, headers=_get_headers(access_token), timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++def capsule_crm_source(+ access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CapsuleCRMResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = CAPSULE_CRM_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ access_token=access_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Capsule does not document an ordering guarantee for `since`, but the ResumableSource+ # next-URL state (not the watermark) drives mid-sync resume, so the dominant interruption+ # path is order-independent. `asc` matches the framework's default incremental checkpointing.+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/settings.pynew file mode 100644index 000000000000..3d9029f4b3b3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/settings.py@@ -0,0 +1,109 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class CapsuleCRMEndpointConfig:+ name: str+ path: str+ # Wrapper key the list response nests its array under (e.g. {"parties": [...]}).+ data_key: str+ incremental_fields: list[IncrementalField]+ # True only when Capsule exposes the server-side `?since=<ISO8601>` change filter for this+ # list endpoint (parties, opportunities, kases). Every other endpoint is full refresh.+ supports_since: bool = False+ # Stable creation timestamp used for datetime partitioning. None for small metadata+ # endpoints with no creation timestamp / not worth partitioning.+ partition_key: Optional[str] = None+ # Comma-separated `embed` values folded into each request to pull related data in one round-trip.+ embed: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+++def _updated_at_incremental_fields() -> list[IncrementalField]:+ # `?since` filters by change date, so `updatedAt` is the only meaningful cursor.+ return [+ {+ "label": "updatedAt",+ "type": IncrementalFieldType.DateTime,+ "field": "updatedAt",+ "field_type": IncrementalFieldType.DateTime,+ },+ ]+++CAPSULE_CRM_ENDPOINTS: dict[str, CapsuleCRMEndpointConfig] = {+ "parties": CapsuleCRMEndpointConfig(+ name="parties",+ path="/parties",+ data_key="parties",+ supports_since=True,+ partition_key="createdAt",+ embed="tags,fields,organisation",+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "opportunities": CapsuleCRMEndpointConfig(+ name="opportunities",+ path="/opportunities",+ data_key="opportunities",+ supports_since=True,+ partition_key="createdAt",+ embed="tags,fields",+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "kases": CapsuleCRMEndpointConfig(+ name="kases",+ path="/kases",+ data_key="kases",+ supports_since=True,+ partition_key="createdAt",+ embed="tags,fields",+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "tasks": CapsuleCRMEndpointConfig(+ name="tasks",+ path="/tasks",+ data_key="tasks",+ partition_key="createdAt",+ incremental_fields=[],+ ),+ "users": CapsuleCRMEndpointConfig(+ name="users",+ path="/users",+ data_key="users",+ incremental_fields=[],+ ),+ "milestones": CapsuleCRMEndpointConfig(+ name="milestones",+ path="/milestones",+ data_key="milestones",+ incremental_fields=[],+ ),+ "pipelines": CapsuleCRMEndpointConfig(+ name="pipelines",+ path="/pipelines",+ data_key="pipelines",+ incremental_fields=[],+ ),+ "categories": CapsuleCRMEndpointConfig(+ name="categories",+ path="/categories",+ data_key="categories",+ incremental_fields=[],+ ),+ "lost_reasons": CapsuleCRMEndpointConfig(+ name="lost_reasons",+ path="/lostreasons",+ data_key="lostReasons",+ incremental_fields=[],+ ),+}++ENDPOINTS = tuple(CAPSULE_CRM_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CAPSULE_CRM_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/source.pyindex 73a901d186c2..bf495fbb1092 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/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.capsule_crm.capsule_crm import (+ CapsuleCRMResumeConfig,+ capsule_crm_source,+ validate_credentials as validate_capsule_crm_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.capsule_crm.settings import (+ CAPSULE_CRM_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+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 CapsuleCRMSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CapsuleCRMSource(SimpleSource[CapsuleCRMSourceConfig]):+class CapsuleCRMSource(ResumableSource[CapsuleCRMSourceConfig, CapsuleCRMResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CAPSULECRM@@ -24,7 +48,93 @@ class CapsuleCRMSource(SimpleSource[CapsuleCRMSourceConfig]):name=SchemaExternalDataSourceType.CAPSULE_CRM,category=DataWarehouseSourceCategory.CRM,label="Capsule CRM",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Capsule CRM Personal Access Token to automatically pull your Capsule CRM data into the PostHog Data warehouse.++You can create a Personal Access Token under **My Preferences → API Authentication Tokens** in your Capsule account.++The token inherits your user's permissions, so make sure your user can see the records you want to sync (parties, opportunities, projects, tasks).""",iconPath="/static/services/capsule_crm.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/capsule-crm",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token",+ label="Personal Access Token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.capsule_crm.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked token surfaces as a requests HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Match the stable status text and base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://api.capsulecrm.com": "Your Capsule CRM Personal Access Token is invalid or has been revoked. Create a new token in your Capsule account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.capsulecrm.com": "Your Capsule CRM user does not have permission to read this data. Check the user's permissions in Capsule, then reconnect.",+ }++ def get_schemas(+ self,+ config: CapsuleCRMSourceConfig,+ 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 = CAPSULE_CRM_ENDPOINTS[endpoint]+ has_incremental = endpoint_config.supports_since and bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ 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: CapsuleCRMSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_capsule_crm_credentials(config.access_token):+ return True, None++ return False, "Invalid Capsule CRM Personal Access Token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CapsuleCRMResumeConfig]:+ return ResumableSourceManager[CapsuleCRMResumeConfig](inputs, CapsuleCRMResumeConfig)++ def source_for_pipeline(+ self,+ config: CapsuleCRMSourceConfig,+ resumable_source_manager: ResumableSourceManager[CapsuleCRMResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return capsule_crm_source(+ access_token=config.access_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/tests/test_capsule_crm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/tests/test_capsule_crm.pynew file mode 100644index 000000000000..1696a45edcc0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/tests/test_capsule_crm.py@@ -0,0 +1,329 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.capsule_crm import capsule_crm+from products.warehouse_sources.backend.temporal.data_imports.sources.capsule_crm.capsule_crm import (+ CAPSULE_CRM_BASE_URL,+ CapsuleCRMResumeConfig,+ CapsuleCRMUntrustedURLError,+ _build_initial_url,+ _clamp_future_value_to_now,+ _format_since_value,+ _validate_pagination_url,+ capsule_crm_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.capsule_crm.settings import CAPSULE_CRM_ENDPOINTS+++class TestFormatSinceValue:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("string_passthrough", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),+ ]+ )+ def test_format_since_value(self, _name: str, value: object, expected: str) -> None:+ assert _format_since_value(value) == expected++ def test_no_offset_suffix(self) -> None:+ # Capsule expects a Z suffix, not the +00:00 offset isoformat() produces.+ assert "+00:00" not in _format_since_value(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))++ def test_non_utc_datetime_is_converted_to_utc(self) -> None:+ from datetime import timedelta, timezone++ value = datetime(2026, 3, 4, 12, 0, 0, tzinfo=timezone(timedelta(hours=5)))+ assert _format_since_value(value) == "2026-03-04T07:00:00Z"+++class TestClampFutureValueToNow:+ @freeze_time("2026-06-15T12:00:00Z")+ def test_future_datetime_is_clamped(self) -> None:+ assert _clamp_future_value_to_now(datetime(2027, 2, 5, 21, 46, 42, tzinfo=UTC)) == datetime(+ 2026, 6, 15, 12, 0, 0, tzinfo=UTC+ )++ @freeze_time("2026-06-15T12:00:00Z")+ def test_naive_future_datetime_is_clamped(self) -> None:+ assert _clamp_future_value_to_now(datetime(2027, 2, 5, 21, 46, 42)) == datetime(+ 2026, 6, 15, 12, 0, 0, tzinfo=UTC+ )++ @freeze_time("2026-06-15T12:00:00Z")+ def test_past_datetime_is_unchanged(self) -> None:+ value = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)+ assert _clamp_future_value_to_now(value) == value++ @freeze_time("2026-06-15T12:00:00Z")+ def test_future_date_is_clamped(self) -> None:+ assert _clamp_future_value_to_now(date(2027, 2, 5)) == date(2026, 6, 15)++ def test_string_passthrough(self) -> None:+ assert _clamp_future_value_to_now("some-cursor") == "some-cursor"+++class TestBuildInitialUrl:+ def test_full_refresh_url_has_no_since(self) -> None:+ url = _build_initial_url(+ CAPSULE_CRM_ENDPOINTS["users"], should_use_incremental_field=False, db_incremental_field_last_value=None+ )+ assert url == f"{CAPSULE_CRM_BASE_URL}/users?perPage=100"++ def test_incremental_endpoint_embeds_related_data(self) -> None:+ url = _build_initial_url(+ CAPSULE_CRM_ENDPOINTS["parties"], should_use_incremental_field=False, db_incremental_field_last_value=None+ )+ # embed values are folded in to reduce round-trips; urlencode escapes the comma.+ assert "perPage=100" in url+ assert "embed=tags%2Cfields%2Corganisation" in url+ assert "since" not in url++ def test_first_incremental_sync_omits_since(self) -> None:+ # No watermark yet -> pull full history, no `since` filter.+ url = _build_initial_url(+ CAPSULE_CRM_ENDPOINTS["opportunities"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )+ assert "since" not in url++ def test_incremental_sync_with_watermark_adds_since(self) -> None:+ url = _build_initial_url(+ CAPSULE_CRM_ENDPOINTS["opportunities"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ assert "since=2026-03-04T02%3A58%3A14Z" in url++ def test_since_ignored_for_full_refresh_only_endpoint(self) -> None:+ # tasks has no server-side `since` filter, so a watermark must not produce a `since` param.+ url = _build_initial_url(+ CAPSULE_CRM_ENDPOINTS["tasks"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ assert "since" not in url+++class _FakeResumableManager:+ def __init__(self, state: CapsuleCRMResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[CapsuleCRMResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> CapsuleCRMResumeConfig | None:+ return self._state++ def save_state(self, data: CapsuleCRMResumeConfig) -> None:+ self.saved.append(data)+++def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any], endpoint: str = "parties", **kwargs: Any+) -> list[dict]:+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> tuple[dict, str | None]:+ fetched.append(url)+ result = pages[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(capsule_crm, "_fetch_page", fake_fetch)+ rows: list[dict] = []+ for batch in get_rows(+ access_token="tok",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ manager.fetched = fetched # type: ignore[attr-defined]+ return rows+++class TestGetRows:+ def test_follows_link_header_pagination(self, monkeypatch: Any) -> None:+ page2 = f"{CAPSULE_CRM_BASE_URL}/parties?perPage=100&page=2"+ start = _build_initial_url(CAPSULE_CRM_ENDPOINTS["parties"], False, None)+ pages = {+ start: ({"parties": [{"id": 1}, {"id": 2}]}, page2),+ page2: ({"parties": [{"id": 3}]}, None),+ }+ rows = _collect(_FakeResumableManager(), monkeypatch, pages)+ assert rows == [{"id": 1}, {"id": 2}, {"id": 3}]++ def test_saves_resume_state_after_each_page_with_more(self, monkeypatch: Any) -> None:+ page2 = f"{CAPSULE_CRM_BASE_URL}/parties?perPage=100&page=2"+ start = _build_initial_url(CAPSULE_CRM_ENDPOINTS["parties"], False, None)+ pages = {+ start: ({"parties": [{"id": 1}]}, page2),+ page2: ({"parties": [{"id": 2}]}, None),+ }+ manager = _FakeResumableManager()+ _collect(manager, monkeypatch, pages)+ # State saved once (after page 1, which still had a next page); not after the final page.+ assert [s.next_url for s in manager.saved] == [page2]++ def test_resumes_from_saved_next_url(self, monkeypatch: Any) -> None:+ page2 = f"{CAPSULE_CRM_BASE_URL}/parties?perPage=100&page=2"+ start = _build_initial_url(CAPSULE_CRM_ENDPOINTS["parties"], False, None)+ pages = {+ # The starting URL must NOT be fetched when resuming.+ start: (Exception("should not fetch first page on resume"), None),+ page2: ({"parties": [{"id": 2}]}, None),+ }+ manager = _FakeResumableManager(CapsuleCRMResumeConfig(next_url=page2))+ rows = _collect(manager, monkeypatch, pages)+ assert rows == [{"id": 2}]+ assert manager.fetched == [page2] # type: ignore[attr-defined]++ def test_extracts_rows_from_endpoint_specific_wrapper_key(self, monkeypatch: Any) -> None:+ # lost_reasons nests its array under "lostReasons", not the endpoint name.+ start = _build_initial_url(CAPSULE_CRM_ENDPOINTS["lost_reasons"], False, None)+ pages = {start: ({"lostReasons": [{"id": 7, "name": "No budget"}]}, None)}+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, endpoint="lost_reasons")+ assert rows == [{"id": 7, "name": "No budget"}]++ def test_hostile_upstream_next_url_is_rejected(self, monkeypatch: Any) -> None:+ # An upstream Link header pointing at another host must abort before the bearer token is sent+ # there, and the poisoned URL must not be persisted as resume state.+ start = _build_initial_url(CAPSULE_CRM_ENDPOINTS["parties"], False, None)+ pages = {start: ({"parties": [{"id": 1}]}, "https://evil.example.com/api/v2/parties")}+ manager = _FakeResumableManager()+ with pytest.raises(CapsuleCRMUntrustedURLError):+ _collect(manager, monkeypatch, pages)+ assert manager.saved == []++ def test_hostile_resumed_next_url_is_rejected(self, monkeypatch: Any) -> None:+ # A poisoned resume state from Redis must never be requested with the bearer token.+ manager = _FakeResumableManager(CapsuleCRMResumeConfig(next_url="https://evil.example.com/api/v2/parties"))+ with pytest.raises(CapsuleCRMUntrustedURLError):+ _collect(manager, monkeypatch, {})+++class TestValidatePaginationUrl:+ @parameterized.expand(+ [+ ("first_page", f"{CAPSULE_CRM_BASE_URL}/parties?perPage=100"),+ ("next_page", f"{CAPSULE_CRM_BASE_URL}/parties?perPage=100&page=2"),+ ("other_endpoint", f"{CAPSULE_CRM_BASE_URL}/opportunities?page=3"),+ ]+ )+ def test_trusted_urls_pass_through(self, _name: str, url: str) -> None:+ assert _validate_pagination_url(url) == url++ @parameterized.expand(+ [+ ("foreign_host", "https://evil.example.com/api/v2/parties"),+ ("subdomain_lookalike", "https://api.capsulecrm.com.evil.example.com/api/v2/parties"),+ ("http_scheme", "http://api.capsulecrm.com/api/v2/parties"),+ ("wrong_path_prefix", "https://api.capsulecrm.com/internal/parties"),+ ("missing_path", "https://api.capsulecrm.com"),+ ("metadata_endpoint", "http://169.254.169.254/latest/meta-data/"),+ ]+ )+ def test_untrusted_urls_raise(self, _name: str, url: str) -> None:+ with pytest.raises(CapsuleCRMUntrustedURLError):+ _validate_pagination_url(url)+++class TestTokenRedaction:+ def test_validate_credentials_redacts_token_and_disables_redirects(self) -> None:+ session = MagicMock()+ response = MagicMock()+ response.status_code = 200+ session.get.return_value = response+ with patch.object(capsule_crm, "make_tracked_session", return_value=session) as make_session:+ validate_credentials("secret-token")+ assert make_session.call_args.kwargs["redact_values"] == ("secret-token",)+ assert make_session.call_args.kwargs["allow_redirects"] is False++ def test_get_rows_redacts_token_and_disables_redirects(self, monkeypatch: Any) -> None:+ session = MagicMock()+ make_session = MagicMock(return_value=session)+ monkeypatch.setattr(capsule_crm, "make_tracked_session", make_session)+ monkeypatch.setattr(capsule_crm, "_fetch_page", lambda *a, **k: ({"parties": []}, None))+ list(+ get_rows(+ access_token="secret-token",+ endpoint="parties",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert make_session.call_args.kwargs["redact_values"] == ("secret-token",)+ assert make_session.call_args.kwargs["allow_redirects"] is False+++class TestSourceResponse:+ @parameterized.expand(+ [+ ("parties", "createdAt"),+ ("opportunities", "createdAt"),+ ("kases", "createdAt"),+ ("tasks", "createdAt"),+ ]+ )+ def test_incremental_and_taskish_endpoints_partition_on_created_at(self, endpoint: str, partition_key: str) -> None:+ response = capsule_crm_source(+ access_token="tok", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [partition_key]+ assert response.sort_mode == "asc"++ @parameterized.expand([("users",), ("milestones",), ("pipelines",), ("categories",), ("lost_reasons",)])+ def test_metadata_endpoints_are_unpartitioned(self, endpoint: str) -> None:+ response = capsule_crm_source(+ access_token="tok", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()+ )+ assert response.primary_keys == ["id"]+ assert response.partition_mode is None+ assert response.partition_keys is None+++def _response_with(status_code: int) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ response._content = b"{}"+ response.url = "https://api.capsulecrm.com/api/v2/users"+ return response+++# The undecorated function behind tenacity's retry wrapper — call it to exercise status handling+# without the retry/backoff loop actually sleeping.+_fetch_page_unwrapped = capsule_crm._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class TestRetryableErrorClassification:+ @parameterized.expand([(429,), (500,), (503,)])+ def test_retryable_statuses_raise_retryable_error(self, status: int) -> None:+ session = MagicMock()+ session.get.return_value = _response_with(status)+ with pytest.raises(capsule_crm.CapsuleCRMRetryableError):+ _fetch_page_unwrapped(session, "https://api.capsulecrm.com/api/v2/users", {}, MagicMock())++ @parameterized.expand([(401,), (403,), (404,)])+ def test_client_errors_raise_for_status(self, status: int) -> None:+ session = MagicMock()+ session.get.return_value = _response_with(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "https://api.capsulecrm.com/api/v2/users", {}, MagicMock())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/tests/test_capsule_crm_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/tests/test_capsule_crm_source.pynew file mode 100644index 000000000000..490837a270a0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/tests/test_capsule_crm_source.py@@ -0,0 +1,132 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.capsule_crm.capsule_crm import (+ CapsuleCRMResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.capsule_crm.source import CapsuleCRMSource+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 CapsuleCRMSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestCapsuleCRMSource:+ def setup_method(self) -> None:+ self.source = CapsuleCRMSource()+ self.config = CapsuleCRMSourceConfig(access_token="tok")+ self.team_id = 123++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.CAPSULECRM++ def test_source_config_basics(self) -> None:+ config = self.source.get_source_config+ assert config.label == "Capsule CRM"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/capsule-crm"+ field_names = [f.name for f in config.fields]+ assert field_names == ["access_token"]+ field = config.fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ # The token is a secret so it must render as a password input.+ assert field.type == "password"+ assert field.required is True++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas is a static catalog with no I/O, so the public docs catalog can render.+ assert self.source.lists_tables_without_credentials is True+ assert len(self.source.get_documented_tables()) == len(self.source.get_schemas(self.config, self.team_id))++ @pytest.mark.parametrize(+ "endpoint,expected_incremental",+ [+ ("parties", True),+ ("opportunities", True),+ ("kases", True),+ ("tasks", False),+ ("users", False),+ ("milestones", False),+ ("pipelines", False),+ ("categories", False),+ ("lost_reasons", False),+ ],+ )+ def test_schema_incremental_support(self, endpoint: str, expected_incremental: bool) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert endpoint in schemas+ assert schemas[endpoint].supports_incremental is expected_incremental+ if expected_incremental:+ assert [f["field"] for f in schemas[endpoint].incremental_fields] == ["updatedAt"]+ else:+ assert schemas[endpoint].incremental_fields == []++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["parties", "tasks"])+ assert {s.name for s in schemas} == {"parties", "tasks"}++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert any(expected_key in key for key in self.source.get_non_retryable_errors())++ def test_validate_credentials_success(self) -> None:+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.capsule_crm.source.validate_capsule_crm_credentials",+ return_value=True,+ ):+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)++ def test_validate_credentials_failure(self) -> None:+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.capsule_crm.source.validate_capsule_crm_credentials",+ return_value=False,+ ):+ ok, message = self.source.validate_credentials(self.config, self.team_id)+ assert ok is False+ assert message is not None++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is CapsuleCRMResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "parties"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = mock.MagicMock()++ captured: dict[str, Any] = {}++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.capsule_crm.source.capsule_crm_source",+ side_effect=lambda **kwargs: captured.update(kwargs),+ ):+ self.source.source_for_pipeline(self.config, manager, inputs)++ assert captured["access_token"] == "tok"+ assert captured["endpoint"] == "parties"+ assert captured["resumable_source_manager"] is manager+ assert captured["should_use_incremental_field"] is True+ assert captured["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ def test_source_for_pipeline_drops_watermark_when_not_incremental(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "tasks"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ captured: dict[str, Any] = {}++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.capsule_crm.source.capsule_crm_source",+ side_effect=lambda **kwargs: captured.update(kwargs),+ ):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ # A non-incremental run must not pass a stale watermark through as a `since` filter.+ assert captured["db_incremental_field_last_value"] is Nonediff --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 9006cf8baac7..a3f9da603a9f 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@@ -573,7 +573,7 @@ class CannySourceConfig(config.Config):@config.configclass CapsuleCRMSourceConfig(config.Config):- pass+ access_token: str@config.config