: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 runpod import source (#70710)
Tom Owersa9bbb0697ac1
diff --git a/frontend/public/services/runpod.svg b/frontend/public/services/runpod.svgnew file mode 100644index 000000000000..294bff92e22f--- /dev/null+++ b/frontend/public/services/runpod.svg@@ -0,0 +1,10 @@+<svg width="168" height="184" viewBox="0 0 168 184" fill="none" xmlns="http://www.w3.org/2000/svg">+<g clip-path="url(#clip0_24_31)">+<path fill-rule="evenodd" clip-rule="evenodd" d="M152.487 149.333C162.086 143.802 168 133.581 168 122.519L168 61.4805C168 50.4192 162.086 40.1981 152.487 34.6675L99.5133 4.148C89.9136 -1.38267 78.0863 -1.38266 68.4866 4.148L15.5133 34.6675C5.91365 40.1981 -2.2186e-06 50.4192 0 61.4805L7.0004e-06 122.519C3.30114e-06 133.581 5.91367 143.802 15.5134 149.333L68.4867 179.852C78.0864 185.383 89.9137 185.383 99.5133 179.852L152.487 149.333ZM152.487 122.519C152.487 128.05 149.53 133.161 144.73 135.926L117.005 151.899C114.561 153.307 113.339 154.011 112.337 153.906C111.462 153.814 110.668 153.357 110.151 152.647C109.558 151.833 109.558 150.425 109.558 147.609L109.558 115.663C109.558 110.133 112.515 105.022 117.315 102.257L132.16 93.7043C134.198 92.5298 135.218 91.9426 135.958 91.1209C136.614 90.3938 137.108 89.5372 137.41 88.6068C137.751 87.5552 137.749 86.3808 137.745 84.0319L137.743 83.3264C137.737 79.813 137.734 78.0562 136.993 77.0408C136.346 76.155 135.354 75.5843 134.261 75.4703C133.009 75.3396 131.485 76.218 128.435 77.9747L109.558 88.8503C99.9587 94.3809 94.045 104.602 94.045 115.663L94.045 162.49C94.045 164.122 93.1727 165.63 91.7567 166.445C86.9568 169.211 81.0432 169.211 76.2433 166.445L23.27 135.926C18.4702 133.161 15.5134 128.05 15.5133 122.519L15.5134 91.0571C15.5134 88.2414 15.5134 86.8336 16.1059 86.0198C16.6227 85.3099 17.4171 84.8522 18.2916 84.7604C19.2942 84.6553 20.516 85.3591 22.9596 86.7669L50.1109 102.408C54.9106 105.174 57.8675 110.284 57.8675 115.815L57.8675 132.105C57.8675 134.454 57.8675 135.628 58.2104 136.679C58.5137 137.609 59.0098 138.465 59.6664 139.191C60.4086 140.011 61.4288 140.597 63.4694 141.767L64.0824 142.119C67.1346 143.871 68.6608 144.746 69.9127 144.613C71.0048 144.497 71.9964 143.925 72.6414 143.038C73.3809 142.021 73.3809 140.265 73.3809 136.751L73.3809 115.815C73.3809 104.754 67.4672 94.5326 57.8675 89.002L18.2224 66.1628C16.546 65.197 15.5133 63.4121 15.5133 61.4805C15.5133 55.9499 18.4702 50.8393 23.27 48.074L76.2433 17.5545C81.0432 14.7892 86.9568 14.7892 91.7567 17.5545L119.18 33.3541C121.624 34.762 122.846 35.4659 123.256 36.3849C123.614 37.1865 123.614 38.1019 123.256 38.9035C122.846 39.8225 121.624 40.5265 119.18 41.9343L91.3278 57.981C86.5279 60.7464 80.6143 60.7464 75.8144 57.981L60.2092 48.9904C58.6558 48.0955 57.8792 47.648 57.0526 47.4683C56.3212 47.3093 55.5647 47.303 54.8307 47.4497C54.0012 47.6155 53.2171 48.0498 51.6489 48.9186L49.7141 49.9904C46.5777 51.7278 45.0095 52.5965 44.4789 53.749C44.0162 54.7539 44.0065 55.9084 44.4522 56.9209C44.9633 58.0822 46.5166 58.9771 49.6233 60.7669L68.0577 71.3876C77.6574 76.9182 89.4847 76.9182 99.0844 71.3876L139.55 48.074C141.153 47.1507 143.127 47.1507 144.73 48.074C149.53 50.8393 152.487 55.9499 152.487 61.4805V122.519Z" fill="#5D29F0"/>+</g>+<defs>+<clipPath id="clip0_24_31">+<rect width="168" height="184" fill="white"/>+</clipPath>+</defs>+</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 c06c15bffe70..b4019a894f54 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -379,6 +379,7 @@ the row lists both.| rootly | HTTP | requests | ✅ || rss | HTTP | requests | ✅ || ruddr | HTTP | requests | ✅ |+| runpod | HTTP | requests | ✅ || safetyculture | HTTP | requests | ✅ || sage_hr | HTTP | requests | ✅ || salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -843,7 +844,6 @@ doesn't conflict with concurrent PRs.- rocketlane- rss- rudderstack-- runpod- safetyculture- sage_intacct- sailthrudiff --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 0c73f20059a8..4b78ecf3a92f 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@@ -3574,7 +3574,7 @@ class RuddrSourceConfig(config.Config):@config.configclass RunPodSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/canonical_descriptions.pynew file mode 100644index 000000000000..88957c634660--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/canonical_descriptions.py@@ -0,0 +1,121 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_API_DOCS = "https://rest.runpod.io/v1/docs"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "pods": {+ "description": "GPU and CPU Pods in your RunPod account, including on-demand instances and Serverless workers.",+ "docs_url": _API_DOCS,+ "columns": {+ "id": "Unique identifier for the Pod.",+ "name": "User-defined name for the Pod. Does not need to be unique.",+ "desiredStatus": "The current expected status of the Pod.",+ "image": "The image tag for the container run on the Pod.",+ "gpuTypeId": "The GPU type attached to the Pod.",+ "costPerHr": "The cost in RunPod credits per hour of running the Pod, before Savings Plans.",+ "adjustedCostPerHr": "The effective cost per hour of running the Pod, adjusted by active Savings Plans.",+ "machineId": "Unique identifier of the host machine the Pod is running on.",+ "endpointId": "If the Pod is a Serverless worker, the identifier of the associated endpoint.",+ "templateId": "If the Pod was created from a template, the identifier of that template.",+ "networkVolumeId": "If a network volume is attached, the identifier of that network volume.",+ "vcpuCount": "The number of virtual CPUs attached to the Pod.",+ "memoryInGb": "The amount of RAM, in gigabytes, attached to the Pod.",+ "containerDiskInGb": "Disk space, in gigabytes, allocated on the container disk (wiped on restart).",+ "volumeInGb": "Disk space, in gigabytes, allocated on the Pod volume (persisted across restarts).",+ "interruptible": "True if the Pod is rented as interruptible (lower cost, can be stopped at any time).",+ "publicIp": "The public IP address of the Pod, once initialized.",+ "lastStartedAt": "UTC timestamp when the Pod was last started.",+ "lastStatusChange": "Description of the last lifecycle event on the Pod.",+ "locked": "True if the Pod is locked, disabling stop and reset.",+ },+ },+ "endpoints": {+ "description": "Serverless endpoints in your RunPod account, including autoscaling configuration.",+ "docs_url": _API_DOCS,+ "columns": {+ "id": "Unique identifier for the Serverless endpoint.",+ "name": "User-defined name for the endpoint. Does not need to be unique.",+ "createdAt": "UTC timestamp when the endpoint was created.",+ "computeType": "The type of compute used by workers on the endpoint.",+ "gpuTypeIds": "RunPod GPU types which can be attached to the endpoint.",+ "gpuCount": "The number of GPUs attached to each worker.",+ "dataCenterIds": "RunPod data center IDs where workers can be located.",+ "templateId": "Identifier of the template used to create the endpoint.",+ "networkVolumeId": "Identifier of the network volume attached to the endpoint.",+ "workersMin": "The minimum number of workers kept running at the same time.",+ "workersMax": "The maximum number of workers that can run at the same time.",+ "idleTimeout": "Seconds a worker can run without a job before being scaled down.",+ "scalerType": "The method used to scale up workers (QUEUE_DELAY or REQUEST_COUNT).",+ "scalerValue": "The threshold value used by the configured scaler type.",+ "executionTimeoutMs": "Maximum milliseconds a request can run before the worker is stopped.",+ "version": "The latest version of the endpoint, updated on template or env changes.",+ "userId": "Identifier of the RunPod user who created the endpoint.",+ },+ },+ "templates": {+ "description": "Pod and Serverless templates in your RunPod account.",+ "docs_url": _API_DOCS,+ "columns": {+ "id": "Unique identifier for the template.",+ "name": "User-defined name for the template. Must be unique.",+ "imageName": "The image tag for the container run on Pods or workers created from the template.",+ "category": "The template category (NVIDIA, AMD, or CPU).",+ "isServerless": "True if instances created from the template are Serverless workers, false for Pods.",+ "isPublic": "True if the template is public and usable by any RunPod user.",+ "isRunpod": "True if the template is an official template managed by RunPod.",+ "containerDiskInGb": "Disk space, in gigabytes, allocated on the container disk (wiped on restart).",+ "volumeInGb": "Disk space, in gigabytes, allocated on the local volume (persisted across restarts).",+ "volumeMountPath": "Absolute path where the volume is mounted in the filesystem.",+ "ports": "Ports exposed on Pods or workers, formatted as [port]/[protocol].",+ "earned": "RunPod credits earned by the template creator from all instances created from it.",+ },+ },+ "network_volumes": {+ "description": "Network volumes in your RunPod account, attachable to Pods and Serverless endpoints.",+ "docs_url": _API_DOCS,+ "columns": {+ "id": "Unique identifier for the network volume.",+ "name": "User-defined name for the network volume. Does not need to be unique.",+ "size": "The amount of disk space, in gigabytes, allocated to the network volume.",+ "dataCenterId": "The RunPod data center ID where the network volume is located.",+ },+ },+ "billing_pods": {+ "description": "Daily billing history for Pods, one record per Pod per day bucket.",+ "docs_url": _API_DOCS,+ "columns": {+ "id": "Surrogate key derived from the bucket start and Pod ID.",+ "time": "The start of the day bucket the billing record applies to.",+ "podId": "The Pod the billing record applies to.",+ "amount": "The amount charged for the bucket, in USD.",+ "timeBilledMs": "The total time billed for the bucket, in milliseconds.",+ "diskSpaceBilledGb": "The amount of disk space billed for the bucket, in gigabytes.",+ },+ },+ "billing_endpoints": {+ "description": "Daily billing history for Serverless endpoints, one record per endpoint per day bucket.",+ "docs_url": _API_DOCS,+ "columns": {+ "id": "Surrogate key derived from the bucket start and endpoint ID.",+ "time": "The start of the day bucket the billing record applies to.",+ "endpointId": "The Serverless endpoint the billing record applies to.",+ "amount": "The amount charged for the bucket, in USD.",+ "timeBilledMs": "The total time billed for the bucket, in milliseconds.",+ "diskSpaceBilledGb": "The amount of disk space billed for the bucket, in gigabytes.",+ },+ },+ "billing_network_volumes": {+ "description": "Daily billing history for network volume storage, aggregated account-wide per day bucket.",+ "docs_url": _API_DOCS,+ "columns": {+ "id": "Surrogate key derived from the bucket start.",+ "time": "The start of the day bucket the billing record applies to.",+ "amount": "The amount charged for the bucket, in USD.",+ "diskSpaceBilledGb": "The amount of disk space billed for the bucket, in gigabytes.",+ "highPerformanceStorageAmount": "The amount charged for high performance storage for the bucket, in USD.",+ "highPerformanceStorageDiskSpaceBilledGb": "High performance storage disk space billed for the bucket, in gigabytes.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/runpod.py b/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/runpod.pynew file mode 100644index 000000000000..765218d881e8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/runpod.py@@ -0,0 +1,300 @@+import hashlib+import dataclasses+from collections.abc import Iterator+from datetime import (+ UTC,+ date,+ datetime,+ time as datetime_time,+ timedelta,+)+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.runpod.settings import (+ BILLING_BUCKET_SIZE,+ RUNPOD_BASE_URL,+ RUNPOD_ENDPOINTS,+ RunPodEndpointConfig,+)++# Billing responses are unpaginated, so bound each request to a fixed window and walk the windows+# chronologically — memory stays bounded and a crash resumes at the last unfetched window.+BILLING_WINDOW = timedelta(days=90)++# Floor for `startTime` on a full refresh. RunPod launched in 2022, so no billing data can predate+# this — starting here pulls all available history without requesting decades of empty buckets.+DEFAULT_STARTING_AT = datetime(2022, 1, 1, tzinfo=UTC)+++class RunPodRetryableError(Exception):+ pass+++class RunPodResumeConfig:+ # RFC 3339 start of the next unfetched billing window. Windows before it are fully yielded.+ window_start: str+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++def _format_rfc3339(value: datetime) -> str:+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _coerce_datetime(value: Any) -> datetime:+ 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_time.min, tzinfo=UTC)+ return datetime.fromisoformat(str(value).replace("Z", "+00:00")).astimezone(UTC)+++def _floor_to_day(value: datetime) -> datetime:+ return value.replace(hour=0, minute=0, second=0, microsecond=0)+++def _build_url(path: str, params: dict[str, Any]) -> str:+ encoded = urlencode([(k, str(v)) for k, v in params.items() if v is not None])+ url = f"{RUNPOD_BASE_URL}{path}"+ return f"{url}?{encoded}" if encoded else url+++@retry(+ retry=retry_if_exception_type(+ (+ RunPodRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_list(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> list[dict[str, Any]]:+ response = session.get(url, headers=headers, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ raise RunPodRetryableError(f"RunPod API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"RunPod API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ data = response.json()+ if data is None:+ return []+ if not isinstance(data, list):+ raise ValueError(f"RunPod API returned an unexpected non-list response for url={url}")+ return data+++def validate_credentials(api_key: str) -> bool:+ # A single cheap probe against the pods list confirms the API key is genuine.+ url = _build_url("/pods", {})+ try:+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10)+ except Exception:+ return False+ # 200 => valid. 403 => valid key restricted to other endpoints; still a real key, so accept it at+ # create time (sync-time 403s are caught by get_non_retryable_errors). 401 => bad key.+ return response.status_code in (200, 403)+++def _row_id(*parts: Any) -> str:+ """Deterministic surrogate id for a billing record.++ Hashes only the identity/dimension fields (never the amounts), so a bucket whose charges get+ restated between runs keeps the same id and merge updates it in place rather than inserting a+ duplicate.+ """+ # Use a sentinel for None so a missing dimension can never collide with an empty-string value.+ joined = "|".join("\x00" if p is None else str(p) for p in parts)+ return hashlib.sha256(joined.encode()).hexdigest()+++def _normalize_billing_record(record: dict[str, Any]) -> dict[str, Any]:+ return {+ "id": _row_id(record.get("time"), record.get("podId"), record.get("endpointId"), record.get("gpuTypeId")),+ **record,+ }+++def _billing_params(+ config: RunPodEndpointConfig, window_start: datetime, window_end: Optional[datetime]+) -> dict[str, Any]:+ params: dict[str, Any] = {+ "bucketSize": BILLING_BUCKET_SIZE,+ "startTime": _format_rfc3339(window_start),+ }+ if window_end is not None:+ params["endTime"] = _format_rfc3339(window_end)+ if config.group_by:+ params["grouping"] = config.group_by+ return params+++def _initial_window_start(+ resumable_source_manager: ResumableSourceManager[RunPodResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ logger: FilteringBoundLogger,+ now: datetime,+) -> datetime:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.window_start:+ logger.debug(f"RunPod: resuming billing sync from window_start={resume.window_start}")+ return _coerce_datetime(resume.window_start)++ if should_use_incremental_field and db_incremental_field_last_value:+ # Floor to UTC midnight so `startTime` stays aligned with day-bucket boundaries — a shifted+ # start could re-bucket the overlap window under different `time` values that merge can't+ # dedupe. Cap at today's bucket so a future-dated watermark still re-pulls the open bucket.+ watermark = _floor_to_day(_coerce_datetime(db_incremental_field_last_value))+ return min(watermark, _floor_to_day(now))++ return DEFAULT_STARTING_AT+++def _iter_billing_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RunPodResumeConfig],+ config: RunPodEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ now = datetime.now(UTC)+ window_start = _initial_window_start(+ resumable_source_manager, should_use_incremental_field, db_incremental_field_last_value, logger, now+ )++ while window_start <= now:+ proposed_end = window_start + BILLING_WINDOW+ # The final window runs to "now": omit endTime so the open bucket is included.+ window_end = proposed_end if proposed_end < now else None++ url = _build_url(config.path, _billing_params(config, window_start, window_end))+ records = _fetch_list(session, url, headers, logger)++ # Response ordering is undocumented; each window arrives whole, so sort client-side to keep+ # the ascending guarantee sort_mode="asc" promises the pipeline.+ rows = sorted((_normalize_billing_record(record) for record in records), key=lambda r: r.get("time") or "")+ if rows:+ yield rows++ if window_end is None:+ break+ # Save AFTER yielding so a crash re-yields the last window rather than skipping it — merge+ # dedupes the re-pulled rows on the surrogate id.+ resumable_source_manager.save_state(RunPodResumeConfig(window_start=_format_rfc3339(window_end)))+ window_start = window_end+++def _strip_sensitive_keys(value: Any, keys: tuple[str, ...]) -> Any:+ """Recursively drop keys holding user-configured secrets (e.g. `env` maps).++ Removes the whole field wherever it appears in the object graph, so a secret map nested under an+ embedded resource (an endpoint's template, say) is stripped too. The names inside an `env` map are+ arbitrary and user-chosen, so a key-name denylist can't recognise them — removing the container is+ the only reliable way to keep credentials out of the warehouse.+ """+ if isinstance(value, dict):+ return {k: _strip_sensitive_keys(v, keys) for k, v in value.items() if k not in keys}+ if isinstance(value, list):+ return [_strip_sensitive_keys(item, keys) for item in value]+ return value+++def _iter_inventory_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ config: RunPodEndpointConfig,+) -> Iterator[list[dict[str, Any]]]:+ # Inventory endpoints are unpaginated — the whole account snapshot arrives in one response.+ items = _fetch_list(session, _build_url(config.path, {}), headers, logger)+ if config.sensitive_keys:+ items = [_strip_sensitive_keys(item, config.sensitive_keys) for item in items]+ if items:+ yield items+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RunPodResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = RUNPOD_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # Endpoints carrying user-configured `env` secrets are excluded from HTTP sample capture so raw+ # response bodies with those credentials never reach captured samples (the values have arbitrary+ # names the name-based sample scrubbers can't recognise).+ session = make_tracked_session(capture=not config.sensitive_keys)++ if config.is_billing:+ yield from _iter_billing_rows(+ session,+ headers,+ logger,+ resumable_source_manager,+ config,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ else:+ yield from _iter_inventory_rows(session, headers, logger, config)+++def runpod_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RunPodResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = RUNPOD_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,+ ),+ primary_keys=config.primary_keys,+ # Billing windows advance chronologically and each window is sorted by bucket start before+ # yielding, so rows arrive ascending — the pipeline checkpoints the watermark per batch.+ 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/runpod/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/settings.pynew file mode 100644index 000000000000..91c2e733c17e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/settings.py@@ -0,0 +1,125 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++RUNPOD_BASE_URL = "https://rest.runpod.io/v1"++# Billing history is aggregated into time buckets; a fixed size keeps the bucket `time` values (and+# the surrogate ids derived from them) stable across syncs. `day` matches the API default and keeps+# row volume low while still supporting daily cost analytics.+BILLING_BUCKET_SIZE = "day"++# A bucket keeps accumulating charges until it closes, and RunPod doesn't document how long a closed+# bucket can be restated, so every incremental run re-pulls a trailing two days of buckets. Merge+# dedupes the overlap on the surrogate `id`.+_BILLING_LOOKBACK_SECONDS = 60 * 60 * 48++_TIME_INCREMENTAL_FIELD: list[IncrementalField] = [+ {+ "label": "time",+ "type": IncrementalFieldType.DateTime,+ "field": "time",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class RunPodEndpointConfig:+ name: str+ path: str+ primary_keys: list[str]+ # Billing endpoints return time-bucketed usage records windowed by startTime/endTime; resource+ # list endpoints return the full account inventory in one unpaginated response.+ is_billing: bool = False+ # Billing only: the `grouping` dimension requested so each bucket splits per resource. None keeps+ # the endpoint's aggregate shape (network volume billing has no grouping parameter).+ group_by: Optional[str] = None+ # Stable partition key — the bucket start never changes once emitted. Inventory tables are small+ # full-refresh snapshots, so they are not partitioned.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Only True where the API exposes a genuine server-side time filter (the billing endpoints via+ # startTime). Inventory lists have no updated-since filter, so they are full-refresh only.+ supports_incremental: bool = False+ # Response keys holding user-configured secrets — RunPod Pods, endpoints, and templates carry an+ # `env` map and `dockerStartCmd`/`dockerEntrypoint` command arrays that can contain cloud access+ # keys and other credentials. These are stripped recursively before yielding, and HTTP sample+ # capture is disabled for the endpoint (the values are arbitrary user-chosen strings the sample+ # scrubbers can't recognise) so raw bodies with the secrets never land in captured samples.+ sensitive_keys: tuple[str, ...] = ()+ # Billing buckets get restated while open, so append would materialize duplicates; merge-only.+ supports_append: bool = False+ default_incremental_lookback_seconds: Optional[int] = None+ should_sync_default: bool = True+++RUNPOD_ENDPOINTS: dict[str, RunPodEndpointConfig] = {+ "pods": RunPodEndpointConfig(+ name="pods",+ path="/pods",+ primary_keys=["id"],+ sensitive_keys=("env", "dockerStartCmd", "dockerEntrypoint"),+ ),+ "endpoints": RunPodEndpointConfig(+ name="endpoints",+ path="/endpoints",+ primary_keys=["id"],+ sensitive_keys=("env", "dockerStartCmd", "dockerEntrypoint"),+ ),+ "templates": RunPodEndpointConfig(+ name="templates",+ path="/templates",+ primary_keys=["id"],+ sensitive_keys=("env", "dockerStartCmd", "dockerEntrypoint"),+ ),+ "network_volumes": RunPodEndpointConfig(+ name="network_volumes",+ path="/networkvolumes",+ primary_keys=["id"],+ ),+ # `id` on the billing tables is synthesized from the bucket start plus every grouping dimension+ # (see runpod.py) — a non-null, stable key so merge updates a bucket in place as its amounts get+ # restated.+ "billing_pods": RunPodEndpointConfig(+ name="billing_pods",+ path="/billing/pods",+ primary_keys=["id"],+ is_billing=True,+ group_by="podId",+ partition_key="time",+ incremental_fields=_TIME_INCREMENTAL_FIELD,+ supports_incremental=True,+ default_incremental_lookback_seconds=_BILLING_LOOKBACK_SECONDS,+ ),+ "billing_endpoints": RunPodEndpointConfig(+ name="billing_endpoints",+ path="/billing/endpoints",+ primary_keys=["id"],+ is_billing=True,+ group_by="endpointId",+ partition_key="time",+ incremental_fields=_TIME_INCREMENTAL_FIELD,+ supports_incremental=True,+ default_incremental_lookback_seconds=_BILLING_LOOKBACK_SECONDS,+ ),+ # Network volume billing has no grouping parameter — records are account-wide aggregates per+ # bucket, so the surrogate id reduces to the bucket start.+ "billing_network_volumes": RunPodEndpointConfig(+ name="billing_network_volumes",+ path="/billing/networkvolumes",+ primary_keys=["id"],+ is_billing=True,+ partition_key="time",+ incremental_fields=_TIME_INCREMENTAL_FIELD,+ supports_incremental=True,+ default_incremental_lookback_seconds=_BILLING_LOOKBACK_SECONDS,+ ),+}++ENDPOINTS = tuple(RUNPOD_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in RUNPOD_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/source.pyindex c04df665c91d..2230f4d114cc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/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 RunPodSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.runpod.runpod import (+ RunPodResumeConfig,+ runpod_source,+ validate_credentials as validate_runpod_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.runpod.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ RUNPOD_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class RunPodSource(SimpleSource[RunPodSourceConfig]):+class RunPodSource(ResumableSource[RunPodSourceConfig, RunPodResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.RUNPOD@@ -24,8 +48,90 @@ class RunPodSource(SimpleSource[RunPodSourceConfig]):name=SchemaExternalDataSourceType.RUN_POD,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="RunPod",- iconPath="/static/services/runpod.png",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your RunPod API key to pull your GPU cloud infrastructure and billing history into the PostHog Data warehouse.++Create an API key in your [RunPod console settings](https://console.runpod.io/user/settings). A key with read permission is sufficient.""",+ iconPath="/static/services/runpod.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/runpod",keywords=["gpu", "cloud", "serverless", "billing"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="rpa_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.runpod.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://rest.runpod.io": "Your RunPod API key is invalid or has been revoked. Create a new API key in your RunPod console settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://rest.runpod.io": "Your RunPod API key does not have read access to this data. Update the key's permissions in your RunPod console settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: RunPodSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = RUNPOD_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_append,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,+ )++ 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: RunPodSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_runpod_credentials(config.api_key):+ return True, None++ return False, "Invalid RunPod API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RunPodResumeConfig]:+ return ResumableSourceManager[RunPodResumeConfig](inputs, RunPodResumeConfig)++ def source_for_pipeline(+ self,+ config: RunPodSourceConfig,+ resumable_source_manager: ResumableSourceManager[RunPodResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return runpod_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/tests/test_runpod.py b/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/tests/test_runpod.pynew file mode 100644index 000000000000..3f0405433dc2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/tests/test_runpod.py@@ -0,0 +1,286 @@+from datetime import UTC, datetime+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.runpod import runpod+from products.warehouse_sources.backend.temporal.data_imports.sources.runpod.runpod import (+ RunPodResumeConfig,+ _row_id,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.runpod.source import RunPodSource+++class _FakeResumableManager:+ def __init__(self, state: RunPodResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[RunPodResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> RunPodResumeConfig | None:+ return self._state++ def save_state(self, data: RunPodResumeConfig) -> None:+ self.saved.append(data)+++def _collect(+ manager: _FakeResumableManager, responses: list[list[dict]], endpoint: str, **kw: Any+) -> tuple[list[dict], list[dict[str, list[str]]]]:+ """Run get_rows with a stubbed HTTP layer; returns (rows, parsed query params per request)."""+ calls: list[dict[str, list[str]]] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> list[dict]:+ calls.append(parse_qs(urlparse(url).query))+ return responses[len(calls) - 1] if len(calls) <= len(responses) else []++ rows: list[dict] = []+ with (+ patch.object(runpod, "_fetch_list", fake_fetch),+ patch.object(runpod, "make_tracked_session", MagicMock()),+ ):+ for batch in get_rows(+ api_key="rpa_test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kw,+ ):+ rows.extend(batch)+ return rows, calls+++class TestRowId:+ def test_id_is_stable_across_amount_changes(self) -> None:+ # The surrogate key depends only on the bucket start and grouping dims, never the amounts —+ # otherwise a restated bucket would get a new id and merge would insert a duplicate.+ a = _row_id("2025-08-01T00:00:00Z", "pod_1", None, None)+ b = _row_id("2025-08-01T00:00:00Z", "pod_1", None, None)+ assert a == b+ assert a != _row_id("2025-08-01T00:00:00Z", "pod_2", None, None)++ def test_none_and_empty_string_distinguished_positionally(self) -> None:+ assert _row_id(None, "x") != _row_id("", "x")+ assert _row_id(None, "x") != _row_id("x", None)+++@freeze_time("2022-05-15T12:00:00Z")+class TestBillingWindows:+ def test_full_refresh_walks_windows_from_launch_date(self) -> None:+ responses = [+ [+ {"time": "2022-02-01T00:00:00Z", "podId": "p1", "amount": 2.0},+ {"time": "2022-01-01T00:00:00Z", "podId": "p1", "amount": 1.0},+ ],+ [{"time": "2022-04-15T00:00:00Z", "podId": "p1", "amount": 3.0}],+ ]+ manager = _FakeResumableManager()+ rows, calls = _collect(manager, responses, "billing_pods")++ # 2022-01-01 + 90 days = 2022-04-01; the second window reaches past "now" so endTime is+ # omitted to include the open bucket, and the walk terminates.+ assert len(calls) == 2+ assert calls[0]["startTime"] == ["2022-01-01T00:00:00Z"]+ assert calls[0]["endTime"] == ["2022-04-01T00:00:00Z"]+ assert calls[1]["startTime"] == ["2022-04-01T00:00:00Z"]+ assert "endTime" not in calls[1]+ assert calls[0]["bucketSize"] == ["day"]++ # Rows within a window are sorted ascending on the bucket start (sort_mode="asc" contract).+ assert [r["time"] for r in rows] == [+ "2022-01-01T00:00:00Z",+ "2022-02-01T00:00:00Z",+ "2022-04-15T00:00:00Z",+ ]+ assert all(r["id"] for r in rows)++ # State is saved after each non-final window so a crash resumes without skipping data.+ assert [s.window_start for s in manager.saved] == ["2022-04-01T00:00:00Z"]++ def test_resumes_from_saved_window_start(self) -> None:+ manager = _FakeResumableManager(RunPodResumeConfig(window_start="2022-04-01T00:00:00Z"))+ _, calls = _collect(manager, [[]], "billing_pods")+ assert len(calls) == 1+ assert calls[0]["startTime"] == ["2022-04-01T00:00:00Z"]++ def test_incremental_watermark_is_floored_to_day_bucket_boundary(self) -> None:+ # A mid-bucket startTime could re-bucket the overlap under shifted `time` values that merge+ # can't dedupe, so the watermark must be aligned to UTC midnight.+ _, calls = _collect(+ _FakeResumableManager(),+ [[]],+ "billing_pods",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2022, 5, 14, 9, 30, tzinfo=UTC),+ )+ assert calls[0]["startTime"] == ["2022-05-14T00:00:00Z"]++ def test_future_watermark_clamped_to_today(self) -> None:+ # A future-dated watermark must not skip syncing entirely; it re-pulls today's open bucket.+ _, calls = _collect(+ _FakeResumableManager(),+ [[]],+ "billing_pods",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2030, 1, 1, tzinfo=UTC),+ )+ assert len(calls) == 1+ assert calls[0]["startTime"] == ["2022-05-15T00:00:00Z"]++ @parameterized.expand(+ [+ ("billing_pods", "podId"),+ ("billing_endpoints", "endpointId"),+ ("billing_network_volumes", None),+ ]+ )+ def test_grouping_param_per_endpoint(self, endpoint: str, grouping: str | None) -> None:+ _, calls = _collect(_FakeResumableManager(), [[]], endpoint)+ if grouping is None:+ assert "grouping" not in calls[0]+ else:+ assert calls[0]["grouping"] == [grouping]+++class TestInventoryEndpoints:+ def test_single_unpaginated_request_yields_items_as_is(self) -> None:+ responses = [[{"id": "pod_1", "name": "worker"}, {"id": "pod_2", "name": "trainer"}]]+ rows, calls = _collect(_FakeResumableManager(), responses, "pods")+ assert len(calls) == 1+ assert "startTime" not in calls[0]+ assert [r["id"] for r in rows] == ["pod_1", "pod_2"]++ def test_empty_account_yields_no_batches(self) -> None:+ rows, _ = _collect(_FakeResumableManager(), [[]], "templates")+ assert rows == []+++class TestSensitiveDataStripping:+ @parameterized.expand(["pods", "endpoints", "templates"])+ def test_env_secrets_are_stripped_from_inventory_rows(self, endpoint: str) -> None:+ # A user-configured env map or startup command on a Pod/endpoint/template can hold cloud+ # credentials (as env values or CLI args); none of them may reach the warehouse where any+ # project member with warehouse access could read them.+ responses = [+ [+ {+ "id": "r1",+ "name": "worker",+ "env": {"AWS_SECRET_ACCESS_KEY": "supersecret"},+ "dockerStartCmd": ["serve", "--api-key=supersecret"],+ "dockerEntrypoint": ["/entry.sh", "--token=supersecret"],+ },+ {"id": "r2", "name": "trainer", "env": {}},+ ]+ ]+ rows, _ = _collect(_FakeResumableManager(), responses, endpoint)+ assert [r["id"] for r in rows] == ["r1", "r2"]+ assert all(key not in r for r in rows for key in ("env", "dockerStartCmd", "dockerEntrypoint"))++ def test_nested_env_is_stripped_recursively(self) -> None:+ # An endpoint can embed its template, so the secret map can be nested rather than top-level.+ responses = [[{"id": "e1", "template": {"id": "t1", "env": {"API_KEY": "secret"}}}]]+ rows, _ = _collect(_FakeResumableManager(), responses, "endpoints")+ assert rows[0]["template"] == {"id": "t1"}+ assert "env" not in rows[0]["template"]+++@freeze_time("2022-05-15T12:00:00Z")+class TestSampleCapture:+ @parameterized.expand(+ [+ ("pods", False),+ ("endpoints", False),+ ("templates", False),+ ("network_volumes", True),+ ("billing_pods", True),+ ]+ )+ def test_capture_disabled_only_where_responses_carry_env_secrets(+ self, endpoint: str, expected_capture: bool+ ) -> None:+ # Endpoints whose responses carry user-configured env secrets are excluded from HTTP sample+ # capture — the env values have arbitrary names the name-based scrubbers can't redact — while+ # secret-free endpoints keep capture on for debugging fixtures.+ with (+ patch.object(runpod, "_fetch_list", return_value=[]),+ patch.object(runpod, "make_tracked_session") as mock_session,+ ):+ list(+ get_rows(+ api_key="rpa_test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert mock_session.call_args.kwargs.get("capture") is expected_capture+++class TestFetchList:+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])+ def test_retryable_statuses_exhaust_retry_budget(self, _name: str, status: int) -> None:+ response = MagicMock(status_code=status, ok=False)+ session = MagicMock()+ session.get.return_value = response+ with patch.object(runpod._fetch_list.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(runpod.RunPodRetryableError):+ runpod._fetch_list(session, "https://rest.runpod.io/v1/pods", {}, MagicMock())+ assert session.get.call_count == 5++ def test_client_error_raises_for_status_without_retry(self) -> None:+ response = MagicMock(status_code=401, ok=False, text="unauthorized")+ response.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=response)+ session = MagicMock()+ session.get.return_value = response+ with pytest.raises(requests.HTTPError):+ runpod._fetch_list(session, "https://rest.runpod.io/v1/pods", {}, MagicMock())+ assert session.get.call_count == 1++ def test_non_list_response_raises(self) -> None:+ response = MagicMock(status_code=200, ok=True)+ response.json.return_value = {"error": "unexpected"}+ session = MagicMock()+ session.get.return_value = response+ with pytest.raises(ValueError):+ runpod._fetch_list(session, "https://rest.runpod.io/v1/pods", {}, MagicMock())+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("forbidden_scope", 403, True), ("unauthorized", 401, False)])+ def test_status_mapping(self, _name: str, status: int, expected: bool) -> None:+ # 403 is accepted at create time (real key restricted to other endpoints); 401 means a bad key.+ session = MagicMock()+ session.get.return_value = MagicMock(status_code=status)+ with patch.object(runpod, "make_tracked_session", return_value=session):+ assert validate_credentials("rpa_test") is expected++ def test_network_error_is_invalid(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(runpod, "make_tracked_session", return_value=session):+ assert validate_credentials("rpa_test") is False+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://rest.runpod.io/v1/billing/pods", True),+ ("forbidden", "403 Client Error: Forbidden for url: https://rest.runpod.io/v1/pods", True),+ ("read_timeout", "HTTPSConnectionPool(host='rest.runpod.io', port=443): Read timed out.", False),+ ("server_error", "500 Server Error: Internal Server Error for url: https://rest.runpod.io/v1/pods", False),+ ]+ )+ def test_only_credential_errors_are_non_retryable(self, _name: str, observed_error: str, expected: bool) -> None:+ non_retryable = RunPodSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable) is expecteddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/tests/test_runpod_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/tests/test_runpod_source.pynew file mode 100644index 000000000000..b17315f67ae2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/tests/test_runpod_source.py@@ -0,0 +1,100 @@+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import (+ ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,+ SourceFieldInputConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.runpod.runpod import RunPodResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.runpod.source import RunPodSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++_BILLING_ENDPOINTS = ["billing_pods", "billing_endpoints", "billing_network_volumes"]+_INVENTORY_ENDPOINTS = ["pods", "endpoints", "templates", "network_volumes"]+++class TestRunPodSourceConfig:+ def test_source_type(self) -> None:+ assert RunPodSource().source_type == ExternalDataSourceType.RUNPOD++ def test_config_exposes_single_secret_api_key_field(self) -> None:+ config = RunPodSource().get_source_config+ assert config.name == SchemaExternalDataSourceType.RUN_POD+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/runpod"+ fields = [f for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert [f.name for f in fields] == ["api_key"]+ assert fields[0].secret is True and fields[0].required is True+++class TestRunPodSchemas:+ def test_all_endpoints_present(self) -> None:+ names = {s.name for s in RunPodSource().get_schemas(MagicMock(), team_id=1)}+ assert names == set(_BILLING_ENDPOINTS) | set(_INVENTORY_ENDPOINTS)++ @parameterized.expand([(name,) for name in _BILLING_ENDPOINTS])+ def test_billing_endpoints_are_incremental_on_time(self, endpoint: str) -> None:+ # Only the billing endpoints have a genuine server-side time filter (startTime).+ schema = next(s for s in RunPodSource().get_schemas(MagicMock(), team_id=1) if s.name == endpoint)+ assert schema.supports_incremental is True+ assert schema.supports_append is False # open buckets get restated; append would duplicate+ assert [f["field"] for f in schema.incremental_fields] == ["time"]+ assert schema.default_incremental_lookback_seconds == 60 * 60 * 48++ @parameterized.expand([(name,) for name in _INVENTORY_ENDPOINTS])+ def test_inventory_endpoints_are_full_refresh_only(self, endpoint: str) -> None:+ # No updated-since filter exists on the resource lists, so they must not advertise incremental.+ schema = next(s for s in RunPodSource().get_schemas(MagicMock(), team_id=1) if s.name == endpoint)+ assert schema.supports_incremental is False+ assert schema.supports_append is False++ def test_names_filter(self) -> None:+ schemas = RunPodSource().get_schemas(MagicMock(), team_id=1, names=["billing_pods"])+ assert [s.name for s in schemas] == ["billing_pods"]+++class TestRunPodResumableManager:+ def test_manager_bound_to_resume_config(self) -> None:+ manager = RunPodSource().get_resumable_source_manager(MagicMock())+ assert manager._data_class is RunPodResumeConfig+++class TestRunPodSourceForPipeline:+ @parameterized.expand(+ [+ ("billing_pods", "datetime", ["time"]),+ ("billing_endpoints", "datetime", ["time"]),+ ("billing_network_volumes", "datetime", ["time"]),+ ("pods", None, None),+ ("templates", None, None),+ ]+ )+ def test_primary_keys_and_partitioning(+ self, endpoint: str, partition_mode: str | None, partition_keys: list[str] | None+ ) -> None:+ inputs = MagicMock()+ inputs.schema_name = endpoint+ inputs.logger = MagicMock()+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = None+ response = RunPodSource().source_for_pipeline(MagicMock(api_key="rpa_test"), MagicMock(), inputs)+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"+ assert response.partition_mode == partition_mode+ assert response.partition_keys == partition_keys+++class TestDocumentedTables:+ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog => the source opts into publishing its table list to public docs.+ assert RunPodSource().lists_tables_without_credentials is True+ tables = RunPodSource().get_documented_tables()+ names = {t["name"] for t in tables}+ assert set(_BILLING_ENDPOINTS) | set(_INVENTORY_ENDPOINTS) <= names+ billing = next(t for t in tables if t["name"] == "billing_pods")+ assert "Incremental" in billing["sync_methods"]+ assert billing["description"] # canonical description is surfaced