: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 membrain import source (#107244)
Tom Owers9969102fa5f8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex cb669cfae023..7caeec4d515a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -457,6 +457,7 @@ the row lists both.| matomo | HTTP | requests | ✅ || maxio | HTTP | requests + `rest_source.RESTClient` | ✅ || medusa | HTTP | requests + `rest_source.RESTClient` | ✅ |+| membrain | HTTP | requests + `rest_source.RESTClient` | ✅ || mention | HTTP | requests | ✅ || mercury | HTTP | requests + `rest_source.RESTClient` | ✅ || meta_ads | HTTP | requests | ✅ |@@ -1187,7 +1188,6 @@ doesn't conflict with concurrent PRs.- mastodon- meetup- memberful-- membrain- mendeley- mercado_ads- mercado_pagodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/membrain.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/membrain.pyindex 4c2509ebc5ba..cd67929708c3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/membrain.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/membrain.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass MembrainSourceConfig(config.Config):- pass+ api_key: str+ subdomain: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/canonical_descriptions.pynew file mode 100644index 000000000000..29a100493b41--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/canonical_descriptions.py@@ -0,0 +1,156 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://www.membrain.com/developers/api-documentation"++_AUDIT_COLUMNS = {+ "Id": "Unique identifier (GUID).",+ "CreatedById": "GUID of the user who created the record.",+ "CreatedByName": "Name of the user who created the record.",+ "CreatedDate": "Timestamp when the record was created.",+ "ChangedById": "GUID of the user who last changed the record.",+ "ChangedByName": "Name of the user who last changed the record.",+ "ChangedDate": "Timestamp when the record was last changed.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "companies": {+ "description": "Companies (accounts) in the Membrain CRM, including deleted ones.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_AUDIT_COLUMNS,+ "Name": "Company name.",+ "City": "City of the company's address.",+ "CountryName": "Country of the company's address.",+ "CountryCode": "ISO country code of the company's address.",+ "EmailAddress": "Company email address.",+ },+ },+ "contacts": {+ "description": "Contacts (people) in the Membrain CRM, including deleted and retired ones. Custom field values appear as CustomField<GUID> columns.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_AUDIT_COLUMNS,+ "Name": "Contact's full name.",+ "EmailAddress": "Contact's email address.",+ "CompanyId": "GUID of the company the contact belongs to.",+ "CompanyName": "Name of the company the contact belongs to.",+ },+ },+ "prospects": {+ "description": "Prospecting-pipeline items. A prospect's human-readable key has the form P-{n}.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_AUDIT_COLUMNS,+ "Name": "Prospect name.",+ "CompanyId": "GUID of the related company.",+ "CompanyName": "Name of the related company.",+ "Deleted": "Whether the prospect has been deleted.",+ "DeletedDate": "Timestamp when the prospect was deleted.",+ },+ },+ "opportunities": {+ "description": "Sales projects (opportunities). A sales project's human-readable key has the form SP-{n}.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_AUDIT_COLUMNS,+ "Name": "Sales project name.",+ "CompanyId": "GUID of the related company.",+ "CompanyName": "Name of the related company.",+ "EstimatedClosingDate": "Estimated closing date of the sales project.",+ "LostComment": "Comment recorded when the sales project was lost.",+ "LostReasonId": "GUID of the recorded lost reason.",+ "LostReasonName": "Name of the recorded lost reason.",+ },+ },+ "account_growth_items": {+ "description": "Account growth projects. An account growth project's human-readable key has the form AGP-{n}.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_AUDIT_COLUMNS,+ "Name": "Account growth project name.",+ "CompanyId": "GUID of the related company.",+ "CompanyName": "Name of the related company.",+ "OwnerId": "GUID of the owning user.",+ "OwnerName": "Name of the owning user.",+ "ProcessId": "GUID of the account growth process the project runs in.",+ "ProcessCurrentStageId": "GUID of the project's current process stage.",+ "ProcessCurrentStageName": "Name of the project's current process stage.",+ },+ },+ "tickets": {+ "description": "Support or service tickets. A ticket's human-readable key has the form T-{n}.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_AUDIT_COLUMNS,+ "Name": "Ticket name.",+ "Description": "Ticket description.",+ "CompanyId": "GUID of the related company.",+ "CompanyName": "Name of the related company.",+ "OwnerId": "GUID of the owning user.",+ "OwnerName": "Name of the owning user.",+ "Status": "Ticket status (New, Open, Pending, Resolved, or Archived).",+ "Priority": "Ticket priority (Highest, High, Medium, Low, or Lowest).",+ },+ },+ "activities": {+ "description": "Activities: tasks, appointments, calls, notes, and emails. Unset dates use the sentinel value 1753-01-01 00:00:00.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_AUDIT_COLUMNS,+ "ActivityTypeId": "GUID of the activity type.",+ "ActivityTypeName": "Name of the activity type.",+ "Contents": "Text contents of the activity.",+ "Completed": "Whether the activity has been completed.",+ "OrganizerId": "GUID of the organizing user.",+ "Deadline": "Deadline of the activity.",+ },+ },+ "users": {+ "description": "Membrain users. Every user is also a contact; additional properties such as title and phone number live on the contacts table.",+ "docs_url": _DOCS_URL,+ "columns": {+ "Id": "Unique identifier (GUID).",+ "Name": "User's full name.",+ "CompanyId": "GUID of the user's company.",+ "CompanyName": "Name of the user's company.",+ "EmailAddress": "User's email address.",+ "UserInterfaceLanguage": "Language the user's Membrain interface uses.",+ "TimeZone": "User's time zone.",+ "SalesTeams": "Sales teams the user belongs to, as a list of {Id, Name} objects.",+ },+ },+ "roles": {+ "description": "Roles that can be assigned to a stakeholder on a project (for example Accountable or Approver).",+ "docs_url": _DOCS_URL,+ "columns": {+ "Id": "Unique identifier (GUID).",+ "Name": "Role name.",+ },+ },+ "custom_fields": {+ "description": "Custom field definitions across entity types. One row per definition, with EntityType naming the entity the field belongs to.",+ "docs_url": _DOCS_URL,+ "columns": {+ "Id": "Unique identifier (GUID) of the field definition. Matches the GUID in CustomField<GUID> columns on entity tables.",+ "Name": "Display name of the custom field.",+ "Type": "Field type (for example Text, Date, or SingleSelect).",+ "Options": "For select types, the selectable options as a list of {Id, Name} objects.",+ "EntityType": "Entity the field belongs to (for example company, contact, or user). Added by PostHog from the response's per-entity grouping.",+ },+ },+ "products": {+ "description": "Products that can be attached to sales projects.",+ "docs_url": _DOCS_URL,+ "columns": {+ **_AUDIT_COLUMNS,+ "Name": "Product name.",+ "Description": "Product description.",+ "Price": "Product price.",+ "PriceCurrency": "Currency of the product price.",+ "PriceType": "Pricing model of the product.",+ "Cost": "Product cost.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/membrain.py b/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/membrain.pynew file mode 100644index 000000000000..8362aadf18f7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/membrain.py@@ -0,0 +1,293 @@+from collections.abc import Iterator+from typing import Any, Optional++from requests import Request, Response++from posthog.dataclasses import frozen++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpoint+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.membrain.settings import MEMBRAIN_ENDPOINTS++PAGE_START = 0+PROBE_TIMEOUT_SECONDS = 10.0+CUSTOM_FIELDS_TIMEOUT_SECONDS = 60.0+REQUEST_TIMEOUT_SECONDS: tuple[float, float] = (10.0, 60.0)++# The reference's per-entity custom-field arrays are keyed `<entity>CustomFields`+# (companyCustomFields, contactCustomFields, userCustomFields, ...).+_CUSTOM_FIELDS_KEY_SUFFIX = "CustomFields"+++@frozen+class MembrainResumeConfig:+ # Row offset of the next page (the `to` of the last page yielded). Offset pagination is+ # deterministic under the explicit sort we request, so a crashed sync resumes from here.+ next_from: int = PAGE_START+++def base_url(subdomain: str) -> str:+ """Per-account hostname: every Membrain instance lives on its own subdomain."""+ return f"https://{subdomain}.membrain.com/API/v2"+++def _auth_headers(api_key: str) -> dict[str, str]:+ # Membrain accepts the key either as an `?APIKey=` query param or an `APIKey` request+ # header. The header keeps the key out of logged URLs.+ return {"APIKey": api_key, "Accept": "application/json"}+++class MembrainPaginator(BasePaginator):+ """Offset paginator for Membrain's `{count, from, to, items}` envelope.++ `to` is the end of the returned window and doubles as the next request's `From`; the last+ page is the one where `to` reaches `count`. All three counters arrive as JSON strings.+ """++ def __init__(self) -> None:+ super().__init__()+ self._current_from = PAGE_START+ self._next_from: Optional[int] = None++ def init_request(self, request: Request) -> None:+ # Honour a seeded resume offset on the first request; a fresh run starts unparametered+ # at offset 0.+ if self._current_from != PAGE_START:+ if request.params is None:+ request.params = {}+ request.params["From"] = self._current_from++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ self._next_from = None+ body = response.json()++ # A malformed envelope must fail loud rather than silently truncate a full-refresh sync+ # partway through: without `count`/`to` there is no way to tell a genuine last page from+ # a mid-sync response the API failed to fill in correctly.+ if not isinstance(body, dict) or "count" not in body or "to" not in body:+ raise ValueError(f"Unexpected Membrain pagination response: missing count or to (body: {body!r})")++ # int() raising on a non-numeric counter is deliberate: a malformed envelope must fail+ # loud rather than silently truncate the sync at page one.+ count = int(body["count"])+ to = int(body["to"])++ # `to >= count` is the documented end of the set; a `to` that did not advance past the+ # offset we requested would otherwise refetch the same window forever.+ if to >= count or to <= self._current_from:+ self._has_next_page = False+ return++ self._has_next_page = True+ self._next_from = to++ def update_request(self, request: Request) -> None:+ if self._next_from is None:+ return+ self._current_from = self._next_from+ if request.params is None:+ request.params = {}+ request.params["From"] = self._current_from++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if self._has_next_page and self._next_from is not None:+ return {"next_from": self._next_from}+ return None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ next_from = state.get("next_from")+ if next_from is not None:+ self._current_from = int(next_from)+ self._has_next_page = True+++def _custom_fields_rows(api_key: str, subdomain: str) -> Iterator[list[dict[str, Any]]]:+ """Flatten `/customFields/` into one row per field definition with an `EntityType` column."""+ # capture=False, matching the main sync client and the credential probe: custom field+ # options are admin-authored free text, not something the generic scrubber is guaranteed to+ # catch.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False)+ response = session.get(+ f"{base_url(subdomain)}/customFields/",+ headers=_auth_headers(api_key),+ timeout=CUSTOM_FIELDS_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ body = response.json()++ if not isinstance(body, dict) or not any(key.endswith(_CUSTOM_FIELDS_KEY_SUFFIX) for key in body):+ # Membrain reports some failures as HTTP 200 with an error body, so an unexpected shape+ # must fail loud rather than sync zero rows.+ keys = sorted(body.keys())[:20] if isinstance(body, dict) else type(body).__name__+ raise ValueError(f"Unexpected Membrain customFields response shape (body keys: {keys})")++ rows: list[dict[str, Any]] = []+ for key, definitions in body.items():+ if not key.endswith(_CUSTOM_FIELDS_KEY_SUFFIX) or not isinstance(definitions, list):+ continue+ entity_type = key.removesuffix(_CUSTOM_FIELDS_KEY_SUFFIX)+ for definition in definitions:+ rows.append({**definition, "EntityType": entity_type})++ yield rows+++def membrain_source(+ api_key: str,+ subdomain: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[MembrainResumeConfig],+) -> SourceResponse:+ config = MEMBRAIN_ENDPOINTS[endpoint]++ if endpoint == "custom_fields":+ return SourceResponse(+ name=endpoint,+ items=lambda: _custom_fields_rows(api_key, subdomain),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )++ endpoint_config: Endpoint+ if config.paged:+ params: dict[str, Any] = dict(config.extra_params)+ if config.supports_sort_by:+ # An explicit stable sort keeps offset pages from drifting as rows are written+ # mid-sync (activities otherwise default to Date DESC, companies and contacts to+ # Name ASC).+ params["SortBy"] = "CreatedDate ASC"+ endpoint_config = {+ "path": config.path,+ "params": params,+ "paginator": MembrainPaginator(),+ # A 200 body without `items` (e.g. Membrain's `{"error": ...}` failure shape) is an+ # auth or shape failure. Fail loud rather than silently syncing zero rows.+ "data_selector": "items",+ "data_selector_required": True,+ }+ else:+ endpoint_config = {+ "path": config.path,+ "paginator": SinglePagePaginator(),+ # Bare-array endpoint: a non-list 200 body means the shape changed or the request+ # failed, so fail loud instead of syncing a stray object as a row.+ "data_selector_required": True,+ }++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": base_url(subdomain),+ "headers": {"Accept": "application/json"},+ # The framework redacts the key from logged URLs, headers and raised error messages.+ "auth": {"type": "api_key", "api_key": api_key, "name": "APIKey", "location": "header"},+ # Defense-in-depth: a 30x must not replay the credentialed APIKey header off-host.+ "allow_redirects": False,+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ # CRM rows carry customer emails and free-text notes the name-based sample scrubbers+ # aren't guaranteed to catch; keep responses out of HTTP sample capture (still+ # metered and logged).+ "capture": False,+ },+ "resources": [+ {+ "name": endpoint,+ "endpoint": endpoint_config,+ }+ ],+ }++ # Cross-run offset resume is only safe under the explicit stable sort we request; the four+ # paged endpoints with no documented SortBy have an unestablished default order, where a+ # `From=N` resume could silently skip or duplicate rows if that order shifts between runs.+ # Gate both loading and saving on the same predicate and those endpoints restart at offset 0+ # on every run instead.+ is_resumable = config.paged and config.supports_sort_by++ initial_paginator_state: Optional[dict[str, Any]] = None+ if is_resumable and resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_paginator_state = {"next_from": resume.next_from}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Saved AFTER a page is yielded, pointing at the next offset to fetch; no save once+ # pagination is exhausted (state is None).+ if state and state.get("next_from") is not None:+ resumable_source_manager.save_state(MembrainResumeConfig(next_from=int(state["next_from"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint if is_resumable else None,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ 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,+ )+++def validate_credentials(api_key: str, subdomain: str) -> tuple[bool, str | None]:+ """Probe `/users/` (present on every instance, bare array response) to validate the key.++ Membrain reports a missing instance as HTTP 200 with `{"error": "Instance not found"}`, so+ the body has to be inspected as well as the status. Fixed messages only: the raw response or+ exception text is never surfaced.+ """+ try:+ # capture=False: the probe fetches a real user list, whose names and emails the+ # name-based sample scrubbers aren't guaranteed to catch.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False)+ response = session.get(+ f"{base_url(subdomain)}/users/",+ headers=_auth_headers(api_key),+ timeout=PROBE_TIMEOUT_SECONDS,+ )+ except Exception:+ return False, "Could not connect to Membrain. Check the subdomain and try again."++ if response.status_code in (401, 403):+ return False, "Invalid Membrain API key. Ask a Membrain admin to check the key, then try again."+ if response.status_code != 200:+ return False, f"Membrain returned HTTP {response.status_code}. Try again in a few minutes."++ try:+ body = response.json()+ except ValueError:+ return False, "Membrain returned an unexpected response. Check the subdomain and try again."++ if isinstance(body, list):+ return True, None++ if isinstance(body, dict) and "error" in body:+ if "instance" in str(body["error"]).lower():+ return (+ False,+ "No Membrain instance was found at that subdomain. Enter just the subdomain of your "+ "Membrain URL: the 'acme' in 'acme.membrain.com'.",+ )+ return False, "Membrain rejected the request. Check your API key and subdomain, then try again."++ return False, "Membrain returned an unexpected response. Check the subdomain and try again."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/settings.pynew file mode 100644index 000000000000..a0e7ed829b52--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/settings.py@@ -0,0 +1,108 @@+from dataclasses import field++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField+++@frozen+class MembrainEndpointConfig:+ name: str+ # Path under `https://{subdomain}.membrain.com/API/v2` (the documented paths all end in `/`).+ path: str+ # Paged endpoints return a `{count, from, to, items: [...]}` envelope and accept `?From=N`;+ # the rest return a bare JSON array in one response.+ paged: bool = False+ # Whether the endpoint's reference documents `SortBy` ('CreatedDate ASC' etc). Only+ # companies, contacts and activities do; the other paged endpoints don't document it, so we+ # don't send it there and their page order follows the API's default. Also gates cross-run+ # offset resume in membrain.py: without an explicit stable sort, `From=N` resume is not+ # provably safe against reordering between runs.+ supports_sort_by: bool = False+ # Documented query params sent on every request (e.g. IncludeDeleted, so deletions reach the+ # warehouse instead of rows silently disappearing from the sync).+ extra_params: dict[str, str] = field(default_factory=dict)+ # Stable creation timestamp used for datetime partitioning. Never a Changed* field, which+ # would rewrite partitions on every update.+ partition_key: str | None = None+ # Membrain ids are GUIDs in a PascalCase `Id` field, unique per entity type, and each+ # endpoint maps to its own table.+ primary_keys: list[str] = field(default_factory=lambda: ["Id"])+++# Membrain REST API v2 endpoints (https://www.membrain.com/developers/api-documentation).+# `opportunities` are Membrain's Sales Projects and `account_growth_items` its Account Growth+# projects; the schema names follow the API paths so they match what the reference documents.+MEMBRAIN_ENDPOINTS: dict[str, MembrainEndpointConfig] = {+ "companies": MembrainEndpointConfig(+ name="companies",+ path="/companies/",+ paged=True,+ supports_sort_by=True,+ extra_params={"IncludeDeleted": "true"},+ partition_key="CreatedDate",+ ),+ "contacts": MembrainEndpointConfig(+ name="contacts",+ path="/contacts/",+ paged=True,+ supports_sort_by=True,+ extra_params={"IncludeDeleted": "true", "IncludeRetired": "true"},+ partition_key="CreatedDate",+ ),+ "prospects": MembrainEndpointConfig(+ name="prospects",+ path="/prospects/",+ paged=True,+ partition_key="CreatedDate",+ ),+ "opportunities": MembrainEndpointConfig(+ name="opportunities",+ path="/opportunities/",+ paged=True,+ partition_key="CreatedDate",+ ),+ "account_growth_items": MembrainEndpointConfig(+ name="account_growth_items",+ path="/accountGrowthItems/",+ paged=True,+ partition_key="CreatedDate",+ ),+ "tickets": MembrainEndpointConfig(+ name="tickets",+ path="/tickets/",+ paged=True,+ partition_key="CreatedDate",+ ),+ "activities": MembrainEndpointConfig(+ name="activities",+ path="/activities/",+ paged=True,+ supports_sort_by=True,+ partition_key="CreatedDate",+ ),+ "users": MembrainEndpointConfig(name="users", path="/users/"),+ "roles": MembrainEndpointConfig(name="roles", path="/roles/"),+ # `/customFields/` returns one object holding a per-entity array of field definitions+ # (companyCustomFields, contactCustomFields, ...); the transport flattens it into one row per+ # definition with an `EntityType` column, so the composite key covers a definition that+ # appears under more than one entity.+ "custom_fields": MembrainEndpointConfig(+ name="custom_fields",+ path="/customFields/",+ primary_keys=["EntityType", "Id"],+ ),+ "products": MembrainEndpointConfig(name="products", path="/products/"),+}++ENDPOINTS = tuple(MEMBRAIN_ENDPOINTS.keys())++# All endpoints are full refresh only for now. The main list endpoints do document server-side+# ChangedFromDate/ChangedToDate and CreatedFromDate/CreatedToDate range filters (both ends of a+# range must be provided together), but the reference is the only evidence available: the filters+# could not be verified against a live instance here (no credentials), and four of the paged+# endpoints (prospects, opportunities, accountGrowthItems, tickets) document no SortBy, so row+# order inside a window is unknown. Enabling incremental is a matter of populating this dict,+# mapping the user's cursor into the range params in `membrain.py`, and passing an explicit upper+# bound, once the filters are verified live.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/source.pyindex 4ab85d862c5e..469b54a5e6e3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/source.py@@ -1,28 +1,156 @@-from typing import cast+import re+from typing import Optional, cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+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 (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.membrain import (MembrainSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.membrain.membrain import (+ MembrainResumeConfig,+ membrain_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.membrain.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ MEMBRAIN_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+# Membrain instance subdomains are DNS labels: alphanumeric with optional internal hyphens.+SUBDOMAIN_REGEX = re.compile(r"^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$")+@SourceRegistry.register-class MembrainSource(SimpleSource[MembrainSourceConfig]):+class MembrainSource(ResumableSource[MembrainSourceConfig, MembrainResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://www.membrain.com/developers/api-documentation"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MEMBRAIN+ @property+ def connection_host_fields(self) -> list[str]:+ # The stored API key is sent to `https://{subdomain}.membrain.com`, so retargeting+ # `subdomain` must force the editor to re-enter the key (prevents credential+ # exfiltration).+ return ["subdomain"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.MEMBRAIN,category=DataWarehouseSourceCategory.CRM,label="Membrain",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Membrain API key and account subdomain to sync your CRM data, including companies, contacts, prospects, sales projects, and tickets, into the PostHog Data warehouse.++A Membrain admin can create an API key under **System Setup → Membrain API**. Your subdomain is the first part of your Membrain URL. For `acme.membrain.com` the subdomain is `acme`.""",iconPath="/static/services/membrain.png",+ docsUrl="https://posthog.com/docs/cdp/sources/membrain",keywords=["crm", "sales"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="subdomain",+ label="Account subdomain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="acme",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.membrain.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Membrain hosts are per-account subdomains, so match the stable status prefix rather+ # than a fixed hostname. A bad or revoked API key can never be fixed by retrying.+ return {+ "401 Client Error: Unauthorized for url": "Your Membrain API key is invalid or has been revoked. Ask a Membrain admin to create a new key under System Setup, then reconnect.",+ "403 Client Error: Forbidden for url": "Your Membrain API key does not have access to this data. Ask a Membrain admin to check the key, then reconnect.",+ }++ def get_schemas(+ self,+ config: MembrainSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only until the documented ChangedFromDate/ChangedToDate+ # filters are verified against a live instance (INCREMENTAL_FIELDS is empty, so every+ # schema comes back full-refresh only); see settings.py.+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: MembrainSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if not SUBDOMAIN_REGEX.match(config.subdomain):+ return False, "Membrain account subdomain is invalid"++ # The API key is instance-wide, so a single probe validates access to every schema.+ return validate_credentials(config.api_key, config.subdomain)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MembrainResumeConfig]:+ return ResumableSourceManager[MembrainResumeConfig](inputs, MembrainResumeConfig)++ def source_for_pipeline(+ self,+ config: MembrainSourceConfig,+ resumable_source_manager: ResumableSourceManager[MembrainResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in MEMBRAIN_ENDPOINTS:+ raise ValueError(f"Unknown Membrain schema '{inputs.schema_name}'")++ return membrain_source(+ api_key=config.api_key,+ subdomain=config.subdomain,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/tests/test_membrain.py b/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/tests/test_membrain.pynew file mode 100644index 000000000000..3031d05df4aa--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/tests/test_membrain.py@@ -0,0 +1,481 @@+import json+from typing import Any, cast++import pytest+from unittest import mock++from parameterized import parameterized+from requests import HTTPError, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.membrain.membrain import (+ MembrainPaginator,+ MembrainResumeConfig,+ membrain_source,+ validate_credentials,+)++# RESTClient builds its session via make_tracked_session in the rest_client module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+# validate_credentials and the custom-fields iterator build their own tracked session in the+# membrain module.+MEMBRAIN_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.membrain.membrain.make_tracked_session"+)++_REASONS = {401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 500: "Internal Server Error"}+++def _envelope(items: list[dict[str, Any]], count: int, start: int) -> dict[str, Any]:+ # Membrain serializes every value as a JSON string, including the paging counters.+ return {+ "count": str(count),+ "from": str(start),+ "to": str(start + len(items)),+ "items": items,+ }+++def _response(body: Any, *, status: int = 200, raw: bytes | None = None) -> Response:+ resp = Response()+ resp.status_code = status+ resp._content = raw if raw is not None else json.dumps(body).encode()+ resp.url = "https://acme.membrain.com/API/v2/companies/"+ resp.reason = cast("str", _REASONS.get(status))+ return resp+++def _make_manager(resume_state: MembrainResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> tuple[list[dict[str, Any]], list[Any]]:+ """Wire a mock session; return (param_snapshots, auth_snapshots) captured AT SEND TIME.++ ``request.params`` is a single dict mutated in place across pages, so a snapshot copy per+ prepared request is the only way to see each page's params.+ """+ session.headers = {}+ param_snapshots: list[dict[str, Any]] = []+ auth_snapshots: list[Any] = []++ def _prepare(request: Any) -> mock.MagicMock:+ param_snapshots.append(dict(request.params or {}))+ auth_snapshots.append(request.auth)+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return param_snapshots, auth_snapshots+++def _rows(source_response: Any) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++def _source(manager: Any, endpoint: str = "companies") -> Any:+ return membrain_source(+ api_key="mb-key",+ subdomain="acme",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ )+++class TestMembrainPaginator:+ def _update(self, paginator: MembrainPaginator, body: Any) -> None:+ paginator.update_state(_response(body))++ def test_advances_to_the_envelope_to_offset(self) -> None:+ paginator = MembrainPaginator()+ self._update(paginator, _envelope([{"Id": "a"}], count=250, start=0))++ assert paginator.has_next_page is True+ assert paginator.get_resume_state() == {"next_from": 1}++ def test_terminates_when_to_reaches_count(self) -> None:+ paginator = MembrainPaginator()+ self._update(paginator, _envelope([{"Id": "a"}], count=1, start=0))++ assert paginator.has_next_page is False+ assert paginator.get_resume_state() is None++ def test_terminates_when_to_does_not_advance(self) -> None:+ # A `to` equal to the offset we requested would refetch the same window forever.+ paginator = MembrainPaginator()+ paginator.set_resume_state({"next_from": 100})+ self._update(paginator, {"count": "250", "from": "100", "to": "100", "items": []})++ assert paginator.has_next_page is False++ @parameterized.expand(+ [+ ("missing_counters", {"items": [{"Id": "a"}]}),+ ("non_dict_body", [{"Id": "a"}]),+ ]+ )+ def test_fails_loudly_on_unexpected_envelope(self, _name: str, body: Any) -> None:+ # Missing count/to must not be treated as a graceful last page: that could truncate a+ # full-refresh sync without ever raising.+ paginator = MembrainPaginator()+ with pytest.raises(ValueError):+ self._update(paginator, body)++ def test_non_numeric_counter_fails_loudly(self) -> None:+ paginator = MembrainPaginator()+ with pytest.raises(ValueError):+ self._update(paginator, {"count": "many", "from": "0", "to": "1", "items": []})++ def test_set_resume_state_round_trip(self) -> None:+ paginator = MembrainPaginator()+ paginator.set_resume_state({"next_from": "200"})++ request = mock.MagicMock(params=None)+ paginator.init_request(request)++ assert request.params == {"From": 200}+ assert paginator.has_next_page is True+++class TestPagination:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_follows_from_offsets_until_count_reached(self, MockSession) -> None:+ session = MockSession.return_value+ params, _ = _wire(+ session,+ [+ _response(_envelope([{"Id": "a"}, {"Id": "b"}], count=3, start=0)),+ _response(_envelope([{"Id": "c"}], count=3, start=2)),+ ],+ )++ rows = _rows(_source(_make_manager()))++ assert rows == [{"Id": "a"}, {"Id": "b"}, {"Id": "c"}]+ # A fresh run sends no From; the second page starts at the first page's `to`.+ assert [p.get("From") for p in params] == [None, 2]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_next_from_after_yielding_each_non_terminal_page(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response(_envelope([{"Id": "a"}, {"Id": "b"}], count=3, start=0)),+ _response(_envelope([{"Id": "c"}], count=3, start=2)),+ ],+ )++ manager = _make_manager()+ _rows(_source(manager))++ assert [c.args[0].next_from for c in manager.save_state.call_args_list] == [2]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_offset(self, MockSession) -> None:+ session = MockSession.return_value+ params, _ = _wire(session, [_response(_envelope([{"Id": "c"}], count=3, start=2))])++ manager = _make_manager(MembrainResumeConfig(next_from=2))+ rows = _rows(_source(manager))++ assert rows == [{"Id": "c"}]+ # Offset 0 must never be refetched on resume.+ assert params[0]["From"] == 2++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_key_rides_the_apikey_header_and_never_the_url(self, MockSession) -> None:+ session = MockSession.return_value+ params, auths = _wire(session, [_response(_envelope([], count=0, start=0))])++ _rows(_source(_make_manager()))++ assert "APIKey" not in params[0]+ auth = auths[0]+ assert isinstance(auth, APIKeyAuth)+ assert (auth.name, auth.location) == ("APIKey", "header")++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_excludes_crm_rows_from_http_sample_capture(self, MockSession) -> None:+ # CRM rows carry customer emails and free-text notes the name-based sample scrubbers+ # aren't guaranteed to catch.+ session = MockSession.return_value+ _wire(session, [_response(_envelope([], count=0, start=0))])++ _rows(_source(_make_manager()))++ assert MockSession.call_args.kwargs.get("capture") is False++ @parameterized.expand(+ [+ ("companies", {"IncludeDeleted": "true", "SortBy": "CreatedDate ASC"}),+ ("contacts", {"IncludeDeleted": "true", "IncludeRetired": "true", "SortBy": "CreatedDate ASC"}),+ ("activities", {"SortBy": "CreatedDate ASC"}),+ # These endpoints document neither SortBy nor Include* params, so none are sent.+ ("prospects", {}),+ ("opportunities", {}),+ ("account_growth_items", {}),+ ("tickets", {}),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_documented_params_sent_per_endpoint(self, endpoint: str, expected: dict[str, str], MockSession) -> None:+ session = MockSession.return_value+ params, _ = _wire(session, [_response(_envelope([], count=0, start=0))])++ _rows(_source(_make_manager(), endpoint=endpoint))++ assert params[0] == expected++ @parameterized.expand([("prospects",), ("opportunities",), ("account_growth_items",), ("tickets",)])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_unsorted_endpoints_never_save_or_load_resume_state(self, endpoint: str, MockSession) -> None:+ # No documented SortBy means no established stable order, so an offset resume across runs+ # could silently skip or duplicate rows if that order shifts between them.+ session = MockSession.return_value+ _wire(+ session,+ [+ _response(_envelope([{"Id": "a"}, {"Id": "b"}], count=3, start=0)),+ _response(_envelope([{"Id": "c"}], count=3, start=2)),+ ],+ )++ manager = _make_manager()+ rows = _rows(_source(manager, endpoint=endpoint))++ assert rows == [{"Id": "a"}, {"Id": "b"}, {"Id": "c"}]+ manager.load_state.assert_not_called()+ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_unsorted_endpoint_ignores_a_saved_resume_offset(self, MockSession) -> None:+ # Even if a stale checkpoint exists (e.g. saved before this gate shipped), an endpoint+ # with no established stable order must restart at offset 0 rather than honour it.+ session = MockSession.return_value+ params, _ = _wire(session, [_response(_envelope([{"Id": "a"}], count=1, start=0))])++ manager = _make_manager(MembrainResumeConfig(next_from=2))+ rows = _rows(_source(manager, endpoint="prospects"))++ assert rows == [{"Id": "a"}]+ assert "From" not in params[0]+++class TestBareArrayEndpoints:+ @parameterized.expand([("users",), ("roles",), ("products",)])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_yields_rows_from_a_single_unpaged_request(self, endpoint: str, MockSession) -> None:+ session = MockSession.return_value+ params, _ = _wire(session, [_response([{"Id": "u1"}, {"Id": "u2"}])])++ manager = _make_manager()+ rows = _rows(_source(manager, endpoint=endpoint))++ assert rows == [{"Id": "u1"}, {"Id": "u2"}]+ assert session.send.call_count == 1+ assert "From" not in params[0]+ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_error_object_on_200_fails_loudly(self, MockSession) -> None:+ # Membrain reports some failures as HTTP 200 with an error body; syncing it as a row+ # would silently produce a one-row garbage table.+ session = MockSession.return_value+ _wire(session, [_response({"error": "Instance not found"})])++ with pytest.raises(ValueError, match="list response body"):+ _rows(_source(_make_manager(), endpoint="users"))+++class TestMalformedPagedPayload:+ @parameterized.expand(+ [+ ("error_object", {"error": "Instance not found"}),+ ("missing_items", {"count": "0", "from": "0", "to": "0"}),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_body_without_items_fails_loudly(self, _name: str, body: Any, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response(body)])++ with pytest.raises(ValueError, match="matched nothing"):+ _rows(_source(_make_manager()))+++class TestErrorHandling:+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_client_errors_raise_http_error(self, _name: str, status: int, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({}, status=status)])++ with pytest.raises(HTTPError) as exc_info:+ _rows(_source(_make_manager()))++ # get_non_retryable_errors matches on this stable prefix.+ assert str(exc_info.value).startswith(f"{status} Client Error")++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ @mock.patch("time.sleep", return_value=None)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_transient_statuses_are_retried_then_recover(self, _name: str, status: int, MockSession, _sleep) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response({}, status=status),+ _response(_envelope([{"Id": "a"}], count=1, start=0)),+ ],+ )++ rows = _rows(_source(_make_manager()))++ assert rows == [{"Id": "a"}]+ assert session.send.call_count == 2+++class TestCustomFields:+ def _probe(self, response_or_exc: Any) -> Any:+ session = mock.MagicMock()+ if isinstance(response_or_exc, Exception):+ session.get.side_effect = response_or_exc+ else:+ session.get.return_value = response_or_exc+ return mock.patch(MEMBRAIN_SESSION_PATCH, return_value=session)++ def test_flattens_per_entity_arrays_into_rows_with_entity_type(self) -> None:+ body = {+ "companyCustomFields": [{"Id": "cf-1", "Name": "Tier", "Type": "Text"}],+ "contactCustomFields": [+ {"Id": "cf-2", "Name": "Birthday", "Type": "Date"},+ {"Id": "cf-3", "Name": "Segment", "Type": "SingleSelect", "Options": [{"Id": "o1", "Name": "A"}]},+ ],+ }+ with self._probe(_response(body)):+ rows = _rows(_source(_make_manager(), endpoint="custom_fields"))++ assert rows == [+ {"Id": "cf-1", "Name": "Tier", "Type": "Text", "EntityType": "company"},+ {"Id": "cf-2", "Name": "Birthday", "Type": "Date", "EntityType": "contact"},+ {+ "Id": "cf-3",+ "Name": "Segment",+ "Type": "SingleSelect",+ "Options": [{"Id": "o1", "Name": "A"}],+ "EntityType": "contact",+ },+ ]++ @mock.patch(MEMBRAIN_SESSION_PATCH)+ def test_excludes_custom_field_definitions_from_http_sample_capture(self, MockSession) -> None:+ MockSession.return_value.get.return_value = _response({"companyCustomFields": []})++ _rows(_source(_make_manager(), endpoint="custom_fields"))++ assert MockSession.call_args.kwargs.get("capture") is False++ @parameterized.expand(+ [+ ("error_object", {"error": "Instance not found"}),+ ("bare_array", [{"Id": "cf-1"}]),+ ]+ )+ def test_unexpected_shape_fails_loudly(self, _name: str, body: Any) -> None:+ with self._probe(_response(body)):+ with pytest.raises(ValueError, match="customFields"):+ _rows(_source(_make_manager(), endpoint="custom_fields"))+++class TestValidateCredentials:+ def _probe(self, response_or_exc: Any) -> Any:+ session = mock.MagicMock()+ if isinstance(response_or_exc, Exception):+ session.get.side_effect = response_or_exc+ else:+ session.get.return_value = response_or_exc+ return mock.patch(MEMBRAIN_SESSION_PATCH, return_value=session)++ def test_a_bare_user_list_is_valid(self) -> None:+ with self._probe(_response([{"Id": "u1", "Name": "Ada"}])):+ assert validate_credentials("mb-key", "acme") == (True, None)++ @mock.patch(MEMBRAIN_SESSION_PATCH)+ def test_probe_excludes_the_real_user_list_from_http_sample_capture(self, MockSession) -> None:+ # The probe fetches a real user list, whose names and emails the name-based sample+ # scrubbers aren't guaranteed to catch.+ MockSession.return_value.get.return_value = _response([{"Id": "u1", "Name": "Ada"}])++ validate_credentials("mb-key", "acme")++ assert MockSession.call_args.kwargs.get("capture") is False++ @parameterized.expand(+ [+ ("instance_not_found", {"error": "Instance not found"}, "subdomain"),+ ("other_error", {"error": "Invalid key"}, "API key"),+ ]+ )+ def test_200_error_bodies_map_to_guidance(self, _name: str, body: Any, expected_fragment: str) -> None:+ # Membrain reports these failures as HTTP 200 with an error body, so the status alone+ # would wrongly validate the credentials.+ with self._probe(_response(body)):+ is_valid, message = validate_credentials("mb-key", "acme")++ assert is_valid is False+ assert message is not None and expected_fragment in message++ @parameterized.expand(+ [+ ("unauthorized", 401, "Invalid Membrain API key"),+ ("forbidden", 403, "Invalid Membrain API key"),+ ("server_error", 500, "Membrain returned HTTP 500"),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, expected_prefix: str) -> None:+ with self._probe(_response({}, status=status)):+ is_valid, message = validate_credentials("mb-key", "acme")++ assert is_valid is False+ assert message is not None and message.startswith(expected_prefix)++ def test_non_json_200_is_rejected(self) -> None:+ with self._probe(_response(None, raw=b"<html>maintenance</html>")):+ is_valid, message = validate_credentials("mb-key", "acme")++ assert is_valid is False+ assert message is not None and "unexpected response" in message++ def test_connection_error_maps_to_fixed_message(self) -> None:+ # The probe swallows the exception and returns a fixed message, so raw exception text+ # never reaches the user.+ with self._probe(RuntimeError("boom")):+ is_valid, message = validate_credentials("mb-key", "acme")++ assert is_valid is False+ assert message is not None and message.startswith("Could not connect to Membrain")+++class TestMembrainSourceResponse:+ @parameterized.expand(+ [+ ("companies", ["Id"], "datetime"),+ ("users", ["Id"], None),+ ("custom_fields", ["EntityType", "Id"], None),+ ]+ )+ def test_primary_keys_and_partitioning_follow_endpoint_shape(+ self, endpoint: str, primary_keys: list[str], partition_mode: str | None+ ) -> None:+ response = _source(_make_manager(), endpoint=endpoint)++ assert response.primary_keys == primary_keys+ assert response.partition_mode == partition_mode+ if partition_mode == "datetime":+ assert response.partition_keys == ["CreatedDate"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/tests/test_membrain_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/tests/test_membrain_source.pynew file mode 100644index 000000000000..4e18c5287986--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/membrain/tests/test_membrain_source.py@@ -0,0 +1,102 @@+import pytest+from unittest import mock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.membrain import (+ MembrainSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.membrain import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.membrain.source import MembrainSource+++class TestMembrainSource:+ def setup_method(self) -> None:+ self.source = MembrainSource()+ self.team_id = 123+ self.config = MembrainSourceConfig(api_key="mb-key", subdomain="acme")++ def test_connection_host_fields_include_subdomain(self) -> None:+ # The API key is sent to the customer-controlled `{subdomain}.membrain.com` host, so+ # editing the subdomain must force re-entering the key.+ assert self.source.connection_host_fields == ["subdomain"]++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://acme.membrain.com/API/v2/companies/",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://acme.membrain.com/API/v2/contacts/",+ ),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.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://acme.membrain.com/API/v2/tickets/",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://acme.membrain.com/API/v2/activities/",+ ),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @parameterized.expand(+ [+ ("path_traversal", "acme.membrain.com/evil"),+ ("dotted_host", "evil.example"),+ ("empty", ""),+ ("whitespace", "acme corp"),+ ("leading_hyphen", "-acme"),+ ("trailing_hyphen", "acme-"),+ ]+ )+ def test_validate_credentials_rejects_invalid_subdomain_without_probe(self, _name: str, subdomain: str) -> None:+ config = MembrainSourceConfig(api_key="mb-key", subdomain=subdomain)+ with mock.patch.object(source_module, "validate_credentials") as mock_validate:+ valid, message = self.source.validate_credentials(config, self.team_id)+ assert valid is False+ assert message == "Membrain account subdomain is invalid"+ mock_validate.assert_not_called()++ def test_validate_credentials_delegates_to_probe(self) -> None:+ # The status and body mapping is covered by the membrain.validate_credentials unit+ # tests; here we only guard that the source extracts the credentials and returns the+ # probe result unchanged.+ with mock.patch.object(source_module, "validate_credentials", return_value=(True, None)) as mock_validate:+ result = self.source.validate_credentials(self.config, self.team_id)+ assert result == (True, None)+ mock_validate.assert_called_once_with("mb-key", "acme")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.membrain.source.membrain_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "companies"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "mb-key"+ assert kwargs["subdomain"] == "acme"+ assert kwargs["endpoint"] == "companies"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Membrain schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)