: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 agilecrm import source (#66726)
Tom Owers9df32d76703e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 523914290290..b0bd2137ecb1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -45,6 +45,7 @@ the row lists both.| Source | Comm method | Primary library | Tracked transport || ------------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- || adroll | HTTP | requests | ✅ |+| agilecrm | HTTP | requests | ✅ || aircall | HTTP | requests | ✅ || airtable | HTTP | requests | ✅ || algolia | HTTP | requests | ✅ |@@ -293,7 +294,6 @@ doesn't conflict with concurrent PRs.- adobe_commerce- adp_workforce_now- adyen-- agilecrm- aha- ahrefs- airbytediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/agilecrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/agilecrm.pynew file mode 100644index 000000000000..4d4ebe1b927d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/agilecrm.py@@ -0,0 +1,170 @@+import re+import dataclasses+from collections.abc import Iterator+from typing import Any++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.batcher import Batcher+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.settings import (+ AGILECRM_ENDPOINTS,+ BASE_URL_TEMPLATE,+)+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++# A valid Agile CRM subdomain is a single DNS label: letters, digits and hyphens only. Constraining+# the domain to this pattern stops a malicious value (e.g. `evil.com#`) from retargeting the basic-auth+# credentials at an attacker-controlled host once it's interpolated into the base URL.+_DOMAIN_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9-]*$")++REQUEST_TIMEOUT_SECONDS = 60+++class AgileCRMRetryableError(Exception):+ pass+++class AgileCRMResumeConfig:+ # The cursor returned on the last item of the most recently yielded page. `None` starts at the+ # first page.+ cursor: str | None = None+++def _validate_domain(domain: str) -> str:+ cleaned = (domain or "").strip()+ if not _DOMAIN_RE.match(cleaned):+ raise ValueError(f"Invalid Agile CRM domain: {domain!r}. Use just the subdomain, e.g. 'acme'.")+ return cleaned+++def base_url(domain: str) -> str:+ return BASE_URL_TEMPLATE.format(domain=_validate_domain(domain))+++def _make_session(email: str, api_key: str) -> requests.Session:+ # Agile CRM authenticates with HTTP Basic: account email as username, API key as password.+ session = make_tracked_session(headers={"Accept": "application/json"}, redact_values=(api_key,))+ session.auth = (email, api_key)+ return session+++@retry(+ retry=retry_if_exception_type((AgileCRMRetryableError, 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, params: dict[str, Any], logger: FilteringBoundLogger+) -> list[dict[str, Any]]:+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise AgileCRMRetryableError(f"Agile CRM API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Agile CRM API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ data = response.json()+ # Known list endpoints return a bare JSON array. Tolerate an unexpected object by returning no rows+ # rather than crashing the sync.+ if isinstance(data, list):+ return data+ return []+++def get_rows(+ domain: str,+ email: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AgileCRMResumeConfig],+) -> Iterator[Any]:+ config = AGILECRM_ENDPOINTS[endpoint]+ url = f"{base_url(domain)}/{config.path}"+ session = _make_session(email, api_key)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor = resume.cursor if resume else None+ if cursor:+ logger.debug(f"Agile CRM: resuming {endpoint} from cursor={cursor}")++ while True:+ params: dict[str, Any] = {"page_size": config.page_size}+ if cursor:+ params["cursor"] = cursor++ items = _fetch_page(session, url, params, logger)+ if not items:+ break++ # Agile CRM signals the next page via a `cursor` field on the *last* item of the current page.+ last_item = items[-1]+ next_cursor = last_item.get("cursor") if isinstance(last_item, dict) else None+ # The cursor is navigation metadata, not data. Strip it from the last item so it isn't written+ # to the warehouse as a sparse `cursor` column that only the final row of each page carries.+ if isinstance(last_item, dict) and "cursor" in last_item:+ items = [*items[:-1], {k: v for k, v in last_item.items() if k != "cursor"}]++ for item in items:+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ # Save AFTER yielding so a crash re-yields the last page (merge dedupes on the primary+ # key) rather than skipping it. Only persist when another page follows.+ if next_cursor:+ resumable_source_manager.save_state(AgileCRMResumeConfig(cursor=next_cursor))++ # No cursor, or a short page, means we've reached the end.+ if not next_cursor or len(items) < config.page_size:+ break++ cursor = next_cursor++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def validate_credentials(domain: str, email: str, api_key: str) -> bool:+ try:+ url = f"{base_url(domain)}/contacts"+ except ValueError:+ return False++ try:+ response = _make_session(email, api_key).get(url, params={"page_size": 1}, timeout=REQUEST_TIMEOUT_SECONDS)+ return response.status_code == 200+ except Exception:+ return False+++def agilecrm_source(+ domain: str,+ email: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AgileCRMResumeConfig],+) -> SourceResponse:+ endpoint_config = AGILECRM_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ domain=domain,+ email=email,+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=endpoint_config.primary_keys,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/canonical_descriptions.pynew file mode 100644index 000000000000..962f1c686212--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/canonical_descriptions.py@@ -0,0 +1,79 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Curated, documentation-sourced descriptions for Agile CRM's well-known tables. Keyed by the schema+# name returned by `get_schemas` (matching the `ENDPOINTS` catalog). Partial coverage is fine — any+# missing table or column falls back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "contacts": {+ "description": "People stored in Agile CRM (contacts of type PERSON), with their properties, tags and score.",+ "docs_url": "https://github.com/agilecrm/rest-api#contacts-api",+ "columns": {+ "id": "Unique identifier for the contact.",+ "type": "Contact type — PERSON for contacts.",+ "created_time": "Unix epoch timestamp of when the contact was created.",+ "updated_time": "Unix epoch timestamp of when the contact was last updated.",+ "star_value": "Star rating (0-5) assigned to the contact.",+ "lead_score": "Lead score assigned to the contact.",+ "tags": "Tags applied to the contact.",+ "properties": "Custom and system properties (name, email, phone, etc.) of the contact.",+ "owner_id": "Identifier of the Agile CRM user who owns the contact.",+ },+ },+ "companies": {+ "description": "Companies stored in Agile CRM (contacts of type COMPANY).",+ "docs_url": "https://github.com/agilecrm/rest-api#contacts-api",+ "columns": {+ "id": "Unique identifier for the company.",+ "type": "Contact type — COMPANY for companies.",+ "created_time": "Unix epoch timestamp of when the company was created.",+ "updated_time": "Unix epoch timestamp of when the company was last updated.",+ "tags": "Tags applied to the company.",+ "properties": "Custom and system properties of the company.",+ "owner_id": "Identifier of the Agile CRM user who owns the company.",+ },+ },+ "deals": {+ "description": "Deals (opportunities) tracked in the Agile CRM sales pipeline.",+ "docs_url": "https://github.com/agilecrm/rest-api#deals-api",+ "columns": {+ "id": "Unique identifier for the deal.",+ "name": "Name of the deal.",+ "expected_value": "Expected monetary value of the deal.",+ "probability": "Probability (percentage) of the deal closing.",+ "milestone": "Current milestone (stage) of the deal in its pipeline.",+ "pipeline_id": "Identifier of the pipeline the deal belongs to.",+ "close_date": "Unix epoch timestamp of the deal's expected close date.",+ "created_time": "Unix epoch timestamp of when the deal was created.",+ "owner_id": "Identifier of the Agile CRM user who owns the deal.",+ },+ },+ "tasks": {+ "description": "Tasks created in Agile CRM and assigned to users or contacts.",+ "docs_url": "https://github.com/agilecrm/rest-api#tasks-api",+ "columns": {+ "id": "Unique identifier for the task.",+ "subject": "Subject / title of the task.",+ "type": "Task type (e.g. CALL, EMAIL, FOLLOW_UP).",+ "priority_type": "Priority of the task (HIGH, NORMAL, LOW).",+ "status": "Status of the task (e.g. YET_TO_START, IN_PROGRESS, COMPLETED).",+ "due": "Unix epoch timestamp of the task's due date.",+ "created_time": "Unix epoch timestamp of when the task was created.",+ "owner_id": "Identifier of the Agile CRM user who owns the task.",+ },+ },+ "events": {+ "description": "Calendar events scheduled in Agile CRM.",+ "docs_url": "https://github.com/agilecrm/rest-api#events-api",+ "columns": {+ "id": "Unique identifier for the event.",+ "title": "Title of the event.",+ "start": "Unix epoch timestamp of the event start time.",+ "end": "Unix epoch timestamp of the event end time.",+ "is_event_starts_today": "Whether the event starts today.",+ "color": "Display color of the event.",+ "created_time": "Unix epoch timestamp of when the event was created.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/settings.pynew file mode 100644index 000000000000..9fc55094fde0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/settings.py@@ -0,0 +1,41 @@+from dataclasses import dataclass, field++# Per-account base URL. `{domain}` is the customer's Agile CRM subdomain+# (e.g. `acme` for https://acme.agilecrm.com). HTTPS only.+BASE_URL_TEMPLATE = "https://{domain}.agilecrm.com/dev/api"++# Agile CRM caps list responses and recommends a page size around 200 to avoid timeouts.+DEFAULT_PAGE_SIZE = 200+++@dataclass+class AgileCRMEndpointConfig:+ name: str+ # Path appended to the per-account base URL (no leading slash).+ path: str+ # Dotted path to the list inside the response body, or None when the body *is* the list.+ # Agile CRM list endpoints return a bare JSON array, so this is None for all known endpoints.+ data_selector: str | None = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ page_size: int = DEFAULT_PAGE_SIZE+ should_sync_default: bool = True+++# Agile CRM exposes a plain REST/JSON API with cursor pagination (page_size + a `cursor`+# returned on the last item of each page). It documents no server-side updated-since/created-after+# filter on any list endpoint, so every table is full refresh only.+AGILECRM_ENDPOINTS: dict[str, AgileCRMEndpointConfig] = {+ # Contacts of type PERSON.+ "contacts": AgileCRMEndpointConfig(name="contacts", path="contacts"),+ # Contacts of type COMPANY (Agile CRM stores companies in the same backing store as contacts+ # but exposes them through a dedicated list endpoint).+ "companies": AgileCRMEndpointConfig(name="companies", path="contacts/companies/list"),+ # Deals / opportunities.+ "deals": AgileCRMEndpointConfig(name="deals", path="opportunity"),+ # Tasks.+ "tasks": AgileCRMEndpointConfig(name="tasks", path="tasks"),+ # Calendar events.+ "events": AgileCRMEndpointConfig(name="events", path="events"),+}++ENDPOINTS = tuple(AGILECRM_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/source.pyindex da2d47e6dd57..de0749778e8c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/source.py@@ -1,30 +1,158 @@-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.agilecrm.agilecrm import (+ AgileCRMResumeConfig,+ agilecrm_source,+ validate_credentials as validate_agilecrm_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.settings import ENDPOINTS+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 AgileCRMSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AgileCRMSource(SimpleSource[AgileCRMSourceConfig]):+class AgileCRMSource(ResumableSource[AgileCRMSourceConfig, AgileCRMResumeConfig]):+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to+ # surface in the public docs without credentials.+ lists_tables_without_credentials = True+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AGILECRM+ @property+ def connection_host_fields(self) -> list[str]:+ # The API key is sent to `{domain}.agilecrm.com`, so retargeting `domain` must re-require secrets.+ return ["domain"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.AGILE_CRM,category=DataWarehouseSourceCategory.CRM,label="AgileCRM",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Agile CRM credentials to pull your CRM data into the PostHog Data warehouse.++Find your API key under **Admin Settings → Developers & API** in your Agile CRM account. Authenticate with the email address you log in with and that API key.++Your domain is the subdomain of your Agile CRM URL — for `https://acme.agilecrm.com` the domain is `acme`.+""",iconPath="/static/services/agilecrm.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/agilecrm",unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="domain",+ label="Domain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="acme",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="email",+ label="Email",+ type=SourceFieldInputConfigType.EMAIL,+ required=True,+ placeholder="[email protected]",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # Bad / revoked credentials surface as an HTTPError from `raise_for_status()`. Retrying can+ # never fix a credential problem. The per-request path varies, so match the stable status text.+ "401 Client Error: Unauthorized": "Your Agile CRM email or API key is invalid. Generate a new API key under Admin Settings → Developers & API, then reconnect.",+ "403 Client Error: Forbidden": "Your Agile CRM account does not have permission to access this data. Check your API access settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: AgileCRMSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Agile CRM documents no server-side updated-since/created-after filter on any list endpoint,+ # so every table is full refresh only.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: AgileCRMSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_agilecrm_credentials(config.domain, config.email, config.api_key):+ return True, None++ return False, "Invalid Agile CRM credentials. Check your domain, email, and API key."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AgileCRMResumeConfig]:+ return ResumableSourceManager[AgileCRMResumeConfig](inputs, AgileCRMResumeConfig)++ def source_for_pipeline(+ self,+ config: AgileCRMSourceConfig,+ resumable_source_manager: ResumableSourceManager[AgileCRMResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return agilecrm_source(+ domain=config.domain,+ email=config.email,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.pynew file mode 100644index 000000000000..6f9d026f65a2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.py@@ -0,0 +1,169 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm import agilecrm+from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.agilecrm import (+ AgileCRMResumeConfig,+ base_url,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.settings import AGILECRM_ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: AgileCRMResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[AgileCRMResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> AgileCRMResumeConfig | None:+ return self._state++ def save_state(self, data: AgileCRMResumeConfig) -> None:+ self.saved.append(data)+++def _collect_rows(+ monkeypatch: Any,+ pages: list[list[dict[str, Any]]],+ manager: _FakeResumableManager,+ endpoint: str = "contacts",+) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+ """Drive get_rows against a queue of fake pages, returning (rows, recorded request params)."""+ recorded_params: list[dict[str, Any]] = []+ queue = list(pages)++ def fake_fetch(session: Any, url: str, params: dict[str, Any], logger: Any) -> list[dict[str, Any]]:+ recorded_params.append(dict(params))+ return queue.pop(0) if queue else []++ monkeypatch.setattr(agilecrm, "_fetch_page", fake_fetch)+ monkeypatch.setattr(agilecrm, "_make_session", lambda email, api_key: MagicMock())++ rows: list[dict[str, Any]] = []+ for table in get_rows(+ domain="acme",+ email="[email protected]",+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(table.to_pylist())+ return rows, recorded_params+++class TestBaseUrl:+ @parameterized.expand(+ [+ ("simple", "acme", "https://acme.agilecrm.com/dev/api"),+ ("with_hyphen", "my-company", "https://my-company.agilecrm.com/dev/api"),+ ("trims_whitespace", " acme ", "https://acme.agilecrm.com/dev/api"),+ ]+ )+ def test_valid_domains(self, _name: str, domain: str, expected: str) -> None:+ assert base_url(domain) == expected++ @parameterized.expand(+ [+ ("empty", ""),+ # A `#`/`/`/`.` in the domain could break out of the agilecrm.com host and retarget the+ # basic-auth credentials at an attacker-controlled server, so these must be rejected.+ ("fragment_breakout", "evil.com#"),+ ("slash_breakout", "evil.com/"),+ ("dotted", "evil.com"),+ ("at_breakout", "[email protected]"),+ ]+ )+ def test_invalid_domains_rejected(self, _name: str, domain: str) -> None:+ with pytest.raises(ValueError):+ base_url(domain)+++class TestPagination:+ def test_paginates_until_short_page(self, monkeypatch: Any) -> None:+ page_size = AGILECRM_ENDPOINTS["contacts"].page_size+ first_page = [{"id": i} for i in range(page_size - 1)] + [{"id": page_size, "cursor": "CURSOR1"}]+ second_page = [{"id": 9001}] # short page -> terminal+ manager = _FakeResumableManager()++ rows, params = _collect_rows(monkeypatch, [first_page, second_page], manager)++ assert len(rows) == page_size + 1+ # First request has no cursor; the second carries the cursor from the last item of page one.+ assert "cursor" not in params[0]+ assert params[1]["cursor"] == "CURSOR1"+ # The cursor is navigation metadata and must never leak into the warehouse rows.+ assert all("cursor" not in row for row in rows)++ def test_stops_when_full_page_has_no_cursor(self, monkeypatch: Any) -> None:+ # A full page whose last item carries no cursor must terminate rather than loop forever.+ page_size = AGILECRM_ENDPOINTS["contacts"].page_size+ full_page_no_cursor = [{"id": i} for i in range(page_size)]+ manager = _FakeResumableManager()++ rows, params = _collect_rows(monkeypatch, [full_page_no_cursor, [{"id": 1}]], manager)++ assert len(rows) == page_size+ assert len(params) == 1++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, params = _collect_rows(monkeypatch, [[]], manager)+ assert rows == []+ assert len(params) == 1++ def test_resume_uses_saved_cursor(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(AgileCRMResumeConfig(cursor="SAVED"))+ rows, params = _collect_rows(monkeypatch, [[{"id": 1}]], manager)++ assert rows == [{"id": 1}]+ assert params[0]["cursor"] == "SAVED"++ def test_saves_state_after_yielding_batch(self, monkeypatch: Any) -> None:+ # The Batcher flushes once 2000 rows accumulate; state must be saved (with the next cursor)+ # only after that batch is yielded, so a crash re-yields the last page rather than skipping it.+ big_first_page = [{"id": i} for i in range(2499)] + [{"id": 2500, "cursor": "NEXT"}]+ manager = _FakeResumableManager()++ rows, _ = _collect_rows(monkeypatch, [big_first_page, [{"id": 1}]], manager)++ assert manager.saved+ assert manager.saved[0].cursor == "NEXT"+ # The cursor is navigation metadata and must never leak into the warehouse rows.+ assert all("cursor" not in row for row in rows)+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_status_maps_to_bool(self, _name: str, status_code: int, expected: bool) -> None:+ response = MagicMock()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response++ with patch.object(agilecrm, "_make_session", lambda email, api_key: session):+ assert validate_credentials("acme", "[email protected]", "key") is expected++ def test_invalid_domain_short_circuits_to_false(self, monkeypatch: Any) -> None:+ # An invalid domain must fail before any request is attempted.+ session = MagicMock()+ monkeypatch.setattr(agilecrm, "_make_session", lambda email, api_key: session)++ assert validate_credentials("evil.com#", "[email protected]", "key") is False+ session.get.assert_not_called()++ def test_network_error_is_false(self, monkeypatch: Any) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ monkeypatch.setattr(agilecrm, "_make_session", lambda email, api_key: session)++ assert validate_credentials("acme", "[email protected]", "key") is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm_source.pynew file mode 100644index 000000000000..164f1e21c32c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm_source.py@@ -0,0 +1,131 @@+from typing import Any++from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm import source as agilecrm_source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.agilecrm import AgileCRMResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.source import AgileCRMSource+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 AgileCRMSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config() -> AgileCRMSourceConfig:+ return AgileCRMSourceConfig(domain="acme", email="[email protected]", api_key="key")+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert AgileCRMSource().source_type == ExternalDataSourceType.AGILECRM++ def test_get_source_config_basics(self) -> None:+ config = AgileCRMSource().get_source_config+ assert config.category == DataWarehouseSourceCategory.CRM+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/agilecrm"+ # Ships hidden behind unreleasedSource for now, labelled alpha.+ assert config.unreleasedSource is True++ def test_fields_are_domain_email_api_key(self) -> None:+ fields = AgileCRMSource().get_source_config.fields+ assert [f.name for f in fields] == ["domain", "email", "api_key"]+ by_name = {f.name: f for f in fields}+ api_key, domain, email = by_name["api_key"], by_name["domain"], by_name["email"]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert isinstance(domain, SourceFieldInputConfig)+ assert isinstance(email, SourceFieldInputConfig)+ assert api_key.secret is True+ assert domain.secret is False+ assert email.secret is False++ def test_domain_is_a_connection_host_field(self) -> None:+ # Retargeting the domain (where the API key is sent) must re-require secrets.+ assert AgileCRMSource().connection_host_fields == ["domain"]+++class TestSchemas:+ def test_lists_all_endpoints_full_refresh_only(self) -> None:+ schemas = AgileCRMSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ for schema in schemas:+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_names_filter(self) -> None:+ schemas = AgileCRMSource().get_schemas(_config(), team_id=1, names=["contacts"])+ assert [s.name for s in schemas] == ["contacts"]++ def test_lists_tables_without_credentials(self) -> None:+ assert AgileCRMSource.lists_tables_without_credentials is True++ def test_documented_tables_render_from_static_catalog(self) -> None:+ tables = AgileCRMSource().get_documented_tables()+ names = {t["name"] for t in tables}+ assert set(ENDPOINTS).issubset(names)+ contacts = next(t for t in tables if t["name"] == "contacts")+ assert "Full refresh" in contacts["sync_methods"]+ # Canonical descriptions should flow through to the docs.+ assert contacts["description"]+++class TestCanonicalDescriptions:+ def test_covers_known_endpoints(self) -> None:+ descriptions = AgileCRMSource().get_canonical_descriptions()+ assert "contacts" in descriptions+ assert descriptions["contacts"]["columns"]["id"]+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://acme.agilecrm.com/dev/api/contacts"),+ ("forbidden", "403 Client Error: Forbidden for url: https://acme.agilecrm.com/dev/api/opportunity"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = AgileCRMSource().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"),+ ("timeout", "Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = AgileCRMSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestValidateCredentials:+ def test_success(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(agilecrm_source_module, "validate_agilecrm_credentials", lambda *a, **k: True)+ ok, error = AgileCRMSource().validate_credentials(_config(), team_id=1)+ assert ok is True+ assert error is None++ def test_failure(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(agilecrm_source_module, "validate_agilecrm_credentials", lambda *a, **k: False)+ ok, error = AgileCRMSource().validate_credentials(_config(), team_id=1)+ assert ok is False+ assert error is not None+++class TestPipelinePlumbing:+ def test_resumable_manager_bound_to_resume_config(self) -> None:+ manager = AgileCRMSource().get_resumable_source_manager(MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is AgileCRMResumeConfig++ def test_source_for_pipeline_passes_endpoint_and_primary_keys(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "contacts"+ response = AgileCRMSource().source_for_pipeline(_config(), MagicMock(), inputs)+ assert response.name == "contacts"+ assert response.primary_keys == ["id"]diff --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 bbf317933864..616e38c604bd 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@@ -163,7 +163,9 @@ class AdyenSourceConfig(config.Config):@config.configclass AgileCRMSourceConfig(config.Config):- pass+ domain: str+ email: str+ api_key: str@config.config