: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 lambda_labs import source (#70020)
Tom Owersb795932d2183
diff --git a/frontend/public/services/lambda_labs.svg b/frontend/public/services/lambda_labs.svgnew file mode 100644index 000000000000..67fcc4da7059--- /dev/null+++ b/frontend/public/services/lambda_labs.svg@@ -0,0 +1,12 @@+<svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">+<rect width="48" height="48" fill="black"/>+<g clip-path="url(#clip0_1_735)">+<path d="M15.3456 12.2712L21.6096 23.2476L14.64 35.9592L19.1256 35.9556L23.7696 27.2832L28.716 35.9592H33.288L19.9176 12.2676L15.3456 12.2712Z" fill="white"/>+<path d="M6 6V42H42V6H6ZM38.8212 38.8307H9.1788V9.16929H38.8212V38.8307Z" fill="white"/>+</g>+<defs>+<clipPath id="clip0_1_735">+<rect width="36" height="36" fill="white" transform="translate(6 6)"/>+</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 f659f63ad5da..795dab26f79e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -243,6 +243,7 @@ the row lists both.| kernel | HTTP | requests | ✅ || klaviyo | HTTP | requests | ✅ || lago | HTTP | requests | ✅ |+| lambda_labs | HTTP | requests | ✅ || langfuse | HTTP | requests | ✅ || launchdarkly | HTTP | requests | ✅ || kustomer | HTTP | requests | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.pyindex b5affeac20fc..7706b67c6e84 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.py@@ -45,6 +45,10 @@ REDACT_FIELD_NAMES: frozenset[str] = frozenset("apikey","password","authorization",+ # Lambda `/instances` embeds a live JupyterLab access token here (and in `jupyter_url`);+ # either grants terminal access, so keep them out of captured HTTP samples too.+ "jupyter_token",+ "jupyter_url",})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.pyindex b0d6771a72ca..e551d8c794cd 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@@ -2282,7 +2282,7 @@ class LagoSourceConfig(config.Config):@config.configclass LambdaLabsSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/canonical_descriptions.pynew file mode 100644index 000000000000..a17c27bfc4f0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/canonical_descriptions.py@@ -0,0 +1,138 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Lambda Cloud API reference (v1.10.0),+# https://cloud.lambda.ai/api/v1/docs. Keys match the endpoint names returned by `get_schemas`.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "instances": {+ "description": "Your running Lambda GPU cloud instances, including their instance type, region, and network details.",+ "docs_url": "https://cloud.lambda.ai/api/v1/docs#get-/api/v1/instances",+ "columns": {+ "id": "The unique identifier of the instance.",+ "name": "If set, the user-provided name of the instance.",+ "ip": "The public IPv4 address of the instance.",+ "private_ip": "The private IPv4 address of the instance.",+ "status": "The current status of the instance (e.g. active, booting, terminated).",+ "ssh_key_names": "The names of the SSH keys that are allowed to access the instance.",+ "file_system_names": "The names of the filesystems mounted to the instance.",+ "file_system_mounts": "The filesystems, along with their mount paths, mounted to the instance.",+ "region": "The region in which the instance is deployed.",+ "instance_type": "Detailed information about the instance's instance type, including its hourly price.",+ "hostname": "The hostname assigned to this instance, which resolves to the instance's IP.",+ "jupyter_token": "The secret token used to log into the JupyterLab server hosted on the instance.",+ "jupyter_url": "The URL that opens the JupyterLab environment on the instance.",+ "actions": "The current availability of common instance operations (restart, terminate, etc.).",+ "tags": "Key/value pairs representing the instance's tags.",+ "firewall_rulesets": "The firewall rulesets associated with this instance.",+ },+ },+ "instance_types": {+ "description": "The catalog of available Lambda instance types with pricing, hardware specs, and regional availability.",+ "docs_url": "https://cloud.lambda.ai/api/v1/docs#get-/api/v1/instance-types",+ "columns": {+ "name": "The name of the instance type (e.g. gpu_1x_a100).",+ "description": "A human-readable description of the instance type.",+ "gpu_description": "The type of GPU used by this instance type.",+ "price_cents_per_hour": "The price of the instance type in US cents per hour.",+ "specs": "Detailed technical specifications (vCPUs, memory, storage, GPU count).",+ "regions_with_capacity_available": "The regions where this instance type currently has capacity available.",+ },+ },+ "filesystems": {+ "description": "Your shared filesystems that can be mounted to instances.",+ "docs_url": "https://cloud.lambda.ai/api/v1/docs#get-/api/v1/file-systems",+ "columns": {+ "id": "The unique identifier (ID) of the filesystem.",+ "name": "The name of the filesystem.",+ "mount_point": "The default absolute path where the filesystem is mounted on instances.",+ "created": "The date and time at which the filesystem was created (ISO 8601).",+ "created_by": "The user in your team that created the filesystem.",+ "is_in_use": "Whether the filesystem is currently mounted to an instance.",+ "region": "The region in which the filesystem is deployed.",+ "bytes_used": "The approximate amount of storage used by the filesystem in bytes.",+ },+ },+ "images": {+ "description": "The machine images available in Lambda Cloud for launching instances.",+ "docs_url": "https://cloud.lambda.ai/api/v1/docs#get-/api/v1/images",+ "columns": {+ "id": "The unique identifier (ID) for an image.",+ "created_time": "The date and time that the image was created.",+ "updated_time": "The date and time that the image was last updated.",+ "name": "The human-readable identifier for the image.",+ "description": "Additional information about the image.",+ "family": "The family the image belongs to.",+ "version": "The image version.",+ "architecture": "The CPU architecture the image supports.",+ "region": "The region in which this image is available.",+ },+ },+ "ssh_keys": {+ "description": "The SSH keys stored on your account that can be used to access instances over SSH.",+ "docs_url": "https://cloud.lambda.ai/api/v1/docs#get-/api/v1/ssh-keys",+ "columns": {+ "id": "The unique identifier (ID) of the SSH key.",+ "name": "The name of the SSH key.",+ "public_key": "The public key for the SSH key.",+ },+ },+ "firewall_rulesets": {+ "description": "Collections of firewall rules that can be associated with instances.",+ "docs_url": "https://cloud.lambda.ai/api/v1/docs#get-/api/v1/firewall-rulesets",+ "columns": {+ "id": "The unique identifier of the firewall ruleset.",+ "name": "The name of the firewall ruleset.",+ "region": "The region in which the firewall ruleset is deployed.",+ "rules": "The list of firewall rules in this ruleset.",+ "created": "The date and time at which the firewall ruleset was created (ISO 8601).",+ "instance_ids": "The IDs of instances this firewall ruleset is associated with.",+ },+ },+ "regions": {+ "description": "The Lambda Cloud regions available to your account.",+ "docs_url": "https://cloud.lambda.ai/api/v1/docs#get-/api/v1/regions",+ "columns": {+ "name": "The region code (e.g. us-west-1).",+ "description": "The region description.",+ },+ },+ "audit_events": {+ "description": "Your account's audit log: a historical, immutable stream of actions performed against Lambda resources.",+ "docs_url": "https://cloud.lambda.ai/api/v1/docs#get-/api/v1/audit-events",+ "columns": {+ "event_id": "The unique identifier (ID) for this audit event.",+ "event_time": "The UTC timestamp for when the event occurred (ISO 8601).",+ "service_name": "The service in which the action was performed.",+ "resource_name": "The type of resource that was affected.",+ "action": "The action that was performed.",+ "catalog_version": "The version of the event catalog schema.",+ "actor_lrn": "The Lambda Resource Name (LRN) of the actor who performed the action.",+ "resource_lrns": "The Lambda Resource Names (LRNs) of the resources affected by this action.",+ "resource_owner_lrn": "The Lambda Resource Name (LRN) of the account that owns the affected resources.",+ "request_api_key_lrn": "The Lambda Resource Name (LRN) of the API key used to authenticate the request, if applicable.",+ "additional_details": "Additional event-specific details; the exact keys vary by event type.",+ },+ },+ "tickets": {+ "description": "Your Lambda support tickets, including their status, severity, and comment history.",+ "docs_url": "https://cloud.lambda.ai/api/v1/docs#get-/api/v1/tickets",+ "columns": {+ "id": "The unique identifier for the ticket.",+ "subject": "A short summary of the issue.",+ "description": "The initial text provided when creating the issue or request.",+ "type": "The type of support ticket (incident, service_request, automated_event).",+ "severity": "The severity level of the issue; omitted unless the ticket is an incident.",+ "status": "The current status of the ticket.",+ "external_ticket_provider": "The external ticketing provider name (e.g. zendesk).",+ "external_ticket_id": "The external provider ticket ID.",+ "hostname": "The hostname of the affected device.",+ "device_serial": "The serial number of the affected device.",+ "created_at": "The date and time at which the ticket was created (ISO 8601).",+ "updated_at": "The date and time at which the ticket was last updated (ISO 8601).",+ "resolved_at": "The date and time at which the ticket was resolved (ISO 8601).",+ "affected_devices": "The list of devices affected by the issue.",+ "comments": "The ticket's full comment history.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/lambda_labs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/lambda_labs.pynew file mode 100644index 000000000000..01c4ec3ce0c8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/lambda_labs.py@@ -0,0 +1,225 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.lambda_labs.settings import (+ LAMBDA_LABS_ENDPOINTS,+ LambdaLabsEndpoint,+)++# cloud.lambdalabs.com is a deprecated alias for the same API.+LAMBDA_LABS_BASE_URL = "https://cloud.lambda.ai/api/v1"+++class LambdaLabsRetryableError(Exception):+ pass+++class LambdaLabsResumeConfig:+ # The `page_token` cursor of the next page to fetch. Lambda's cursor already encodes the query+ # window (the incremental `start` filter is only sent on the first request), so the token alone+ # is enough to resume mid-endpoint.+ page_token: str+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++def _format_iso8601(value: Any) -> str:+ """Format a datetime/date as an ISO 8601 UTC timestamp with a `Z` suffix (millisecond precision),+ which the Lambda API's `start`/`end` filters accept."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+ if isinstance(value, date):+ return _format_iso8601(datetime.combine(value, datetime.min.time(), tzinfo=UTC))+ return str(value)+++def _dig(data: dict[str, Any], dotted_path: str) -> Any:+ """Resolve a dotted key path within a nested response body, returning None if any hop is missing."""+ current: Any = data+ for part in dotted_path.split("."):+ if not isinstance(current, dict):+ return None+ current = current.get(part)+ return current+++def _flatten_instance_type(value: dict[str, Any]) -> dict[str, Any]:+ """Turn one `/instance-types` map value into a flat row.++ The endpoint returns `data` as an object keyed by instance-type name; each value nests the+ catalog entry under `instance_type` alongside `regions_with_capacity_available`. We hoist the+ `instance_type` fields (which include `name`, the primary key) to the top level and keep the+ regional availability alongside them.++ A missing or malformed `instance_type` raises rather than yielding a row without its primary+ key, which would otherwise surface later as a warehouse load failure or a keyless bad row.+ """+ row = dict(value["instance_type"])+ row["regions_with_capacity_available"] = value.get("regions_with_capacity_available", [])+ return row+++# `/instances` records carry a live JupyterLab access token (`jupyter_token`) and a URL that+# embeds the same token (`jupyter_url`). Either grants terminal access to the running instance, so+# they must never land in the warehouse where any project member with read access could retrieve+# them. Stripped from every record defensively, regardless of endpoint.+_SENSITIVE_FIELDS: frozenset[str] = frozenset({"jupyter_token", "jupyter_url"})+++def _scrub_sensitive(record: dict[str, Any]) -> dict[str, Any]:+ if _SENSITIVE_FIELDS.isdisjoint(record):+ return record+ return {key: value for key, value in record.items() if key not in _SENSITIVE_FIELDS}+++def _extract_records(data: dict[str, Any], endpoint: LambdaLabsEndpoint) -> list[dict[str, Any]]:+ if endpoint.is_map:+ raw_map = data.get("data") or {}+ records = [_flatten_instance_type(value) for value in raw_map.values()]+ else:+ records = _dig(data, endpoint.records_path) or []+ return [_scrub_sensitive(record) for record in records]+++@retry(+ # ChunkedEncodingError is a mid-stream connection break (truncated chunked body); it's transient+ # like ConnectionError/ReadTimeout but not a ConnectionError subclass, so list it explicitly.+ retry=retry_if_exception_type(+ (+ LambdaLabsRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ # Lambda rate-limits to ~1 request/second; the jittered backoff also absorbs 429s without a+ # hardcoded inter-request sleep.+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ url: str,+ headers: dict[str, str],+ params: dict[str, str],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.get(url, headers=headers, params=params or None, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ raise LambdaLabsRetryableError(f"Lambda API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Lambda API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LambdaLabsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = LAMBDA_LABS_ENDPOINTS[endpoint]+ session = make_tracked_session()+ headers = _get_headers(api_key)+ url = f"{LAMBDA_LABS_BASE_URL}{config.path}"++ params: dict[str, str] = {}+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if resume is not None and resume.page_token:+ # Mid-endpoint resume: the cursor already encodes the query window, so only the token is sent.+ params = {"page_token": resume.page_token}+ logger.debug(f"Lambda: resuming {endpoint} from page_token")+ elif config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value is not None:+ # `start` is inclusive, so the boundary event is re-fetched and deduped on the primary key.+ params["start"] = _format_iso8601(db_incremental_field_last_value)++ while True:+ data = _fetch_page(session, url, headers, params, logger)++ records = _extract_records(data, config)+ if records:+ yield records++ next_token = _dig(data, config.page_token_path) if config.page_token_path else None+ if not next_token:+ break++ # Save AFTER yielding so a crash re-yields the last page rather than skipping it; merge+ # dedupes the overlap on the primary key.+ resumable_source_manager.save_state(LambdaLabsResumeConfig(page_token=str(next_token)))+ # The cursor carries the window forward; subsequent pages send only the token.+ params = {"page_token": str(next_token)}+++def lambda_labs_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LambdaLabsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = LAMBDA_LABS_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,+ # audit-events pages forward from `start` via an ascending timestamp cursor; the unpaginated+ # full-refresh endpoints don't use the watermark, so asc is a safe default for them too.+ sort_mode="asc",+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def validate_credentials(api_key: str) -> bool:+ """Confirm the API key is accepted with one cheap, account-wide read (`/ssh-keys`).++ Returns False only on a definitive auth rejection (401/403). A network error, timeout, or+ 5xx propagates so the caller can tell an invalid key apart from a temporary Lambda outage+ rather than reporting the latter as an invalid key.+ """+ response = make_tracked_session().get(+ f"{LAMBDA_LABS_BASE_URL}/ssh-keys",+ headers=_get_headers(api_key),+ timeout=10,+ )+ if response.status_code in (401, 403):+ return False+ response.raise_for_status()+ return Truediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/settings.pynew file mode 100644index 000000000000..8e6da99e9053--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/settings.py@@ -0,0 +1,71 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class LambdaLabsEndpoint:+ name: str+ path: str+ primary_keys: list[str]+ # Dotted path to the record list within the JSON body. Lambda wraps every payload in a+ # top-level `data` key; `tickets` nests its list one level deeper under `data.tickets`.+ records_path: str = "data"+ # Dotted path to the next-page cursor, or None when the endpoint returns the whole list in a+ # single response (most Lambda list endpoints are unpaginated).+ page_token_path: Optional[str] = None+ # `data` is an object keyed by id rather than a list (only `/instance-types`).+ is_map: bool = False+ # Stable creation-style timestamp to partition by; never an `updated_at`-style field.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # True only when the API exposes a genuine server-side timestamp filter (audit-events `start`).+ supports_incremental: bool = False+++# Only `audit-events` accepts server-side `start`/`end` timestamp filters, so it is the only+# endpoint synced incrementally. Every other list endpoint returns the full collection with no+# time filter, so those are full-refresh only (declaring them incremental would re-fetch the whole+# list each run at no saving).+LAMBDA_LABS_ENDPOINTS: dict[str, LambdaLabsEndpoint] = {+ "instances": LambdaLabsEndpoint(name="instances", path="/instances", primary_keys=["id"]),+ "instance_types": LambdaLabsEndpoint(+ name="instance_types", path="/instance-types", primary_keys=["name"], is_map=True+ ),+ "filesystems": LambdaLabsEndpoint(name="filesystems", path="/file-systems", primary_keys=["id"]),+ "images": LambdaLabsEndpoint(name="images", path="/images", primary_keys=["id"]),+ "ssh_keys": LambdaLabsEndpoint(name="ssh_keys", path="/ssh-keys", primary_keys=["id"]),+ "firewall_rulesets": LambdaLabsEndpoint(name="firewall_rulesets", path="/firewall-rulesets", primary_keys=["id"]),+ "regions": LambdaLabsEndpoint(name="regions", path="/regions", primary_keys=["name"]),+ "audit_events": LambdaLabsEndpoint(+ name="audit_events",+ path="/audit-events",+ primary_keys=["event_id"],+ page_token_path="page_token",+ partition_key="event_time",+ supports_incremental=True,+ incremental_fields=[+ {+ "label": "event_time",+ "type": IncrementalFieldType.DateTime,+ "field": "event_time",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "tickets": LambdaLabsEndpoint(+ name="tickets",+ path="/tickets",+ primary_keys=["id"],+ records_path="data.tickets",+ page_token_path="data.page_token",+ partition_key="created_at",+ ),+}++ENDPOINTS = tuple(LAMBDA_LABS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in LAMBDA_LABS_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/source.pyindex becaf4c1cbdc..c59a8721d8dc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/source.py@@ -1,31 +1,143 @@-from typing import cast+from typing import Optional, cast++import requestsfrom 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 LambdaLabsSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.lambda_labs.lambda_labs import (+ LambdaLabsResumeConfig,+ lambda_labs_source,+ validate_credentials as validate_lambda_labs_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.lambda_labs.settings import LAMBDA_LABS_ENDPOINTSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class LambdaLabsSource(SimpleSource[LambdaLabsSourceConfig]):+class LambdaLabsSource(ResumableSource[LambdaLabsSourceConfig, LambdaLabsResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.LAMBDALABS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A bad/revoked key surfaces as an HTTPError when `_fetch_page` calls `raise_for_status()`.+ # Retrying can't fix a credential problem, so stop the sync. Match the stable status text+ # and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://cloud.lambda.ai": "Your Lambda API key is invalid or has been revoked. Create a new API key in your Lambda dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://cloud.lambda.ai": "Your Lambda API key does not have permission to access this data. Check the key in your Lambda dashboard, then reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.lambda_labs.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: LambdaLabsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint.name,+ supports_incremental=endpoint.supports_incremental,+ supports_append=endpoint.supports_incremental,+ incremental_fields=endpoint.incremental_fields,+ )+ for endpoint in LAMBDA_LABS_ENDPOINTS.values()+ ]++ 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: LambdaLabsSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ if validate_lambda_labs_credentials(config.api_key):+ return True, None+ return False, "Invalid Lambda API key"+ except requests.RequestException:+ # A network blip, timeout, or 5xx isn't a bad key — don't mislabel it as invalid.+ return (+ False,+ "Could not reach Lambda to validate the API key. This may be a temporary network or service issue — please try again.",+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LambdaLabsResumeConfig]:+ return ResumableSourceManager[LambdaLabsResumeConfig](inputs, LambdaLabsResumeConfig)++ def source_for_pipeline(+ self,+ config: LambdaLabsSourceConfig,+ resumable_source_manager: ResumableSourceManager[LambdaLabsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return lambda_labs_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,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.LAMBDA_LABS,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Lambda",- iconPath="/static/services/lambda_labs.png",- keywords=["gpu", "cloud", "compute", "infrastructure"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Lambda API key to pull your Lambda (Lambda Labs) GPU cloud data into the PostHog Data warehouse.++You can create an API key in the [API keys section](https://cloud.lambda.ai/api-keys) of your Lambda dashboard. The key has account-wide access.""",+ iconPath="/static/services/lambda_labs.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/lambda-labs",+ keywords=["gpu", "cloud", "compute", "infrastructure", "lambda labs"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="secret_...",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/tests/test_lambda_labs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/tests/test_lambda_labs.pynew file mode 100644index 000000000000..87f558ef408c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/tests/test_lambda_labs.py@@ -0,0 +1,242 @@+import json+from datetime import UTC, date, datetime+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++import requests+import structlog++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.lambda_labs.lambda_labs import (+ LambdaLabsResumeConfig,+ _extract_records,+ _format_iso8601,+ get_rows,+ lambda_labs_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.lambda_labs.settings import LAMBDA_LABS_ENDPOINTS++_TRANSPORT = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.lambda_labs.lambda_labs.make_tracked_session"+)+++class _FakeResponse:+ def __init__(self, body: dict[str, Any], status_code: int = 200) -> None:+ self._body = body+ self.status_code = status_code+ self.ok = 200 <= status_code < 400+ self.text = json.dumps(body)++ def json(self) -> dict[str, Any]:+ return self._body++ def raise_for_status(self) -> None:+ if not self.ok:+ raise requests.HTTPError(f"{self.status_code} Client Error", response=cast("requests.Response", self))+++class _FakeSession:+ def __init__(self, responses: list[_FakeResponse]) -> None:+ self._responses = iter(responses)+ self.calls: list[dict[str, Any]] = []++ def get(self, url: str, headers: Any = None, params: Any = None, timeout: Any = None) -> _FakeResponse:+ self.calls.append({"url": url, "params": dict(params or {})})+ return next(self._responses)+++def _drive(+ endpoint: str, manager: Any, responses: list[_FakeResponse], **kwargs: Any+) -> tuple[_FakeSession, list[Any]]:+ session = _FakeSession(responses)+ with patch(_TRANSPORT, return_value=session):+ rows = list(+ get_rows(+ api_key="secret_key",+ endpoint=endpoint,+ logger=structlog.get_logger(),+ resumable_source_manager=manager,+ **kwargs,+ )+ )+ return session, rows+++class TestExtractRecords:+ @pytest.mark.parametrize(+ ("endpoint", "body", "expected"),+ [+ (+ "instances",+ {"data": [{"id": "i-1"}, {"id": "i-2"}]},+ [{"id": "i-1"}, {"id": "i-2"}],+ ),+ (+ # A live JupyterLab access token (and the URL embedding it) must be stripped so it+ # never lands in the warehouse where a project member could retrieve it.+ "instances",+ {+ "data": [+ {+ "id": "i-1",+ "jupyter_token": "secret-token",+ "jupyter_url": "https://jupyter.lambda.ai/?token=secret-token",+ "name": "gpu-box",+ }+ ]+ },+ [{"id": "i-1", "name": "gpu-box"}],+ ),+ (+ # The map endpoint hoists `instance_type` fields to the top level (including `name`,+ # the primary key) and keeps regional availability alongside them.+ "instance_types",+ {+ "data": {+ "gpu_1x_a100": {+ "instance_type": {"name": "gpu_1x_a100", "price_cents_per_hour": 110},+ "regions_with_capacity_available": [{"name": "us-west-1"}],+ }+ }+ },+ [+ {+ "name": "gpu_1x_a100",+ "price_cents_per_hour": 110,+ "regions_with_capacity_available": [{"name": "us-west-1"}],+ }+ ],+ ),+ (+ # tickets nests its list one level deeper under `data.tickets`.+ "tickets",+ {"data": {"tickets": [{"id": "t1"}], "page_token": None}},+ [{"id": "t1"}],+ ),+ (+ "audit_events",+ {"data": [{"event_id": "e1"}], "page_token": "next"},+ [{"event_id": "e1"}],+ ),+ ],+ )+ def test_extract_records(self, endpoint: str, body: dict[str, Any], expected: list[dict[str, Any]]) -> None:+ assert _extract_records(body, LAMBDA_LABS_ENDPOINTS[endpoint]) == expected+++class TestFormatIso8601:+ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ (datetime(2025, 9, 15, 10, 30, 45, 123456, tzinfo=UTC), "2025-09-15T10:30:45.123Z"),+ # A naive datetime is treated as UTC rather than shifted by the machine's local zone.+ (datetime(2025, 1, 1, 0, 0, 0), "2025-01-01T00:00:00.000Z"),+ (date(2025, 3, 4), "2025-03-04T00:00:00.000Z"),+ ],+ )+ def test_format(self, value: Any, expected: str) -> None:+ assert _format_iso8601(value) == expected+++class TestPaginationAndResume:+ def test_unpaginated_endpoint_yields_once_and_never_saves_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ session, rows = _drive("instances", manager, [_FakeResponse({"data": [{"id": "i-1"}]})])++ assert rows == [[{"id": "i-1"}]]+ assert len(session.calls) == 1+ manager.save_state.assert_not_called()++ def test_paginates_and_saves_state_after_each_non_terminal_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _FakeResponse({"data": [{"event_id": "e1"}], "page_token": "tok-1"}),+ _FakeResponse({"data": [{"event_id": "e2"}], "page_token": "tok-2"}),+ _FakeResponse({"data": [{"event_id": "e3"}], "page_token": None}),+ ]+ session, rows = _drive("audit_events", manager, responses)++ assert rows == [[{"event_id": "e1"}], [{"event_id": "e2"}], [{"event_id": "e3"}]]+ # First page carries no cursor; subsequent pages carry the prior page's token only.+ assert [c["params"].get("page_token") for c in session.calls] == [None, "tok-1", "tok-2"]+ # State is saved only for non-terminal pages, so a crash re-yields the last page.+ assert [c.args[0] for c in manager.save_state.call_args_list] == [+ LambdaLabsResumeConfig(page_token="tok-1"),+ LambdaLabsResumeConfig(page_token="tok-2"),+ ]++ def test_resume_seeds_first_request_with_saved_token_only(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = LambdaLabsResumeConfig(page_token="tok-resumed")++ session, _ = _drive(+ "audit_events",+ manager,+ [_FakeResponse({"data": [{"event_id": "e9"}], "page_token": None})],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2025, 1, 1, tzinfo=UTC),+ )++ # On resume the cursor already encodes the window, so only the token is sent — never `start`.+ assert session.calls[0]["params"] == {"page_token": "tok-resumed"}++ def test_incremental_first_sync_sends_start_filter(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ session, _ = _drive(+ "audit_events",+ manager,+ [_FakeResponse({"data": [{"event_id": "e1"}], "page_token": None})],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2025, 6, 1, 12, 0, 0, tzinfo=UTC),+ )++ assert session.calls[0]["params"] == {"start": "2025-06-01T12:00:00.000Z"}++ def test_non_incremental_endpoint_ignores_incremental_value(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ # `instances` has no server-side time filter, so a stray last-value must not become a `start`.+ session, _ = _drive(+ "instances",+ manager,+ [_FakeResponse({"data": [{"id": "i-1"}]})],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2025, 6, 1, tzinfo=UTC),+ )++ assert session.calls[0]["params"] == {}+++class TestSourceResponse:+ @pytest.mark.parametrize("endpoint", list(LAMBDA_LABS_ENDPOINTS.keys()))+ def test_source_response_shape(self, endpoint: str) -> None:+ config = LAMBDA_LABS_ENDPOINTS[endpoint]+ response = lambda_labs_source(+ api_key="secret_key",+ endpoint=endpoint,+ logger=structlog.get_logger(),+ resumable_source_manager=MagicMock(spec=ResumableSourceManager),+ )++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ # Ascending is required for the audit-events incremental watermark to advance correctly.+ assert response.sort_mode == "asc"++ 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 Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/tests/test_lambda_labs_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/tests/test_lambda_labs_source.pynew file mode 100644index 000000000000..fad11231f733--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/tests/test_lambda_labs_source.py@@ -0,0 +1,118 @@+from typing import Any++import pytest+from unittest.mock import patch++import requests++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++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 LambdaLabsSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.lambda_labs.lambda_labs import (+ LambdaLabsResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.lambda_labs.source import LambdaLabsSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _inputs() -> Any:+ return type(+ "Inputs",+ (),+ {"team_id": 1, "job_id": "job-1", "logger": None},+ )()+++class TestLambdaLabsSource:+ def test_source_type(self) -> None:+ assert LambdaLabsSource().source_type == ExternalDataSourceType.LAMBDALABS++ def test_get_source_config(self) -> None:+ config = LambdaLabsSource().get_source_config+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/lambda-labs"++ fields = config.fields+ assert len(fields) == 1+ api_key = fields[0]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert api_key.name == "api_key"+ # The API key is a secret and must render as a password input.+ assert api_key.type == SourceFieldInputConfigType.PASSWORD+ assert api_key.secret is True+ assert api_key.required is True++ def test_only_audit_events_is_incremental(self) -> None:+ schemas = {s.name: s for s in LambdaLabsSource().get_schemas(LambdaLabsSourceConfig(api_key="k"), team_id=1)}++ assert schemas["audit_events"].supports_incremental is True+ assert [f["field"] for f in schemas["audit_events"].incremental_fields] == ["event_time"]++ for name, schema in schemas.items():+ if name == "audit_events":+ continue+ assert schema.supports_incremental is False, name+ assert schema.incremental_fields == [], name++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = LambdaLabsSource().get_schemas(+ LambdaLabsSourceConfig(api_key="k"), team_id=1, names=["instances", "regions"]+ )+ assert {s.name for s in schemas} == {"instances", "regions"}++ @pytest.mark.parametrize(+ ("outcome", "expected_ok", "expected_error"),+ [+ (True, True, None),+ (False, False, "Invalid Lambda API key"),+ # A transient failure must not be reported as an invalid key — it should surface as a+ # retryable "could not reach" message so the user isn't sent to rotate a valid key.+ (+ requests.ConnectionError("boom"),+ False,+ "Could not reach Lambda to validate the API key. This may be a temporary network or service issue — please try again.",+ ),+ ],+ )+ def test_validate_credentials(self, outcome: Any, expected_ok: bool, expected_error: str | None) -> None:+ patch_kwargs = {"side_effect": outcome} if isinstance(outcome, Exception) else {"return_value": outcome}+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.lambda_labs.source.validate_lambda_labs_credentials",+ **patch_kwargs,+ ):+ ok, error = LambdaLabsSource().validate_credentials(LambdaLabsSourceConfig(api_key="k"), team_id=1)+ assert ok is expected_ok+ assert error == expected_error++ def test_non_retryable_errors_cover_auth_failures(self) -> None:+ errors = LambdaLabsSource().get_non_retryable_errors()+ assert any(k.startswith("401 Client Error") for k in errors)+ assert any(k.startswith("403 Client Error") for k in errors)++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = LambdaLabsSource().get_resumable_source_manager(_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is LambdaLabsResumeConfig++ def test_documented_tables_render_without_credentials(self) -> None:+ # `lists_tables_without_credentials` powers the public docs "Supported tables" section; it must+ # enumerate every endpoint with no I/O.+ tables = LambdaLabsSource().get_documented_tables()+ assert {t["name"] for t in tables} == {+ "instances",+ "instance_types",+ "filesystems",+ "images",+ "ssh_keys",+ "firewall_rulesets",+ "regions",+ "audit_events",+ "tickets",+ }