: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): add AWS Cost Anomaly Detection import source (#84472)
Tom Owers8973d440aa46
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/aws_cost_anomaly_detection.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/aws_cost_anomaly_detection.pynew file mode 100644index 000000000000..a98cab18f86f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/aws_cost_anomaly_detection.py@@ -0,0 +1,449 @@+import re+import json+import datetime as dt+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++import requests+from botocore.auth import SigV4Auth+from botocore.awsrequest import AWSRequest+from botocore.credentials import Credentials+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.sources.aws_cost_anomaly_detection.settings import (+ ANOMALY_RETENTION_DAYS,+ AWS_COST_ANOMALY_DETECTION_ENDPOINTS,+ CE_CONTENT_TYPE,+ CE_ENDPOINT_URL,+ CE_SIGNING_NAME,+ CE_SIGNING_REGION,+ CE_TARGET_PREFIX,+ ONGOING_ANOMALY_LOOKBACK_DAYS,+ REQUEST_TIMEOUT_SECONDS,+ AnomalyDetectionEndpointConfig,+)+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.typings import SourceResponse++MAX_THROTTLE_ATTEMPTS = 6++# Cost Explorer is a POST-only JSON RPC, and the tracked session's default policy only retries+# idempotent verbs — so opt POST in explicitly for the transport-level statuses.+TRANSPORT_RETRY = BoundedRetry(+ total=3,+ backoff_factor=1,+ status_forcelist=(429, 500, 502, 503, 504),+ allowed_methods=frozenset(["POST"]),+ raise_on_status=False,+)++# AWS returns these as HTTP 400 with the code in the body, so the transport can't see them.+THROTTLING_ERROR_CODES = frozenset(+ {+ "LimitExceededException",+ "RequestLimitExceeded",+ "ThrottlingException",+ "TooManyRequestsException",+ }+)++# Codes that mean the key itself is bad, as opposed to a valid key missing an IAM permission.+CREDENTIAL_ERROR_CODES = (+ "UnrecognizedClientException",+ "InvalidClientTokenId",+ "SignatureDoesNotMatch",+ "InvalidSignatureException",+ "ExpiredTokenException",+)++# Cost Explorer serves nothing until it has been enabled once in the console (it can't be enabled+# through the API) and it takes up to 24 hours to prepare data. That arrives as a data-unavailable+# error rather than an empty list, so it gets its own message instead of reading as a bad key.+DATA_UNAVAILABLE_ERROR_CODES = ("DataUnavailableException", "BillExpirationException")++ENABLEMENT_MESSAGE = (+ "AWS has no Cost Explorer data for this account yet. Enable Cost Explorer in the AWS console, "+ "then try again in up to 24 hours once AWS has prepared the data."+)++_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")++_IAM_ACTION_PATTERN = re.compile(r"ce:[A-Za-z0-9]+")+++class AwsCostAnomalyDetectionError(Exception):+ pass+++class AwsCostAnomalyDetectionThrottledError(AwsCostAnomalyDetectionError):+ pass++[email protected](frozen=True)+class AwsCostAnomalyDetectionResumeConfig:+ """Where a previous attempt stopped: the date the window started on, plus its page token."""++ date_interval_start: Optional[str] = None+ next_page_token: Optional[str] = None+++def _snake(name: str) -> str:+ """`AnomalyStartDate` -> `anomaly_start_date`, `TotalImpactPercentage` -> `total_impact_percentage`."""+ return _CAMEL_BOUNDARY.sub("_", name).lower()+++def _parse_date(value: Any) -> Any:+ """Cost Explorer dates are `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM:SSZ`; keep anything else untouched."""+ if not isinstance(value, str) or not value:+ return value+ try:+ parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return value+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=dt.UTC)+++def coerce_date(value: Any) -> Optional[dt.date]:+ if isinstance(value, dt.datetime):+ return value.date()+ if isinstance(value, dt.date):+ return value+ if isinstance(value, str) and value:+ try:+ return dt.datetime.fromisoformat(value.replace("Z", "+00:00")).date()+ except ValueError:+ return None+ return None+++def _flatten(prefix: str, obj: dict[str, Any], raw_keys: frozenset[str]) -> dict[str, Any]:+ flattened: dict[str, Any] = {}+ for key, value in obj.items():+ column = f"{prefix}_{_snake(key)}" if prefix else _snake(key)+ if key in raw_keys:+ flattened[column] = value+ elif isinstance(value, dict):+ flattened.update(_flatten(column, value, raw_keys))+ elif isinstance(value, list):+ flattened[column] = [_flatten("", item, raw_keys) if isinstance(item, dict) else item for item in value]+ else:+ flattened[column] = value+ return flattened+++def normalize_row(endpoint_config: AnomalyDetectionEndpointConfig, obj: dict[str, Any]) -> dict[str, Any]:+ """Flatten nested structures into snake_case columns and parse the date members."""+ row = _flatten("", obj, endpoint_config.raw_keys)+ for column in endpoint_config.date_columns:+ if column in row:+ row[column] = _parse_date(row[column])+ return row+++def resolve_date_interval_start(+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ today: dt.date,+) -> dt.date:+ """The earliest `AnomalyEndDate` this run asks AWS for.++ Never earlier than the 90-day retention floor, and an incremental run rewinds behind the+ stored watermark so anomalies AWS is still updating get re-read and re-merged.+ """+ floor = today - dt.timedelta(days=ANOMALY_RETENTION_DAYS)+ if not should_use_incremental_field:+ return floor++ watermark = coerce_date(db_incremental_field_last_value)+ if watermark is None:+ return floor+ return max(floor, min(watermark - dt.timedelta(days=ONGOING_ANOMALY_LOOKBACK_DAYS), today))+++def build_payload(+ endpoint_config: AnomalyDetectionEndpointConfig,+ date_interval_start: Optional[dt.date],+ page_token: Optional[str],+) -> dict[str, Any]:+ payload: dict[str, Any] = {"MaxResults": endpoint_config.page_size}+ if endpoint_config.supports_date_interval and date_interval_start is not None:+ # `EndDate` is left off deliberately: an anomaly that is still open has its `AnomalyEndDate`+ # pushed forward by AWS, and an open-ended window can't drop it.+ payload["DateInterval"] = {"StartDate": date_interval_start.isoformat()}+ if page_token:+ payload["NextPageToken"] = page_token+ return payload+++def _error_code(response: requests.Response) -> str:+ header = response.headers.get("x-amzn-ErrorType") or ""+ if header:+ return header.split(":")[0].split("#")[-1]+ try:+ body = response.json()+ except ValueError:+ return f"HTTP {response.status_code}"+ raw = body.get("__type") or body.get("code") or f"HTTP {response.status_code}"+ return str(raw).split("#")[-1]+++def _error_message(response: requests.Response) -> str:+ try:+ body = response.json()+ except ValueError:+ return response.text[:500]+ message = body.get("message") or body.get("Message") or ""+ return str(message)[:500]+++def error_for_response(response: requests.Response) -> AwsCostAnomalyDetectionError:+ code = _error_code(response)+ text = f"AWS Cost Anomaly Detection request failed: {code} - {_error_message(response)}"+ # 429/5xx are already retried by the tracked transport; only the app-level throttling codes+ # (returned as HTTP 400) need a second, bounded retry here.+ if code in THROTTLING_ERROR_CODES:+ return AwsCostAnomalyDetectionThrottledError(text)+ return AwsCostAnomalyDetectionError(text)+++def make_session(secret_access_key: str, session_token: Optional[str]) -> requests.Session:+ redact = tuple(value for value in (secret_access_key, session_token) if value)+ return make_tracked_session(retry=TRANSPORT_RETRY, redact_values=redact)+++@retry(+ retry=retry_if_exception_type(AwsCostAnomalyDetectionThrottledError),+ stop=stop_after_attempt(MAX_THROTTLE_ATTEMPTS),+ wait=wait_exponential_jitter(initial=5, max=120),+ reraise=True,+)+def send_operation(+ session: requests.Session,+ credentials: Credentials,+ operation: str,+ payload: dict[str, Any],+) -> dict[str, Any]:+ """Sign one Cost Explorer JSON-RPC call with SigV4 and send it over the tracked session."""+ body = json.dumps(payload).encode()+ aws_request = AWSRequest(+ method="POST",+ url=CE_ENDPOINT_URL,+ data=body,+ headers={+ "Content-Type": CE_CONTENT_TYPE,+ "X-Amz-Target": f"{CE_TARGET_PREFIX}.{operation}",+ },+ )+ SigV4Auth(credentials, CE_SIGNING_NAME, CE_SIGNING_REGION).add_auth(aws_request)++ response = session.post(+ CE_ENDPOINT_URL,+ data=body,+ headers=dict(aws_request.headers.items()),+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code >= 400:+ raise error_for_response(response)++ return response.json()+++def make_credentials(+ aws_access_key_id: str, aws_secret_access_key: str, aws_session_token: Optional[str]+) -> Credentials:+ return Credentials(aws_access_key_id, aws_secret_access_key, aws_session_token or None)+++def get_rows(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[AwsCostAnomalyDetectionResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ endpoint_config = AWS_COST_ANOMALY_DETECTION_ENDPOINTS[endpoint]+ session = make_session(aws_secret_access_key, aws_session_token)+ credentials = make_credentials(aws_access_key_id, aws_secret_access_key, aws_session_token)++ date_interval_start: Optional[dt.date] = None+ if endpoint_config.supports_date_interval:+ date_interval_start = resolve_date_interval_start(+ should_use_incremental_field, db_incremental_field_last_value, dt.datetime.now(dt.UTC).date()+ )+ window_start = date_interval_start.isoformat() if date_interval_start is not None else None++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ # A token only belongs to the window it was issued for, so a saved window that no longer+ # matches this run's window restarts the walk.+ page_token = resume.next_page_token if resume is not None and resume.date_interval_start == window_start else None+ resumed_token = page_token is not None+ if resumed_token:+ logger.debug(f"Resuming AWS Cost Anomaly Detection sync from a saved page token. endpoint={endpoint}")++ while True:+ try:+ body = send_operation(+ session,+ credentials,+ endpoint_config.operation,+ build_payload(endpoint_config, date_interval_start, page_token),+ )+ except AwsCostAnomalyDetectionError as error:+ # A token saved by a previous attempt can expire; restart the walk instead of failing+ # the job. Merge on the primary key absorbs the re-read rows.+ if resumed_token and "InvalidNextTokenException" in str(error):+ logger.debug(f"Saved page token no longer valid; restarting. endpoint={endpoint}")+ page_token = None+ resumed_token = False+ resumable_source_manager.clear_state()+ continue+ raise+ resumed_token = False++ rows = [normalize_row(endpoint_config, item) for item in body.get(endpoint_config.result_key) or []]+ if rows:+ yield rows++ page_token = body.get("NextPageToken")+ # Saved after yielding: a crash re-yields the last page, which merges away on the primary+ # key, rather than skipping it.+ resumable_source_manager.save_state(+ AwsCostAnomalyDetectionResumeConfig(date_interval_start=window_start, next_page_token=page_token)+ )+ if not page_token:+ break++ resumable_source_manager.clear_state()+++def _permission_reason(error: AwsCostAnomalyDetectionError) -> Optional[str]:+ text = str(error)+ if "AccessDeniedException" in text:+ match = _IAM_ACTION_PATTERN.search(text)+ if match:+ return f"Missing IAM permission {match.group(0)}"+ return "The connected IAM user or role is not allowed to read this table"+ if any(code in text for code in DATA_UNAVAILABLE_ERROR_CODES):+ return ENABLEMENT_MESSAGE+ if any(code in text for code in CREDENTIAL_ERROR_CODES):+ return "AWS rejected the access key. Please check the access key ID and secret access key."+ return None+++def endpoint_permission_reason(+ session: requests.Session,+ credentials: Credentials,+ endpoint_config: AnomalyDetectionEndpointConfig,+) -> Optional[str]:+ """Probe the operation a sync of this endpoint calls. `None` when reachable.++ Only a real denial counts as unreachable: throttles, 5xx and network errors leave the endpoint+ reported as reachable, so a blip can't hide tables from the schema picker.+ """+ payload: dict[str, Any] = {"MaxResults": 1}+ if endpoint_config.supports_date_interval:+ yesterday = dt.datetime.now(dt.UTC).date() - dt.timedelta(days=1)+ payload["DateInterval"] = {"StartDate": yesterday.isoformat()}++ try:+ send_operation(session, credentials, endpoint_config.operation, payload)+ except AwsCostAnomalyDetectionError as error:+ return _permission_reason(error)+ except Exception:+ return None+ return None+++def probe_endpoint_permissions(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+ endpoints: list[str],+) -> dict[str, str | None]:+ session = make_session(aws_secret_access_key, aws_session_token)+ credentials = make_credentials(aws_access_key_id, aws_secret_access_key, aws_session_token)++ reasons: dict[str, str | None] = {}+ for endpoint in endpoints:+ endpoint_config = AWS_COST_ANOMALY_DETECTION_ENDPOINTS.get(endpoint)+ reasons[endpoint] = (+ endpoint_permission_reason(session, credentials, endpoint_config) if endpoint_config is not None else None+ )+ return reasons+++def validate_credentials(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+ schema_name: Optional[str] = None,+) -> tuple[bool, Optional[str]]:+ if not aws_access_key_id or not aws_secret_access_key:+ return False, "AWS access key ID and secret access key are required"++ session = make_session(aws_secret_access_key, aws_session_token)+ credentials = make_credentials(aws_access_key_id, aws_secret_access_key, aws_session_token)++ if schema_name is not None and schema_name in AWS_COST_ANOMALY_DETECTION_ENDPOINTS:+ reason = endpoint_permission_reason(session, credentials, AWS_COST_ANOMALY_DETECTION_ENDPOINTS[schema_name])+ return reason is None, reason++ try:+ send_operation(+ session, credentials, AWS_COST_ANOMALY_DETECTION_ENDPOINTS["anomaly_monitors"].operation, {"MaxResults": 1}+ )+ except AwsCostAnomalyDetectionError as error:+ text = str(error)+ if any(code in text for code in DATA_UNAVAILABLE_ERROR_CODES):+ return False, ENABLEMENT_MESSAGE+ # A denied read still proves the key is genuine; per-table access is reported in the schema+ # picker instead of blocking source creation.+ if "AccessDeniedException" in text:+ return True, None+ return False, text+ except Exception:+ return False, "Could not reach the AWS Cost Explorer API"++ return True, None+++def aws_cost_anomaly_detection_source(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[AwsCostAnomalyDetectionResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ endpoint_config = AWS_COST_ANOMALY_DETECTION_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ aws_access_key_id=aws_access_key_id,+ aws_secret_access_key=aws_secret_access_key,+ aws_session_token=aws_session_token,+ endpoint=endpoint,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ logger=logger,+ ),+ primary_keys=endpoint_config.primary_key,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ # AWS documents no ordering for GetAnomalies, so the incremental watermark must only commit+ # once the walk completes; "desc" gives exactly that single end-of-run commit.+ sort_mode="desc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/canonical_descriptions.pynew file mode 100644index 000000000000..93aaf5bbb6d5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/canonical_descriptions.py@@ -0,0 +1,55 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "anomalies": {+ "description": "Unusual cost patterns AWS detected on the account, with the spend impact and the root causes of each one. AWS keeps anomalies for 90 days.",+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetAnomalies.html",+ "columns": {+ "anomaly_id": "Unique identifier for the anomaly.",+ "anomaly_start_date": "First day the anomaly was detected.",+ "anomaly_end_date": "Last day the anomaly was detected. AWS keeps moving this forward while the anomaly is ongoing.",+ "dimension_value": "Dimension the anomaly was detected on, for example the AWS service in a service monitor.",+ "monitor_arn": "ARN of the cost monitor that generated the anomaly.",+ "feedback": "Feedback submitted for the anomaly in the console: YES, NO or PLANNED_ACTIVITY.",+ "anomaly_score_current_score": "Last observed anomaly score. A higher score means more anomalous.",+ "anomaly_score_max_score": "Highest score observed over the anomaly's date interval.",+ "impact_max_impact": "Largest single-day dollar impact observed for the anomaly.",+ "impact_total_impact": "Cumulative dollar difference between actual and expected spend, calculated as total actual spend minus total expected spend.",+ "impact_total_actual_spend": "Cumulative dollars actually spent during the anomaly.",+ "impact_total_expected_spend": "Cumulative dollars AWS expected to be spent, predicted from the account's historical spending pattern.",+ "impact_total_impact_percentage": "Total impact as a percentage of total expected spend.",+ "root_causes": "JSON array of the root causes AWS identified, each with the service, region, linked account, usage type, and the dollars it contributed to the total impact.",+ },+ },+ "anomaly_monitors": {+ "description": "Cost monitors that continuously inspect the account's spend for anomalies.",+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetAnomalyMonitors.html",+ "columns": {+ "monitor_arn": "ARN of the monitor.",+ "monitor_name": "Name of the monitor.",+ "monitor_type": "DIMENSIONAL for an AWS managed monitor that tracks values within one dimension, CUSTOM for a customer managed monitor over specific dimension values.",+ "monitor_dimension": "Dimension an AWS managed monitor analyzes: SERVICE, LINKED_ACCOUNT, TAG or COST_CATEGORY. Empty for customer managed monitors.",+ "monitor_specification": "JSON expression controlling which costs the monitor analyzes.",+ "dimensional_value_count": "Number of dimension values the monitor evaluates.",+ "creation_date": "Date the monitor was created.",+ "last_updated_date": "Date the monitor was last updated.",+ "last_evaluated_date": "Date the monitor last evaluated the account for anomalies.",+ },+ },+ "anomaly_subscriptions": {+ "description": "Alert subscriptions that notify subscribers about anomalies detected by their associated cost monitors.",+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetAnomalySubscriptions.html",+ "columns": {+ "subscription_arn": "ARN of the alert subscription.",+ "subscription_name": "Name of the alert subscription.",+ "account_id": "Account the subscription belongs to.",+ "monitor_arn_list": "JSON array of the cost monitor ARNs the subscription watches.",+ "subscribers": "JSON array of subscribers to notify, each with an email address or SNS topic ARN, its type, and whether the subscriber confirmed the notifications.",+ "frequency": "How often notifications are sent: DAILY, WEEKLY or IMMEDIATE.",+ "threshold": "Deprecated absolute dollar impact an anomaly must exceed to trigger a notification. AWS treats it as shorthand for a threshold expression.",+ "threshold_expression": "JSON expression selecting which anomalies trigger alerts, by absolute or percentage total impact.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/settings.pynew file mode 100644index 000000000000..f1d71603c3f8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/settings.py@@ -0,0 +1,97 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Cost Anomaly Detection is part of Cost Explorer, a global service reached through us-east-1, so+# both the endpoint and the SigV4 signing region are fixed.+CE_ENDPOINT_URL = "https://ce.us-east-1.amazonaws.com/"+CE_SIGNING_REGION = "us-east-1"+CE_SIGNING_NAME = "ce"+CE_TARGET_PREFIX = "AWSInsightsIndexService"+CE_CONTENT_TYPE = "application/x-amz-json-1.1"++REQUEST_TIMEOUT_SECONDS = 120++# AWS keeps anomalies for up to 90 days, so no sync can reach back further than that.+ANOMALY_RETENTION_DAYS = 90++# An ongoing anomaly keeps changing: its score, impact and end date all move until AWS closes it.+# So an incremental run rewinds this far behind the stored watermark and re-merges those rows.+ONGOING_ANOMALY_LOOKBACK_DAYS = 14+++@dataclass(frozen=True)+class AnomalyDetectionEndpointConfig:+ name: str+ # Operation name, dispatched through the `X-Amz-Target` header.+ operation: str+ # Response key holding the list of items.+ result_key: str+ primary_key: list[str]+ # `MaxResults` per request. The API bills per paginated request, so pages are as wide as the+ # documented range allows (`MaxResults` has a minimum of 1 and no documented maximum).+ page_size: int+ # Only GetAnomalies takes a server-side date filter: `DateInterval`, matched against+ # `AnomalyEndDate`.+ supports_date_interval: bool = False+ # Flattened columns holding `YearMonthDay` values, parsed into datetimes.+ date_columns: tuple[str, ...] = ()+ # Response members kept whole rather than flattened into columns: filter expressions nest+ # arbitrarily deep and are keyed by the customer's own tag and cost category keys, so+ # flattening them would mint a column per key. The pipeline stores them as JSON.+ raw_keys: frozenset[str] = field(default_factory=frozenset)+ # Stable datetime column to partition on, if the table has one.+ partition_key: str | None = None+++AWS_COST_ANOMALY_DETECTION_ENDPOINTS: dict[str, AnomalyDetectionEndpointConfig] = {+ "anomalies": AnomalyDetectionEndpointConfig(+ name="anomalies",+ operation="GetAnomalies",+ result_key="Anomalies",+ primary_key=["anomaly_id"],+ page_size=100,+ supports_date_interval=True,+ date_columns=("anomaly_start_date", "anomaly_end_date"),+ # The first day an anomaly was detected never moves once AWS has reported it.+ partition_key="anomaly_start_date",+ ),+ "anomaly_monitors": AnomalyDetectionEndpointConfig(+ name="anomaly_monitors",+ operation="GetAnomalyMonitors",+ result_key="AnomalyMonitors",+ primary_key=["monitor_arn"],+ page_size=100,+ date_columns=("creation_date", "last_updated_date", "last_evaluated_date"),+ raw_keys=frozenset({"MonitorSpecification"}),+ ),+ "anomaly_subscriptions": AnomalyDetectionEndpointConfig(+ name="anomaly_subscriptions",+ operation="GetAnomalySubscriptions",+ result_key="AnomalySubscriptions",+ primary_key=["subscription_arn"],+ page_size=100,+ raw_keys=frozenset({"ThresholdExpression"}),+ ),+}++ENDPOINTS = tuple(AWS_COST_ANOMALY_DETECTION_ENDPOINTS.keys())++# Only GetAnomalies filters server-side, on `AnomalyEndDate`. Monitors and subscriptions carry no+# filter (and subscriptions carry no timestamp at all), so they stay full refresh.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "anomalies": [+ {+ "label": "anomaly_end_date",+ "type": IncrementalFieldType.DateTime,+ "field": "anomaly_end_date",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+}++ENDPOINT_DESCRIPTIONS: dict[str, str] = {+ "anomalies": "Cost anomalies AWS detected on the account, with their spend impact and root causes. AWS keeps 90 days of anomalies.",+ "anomaly_monitors": "Cost monitors that inspect the account's spend, with the dimension and specification each one evaluates.",+ "anomaly_subscriptions": "Alert subscriptions attached to the cost monitors, with their subscribers, frequency and alert threshold.",+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/source.pyindex decdab37b46f..7604fb5bf9de 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/source.py@@ -1,13 +1,36 @@-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.sources.aws_cost_anomaly_detection.aws_cost_anomaly_detection import (+ AwsCostAnomalyDetectionResumeConfig,+ aws_cost_anomaly_detection_source,+ probe_endpoint_permissions,+ validate_credentials as validate_aws_cost_anomaly_detection_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_anomaly_detection.settings import (+ ENDPOINT_DESCRIPTIONS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+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.awscostanomalydetection import (AwsCostAnomalyDetectionSourceConfig,)@@ -15,18 +38,141 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AwsCostAnomalyDetectionSource(SimpleSource[AwsCostAnomalyDetectionSourceConfig]):+class AwsCostAnomalyDetectionSource(+ ResumableSource[AwsCostAnomalyDetectionSourceConfig, AwsCostAnomalyDetectionResumeConfig]+):+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs+ api_docs_url = "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_Operations_AWS_Cost_Explorer_Service.html"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AWSCOSTANOMALYDETECTION+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "AWS Cost Anomaly Detection request failed: UnrecognizedClientException": "AWS rejected the access key. Please check the access key ID and secret access key, and that the key is still active.",+ "AWS Cost Anomaly Detection request failed: InvalidClientTokenId": "AWS rejected the access key. Please check the access key ID and secret access key, and that the key is still active.",+ "AWS Cost Anomaly Detection request failed: SignatureDoesNotMatch": "AWS rejected the request signature. Please re-enter the secret access key.",+ "AWS Cost Anomaly Detection request failed: InvalidSignatureException": "AWS rejected the request signature. If you are using temporary credentials, the session token has expired.",+ "AWS Cost Anomaly Detection request failed: ExpiredTokenException": "The AWS session token has expired. Please reconnect with fresh credentials.",+ "AWS Cost Anomaly Detection request failed: AccessDeniedException": "These AWS credentials are missing Cost Explorer permissions. Grant ce:GetAnomalies, ce:GetAnomalyMonitors and ce:GetAnomalySubscriptions to the IAM user or role.",+ "AWS Cost Anomaly Detection request failed: DataUnavailableException": "AWS has no Cost Explorer data for this account yet. Enable Cost Explorer in the AWS console, then try again in up to 24 hours once AWS has prepared the data.",+ "AWS access key ID and secret access key are required": "Enter both an AWS access key ID and a secret access key.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_anomaly_detection.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AwsCostAnomalyDetectionSourceConfig,+ 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: AwsCostAnomalyDetectionSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_aws_cost_anomaly_detection_credentials(+ config.aws_access_key_id,+ config.aws_secret_access_key,+ config.aws_session_token,+ schema_name=schema_name,+ )++ def get_endpoint_permissions(+ self,+ config: AwsCostAnomalyDetectionSourceConfig,+ team_id: int,+ endpoints: list[str],+ api_version: str | None = None,+ ) -> dict[str, str | None]:+ return probe_endpoint_permissions(+ config.aws_access_key_id,+ config.aws_secret_access_key,+ config.aws_session_token,+ endpoints,+ )++ def get_resumable_source_manager(+ self, inputs: SourceInputs+ ) -> ResumableSourceManager[AwsCostAnomalyDetectionResumeConfig]:+ return ResumableSourceManager[AwsCostAnomalyDetectionResumeConfig](inputs, AwsCostAnomalyDetectionResumeConfig)++ def source_for_pipeline(+ self,+ config: AwsCostAnomalyDetectionSourceConfig,+ resumable_source_manager: ResumableSourceManager[AwsCostAnomalyDetectionResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return aws_cost_anomaly_detection_source(+ aws_access_key_id=config.aws_access_key_id,+ aws_secret_access_key=config.aws_secret_access_key,+ aws_session_token=config.aws_session_token,+ endpoint=inputs.schema_name,+ 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,+ logger=inputs.logger,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.AWS_COST_ANOMALY_DETECTION,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,- label="Amazon Web Services (AWS Cost Explorer / Cost Anomaly Detection)",+ label="AWS Cost Anomaly Detection",+ caption="""Sync the cost anomalies AWS detected on your account into the PostHog Data warehouse.++Create an IAM user or role with the `ce:GetAnomalies`, `ce:GetAnomalyMonitors` and `ce:GetAnomalySubscriptions` permissions, then paste its access key ID and secret access key. Add a session token too if you are using temporary credentials.++Cost Explorer has to be enabled once in the AWS console, and it can take up to 24 hours before data is ready. AWS keeps anomalies for 90 days, so that is as far back as a first sync reaches. You only see the monitors and subscriptions created by the account you connect, so connect the management (payer) account for organization-wide coverage.""",iconPath="/static/services/aws_cost_anomaly_detection.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/aws-cost-anomaly-detection",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["aws", "finops", "cloud spend", "cost explorer", "cost anomaly detection"],+ 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",+ caption="Only for temporary credentials. Session tokens expire after a few hours, so scheduled syncs will fail once the token expires. Use a permanent access key (starts with AKIA) for recurring imports.",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/tests/test_aws_cost_anomaly_detection.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/tests/test_aws_cost_anomaly_detection.pynew file mode 100644index 000000000000..d08332add193--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/tests/test_aws_cost_anomaly_detection.py@@ -0,0 +1,629 @@+import json+import datetime as dt+from typing import Any, Optional, cast++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+import structlog+from tenacity import wait_none++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_anomaly_detection import (+ aws_cost_anomaly_detection,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_anomaly_detection.aws_cost_anomaly_detection import (+ ENABLEMENT_MESSAGE,+ AwsCostAnomalyDetectionError,+ AwsCostAnomalyDetectionResumeConfig,+ AwsCostAnomalyDetectionThrottledError,+ build_payload,+ error_for_response,+ get_rows,+ normalize_row,+ probe_endpoint_permissions,+ resolve_date_interval_start,+ send_operation,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_anomaly_detection.settings import (+ AWS_COST_ANOMALY_DETECTION_ENDPOINTS,+ CE_ENDPOINT_URL,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++LOGGER = structlog.get_logger()++ANOMALIES = AWS_COST_ANOMALY_DETECTION_ENDPOINTS["anomalies"]+MONITORS = AWS_COST_ANOMALY_DETECTION_ENDPOINTS["anomaly_monitors"]+SUBSCRIPTIONS = AWS_COST_ANOMALY_DETECTION_ENDPOINTS["anomaly_subscriptions"]+++def without_retry_backoff(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(cast(Any, send_operation).retry, "wait", wait_none())+++class FakeResumeManager(ResumableSourceManager[AwsCostAnomalyDetectionResumeConfig]):+ def __init__(self, state: Optional[AwsCostAnomalyDetectionResumeConfig] = None) -> None:+ self.state = state+ self.saved: list[AwsCostAnomalyDetectionResumeConfig] = []+ self.cleared = False++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> Optional[AwsCostAnomalyDetectionResumeConfig]:+ return self.state++ def save_state(self, data: AwsCostAnomalyDetectionResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.cleared = True+++def make_response(+ status_code: int, payload: Optional[dict[str, Any]] = None, headers: Optional[dict[str, str]] = None+) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ response.headers.update(headers or {})+ response._content = json.dumps(payload if payload is not None else {}).encode()+ return response+++def anomaly(anomaly_id: str = "anomaly-1", root_causes: Optional[list[dict[str, Any]]] = None) -> dict[str, Any]:+ return {+ "AnomalyId": anomaly_id,+ "AnomalyStartDate": "2024-05-01",+ "AnomalyEndDate": "2024-05-04T00:00:00Z",+ "DimensionValue": "AmazonS3",+ "MonitorArn": "arn:aws:ce::123456789012:anomalymonitor/abc",+ "Feedback": "PLANNED_ACTIVITY",+ "AnomalyScore": {"CurrentScore": 0.4, "MaxScore": 0.9},+ "Impact": {+ "MaxImpact": 40.5,+ "TotalImpact": 120.25,+ "TotalActualSpend": 220.25,+ "TotalExpectedSpend": 100.0,+ "TotalImpactPercentage": 120.25,+ },+ "RootCauses": root_causes if root_causes is not None else [],+ }+++def anomalies_page(items: list[dict[str, Any]], next_page_token: Optional[str] = None) -> dict[str, Any]:+ body: dict[str, Any] = {"Anomalies": items}+ if next_page_token is not None:+ body["NextPageToken"] = next_page_token+ return body+++class TestResolveDateIntervalStart:+ TODAY = dt.date(2024, 6, 1)++ def test_a_full_refresh_asks_for_the_whole_retention_window(self) -> None:+ assert resolve_date_interval_start(False, None, self.TODAY) == dt.date(2024, 3, 3)++ def test_a_watermark_is_ignored_when_the_run_is_not_incremental(self) -> None:+ assert resolve_date_interval_start(False, "2024-05-30", self.TODAY) == dt.date(2024, 3, 3)++ @pytest.mark.parametrize(+ "watermark",+ [+ "2024-05-20",+ "2024-05-20T09:30:00Z",+ dt.date(2024, 5, 20),+ dt.datetime(2024, 5, 20, 9, 30, tzinfo=dt.UTC),+ ],+ )+ def test_incremental_rewinds_behind_the_watermark_so_ongoing_anomalies_are_re_read(self, watermark: Any) -> None:+ assert resolve_date_interval_start(True, watermark, self.TODAY) == dt.date(2024, 5, 6)++ def test_incremental_never_reaches_past_the_ninety_day_retention_floor(self) -> None:+ assert resolve_date_interval_start(True, "2023-01-01", self.TODAY) == dt.date(2024, 3, 3)++ def test_a_watermark_in_the_future_is_clamped_to_today(self) -> None:+ assert resolve_date_interval_start(True, "2025-01-01", self.TODAY) == self.TODAY++ def test_an_unparseable_watermark_falls_back_to_the_retention_floor(self) -> None:+ assert resolve_date_interval_start(True, "not-a-date", self.TODAY) == dt.date(2024, 3, 3)+++class TestBuildPayload:+ def test_anomalies_send_an_open_ended_date_interval(self) -> None:+ payload = build_payload(ANOMALIES, dt.date(2024, 3, 3), None)++ assert payload["MaxResults"] == ANOMALIES.page_size+ # An open anomaly has its end date pushed forward by AWS, so bounding the window with an+ # `EndDate` could drop it from the results.+ assert payload["DateInterval"] == {"StartDate": "2024-03-03"}+ assert "NextPageToken" not in payload++ def test_a_page_token_is_sent_back_under_the_key_aws_returned_it_in(self) -> None:+ assert build_payload(ANOMALIES, dt.date(2024, 3, 3), "tok")["NextPageToken"] == "tok"++ @pytest.mark.parametrize("endpoint_config", [MONITORS, SUBSCRIPTIONS])+ def test_operations_without_a_date_filter_never_send_a_date_interval(self, endpoint_config: Any) -> None:+ assert build_payload(endpoint_config, dt.date(2024, 3, 3), None) == {"MaxResults": endpoint_config.page_size}+++class TestNormalizeRow:+ def test_anomaly_scores_and_impact_flatten_into_prefixed_columns(self) -> None:+ row = normalize_row(ANOMALIES, anomaly())++ assert row["anomaly_id"] == "anomaly-1"+ assert row["dimension_value"] == "AmazonS3"+ assert row["feedback"] == "PLANNED_ACTIVITY"+ assert row["anomaly_score_current_score"] == 0.4+ assert row["anomaly_score_max_score"] == 0.9+ assert row["impact_max_impact"] == 40.5+ assert row["impact_total_impact"] == 120.25+ assert row["impact_total_actual_spend"] == 220.25+ assert row["impact_total_expected_spend"] == 100.0+ assert row["impact_total_impact_percentage"] == 120.25++ @pytest.mark.parametrize(+ "column,expected",+ [+ ("anomaly_start_date", dt.datetime(2024, 5, 1, tzinfo=dt.UTC)),+ ("anomaly_end_date", dt.datetime(2024, 5, 4, tzinfo=dt.UTC)),+ ],+ )+ def test_both_date_only_and_timestamped_dates_parse_to_utc_datetimes(self, column: str, expected: Any) -> None:+ # The incremental cursor is a datetime column, so a bare `YYYY-MM-DD` has to parse too.+ assert normalize_row(ANOMALIES, anomaly())[column] == expected++ def test_root_causes_stay_a_list_with_their_own_fields_snake_cased(self) -> None:+ row = normalize_row(+ ANOMALIES,+ anomaly(+ root_causes=[+ {+ "Service": "AmazonS3",+ "Region": "us-east-1",+ "LinkedAccount": "123456789012",+ "LinkedAccountName": "prod",+ "UsageType": "USE1-TimedStorage-ByteHrs",+ "Impact": {"Contribution": 88.5},+ }+ ]+ ),+ )++ assert row["root_causes"] == [+ {+ "service": "AmazonS3",+ "region": "us-east-1",+ "linked_account": "123456789012",+ "linked_account_name": "prod",+ "usage_type": "USE1-TimedStorage-ByteHrs",+ "impact_contribution": 88.5,+ }+ ]++ def test_a_monitor_specification_is_kept_whole_rather_than_exploded_into_columns(self) -> None:+ # The keys inside it are the customer's own tag and cost category keys, so flattening+ # would mint a column per key and shift the table's schema per account.+ row = normalize_row(+ MONITORS,+ {+ "MonitorArn": "arn:aws:ce::123456789012:anomalymonitor/abc",+ "MonitorName": "Service monitor",+ "MonitorType": "DIMENSIONAL",+ "MonitorDimension": "SERVICE",+ "MonitorSpecification": {"Tags": {"Key": "team", "Values": ["growth"]}},+ "DimensionalValueCount": 12,+ "CreationDate": "2024-01-02T03:04:05Z",+ "LastUpdatedDate": "2024-02-01",+ "LastEvaluatedDate": "2024-06-01",+ },+ )++ assert row["monitor_specification"] == {"Tags": {"Key": "team", "Values": ["growth"]}}+ assert row["monitor_name"] == "Service monitor"+ assert row["dimensional_value_count"] == 12+ assert row["creation_date"] == dt.datetime(2024, 1, 2, 3, 4, 5, tzinfo=dt.UTC)+ assert row["last_updated_date"] == dt.datetime(2024, 2, 1, tzinfo=dt.UTC)+ assert row["last_evaluated_date"] == dt.datetime(2024, 6, 1, tzinfo=dt.UTC)++ def test_subscription_lists_survive_normalization(self) -> None:+ row = normalize_row(+ SUBSCRIPTIONS,+ {+ "SubscriptionArn": "arn:aws:ce::123456789012:anomalysubscription/def",+ "SubscriptionName": "Daily alerts",+ "AccountId": "123456789012",+ "MonitorArnList": ["arn:aws:ce::123456789012:anomalymonitor/abc"],+ "Subscribers": [{"Address": "[email protected]", "Type": "EMAIL", "Status": "CONFIRMED"}],+ "Frequency": "DAILY",+ "Threshold": 100.0,+ "ThresholdExpression": {+ "Dimensions": {"Key": "ANOMALY_TOTAL_IMPACT_ABSOLUTE", "Values": ["100"]},+ },+ },+ )++ assert row["monitor_arn_list"] == ["arn:aws:ce::123456789012:anomalymonitor/abc"]+ assert row["subscribers"] == [+ {"address": "[email protected]", "type": "EMAIL", "status": "CONFIRMED"},+ ]+ assert row["threshold_expression"] == {+ "Dimensions": {"Key": "ANOMALY_TOTAL_IMPACT_ABSOLUTE", "Values": ["100"]}+ }+ assert row["threshold"] == 100.0++ def test_missing_members_do_not_invent_columns(self) -> None:+ row = normalize_row(ANOMALIES, {"AnomalyId": "anomaly-2", "MonitorArn": "arn"})++ assert row == {"anomaly_id": "anomaly-2", "monitor_arn": "arn"}+++class TestErrorClassification:+ @pytest.mark.parametrize(+ "code",+ ["LimitExceededException", "ThrottlingException", "TooManyRequestsException", "RequestLimitExceeded"],+ )+ def test_throttling_codes_are_retryable(self, code: str) -> None:+ response = make_response(400, {"__type": f"com.amazon.coral.availability#{code}", "message": "slow down"})++ error = error_for_response(response)++ assert isinstance(error, AwsCostAnomalyDetectionThrottledError)+ assert f"AWS Cost Anomaly Detection request failed: {code}" in str(error)++ @pytest.mark.parametrize(+ "code",+ [+ "AccessDeniedException",+ "UnrecognizedClientException",+ "ExpiredTokenException",+ "DataUnavailableException",+ "InvalidNextTokenException",+ ],+ )+ def test_permanent_codes_are_not_retryable_and_stringify_for_the_source_mapping(self, code: str) -> None:+ response = make_response(400, {"__type": code, "message": "nope"})++ error = error_for_response(response)++ assert not isinstance(error, AwsCostAnomalyDetectionThrottledError)+ assert str(error) == f"AWS Cost Anomaly Detection request failed: {code} - nope"++ def test_the_error_type_header_wins_over_the_body(self) -> None:+ response = make_response(+ 400,+ {"message": "nope"},+ headers={"x-amzn-ErrorType": "AccessDeniedException:http://internal.amazon.com/coral/"},+ )++ assert str(error_for_response(response)).startswith(+ "AWS Cost Anomaly Detection request failed: AccessDeniedException - nope"+ )++ def test_a_non_json_error_body_still_produces_a_usable_message(self) -> None:+ response = requests.Response()+ response.status_code = 503+ response._content = b"<html>gateway</html>"++ assert "HTTP 503" in str(error_for_response(response))+++class TestSendOperation:+ def test_requests_are_sigv4_signed_against_us_east_1_and_dispatched_via_x_amz_target(self) -> None:+ session = mock.MagicMock(spec=requests.Session)+ session.post.return_value = make_response(200, {"Anomalies": []})+ credentials = aws_cost_anomaly_detection.Credentials("AKIAEXAMPLE", "secret")++ with freeze_time("2024-06-05T10:00:00Z"):+ send_operation(session, credentials, "GetAnomalies", {"MaxResults": 100})++ kwargs = session.post.call_args[1]+ assert session.post.call_args[0][0] == CE_ENDPOINT_URL+ assert kwargs["headers"]["X-Amz-Target"] == "AWSInsightsIndexService.GetAnomalies"+ assert kwargs["headers"]["Content-Type"] == "application/x-amz-json-1.1"+ # Cost Anomaly Detection is global: a request signed for any other region is rejected.+ assert kwargs["headers"]["Authorization"].startswith(+ "AWS4-HMAC-SHA256 Credential=AKIAEXAMPLE/20240605/us-east-1/ce/aws4_request"+ )+ assert json.loads(kwargs["data"]) == {"MaxResults": 100}++ def test_temporary_credentials_carry_the_session_token(self) -> None:+ session = mock.MagicMock(spec=requests.Session)+ session.post.return_value = make_response(200, {})+ credentials = aws_cost_anomaly_detection.Credentials("AKIAEXAMPLE", "secret", "session-token")++ send_operation(session, credentials, "GetAnomalies", {})++ assert session.post.call_args[1]["headers"]["X-Amz-Security-Token"] == "session-token"++ def test_throttled_calls_are_retried_until_they_succeed(self, monkeypatch: pytest.MonkeyPatch) -> None:+ without_retry_backoff(monkeypatch)+ session = mock.MagicMock(spec=requests.Session)+ session.post.side_effect = [+ make_response(400, {"__type": "LimitExceededException", "message": "slow down"}),+ make_response(200, {"Anomalies": []}),+ ]++ body = send_operation(session, aws_cost_anomaly_detection.Credentials("k", "s"), "GetAnomalies", {})++ assert body == {"Anomalies": []}+ assert session.post.call_count == 2++ def test_permanent_errors_are_raised_without_retrying(self, monkeypatch: pytest.MonkeyPatch) -> None:+ without_retry_backoff(monkeypatch)+ session = mock.MagicMock(spec=requests.Session)+ session.post.return_value = make_response(400, {"__type": "AccessDeniedException", "message": "denied"})++ with pytest.raises(AwsCostAnomalyDetectionError):+ send_operation(session, aws_cost_anomaly_detection.Credentials("k", "s"), "GetAnomalies", {})++ assert session.post.call_count == 1+++@freeze_time("2024-06-01T12:00:00Z")+class TestGetRows:+ def _run(+ self,+ responses: list[Any],+ manager: FakeResumeManager,+ endpoint: str = "anomalies",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[list[dict[str, Any]]], mock.MagicMock]:+ with mock.patch.object(aws_cost_anomaly_detection, "send_operation", side_effect=responses) as send:+ batches = list(+ get_rows(+ aws_access_key_id="key",+ aws_secret_access_key="secret",+ aws_session_token=None,+ endpoint=endpoint,+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ logger=LOGGER,+ )+ )+ return batches, send++ def test_pagination_stops_when_aws_stops_returning_a_token(self) -> None:+ batches, send = self._run(+ [+ anomalies_page([anomaly("anomaly-1")], next_page_token="page-2"),+ anomalies_page([anomaly("anomaly-2")]),+ ],+ FakeResumeManager(),+ )++ assert send.call_count == 2+ assert [row["anomaly_id"] for batch in batches for row in batch] == ["anomaly-1", "anomaly-2"]+ assert "NextPageToken" not in send.call_args_list[0][0][3]+ assert send.call_args_list[1][0][3]["NextPageToken"] == "page-2"++ def test_state_is_saved_after_each_page_and_cleared_once_the_walk_completes(self) -> None:+ manager = FakeResumeManager()++ self._run([anomalies_page([anomaly()], next_page_token="page-2"), anomalies_page([])], manager)++ assert manager.saved == [+ AwsCostAnomalyDetectionResumeConfig(date_interval_start="2024-03-03", next_page_token="page-2"),+ AwsCostAnomalyDetectionResumeConfig(date_interval_start="2024-03-03", next_page_token=None),+ ]+ assert manager.cleared is True++ def test_a_saved_token_for_this_windows_start_resumes_mid_walk(self) -> None:+ manager = FakeResumeManager(+ AwsCostAnomalyDetectionResumeConfig(date_interval_start="2024-03-03", next_page_token="page-7")+ )++ _, send = self._run([anomalies_page([anomaly()])], manager)++ assert send.call_args_list[0][0][3]["NextPageToken"] == "page-7"++ def test_a_token_saved_for_a_different_window_restarts_the_walk(self) -> None:+ # The window start moves with the watermark, and a token only ever belongs to the window+ # it was issued for, so reusing it would skip the anomalies before it.+ manager = FakeResumeManager(+ AwsCostAnomalyDetectionResumeConfig(date_interval_start="2024-01-01", next_page_token="stale")+ )++ _, send = self._run([anomalies_page([anomaly()])], manager)++ assert "NextPageToken" not in send.call_args_list[0][0][3]+ assert send.call_args_list[0][0][3]["DateInterval"] == {"StartDate": "2024-03-03"}++ def test_an_expired_saved_token_restarts_the_walk_instead_of_failing_the_job(self) -> None:+ manager = FakeResumeManager(+ AwsCostAnomalyDetectionResumeConfig(date_interval_start="2024-03-03", next_page_token="expired")+ )++ batches, send = self._run(+ [+ AwsCostAnomalyDetectionError(+ "AWS Cost Anomaly Detection request failed: InvalidNextTokenException - bad token"+ ),+ anomalies_page([anomaly("anomaly-1")]),+ ],+ manager,+ )++ assert send.call_count == 2+ assert "NextPageToken" not in send.call_args_list[1][0][3]+ assert [row["anomaly_id"] for batch in batches for row in batch] == ["anomaly-1"]++ def test_an_expired_token_error_on_a_fresh_walk_is_not_swallowed(self) -> None:+ with pytest.raises(AwsCostAnomalyDetectionError):+ self._run(+ [+ AwsCostAnomalyDetectionError(+ "AWS Cost Anomaly Detection request failed: InvalidNextTokenException - bad token"+ )+ ],+ FakeResumeManager(),+ )++ @pytest.mark.parametrize(+ "should_use_incremental_field,watermark,expected_start",+ [+ (False, None, "2024-03-03"),+ (True, None, "2024-03-03"),+ (True, "2024-05-28", "2024-05-14"),+ ],+ )+ def test_the_requested_window_follows_the_watermark(+ self, should_use_incremental_field: bool, watermark: Any, expected_start: str+ ) -> None:+ _, send = self._run(+ [anomalies_page([])],+ FakeResumeManager(),+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=watermark,+ )++ assert send.call_args_list[0][0][3]["DateInterval"] == {"StartDate": expected_start}++ @pytest.mark.parametrize(+ "endpoint,result_key,identifier_column,identifier",+ [+ ("anomaly_monitors", "AnomalyMonitors", "monitor_arn", "arn:aws:ce::1:anomalymonitor/abc"),+ (+ "anomaly_subscriptions",+ "AnomalySubscriptions",+ "subscription_arn",+ "arn:aws:ce::1:anomalysubscription/def",+ ),+ ],+ )+ def test_the_undated_operations_send_no_date_interval(+ self, endpoint: str, result_key: str, identifier_column: str, identifier: str+ ) -> None:+ column = {"anomaly_monitors": "MonitorArn", "anomaly_subscriptions": "SubscriptionArn"}[endpoint]++ batches, send = self._run(+ [{result_key: [{column: identifier}]}],+ FakeResumeManager(),+ endpoint=endpoint,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-05-28",+ )++ assert "DateInterval" not in send.call_args_list[0][0][3]+ assert batches[0][0][identifier_column] == identifier++ def test_an_empty_page_yields_nothing_but_still_finishes_cleanly(self) -> None:+ manager = FakeResumeManager()++ batches, send = self._run([anomalies_page([])], manager)++ assert batches == []+ assert send.call_count == 1+ assert manager.cleared is True+++class TestValidateCredentials:+ def test_missing_credentials_short_circuit_without_a_billed_request(self) -> None:+ with mock.patch.object(aws_cost_anomaly_detection, "send_operation") as send:+ assert validate_credentials("", "secret", None) == (+ False,+ "AWS access key ID and secret access key are required",+ )++ send.assert_not_called()++ def test_a_successful_probe_validates_against_the_cheapest_operation(self) -> None:+ with mock.patch.object(aws_cost_anomaly_detection, "send_operation", return_value={"AnomalyMonitors": []}) as s:+ assert validate_credentials("key", "secret", None) == (True, None)++ assert s.call_args[0][2] == "GetAnomalyMonitors"+ assert s.call_args[0][3] == {"MaxResults": 1}++ def test_a_denied_probe_still_creates_the_source_so_readable_tables_can_sync(self) -> None:+ error = AwsCostAnomalyDetectionError(+ "AWS Cost Anomaly Detection request failed: AccessDeniedException - not authorized"+ )++ with mock.patch.object(aws_cost_anomaly_detection, "send_operation", side_effect=error):+ assert validate_credentials("key", "secret", None) == (True, None)++ @pytest.mark.parametrize("code", ["DataUnavailableException", "BillExpirationException"])+ def test_an_account_without_cost_explorer_is_told_to_enable_it(self, code: str) -> None:+ error = AwsCostAnomalyDetectionError(f"AWS Cost Anomaly Detection request failed: {code} - no data")++ with mock.patch.object(aws_cost_anomaly_detection, "send_operation", side_effect=error):+ assert validate_credentials("key", "secret", None) == (False, ENABLEMENT_MESSAGE)++ def test_a_rejected_key_is_surfaced_to_the_user(self) -> None:+ error = AwsCostAnomalyDetectionError(+ "AWS Cost Anomaly Detection request failed: UnrecognizedClientException - invalid token"+ )++ with mock.patch.object(aws_cost_anomaly_detection, "send_operation", side_effect=error):+ assert validate_credentials("key", "secret", None) == (False, str(error))++ def test_a_transport_failure_does_not_leak_internals(self) -> None:+ with mock.patch.object(+ aws_cost_anomaly_detection, "send_operation", side_effect=requests.ConnectionError("boom")+ ):+ assert validate_credentials("key", "secret", None) == (False, "Could not reach the AWS Cost Explorer API")++ @freeze_time("2024-06-01T12:00:00Z")+ def test_a_per_schema_check_probes_that_schemas_own_operation(self) -> None:+ with mock.patch.object(aws_cost_anomaly_detection, "send_operation", return_value={"Anomalies": []}) as send:+ assert validate_credentials("key", "secret", None, schema_name="anomalies") == (True, None)++ assert send.call_args[0][2] == "GetAnomalies"+ # `DateInterval` is required, so the probe has to send one or AWS rejects the call.+ assert send.call_args[0][3]["DateInterval"] == {"StartDate": "2024-05-31"}++ def test_a_per_schema_check_reports_the_missing_iam_permission(self) -> None:+ error = AwsCostAnomalyDetectionError(+ "AWS Cost Anomaly Detection request failed: AccessDeniedException - "+ "User is not authorized to perform ce:GetAnomalies"+ )++ with mock.patch.object(aws_cost_anomaly_detection, "send_operation", side_effect=error):+ assert validate_credentials("key", "secret", None, schema_name="anomalies") == (+ False,+ "Missing IAM permission ce:GetAnomalies",+ )+++class TestProbeEndpointPermissions:+ def test_reachable_endpoints_report_no_reason(self) -> None:+ with mock.patch.object(aws_cost_anomaly_detection, "send_operation", return_value={}):+ assert probe_endpoint_permissions("key", "secret", None, list(AWS_COST_ANOMALY_DETECTION_ENDPOINTS)) == {+ "anomalies": None,+ "anomaly_monitors": None,+ "anomaly_subscriptions": None,+ }++ def test_a_denial_names_the_permission_to_grant(self) -> None:+ error = AwsCostAnomalyDetectionError(+ "AWS Cost Anomaly Detection request failed: AccessDeniedException - "+ "User is not authorized to perform ce:GetAnomalySubscriptions"+ )++ with mock.patch.object(aws_cost_anomaly_detection, "send_operation", side_effect=error):+ reasons = probe_endpoint_permissions("key", "secret", None, ["anomaly_subscriptions"])++ assert reasons == {"anomaly_subscriptions": "Missing IAM permission ce:GetAnomalySubscriptions"}++ @pytest.mark.parametrize(+ "error",+ [+ AwsCostAnomalyDetectionThrottledError(+ "AWS Cost Anomaly Detection request failed: LimitExceededException - slow down"+ ),+ requests.ConnectionError("boom"),+ ],+ )+ def test_a_throttle_or_network_blip_never_hides_a_table_from_the_picker(self, error: Exception) -> None:+ with mock.patch.object(aws_cost_anomaly_detection, "send_operation", side_effect=error):+ assert probe_endpoint_permissions("key", "secret", None, ["anomalies"]) == {"anomalies": None}++ def test_an_unknown_endpoint_name_is_reported_as_reachable_rather_than_raising(self) -> None:+ with mock.patch.object(aws_cost_anomaly_detection, "send_operation", return_value={}) as send:+ assert probe_endpoint_permissions("key", "secret", None, ["not_a_table"]) == {"not_a_table": None}++ send.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/tests/test_aws_cost_anomaly_detection_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/tests/test_aws_cost_anomaly_detection_source.pynew file mode 100644index 000000000000..a94e0d93b263--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/tests/test_aws_cost_anomaly_detection_source.py@@ -0,0 +1,248 @@+import datetime as dt+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest import mock++import structlog++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_anomaly_detection import (+ aws_cost_anomaly_detection as transport_module,+ source as source_module,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_anomaly_detection.aws_cost_anomaly_detection import (+ AwsCostAnomalyDetectionResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_anomaly_detection.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_anomaly_detection.settings import (+ AWS_COST_ANOMALY_DETECTION_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_anomaly_detection.source import (+ AwsCostAnomalyDetectionSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awscostanomalydetection import (+ AwsCostAnomalyDetectionSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def make_inputs(+ schema_name: str,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=1,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ db_incremental_field_earliest_value=None,+ incremental_field="anomaly_end_date",+ incremental_field_type=None,+ job_id="job-id",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestAwsCostAnomalyDetectionSource:+ def setup_method(self) -> None:+ self.source = AwsCostAnomalyDetectionSource()+ self.config = AwsCostAnomalyDetectionSourceConfig(+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key="secret",+ aws_session_token=None,+ )++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.AWSCOSTANOMALYDETECTION++ def test_source_is_released_and_labelled_alpha(self) -> None:+ config = self.source.get_source_config++ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.category == DataWarehouseSourceCategory.FINANCE___ACCOUNTING+ assert config.iconPath == "/static/services/aws_cost_anomaly_detection.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/aws-cost-anomaly-detection"++ def test_the_form_asks_only_for_iam_credentials(self) -> None:+ # Cost Anomaly Detection is global and always signed for us-east-1, so a region field+ # would suggest a routing choice the user does not have.+ assert [field.name for field in self.source.get_source_config.fields] == [+ "aws_access_key_id",+ "aws_secret_access_key",+ "aws_session_token",+ ]++ @pytest.mark.parametrize(+ "field_name,required,secret",+ [+ ("aws_access_key_id", True, False),+ ("aws_secret_access_key", True, True),+ ("aws_session_token", False, True),+ ],+ )+ def test_credential_fields_are_marked_secret_so_they_are_not_echoed_back(+ self, field_name: str, required: bool, secret: bool+ ) -> None:+ field = next(+ f+ for f in self.source.get_source_config.fields+ if isinstance(f, SourceFieldInputConfig) and f.name == field_name+ )++ assert field.required is required+ assert field.secret is secret+ assert (field.type == SourceFieldInputConfigType.PASSWORD) is secret++ def test_only_the_anomalies_table_syncs_incrementally(self) -> None:+ # GetAnomalies is the one operation with a server-side date filter; monitors and+ # subscriptions have no filter, so an "incremental" sync there would cost the same as a+ # full refresh.+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, team_id=1)}++ assert list(schemas) == list(ENDPOINTS)+ assert schemas["anomalies"].supports_incremental is True+ assert [field["field"] for field in schemas["anomalies"].incremental_fields] == ["anomaly_end_date"]+ assert schemas["anomaly_monitors"].supports_incremental is False+ assert schemas["anomaly_subscriptions"].supports_incremental is False+ assert all(schema.description for schema in schemas.values())++ def test_get_schemas_honors_the_schema_picker_filter(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["anomaly_monitors"])++ assert [schema.name for schema in schemas] == ["anomaly_monitors"]++ def test_table_catalog_is_listable_without_credentials_for_public_docs(self) -> None:+ assert self.source.lists_tables_without_credentials is True+ assert self.source.get_schemas(+ AwsCostAnomalyDetectionSourceConfig(aws_access_key_id="", aws_secret_access_key=""), 1+ )++ def test_canonical_descriptions_are_keyed_by_the_schema_names(self) -> None:+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "observed_error",+ [+ "AWS Cost Anomaly Detection request failed: AccessDeniedException - User is not authorized to perform ce:GetAnomalies",+ "AWS Cost Anomaly Detection request failed: UnrecognizedClientException - The security token included in the request is invalid",+ "AWS Cost Anomaly Detection request failed: ExpiredTokenException - The security token included in the request is expired",+ "AWS Cost Anomaly Detection request failed: SignatureDoesNotMatch - Signature expired",+ "AWS Cost Anomaly Detection request failed: DataUnavailableException - no data",+ ],+ )+ def test_permanent_aws_failures_stop_the_sync_instead_of_retrying(self, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "observed_error",+ [+ "AWS Cost Anomaly Detection request failed: LimitExceededException - Rate exceeded",+ "AWS Cost Anomaly Detection request failed: HTTP 503 - ",+ ],+ )+ def test_transient_aws_failures_keep_retrying(self, observed_error: str) -> None:+ assert not any(key in observed_error for key in self.source.get_non_retryable_errors())++ def test_validate_credentials_passes_the_configured_credentials_and_schema_through(self) -> None:+ with mock.patch.object(+ source_module, "validate_aws_cost_anomaly_detection_credentials", return_value=(True, None)+ ) as validate:+ assert self.source.validate_credentials(self.config, team_id=1, schema_name="anomalies") == (True, None)++ assert validate.call_args[0] == ("AKIAEXAMPLE", "secret", None)+ assert validate.call_args[1] == {"schema_name": "anomalies"}++ def test_validate_credentials_surfaces_the_failure_reason(self) -> None:+ with mock.patch.object(+ source_module, "validate_aws_cost_anomaly_detection_credentials", return_value=(False, "denied")+ ):+ assert self.source.validate_credentials(self.config, team_id=1) == (False, "denied")++ def test_endpoint_permissions_are_probed_per_table_for_the_schema_picker(self) -> None:+ with mock.patch.object(source_module, "probe_endpoint_permissions", return_value={"anomalies": None}) as probe:+ assert self.source.get_endpoint_permissions(self.config, 1, ["anomalies"]) == {"anomalies": None}++ assert probe.call_args[0] == ("AKIAEXAMPLE", "secret", None, ["anomalies"])++ def test_resumable_manager_is_bound_to_the_sources_resume_dataclass(self) -> None:+ manager = self.source.get_resumable_source_manager(make_inputs("anomalies"))++ assert manager._data_class is AwsCostAnomalyDetectionResumeConfig++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_source_for_pipeline_carries_the_endpoints_primary_key(self, endpoint: str) -> None:+ inputs = make_inputs(endpoint)+ manager = self.source.get_resumable_source_manager(inputs)++ response = self.source.source_for_pipeline(self.config, manager, inputs)++ assert response.name == endpoint+ assert response.primary_keys == AWS_COST_ANOMALY_DETECTION_ENDPOINTS[endpoint].primary_key+ # AWS documents no ordering for these operations, so the watermark only commits once the+ # walk has finished.+ assert response.sort_mode == "desc"++ def test_anomalies_partition_on_the_start_date_because_it_never_moves(self) -> None:+ # The end date keeps moving while an anomaly is open, so partitioning on it would rewrite+ # partitions every sync.+ inputs = make_inputs("anomalies")++ response = self.source.source_for_pipeline(+ self.config, self.source.get_resumable_source_manager(inputs), inputs+ )++ assert response.partition_keys == ["anomaly_start_date"]+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"++ @pytest.mark.parametrize("endpoint", ["anomaly_monitors", "anomaly_subscriptions"])+ def test_the_dateless_tables_are_not_partitioned(self, endpoint: str) -> None:+ inputs = make_inputs(endpoint)++ response = self.source.source_for_pipeline(+ self.config, self.source.get_resumable_source_manager(inputs), inputs+ )++ assert response.partition_keys is None+ assert response.partition_mode is None++ def test_source_for_pipeline_forwards_the_watermark_only_on_an_incremental_run(self) -> None:+ watermark = dt.datetime(2024, 5, 1, tzinfo=dt.UTC)++ with mock.patch.object(source_module, "aws_cost_anomaly_detection_source") as build:+ inputs = make_inputs("anomalies", True, watermark)+ self.source.source_for_pipeline(self.config, self.source.get_resumable_source_manager(inputs), inputs)+ assert build.call_args[1]["db_incremental_field_last_value"] == watermark++ inputs = make_inputs("anomalies", False, watermark)+ self.source.source_for_pipeline(self.config, self.source.get_resumable_source_manager(inputs), inputs)+ assert build.call_args[1]["db_incremental_field_last_value"] is None++ def test_items_are_lazy_so_building_the_response_bills_no_api_request(self) -> None:+ inputs = make_inputs("anomalies")+ manager = self.source.get_resumable_source_manager(inputs)++ with mock.patch.object(transport_module, "send_operation") as send:+ response = self.source.source_for_pipeline(self.config, manager, inputs)+ items = cast("Iterable[Any]", response.items())++ assert iter(items) is not None+ send.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awscostanomalydetection.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awscostanomalydetection.pyindex 6a2b1cd7fdd4..68ff749f4c3e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awscostanomalydetection.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awscostanomalydetection.py@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AwsCostAnomalyDetectionSourceConfig(config.Config):- pass+ aws_access_key_id: str+ aws_secret_access_key: str+ aws_session_token: str | None = None