Skip to content

: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.

feat(data-warehouse): implement render import source (#70723)

Tom Owers45a43744fff0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 690657b14918..7494f0d76903 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -353,6 +353,7 @@ the row lists both.
| recruitee | HTTP | requests | ✅ |
| reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
| redshift | DB protocol | psycopg (Postgres-compatible) | ➖ |
+| render | HTTP | requests | ✅ |
| rentcast | HTTP | requests | ✅ |
| replicate | HTTP | requests | ✅ |
| reply_io | HTTP | requests | ✅ |
@@ -823,7 +824,6 @@ doesn't conflict with concurrent PRs.
- reddit
- redis
- referralhero
-- render
- repairshopr
- reply_io
- retail_express
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 1ca5387c7214..1ef35a35c5d1 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
@@ -3437,7 +3437,8 @@ class ReferralHeroSourceConfig(config.Config):
@config.config
class RenderSourceConfig(config.Config):
- pass
+ api_key: str
+ owner_id: str | None = None
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/render/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/render/canonical_descriptions.py
new file mode 100644
index 000000000000..37ad7817b3db
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/render/canonical_descriptions.py
@@ -0,0 +1,194 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "owners": {
+ "description": "Workspaces (users and teams) that the API key's user belongs to. Other resources reference their owning workspace via ownerId.",
+ "docs_url": "https://api-docs.render.com/reference/list-owners",
+ "columns": {
+ "id": "Unique identifier for the workspace (user or team).",
+ "name": "Display name of the workspace.",
+ "email": "Email address associated with the workspace.",
+ "twoFactorAuthEnabled": "Whether two-factor authentication is enabled for the workspace.",
+ "type": "Whether the owner is an individual user or a team.",
+ },
+ },
+ "projects": {
+ "description": "Projects that group related services and databases into environments (e.g. production and staging).",
+ "docs_url": "https://api-docs.render.com/reference/list-projects",
+ "columns": {
+ "id": "Unique identifier for the project.",
+ "name": "Name of the project.",
+ "owner": "The workspace that owns the project.",
+ "environmentIds": "IDs of the environments that belong to the project.",
+ "createdAt": "When the project was created.",
+ "updatedAt": "When the project was last updated.",
+ },
+ },
+ "environments": {
+ "description": "Environments within a project (e.g. production, staging), listing the services, databases, and env groups they contain.",
+ "docs_url": "https://api-docs.render.com/reference/list-environments",
+ "columns": {
+ "id": "Unique identifier for the environment.",
+ "name": "Name of the environment.",
+ "projectId": "ID of the project the environment belongs to.",
+ "serviceIds": "IDs of the services in the environment.",
+ "databasesIds": "IDs of the Postgres databases in the environment.",
+ "redisIds": "IDs of the Key Value (Redis-compatible) instances in the environment.",
+ "envGroupIds": "IDs of the environment groups linked to the environment.",
+ "protectedStatus": "Whether the environment is protected from unauthorized changes.",
+ "networkIsolationEnabled": "Whether services in the environment can only communicate with other services in the same environment.",
+ },
+ },
+ "services": {
+ "description": "Services in the workspace: web services, static sites, private services, background workers, and cron jobs.",
+ "docs_url": "https://api-docs.render.com/reference/list-services",
+ "columns": {
+ "id": "Unique identifier for the service.",
+ "name": "Name of the service.",
+ "type": "Service type: static_site, web_service, private_service, background_worker, or cron_job.",
+ "ownerId": "ID of the workspace that owns the service.",
+ "environmentId": "ID of the environment the service belongs to, if any.",
+ "repo": "URL of the Git repository the service deploys from, if Git-backed.",
+ "branch": "Git branch the service deploys from.",
+ "imagePath": "Container image the service deploys from, if image-backed.",
+ "rootDir": "Root directory of the service within its repository.",
+ "autoDeploy": "Whether the service automatically deploys on push to its branch.",
+ "suspended": "Whether the service is currently suspended.",
+ "suspenders": "The actors that suspended the service, if suspended.",
+ "slug": "URL-safe slug for the service.",
+ "dashboardUrl": "URL to view the service in the Render Dashboard.",
+ "serviceDetails": "Type-specific details (plan, region, runtime, URLs, and more).",
+ "createdAt": "When the service was created.",
+ "updatedAt": "When the service was last updated.",
+ },
+ },
+ "deploys": {
+ "description": "Deploys for each service, with status, trigger, and timing — one row per deploy per service.",
+ "docs_url": "https://api-docs.render.com/reference/list-deploys",
+ "columns": {
+ "id": "Unique identifier for the deploy.",
+ "serviceId": "ID of the service the deploy belongs to.",
+ "commit": "The Git commit that was deployed (id, message, createdAt), for Git-backed services.",
+ "image": "The container image that was deployed, for image-backed services.",
+ "status": "Deploy status (e.g. created, build_in_progress, live, build_failed, canceled).",
+ "trigger": "What triggered the deploy (e.g. a push, the API, or the dashboard).",
+ "startedAt": "When the deploy started running.",
+ "finishedAt": "When the deploy reached a terminal state. Null while in progress.",
+ "createdAt": "When the deploy was created.",
+ "updatedAt": "When the deploy was last updated.",
+ },
+ },
+ "jobs": {
+ "description": "One-off jobs run against each service: standalone tasks that run to completion using the service's most recent successful build.",
+ "docs_url": "https://api-docs.render.com/reference/list-job",
+ "columns": {
+ "id": "Unique identifier for the job.",
+ "serviceId": "ID of the service the job ran against.",
+ "startCommand": "Command the job executed.",
+ "planId": "ID of the instance plan the job ran on.",
+ "status": "Job status: pending, running, succeeded, failed, or canceled.",
+ "createdAt": "When the job was created.",
+ "startedAt": "When the job started running. Null while pending.",
+ "finishedAt": "When the job reached a terminal state. Null until finished.",
+ },
+ },
+ "events": {
+ "description": "Operational events for each service: deploys, builds, restarts, suspensions, autoscaling, disk and plan changes, and more.",
+ "docs_url": "https://api-docs.render.com/reference/list-events",
+ "columns": {
+ "id": "Unique identifier for the event.",
+ "serviceId": "ID of the service the event belongs to.",
+ "timestamp": "When the event occurred.",
+ "type": "Event type (e.g. deploy_started, deploy_ended, build_started, server_restarted).",
+ "details": "Type-specific event details.",
+ },
+ },
+ "custom_domains": {
+ "description": "Custom domains attached to each service, with verification status.",
+ "docs_url": "https://api-docs.render.com/reference/list-custom-domains",
+ "columns": {
+ "id": "Unique identifier for the custom domain.",
+ "serviceId": "ID of the service the domain is attached to.",
+ "name": "The domain name.",
+ "domainType": "Whether the domain is an apex domain or a subdomain.",
+ "publicSuffix": "The public suffix of the domain (e.g. com, co.uk).",
+ "redirectForName": "The domain this domain redirects to, if any.",
+ "verificationStatus": "Whether the domain's DNS configuration has been verified.",
+ "createdAt": "When the custom domain was added.",
+ "server": "The server the domain routes to.",
+ },
+ },
+ "env_groups": {
+ "description": "Environment groups: named sets of environment variables and secret files shared across services.",
+ "docs_url": "https://api-docs.render.com/reference/list-env-groups",
+ "columns": {
+ "id": "Unique identifier for the environment group.",
+ "name": "Name of the environment group.",
+ "ownerId": "ID of the workspace that owns the environment group.",
+ "environmentId": "ID of the environment the group is linked to, if any.",
+ "serviceLinks": "The services linked to the environment group.",
+ "createdAt": "When the environment group was created.",
+ "updatedAt": "When the environment group was last updated.",
+ },
+ },
+ "postgres": {
+ "description": "Managed Postgres instances in the workspace, with plan, status, and configuration.",
+ "docs_url": "https://api-docs.render.com/reference/list-postgres",
+ "columns": {
+ "id": "Unique identifier for the Postgres instance.",
+ "name": "Name of the Postgres instance.",
+ "databaseName": "Name of the underlying database.",
+ "databaseUser": "Name of the default database user.",
+ "environmentId": "ID of the environment the instance belongs to, if any.",
+ "owner": "The workspace that owns the instance.",
+ "plan": "The instance's pricing plan.",
+ "diskSizeGB": "Provisioned disk size in GB.",
+ "diskAutoscalingEnabled": "Whether disk autoscaling is enabled.",
+ "highAvailabilityEnabled": "Whether high availability is enabled.",
+ "primaryPostgresID": "For read replicas, the ID of the primary instance.",
+ "readReplicas": "Read replicas of the instance.",
+ "role": "Whether the instance is a primary or a replica.",
+ "region": "Region the instance runs in.",
+ "status": "Current status of the instance.",
+ "version": "Postgres major version.",
+ "suspended": "Whether the instance is suspended.",
+ "expiresAt": "When a free-tier instance expires, if applicable.",
+ "dashboardUrl": "URL to view the instance in the Render Dashboard.",
+ "createdAt": "When the instance was created.",
+ "updatedAt": "When the instance was last updated.",
+ },
+ },
+ "key_value": {
+ "description": "Key Value (Redis-compatible) instances in the workspace, with plan, status, and configuration.",
+ "docs_url": "https://api-docs.render.com/reference/list-key-value",
+ "columns": {
+ "id": "Unique identifier for the Key Value instance.",
+ "name": "Name of the Key Value instance.",
+ "owner": "The workspace that owns the instance.",
+ "plan": "The instance's pricing plan.",
+ "region": "Region the instance runs in.",
+ "status": "Current status of the instance.",
+ "version": "Engine version.",
+ "environmentId": "ID of the environment the instance belongs to, if any.",
+ "options": "Instance options such as the eviction policy.",
+ "dashboardUrl": "URL to view the instance in the Render Dashboard.",
+ "createdAt": "When the instance was created.",
+ "updatedAt": "When the instance was last updated.",
+ },
+ },
+ "disks": {
+ "description": "Persistent disks attached to services, with size and mount path.",
+ "docs_url": "https://api-docs.render.com/reference/list-disks",
+ "columns": {
+ "id": "Unique identifier for the disk.",
+ "name": "Name of the disk.",
+ "serviceId": "ID of the service the disk is attached to.",
+ "sizeGB": "Disk size in GB.",
+ "mountPath": "Filesystem path the disk is mounted at.",
+ "createdAt": "When the disk was created.",
+ "updatedAt": "When the disk was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/render/render.py b/products/warehouse_sources/backend/temporal/data_imports/sources/render/render.py
new file mode 100644
index 000000000000..f87b4d6ebc71
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/render/render.py
@@ -0,0 +1,405 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.render.settings import (
+ RENDER_ENDPOINTS,
+ RenderEndpointConfig,
+)
+
+RENDER_BASE_URL = "https://api.render.com/v1"
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+REDACTED_VALUE = "__redacted__"
+
+
+class RenderRetryableError(Exception):
+ pass
+
+
+class RenderResumeConfig:
+ # Cursor of the last processed item — passed back as `?cursor=` to fetch what follows.
+ # None means "start the listing from its first page".
+ cursor: str | None = None
+ # The fan-out parent currently being processed. A stable parent-ID bookmark (not a
+ # positional index) so parents added/removed between a crash and the retry can't resume
+ # us into the wrong parent. None for top-level endpoints.
+ parent_id: str | None = None
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _format_incremental_value(value: Any) -> str:
+ """Format a watermark as an ISO 8601 UTC timestamp, the format Render's time filters document."""
+ if isinstance(value, datetime):
+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return utc_value.strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return f"{value.isoformat()}T00:00:00Z"
+ return str(value)
+
+
+def validate_credentials(api_key: str) -> bool:
+ # /owners is the cheapest authenticated probe: every valid key can list the workspaces
+ # it belongs to, regardless of what resources exist.
+ url = f"{RENDER_BASE_URL}/owners?limit=1"
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ RenderRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=2, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> list[dict[str, Any]]:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Render rate-limits per user (400/min for most GETs) and returns 429 with
+ # Ratelimit-* headers; exponential backoff comfortably outlasts the window.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise RenderRetryableError(f"Render API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # 404 is expected during fan-out (a service deleted mid-sync) and handled by the caller.
+ log = logger.warning if response.status_code == 404 else logger.error
+ log(f"Render API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ if not isinstance(data, list):
+ raise ValueError(f"Render API returned a non-list response for url={url}")
+ return data
+
+
+def _unwrap_item(item: dict[str, Any], wrapper_key: str) -> tuple[dict[str, Any], str | None]:
+ """Split a list item into (resource row, sibling cursor).
+
+ Render list items wrap the resource next to its pagination cursor:
+ `{"service": {...}, "cursor": "..."}`. A couple of endpoints (env groups) are documented
+ unwrapped, so fall back to treating the item as the row itself when the key is absent.
+ """
+ if wrapper_key in item and isinstance(item[wrapper_key], dict):
+ return item[wrapper_key], item.get("cursor")
+ return item, item.get("cursor") if isinstance(item.get("cursor"), str) else None
+
+
+def _build_params(
+ config: RenderEndpointConfig,
+ owner_id: str | None,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"limit": config.page_size}
+
+ if config.supports_owner_filter and owner_id:
+ params["ownerId"] = owner_id
+
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ field = incremental_field or config.default_incremental_field
+ param = config.incremental_param_by_field.get(field) if field else None
+ if param:
+ params[param] = _format_incremental_value(db_incremental_field_last_value)
+ else:
+ logger.warning(
+ f"Render: incremental field {field} has no server-side filter for endpoint "
+ f"{config.name}, syncing the full endpoint instead"
+ )
+
+ return params
+
+
+def _walk_pages(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ config: RenderEndpointConfig,
+ path: str,
+ params: dict[str, Any],
+ cursor: str | None,
+ max_pages: int | None = None,
+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:
+ """Yield (rows, next_cursor) per page, following each page's last-item cursor.
+
+ Render doesn't document an explicit end-of-results signal, so pagination only stops on an
+ empty page (a short page could in principle still have more results). The next cursor is
+ the cursor of the last item in the page.
+ """
+ pages_fetched = 0
+ while True:
+ page_params = dict(params)
+ if cursor:
+ page_params["cursor"] = cursor
+ url = f"{RENDER_BASE_URL}{path}?{urlencode(page_params)}"
+
+ items = _fetch_page(session, url, headers, logger)
+ if not items:
+ return
+
+ rows: list[dict[str, Any]] = []
+ next_cursor: str | None = None
+ for item in items:
+ row, item_cursor = _unwrap_item(item, config.wrapper_key)
+ rows.append(row)
+ if item_cursor:
+ next_cursor = item_cursor
+
+ yield rows, next_cursor
+
+ if next_cursor is None:
+ # Unwrapped responses carry no cursor, so a full page here may mean truncation.
+ if len(items) >= config.page_size:
+ logger.warning(
+ f"Render: endpoint {config.name} returned a full page with no pagination "
+ f"cursor — results may be truncated at {config.page_size} items"
+ )
+ return
+
+ pages_fetched += 1
+ if max_pages is not None and pages_fetched >= max_pages:
+ logger.warning(
+ f"Render: page cap of {max_pages} reached for endpoint {config.name} "
+ f"(path={path}) — remaining results were not fetched"
+ )
+ return
+
+ cursor = next_cursor
+
+
+def _iter_parent_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ parent_config: RenderEndpointConfig,
+ owner_id: str | None,
+) -> Iterator[dict[str, Any]]:
+ """Fully enumerate the parent endpoint (no incremental bound: a new child can land on an
+ old parent, so every sync must consider every parent)."""
+ params: dict[str, Any] = {"limit": parent_config.page_size}
+ if parent_config.supports_owner_filter and owner_id:
+ params["ownerId"] = owner_id
+
+ for rows, _ in _walk_pages(session, headers, logger, parent_config, parent_config.path, params, cursor=None):
+ yield from rows
+
+
+def _get_top_level_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RenderResumeConfig],
+ config: RenderEndpointConfig,
+ params: dict[str, Any],
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor = resume.cursor if resume else None
+ if cursor:
+ logger.debug(f"Render: resuming {config.name} from cursor={cursor}")
+
+ for rows, next_cursor in _walk_pages(session, headers, logger, config, config.path, params, cursor):
+ yield rows
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —
+ # merge dedupes on the primary key.
+ if next_cursor:
+ resumable_source_manager.save_state(RenderResumeConfig(cursor=next_cursor))
+
+
+def _get_fan_out_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RenderResumeConfig],
+ config: RenderEndpointConfig,
+ params: dict[str, Any],
+ owner_id: str | None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan out over every parent resource, fetching this child endpoint once per parent.
+
+ Fan-out runs report sort_mode="desc" (see render_source), so the incremental watermark
+ persists only after every parent completes — a partial run's max says nothing about
+ parents it never reached.
+ """
+ assert config.parent is not None
+ parent_config = RENDER_ENDPOINTS[config.parent]
+ parents = [
+ (row["id"], row) for row in _iter_parent_rows(session, headers, logger, parent_config, owner_id) if "id" in row
+ ]
+
+ # Resolve the saved parent-ID bookmark to the slice of parents still to process. If the
+ # bookmarked parent no longer exists (deleted between runs), start over from the first
+ # parent — merge dedupes the re-pulled rows on the primary key.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = parents
+ resume_cursor: str | None = None
+ if resume is not None and resume.parent_id is not None:
+ parent_ids = [parent_id for parent_id, _ in parents]
+ if resume.parent_id in parent_ids:
+ remaining = parents[parent_ids.index(resume.parent_id) :]
+ resume_cursor = resume.cursor
+ logger.debug(f"Render: resuming {config.name} from parent_id={resume.parent_id}, cursor={resume_cursor}")
+
+ window_param = (
+ config.incremental_param_by_field.get(config.default_incremental_field)
+ if config.window_start_from_parent_field and config.default_incremental_field
+ else None
+ )
+
+ for index, (parent_id, parent_row) in enumerate(remaining):
+ child_params = dict(params)
+ # Events default to a one-hour server-side window, so always pass an explicit lower
+ # bound: the watermark when incremental, else the parent's creation time.
+ if window_param and window_param not in child_params:
+ window_start = parent_row.get(config.window_start_from_parent_field or "")
+ if window_start:
+ child_params[window_param] = window_start
+
+ if config.parent_query_param:
+ path = config.path
+ child_params[config.parent_query_param] = parent_id
+ else:
+ path = config.path.format(parent_id=parent_id)
+
+ cursor = resume_cursor
+ resume_cursor = None # only the resumed-into parent uses the saved cursor
+
+ try:
+ for rows, next_cursor in _walk_pages(
+ session, headers, logger, config, path, child_params, cursor, max_pages=config.max_pages_per_parent
+ ):
+ if config.inject_parent_key:
+ rows = [{config.inject_parent_key: parent_id, **row} for row in rows]
+ yield rows
+ if next_cursor:
+ resumable_source_manager.save_state(RenderResumeConfig(cursor=next_cursor, parent_id=parent_id))
+ except requests.HTTPError as exc:
+ # A parent deleted between enumeration and this fetch 404s. Skip it rather than
+ # failing the whole sync — the resource is genuinely gone.
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Render: {config.parent} {parent_id} not found while fetching {config.name}, skipping")
+ else:
+ raise
+
+ # Advance the bookmark to the next parent so a crash between parents resumes correctly.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(RenderResumeConfig(cursor=None, parent_id=remaining[index + 1][0]))
+
+
+def _redact_row(row: dict[str, Any], redact_spec: dict[str, tuple[str, ...]]) -> dict[str, Any]:
+ """Strip secret values out of a row before it reaches the warehouse.
+
+ Render's env-group payload carries the actual env var values and secret-file contents; the
+ API key is meant to *use* those for sync, not surface them as queryable columns. Replace the
+ value-bearing fields with a marker while keeping the surrounding metadata (names/keys/ids).
+ """
+ for list_field, secret_keys in redact_spec.items():
+ items = row.get(list_field)
+ if not isinstance(items, list):
+ continue
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ for key in secret_keys:
+ if key in item:
+ item[key] = REDACTED_VALUE
+ return row
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RenderResumeConfig],
+ owner_id: str | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = RENDER_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ # One session reused across every page (and, for fan-out, every parent) so urllib3 keeps
+ # the connection alive instead of re-handshaking per request. Sensitive endpoints opt out of
+ # HTTP sample capture — capture snapshots the raw response before row-level redaction runs.
+ session = make_tracked_session(capture=not config.is_sensitive)
+
+ params = _build_params(
+ config, owner_id, should_use_incremental_field, db_incremental_field_last_value, incremental_field, logger
+ )
+
+ if config.parent:
+ batches = _get_fan_out_rows(session, headers, logger, resumable_source_manager, config, params, owner_id)
+ else:
+ batches = _get_top_level_rows(session, headers, logger, resumable_source_manager, config, params)
+
+ if config.redact_list_item_fields:
+ for batch in batches:
+ yield [_redact_row(row, config.redact_list_item_fields) for row in batch]
+ else:
+ yield from batches
+
+
+def render_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RenderResumeConfig],
+ owner_id: str | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config = RENDER_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ owner_id=owner_id,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ # Render doesn't document list ordering and cursor pagination accepts no sort param, so
+ # the watermark is only safe to persist once the run completes (desc mode computes the
+ # max across all batches and saves it at successful job end).
+ sort_mode="desc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/render/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/render/settings.py
new file mode 100644
index 000000000000..b3e8a666d143
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/render/settings.py
@@ -0,0 +1,218 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+def _datetime_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class RenderEndpointConfig:
+ name: str
+ # Path relative to the API base. Fan-out children use a `{parent_id}` placeholder
+ # (or `parent_query_param` when the parent id is passed as a query param instead).
+ path: str
+ # Key the resource is nested under in each list item (Render wraps every item as
+ # `{"<wrapper_key>": {...}, "cursor": "..."}` — the cursor is a sibling of the resource).
+ wrapper_key: str
+ # Primary key columns for dedup. Fan-out children include the parent id: Render ids carry
+ # unique prefixes (dep-, job-, evt-) but global uniqueness isn't documented, and a
+ # non-unique key would multi-match on every delta merge.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Incremental field name -> server-side "after" query param (e.g. updatedAt -> updatedAfter).
+ # Only fields with a genuine server-side filter are advertised as incremental options.
+ incremental_param_by_field: dict[str, str] = field(default_factory=dict)
+ default_incremental_field: str | None = None
+ # Stable datetime field to partition by (createdAt-style, never updatedAt).
+ partition_key: str | None = None
+ # Fan-out: name of the parent endpoint whose rows seed this child's requests.
+ parent: str | None = None
+ # Pass the parent id as this query param instead of a `{parent_id}` path placeholder.
+ parent_query_param: str | None = None
+ # Column to copy the parent id onto child rows that don't carry it themselves
+ # (deploys and custom domains omit the service id from their payloads).
+ inject_parent_key: str | None = None
+ # Whether the endpoint accepts the `ownerId` filter (used to scope a multi-workspace key).
+ supports_owner_filter: bool = False
+ # Rows are immutable (events): append-only is the only incremental-style sync mode.
+ append_only: bool = False
+ # Fallback lower bound for endpoints whose time window defaults server-side to a recent
+ # slice (events default to the last hour) — read from this parent field when no
+ # incremental watermark applies, so a full refresh still covers the parent's lifetime.
+ window_start_from_parent_field: str | None = None
+ should_sync_default: bool = True
+ page_size: int = 100
+ # Hard cap on pages fetched per parent in a fan-out, to bound runaway pagination.
+ # A structured warning is logged if the cap is reached.
+ max_pages_per_parent: int = 500
+ # Some endpoints return secrets the API key is only meant to *use* for sync (env var
+ # values, secret-file contents), not data worth warehousing. Maps a list column to the
+ # item keys whose values are redacted before a row is yielded, keeping the safe metadata
+ # (names, keys, ids). Any endpoint with entries here is treated as sensitive: its raw
+ # responses are also excluded from HTTP sample capture (see `is_sensitive`).
+ redact_list_item_fields: dict[str, tuple[str, ...]] = field(default_factory=dict)
+
+ @property
+ def is_sensitive(self) -> bool:
+ return bool(self.redact_list_item_fields)
+
+
+RENDER_ENDPOINTS: dict[str, RenderEndpointConfig] = {
+ "owners": RenderEndpointConfig(
+ name="owners",
+ path="/owners",
+ wrapper_key="owner",
+ # No timestamps on the owner object and no time filters on the endpoint: full refresh only.
+ ),
+ "projects": RenderEndpointConfig(
+ name="projects",
+ path="/projects",
+ wrapper_key="project",
+ incremental_fields=[_datetime_field("updatedAt"), _datetime_field("createdAt")],
+ incremental_param_by_field={"updatedAt": "updatedAfter", "createdAt": "createdAfter"},
+ default_incremental_field="updatedAt",
+ supports_owner_filter=True,
+ ),
+ "environments": RenderEndpointConfig(
+ name="environments",
+ path="/environments",
+ wrapper_key="environment",
+ # The environment object carries no timestamps, so there is no watermark column to
+ # sync incrementally on despite the endpoint's updatedBefore/After filters.
+ primary_keys=["projectId", "id"],
+ parent="projects",
+ parent_query_param="projectId",
+ ),
+ "services": RenderEndpointConfig(
+ name="services",
+ path="/services",
+ wrapper_key="service",
+ incremental_fields=[_datetime_field("updatedAt"), _datetime_field("createdAt")],
+ incremental_param_by_field={"updatedAt": "updatedAfter", "createdAt": "createdAfter"},
+ default_incremental_field="updatedAt",
+ partition_key="createdAt",
+ supports_owner_filter=True,
+ ),
+ "deploys": RenderEndpointConfig(
+ name="deploys",
+ path="/services/{parent_id}/deploys",
+ wrapper_key="deploy",
+ primary_keys=["serviceId", "id"],
+ incremental_fields=[
+ _datetime_field("finishedAt"),
+ _datetime_field("updatedAt"),
+ _datetime_field("createdAt"),
+ ],
+ incremental_param_by_field={
+ "finishedAt": "finishedAfter",
+ "updatedAt": "updatedAfter",
+ "createdAt": "createdAfter",
+ },
+ # finishedAt: in-flight deploys (null finishedAt) are excluded by finishedAfter and
+ # picked up once they reach a terminal state, so each deploy lands exactly once with
+ # its final status — the right grain for deploy analytics.
+ default_incremental_field="finishedAt",
+ partition_key="createdAt",
+ parent="services",
+ inject_parent_key="serviceId",
+ ),
+ "jobs": RenderEndpointConfig(
+ name="jobs",
+ path="/services/{parent_id}/jobs",
+ wrapper_key="job",
+ primary_keys=["serviceId", "id"],
+ incremental_fields=[
+ _datetime_field("finishedAt"),
+ _datetime_field("startedAt"),
+ _datetime_field("createdAt"),
+ ],
+ incremental_param_by_field={
+ "finishedAt": "finishedAfter",
+ "startedAt": "startedAfter",
+ "createdAt": "createdAfter",
+ },
+ default_incremental_field="finishedAt",
+ partition_key="createdAt",
+ parent="services",
+ ),
+ "events": RenderEndpointConfig(
+ name="events",
+ path="/services/{parent_id}/events",
+ wrapper_key="event",
+ primary_keys=["serviceId", "id"],
+ incremental_fields=[_datetime_field("timestamp")],
+ incremental_param_by_field={"timestamp": "startTime"},
+ default_incremental_field="timestamp",
+ partition_key="timestamp",
+ parent="services",
+ append_only=True,
+ # The events window defaults to the last hour server-side, so every request must pass
+ # an explicit startTime; events can't predate their service, so its createdAt is a
+ # complete lower bound for full refreshes and first syncs.
+ window_start_from_parent_field="createdAt",
+ ),
+ "custom_domains": RenderEndpointConfig(
+ name="custom_domains",
+ path="/services/{parent_id}/custom-domains",
+ wrapper_key="customDomain",
+ primary_keys=["serviceId", "id"],
+ # Only createdBefore/After filters exist, but verificationStatus mutates after
+ # creation — a createdAt cursor would freeze it. Tiny table: full refresh only.
+ parent="services",
+ inject_parent_key="serviceId",
+ ),
+ "env_groups": RenderEndpointConfig(
+ name="env_groups",
+ path="/env-groups",
+ # The docs show env group list items unwrapped (no cursor sibling); the transport
+ # falls back to treating the item as the row when the wrapper key is absent.
+ wrapper_key="envGroup",
+ incremental_fields=[_datetime_field("updatedAt"), _datetime_field("createdAt")],
+ incremental_param_by_field={"updatedAt": "updatedAfter", "createdAt": "createdAfter"},
+ default_incremental_field="updatedAt",
+ supports_owner_filter=True,
+ # The list response embeds env var values and secret-file contents (database URLs, API
+ # tokens, …). Redact the value-bearing fields so only names/keys/ids reach the warehouse.
+ redact_list_item_fields={"envVars": ("value",), "secretFiles": ("content", "contents")},
+ ),
+ "postgres": RenderEndpointConfig(
+ name="postgres",
+ path="/postgres",
+ wrapper_key="postgres",
+ incremental_fields=[_datetime_field("updatedAt"), _datetime_field("createdAt")],
+ incremental_param_by_field={"updatedAt": "updatedAfter", "createdAt": "createdAfter"},
+ default_incremental_field="updatedAt",
+ supports_owner_filter=True,
+ ),
+ "key_value": RenderEndpointConfig(
+ name="key_value",
+ path="/key-value",
+ wrapper_key="keyValue",
+ incremental_fields=[_datetime_field("updatedAt"), _datetime_field("createdAt")],
+ incremental_param_by_field={"updatedAt": "updatedAfter", "createdAt": "createdAfter"},
+ default_incremental_field="updatedAt",
+ supports_owner_filter=True,
+ ),
+ "disks": RenderEndpointConfig(
+ name="disks",
+ path="/disks",
+ wrapper_key="disk",
+ incremental_fields=[_datetime_field("updatedAt"), _datetime_field("createdAt")],
+ incremental_param_by_field={"updatedAt": "updatedAfter", "createdAt": "createdAfter"},
+ default_incremental_field="updatedAt",
+ supports_owner_filter=True,
+ ),
+}
+
+ENDPOINTS = tuple(RENDER_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in RENDER_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/render/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/render/source.py
index d96d755d8b21..bf1a846cc617 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/render/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/render/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from 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 SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import RenderSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.render.render import (
+ RenderResumeConfig,
+ render_source,
+ validate_credentials as validate_render_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.render.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ RENDER_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class RenderSource(SimpleSource[RenderSourceConfig]):
+class RenderSource(ResumableSource[RenderSourceConfig, RenderResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.RENDER
@@ -24,8 +48,109 @@ class RenderSource(SimpleSource[RenderSourceConfig]):
name=SchemaExternalDataSourceType.RENDER,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Render",
- iconPath="/static/services/render.png",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Render API key to pull your services, deploys, jobs, and databases into the PostHog Data warehouse.
+
+You can create an API key in your [Render account settings](https://dashboard.render.com/settings#api-keys).
+
+An API key grants access to every workspace your user belongs to. To sync a single workspace, set the optional workspace ID (found in your workspace settings, or via the `owners` table).
+""",
+ iconPath="/static/services/render.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/render",
keywords=["cloud", "hosting", "deploys", "infrastructure"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="rnd_...",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="owner_id",
+ label="Workspace ID (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="tea-...",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.render.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # An invalid or revoked Render API key surfaces as a requests HTTPError when
+ # `_fetch_page` calls `raise_for_status()`. Retrying can never satisfy a credential
+ # problem, so stop the sync. Match the stable status text and base host, not the
+ # per-request path/query.
+ return {
+ "401 Client Error: Unauthorized for url: https://api.render.com": "Your Render API key is invalid or has been revoked. Create a new API key in your Render account settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.render.com": "Your Render API key does not have access to this resource. Check the key's workspace access, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: RenderSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = RENDER_ENDPOINTS[endpoint]
+ has_incremental = bool(endpoint_config.incremental_fields)
+ return SourceSchema(
+ name=endpoint,
+ # Events are immutable, so append-only is the only incremental-style sync mode;
+ # every other resource mutates and needs merge semantics.
+ supports_incremental=has_incremental and not endpoint_config.append_only,
+ supports_append=has_incremental and endpoint_config.append_only,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: RenderSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_render_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Render API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RenderResumeConfig]:
+ return ResumableSourceManager[RenderResumeConfig](inputs, RenderResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: RenderSourceConfig,
+ resumable_source_manager: ResumableSourceManager[RenderResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return render_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ owner_id=config.owner_id,
+ 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,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/render/tests/test_render.py b/products/warehouse_sources/backend/temporal/data_imports/sources/render/tests/test_render.py
new file mode 100644
index 000000000000..86d7ed0cf49c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/render/tests/test_render.py
@@ -0,0 +1,444 @@
+from datetime import UTC, date, datetime, timedelta, timezone
+from typing import Any, cast
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.render import render
+from products.warehouse_sources.backend.temporal.data_imports.sources.render.render import (
+ RenderResumeConfig,
+ _build_params,
+ _fetch_page,
+ _format_incremental_value,
+ _unwrap_item,
+ get_rows,
+ render_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.render.settings import (
+ RENDER_ENDPOINTS,
+ RenderEndpointConfig,
+)
+
+
+def _response(payload: Any, status: int = 200) -> MagicMock:
+ response = MagicMock(spec=requests.Response)
+ response.status_code = status
+ response.ok = status < 400
+ response.text = ""
+ response.json.return_value = payload
+ if status >= 400:
+ response.raise_for_status.side_effect = requests.HTTPError(
+ f"{status} Client Error: Error for url: https://api.render.com", response=response
+ )
+ return response
+
+
+class FakeSession:
+ """Returns queued page payloads in request order and records every requested URL."""
+
+ def __init__(self, responses: list[Any]) -> None:
+ self._responses = list(responses)
+ self.urls: list[str] = []
+
+ def get(self, url: str, headers: dict | None = None, timeout: int | None = None) -> Any:
+ self.urls.append(url)
+ response = self._responses.pop(0)
+ if isinstance(response, MagicMock):
+ return response
+ return _response(response)
+
+
+def _manager(resume: RenderResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock()
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+def _rows(
+ endpoint: str,
+ responses: list[Any],
+ manager: MagicMock | None = None,
+ owner_id: str | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> tuple[list[list[dict]], FakeSession, MagicMock]:
+ session = FakeSession(responses)
+ manager = manager if manager is not None else _manager()
+ with patch.object(render, "make_tracked_session", return_value=session):
+ batches = list(
+ get_rows(
+ api_key="rnd_test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ owner_id=owner_id,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ )
+ )
+ return batches, session, manager
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlparse(url).query)
+
+
+class TestFormatIncrementalValue:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ (
+ # Watermarks come back from the pipeline in whatever offset the API row carried;
+ # sending a non-UTC offset to Render's ISO filters is undocumented territory.
+ "non_utc_offset_converted",
+ datetime(2026, 3, 4, 4, 58, 14, tzinfo=timezone(timedelta(hours=2))),
+ "2026-03-04T02:58:14Z",
+ ),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),
+ ("string_passthrough", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),
+ ]
+ )
+ def test_format_incremental_value(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_incremental_value(value) == expected
+
+
+class TestUnwrapItem:
+ @parameterized.expand(
+ [
+ (
+ "wrapped_with_sibling_cursor",
+ {"service": {"id": "srv-1"}, "cursor": "c1"},
+ "service",
+ ({"id": "srv-1"}, "c1"),
+ ),
+ (
+ "unwrapped_env_group_shape",
+ {"id": "evg-1", "name": "group"},
+ "envGroup",
+ ({"id": "evg-1", "name": "group"}, None),
+ ),
+ ]
+ )
+ def test_unwrap_item(self, _name: str, item: dict, wrapper_key: str, expected: tuple) -> None:
+ assert _unwrap_item(item, wrapper_key) == expected
+
+
+class TestBuildParams:
+ WATERMARK = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)
+
+ @parameterized.expand(
+ [
+ ("services_updated_at", "services", "updatedAt", {"updatedAfter": "2026-03-04T02:58:14Z"}),
+ ("deploys_finished_at", "deploys", "finishedAt", {"finishedAfter": "2026-03-04T02:58:14Z"}),
+ ("deploys_default_field", "deploys", None, {"finishedAfter": "2026-03-04T02:58:14Z"}),
+ ("events_timestamp_maps_to_start_time", "events", "timestamp", {"startTime": "2026-03-04T02:58:14Z"}),
+ ]
+ )
+ def test_incremental_field_maps_to_server_side_filter(
+ self, _name: str, endpoint: str, incremental_field: str | None, expected_params: dict
+ ) -> None:
+ params = _build_params(
+ RENDER_ENDPOINTS[endpoint],
+ owner_id=None,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=self.WATERMARK,
+ incremental_field=incremental_field,
+ logger=MagicMock(),
+ )
+ for key, value in expected_params.items():
+ assert params[key] == value
+
+ def test_no_watermark_means_no_time_filter(self) -> None:
+ params = _build_params(
+ RENDER_ENDPOINTS["services"],
+ owner_id=None,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="updatedAt",
+ logger=MagicMock(),
+ )
+ assert "updatedAfter" not in params
+
+ @parameterized.expand(
+ [
+ ("owner_filter_on_supporting_endpoint", "services", True),
+ ("no_owner_filter_on_fan_out_child", "deploys", False),
+ ]
+ )
+ def test_owner_filter(self, _name: str, endpoint: str, expects_owner: bool) -> None:
+ params = _build_params(
+ RENDER_ENDPOINTS[endpoint],
+ owner_id="tea-123",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ logger=MagicMock(),
+ )
+ assert ("ownerId" in params) == expects_owner
+
+ def test_incremental_field_without_server_filter_is_skipped(self) -> None:
+ config = RenderEndpointConfig(name="x", path="/x", wrapper_key="x", default_incremental_field="updatedAt")
+ logger = MagicMock()
+ params = _build_params(
+ config,
+ owner_id=None,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=self.WATERMARK,
+ incremental_field="updatedAt",
+ logger=logger,
+ )
+ assert params == {"limit": 100}
+ logger.warning.assert_called_once()
+
+
+class TestPagination:
+ def test_follows_last_item_cursor_and_stops_on_empty_page(self) -> None:
+ batches, session, manager = _rows(
+ "services",
+ [
+ [
+ {"service": {"id": "srv-1"}, "cursor": "c1"},
+ {"service": {"id": "srv-2"}, "cursor": "c2"},
+ ],
+ [{"service": {"id": "srv-3"}, "cursor": "c3"}],
+ [],
+ ],
+ )
+
+ assert batches == [[{"id": "srv-1"}, {"id": "srv-2"}], [{"id": "srv-3"}]]
+ assert "cursor" not in _query(session.urls[0])
+ assert _query(session.urls[1])["cursor"] == ["c2"]
+ assert _query(session.urls[2])["cursor"] == ["c3"]
+ # State saved after each yielded page so a crash re-yields the last page.
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert [state.cursor for state in saved] == ["c2", "c3"]
+
+ def test_resume_starts_from_saved_cursor(self) -> None:
+ batches, session, _ = _rows(
+ "services",
+ [[{"service": {"id": "srv-9"}, "cursor": "c9"}], []],
+ manager=_manager(RenderResumeConfig(cursor="c-resume")),
+ )
+
+ assert _query(session.urls[0])["cursor"] == ["c-resume"]
+ assert batches == [[{"id": "srv-9"}]]
+
+ def test_full_page_without_cursor_stops_instead_of_looping(self) -> None:
+ # Unwrapped responses (env groups) carry no cursor: a full page must terminate with a
+ # truncation warning, not refetch the same page forever.
+ page = [{"id": f"evg-{i}"} for i in range(100)]
+ batches, session, _ = _rows("env_groups", [page])
+
+ assert len(batches) == 1
+ assert len(session.urls) == 1
+
+
+class TestFanOut:
+ SERVICES_PAGE = [
+ {"service": {"id": "srv-1", "createdAt": "2024-01-01T00:00:00Z"}},
+ {"service": {"id": "srv-2", "createdAt": "2024-02-01T00:00:00Z"}},
+ ]
+
+ def test_deploys_fetched_per_service_with_injected_service_id(self) -> None:
+ batches, session, manager = _rows(
+ "deploys",
+ [
+ self.SERVICES_PAGE,
+ [{"deploy": {"id": "dep-1", "status": "live"}}],
+ [{"deploy": {"id": "dep-2", "status": "live"}}],
+ ],
+ )
+
+ assert urlparse(session.urls[1]).path == "/v1/services/srv-1/deploys"
+ assert urlparse(session.urls[2]).path == "/v1/services/srv-2/deploys"
+ # Deploy payloads omit the service id; rows must carry it for the composite primary key.
+ assert batches == [
+ [{"serviceId": "srv-1", "id": "dep-1", "status": "live"}],
+ [{"serviceId": "srv-2", "id": "dep-2", "status": "live"}],
+ ]
+ # The bookmark advances to the next parent so a crash between parents resumes correctly.
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert RenderResumeConfig(cursor=None, parent_id="srv-2") in saved
+
+ def test_deleted_parent_404_is_skipped(self) -> None:
+ batches, _, _ = _rows(
+ "deploys",
+ [
+ self.SERVICES_PAGE,
+ _response({"message": "Not Found"}, status=404),
+ [{"deploy": {"id": "dep-2"}}],
+ ],
+ )
+
+ assert batches == [[{"serviceId": "srv-2", "id": "dep-2"}]]
+
+ def test_resume_skips_parents_before_bookmark_and_seeds_cursor(self) -> None:
+ batches, session, _ = _rows(
+ "deploys",
+ [
+ self.SERVICES_PAGE,
+ [{"deploy": {"id": "dep-5"}}],
+ ],
+ manager=_manager(RenderResumeConfig(cursor="c-mid", parent_id="srv-2")),
+ )
+
+ deploy_urls = [url for url in session.urls if "/deploys" in url]
+ assert len(deploy_urls) == 1
+ assert urlparse(deploy_urls[0]).path == "/v1/services/srv-2/deploys"
+ assert _query(deploy_urls[0])["cursor"] == ["c-mid"]
+
+ def test_resume_bookmark_for_deleted_parent_restarts_from_first_parent(self) -> None:
+ _, session, _ = _rows(
+ "deploys",
+ [
+ self.SERVICES_PAGE,
+ [{"deploy": {"id": "dep-1"}}],
+ [{"deploy": {"id": "dep-2"}}],
+ ],
+ manager=_manager(RenderResumeConfig(cursor="c-mid", parent_id="srv-gone")),
+ )
+
+ deploy_urls = [url for url in session.urls if "/deploys" in url]
+ assert urlparse(deploy_urls[0]).path == "/v1/services/srv-1/deploys"
+ assert "cursor" not in _query(deploy_urls[0])
+
+ def test_environments_pass_project_id_as_query_param(self) -> None:
+ _, session, _ = _rows(
+ "environments",
+ [
+ [{"project": {"id": "prj-1"}}],
+ [{"environment": {"id": "env-1", "projectId": "prj-1"}}],
+ ],
+ )
+
+ env_url = session.urls[1]
+ assert urlparse(env_url).path == "/v1/environments"
+ assert _query(env_url)["projectId"] == ["prj-1"]
+
+ def test_events_full_refresh_uses_service_created_at_as_window_start(self) -> None:
+ # The events endpoint defaults to the last hour server-side; omitting startTime on a
+ # full refresh would silently drop everything older.
+ _, session, _ = _rows(
+ "events",
+ [
+ [{"service": {"id": "srv-1", "createdAt": "2024-01-01T00:00:00Z"}}],
+ [{"event": {"id": "evt-1", "serviceId": "srv-1"}}],
+ ],
+ )
+
+ assert _query(session.urls[1])["startTime"] == ["2024-01-01T00:00:00Z"]
+
+ def test_events_incremental_watermark_overrides_window_start(self) -> None:
+ _, session, _ = _rows(
+ "events",
+ [
+ [{"service": {"id": "srv-1", "createdAt": "2024-01-01T00:00:00Z"}}],
+ [{"event": {"id": "evt-1", "serviceId": "srv-1"}}],
+ ],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="timestamp",
+ )
+
+ assert _query(session.urls[1])["startTime"] == ["2026-03-04T02:58:14Z"]
+
+
+class TestSensitiveEndpointHandling:
+ def test_env_group_secret_values_are_redacted_from_rows(self) -> None:
+ # Env var values and secret-file contents are credentials the key is only meant to use
+ # for sync; leaking them into a queryable table exposes database URLs and API tokens.
+ batches, _, _ = _rows(
+ "env_groups",
+ [
+ [
+ {
+ "id": "evg-1",
+ "name": "prod",
+ "envVars": [{"key": "DATABASE_URL", "value": "postgres://user:pw@host/db"}],
+ "secretFiles": [{"name": "config.yaml", "contents": "token: super-secret"}],
+ }
+ ],
+ ],
+ )
+
+ row = batches[0][0]
+ # Metadata survives so the table stays useful.
+ assert row["id"] == "evg-1"
+ assert row["name"] == "prod"
+ assert row["envVars"][0]["key"] == "DATABASE_URL"
+ assert row["secretFiles"][0]["name"] == "config.yaml"
+ # The actual secrets do not.
+ assert row["envVars"][0]["value"] == render.REDACTED_VALUE
+ assert row["secretFiles"][0]["contents"] == render.REDACTED_VALUE
+
+ @parameterized.expand(
+ [
+ # Sensitive endpoints skip sample capture — capture snapshots the raw response before
+ # row-level redaction, so it would otherwise persist secrets to the sample store.
+ ("env_groups", [{"id": "evg-1"}], False),
+ ("owners", [{"owner": {"id": "own-1"}}], True),
+ ]
+ )
+ def test_sample_capture_disabled_for_sensitive_endpoints(
+ self, endpoint: str, page: list[dict], expected_capture: bool
+ ) -> None:
+ session = FakeSession([page])
+ with patch.object(render, "make_tracked_session", return_value=session) as make_session:
+ list(
+ get_rows(
+ api_key="rnd_test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+ )
+
+ make_session.assert_called_once_with(capture=expected_capture)
+
+
+class TestFetchPage:
+ def test_retryable_status_is_retried_until_success(self) -> None:
+ session = FakeSession([_response({"message": "rate limited"}, status=429), [{"owner": {"id": "own-1"}}]])
+ result = _fetch_page(cast(requests.Session, session), "https://api.render.com/v1/owners", {}, MagicMock())
+
+ assert result == [{"owner": {"id": "own-1"}}]
+ assert len(session.urls) == 2
+
+ def test_auth_error_raises_without_retry(self) -> None:
+ session = FakeSession([_response({"message": "Unauthorized"}, status=401)])
+ with pytest.raises(requests.HTTPError):
+ _fetch_page(cast(requests.Session, session), "https://api.render.com/v1/owners", {}, MagicMock())
+
+ assert len(session.urls) == 1
+
+
+class TestRenderSourceResponse:
+ @parameterized.expand(
+ [
+ ("services", ["id"], ["createdAt"]),
+ # Fan-out children key on (parent, id): a non-unique key multi-matches on every
+ # delta merge and degrades each sync until the pod OOMs.
+ ("deploys", ["serviceId", "id"], ["createdAt"]),
+ ("events", ["serviceId", "id"], ["timestamp"]),
+ ("owners", ["id"], None),
+ ]
+ )
+ def test_source_response_keys_and_partitioning(
+ self, endpoint: str, expected_primary_keys: list[str], expected_partition_keys: list[str] | None
+ ) -> None:
+ response = render_source(
+ api_key="rnd_test", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()
+ )
+
+ assert response.primary_keys == expected_primary_keys
+ assert response.partition_keys == expected_partition_keys
+ # Render documents no list ordering, so the watermark must only persist at job end.
+ assert response.sort_mode == "desc"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/render/tests/test_render_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/render/tests/test_render_source.py
new file mode 100644
index 000000000000..17a7208c4958
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/render/tests/test_render_source.py
@@ -0,0 +1,140 @@
+from datetime import UTC, datetime
+
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import RenderSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.render import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.render.render import RenderResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.render.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.render.source import RenderSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _inputs(
+ schema_name: str = "services",
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: object = None,
+ incremental_field: str | None = None,
+) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-id",
+ source_id="source-id",
+ team_id=1,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ db_incremental_field_earliest_value=None,
+ incremental_field=incremental_field,
+ incremental_field_type=None,
+ job_id="job-id",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestRenderSource:
+ def setup_method(self) -> None:
+ self.source = RenderSource()
+ self.config = RenderSourceConfig(api_key="rnd_test", owner_id="tea-123")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.RENDER
+
+ def test_source_config_fields(self) -> None:
+ fields = self.source.get_source_config.fields
+ by_name = {field.name: field for field in fields}
+
+ api_key = by_name["api_key"]
+ assert isinstance(api_key, SourceFieldInputConfig)
+ assert api_key.required is True
+ assert api_key.secret is True
+
+ owner_id = by_name["owner_id"]
+ assert isinstance(owner_id, SourceFieldInputConfig)
+ assert owner_id.required is False
+
+ def test_get_schemas_covers_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1)
+ assert [schema.name for schema in schemas] == list(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ # Mutating resources with a server-side time filter sync incrementally via merge.
+ ("services", True, False),
+ ("deploys", True, False),
+ # Events are immutable: append-only, never merge-incremental.
+ ("events", False, True),
+ # No usable watermark column: full refresh only.
+ ("owners", False, False),
+ ("environments", False, False),
+ ("custom_domains", False, False),
+ ]
+ )
+ def test_get_schemas_sync_modes(self, endpoint: str, supports_incremental: bool, supports_append: bool) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, team_id=1) if s.name == endpoint)
+ assert schema.supports_incremental == supports_incremental
+ assert schema.supports_append == supports_append
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1, names=["services", "deploys"])
+ assert {schema.name for schema in schemas} == {"services", "deploys"}
+
+ @parameterized.expand([("valid", True, True), ("invalid", False, False)])
+ def test_validate_credentials(self, _name: str, probe_result: bool, expected_valid: bool) -> None:
+ with patch.object(source_module, "validate_render_credentials", return_value=probe_result):
+ valid, error = self.source.validate_credentials(self.config, team_id=1)
+
+ assert valid == expected_valid
+ assert (error is None) == expected_valid
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_inputs())
+ assert manager._data_class is RenderResumeConfig
+
+ def test_source_for_pipeline_passes_config_and_incremental_state(self) -> None:
+ inputs = _inputs(
+ schema_name="deploys",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ incremental_field="finishedAt",
+ )
+ manager = MagicMock()
+ with patch.object(source_module, "render_source") as mock_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "rnd_test"
+ assert kwargs["owner_id"] == "tea-123"
+ assert kwargs["endpoint"] == "deploys"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == datetime(2026, 3, 4, tzinfo=UTC)
+ assert kwargs["incremental_field"] == "finishedAt"
+
+ def test_source_for_pipeline_drops_watermark_on_full_refresh(self) -> None:
+ # A stale watermark leaking into a full refresh would silently skip older rows.
+ inputs = _inputs(
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ )
+ with patch.object(source_module, "render_source") as mock_source:
+ self.source.source_for_pipeline(self.config, MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_non_retryable_errors_match_requests_error_format(self) -> None:
+ # The pipeline disables a source by substring-matching these keys against the raised
+ # error; they must match the message `requests.raise_for_status` actually produces.
+ response = MagicMock(spec=requests.Response)
+ response.status_code = 401
+ response.reason = "Unauthorized"
+ response.url = "https://api.render.com/v1/services?limit=100"
+ error = requests.HTTPError(f"401 Client Error: Unauthorized for url: {response.url}", response=response)
+
+ assert any(key in str(error) for key in self.source.get_non_retryable_errors())