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 baseten import source (#69996)

Tom Owersdc89d1d41a4b
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 1ff451eafa92..c9be0bc7c901 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -70,6 +70,7 @@ the row lists both.
| awin | HTTP | requests | ✅ |
| azure_devops | HTTP | requests | ✅ |
| bamboohr | HTTP | requests | ✅ |
+| baseten | HTTP | requests | ✅ |
| beamer | HTTP | requests | ✅ |
| bigmailer | HTTP | requests | ✅ |
| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
@@ -494,7 +495,6 @@ doesn't conflict with concurrent PRs.
- babelforce
- backblaze
- basecamp
-- baseten
- bigcommerce
- bitly
- box
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/baseten.py b/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/baseten.py
new file mode 100644
index 000000000000..7d1219e6b8f2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/baseten.py
@@ -0,0 +1,270 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.baseten.settings import (
+ BASETEN_ENDPOINTS,
+ BasetenEndpointConfig,
+)
+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
+
+BASETEN_BASE_URL = "https://api.baseten.co"
+# Cursor-paginated endpoints (users, model_apis) accept a `limit`; the entity endpoints ignore it.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT = 60
+
+
+class BasetenRetryableError(Exception):
+ pass
+
+
+class BasetenResumeConfig:
+ # Cursor for the current page of a cursor-paginated endpoint (users, model_apis).
+ cursor: str | None = None
+ # For fan-out endpoints: the next parent id to process. A stable id (not a positional index) so
+ # parents added/removed between a crash and the retry can't resume us into the wrong parent.
+ parent_id: str | None = None
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _get_session(api_key: str) -> requests.Session:
+ # Redact the key everywhere the tracked transport might surface it (logged URLs, captured
+ # samples). The `Authorization` header is already dropped wholesale by the sampler, but masking
+ # the literal value is cheap defense-in-depth in case it ever lands in an error body or URL.
+ return make_tracked_session(redact_values=(api_key,))
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ BasetenRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ params: dict[str, Any] | None,
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ response = session.get(url, headers=headers, params=params, timeout=REQUEST_TIMEOUT)
+
+ # 429 responses carry a `retry_after` seconds hint; exponential backoff subsumes it without us
+ # having to sleep here. 5xx are transient too.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise BasetenRetryableError(f"Baseten API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # 404 is expected during fan-out when a parent resource is deleted mid-sync; caller handles it.
+ # Log only status + url — upstream error bodies can echo workspace metadata or secret-adjacent
+ # data, so we never persist `response.text`.
+ log = logger.warning if response.status_code == 404 else logger.error
+ log(f"Baseten API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(api_key: str) -> bool:
+ # /v1/users/me is the cheapest workspace-scoped probe and doesn't depend on any resource existing.
+ url = f"{BASETEN_BASE_URL}/v1/users/me"
+ try:
+ response = _get_session(api_key).get(url, headers=_headers(api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _flatten_row(item: dict[str, Any], flatten_key: str | None) -> dict[str, Any]:
+ """Lift a nested object (e.g. instance_type_prices' `instance_type`) up into the root."""
+ if flatten_key and isinstance(item.get(flatten_key), dict):
+ nested = item.pop(flatten_key)
+ # Root-level siblings (e.g. `price`) take precedence over nested keys on collision.
+ return {**nested, **item}
+ return item
+
+
+def _top_level_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ config: BasetenEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Single unpaginated request returning a full array under `config.data_key`."""
+ data = _fetch(session, f"{BASETEN_BASE_URL}{config.path}", headers, None, logger)
+ rows = [_flatten_row(item, config.flatten_key) for item in data.get(config.data_key, [])]
+ if rows:
+ yield rows
+
+
+def _paginated_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ config: BasetenEndpointConfig,
+ manager: ResumableSourceManager[BasetenResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Cursor+limit pagination: {"items": [...], "pagination": {"has_more": bool, "cursor": str}}."""
+ resume = manager.load_state() if manager.can_resume() else None
+ cursor = resume.cursor if resume else None
+
+ url = f"{BASETEN_BASE_URL}{config.path}"
+ while True:
+ params: dict[str, Any] = {"limit": PAGE_SIZE}
+ if cursor:
+ params["cursor"] = cursor
+
+ data = _fetch(session, url, headers, params, logger)
+ rows = data.get(config.data_key, [])
+ if rows:
+ yield rows
+
+ pagination = data.get("pagination") or {}
+ next_cursor = pagination.get("cursor") if pagination.get("has_more") else None
+ if not next_cursor:
+ break
+
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it. These are
+ # full-refresh tables (append writes, no primary-key merge), so a resumed run can re-append
+ # at most the one in-flight page — bounded, and cleared by the next clean full refresh. We
+ # prefer that transient duplicate over the alternative (save-before-yield), which would drop
+ # a page entirely on a crash in the same window.
+ manager.save_state(BasetenResumeConfig(cursor=next_cursor))
+ cursor = next_cursor
+
+
+def _iter_parents(
+ session: requests.Session,
+ headers: dict[str, str],
+ parent_config: BasetenEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ """Fetch the (unpaginated) parent list for a fan-out."""
+ data = _fetch(session, f"{BASETEN_BASE_URL}{parent_config.path}", headers, None, logger)
+ return list(data.get(parent_config.data_key, []))
+
+
+def _fan_out_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ config: BasetenEndpointConfig,
+ manager: ResumableSourceManager[BasetenResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Iterate a parent resource and fetch this child endpoint once per parent row."""
+ assert config.fan_out_parent is not None
+ parent_config = BASETEN_ENDPOINTS[config.fan_out_parent]
+ parents = _iter_parents(session, headers, parent_config, logger)
+
+ # Drop parents missing the fan-out id. Stringifying a missing id would build a bogus child path
+ # (e.g. `/v1/models/None/deployments`) and could sync child rows keyed to a literal "None".
+ parented: list[tuple[str, dict[str, Any]]] = []
+ for parent in parents:
+ raw_id = parent.get(config.fan_out_parent_field)
+ if raw_id is None or raw_id == "":
+ logger.warning(f"Baseten: skipping {config.fan_out_parent} without {config.fan_out_parent_field}")
+ continue
+ parented.append((str(raw_id), parent))
+ parent_ids = [pid for pid, _ in parented]
+
+ # Resolve the saved parent bookmark to the slice still to process. If the bookmarked parent no
+ # longer exists (deleted between runs), start over. These are full-refresh tables, so re-pulling
+ # a parent's children can at most re-append them (bounded, cleared by the next clean full refresh).
+ resume = manager.load_state() if manager.can_resume() else None
+ remaining = parented
+ if resume is not None and resume.parent_id is not None and resume.parent_id in parent_ids:
+ start = parent_ids.index(resume.parent_id)
+ remaining = remaining[start:]
+ logger.debug(f"Baseten: resuming {config.name} from parent_id={resume.parent_id}")
+
+ for index, (parent_id, parent) in enumerate(remaining):
+ child_path = config.path.replace(f"{{{config.fan_out_path_param}}}", parent_id)
+ try:
+ data = _fetch(session, f"{BASETEN_BASE_URL}{child_path}", headers, None, logger)
+ except requests.HTTPError as exc:
+ # A parent deleted between enumeration and this fetch 404s. Skip it rather than failing
+ # the whole sync. Any other HTTP error is re-raised.
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Baseten: {config.fan_out_parent} {parent_id} not found for {config.name}, skipping")
+ continue
+ raise
+
+ rows = []
+ for item in data.get(config.data_key, []):
+ row = _flatten_row(item, config.flatten_key)
+ if config.fan_out_include_parent_fields:
+ for parent_field, child_column in config.fan_out_include_parent_fields.items():
+ row[child_column] = parent.get(parent_field)
+ rows.append(row)
+
+ if rows:
+ yield rows
+
+ # Advance the bookmark to the next parent so a crash between parents resumes correctly.
+ if index + 1 < len(remaining):
+ manager.save_state(BasetenResumeConfig(parent_id=remaining[index + 1][0]))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BasetenResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = BASETEN_ENDPOINTS[endpoint]
+ headers = _headers(api_key)
+ # One session reused across every page/parent so urllib3 keeps the connection alive.
+ session = _get_session(api_key)
+
+ if config.paginated:
+ yield from _paginated_rows(session, headers, config, resumable_source_manager, logger)
+ elif config.fan_out_parent:
+ yield from _fan_out_rows(session, headers, config, resumable_source_manager, logger)
+ else:
+ yield from _top_level_rows(session, headers, config, logger)
+
+
+def baseten_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BasetenResumeConfig],
+) -> SourceResponse:
+ config = BASETEN_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/canonical_descriptions.py
new file mode 100644
index 000000000000..8f5b1cd9a10a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/canonical_descriptions.py
@@ -0,0 +1,168 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Sourced from the Baseten management API OpenAPI spec (https://api.baseten.co/v1/spec). Keys match
+# the endpoint names returned by BasetenSource.get_schemas.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "models": {
+ "description": "Models deployed in your Baseten workspace.",
+ "docs_url": "https://docs.baseten.co/reference/management-api/models/gets-all-models-that-the-user-has-access-to",
+ "columns": {
+ "id": "Unique identifier of the model.",
+ "created_at": "Time the model was created, in ISO 8601 format.",
+ "name": "Name of the model.",
+ "deployments_count": "Number of deployments of the model.",
+ "production_deployment_id": "Unique identifier of the production deployment of the model.",
+ "development_deployment_id": "Unique identifier of the development deployment of the model.",
+ "instance_type_name": "Name of the instance type for the production deployment of the model.",
+ "team_name": "Name of the team associated with the model.",
+ },
+ },
+ "deployments": {
+ "description": "Deployments of each model, including autoscaling state and active replica counts.",
+ "docs_url": "https://docs.baseten.co/reference/management-api/deployments/gets-all-deployments-of-a-model",
+ "columns": {
+ "id": "Unique identifier of the deployment.",
+ "created_at": "Time the deployment was created, in ISO 8601 format.",
+ "name": "Name of the deployment.",
+ "model_id": "Unique identifier of the model this deployment belongs to.",
+ "is_production": "Whether the deployment is the production deployment of the model.",
+ "is_development": "Whether the deployment is the development deployment of the model.",
+ "status": "Status of the deployment.",
+ "active_replica_count": "Number of active replicas.",
+ "autoscaling_settings": "Autoscaling settings for the deployment. Null until the model finishes deploying.",
+ "instance_type_name": "Name of the instance type the deployment is running on.",
+ "environment": "The environment associated with the deployment.",
+ "labels": "User-provided key-value labels for the deployment.",
+ },
+ },
+ "model_environments": {
+ "description": "Environments (e.g. production, staging) configured for each model.",
+ "docs_url": "https://docs.baseten.co/reference/management-api/environments/gets-all-environments-of-a-model",
+ "columns": {
+ "name": "Name of the environment.",
+ "created_at": "Time the environment was created, in ISO 8601 format.",
+ "model_id": "Unique identifier of the model this environment belongs to.",
+ "current_deployment": "Current deployment of the environment.",
+ "candidate_deployment": "Candidate deployment being promoted, if a promotion is in progress.",
+ "in_progress_promotion": "Details of the in-progress promotion, if any.",
+ "autoscaling_settings": "Autoscaling settings for the environment.",
+ "promotion_settings": "Promotion settings for the environment.",
+ "instance_type": "Instance type for the environment.",
+ },
+ },
+ "chains": {
+ "description": "Chains (multi-model inference pipelines) in your workspace.",
+ "docs_url": "https://docs.baseten.co/reference/management-api/chains/gets-all-chains",
+ "columns": {
+ "id": "Unique identifier of the chain.",
+ "created_at": "Time the chain was created, in ISO 8601 format.",
+ "name": "Name of the chain.",
+ "deployments_count": "Number of deployments of the chain.",
+ "team_name": "Name of the team associated with the chain.",
+ },
+ },
+ "chain_deployments": {
+ "description": "Deployments of each chain, including their chainlets and status.",
+ "docs_url": "https://docs.baseten.co/reference/management-api/chains/gets-all-deployments-of-a-chain",
+ "columns": {
+ "id": "Unique identifier of the chain deployment.",
+ "created_at": "Time the chain deployment was created, in ISO 8601 format.",
+ "chain_id": "Unique identifier of the chain this deployment belongs to.",
+ "environment": "Environment the chain deployment is deployed in.",
+ "chainlets": "Chainlets in the chain deployment.",
+ "status": "Status of the chain deployment.",
+ },
+ },
+ "training_projects": {
+ "description": "Training projects in your workspace.",
+ "docs_url": "https://docs.baseten.co/reference/management-api/training/lists-all-training-projects",
+ "columns": {
+ "id": "Unique identifier of the training project.",
+ "name": "Name of the training project.",
+ "created_at": "Time the training project was created, in ISO 8601 format.",
+ "updated_at": "Time the training project was last updated, in ISO 8601 format.",
+ "team_name": "Name of the team associated with the training project.",
+ "latest_job": "Most recently created training job for the training project.",
+ },
+ },
+ "training_jobs": {
+ "description": "Training jobs across all training projects.",
+ "docs_url": "https://docs.baseten.co/reference/management-api/training/lists-all-training-jobs-for-a-project",
+ "columns": {
+ "id": "Unique identifier of the training job.",
+ "created_at": "Time the job was created, in ISO 8601 format.",
+ "current_status": "Current status of the training job.",
+ "error_message": "Error message if the training job failed.",
+ "instance_type": "Instance type of the training job.",
+ "updated_at": "Time the job was last updated, in ISO 8601 format.",
+ "training_project_id": "ID of the training project this job belongs to.",
+ "name": "Name of the training job.",
+ "priority": "Queue priority. Higher values are dequeued first; null is treated as 0.",
+ "availability_model": "Capacity guarantee for the job (dedicated on-demand vs preemptible spot).",
+ "user": "The user who created the training job.",
+ },
+ },
+ "users": {
+ "description": "Users with access to your Baseten workspace.",
+ "docs_url": "https://docs.baseten.co/reference/management-api/users/lists-all-users",
+ "columns": {
+ "user_id": "Unique identifier for the user.",
+ "email": "Email address of the user.",
+ "name": "Display name of the user.",
+ "workspace_name": "Name of the user's workspace.",
+ },
+ },
+ "model_apis": {
+ "description": "Baseten Model APIs catalog, enriched with any workspace-specific state.",
+ "docs_url": "https://docs.baseten.co/reference/management-api/model-apis/lists-all-model-apis",
+ "columns": {
+ "name": "Stable, URL-safe slug used as the public identifier of the Model API.",
+ "display_name": "Human-readable name of the Model API.",
+ "description": "Description of the Model API.",
+ "model_family": "Family the underlying model belongs to.",
+ "release_date": "Date the Model API was made available.",
+ "invoke_url": "Base URL for invoking the Model API.",
+ "context_length": "The model's context window length, in tokens.",
+ "cost_per_million_input_tokens": "Cost per million input tokens, in dollars.",
+ "cost_per_million_output_tokens": "Cost per million output tokens, in dollars.",
+ "rate_limits": "Rate limits in effect for the workspace.",
+ "org_details": "Workspace-specific state. Null when the workspace has not added this Model API.",
+ },
+ },
+ "instance_types": {
+ "description": "Catalog of compute instance types available on Baseten.",
+ "docs_url": "https://docs.baseten.co/reference/management-api/instances/gets-all-instance-types",
+ "columns": {
+ "id": "Identifier string for the instance type.",
+ "name": "Display name of the instance type.",
+ "memory_limit_mib": "Memory limit of the instance type, in Mebibytes.",
+ "millicpu_limit": "CPU limit of the instance type, in millicpu.",
+ "gpu_count": "Number of GPUs on the instance type.",
+ "gpu_type": "Type of GPU on the instance type.",
+ "gpu_memory_limit_mib": "Memory limit of the GPU on the instance type, in Mebibytes.",
+ },
+ },
+ "instance_type_prices": {
+ "description": "Instance types with their usage price, in USD per minute.",
+ "docs_url": "https://docs.baseten.co/reference/management-api/instances/gets-all-instance-type-prices",
+ "columns": {
+ "id": "Identifier string for the instance type.",
+ "name": "Display name of the instance type.",
+ "price": "Usage price in USD per minute.",
+ "gpu_count": "Number of GPUs on the instance type.",
+ "gpu_type": "Type of GPU on the instance type.",
+ },
+ },
+ "secrets": {
+ "description": "Secrets configured in your workspace. Values are never returned by the API.",
+ "docs_url": "https://docs.baseten.co/reference/management-api/secrets/gets-all-secrets",
+ "columns": {
+ "id": "Stable identifier for the secret. Unchanged across rotation.",
+ "created_at": "Time the secret was created, in ISO 8601 format.",
+ "name": "Name of the secret.",
+ "team_name": "Name of the team the secret belongs to.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/settings.py
new file mode 100644
index 000000000000..fdc68f41bc06
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/settings.py
@@ -0,0 +1,129 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+# Baseten's management API returns full arrays for its entity list endpoints (no server-side
+# `updated_since` filter on any of them), so every table syncs as a full refresh. A couple of
+# endpoints (users, model_apis) use cursor+limit pagination; the rest are single unpaginated
+# requests, and a few are fan-out children fetched once per parent resource.
+
+
+@dataclass
+class BasetenEndpointConfig:
+ name: str
+ # Path template. For fan-out children it carries a `{<fan_out_path_param>}` placeholder that is
+ # substituted with the parent field value per parent row.
+ path: str
+ # Key in the JSON response body holding the row array (e.g. {"models": [...]}). Cursor endpoints
+ # return {"items": [...], "pagination": {...}}.
+ data_key: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # STABLE creation timestamp used for datetime partitioning. None for endpoints whose rows have no
+ # stable creation timestamp (reference tables, cursor-paginated user/model_api catalogs).
+ partition_key: Optional[str] = None
+ # True for endpoints that page via cursor+limit, returning a `pagination` object.
+ paginated: bool = False
+ # Fan-out: iterate the named parent endpoint and call this child once per parent row.
+ fan_out_parent: Optional[str] = None
+ fan_out_path_param: str = "parent_id" # placeholder name in `path`
+ fan_out_parent_field: str = "id" # field read off the parent row to fill the placeholder
+ # Parent field -> child column: copies parent context onto each child row so the linkage column
+ # is always present (and the composite primary key stays unique table-wide).
+ fan_out_include_parent_fields: Optional[dict[str, str]] = None
+ # Flatten a nested object in each row up into the root (instance_type_prices wraps the instance
+ # type under `instance_type` alongside a sibling `price`).
+ flatten_key: Optional[str] = None
+ should_sync_default: bool = True
+
+
+BASETEN_ENDPOINTS: dict[str, BasetenEndpointConfig] = {
+ "models": BasetenEndpointConfig(
+ name="models",
+ path="/v1/models",
+ data_key="models",
+ partition_key="created_at",
+ ),
+ "deployments": BasetenEndpointConfig(
+ name="deployments",
+ path="/v1/models/{model_id}/deployments",
+ data_key="deployments",
+ partition_key="created_at",
+ fan_out_parent="models",
+ fan_out_path_param="model_id",
+ fan_out_include_parent_fields={"id": "model_id"},
+ ),
+ "model_environments": BasetenEndpointConfig(
+ name="model_environments",
+ path="/v1/models/{model_id}/environments",
+ data_key="environments",
+ # Environment names ("production", "staging", ...) repeat across models, so the name is only
+ # unique within its model — key on both to stay unique table-wide.
+ primary_keys=["model_id", "name"],
+ partition_key="created_at",
+ fan_out_parent="models",
+ fan_out_path_param="model_id",
+ fan_out_include_parent_fields={"id": "model_id"},
+ ),
+ "chains": BasetenEndpointConfig(
+ name="chains",
+ path="/v1/chains",
+ data_key="chains",
+ partition_key="created_at",
+ ),
+ "chain_deployments": BasetenEndpointConfig(
+ name="chain_deployments",
+ path="/v1/chains/{chain_id}/deployments",
+ data_key="deployments",
+ partition_key="created_at",
+ fan_out_parent="chains",
+ fan_out_path_param="chain_id",
+ fan_out_include_parent_fields={"id": "chain_id"},
+ ),
+ "training_projects": BasetenEndpointConfig(
+ name="training_projects",
+ path="/v1/training_projects",
+ data_key="training_projects",
+ partition_key="created_at",
+ ),
+ "training_jobs": BasetenEndpointConfig(
+ name="training_jobs",
+ path="/v1/training_projects/{training_project_id}/jobs",
+ data_key="training_jobs",
+ partition_key="created_at",
+ fan_out_parent="training_projects",
+ fan_out_path_param="training_project_id",
+ fan_out_include_parent_fields={"id": "training_project_id"},
+ ),
+ "users": BasetenEndpointConfig(
+ name="users",
+ path="/v1/users",
+ data_key="items",
+ primary_keys=["user_id"],
+ paginated=True,
+ ),
+ "model_apis": BasetenEndpointConfig(
+ name="model_apis",
+ path="/v1/model_apis",
+ data_key="items",
+ primary_keys=["name"],
+ paginated=True,
+ ),
+ "instance_types": BasetenEndpointConfig(
+ name="instance_types",
+ path="/v1/instance_types",
+ data_key="instance_types",
+ ),
+ "instance_type_prices": BasetenEndpointConfig(
+ name="instance_type_prices",
+ path="/v1/instance_type_prices",
+ data_key="instance_types",
+ flatten_key="instance_type",
+ ),
+ "secrets": BasetenEndpointConfig(
+ name="secrets",
+ path="/v1/secrets",
+ data_key="secrets",
+ partition_key="created_at",
+ ),
+}
+
+ENDPOINTS = tuple(BASETEN_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/source.py
index aa29dd5f62dd..fb6579c0f92e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/source.py
@@ -1,19 +1,42 @@
-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.baseten.baseten import (
+ BasetenResumeConfig,
+ baseten_source,
+ validate_credentials as validate_baseten_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.baseten.settings import (
+ BASETEN_ENDPOINTS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BasetenSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BasetenSource(SimpleSource[BasetenSourceConfig]):
+class BasetenSource(ResumableSource[BasetenSourceConfig, BasetenResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BASETEN
@@ -24,8 +47,90 @@ class BasetenSource(SimpleSource[BasetenSourceConfig]):
name=SchemaExternalDataSourceType.BASETEN,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Baseten",
+ releaseStatus=ReleaseStatus.ALPHA,
+ unreleasedSource=True,
+ caption="""Enter your Baseten API key to sync your Baseten workspace data into the PostHog Data warehouse.
+
+Create an API key in your [Baseten workspace settings](https://app.baseten.co/settings/api_keys). The key is workspace-scoped and read access to your models, deployments, chains, and training resources is sufficient.""",
iconPath="/static/services/baseten.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/baseten",
keywords=["ai", "inference", "ml", "gpu"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.baseten.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # Baseten answers both a missing and an invalid API key with 403 PERMISSION_DENIED (it does
+ # not use 401), so a 403 at sync time means the key is invalid or lacks access — retrying
+ # can never fix that. Match the stable status text and base host, not the per-request path.
+ return {
+ "401 Client Error: Unauthorized for url: https://api.baseten.co": "Your Baseten API key is invalid or has been revoked. Create a new API key in your Baseten workspace settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.baseten.co": "Your Baseten API key is invalid or does not have access to this workspace data. Check the key in your Baseten workspace settings, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: BasetenSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Baseten exposes no server-side "updated since" filter on any entity list endpoint, so every
+ # table syncs as a full refresh.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ should_sync_default=BASETEN_ENDPOINTS[endpoint].should_sync_default,
+ )
+ 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: BasetenSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_baseten_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Baseten API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BasetenResumeConfig]:
+ return ResumableSourceManager[BasetenResumeConfig](inputs, BasetenResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BasetenSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BasetenResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return baseten_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/tests/test_baseten.py b/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/tests/test_baseten.py
new file mode 100644
index 000000000000..2a128424da14
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/tests/test_baseten.py
@@ -0,0 +1,227 @@
+import json
+from collections.abc import Iterator
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.baseten.baseten import (
+ BasetenResumeConfig,
+ _flatten_row,
+ baseten_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.baseten.settings import (
+ BASETEN_ENDPOINTS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.baseten.baseten"
+
+
+def _response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+def _drive(endpoint: str, manager: MagicMock, responses: list[Response]) -> tuple[list[list[dict]], list[dict]]:
+ """Run ``get_rows`` against a mocked HTTP session; return (yielded batches, captured get kwargs)."""
+ captured: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_get(url: str, **kwargs: Any) -> Response:
+ captured.append({"url": url, "params": kwargs.get("params")})
+ return next(response_iter)
+
+ with patch(f"{MODULE}.make_tracked_session") as mock_factory:
+ session = mock_factory.return_value
+ session.get.side_effect = fake_get
+ batches = list(get_rows("test-key", endpoint, MagicMock(), manager))
+ return batches, captured
+
+
+class TestFlattenRow:
+ def test_lifts_nested_object_into_root(self) -> None:
+ row = _flatten_row({"instance_type": {"id": "gpu-1", "name": "A100"}, "price": 0.5}, "instance_type")
+ assert row == {"id": "gpu-1", "name": "A100", "price": 0.5}
+
+ def test_root_keys_win_on_collision(self) -> None:
+ # A sibling `price` (or any root key) must survive a nested key of the same name.
+ row = _flatten_row({"instance_type": {"id": "gpu-1", "price": 999}, "price": 0.5}, "instance_type")
+ assert row["price"] == 0.5
+
+ def test_noop_without_flatten_key(self) -> None:
+ row = _flatten_row({"id": "1"}, None)
+ assert row == {"id": "1"}
+
+ def test_noop_when_key_absent(self) -> None:
+ row = _flatten_row({"id": "1"}, "instance_type")
+ assert row == {"id": "1"}
+
+
+class TestTopLevelEndpoints:
+ def test_yields_rows_under_data_key(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ batches, captured = _drive("models", manager, [_response({"models": [{"id": "m1"}, {"id": "m2"}]})])
+ assert batches == [[{"id": "m1"}, {"id": "m2"}]]
+ assert captured[0]["url"].endswith("/v1/models")
+
+ def test_empty_array_yields_nothing(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ batches, _ = _drive("models", manager, [_response({"models": []})])
+ assert batches == []
+
+ def test_instance_type_prices_flattened(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ body = {"instance_types": [{"instance_type": {"id": "gpu-1", "name": "A100"}, "price": 0.5}]}
+ batches, _ = _drive("instance_type_prices", manager, [_response(body)])
+ assert batches == [[{"id": "gpu-1", "name": "A100", "price": 0.5}]]
+
+
+class TestCursorPagination:
+ def test_saves_cursor_after_each_non_terminal_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ responses = [
+ _response({"items": [{"user_id": "u1"}], "pagination": {"has_more": True, "cursor": "c1"}}),
+ _response({"items": [{"user_id": "u2"}], "pagination": {"has_more": True, "cursor": "c2"}}),
+ _response({"items": [{"user_id": "u3"}], "pagination": {"has_more": False, "cursor": None}}),
+ ]
+ batches, captured = _drive("users", manager, responses)
+
+ assert batches == [[{"user_id": "u1"}], [{"user_id": "u2"}], [{"user_id": "u3"}]]
+ # First request has no cursor; later requests carry the prior page's cursor.
+ assert [p["params"].get("cursor") for p in captured] == [None, "c1", "c2"]
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [BasetenResumeConfig(cursor="c1"), BasetenResumeConfig(cursor="c2")]
+
+ def test_single_terminal_page_does_not_save(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ _drive("users", manager, [_response({"items": [{"user_id": "u1"}], "pagination": {"has_more": False}})])
+ manager.save_state.assert_not_called()
+
+ def test_resume_seeds_saved_cursor(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = BasetenResumeConfig(cursor="resumed-cursor")
+ _, captured = _drive("users", manager, [_response({"items": [{"user_id": "u9"}], "pagination": {}})])
+ assert captured[0]["params"].get("cursor") == "resumed-cursor"
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ _drive("users", manager, [_response({"items": [], "pagination": {}})])
+ manager.load_state.assert_not_called()
+
+
+class TestFanOut:
+ def test_injects_parent_id_and_yields_per_parent(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ responses = [
+ _response({"models": [{"id": "m1"}, {"id": "m2"}]}), # parent list
+ _response({"deployments": [{"id": "d1"}]}), # m1 children
+ _response({"deployments": [{"id": "d2"}]}), # m2 children
+ ]
+ batches, captured = _drive("deployments", manager, responses)
+
+ assert batches == [[{"id": "d1", "model_id": "m1"}], [{"id": "d2", "model_id": "m2"}]]
+ assert captured[1]["url"].endswith("/v1/models/m1/deployments")
+ assert captured[2]["url"].endswith("/v1/models/m2/deployments")
+ # Bookmark advances to the next parent after finishing the first one.
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [BasetenResumeConfig(parent_id="m2")]
+
+ def test_composite_key_column_present_for_environments(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ responses = [
+ _response({"models": [{"id": "m1"}]}),
+ _response({"environments": [{"name": "production"}]}),
+ ]
+ batches, _ = _drive("model_environments", manager, responses)
+ # model_id is injected so [model_id, name] stays unique table-wide.
+ assert batches == [[{"name": "production", "model_id": "m1"}]]
+
+ def test_404_child_is_skipped(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ responses = [
+ _response({"models": [{"id": "gone"}, {"id": "m2"}]}),
+ _response({"code": "NOT_FOUND"}, status_code=404), # parent deleted mid-sync
+ _response({"deployments": [{"id": "d2"}]}),
+ ]
+ batches, _ = _drive("deployments", manager, responses)
+ assert batches == [[{"id": "d2", "model_id": "m2"}]]
+
+ def test_parent_without_id_is_skipped(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ responses = [
+ _response({"models": [{"id": "m1"}, {"name": "orphan"}]}), # second parent has no id
+ _response({"deployments": [{"id": "d1"}]}), # only m1's children are fetched
+ ]
+ batches, captured = _drive("deployments", manager, responses)
+ assert batches == [[{"id": "d1", "model_id": "m1"}]]
+ # The id-less parent must not produce a request against a stringified "None" id.
+ assert not any("/models/None/" in c["url"] for c in captured)
+
+ def test_resume_starts_from_bookmarked_parent(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = BasetenResumeConfig(parent_id="m2")
+ responses = [
+ _response({"models": [{"id": "m1"}, {"id": "m2"}]}),
+ _response({"deployments": [{"id": "d2"}]}), # only m2 is fetched
+ ]
+ batches, captured = _drive("deployments", manager, responses)
+ assert batches == [[{"id": "d2", "model_id": "m2"}]]
+ child_urls = [c["url"] for c in captured if "/deployments" in c["url"]]
+ assert child_urls == ["https://api.baseten.co/v1/models/m2/deployments"]
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(("status", "expected"), [(200, True), (403, False), (401, False), (500, False)])
+ def test_status_maps_to_bool(self, status: int, expected: bool) -> None:
+ with patch(f"{MODULE}.make_tracked_session") as mock_factory:
+ session = mock_factory.return_value
+ session.get.return_value = _response({}, status_code=status)
+ assert validate_credentials("key") is expected
+
+ def test_network_error_is_false(self) -> None:
+ with patch(f"{MODULE}.make_tracked_session") as mock_factory:
+ mock_factory.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("key") is False
+
+
+class TestSourceResponseShape:
+ @pytest.mark.parametrize("endpoint", ENDPOINTS)
+ def test_partition_and_primary_keys_match_config(self, endpoint: str) -> None:
+ config = BASETEN_ENDPOINTS[endpoint]
+ response = baseten_source("k", endpoint, MagicMock(), MagicMock(spec=ResumableSourceManager))
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_items_is_lazy(self) -> None:
+ # Building the SourceResponse must not perform any I/O; items is a deferred callable.
+ response = baseten_source("k", "models", MagicMock(), MagicMock(spec=ResumableSourceManager))
+ assert callable(response.items)
+ assert isinstance(response.items(), Iterator)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/tests/test_baseten_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/tests/test_baseten_source.py
new file mode 100644
index 000000000000..62df5abd9263
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/baseten/tests/test_baseten_source.py
@@ -0,0 +1,106 @@
+from typing import cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.baseten.baseten import BasetenResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.baseten.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.baseten.source import BasetenSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BasetenSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.baseten.source"
+
+
+def _inputs(schema_name: str = "models") -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-1",
+ source_id="source-1",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job-1",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestBasetenSourceConfig:
+ def test_source_type(self) -> None:
+ assert BasetenSource().source_type == ExternalDataSourceType.BASETEN
+
+ def test_config_exposes_secret_api_key_field(self) -> None:
+ config = BasetenSource().get_source_config
+ fields = cast(list[SourceFieldInputConfig], config.fields)
+ assert len(fields) == 1
+ api_key = fields[0]
+ assert api_key.name == "api_key"
+ assert api_key.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key.required is True
+ assert api_key.secret is True
+
+ def test_config_metadata(self) -> None:
+ config = BasetenSource().get_source_config
+ # Alpha + unreleased per the task's staged-rollout requirement.
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/baseten"
+
+
+class TestBasetenSchemas:
+ def test_lists_all_endpoints_as_full_refresh(self) -> None:
+ schemas = BasetenSource().get_schemas(BasetenSourceConfig(api_key="k"), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # No Baseten list endpoint exposes a server-side timestamp filter, so nothing is incremental.
+ assert all(not s.supports_incremental and not s.supports_append for s in schemas)
+
+ def test_names_filter(self) -> None:
+ schemas = BasetenSource().get_schemas(BasetenSourceConfig(api_key="k"), team_id=1, names=["models", "chains"])
+ assert {s.name for s in schemas} == {"models", "chains"}
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # Static catalog -> public docs render the table list.
+ assert BasetenSource.lists_tables_without_credentials is True
+ tables = BasetenSource().get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+
+class TestBasetenCredentials:
+ @pytest.mark.parametrize(("valid", "expected_ok"), [(True, True), (False, False)])
+ def test_validate_credentials(self, valid: bool, expected_ok: bool) -> None:
+ with patch(f"{MODULE}.validate_baseten_credentials", return_value=valid):
+ ok, error = BasetenSource().validate_credentials(BasetenSourceConfig(api_key="k"), team_id=1)
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+ def test_non_retryable_errors_cover_403(self) -> None:
+ errors = BasetenSource().get_non_retryable_errors()
+ # Baseten answers a bad key with 403, not 401 — the 403 entry is the one that matters.
+ assert any("403 Client Error" in key and "https://api.baseten.co" in key for key in errors)
+
+
+class TestBasetenPipelineWiring:
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = BasetenSource().get_resumable_source_manager(_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is BasetenResumeConfig
+
+ def test_source_for_pipeline_plumbs_args(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ inputs = _inputs(schema_name="deployments")
+ with patch(f"{MODULE}.baseten_source") as mock_source:
+ BasetenSource().source_for_pipeline(BasetenSourceConfig(api_key="secret"), manager, inputs)
+ mock_source.assert_called_once_with(
+ api_key="secret",
+ endpoint="deployments",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ )
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 b843e4b46faf..e68a20502315 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
@@ -445,7 +445,7 @@ class BaserowSourceConfig(config.Config):
@config.config
class BasetenSourceConfig(config.Config):
- pass
+ api_key: str
@config.config