: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 replicate import source (#70005)
Tom Owersa603de10988d
diff --git a/frontend/public/services/replicate.svg b/frontend/public/services/replicate.svgnew file mode 100644index 000000000000..f9d8aae3dd0a--- /dev/null+++ b/frontend/public/services/replicate.svg@@ -0,0 +1 @@+<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Replicate</title><path d="M24 10.262v2.712h-9.518V24h-3.034V10.262zm0-5.131v2.717H8.755V24H5.722V5.131zM24 0v2.717H3.034V24H0V0z"/></svg>diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 9131d97d5a79..0a303de31567 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -331,6 +331,7 @@ the row lists both.| reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || redshift | DB protocol | psycopg (Postgres-compatible) | ➖ || rentcast | HTTP | requests | ✅ |+| replicate | HTTP | requests | ✅ || reply_io | HTTP | requests | ✅ || resend | HTTP | requests | ✅ || retently | HTTP | requests | ✅ |@@ -741,7 +742,6 @@ doesn't conflict with concurrent PRs.- referralhero- render- repairshopr-- replicate- reply_io- retail_express- retell_aidiff --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 8e5e62292f56..00d75dc9fb7b 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@@ -3123,7 +3123,7 @@ class RepairshoprSourceConfig(config.Config):@config.configclass ReplicateSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/canonical_descriptions.pynew file mode 100644index 000000000000..d5880843af39--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/canonical_descriptions.py@@ -0,0 +1,90 @@+"""Canonical, documentation-sourced descriptions for Replicate endpoints and columns.++Sourced from the official Replicate HTTP API reference (https://replicate.com/docs/reference/http).+Keyed by the endpoint names in `settings.py` `REPLICATE_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Replicate table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Predictions and trainings share the same run-record shape.+_RUN_COLUMNS = {+ "id": "Unique identifier for the run.",+ "model": "The model that was run, as owner/name.",+ "version": "The specific model version that was run.",+ "status": "Current status: starting, processing, succeeded, failed, or canceled.",+ "input": "The input payload the run was created with. Removed ~1 hour after completion for API-created runs.",+ "output": "The output the run produced. Removed ~1 hour after completion for API-created runs.",+ "error": "The error the run raised, if it failed.",+ "logs": "Execution logs. Removed ~1 hour after completion for API-created runs.",+ "source": "How the run was created: web or api.",+ "created_at": "Time at which the run was created.",+ "started_at": "Time at which the run started processing.",+ "completed_at": "Time at which the run finished (succeeded, failed, or canceled).",+ "metrics": "Runtime metrics such as predict_time.",+ "data_removed": "Whether the input/output/logs have been removed by Replicate's retention policy.",+ "urls": "API URLs to fetch, cancel, or view the run.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "predictions": {+ "description": "A prediction is a single run of a model on Replicate, with its input, output, status and timing.",+ "docs_url": "https://replicate.com/docs/reference/http#predictions.list",+ "columns": _RUN_COLUMNS,+ },+ "trainings": {+ "description": "A training is a fine-tuning run that produces a new model version from a base model.",+ "docs_url": "https://replicate.com/docs/reference/http#trainings.list",+ "columns": {+ **_RUN_COLUMNS,+ "output": "The training output, including the created model version and its weights.",+ },+ },+ "deployments": {+ "description": "A deployment is a private, managed endpoint for running a model with your own scaling configuration.",+ "docs_url": "https://replicate.com/docs/reference/http#deployments.list",+ "columns": {+ "owner": "The account that owns the deployment.",+ "name": "The deployment's name.",+ "current_release": "The currently deployed release, including its model, version and configuration.",+ },+ },+ "models": {+ "description": "A model on Replicate that can be run to make predictions. This table lists the public model catalog.",+ "docs_url": "https://replicate.com/docs/reference/http#models.list",+ "columns": {+ "url": "The web URL of the model.",+ "owner": "The account that owns the model.",+ "name": "The model's name.",+ "description": "A description of what the model does.",+ "visibility": "Whether the model is public or private.",+ "github_url": "The GitHub repository backing the model, if any.",+ "paper_url": "A link to a paper describing the model, if any.",+ "license_url": "A link to the model's license, if any.",+ "run_count": "The number of times the model has been run.",+ "cover_image_url": "A cover image for the model.",+ "default_example": "An example prediction for the model.",+ "latest_version": "The most recent version of the model.",+ },+ },+ "hardware": {+ "description": "A hardware SKU available for running models on Replicate.",+ "docs_url": "https://replicate.com/docs/reference/http#hardware.list",+ "columns": {+ "name": "Human-readable hardware name (e.g. Nvidia T4 GPU).",+ "sku": "The hardware SKU identifier (e.g. gpu-t4).",+ },+ },+ "account": {+ "description": "The authenticated Replicate account.",+ "docs_url": "https://replicate.com/docs/reference/http#accounts.get",+ "columns": {+ "type": "The account type: user or organization.",+ "username": "The account's username.",+ "name": "The account's display name.",+ "github_url": "The account's GitHub URL.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/replicate.py b/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/replicate.pynew file mode 100644index 000000000000..0fa537f0c695--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/replicate.py@@ -0,0 +1,273 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urlsplit, urlunsplit++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.replicate.settings import (+ REPLICATE_ENDPOINTS,+ ReplicateEndpointConfig,+)++REPLICATE_BASE_URL = "https://api.replicate.com/v1"+REPLICATE_API_HOST = "api.replicate.com"+++class ReplicateRetryableError(Exception):+ pass+++class ReplicateResumeConfig:+ # Full next-page URL returned by the API (carries the opaque cursor and any created_after filter).+ # None means "start the endpoint from its first page".+ next_url: str | None = None+ # The `created_after` watermark this cursor was built against. A run whose watermark has since+ # advanced must not resume from this cursor (see `get_rows`), so we can tell the two apart.+ created_after: 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 an incremental cursor for Replicate's ISO 8601 `created_after` filter.++ Replicate returns and accepts UTC timestamps with a `Z` suffix (e.g.+ `2023-09-08T16:19:34.765994Z`), so we normalize to that rather than the `+00:00`+ offset `isoformat()` emits.+ """+ if isinstance(value, datetime):+ utc_dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_dt.isoformat().replace("+00:00", "Z")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat().replace("+00:00", "Z")+ return str(value)+++def _parse_datetime(value: Any) -> datetime | None:+ """Parse a Replicate ISO 8601 timestamp into an aware datetime, tolerating the Z suffix."""+ if not isinstance(value, str) or not value:+ return None+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed+++def _to_cutoff(value: Any) -> datetime | None:+ if isinstance(value, datetime):+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ return _parse_datetime(value)+++def validate_credentials(api_key: str) -> bool:+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(+ f"{REPLICATE_BASE_URL}/account", headers=_get_headers(api_key), timeout=10+ )+ return response.status_code == 200+ except Exception:+ return False+++@retry(+ retry=retry_if_exception_type(+ (+ ReplicateRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:+ response = session.get(url, headers=headers, timeout=60)++ # Replicate rate-limits at 3,000 req/min for read endpoints (429 on excess); 5xx are transient.+ if response.status_code == 429 or response.status_code >= 500:+ raise ReplicateRetryableError(f"Replicate API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Replicate API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _extract_items(data: Any, config: ReplicateEndpointConfig) -> list[dict[str, Any]]:+ if config.response_shape == "object":+ # A single-object endpoint (e.g. /account) becomes one row.+ return [data] if isinstance(data, dict) else []+ if config.response_shape == "list":+ # A bare JSON array (e.g. /hardware).+ return data if isinstance(data, list) else []+ # Paginated: rows live under "results".+ return data.get("results", []) if isinstance(data, dict) else []+++def _sanitize_next_url(raw_url: str | None) -> str | None:+ """Pin a Replicate pagination URL to the fixed HTTPS API origin.++ Replicate's documented pagination `next` (and any cursor loaded from resume state) can come+ back as `http://api.replicate.com/...`, which would send the bearer token over plaintext where+ an on-path attacker could capture it. Only the path and query are trusted; the scheme is forced+ to https and the host must be Replicate's API host, otherwise we stop rather than follow it.+ """+ if not raw_url:+ return None+ parts = urlsplit(raw_url)+ if parts.hostname != REPLICATE_API_HOST:+ return None+ return urlunsplit(("https", REPLICATE_API_HOST, parts.path, parts.query, ""))+++def _next_url(data: Any) -> str | None:+ if isinstance(data, dict):+ return _sanitize_next_url(data.get("next"))+ return None+++def _build_initial_url(+ config: ReplicateEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> str:+ base = f"{REPLICATE_BASE_URL}{config.path}"+ if config.time_filter_param and should_use_incremental_field and db_incremental_field_last_value is not None:+ query = urlencode({config.time_filter_param: _format_incremental_value(db_incremental_field_last_value)})+ return f"{base}?{query}"+ return base+++def _page_predates_cutoff(items: list[dict[str, Any]], incremental_field: str, cutoff: datetime) -> bool:+ """True when every dated row in the page is at/older than the cutoff.++ Replicate returns predictions newest-first, so once a whole page predates the watermark there is+ nothing newer left to fetch. This bounds the walk even if the server silently ignores+ `created_after` on paginated requests (unverified against the live API), matching the skill's+ "incremental pagination must terminate at the watermark" rule. Merge dedupes the boundary re-read.+ """+ parsed = [_parse_datetime(item.get(incremental_field)) for item in items]+ dated = [d for d in parsed if d is not None]+ if not dated:+ return False+ return max(dated) <= cutoff+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ReplicateResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = REPLICATE_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # One session reused across every page so urllib3 keeps the connection alive. Redact the token so+ # it never lands in tracked HTTP logs, and disable capture entirely: prediction responses carry+ # user-authored model inputs, outputs, and logs that the generic scrubber can't reliably sanitize.+ session = make_tracked_session(redact_values=(api_key,), capture=False)++ # Single-request endpoints (bare array / single object) have no pagination or resume state.+ if config.response_shape != "paginated":+ data = _fetch_page(session, f"{REPLICATE_BASE_URL}{config.path}", headers, logger)+ items = _extract_items(data, config)+ if items:+ yield items+ return++ incremental = config.time_filter_param is not None and should_use_incremental_field+ current_watermark = (+ _format_incremental_value(db_incremental_field_last_value)+ if incremental and db_incremental_field_last_value is not None+ else None+ )++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ resumed_url = _sanitize_next_url(resume.next_url) if resume is not None else None+ # Only honor a saved cursor when it was written for the current watermark. If the watermark has+ # advanced, resuming from an older descending page would skip predictions created since the prior+ # run (they live on the first page), so rebuild from the initial URL instead.+ if resumed_url and resume is not None and resume.created_after == current_watermark:+ url = resumed_url+ logger.debug(f"Replicate: resuming {endpoint} from URL: {url}")+ else:+ url = _build_initial_url(config, should_use_incremental_field, db_incremental_field_last_value)++ cutoff = _to_cutoff(db_incremental_field_last_value) if incremental else None+ cursor_field = incremental_field or (config.incremental_fields[0]["field"] if config.incremental_fields else None)++ while True:+ data = _fetch_page(session, url, headers, logger)+ items = _extract_items(data, config)++ if items:+ yield items++ next_url = _next_url(data)++ # Desc + incremental: stop once a whole page predates the watermark, so we don't re-walk the+ # entire history if the server drops the created_after filter on later cursor pages.+ if next_url and cutoff is not None and cursor_field and _page_predates_cutoff(items, cursor_field, cutoff):+ break++ if not next_url:+ break++ # Save AFTER yielding, so a crash re-yields the last page rather than skipping it (merge+ # dedupes on the primary key). Tag it with the watermark so a later run with an advanced+ # watermark rebuilds from the first page instead of trusting this cursor.+ resumable_source_manager.save_state(ReplicateResumeConfig(next_url=next_url, created_after=current_watermark))+ url = next_url+++def replicate_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ReplicateResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = REPLICATE_ENDPOINTS[endpoint]++ 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,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ sort_mode=config.sort_mode,+ 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,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/settings.pynew file mode 100644index 000000000000..cb5498c17fe2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/settings.py@@ -0,0 +1,94 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# How the endpoint wraps its rows:+# - "paginated": Replicate's cursor pagination — `{"results": [...], "next": url, "previous": url}`.+# - "list": a bare JSON array (e.g. /v1/hardware).+# - "object": a single JSON object materialized as one row (e.g. /v1/account).+ResponseShape = Literal["paginated", "list", "object"]+++@dataclass+class ReplicateEndpointConfig:+ name: str+ path: str+ response_shape: ResponseShape = "paginated"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable, immutable field to partition by. Never a mutable field like a status timestamp.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # The server-side query param that filters by the incremental field, if the API exposes one.+ # Only predictions documents a genuine server filter (`created_after`); everything else is+ # cursor-only and therefore ships full-refresh.+ time_filter_param: Optional[str] = None+ # Replicate's list endpoints return most-recent-first and expose no ascending sort, so the rows+ # arrive descending by created_at. SourceResponse.sort_mode must match the real emission order.+ sort_mode: Literal["asc", "desc"] = "desc"+ should_sync_default: bool = True+++REPLICATE_ENDPOINTS: dict[str, ReplicateEndpointConfig] = {+ # Historical prediction (inference run) records. The only endpoint with a server-side timestamp+ # filter (`created_after`), so the only one that syncs incrementally. Predictions are immutable+ # once terminal; input/output/logs of API-created predictions are purged ~1h after completion+ # (`data_removed=true`), so older rows typically carry metadata only.+ "predictions": ReplicateEndpointConfig(+ name="predictions",+ path="/predictions",+ partition_key="created_at",+ time_filter_param="created_after",+ incremental_fields=[+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ # Fine-tune / training jobs. No documented timestamp filter, so full refresh only — a+ # client-side cursor walk would cost the same as a full refresh every run.+ "trainings": ReplicateEndpointConfig(+ name="trainings",+ path="/trainings",+ partition_key="created_at",+ ),+ # Deployments owned by the account. Small set, no timestamp filter — full refresh. Deployments+ # have no `id`; they are uniquely identified by owner + name.+ "deployments": ReplicateEndpointConfig(+ name="deployments",+ path="/deployments",+ primary_keys=["owner", "name"],+ ),+ # The full public model catalog exposed by /v1/models (not just the account's own models). Large,+ # so off by default; opt in when the catalog is genuinely wanted. Full refresh, keyed on+ # owner + name.+ "models": ReplicateEndpointConfig(+ name="models",+ path="/models",+ primary_keys=["owner", "name"],+ should_sync_default=False,+ ),+ # Static lookup of hardware SKUs available for running models. Bare JSON array, no pagination.+ "hardware": ReplicateEndpointConfig(+ name="hardware",+ path="/hardware",+ response_shape="list",+ primary_keys=["sku"],+ ),+ # The authenticated account. Single object materialized as one row.+ "account": ReplicateEndpointConfig(+ name="account",+ path="/account",+ response_shape="object",+ primary_keys=["username"],+ ),+}++ENDPOINTS = tuple(REPLICATE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in REPLICATE_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/source.pyindex ccb9225908d1..8f8dc03eb346 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/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 ReplicateSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.replicate.replicate import (+ ReplicateResumeConfig,+ replicate_source,+ validate_credentials as validate_replicate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.replicate.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ REPLICATE_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ReplicateSource(SimpleSource[ReplicateSourceConfig]):+class ReplicateSource(ResumableSource[ReplicateSourceConfig, ReplicateResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.REPLICATE@@ -24,8 +48,107 @@ class ReplicateSource(SimpleSource[ReplicateSourceConfig]):name=SchemaExternalDataSourceType.REPLICATE,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Replicate",- iconPath="/static/services/replicate.png",- keywords=["ml", "ai", "models", "inference"],- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ keywords=["ml", "ai", "models", "inference"],+ caption="""Enter your Replicate API token to automatically pull your Replicate data into the PostHog Data warehouse.++You can create an API token in your [Replicate account settings](https://replicate.com/account/api-tokens).""",+ iconPath="/static/services/replicate.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/replicate",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="r8_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.replicate.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A missing/invalid/revoked token surfaces as an HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Retrying can never fix a credential problem, so stop the sync.+ # Match the stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.replicate.com": "Your Replicate API token is invalid or has been revoked. Create a new token in your Replicate account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.replicate.com": "Your Replicate API token does not have access to this data. Check the token's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: ReplicateSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint == "predictions":+ return (+ "Input, output and logs of API-created predictions are removed by Replicate about "+ "an hour after completion (data_removed=true); older rows carry metadata only."+ )+ if endpoint == "models":+ return "The full public Replicate model catalog, not only your own models. Off by default."+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = REPLICATE_ENDPOINTS[endpoint]+ has_incremental = endpoint_config.time_filter_param is not None+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ detected_primary_keys=endpoint_config.primary_keys,+ description=_description(endpoint),+ )++ 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: ReplicateSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_replicate_credentials(config.api_key):+ return True, None++ return False, "Invalid Replicate API token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ReplicateResumeConfig]:+ return ResumableSourceManager[ReplicateResumeConfig](inputs, ReplicateResumeConfig)++ def source_for_pipeline(+ self,+ config: ReplicateSourceConfig,+ resumable_source_manager: ResumableSourceManager[ReplicateResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return replicate_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,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/tests/test_replicate.py b/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/tests/test_replicate.pynew file mode 100644index 000000000000..d436fa0c4025--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/tests/test_replicate.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 products.warehouse_sources.backend.temporal.data_imports.sources.replicate import replicate+from products.warehouse_sources.backend.temporal.data_imports.sources.replicate.replicate import (+ ReplicateResumeConfig,+ _build_initial_url,+ _extract_items,+ _format_incremental_value,+ _next_url,+ _page_predates_cutoff,+ _sanitize_next_url,+ get_rows,+ replicate_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.replicate.settings import REPLICATE_ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: ReplicateResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[ReplicateResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> ReplicateResumeConfig | None:+ return self._state++ def save_state(self, data: ReplicateResumeConfig) -> None:+ self.saved.append(data)+++class TestFormatIncrementalValue:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("string_passthrough", "2026-03-04T00:00:00Z", "2026-03-04T00:00:00Z"),+ ]+ )+ def test_format_incremental_value(self, _name: str, value: object, expected: str) -> None:+ # A +00:00 offset instead of the Z suffix would build a created_after value the API may reject.+ result = _format_incremental_value(value)+ assert result == expected+ assert "+00:00" not in result+++class TestResponseShapeExtraction:+ @parameterized.expand(+ [+ (+ "paginated_results",+ "predictions",+ {"results": [{"id": "p1"}, {"id": "p2"}], "next": "https://api.replicate.com/v1/predictions?cursor=c"},+ [{"id": "p1"}, {"id": "p2"}],+ "https://api.replicate.com/v1/predictions?cursor=c",+ ),+ ("paginated_last_page", "predictions", {"results": [{"id": "p3"}], "next": None}, [{"id": "p3"}], None),+ (+ "bare_array",+ "hardware",+ [{"name": "Nvidia T4 GPU", "sku": "gpu-t4"}],+ [{"name": "Nvidia T4 GPU", "sku": "gpu-t4"}],+ None,+ ),+ (+ "single_object",+ "account",+ {"username": "acme", "type": "organization"},+ [{"username": "acme", "type": "organization"}],+ None,+ ),+ ]+ )+ def test_extract_items_and_next(+ self, _name: str, endpoint: str, payload: Any, expected_items: list[dict], expected_next: str | None+ ) -> None:+ config = REPLICATE_ENDPOINTS[endpoint]+ assert _extract_items(payload, config) == expected_items+ assert _next_url(payload) == expected_next+++class TestBuildInitialUrl:+ def test_predictions_incremental_appends_created_after(self) -> None:+ url = _build_initial_url(+ REPLICATE_ENDPOINTS["predictions"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ assert url.startswith("https://api.replicate.com/v1/predictions?created_after=")+ assert "2026-03-04T00%3A00%3A00Z" in url++ def test_predictions_first_sync_has_no_filter(self) -> None:+ url = _build_initial_url(+ REPLICATE_ENDPOINTS["predictions"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )+ assert url == "https://api.replicate.com/v1/predictions"++ def test_trainings_never_gets_a_time_filter(self) -> None:+ # trainings exposes no server-side timestamp filter, so a created_after must never be added+ # (it would silently do nothing while implying incremental behavior).+ url = _build_initial_url(+ REPLICATE_ENDPOINTS["trainings"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ assert url == "https://api.replicate.com/v1/trainings"+++class TestPagePredatesCutoff:+ @parameterized.expand(+ [+ ("all_older", ["2026-01-01T00:00:00Z", "2026-02-01T00:00:00Z"], True),+ ("some_newer", ["2026-01-01T00:00:00Z", "2026-05-01T00:00:00Z"], False),+ ("no_dates", [None, None], False),+ ]+ )+ def test_page_predates_cutoff(self, _name: str, timestamps: list[str | None], expected: bool) -> None:+ cutoff = datetime(2026, 3, 4, tzinfo=UTC)+ items = [{"created_at": ts} for ts in timestamps]+ assert _page_predates_cutoff(items, "created_at", cutoff) is expected+++class TestSanitizeNextUrl:+ @parameterized.expand(+ [+ # The API can return an http:// next URL; following it verbatim would leak the bearer+ # token over plaintext, so it must be pinned back to the https origin.+ (+ "http_upgraded_to_https",+ "http://api.replicate.com/v1/predictions?cursor=c",+ "https://api.replicate.com/v1/predictions?cursor=c",+ ),+ (+ "https_preserved",+ "https://api.replicate.com/v1/predictions?cursor=c",+ "https://api.replicate.com/v1/predictions?cursor=c",+ ),+ # A cursor pointing at any other host is dropped rather than followed with the token.+ ("foreign_host_rejected", "https://evil.example.com/v1/predictions?cursor=c", None),+ ("none_passthrough", None, None),+ ]+ )+ def test_sanitize_next_url(self, _name: str, raw: str | None, expected: str | None) -> None:+ assert _sanitize_next_url(raw) == expected+++def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any], endpoint: str, **incremental: Any+) -> tuple[list[dict], list[str]]:+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> Any:+ fetched.append(url)+ return pages[url]++ monkeypatch.setattr(replicate, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for page in get_rows(+ api_key="r8_test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **incremental,+ ):+ rows.extend(page)+ return rows, fetched+++class TestGetRows:+ def test_paginates_following_next_urls(self, monkeypatch: Any) -> None:+ next_url = "https://api.replicate.com/v1/trainings?cursor=c2"+ pages = {+ "https://api.replicate.com/v1/trainings": {"results": [{"id": "t1"}], "next": next_url},+ next_url: {"results": [{"id": "t2"}], "next": None},+ }+ manager = _FakeResumableManager()+ rows, fetched = _collect(manager, monkeypatch, pages, "trainings")++ assert rows == [{"id": "t1"}, {"id": "t2"}]+ assert fetched == ["https://api.replicate.com/v1/trainings", next_url]+ # State is saved after yielding the first page so a crash re-yields it, not skips it.+ assert manager.saved == [ReplicateResumeConfig(next_url=next_url)]++ def test_resumes_from_saved_next_url(self, monkeypatch: Any) -> None:+ resume_url = "https://api.replicate.com/v1/trainings?cursor=resume"+ pages = {resume_url: {"results": [{"id": "t9"}], "next": None}}+ manager = _FakeResumableManager(ReplicateResumeConfig(next_url=resume_url))+ rows, fetched = _collect(manager, monkeypatch, pages, "trainings")++ assert rows == [{"id": "t9"}]+ assert fetched == [resume_url]++ def test_incremental_stops_once_a_page_predates_watermark(self, monkeypatch: Any) -> None:+ # Guards the re-walk-history cost bug: if the server drops created_after on cursor pages, the+ # desc walk must still terminate at the watermark instead of paging through all of history.+ cutoff = datetime(2026, 3, 4, tzinfo=UTC)+ initial = _build_initial_url(REPLICATE_ENDPOINTS["predictions"], True, cutoff)+ page2 = "https://api.replicate.com/v1/predictions?cursor=p2"+ page3 = "https://api.replicate.com/v1/predictions?cursor=p3"+ pages = {+ initial: {"results": [{"id": "a", "created_at": "2026-05-01T00:00:00Z"}], "next": page2},+ page2: {"results": [{"id": "b", "created_at": "2026-01-01T00:00:00Z"}], "next": page3},+ page3: {"results": [{"id": "c", "created_at": "2025-12-01T00:00:00Z"}], "next": None},+ }+ manager = _FakeResumableManager()+ rows, fetched = _collect(+ manager,+ monkeypatch,+ pages,+ "predictions",+ should_use_incremental_field=True,+ db_incremental_field_last_value=cutoff,+ incremental_field="created_at",+ )++ assert [r["id"] for r in rows] == ["a", "b"]+ assert fetched == [initial, page2] # page3 never fetched++ def test_incremental_ignores_stale_cursor_when_watermark_advanced(self, monkeypatch: Any) -> None:+ # A cursor saved against an older watermark must not be resumed: descending pagination puts+ # predictions created since the prior run on the first page, so we rebuild the initial URL+ # for the current watermark instead of paging deeper and skipping them.+ watermark = datetime(2026, 3, 4, tzinfo=UTC)+ initial = _build_initial_url(REPLICATE_ENDPOINTS["predictions"], True, watermark)+ stale_cursor = "https://api.replicate.com/v1/predictions?cursor=stale"+ pages = {initial: {"results": [{"id": "new", "created_at": "2026-05-01T00:00:00Z"}], "next": None}}+ manager = _FakeResumableManager(+ ReplicateResumeConfig(next_url=stale_cursor, created_after="2026-01-01T00:00:00Z")+ )+ rows, fetched = _collect(+ manager,+ monkeypatch,+ pages,+ "predictions",+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ incremental_field="created_at",+ )++ assert [r["id"] for r in rows] == ["new"]+ assert fetched == [initial] # stale cursor never fetched++ def test_incremental_resumes_when_watermark_matches(self, monkeypatch: Any) -> None:+ # Same-watermark cursor (a crash mid-run) is safe to resume: no newer rows exist above it.+ watermark = datetime(2026, 3, 4, tzinfo=UTC)+ resume_url = "https://api.replicate.com/v1/predictions?cursor=resume"+ pages = {resume_url: {"results": [{"id": "r", "created_at": "2026-05-01T00:00:00Z"}], "next": None}}+ manager = _FakeResumableManager(+ ReplicateResumeConfig(next_url=resume_url, created_after=_format_incremental_value(watermark))+ )+ rows, fetched = _collect(+ manager,+ monkeypatch,+ pages,+ "predictions",+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ incremental_field="created_at",+ )++ assert [r["id"] for r in rows] == ["r"]+ assert fetched == [resume_url]++ def test_single_request_endpoints_do_not_paginate(self, monkeypatch: Any) -> None:+ cases = [+ ("hardware", [{"name": "Nvidia T4 GPU", "sku": "gpu-t4"}], [{"name": "Nvidia T4 GPU", "sku": "gpu-t4"}]),+ ("account", {"username": "acme", "type": "organization"}, [{"username": "acme", "type": "organization"}]),+ ]+ for endpoint, payload, expected in cases:+ base = f"https://api.replicate.com/v1{REPLICATE_ENDPOINTS[endpoint].path}"+ manager = _FakeResumableManager()+ rows, fetched = _collect(manager, monkeypatch, {base: payload}, endpoint)++ assert rows == expected+ assert fetched == [base]+ assert manager.saved == []+++class TestFetchPageRetries:+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])+ def test_retryable_status_codes_retry_then_succeed(self, _name: str, status: int) -> None:+ bad = MagicMock(status_code=status, ok=False)+ good = MagicMock(status_code=200, ok=True)+ good.json.return_value = {"results": []}++ session = MagicMock()+ session.get.side_effect = [bad, good]++ with patch.object(replicate._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = replicate._fetch_page(session, "https://api.replicate.com/v1/predictions", {}, MagicMock())++ assert result == {"results": []}+ assert session.get.call_count == 2++ def test_client_error_raises_immediately(self) -> None:+ # A 401/403 must surface (so get_non_retryable_errors can disable the source), not retry.+ response = requests.Response()+ response.status_code = 401+ response.url = "https://api.replicate.com/v1/predictions"++ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(requests.HTTPError):+ replicate._fetch_page(session, "https://api.replicate.com/v1/predictions", {}, MagicMock())+ assert session.get.call_count == 1+++class TestSourceResponse:+ @parameterized.expand(+ [+ ("predictions", ["id"], "created_at", "desc"),+ ("trainings", ["id"], "created_at", "desc"),+ ("deployments", ["owner", "name"], None, "desc"),+ ("models", ["owner", "name"], None, "desc"),+ ("hardware", ["sku"], None, "desc"),+ ("account", ["username"], None, "desc"),+ ]+ )+ def test_source_response_shape(+ self, endpoint: str, expected_pk: list[str], partition_key: str | None, sort_mode: str+ ) -> None:+ response = replicate_source(+ api_key="r8_test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == expected_pk+ assert response.sort_mode == sort_mode+ if partition_key:+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None+ assert response.partition_mode is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/tests/test_replicate_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/tests/test_replicate_source.pynew file mode 100644index 000000000000..49bb20eb3b4f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/replicate/tests/test_replicate_source.py@@ -0,0 +1,117 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.replicate.replicate import ReplicateResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.replicate.source import ReplicateSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(api_key: str = "r8_test") -> MagicMock:+ config = MagicMock()+ config.api_key = api_key+ return config+++class TestReplicateSource:+ def test_source_type(self) -> None:+ assert ReplicateSource().source_type == ExternalDataSourceType.REPLICATE++ def test_source_config_has_password_api_key_field(self) -> None:+ config = ReplicateSource().get_source_config+ api_key_field = next(f for f in config.fields if getattr(f, "name", None) == "api_key")+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.type.value == "password"+ assert api_key_field.required is True++ @parameterized.expand(+ [+ # (endpoint, supports_incremental, should_sync_default, primary_keys)+ ("predictions", True, True, ["id"]),+ ("trainings", False, True, ["id"]),+ ("deployments", False, True, ["owner", "name"]),+ ("models", False, False, ["owner", "name"]),+ ("hardware", False, True, ["sku"]),+ ("account", False, True, ["username"]),+ ]+ )+ def test_get_schemas(+ self, endpoint: str, supports_incremental: bool, should_sync_default: bool, primary_keys: list[str]+ ) -> None:+ # Only predictions has a server-side timestamp filter, so it's the only incremental endpoint;+ # marking any other incremental would fetch every page each run while pretending otherwise.+ schemas = {s.name: s for s in ReplicateSource().get_schemas(_config(), team_id=1)}+ schema = schemas[endpoint]+ assert schema.supports_incremental is supports_incremental+ assert schema.should_sync_default is should_sync_default+ # Merge keys must survive into the schema, otherwise default-created tables lose their+ # dedupe metadata and incremental syncs would append duplicates.+ assert schema.detected_primary_keys == primary_keys+ if supports_incremental:+ assert [f["field"] for f in schema.incremental_fields] == ["created_at"]++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = ReplicateSource().get_schemas(_config(), team_id=1, names=["predictions"])+ assert [s.name for s in schemas] == ["predictions"]++ @parameterized.expand([("valid", True, True, None), ("invalid", False, False, "Invalid Replicate API token")])+ def test_validate_credentials(self, _name: str, api_ok: bool, expected_ok: bool, expected_msg: str | None) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.replicate.source.validate_replicate_credentials",+ return_value=api_ok,+ ):+ ok, msg = ReplicateSource().validate_credentials(_config(), team_id=1)+ assert ok is expected_ok+ assert msg == expected_msg++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.replicate.com/v1/predictions", True),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.replicate.com/v1/account", True),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://api.replicate.com/v1/predictions",+ False,+ ),+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.replicate.com/v1/trainings",+ False,+ ),+ ]+ )+ def test_non_retryable_errors(self, _name: str, observed: str, is_non_retryable: bool) -> None:+ keys = ReplicateSource().get_non_retryable_errors()+ assert any(k in observed for k in keys) is is_non_retryable++ def test_resumable_manager_bound_to_resume_config(self) -> None:+ inputs = MagicMock()+ manager = ReplicateSource().get_resumable_source_manager(inputs)+ assert manager._data_class is ReplicateResumeConfig++ def test_source_for_pipeline_drops_watermark_when_not_incremental(self) -> None:+ # When should_use_incremental_field is False the last-value must not leak into the request,+ # otherwise a full refresh would silently filter by a stale cursor.+ inputs = MagicMock()+ inputs.schema_name = "predictions"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-03-04T00:00:00Z"+ inputs.incremental_field = "created_at"++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.replicate.source.replicate_source"+ ) as mock_source:+ ReplicateSource().source_for_pipeline(_config(), MagicMock(), inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["db_incremental_field_last_value"] is None++ def test_documented_tables_render_without_credentials(self) -> None:+ # lists_tables_without_credentials must yield the public-docs table catalog (SourceTables).+ tables = {t["name"]: t for t in ReplicateSource().get_documented_tables()}+ assert set(tables) == {"predictions", "trainings", "deployments", "models", "hardware", "account"}+ assert "Incremental" in tables["predictions"]["sync_methods"]+ assert "Incremental" not in tables["trainings"]["sync_methods"]