: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 the aws sagemaker import source (#110804)
Tom Owers5372ade688ca
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 47577edac2c2..70f683e2c693 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -110,6 +110,7 @@ the row lists both.| aws_glue_data_catalog | HTTP | requests | ✅ || aws_inspector | HTTP | requests | ✅ || aws_organizations | HTTP | requests | ✅ |+| aws_sagemaker | HTTP | requests | ✅ || aws_security_hub | HTTP | requests | ✅ || aws_ses | HTTP | requests | ✅ || aws_waf | HTTP | requests | ✅ |@@ -928,7 +929,6 @@ doesn't conflict with concurrent PRs.- aws_iam_access_analyzer- aws_macie- aws_rds_performance_insights-- aws_sagemaker- aws_savings_plans- aws_step_functions- aws_supportdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/aws_sagemaker.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/aws_sagemaker.pynew file mode 100644index 000000000000..ba8907c9bd00--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/aws_sagemaker.py@@ -0,0 +1,267 @@+import re+import json+import datetime as dt+from collections.abc import Iterator+from typing import Any++import requests+from botocore.auth import SigV4Auth+from botocore.awsrequest import AWSRequest+from botocore.credentials import Credentials+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_sagemaker.settings import (+ ENDPOINTS,+ MAX_RESULTS,+ TARGET_PREFIXES,+)+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.http.transport import BoundedRetry+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 schema_for_resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awssagemaker import (+ AwsSagemakerSourceConfig,+)++TRANSPORT_RETRY = BoundedRetry(+ total=3,+ backoff_factor=1,+ status_forcelist=(429, 500, 502, 503, 504),+ allowed_methods=frozenset(["POST"]),+ raise_on_status=False,+)+THROTTLE_CODES = {"ThrottlingException", "Throttling", "TooManyRequestsException", "RequestLimitExceeded"}+ERROR_MESSAGES = {+ "AccessDenied": "AWS denied access. Grant the SageMaker list and describe permissions for the selected tables.",+ "UnrecognizedClientException": "AWS rejected the credentials. Check the access key ID, secret access key, and session token.",+ "InvalidClientTokenId": "AWS rejected the access key. Enter an active access key ID and secret access key.",+ "InvalidSignatureException": "AWS rejected the signature. Check the secret access key and session token.",+ "SignatureDoesNotMatch": "AWS rejected the signature. Check the secret access key and selected region.",+ "ExpiredToken": "The AWS session token expired. Reconnect with new credentials.",+ "SubscriptionRequiredException": "Enable SageMaker for this AWS account and region, then try again.",+ "OptInRequired": "Enable SageMaker for this AWS account and region, then try again.",+}+_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")+_TIMESTAMP_FIELDS = {+ "CreationTime",+ "LastModifiedTime",+ "TrainingStartTime",+ "TrainingEndTime",+ "ProcessingStartTime",+ "ProcessingEndTime",+}+++@frozen+class AwsSagemakerResumeConfig:+ next_token: str | None = None+ watermark: float | None = None+ complete: bool = False+++class AwsSagemakerError(Exception):+ def __init__(self, code: str) -> None:+ self.code = code+ super().__init__(f"AWS SageMaker request failed: {code}")+++class AwsSagemakerThrottledError(AwsSagemakerError):+ pass+++def endpoint_url(region: str) -> str:+ if not re.fullmatch(r"(?:af|ap|ca|cn|eu|il|me|mx|sa|us)(?:-gov)?-[a-z]+-\d+", region):+ raise ValueError("Enter an AWS region, such as us-east-1.")+ suffix = "amazonaws.com.cn" if region.startswith("cn-") else "amazonaws.com"+ return f"https://api.sagemaker.{region}.{suffix}/"+++def error_for_response(response: requests.Response) -> AwsSagemakerError:+ try:+ body = response.json()+ except ValueError:+ body = {}+ if not isinstance(body, dict):+ body = {}+ raw_code = response.headers.get("x-amzn-ErrorType") or body.get("__type") or body.get("code")+ code = str(raw_code or f"HTTP {response.status_code}").split(":")[0].split("#")[-1]+ # Only body-level throttles need another retry layer; the transport retries 429 and 5xx.+ if response.status_code == 400 and code in THROTTLE_CODES:+ return AwsSagemakerThrottledError(code)+ return AwsSagemakerError(code)+++class AwsSagemakerClient:+ def __init__(self, config: AwsSagemakerSourceConfig, api_version: str) -> None:+ if not config.aws_access_key_id or not config.aws_secret_access_key:+ raise ValueError("Enter both an AWS access key ID and a secret access key.")+ if api_version not in TARGET_PREFIXES:+ raise ValueError(f"Unsupported SageMaker API version: {api_version}")+ self.url = endpoint_url(config.region)+ self.target_prefix = TARGET_PREFIXES[api_version]+ self.signer = SigV4Auth(+ Credentials(config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token or None),+ "sagemaker",+ config.region,+ )+ self.session = make_tracked_session(+ retry=TRANSPORT_RETRY,+ redact_values=tuple(+ value+ for value in (config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token)+ if value+ ),+ )++ def close(self) -> None:+ self.session.close()++ @retry(+ retry=retry_if_exception_type(AwsSagemakerThrottledError),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def request(self, operation: str, payload: dict[str, Any]) -> dict[str, Any]:+ body = json.dumps(payload).encode("utf-8")+ request = AWSRequest(+ method="POST",+ url=self.url,+ data=body,+ headers={"Content-Type": "application/x-amz-json-1.1", "X-Amz-Target": f"{self.target_prefix}.{operation}"},+ )+ self.signer.add_auth(request)+ response = self.session.post(+ self.url, data=body, headers=dict(request.headers), timeout=60, allow_redirects=False+ )+ if response.status_code >= 300:+ raise error_for_response(response)+ parsed = response.json()+ if not isinstance(parsed, dict):+ raise ValueError("AWS SageMaker returned an invalid response.")+ return parsed+++def normalize_row(item: dict[str, Any]) -> dict[str, Any]:+ row: dict[str, Any] = {}+ for key, value in item.items():+ if key == "ResponseMetadata":+ continue+ if key in _TIMESTAMP_FIELDS and isinstance(value, int | float) and not isinstance(value, bool):+ value = dt.datetime.fromtimestamp(value, tz=dt.UTC)+ row[_CAMEL_BOUNDARY.sub("_", key).lower()] = value+ return row+++def timestamp(value: dt.datetime | str | int | float | None) -> float | None:+ if value is None:+ return None+ if isinstance(value, int | float):+ return float(value)+ parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00")) if isinstance(value, str) else value+ return (parsed if parsed.tzinfo else parsed.replace(tzinfo=dt.UTC)).timestamp()+++def get_rows(+ config: AwsSagemakerSourceConfig,+ endpoint: str,+ api_version: str,+ manager: ResumableSourceManager[AwsSagemakerResumeConfig],+ incremental: bool,+ last_value: dt.datetime | str | int | float | None,+) -> Iterator[list[dict[str, Any]]]:+ settings = schema_for_resource(ENDPOINTS, endpoint)+ state = manager.load_state()+ if state and state.complete:+ return+ watermark = state.watermark if state else timestamp(last_value) if incremental and settings.incremental else None+ token = state.next_token if state else None+ client = AwsSagemakerClient(config, api_version)+ try:+ while True:+ payload: dict[str, Any] = {"MaxResults": MAX_RESULTS, "SortBy": "CreationTime", "SortOrder": "Ascending"}+ if watermark is not None and incremental and settings.incremental:+ payload["CreationTimeAfter"] = watermark+ if token:+ payload["NextToken"] = token+ page = client.request(settings.list_operation, payload)+ next_token = page.get("NextToken") or None+ if next_token == token and next_token is not None:+ raise ValueError("AWS SageMaker returned a repeated pagination token.")+ rows = [+ normalize_row(+ client.request(settings.describe_operation, {settings.name_field: item[settings.name_field]})+ )+ for item in page[settings.result_key]+ ]+ for row in rows:+ if not row.get(settings.primary_key):+ raise ValueError("AWS SageMaker returned a resource without its ARN.")+ manager.save_state(+ AwsSagemakerResumeConfig(next_token=next_token, watermark=watermark, complete=next_token is None)+ )+ if rows:+ yield rows+ manager.safe_point()+ if next_token is None:+ break+ token = next_token+ finally:+ client.close()+++def validate_credentials(+ config: AwsSagemakerSourceConfig, schema_name: str | None, api_version: str+) -> tuple[bool, str | None]:+ if schema_name is not None and schema_name not in ENDPOINTS:+ return False, f"Unknown SageMaker table: {schema_name}"+ settings = ENDPOINTS[schema_name or "models"]+ try:+ client = AwsSagemakerClient(config, api_version)+ except ValueError as error:+ return False, str(error)+ try:+ page = client.request(settings.list_operation, {"MaxResults": 1})+ if schema_name and page.get(settings.result_key):+ item = page[settings.result_key][0]+ client.request(settings.describe_operation, {settings.name_field: item[settings.name_field]})+ except AwsSagemakerError as error:+ if error.code in {"AccessDenied", "AccessDeniedException"}:+ if schema_name is None:+ return True, None+ return (+ False,+ f"Grant sagemaker:{settings.list_operation} and sagemaker:{settings.describe_operation} for this table.",+ )+ for code, message in ERROR_MESSAGES.items():+ if error.code.startswith(code):+ return False, message+ raise+ except requests.RequestException:+ return False, "Could not reach AWS SageMaker. Check the region and try again."+ finally:+ client.close()+ return True, None+++def aws_sagemaker_source(+ config: AwsSagemakerSourceConfig,+ endpoint: str,+ api_version: str,+ manager: ResumableSourceManager[AwsSagemakerResumeConfig],+ incremental: bool,+ last_value: dt.datetime | str | int | float | None,+) -> SourceResponse:+ settings = schema_for_resource(ENDPOINTS, endpoint)+ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(config, endpoint, api_version, manager, incremental, last_value),+ primary_keys=[settings.primary_key],+ partition_keys=["creation_time"],+ partition_mode="datetime",+ partition_format="month",+ sort_mode="asc" if settings.incremental else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/canonical_descriptions.pynew file mode 100644index 000000000000..5fb2c6d8ede4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/canonical_descriptions.py@@ -0,0 +1,64 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "training_jobs": {+ "description": "SageMaker training jobs, including their status, resource configuration, and final metrics.",+ "docs_url": "https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTrainingJob.html",+ "columns": {+ "training_job_arn": "The Amazon Resource Name of the training job.",+ "training_job_name": "The name of the training job.",+ "training_job_status": "The status of the training job.",+ "creation_time": "The time AWS created the training job.",+ "last_modified_time": "The time AWS last modified the training job.",+ "training_start_time": "The time training started.",+ "training_end_time": "The time training ended.",+ "training_time_in_seconds": "The duration of model training, in seconds.",+ "billable_time_in_seconds": "The training duration used for billing, in seconds.",+ "resource_config": "The compute instances and storage configured for training.",+ "final_metric_data_list": "The final values of metrics from the training job.",+ },+ },+ "processing_jobs": {+ "description": "SageMaker processing jobs, including their status, compute resources, and input and output settings.",+ "docs_url": "https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeProcessingJob.html",+ "columns": {+ "processing_job_arn": "The Amazon Resource Name of the processing job.",+ "processing_job_name": "The name of the processing job.",+ "processing_job_status": "The status of the processing job.",+ "creation_time": "The time AWS created the processing job.",+ "last_modified_time": "The time AWS last modified the processing job.",+ "processing_start_time": "The time processing started.",+ "processing_end_time": "The time processing ended.",+ "processing_resources": "The compute resources configured for processing.",+ "failure_reason": "The reason the processing job failed.",+ },+ },+ "endpoints": {+ "description": "SageMaker inference endpoints, including their status and deployed production variants.",+ "docs_url": "https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeEndpoint.html",+ "columns": {+ "endpoint_arn": "The Amazon Resource Name of the endpoint.",+ "endpoint_name": "The name of the endpoint.",+ "endpoint_config_name": "The endpoint configuration used for deployment.",+ "endpoint_status": "The status of the endpoint.",+ "creation_time": "The time AWS created the endpoint.",+ "last_modified_time": "The time AWS last modified the endpoint.",+ "production_variants": "The production variants deployed on the endpoint, including instance counts and weights.",+ },+ },+ "models": {+ "description": "SageMaker models, including container definitions, execution roles, and network settings.",+ "docs_url": "https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeModel.html",+ "columns": {+ "model_arn": "The Amazon Resource Name of the model.",+ "model_name": "The name of the model.",+ "creation_time": "The time AWS created the model.",+ "primary_container": "The primary container used for inference.",+ "containers": "The containers in the inference pipeline.",+ "execution_role_arn": "The IAM role SageMaker uses to access AWS resources for the model.",+ "vpc_config": "The VPC subnets and security groups used by the model.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/settings.pynew file mode 100644index 000000000000..d4d2c4421448--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/settings.py@@ -0,0 +1,60 @@+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++SAGEMAKER_API_VERSION = "2017-07-24"+TARGET_PREFIXES = {SAGEMAKER_API_VERSION: "SageMaker"}+MAX_RESULTS = 100+++@frozen+class SageMakerEndpoint:+ list_operation: str+ result_key: str+ describe_operation: str+ name_field: str+ primary_key: str+ incremental: bool = False+++ENDPOINTS: dict[str, SageMakerEndpoint] = {+ "training_jobs": SageMakerEndpoint(+ list_operation="ListTrainingJobs",+ result_key="TrainingJobSummaries",+ describe_operation="DescribeTrainingJob",+ name_field="TrainingJobName",+ primary_key="training_job_arn",+ ),+ "processing_jobs": SageMakerEndpoint(+ list_operation="ListProcessingJobs",+ result_key="ProcessingJobSummaries",+ describe_operation="DescribeProcessingJob",+ name_field="ProcessingJobName",+ primary_key="processing_job_arn",+ ),+ "endpoints": SageMakerEndpoint(+ list_operation="ListEndpoints",+ result_key="Endpoints",+ describe_operation="DescribeEndpoint",+ name_field="EndpointName",+ primary_key="endpoint_arn",+ ),+ "models": SageMakerEndpoint(+ list_operation="ListModels",+ result_key="Models",+ describe_operation="DescribeModel",+ name_field="ModelName",+ primary_key="model_arn",+ incremental=True,+ ),+}++# Mutable resources cannot sort by modification time, so creation cursors would miss later changes.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {"models": [incremental_field("creation_time")]}+ENDPOINT_DESCRIPTIONS = {+ "training_jobs": "Training jobs with status, resource settings, metrics, and billable duration.",+ "processing_jobs": "Processing jobs with status, input and output settings, and compute resources.",+ "endpoints": "Inference endpoints with status, deployment settings, and production variants.",+ "models": "Models with container settings, execution roles, and creation times.",+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/source.pyindex 790208a23a18..9a169229b75a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/source.py@@ -1,8 +1,38 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_sagemaker.aws_sagemaker import (+ ERROR_MESSAGES,+ AwsSagemakerResumeConfig,+ aws_sagemaker_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_sagemaker.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_sagemaker.settings import (+ ENDPOINT_DESCRIPTIONS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SAGEMAKER_API_VERSION,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awssagemaker import (AwsSagemakerSourceConfig,)@@ -10,18 +40,114 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AwsSagemakerSource(SimpleSource[AwsSagemakerSourceConfig]):+class AwsSagemakerSource(ResumableSource[AwsSagemakerSourceConfig, AwsSagemakerResumeConfig]):+ lists_tables_without_credentials = True+ supported_versions = (SAGEMAKER_API_VERSION,)+ default_version = SAGEMAKER_API_VERSION+ api_docs_url = "https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_Operations.html"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AWSSAGEMAKER+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {f"AWS SageMaker request failed: {code}": message for code, message in ERROR_MESSAGES.items()}++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AwsSagemakerSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, descriptions=ENDPOINT_DESCRIPTIONS)++ def validate_credentials(+ self,+ config: AwsSagemakerSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_credentials(config, schema_name, self.resolve_api_version(api_version))++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AwsSagemakerResumeConfig]:+ return ResumableSourceManager(inputs, AwsSagemakerResumeConfig)++ def source_for_pipeline(+ self,+ config: AwsSagemakerSourceConfig,+ resumable_source_manager: ResumableSourceManager[AwsSagemakerResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return aws_sagemaker_source(+ config,+ inputs.schema_name,+ self.resolve_api_version(inputs.api_version),+ resumable_source_manager,+ inputs.should_use_incremental_field,+ inputs.db_incremental_field_last_value,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.AWSSAGEMAKER,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="Amazon Web Services (Amazon SageMaker)",+ label="AWS SageMaker",+ caption=(+ "Sync SageMaker resources from one AWS region. "+ "Grant these IAM permissions for the tables you select: "+ "`sagemaker:ListTrainingJobs`, `sagemaker:DescribeTrainingJob`, "+ "`sagemaker:ListProcessingJobs`, `sagemaker:DescribeProcessingJob`, "+ "`sagemaker:ListEndpoints`, `sagemaker:DescribeEndpoint`, "+ "`sagemaker:ListModels`, and `sagemaker:DescribeModel`. "+ "Jobs and endpoints use full refresh to capture status changes. "+ "Models also support incremental sync by creation time."+ ),iconPath="/static/services/aws_sagemaker.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="aws_access_key_id",+ label="AWS access key ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="AKIA...",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="aws_secret_access_key",+ label="AWS secret access key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="aws_session_token",+ label="AWS session token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="Only needed for temporary credentials",+ secret=True,+ caption="Temporary credentials require a session token. Scheduled syncs fail when the token expires.",+ ),+ SourceFieldInputConfig(+ name="region",+ label="AWS region",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="us-east-1",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/tests/test_aws_sagemaker.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/tests/test_aws_sagemaker.pynew file mode 100644index 000000000000..1e74441042be--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/tests/test_aws_sagemaker.py@@ -0,0 +1,333 @@+import json+import datetime as dt+from collections.abc import Iterable, Iterator+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++import requests+from tenacity import wait_none++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_sagemaker.aws_sagemaker import (+ TRANSPORT_RETRY,+ AwsSagemakerClient,+ AwsSagemakerError,+ AwsSagemakerResumeConfig,+ AwsSagemakerThrottledError,+ aws_sagemaker_source,+ error_for_response,+ get_rows,+ validate_credentials,+)+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 UnknownResourceError+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awssagemaker import (+ AwsSagemakerSourceConfig,+)+++def config() -> AwsSagemakerSourceConfig:+ return AwsSagemakerSourceConfig(+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key="fake-secret",+ aws_session_token="fake-session",+ region="eu-west-1",+ )+++def transport() -> Iterator[MagicMock]:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.aws_sagemaker.aws_sagemaker.make_tracked_session"+ ) as factory:+ yield factory.return_value+++def response(body: dict[str, object], status: int = 200, header: str | None = None) -> requests.Response:+ result = requests.Response()+ result.status_code = status+ result._content = json.dumps(body).encode()+ if header:+ result.headers["x-amzn-ErrorType"] = header+ return result+++def manager(state: AwsSagemakerResumeConfig | None = None) -> MagicMock:+ result = MagicMock(spec=ResumableSourceManager)+ result.load_state.return_value = state+ return result+++ "region,host",+ [+ ("eu-west-1", "api.sagemaker.eu-west-1.amazonaws.com"),+ ("cn-north-1", "api.sagemaker.cn-north-1.amazonaws.com.cn"),+ ("us-gov-west-1", "api.sagemaker.us-gov-west-1.amazonaws.com"),+ ],+)[email protected]("session_token", [None, "fake-session"])+def test_signed_json_request(+ config: AwsSagemakerSourceConfig, transport: MagicMock, region: str, host: str, session_token: str | None+) -> None:+ config.region = region+ config.aws_session_token = session_token+ transport.post.return_value = response({"Models": []})+ client = AwsSagemakerClient(config, "2017-07-24")+ assert client.request("ListModels", {"MaxResults": 1}) == {"Models": []}+ args, kwargs = transport.post.call_args+ assert args == (f"https://{host}/",)+ assert json.loads(kwargs["data"]) == {"MaxResults": 1}+ headers = kwargs["headers"]+ assert headers["Content-Type"] == "application/x-amz-json-1.1"+ assert headers["X-Amz-Target"] == "SageMaker.ListModels"+ assert "AWS4-HMAC-SHA256 Credential=AKIAEXAMPLE/" in headers["Authorization"]+ assert f"/{region}/sagemaker/aws4_request" in headers["Authorization"]+ assert headers.get("X-Amz-Security-Token") == session_token+ assert headers["X-Amz-Date"]+ assert kwargs["allow_redirects"] is False+ assert kwargs["timeout"] == 60+++ "endpoint,list_operation,result_key,describe_operation,name_field,arn_field,column",+ [+ (+ "training_jobs",+ "ListTrainingJobs",+ "TrainingJobSummaries",+ "DescribeTrainingJob",+ "TrainingJobName",+ "TrainingJobArn",+ "training_job_arn",+ ),+ (+ "processing_jobs",+ "ListProcessingJobs",+ "ProcessingJobSummaries",+ "DescribeProcessingJob",+ "ProcessingJobName",+ "ProcessingJobArn",+ "processing_job_arn",+ ),+ ("endpoints", "ListEndpoints", "Endpoints", "DescribeEndpoint", "EndpointName", "EndpointArn", "endpoint_arn"),+ ("models", "ListModels", "Models", "DescribeModel", "ModelName", "ModelArn", "model_arn"),+ ],+)+def test_pagination_describes_rows_and_stages_only_complete_pages(+ config: AwsSagemakerSourceConfig,+ transport: MagicMock,+ endpoint: str,+ list_operation: str,+ result_key: str,+ describe_operation: str,+ name_field: str,+ arn_field: str,+ column: str,+) -> None:+ transport.post.side_effect = [+ response({result_key: [{name_field: "example"}], "NextToken": "second"}),+ response(+ {+ arn_field: "arn:aws:sagemaker:eu-west-1:123456789012:example/item",+ "CreationTime": 1704067200,+ "ResourceConfig": {"InstanceCount": 2},+ }+ ),+ response({result_key: [], "NextToken": "last"}),+ response({result_key: [{name_field: "other"}]}),+ response({arn_field: "arn:aws:sagemaker:eu-west-1:123456789012:example/other", "CreationTime": 1704153600}),+ ]+ resume = manager()+ resource = aws_sagemaker_source(config, endpoint, "2017-07-24", resume, False, 1700000000)+ rows = [row for batch in cast(Iterable[Any], resource.items()) for row in batch]+ assert len(rows) == 2+ assert rows[0]["creation_time"] == dt.datetime(2024, 1, 1, tzinfo=dt.UTC)+ assert rows[0]["resource_config"] == {"InstanceCount": 2}+ assert rows[0][column].endswith("example/item")+ assert resource.primary_keys == [column]+ calls = transport.post.call_args_list+ assert [call.kwargs["headers"]["X-Amz-Target"] for call in calls] == [+ f"SageMaker.{list_operation}",+ f"SageMaker.{describe_operation}",+ f"SageMaker.{list_operation}",+ f"SageMaker.{list_operation}",+ f"SageMaker.{describe_operation}",+ ]+ assert json.loads(calls[0].kwargs["data"]) == {+ "MaxResults": 100,+ "SortBy": "CreationTime",+ "SortOrder": "Ascending",+ }+ assert json.loads(calls[1].kwargs["data"]) == {name_field: "example"}+ assert json.loads(calls[2].kwargs["data"])["NextToken"] == "second"+ assert json.loads(calls[3].kwargs["data"])["NextToken"] == "last"+ assert [call.args[0] for call in resume.save_state.call_args_list] == [+ AwsSagemakerResumeConfig(next_token="second"),+ AwsSagemakerResumeConfig(next_token="last"),+ AwsSagemakerResumeConfig(complete=True),+ ]+ assert resume.safe_point.call_count == 3+ transport.close.assert_called_once()++[email protected]("incremental", [True, False])+ "last_value",+ [1704067200, 1704067200.0, "2024-01-01T00:00:00Z", dt.datetime(2024, 1, 1), dt.datetime(2024, 1, 1, tzinfo=dt.UTC)],+)+def test_incremental_filter_and_full_refresh(+ config: AwsSagemakerSourceConfig,+ transport: MagicMock,+ incremental: bool,+ last_value: dt.datetime | str | int | float | None,+) -> None:+ transport.post.side_effect = [response({"Models": [], "NextToken": "next"}), response({"Models": []})]+ resource = aws_sagemaker_source(config, "models", "2017-07-24", manager(), incremental, last_value)+ assert list(cast(Iterable[Any], resource.items())) == []+ assert resource.sort_mode == "asc"+ for call in transport.post.call_args_list:+ payload = json.loads(call.kwargs["data"])+ assert payload.get("CreationTimeAfter") == (1704067200.0 if incremental else None)+ assert payload["SortOrder"] == "Ascending"+++def test_resume_preserves_original_filter(config: AwsSagemakerSourceConfig, transport: MagicMock) -> None:+ resume = manager(AwsSagemakerResumeConfig(next_token="resume", watermark=1704067200.0))+ transport.post.return_value = response({"Models": []})+ assert list(get_rows(config, "models", "2017-07-24", resume, True, 1705000000)) == []+ payload = json.loads(transport.post.call_args.kwargs["data"])+ assert payload["NextToken"] == "resume"+ assert payload["CreationTimeAfter"] == 1704067200.0+++def test_complete_resume_makes_no_request(config: AwsSagemakerSourceConfig, transport: MagicMock) -> None:+ assert (+ list(get_rows(config, "models", "2017-07-24", manager(AwsSagemakerResumeConfig(complete=True)), True, None))+ == []+ )+ transport.post.assert_not_called()++[email protected]("failure", ["describe", "repeated_token", "missing_arn"])+def test_failed_page_does_not_advance_resume(+ config: AwsSagemakerSourceConfig, transport: MagicMock, failure: str+) -> None:+ resume = manager(AwsSagemakerResumeConfig(next_token="current"))+ if failure == "repeated_token":+ transport.post.return_value = response({"Models": [], "NextToken": "current"})+ else:+ transport.post.side_effect = [+ response({"Models": [{"ModelName": "example"}], "NextToken": "next"}),+ response({"__type": "AccessDeniedException"}, 400)+ if failure == "describe"+ else response({"ModelName": "example"}),+ ]+ with pytest.raises((AwsSagemakerError, ValueError)):+ list(get_rows(config, "models", "2017-07-24", resume, False, None))+ resume.save_state.assert_not_called()+ transport.close.assert_called_once()+++ "status,code,throttled",+ [+ (400, "ThrottlingException", True),+ (429, "ThrottlingException", False),+ (503, "ServiceUnavailable", False),+ (400, "AccessDeniedException", False),+ (400, "UnrecognizedClientException", False),+ ],+)[email protected]("in_header", [True, False])+def test_error_parsing_and_retry_classification(status: int, code: str, throttled: bool, in_header: bool) -> None:+ result = response({"__type": f"com.amazonaws.sagemaker#{code}"}, status, f"{code}:detail" if in_header else None)+ error = error_for_response(result)+ assert error.code == code+ assert isinstance(error, AwsSagemakerThrottledError) == throttled+ assert TRANSPORT_RETRY.is_retry("POST", status) == (status in {429, 503})+++def test_body_throttle_retries_and_resigns(config: AwsSagemakerSourceConfig, transport: MagicMock) -> None:+ transport.post.side_effect = [response({"__type": "ThrottlingException"}, 400), response({"Models": []})]+ client = AwsSagemakerClient(config, "2017-07-24")+ request = cast(Any, client.request).retry_with(wait=wait_none())+ assert request(client, "ListModels", {"MaxResults": 1}) == {"Models": []}+ assert transport.post.call_count == 2++[email protected]("schema_name,allowed", [(None, True), ("models", False)])[email protected]("code", ["AccessDenied", "AccessDeniedException"])+def test_missing_permission_is_accepted_only_at_creation(+ config: AwsSagemakerSourceConfig, transport: MagicMock, schema_name: str | None, allowed: bool, code: str+) -> None:+ transport.post.return_value = response({"__type": code}, 400)+ valid, message = validate_credentials(config, schema_name, "2017-07-24")+ assert valid is allowed+ if allowed:+ assert message is None+ else:+ assert message and "sagemaker:ListModels" in message and "sagemaker:DescribeModel" in message++[email protected]("schema_name,requests_count", [(None, 1), ("models", 2)])+def test_validation_probes_describe_only_for_selected_table(+ config: AwsSagemakerSourceConfig, transport: MagicMock, schema_name: str | None, requests_count: int+) -> None:+ transport.post.side_effect = [+ response({"Models": [{"ModelName": "example"}]}),+ response({"ModelArn": "example-arn"}),+ ]+ assert validate_credentials(config, schema_name, "2017-07-24") == (True, None)+ assert transport.post.call_count == requests_count+ assert json.loads(transport.post.call_args_list[0].kwargs["data"]) == {"MaxResults": 1}+++ "field,value,message",+ [+ ("region", "us-east-1.example.com/", "Enter an AWS region"),+ ("aws_access_key_id", "", "Enter both"),+ ("aws_secret_access_key", "", "Enter both"),+ ],+)+def test_bad_config_never_sends_credentials(+ config: AwsSagemakerSourceConfig, transport: MagicMock, field: str, value: str, message: str+) -> None:+ setattr(config, field, value)+ valid, error = validate_credentials(config, None, "2017-07-24")+ assert valid is False and error and message in error+ transport.post.assert_not_called()+++def test_unknown_table_and_version_are_rejected(config: AwsSagemakerSourceConfig, transport: MagicMock) -> None:+ assert validate_credentials(config, "unknown", "2017-07-24") == (False, "Unknown SageMaker table: unknown")+ assert validate_credentials(config, None, "invalid") == (False, "Unsupported SageMaker API version: invalid")+ with pytest.raises(UnknownResourceError):+ aws_sagemaker_source(config, "unknown", "2017-07-24", manager(), False, None)+ transport.post.assert_not_called()+++def test_transient_validation_error_propagates(config: AwsSagemakerSourceConfig, transport: MagicMock) -> None:+ transport.post.return_value = response({"__type": "ServiceUnavailable"}, 503)+ with pytest.raises(AwsSagemakerError, match="ServiceUnavailable"):+ validate_credentials(config, "models", "2017-07-24")+ transport.close.assert_called_once()+++def test_non_object_success_response_is_rejected(config: AwsSagemakerSourceConfig, transport: MagicMock) -> None:+ result = response({})+ result._content = b"[]"+ transport.post.return_value = result+ with pytest.raises(ValueError, match="invalid response"):+ AwsSagemakerClient(config, "2017-07-24").request("ListModels", {})+++def test_non_json_error_does_not_leak_body(config: AwsSagemakerSourceConfig, transport: MagicMock) -> None:+ result = response({}, 502)+ result._content = b"upstream error with sensitive details"+ transport.post.return_value = result+ with pytest.raises(AwsSagemakerError, match="^AWS SageMaker request failed: HTTP 502$"):+ AwsSagemakerClient(config, "2017-07-24").request("ListModels", {})diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/tests/test_aws_sagemaker_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/tests/test_aws_sagemaker_source.pynew file mode 100644index 000000000000..42dae4a44456--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_sagemaker/tests/test_aws_sagemaker_source.py@@ -0,0 +1,52 @@+import json++import pytest+from unittest.mock import patch++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_sagemaker.aws_sagemaker import (+ error_for_response,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_sagemaker.source import AwsSagemakerSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awssagemaker import (+ AwsSagemakerSourceConfig,+)+++ "code,hint",+ [+ ("UnrecognizedClientException", "credentials"),+ ("InvalidClientTokenId", "active access key"),+ ("InvalidSignatureException", "signature"),+ ("SignatureDoesNotMatch", "signature"),+ ("ExpiredTokenException", "expired"),+ ("SubscriptionRequiredException", "Enable SageMaker"),+ ("OptInRequired", "Enable SageMaker"),+ ("AccessDeniedException", "permissions"),+ ],+)+def test_aws_errors_have_actionable_validation_and_sync_messages(code: str, hint: str) -> None:+ response = requests.Response()+ response.status_code = 400+ response._content = json.dumps({"__type": f"com.amazonaws.sagemaker#{code}"}).encode()+ config = AwsSagemakerSourceConfig(+ aws_access_key_id="AKIAEXAMPLE", aws_secret_access_key="fake-secret", region="us-east-1"+ )+ source = AwsSagemakerSource()+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.aws_sagemaker.aws_sagemaker.make_tracked_session"+ ) as factory:+ factory.return_value.post.return_value = response+ valid, message = source.validate_credentials(config, 1, schema_name="models")+ assert valid is False+ assert message+ if code == "AccessDeniedException":+ assert "sagemaker:DescribeModel" in message+ else:+ assert hint in message+ error = str(error_for_response(response))+ matches = [message for pattern, message in source.get_non_retryable_errors().items() if pattern in error]+ assert len(matches) == 1+ assert matches[0] and hint in matches[0]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awssagemaker.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awssagemaker.pyindex bb3d55e0dc72..17ca038313c6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awssagemaker.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awssagemaker.py@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AwsSagemakerSourceConfig(config.Config):- pass+ aws_access_key_id: str+ aws_secret_access_key: str+ region: str+ aws_session_token: str | None = None