: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 retently import source (#69393)
Tom Owers362ede908cc7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 0c1794b272c8..4a6e8f8f8110 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -293,6 +293,7 @@ the row lists both.| redshift | DB protocol | psycopg (Postgres-compatible) | ➖ || rentcast | HTTP | requests | ✅ || resend | HTTP | requests | ✅ |+| retently | HTTP | requests | ✅ || revenuecat | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || rippling | HTTP | requests | ✅ || rocketlane | HTTP | requests | ✅ |@@ -636,7 +637,6 @@ doesn't conflict with concurrent PRs.- repairshopr- reply_io- retail_express-- retently- revolut_merchant- ringcentral- rki_coviddiff --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 ef143a4d9acd..81dbaa559f1e 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@@ -2782,7 +2782,7 @@ class RetailExpressSourceConfig(config.Config):@config.configclass RetentlySourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/retently/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/retently/canonical_descriptions.pynew file mode 100644index 000000000000..96f7dd725828--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/retently/canonical_descriptions.py@@ -0,0 +1,129 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Retently API docs (https://www.retently.com/api/).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "customers": {+ "description": "A customer (survey recipient) tracked in your Retently account.",+ "docs_url": "https://www.retently.com/api/",+ "columns": {+ "id": "The unique ID of the customer.",+ "email": "The customer's email address.",+ "firstName": "The customer's first name.",+ "lastName": "The customer's last name.",+ "companyName": "The name of the company the customer belongs to.",+ "companyId": "The ID of the company the customer belongs to.",+ "jobTitle": "The customer's job title.",+ "tags": "Tags assigned to the customer.",+ "properties": "Custom properties assigned to the customer (label, name, type, value).",+ "createdDate": "When the customer was created in Retently.",+ "updatedDate": "When the customer was last updated.",+ },+ },+ "companies": {+ "description": "A company aggregating customers in your Retently account, with per-company CX metrics.",+ "docs_url": "https://www.retently.com/api/",+ "columns": {+ "id": "The unique ID of the company.",+ "createdDate": "When the company was created in Retently.",+ "domain": "The company's domain name.",+ "companyName": "The company's name.",+ "industryName": "The company's industry.",+ "tags": "Tags assigned to the company.",+ "cxMetrics": "The company's aggregated CX metrics (NPS, CSAT, CES, STAR).",+ "contactsCount": "The number of customers associated with the company.",+ },+ },+ "feedback": {+ "description": "A survey response (NPS, CSAT, CES or star rating) submitted by a customer.",+ "docs_url": "https://www.retently.com/api/",+ "columns": {+ "id": "The unique ID of the feedback response.",+ "surveyId": "The ID of the sent survey this response belongs to.",+ "customerId": "The ID of the customer who responded.",+ "email": "The email address of the customer who responded.",+ "firstName": "The first name of the customer who responded.",+ "lastName": "The last name of the customer who responded.",+ "companyName": "The name of the company the customer belongs to.",+ "companyId": "The ID of the company the customer belongs to.",+ "campaignName": "The name of the campaign that sent the survey.",+ "campaignId": "The ID of the campaign that sent the survey.",+ "createdDate": "When the response was submitted.",+ "score": "The score the customer gave.",+ "comment": "The free-text comment left with the response.",+ "additionalQuestions": "Answers to the survey's additional questions.",+ "feedbackTags": "Tags assigned to the response.",+ "feedbackTopics": "Topics detected on the response, each with a sentiment.",+ "notes": "Internal notes left on the response.",+ "assigned": "The team member the response is assigned to.",+ "ratingCategory": "The rating category of the response (e.g. Positive).",+ "resolved": "Whether the response has been marked as resolved.",+ "channel": "The channel the survey was delivered through (email, link, in-app).",+ "metricsType": "The survey metric type (NPS, CSAT, CES, STAR).",+ "isBogus": "Whether the response was flagged as bogus.",+ "isSubmitted": "Whether the response was fully submitted.",+ },+ },+ "outbox": {+ "description": "A survey sent to a customer, with its delivery and response status.",+ "docs_url": "https://www.retently.com/api/",+ "columns": {+ "surveyId": "The ID of the sent survey, when available.",+ "email": "The email address the survey was sent to.",+ "customerId": "The ID of the customer the survey was sent to.",+ "firstName": "The first name of the customer.",+ "lastName": "The last name of the customer.",+ "companyName": "The name of the company the customer belongs to.",+ "companyId": "The ID of the company the customer belongs to.",+ "sentDate": "When the survey was sent.",+ "channel": "The channel the survey was delivered through (email, link, in-app).",+ "campaign": "The name of the campaign that sent the survey.",+ "campaignId": "The ID of the campaign that sent the survey.",+ "surveyTemplateId": "The ID of the template the survey was rendered from.",+ "subject": "The subject line of the survey email.",+ "sentBy": "How the survey was triggered (campaign, reminder, manual, test, imported).",+ "status": "The survey's current status (e.g. OPENED, RESPONDED).",+ "detailedStatus": "Detailed delivery flags (opened, responded, opted out, bounced).",+ "responseId": "The ID of the feedback response, when the customer responded.",+ },+ },+ "campaigns": {+ "description": "A survey campaign configured in your Retently account.",+ "docs_url": "https://www.retently.com/api/",+ "columns": {+ "id": "The unique ID of the campaign.",+ "name": "The campaign's name.",+ "isActive": "Whether the campaign is currently active.",+ "templateId": "The ID of the survey template the campaign uses.",+ "metric": "The survey metric the campaign measures (NPS, CSAT, CES, STAR).",+ "type": "The campaign type (e.g. regular, transactional).",+ "channel": "The channel the campaign delivers surveys through (email, link, in-app).",+ },+ },+ "templates": {+ "description": "A survey template configured in your Retently account.",+ "docs_url": "https://www.retently.com/api/",+ "columns": {+ "id": "The unique ID of the template.",+ "name": "The template's name.",+ "channel": "The channel the template is designed for (email, link, in-app).",+ "metric": "The survey metric the template measures (NPS, CSAT, CES, STAR).",+ },+ },+ "reports": {+ "description": "Per-campaign aggregated survey metrics: score trend, delivery stats and per-question stats.",+ "docs_url": "https://www.retently.com/api/",+ "columns": {+ "campaignId": "The ID of the campaign the report is for.",+ "name": "The campaign's name.",+ "isActive": "Whether the campaign is currently active.",+ "metric": "The survey metric the campaign measures (NPS, CSAT, CES, STAR).",+ "trend": "The campaign's daily score trend (promoters, passives, detractors, score).",+ "last": "The campaign's latest aggregated score snapshot.",+ "deliveryStats": "Delivery statistics (sent, opened, responded, opted out, bounced).",+ "questionsStats": "Aggregated statistics for each survey question.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/retently/retently.py b/products/warehouse_sources/backend/temporal/data_imports/sources/retently/retently.pynew file mode 100644index 000000000000..d6409767824c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/retently/retently.py@@ -0,0 +1,237 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.retently.settings import (+ RETENTLY_ENDPOINTS,+ RetentlyEndpointConfig,+)++RETENTLY_BASE_URL = "https://app.retently.com/api/v2"+# Documented maximum page size; the largest page minimises round trips against the ~150 req/min+# rate limit.+PAGE_SIZE = 1000+FIRST_PAGE = 1+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+++class RetentlyRetryableError(Exception):+ pass+++class RetentlyResumeConfig:+ # Next page to fetch (1-based). Pages are requested in ascending creation order, so rows+ # created mid-sync land on the trailing pages and already-fetched pages stay stable; a crashed+ # sync resumes from the page after the last one yielded and merge dedupes any overlap.+ page: int = FIRST_PAGE+++def _get_headers(api_key: str) -> dict[str, str]:+ return {"X-Api-Key": api_key, "Accept": "application/json"}+++def _format_start_date(value: Any) -> str:+ """Format an incremental cursor value as the ISO-8601 `...Z` string Retently's `startDate` expects.++ The API also accepts UNIX timestamps, so non-datetime values pass through as strings.+ """+ 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(value.year, value.month, value.day, tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def _extract_items(body: Any, config: RetentlyEndpointConfig) -> list[dict[str, Any]]:+ """Locate the record array in a Retently response.++ The docs are inconsistent about envelope nesting (records under ``data.<key>`` for most+ endpoints, a bare list under ``data`` for /reports, a top-level array for campaigns/templates),+ so all documented shapes are handled.+ """+ if not isinstance(body, dict):+ raise RetentlyRetryableError(f"Retently returned an unexpected payload for {config.path}")++ data = body.get("data")+ if isinstance(data, list):+ return data+ if isinstance(data, dict):+ items = data.get(config.data_key)+ if isinstance(items, list):+ return items++ top_level = body.get(config.data_key)+ if isinstance(top_level, list):+ return top_level++ if isinstance(data, dict):+ # Defensive fallback: a single list-valued entry in `data` is unambiguous even if the+ # documented key drifts.+ lists = [value for value in data.values() if isinstance(value, list)]+ if len(lists) == 1:+ return lists[0]++ raise RetentlyRetryableError(f"Retently returned an unexpected payload for {config.path}")+++def _has_more(body: dict[str, Any], page: int, item_count: int) -> bool:+ # Prefer the `pages` metadata when the API returns it — the docs place it inside `data` on+ # some endpoints (feedback, companies, outbox) and at the top level on others (customers), so+ # both spots are checked. Fall back to "a short page ends the loop" when it's missing.+ data = body.get("data")+ for meta in (data if isinstance(data, dict) else {}, body):+ pages = meta.get("pages")+ if isinstance(pages, int):+ return page < pages+ return item_count >= PAGE_SIZE+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RetentlyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> Iterator[list[dict[str, Any]]]:+ config = RETENTLY_ENDPOINTS[endpoint]+ # `redact_values` masks the API key (sent in the X-Api-Key header) from captured HTTP samples.+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))++ @retry(+ retry=retry_if_exception_type((RetentlyRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+ )+ def fetch_page(params: dict[str, Any]) -> tuple[list[dict[str, Any]], dict[str, Any]]:+ response = session.get(+ f"{RETENTLY_BASE_URL}{config.path}",+ params=params,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ # Retently rate-limits at ~150 req/min and returns 429 on exceed; 5xx are transient.+ if response.status_code == 429 or response.status_code >= 500:+ raise RetentlyRetryableError(+ f"Retently API error (retryable): status={response.status_code}, path={config.path}"+ )++ if not response.ok:+ logger.error(f"Retently API error: status={response.status_code}, body={response.text}, path={config.path}")+ response.raise_for_status()++ body = response.json()+ # Extraction happens inside the retried scope so a transiently malformed payload (e.g. an+ # HTML error page from a proxy) retries this one request instead of failing the sync.+ return _extract_items(body, config), body++ base_params: dict[str, Any] = {}+ if config.paginated:+ base_params["limit"] = PAGE_SIZE+ if config.sort_param is not None:+ base_params["sort"] = config.sort_param+ if config.incremental_fields and should_use_incremental_field and db_incremental_field_last_value is not None:+ # `startDate` is inclusive of the boundary as far as the docs indicate; the watermark row+ # is re-fetched and merge dedupes it on the primary key.+ base_params["startDate"] = _format_start_date(db_incremental_field_last_value)++ if not config.paginated:+ items, _ = fetch_page(base_params)+ if items:+ yield items+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if resume is not None else FIRST_PAGE+ if resume is not None:+ logger.debug(f"Retently: resuming {endpoint} from page {page}")++ while True:+ items, body = fetch_page({**base_params, "page": page})+ if items:+ yield items++ if not items or not _has_more(body, page, len(items)):+ break++ page += 1+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes any re-pulled rows on the primary key.+ resumable_source_manager.save_state(RetentlyResumeConfig(page=page))+++def retently_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RetentlyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = RETENTLY_ENDPOINTS[endpoint]+ supports_incremental = bool(config.incremental_fields)++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ 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,+ # The incremental endpoint requests ascending creation order via `sort=createdDate`, but we+ # could not verify against a live account that the param is honored, so "desc" keeps the+ # pipeline from checkpointing the watermark mid-sync — it's only persisted once a sync+ # completes successfully.+ sort_mode="desc" if supports_incremental else "asc",+ 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 check_access(api_key: str) -> tuple[int, Optional[str]]:+ """Probe /ping to validate the API key.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))+ try:+ response = session.get(f"{RETENTLY_BASE_URL}/ping", timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Retently: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Retently returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Retently API key"+ return False, message or "Could not validate Retently API key"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/retently/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/retently/settings.pynew file mode 100644index 000000000000..98480cb993dd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/retently/settings.py@@ -0,0 +1,105 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class RetentlyEndpointConfig:+ name: str+ path: str+ # Key the record array is nested under. Most endpoints wrap it in the `data` object+ # (e.g. {"data": {"responses": [...]}}), but campaigns/templates document the array at the+ # top level and /reports returns a bare list under `data` — the transport handles all three.+ data_key: str+ primary_keys: Optional[list[str]] = None+ # Whether the endpoint accepts `page`/`limit` query params. Campaigns, templates and reports+ # are documented without pagination and return the full collection in one response.+ paginated: bool = True+ # Ascending sort field requested explicitly so page-number pagination stays stable while new+ # rows are appended during a sync (Retently sorts descending by default).+ sort_param: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable creation-time field used for datetime partitioning. Never an updated_at-style field.+ partition_key: Optional[str] = None+++def _created_date_incremental_field() -> list[IncrementalField]:+ return [+ {+ "label": "createdDate",+ "type": IncrementalFieldType.DateTime,+ "field": "createdDate",+ "field_type": IncrementalFieldType.DateTime,+ }+ ]+++# Retently v2 REST API endpoints (https://www.retently.com/api/). Incremental sync is only enabled+# on feedback, where the documented `startDate` query param filters responses server-side by their+# creation date. Customers also documents `startDate`/`endDate`, but the filtered field is not+# specified and customer records are mutable (properties, tags), so a creation-window incremental+# would silently miss updates — customers stays full refresh. Companies expose no date filter, and+# outbox rows carry no consistently documented unique identifier (`surveyId` is absent from some+# example rows), so there is no safe merge key and outbox stays full refresh too.+RETENTLY_ENDPOINTS: dict[str, RetentlyEndpointConfig] = {+ "customers": RetentlyEndpointConfig(+ name="customers",+ path="/customers",+ data_key="subscribers",+ primary_keys=["id"],+ sort_param="createdDate",+ partition_key="createdDate",+ ),+ "companies": RetentlyEndpointConfig(+ name="companies",+ path="/companies",+ data_key="companies",+ primary_keys=["id"],+ sort_param="createdDate",+ partition_key="createdDate",+ ),+ "feedback": RetentlyEndpointConfig(+ name="feedback",+ path="/feedback",+ data_key="responses",+ primary_keys=["id"],+ sort_param="createdDate",+ incremental_fields=_created_date_incremental_field(),+ partition_key="createdDate",+ ),+ "outbox": RetentlyEndpointConfig(+ name="outbox",+ path="/outbox",+ data_key="surveys",+ primary_keys=None,+ sort_param="surveyCreatedDate",+ ),+ "campaigns": RetentlyEndpointConfig(+ name="campaigns",+ path="/campaigns",+ data_key="campaigns",+ primary_keys=["id"],+ paginated=False,+ ),+ "templates": RetentlyEndpointConfig(+ name="templates",+ path="/templates",+ data_key="templates",+ primary_keys=["id"],+ paginated=False,+ ),+ "reports": RetentlyEndpointConfig(+ name="reports",+ path="/reports",+ data_key="data",+ primary_keys=["campaignId"],+ paginated=False,+ ),+}++ENDPOINTS = tuple(RETENTLY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in RETENTLY_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/retently/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/retently/source.pyindex d27061372aa3..a190c1d6d3ba 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/retently/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/retently/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.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 RetentlySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.retently.retently import (+ RetentlyResumeConfig,+ retently_source,+ validate_credentials as validate_retently_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.retently.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ RETENTLY_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class RetentlySource(SimpleSource[RetentlySourceConfig]):+class RetentlySource(ResumableSource[RetentlySourceConfig, RetentlyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.RETENTLY@@ -22,9 +46,95 @@ class RetentlySource(SimpleSource[RetentlySourceConfig]):def get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.RETENTLY,- category=DataWarehouseSourceCategory.PRODUCTIVITY,+ category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,label="Retently",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["nps", "csat", "ces", "survey", "customer feedback"],+ caption="""Enter your Retently API key to pull your customer feedback data into the PostHog Data warehouse.++You can create an API key under **Settings → Integrations → API** in [Retently](https://app.retently.com). A key with **read** permission is sufficient — this source only performs GET requests.+""",iconPath="/static/services/retently.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/retently",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.retently.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://app.retently.com": "Your Retently API key is invalid or has been revoked. Generate a new key under Settings → Integrations → API, then reconnect.",+ "403 Client Error: Forbidden for url: https://app.retently.com": "Your Retently API key does not have access to this data. Check the key's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: RetentlySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Only feedback supports incremental sync — its `startDate` query param filters responses+ # server-side by creation date. See settings.py for why the other endpoints are full+ # refresh only.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=endpoint in INCREMENTAL_FIELDS,+ supports_append=endpoint in INCREMENTAL_FIELDS,+ incremental_fields=INCREMENTAL_FIELDS.get(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: RetentlySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key is account-wide, so a single /ping probe validates access to every schema.+ return validate_retently_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RetentlyResumeConfig]:+ return ResumableSourceManager[RetentlyResumeConfig](inputs, RetentlyResumeConfig)++ def source_for_pipeline(+ self,+ config: RetentlySourceConfig,+ resumable_source_manager: ResumableSourceManager[RetentlyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in RETENTLY_ENDPOINTS:+ raise ValueError(f"Unknown Retently schema '{inputs.schema_name}'")++ return retently_source(+ api_key=config.api_key,+ 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/retently/tests/test_retently.py b/products/warehouse_sources/backend/temporal/data_imports/sources/retently/tests/test_retently.pynew file mode 100644index 000000000000..011b2dfa35e0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/retently/tests/test_retently.py@@ -0,0 +1,349 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized+from tenacity import wait_none++from products.warehouse_sources.backend.temporal.data_imports.sources.retently import retently+from products.warehouse_sources.backend.temporal.data_imports.sources.retently.retently import (+ RetentlyResumeConfig,+ RetentlyRetryableError,+ _extract_items,+ _format_start_date,+ get_rows,+ retently_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.retently.settings import (+ ENDPOINTS,+ RETENTLY_ENDPOINTS,+)+++class _FakeResponse:+ def __init__(self, body: Any, status_code: int = 200) -> None:+ self._body = body+ self.status_code = status_code+ self.text = str(body)++ @property+ def ok(self) -> bool:+ return self.status_code < 400++ def json(self) -> Any:+ return self._body++ def raise_for_status(self) -> None:+ if self.status_code >= 400:+ raise requests.HTTPError(f"{self.status_code} Client Error", response=self) # type: ignore[arg-type]+++class _FakeSession:+ def __init__(self, bodies: list[Any]) -> None:+ self._bodies = list(bodies)+ self.requests: list[tuple[str, dict[str, Any]]] = []++ def get(self, url: str, params: dict[str, Any] | None = None, timeout: Any = None) -> _FakeResponse:+ self.requests.append((url, dict(params or {})))+ body = self._bodies.pop(0)+ if isinstance(body, _FakeResponse):+ return body+ return _FakeResponse(body)+++class _FakeResumableManager:+ def __init__(self, state: RetentlyResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[RetentlyResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> RetentlyResumeConfig | None:+ return self._state++ def save_state(self, data: RetentlyResumeConfig) -> None:+ self.saved.append(data)+++def _collect(+ endpoint: str,+ bodies: list[Any],+ manager: _FakeResumableManager | None = None,+ **kwargs: Any,+) -> tuple[list[dict[str, Any]], _FakeSession]:+ session = _FakeSession(bodies)+ rows: list[dict[str, Any]] = []+ with patch.object(retently, "make_tracked_session", return_value=session):+ for batch in get_rows(+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager or _FakeResumableManager(), # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows, session+++class TestExtractItems:+ @parameterized.expand(+ [+ # Records nested under `data.<key>` — feedback, outbox, customers, companies.+ ("nested_in_data", "feedback", {"data": {"responses": [{"id": "1"}], "pages": 1}}, [{"id": "1"}]),+ # /reports returns a bare list under `data`.+ ("bare_list_under_data", "reports", {"data": [{"campaignId": "c1"}]}, [{"campaignId": "c1"}]),+ # Campaigns/templates document the array at the top level, outside `data`.+ ("top_level_array", "campaigns", {"campaigns": [{"id": "c1"}]}, [{"id": "c1"}]),+ # Fallback: a single list-valued entry in `data` even when the documented key drifts.+ ("renamed_key_fallback", "customers", {"data": {"people": [{"id": "1"}], "total": 1}}, [{"id": "1"}]),+ ]+ )+ def test_documented_envelope_shapes(self, _name: str, endpoint: str, body: Any, expected: list) -> None:+ assert _extract_items(body, RETENTLY_ENDPOINTS[endpoint]) == expected++ @parameterized.expand(+ [+ ("not_a_dict", ["rows"]),+ ("no_recognisable_array", {"data": {"total": 3, "tags": ["a"], "other": ["b"]}}),+ ]+ )+ def test_unexpected_payloads_raise_retryable(self, _name: str, body: Any) -> None:+ with pytest.raises(RetentlyRetryableError):+ _extract_items(body, RETENTLY_ENDPOINTS["feedback"])+++class TestFormatStartDate:+ @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"),+ ("epoch_passthrough", 1704067200, "1704067200"),+ ("string_passthrough", "2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z"),+ ]+ )+ def test_format_start_date(self, _name: str, value: object, expected: str) -> None:+ assert _format_start_date(value) == expected+++class TestPagination:+ def test_walks_pages_using_pages_metadata_inside_data(self) -> None:+ bodies = [+ {"data": {"responses": [{"id": "1"}], "page": 1, "pages": 2}},+ {"data": {"responses": [{"id": "2"}], "page": 2, "pages": 2}},+ ]+ rows, session = _collect("feedback", bodies)+ assert [r["id"] for r in rows] == ["1", "2"]+ # Stops at the last page — never requests page 3.+ assert [params["page"] for _, params in session.requests] == [1, 2]++ def test_top_level_pages_metadata_keeps_paginating(self) -> None:+ # The customers docs place `pages` at the top level; a short page must not end the loop+ # while the metadata says more pages exist (e.g. the API caps `limit` below our request).+ bodies = [+ {"data": {"subscribers": [{"id": "1"}]}, "page": 1, "pages": 2},+ {"data": {"subscribers": [{"id": "2"}]}, "page": 2, "pages": 2},+ ]+ rows, session = _collect("customers", bodies)+ assert [r["id"] for r in rows] == ["1", "2"]+ assert len(session.requests) == 2++ def test_short_page_ends_loop_without_pages_metadata(self) -> None:+ bodies = [{"data": {"responses": [{"id": "1"}]}}]+ rows, session = _collect("feedback", bodies)+ assert rows == [{"id": "1"}]+ assert len(session.requests) == 1++ def test_empty_first_page_yields_nothing(self) -> None:+ bodies = [{"data": {"responses": [], "page": 1, "pages": 0}}]+ rows, _ = _collect("feedback", bodies)+ assert rows == []++ @parameterized.expand(+ [+ ("campaigns", {"campaigns": [{"id": "c1"}]}),+ ("templates", {"templates": [{"id": "t1"}]}),+ ("reports", {"data": [{"campaignId": "c1"}]}),+ ]+ )+ def test_unpaginated_endpoints_make_one_request_without_page_params(self, endpoint: str, body: Any) -> None:+ rows, session = _collect(endpoint, [body])+ assert len(rows) == 1+ assert len(session.requests) == 1+ _, params = session.requests[0]+ assert "page" not in params+ assert "limit" not in params++ def test_requests_ascending_sort_for_page_stability(self) -> None:+ bodies = [{"data": {"surveys": [{"customerId": "1"}], "pages": 1}}]+ _, session = _collect("outbox", bodies)+ _, params = session.requests[0]+ assert params["sort"] == "surveyCreatedDate"+ assert params["limit"] == retently.PAGE_SIZE+++class TestIncremental:+ def test_start_date_sent_when_incremental(self) -> None:+ bodies = [{"data": {"responses": [{"id": "1"}], "pages": 1}}]+ _, session = _collect(+ "feedback",+ bodies,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ _, params = session.requests[0]+ assert params["startDate"] == "2026-03-04T02:58:14Z"+ assert params["sort"] == "createdDate"++ @parameterized.expand(+ [+ ("full_refresh_run", False, datetime(2026, 3, 4, tzinfo=UTC)),+ ("first_incremental_run_has_no_watermark", True, None),+ ]+ )+ def test_start_date_omitted(self, _name: str, should_use: bool, last_value: Any) -> None:+ bodies = [{"data": {"responses": [{"id": "1"}], "pages": 1}}]+ _, session = _collect(+ "feedback",+ bodies,+ should_use_incremental_field=should_use,+ db_incremental_field_last_value=last_value,+ )+ _, params = session.requests[0]+ assert "startDate" not in params++ def test_full_refresh_endpoint_ignores_incremental_inputs(self) -> None:+ bodies = [{"data": {"subscribers": [{"id": "1"}], "pages": 1}}]+ _, session = _collect(+ "customers",+ bodies,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ _, params = session.requests[0]+ assert "startDate" not in params+++class TestResume:+ def test_resume_starts_from_saved_page(self) -> None:+ bodies = [{"data": {"responses": [{"id": "9"}], "page": 3, "pages": 3}}]+ manager = _FakeResumableManager(RetentlyResumeConfig(page=3))+ rows, session = _collect("feedback", bodies, manager=manager)+ assert rows == [{"id": "9"}]+ assert session.requests[0][1]["page"] == 3++ def test_state_saved_after_yield_with_next_page(self) -> None:+ bodies = [+ {"data": {"responses": [{"id": "1"}], "pages": 2}},+ {"data": {"responses": [{"id": "2"}], "pages": 2}},+ ]+ manager = _FakeResumableManager()+ _collect("feedback", bodies, manager=manager)+ # Only the transition to page 2 is checkpointed; the final page saves nothing (a crash+ # after the last yield just re-fetches page 2 and merge dedupes).+ assert [state.page for state in manager.saved] == [2]+++class TestRetries:+ @parameterized.expand(+ [+ ("rate_limited", _FakeResponse({}, status_code=429)),+ ("server_error", _FakeResponse({}, status_code=500)),+ # A transiently malformed payload (e.g. an HTML error page from a proxy) must retry the+ # single request, not fail the sync — extraction runs inside the retried scope.+ ("malformed_payload", "<html>bad gateway</html>"),+ ]+ )+ def test_transient_failures_are_retried(self, _name: str, first_response: Any) -> None:+ bodies = [+ first_response,+ {"data": {"responses": [{"id": "1"}], "pages": 1}},+ ]+ with (+ patch.object(retently, "MAX_RETRIES", 2),+ # No real backoff sleeps in tests.+ patch.object(retently, "wait_exponential_jitter", lambda **kwargs: wait_none()),+ ):+ rows, session = _collect("feedback", bodies)+ assert rows == [{"id": "1"}]+ assert len(session.requests) == 2++ def test_auth_error_raises_immediately(self) -> None:+ bodies = [_FakeResponse({"message": "Account not found", "code": 401, "data": None}, status_code=401)]+ with pytest.raises(requests.HTTPError):+ _collect("feedback", bodies)+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Retently API key"),+ ("forbidden", 403, False, "Invalid Retently API key"),+ ("server_error_is_inconclusive", 500, False, "Retently returned HTTP 500"),+ ]+ )+ def test_status_mapping(self, _name: str, status_code: int, expected_ok: bool, expected_msg: str | None) -> None:+ session = _FakeSession([_FakeResponse({}, status_code=status_code)])+ with patch.object(retently, "make_tracked_session", return_value=session):+ ok, message = validate_credentials("key")+ assert ok is expected_ok+ if expected_msg is None:+ assert message is None+ else:+ assert message is not None and expected_msg in message+ assert session.requests[0][0].endswith("/ping")++ def test_network_error_is_inconclusive_not_invalid(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(retently, "make_tracked_session", return_value=session):+ ok, message = validate_credentials("key")+ assert ok is False+ assert message is not None and "Could not connect to Retently" in message+++class TestSourceResponse:+ @parameterized.expand(+ [+ ("customers", ["id"], "createdDate", "asc"),+ ("companies", ["id"], "createdDate", "asc"),+ # feedback is the only incremental endpoint: "desc" defers the watermark to the end of+ # a successful sync because the API's sort behavior could not be live-verified.+ ("feedback", ["id"], "createdDate", "desc"),+ ("outbox", None, None, "asc"),+ ("campaigns", ["id"], None, "asc"),+ ("templates", ["id"], None, "asc"),+ ("reports", ["campaignId"], None, "asc"),+ ]+ )+ def test_source_response_shape(+ self, endpoint: str, primary_keys: list[str] | None, partition_key: str | None, sort_mode: str+ ) -> None:+ response = retently_source(+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.sort_mode == sort_mode+ if partition_key is None:+ assert response.partition_keys is None+ assert response.partition_mode is None+ else:+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"++ @parameterized.expand(ENDPOINTS)+ def test_every_declared_endpoint_builds_a_response(self, endpoint: str) -> None:+ response = retently_source(+ api_key="key", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()+ )+ assert response.name == endpointdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/retently/tests/test_retently_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/retently/tests/test_retently_source.pynew file mode 100644index 000000000000..8265fd886a52--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/retently/tests/test_retently_source.py@@ -0,0 +1,152 @@+import pytest+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig++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 RetentlySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.retently import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.retently.retently import RetentlyResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.retently.source import RetentlySource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestRetentlySourceConfig:+ def setup_method(self) -> None:+ self.source = RetentlySource()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.RETENTLY++ def test_config_has_api_key_password_field(self) -> None:+ config = self.source.get_source_config+ fields = {f.name: f for f in config.fields}+ assert set(fields) == {"api_key"}+ api_key_field = fields["api_key"]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.required is True+ assert api_key_field.secret is True++ def test_config_is_unreleased_alpha(self) -> None:+ config = self.source.get_source_config+ # Deliberately shipped hidden: the source lands unreleased until it has been verified+ # against a live Retently account.+ assert config.unreleasedSource is True+ assert config.releaseStatus == "alpha"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/retently"++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O — required for the public-docs table list to render.+ assert self.source.lists_tables_without_credentials is True+++class TestGetSchemas:+ def setup_method(self) -> None:+ self.schemas = {s.name: s for s in RetentlySource().get_schemas(MagicMock(), team_id=1)}++ def test_all_expected_tables_present(self) -> None:+ assert set(self.schemas) == {+ "customers",+ "companies",+ "feedback",+ "outbox",+ "campaigns",+ "templates",+ "reports",+ }++ def test_feedback_is_the_only_incremental_table(self) -> None:+ assert self.schemas["feedback"].supports_incremental is True+ assert [f["field"] for f in self.schemas["feedback"].incremental_fields] == ["createdDate"]+ for name, schema in self.schemas.items():+ if name != "feedback":+ assert schema.supports_incremental is False, name+ assert schema.incremental_fields == [], name++ def test_names_filter(self) -> None:+ filtered = RetentlySource().get_schemas(MagicMock(), team_id=1, names=["feedback"])+ assert [s.name for s in filtered] == ["feedback"]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", (True, None)),+ ("invalid", (False, "Invalid Retently API key")),+ ("inconclusive", (False, "Could not connect to Retently: boom")),+ ]+ )+ def test_validate_credentials_passes_probe_result_through(self, _name: str, probe_result: tuple) -> None:+ config = RetentlySourceConfig(api_key="key")+ with patch.object(source_module, "validate_retently_credentials", return_value=probe_result):+ assert RetentlySource().validate_credentials(config, team_id=1) == probe_result+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://app.retently.com/api/v2/feedback"),+ ("forbidden", "403 Client Error: Forbidden for url: https://app.retently.com/api/v2/customers?page=1"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = RetentlySource().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://app.retently.com/api/v2/feedback",+ ),+ ("read_timeout", "HTTPSConnectionPool(host='app.retently.com', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = RetentlySource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestResumablePlumbing:+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = RetentlySource().get_resumable_source_manager(MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is RetentlyResumeConfig++ def test_source_for_pipeline_passes_incremental_inputs(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "feedback"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ config = RetentlySourceConfig(api_key="key")+ manager = MagicMock()++ with patch.object(source_module, "retently_source") as mock_source:+ RetentlySource().source_for_pipeline(config, manager, inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "feedback"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ def test_source_for_pipeline_drops_last_value_when_not_incremental(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "customers"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "ignored"+ config = RetentlySourceConfig(api_key="key")++ with patch.object(source_module, "retently_source") as mock_source:+ RetentlySource().source_for_pipeline(config, MagicMock(), inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["db_incremental_field_last_value"] is None++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "not_a_real_table"+ with pytest.raises(ValueError):+ RetentlySource().source_for_pipeline(RetentlySourceConfig(api_key="key"), MagicMock(), inputs)