: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 aws_cost_explorer source (#73794)
Tom Owers079d91665a6d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 2619ca1510db..66fb5aa0eb52 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -90,6 +90,7 @@ the row lists both.| aviationstack | HTTP | requests | ✅ || aviator | HTTP | requests | ✅ || awin | HTTP | requests | ✅ |+| aws_cost_explorer | HTTP | requests | ✅ || azure_devops | HTTP | requests | ✅ || babelforce | HTTP | requests | ✅ || bamboohr | HTTP | requests | ✅ |@@ -761,7 +762,6 @@ doesn't conflict with concurrent PRs.- aws_connect- aws_cost_and_usage_report- aws_cost_anomaly_detection-- aws_cost_explorer- aws_glue_data_catalog- aws_guardduty- aws_healthdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/aws_cost_explorer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/aws_cost_explorer.pynew file mode 100644index 000000000000..c1a4d670ccad--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/aws_cost_explorer.py@@ -0,0 +1,442 @@+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 urllib3.util.retry import Retry++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer.settings import (+ AWS_COST_EXPLORER_ENDPOINTS,+ CE_CONTENT_TYPE,+ CE_ENDPOINT_URL,+ CE_SIGNING_NAME,+ CE_SIGNING_REGION,+ CE_TARGET_PREFIX,+ DEFAULT_LOOKBACK_DAYS,+ CostExplorerEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++REQUEST_TIMEOUT_SECONDS = 120+MAX_THROTTLE_ATTEMPTS = 6++# The Cost Explorer API 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 = Retry(+ 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",+ }+)++_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")+++class AwsCostExplorerError(Exception):+ pass+++class AwsCostExplorerThrottledError(AwsCostExplorerError):+ pass+++class AwsCostExplorerResumeConfig:+ """Where a previous attempt stopped: the request window plus its page token."""++ window_start: str+ next_page_token: Optional[str] = None++[email protected](frozen=True)+class TimeWindow:+ start: dt.date+ end: dt.date+++def _snake(name: str) -> str:+ """`UtilizationPercentage` -> `utilization_percentage`, `LINKED_ACCOUNT` -> `linked_account`."""+ return _CAMEL_BOUNDARY.sub("_", name).lower()+++def _to_number(value: Any) -> Any:+ """Cost Explorer returns every numeric as a string; keep non-numerics untouched."""+ if not isinstance(value, str):+ return value+ try:+ return float(value)+ except ValueError:+ return value+++def _parse_period(value: Any) -> Optional[dt.datetime]:+ if not isinstance(value, str) or not value:+ return None+ try:+ parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ 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 resolve_start_date(+ configured_start_date: Optional[str],+ endpoint_config: CostExplorerEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ end: dt.date,+) -> dt.date:+ """The earliest date this run asks AWS for.++ Incremental runs rewind behind the stored watermark because Cost Explorer restates recent+ periods until the bill finalizes, but never before the user's configured start date.+ """+ floor = coerce_date(configured_start_date) or (end - dt.timedelta(days=DEFAULT_LOOKBACK_DAYS))++ start = floor+ if should_use_incremental_field:+ watermark = coerce_date(db_incremental_field_last_value)+ if watermark is not None:+ start = max(floor, watermark - dt.timedelta(days=endpoint_config.restatement_lookback_days))++ return min(start, end)+++def build_windows(start: dt.date, end: dt.date, window_days: int) -> list[TimeWindow]:+ """Split [start, end) into request windows. `end` is exclusive, matching `TimePeriod`."""+ windows: list[TimeWindow] = []+ cursor = start+ while cursor < end:+ stop = min(cursor + dt.timedelta(days=window_days), end)+ windows.append(TimeWindow(start=cursor, end=stop))+ cursor = stop+ return windows+++def build_payload(+ endpoint_config: CostExplorerEndpointConfig, window: TimeWindow, page_token: Optional[str]+) -> dict[str, Any]:+ payload: dict[str, Any] = {+ "TimePeriod": {"Start": window.start.isoformat(), "End": window.end.isoformat()},+ "Granularity": endpoint_config.granularity,+ }+ if endpoint_config.metrics:+ payload["Metrics"] = list(endpoint_config.metrics)+ if endpoint_config.group_by:+ payload["GroupBy"] = [{"Type": "DIMENSION", "Key": key} for key in endpoint_config.group_by]+ if page_token and endpoint_config.page_token_key:+ payload[endpoint_config.page_token_key] = page_token+ return payload+++def _flatten(prefix: str, obj: dict[str, Any]) -> dict[str, Any]:+ flattened: dict[str, Any] = {}+ for key, value in obj.items():+ column = f"{prefix}_{_snake(key)}" if prefix else _snake(key)+ if isinstance(value, dict):+ flattened.update(_flatten(column, value))+ else:+ flattened[column] = _to_number(value)+ return flattened+++def _metric_columns(endpoint_config: CostExplorerEndpointConfig, metrics: dict[str, Any]) -> dict[str, Any]:+ # Driven off the configured metric list rather than the response, so a period AWS omits a+ # metric for still lands with the same columns.+ columns: dict[str, Any] = {}+ for metric in endpoint_config.metrics:+ value = metrics.get(metric) or {}+ columns[f"{_snake(metric)}_amount"] = _to_number(value.get("Amount"))+ columns[f"{_snake(metric)}_unit"] = value.get("Unit")+ return columns+++def _cost_rows(+ endpoint_config: CostExplorerEndpointConfig, base: dict[str, Any], result: dict[str, Any]+) -> list[dict[str, Any]]:+ group_columns = [_snake(key) for key in endpoint_config.group_by]+ groups = result.get("Groups") or []++ if not groups:+ row = dict(base)+ row.update(dict.fromkeys(group_columns))+ row.update(_metric_columns(endpoint_config, result.get("Total") or {}))+ return [row]++ rows: list[dict[str, Any]] = []+ for group in groups:+ row = dict(base)+ keys = group.get("Keys") or []+ for index, column in enumerate(group_columns):+ row[column] = keys[index] if index < len(keys) else None+ row.update(_metric_columns(endpoint_config, group.get("Metrics") or {}))+ rows.append(row)+ return rows+++def normalize_results(endpoint_config: CostExplorerEndpointConfig, body: dict[str, Any]) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []++ for result in body.get(endpoint_config.result_key) or []:+ period = result.get("TimePeriod") or {}+ base: dict[str, Any] = {+ "period_start": _parse_period(period.get("Start")),+ "period_end": _parse_period(period.get("End")),+ "granularity": endpoint_config.granularity,+ }++ if endpoint_config.metrics:+ # Recent periods come back estimated and are restated later; the lookback rewind+ # re-merges them once finalized. Only the cost operations report it.+ base["estimated"] = result.get("Estimated")+ rows.extend(_cost_rows(endpoint_config, base, result))+ continue++ row = dict(base)+ for member, prefix in endpoint_config.nested_keys:+ row.update(_flatten(prefix, result.get(member) or {}))+ rows.append(row)++ return rows+++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) -> AwsCostExplorerError:+ code = _error_code(response)+ text = f"AWS Cost Explorer 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 AwsCostExplorerThrottledError(text)+ return AwsCostExplorerError(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(AwsCostExplorerThrottledError),+ 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 validate_credentials(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+) -> tuple[bool, Optional[str]]:+ """One cheap `GetCostAndUsage` probe — the exact permission every table needs."""+ if not aws_access_key_id or not aws_secret_access_key:+ return False, "AWS access key ID and secret access key are required"++ end = dt.datetime.now(dt.UTC).date() + dt.timedelta(days=1)+ payload = {+ "TimePeriod": {"Start": (end - dt.timedelta(days=2)).isoformat(), "End": end.isoformat()},+ "Granularity": "DAILY",+ "Metrics": ["UnblendedCost"],+ }++ try:+ send_operation(+ make_session(aws_secret_access_key, aws_session_token),+ Credentials(aws_access_key_id, aws_secret_access_key, aws_session_token or None),+ "GetCostAndUsage",+ payload,+ )+ except AwsCostExplorerError as error:+ return False, str(error)+ except Exception:+ return False, "Could not reach the AWS Cost Explorer API"++ return True, None+++def _resume_index(+ windows: list[TimeWindow], resume: Optional[AwsCostExplorerResumeConfig]+) -> tuple[int, Optional[str]]:+ """Where to pick up. A saved window that no longer exists (the range moved) restarts the run."""+ if resume is None:+ return 0, None++ for index, window in enumerate(windows):+ if window.start.isoformat() == resume.window_start:+ return index, resume.next_page_token++ return 0, None+++def get_rows(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+ start_date: Optional[str],+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[AwsCostExplorerResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ endpoint_config = AWS_COST_EXPLORER_ENDPOINTS[endpoint]++ session = make_session(aws_secret_access_key, aws_session_token)+ credentials = Credentials(aws_access_key_id, aws_secret_access_key, aws_session_token or None)++ # `End` is exclusive, so tomorrow captures today's partial (flagged estimated) too.+ end = dt.datetime.now(dt.UTC).date() + dt.timedelta(days=1)+ start = resolve_start_date(+ start_date, endpoint_config, should_use_incremental_field, db_incremental_field_last_value, end+ )+ windows = build_windows(start, end, endpoint_config.window_days)+ if not windows:+ resumable_source_manager.clear_state()+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ index, page_token = _resume_index(windows, resume)+ if resume is not None:+ logger.debug(f"Resuming AWS Cost Explorer sync. endpoint={endpoint}, window={windows[index].start}")++ for window in windows[index:]:+ while True:+ body = send_operation(+ session, credentials, endpoint_config.operation, build_payload(endpoint_config, window, page_token)+ )+ rows = normalize_results(endpoint_config, body)+ if rows:+ yield rows++ page_token = body.get(endpoint_config.page_token_key) if endpoint_config.page_token_key else None+ # Saved after yielding: a crash re-yields the last batch, which merges away on the+ # primary key, rather than skipping it.+ resumable_source_manager.save_state(+ AwsCostExplorerResumeConfig(window_start=window.start.isoformat(), next_page_token=page_token)+ )++ if not page_token:+ break++ page_token = None++ resumable_source_manager.clear_state()+++def aws_cost_explorer_source(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+ start_date: Optional[str],+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[AwsCostExplorerResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ endpoint_config = AWS_COST_EXPLORER_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,+ start_date=start_date,+ 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=["period_start"],+ partition_mode="datetime",+ partition_format="month",+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/canonical_descriptions.pynew file mode 100644index 000000000000..e0012052c8cb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/canonical_descriptions.py@@ -0,0 +1,85 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_COST_AND_USAGE_DOCS_URL = (+ "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetCostAndUsage.html"+)++_COST_AND_USAGE_COLUMNS: dict[str, str] = {+ "period_start": "Inclusive start of the billing period the row covers.",+ "period_end": "Exclusive end of the billing period the row covers.",+ "granularity": "Bucket size AWS aggregated the period to (DAILY or MONTHLY).",+ "estimated": "Whether the amounts are still estimated. AWS restates recent periods until the bill finalizes.",+ "service": "AWS service the cost is attributed to, from the SERVICE dimension (for example 'Amazon Elastic Compute Cloud - Compute').",+ "linked_account": "Account ID of the member account the cost belongs to, from the LINKED_ACCOUNT dimension.",+ "amortized_cost_amount": "Effective cost with upfront reservation and Savings Plans fees spread across the periods they cover.",+ "amortized_cost_unit": "Currency of the amortized cost.",+ "blended_cost_amount": "Cost calculated with the blended rate, the average rate across the accounts in the organization.",+ "blended_cost_unit": "Currency of the blended cost.",+ "net_amortized_cost_amount": "Amortized cost after all discounts have been applied.",+ "net_amortized_cost_unit": "Currency of the net amortized cost.",+ "net_unblended_cost_amount": "Unblended cost after all discounts have been applied.",+ "net_unblended_cost_unit": "Currency of the net unblended cost.",+ "unblended_cost_amount": "Charges as they appear on the bill before amortization, using the account's own rates.",+ "unblended_cost_unit": "Currency of the unblended cost.",+ "usage_quantity_amount": "Amount of usage recorded for the period. Only meaningful when the rows share one usage type, since AWS sums across usage types with different units.",+ "usage_quantity_unit": "Unit the usage quantity is measured in.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "cost_and_usage_daily": {+ "description": "Daily AWS cost and usage from Cost Explorer, grouped by service and linked account.",+ "docs_url": _COST_AND_USAGE_DOCS_URL,+ "columns": _COST_AND_USAGE_COLUMNS,+ },+ "cost_and_usage_monthly": {+ "description": "Monthly AWS cost and usage from Cost Explorer, grouped by service and linked account.",+ "docs_url": _COST_AND_USAGE_DOCS_URL,+ "columns": _COST_AND_USAGE_COLUMNS,+ },+ "reservation_utilization_daily": {+ "description": "Daily Reserved Instance utilization and savings totals across the account.",+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetReservationUtilization.html",+ "columns": {+ "period_start": "Inclusive start of the period the utilization covers.",+ "period_end": "Exclusive end of the period the utilization covers.",+ "granularity": "Bucket size AWS aggregated the period to (DAILY).",+ "utilization_percentage": "Percentage of the purchased reservation hours that were used.",+ "utilization_percentage_in_units": "Percentage of the purchased reservation normalized units that were used.",+ "purchased_hours": "Reservation hours purchased for the period.",+ "purchased_units": "Reservation normalized units purchased for the period.",+ "total_actual_hours": "Reservation hours actually used in the period.",+ "total_actual_units": "Reservation normalized units actually used in the period.",+ "unused_hours": "Purchased reservation hours that went unused.",+ "unused_units": "Purchased reservation normalized units that went unused.",+ "on_demand_cost_of_ri_hours_used": "What the used reservation hours would have cost at On-Demand rates.",+ "net_ri_savings": "Savings from the reservations after subtracting their upfront and recurring fees.",+ "total_potential_ri_savings": "Savings that would have been made had every purchased reservation hour been used.",+ "amortized_upfront_fee": "Upfront reservation fee spread over the period.",+ "amortized_recurring_fee": "Recurring monthly reservation fee spread over the period.",+ "total_amortized_fee": "Total amortized reservation fee for the period.",+ "ri_cost_for_unused_hours": "Cost of the reservation hours that went unused.",+ "realized_savings": "Savings realized from used reservation hours, net of the amortized fees.",+ "unrealized_savings": "Savings that were missed because reservation hours went unused.",+ },+ },+ "savings_plans_utilization_daily": {+ "description": "Daily Savings Plans commitment utilization and net savings across the account.",+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetSavingsPlansUtilization.html",+ "columns": {+ "period_start": "Inclusive start of the period the utilization covers.",+ "period_end": "Exclusive end of the period the utilization covers.",+ "granularity": "Bucket size AWS aggregated the period to (DAILY).",+ "total_commitment": "Total Savings Plans commitment for the period.",+ "used_commitment": "Amount of the commitment that was used.",+ "unused_commitment": "Amount of the commitment that went unused.",+ "utilization_percentage": "Share of the commitment that was used, as a percentage.",+ "savings_net_savings": "Savings from the Savings Plans compared to paying On-Demand rates.",+ "savings_on_demand_cost_equivalent": "What the Savings Plans usage would have cost at On-Demand rates.",+ "amortized_commitment_amortized_recurring_commitment": "Recurring Savings Plans fee spread over the period.",+ "amortized_commitment_amortized_upfront_commitment": "Upfront Savings Plans fee spread over the period.",+ "amortized_commitment_total_amortized_commitment": "Total amortized Savings Plans commitment for the period.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/settings.pynew file mode 100644index 000000000000..52c2afe9ef94--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/settings.py@@ -0,0 +1,126 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Cost Explorer is 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"++# Cost Explorer keeps 12 months of history for most operations, so a first sync with no+# explicit start date walks back a year.+DEFAULT_LOOKBACK_DAYS = 365++COST_METRICS = (+ "AmortizedCost",+ "BlendedCost",+ "NetAmortizedCost",+ "NetUnblendedCost",+ "UnblendedCost",+ "UsageQuantity",+)+++@dataclass(frozen=True)+class CostExplorerEndpointConfig:+ name: str+ # Operation name, dispatched through the `X-Amz-Target` header.+ operation: str+ granularity: str+ # Response key holding the list of per-time-period results.+ result_key: str+ primary_key: list[str]+ # Pagination token key, identical in the request and the response. `None` for operations+ # that return everything in one shot (GetSavingsPlansUtilization).+ page_token_key: str | None = None+ metrics: tuple[str, ...] = ()+ group_by: tuple[str, ...] = ()+ # Days covered by a single request window. The API bills $0.01 per paginated request, so+ # windows are deliberately wide.+ window_days: int = 92+ # Cost Explorer restates recent periods (they come back flagged `Estimated`), so an+ # incremental run rewinds this far behind the stored watermark and re-merges.+ restatement_lookback_days: int = 7+ # Response sub-structures to flatten into the row, as (member name, column prefix) pairs.+ # An empty prefix keeps the sub-structure's own field names.+ nested_keys: tuple[tuple[str, str], ...] = field(default_factory=tuple)+++AWS_COST_EXPLORER_ENDPOINTS: dict[str, CostExplorerEndpointConfig] = {+ "cost_and_usage_daily": CostExplorerEndpointConfig(+ name="cost_and_usage_daily",+ operation="GetCostAndUsage",+ granularity="DAILY",+ result_key="ResultsByTime",+ primary_key=["period_start", "service", "linked_account"],+ page_token_key="NextPageToken",+ metrics=COST_METRICS,+ group_by=("SERVICE", "LINKED_ACCOUNT"),+ window_days=92,+ restatement_lookback_days=7,+ ),+ "cost_and_usage_monthly": CostExplorerEndpointConfig(+ name="cost_and_usage_monthly",+ operation="GetCostAndUsage",+ granularity="MONTHLY",+ result_key="ResultsByTime",+ primary_key=["period_start", "service", "linked_account"],+ page_token_key="NextPageToken",+ metrics=COST_METRICS,+ group_by=("SERVICE", "LINKED_ACCOUNT"),+ window_days=366,+ restatement_lookback_days=45,+ ),+ "reservation_utilization_daily": CostExplorerEndpointConfig(+ name="reservation_utilization_daily",+ operation="GetReservationUtilization",+ granularity="DAILY",+ result_key="UtilizationsByTime",+ primary_key=["period_start"],+ page_token_key="NextPageToken",+ window_days=92,+ restatement_lookback_days=7,+ nested_keys=(("Total", ""),),+ ),+ "savings_plans_utilization_daily": CostExplorerEndpointConfig(+ name="savings_plans_utilization_daily",+ operation="GetSavingsPlansUtilization",+ granularity="DAILY",+ result_key="SavingsPlansUtilizationsByTime",+ primary_key=["period_start"],+ page_token_key=None,+ window_days=92,+ restatement_lookback_days=7,+ nested_keys=(+ ("Utilization", ""),+ ("Savings", "savings"),+ ("AmortizedCommitment", "amortized_commitment"),+ ),+ ),+}++ENDPOINTS = tuple(AWS_COST_EXPLORER_ENDPOINTS.keys())++# `period_start` is the window boundary the API itself filters on, so it is the only honest+# cursor: every operation takes a server-side `TimePeriod` and nothing else.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: [+ {+ "label": "period_start",+ "type": IncrementalFieldType.DateTime,+ "field": "period_start",+ "field_type": IncrementalFieldType.DateTime,+ }+ ]+ for name in ENDPOINTS+}++ENDPOINT_DESCRIPTIONS: dict[str, str] = {+ "cost_and_usage_daily": "Daily cost and usage metrics grouped by AWS service and linked account.",+ "cost_and_usage_monthly": "Monthly cost and usage metrics grouped by AWS service and linked account.",+ "reservation_utilization_daily": "Daily Reserved Instance utilization and savings totals.",+ "savings_plans_utilization_daily": "Daily Savings Plans commitment utilization and net savings.",+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/source.pyindex d45a47c961cc..cded554800fa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/source.py@@ -1,13 +1,38 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer.aws_cost_explorer import (+ AwsCostExplorerResumeConfig,+ aws_cost_explorer_source,+ validate_credentials as validate_aws_cost_explorer_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer.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.generated_configs.awscostexplorer import (AwsCostExplorerSourceConfig,)@@ -15,18 +40,131 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AwsCostExplorerSource(SimpleSource[AwsCostExplorerSourceConfig]):+class AwsCostExplorerSource(ResumableSource[AwsCostExplorerSourceConfig, AwsCostExplorerResumeConfig]):+ 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.AWSCOSTEXPLORER+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "AWS Cost Explorer 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 Explorer 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 Explorer request failed: SignatureDoesNotMatch": "AWS rejected the request signature. Please re-enter the secret access key.",+ "AWS Cost Explorer request failed: InvalidSignatureException": "AWS rejected the request signature. If you are using temporary credentials, the session token has expired.",+ "AWS Cost Explorer request failed: ExpiredTokenException": "The AWS session token has expired. Please reconnect with fresh credentials.",+ "AWS Cost Explorer request failed: AccessDeniedException": "These AWS credentials are missing Cost Explorer permissions. Grant ce:GetCostAndUsage, ce:GetReservationUtilization and ce:GetSavingsPlansUtilization to the IAM user or role.",+ "AWS Cost Explorer request failed: DataUnavailableException": "AWS has no Cost Explorer data for the requested dates. Cost Explorer has to be enabled on the account, and it can take up to 24 hours to prepare data.",+ "AWS Cost Explorer request failed: BillExpirationException": "The requested dates are older than the data AWS keeps. Move the start date forward and try again.",+ "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_explorer.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AwsCostExplorerSourceConfig,+ 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: AwsCostExplorerSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_aws_cost_explorer_credentials(+ config.aws_access_key_id,+ config.aws_secret_access_key,+ config.aws_session_token,+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AwsCostExplorerResumeConfig]:+ return ResumableSourceManager[AwsCostExplorerResumeConfig](inputs, AwsCostExplorerResumeConfig)++ def source_for_pipeline(+ self,+ config: AwsCostExplorerSourceConfig,+ resumable_source_manager: ResumableSourceManager[AwsCostExplorerResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return aws_cost_explorer_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,+ start_date=config.start_date,+ 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_EXPLORER,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,- label="Amazon Web Services (AWS Cost Explorer)",+ label="AWS Cost Explorer",+ caption="""Sync your AWS cost and usage data into the PostHog Data warehouse.++Create an IAM user or role with the `ce:GetCostAndUsage`, `ce:GetReservationUtilization` and `ce:GetSavingsPlansUtilization` permissions, then paste its access key ID and secret access key. Add a session token too if you are using temporary credentials.++Connect the management (payer) account to see spend across every member account. AWS charges $0.01 per Cost Explorer API request, so syncs ask for wide date ranges at a time.""",iconPath="/static/services/aws_cost_explorer.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/aws-cost-explorer",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["aws", "finops", "cloud spend", "cost explorer"],+ 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 (only for temporary credentials)",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="start_date",+ label="Start date (defaults to 12 months ago)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="2024-01-01",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.pynew file mode 100644index 000000000000..1a487aa3c4fe--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.py@@ -0,0 +1,571 @@+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_explorer import aws_cost_explorer+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer.aws_cost_explorer import (+ AwsCostExplorerError,+ AwsCostExplorerResumeConfig,+ AwsCostExplorerThrottledError,+ build_payload,+ build_windows,+ error_for_response,+ get_rows,+ normalize_results,+ resolve_start_date,+ send_operation,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer.settings import (+ AWS_COST_EXPLORER_ENDPOINTS,+ CE_ENDPOINT_URL,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++LOGGER = structlog.get_logger()++COST_DAILY = AWS_COST_EXPLORER_ENDPOINTS["cost_and_usage_daily"]+RESERVATION = AWS_COST_EXPLORER_ENDPOINTS["reservation_utilization_daily"]+SAVINGS_PLANS = AWS_COST_EXPLORER_ENDPOINTS["savings_plans_utilization_daily"]+++def without_retry_backoff(monkeypatch: pytest.MonkeyPatch) -> None:+ """Keep the throttling retry's behaviour but drop its wait, so tests stay fast."""+ monkeypatch.setattr(cast(Any, send_operation).retry, "wait", wait_none())+++class FakeResumeManager(ResumableSourceManager[AwsCostExplorerResumeConfig]):+ def __init__(self, state: Optional[AwsCostExplorerResumeConfig] = None) -> None:+ self.state = state+ self.saved: list[AwsCostExplorerResumeConfig] = []+ self.cleared = False++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> Optional[AwsCostExplorerResumeConfig]:+ return self.state++ def save_state(self, data: AwsCostExplorerResumeConfig) -> 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 cost_page(groups: list[dict[str, Any]], next_page_token: Optional[str] = None) -> dict[str, Any]:+ body: dict[str, Any] = {+ "ResultsByTime": [+ {+ "TimePeriod": {"Start": "2024-03-01", "End": "2024-03-02"},+ "Estimated": False,+ "Groups": groups,+ "Total": {},+ }+ ]+ }+ if next_page_token is not None:+ body["NextPageToken"] = next_page_token+ return body+++class TestWindows:+ @pytest.mark.parametrize(+ "start,end,window_days,expected",+ [+ # Exclusive end: the final window stops exactly on `end`.+ (+ "2024-01-01",+ "2024-01-11",+ 4,+ [("2024-01-01", "2024-01-05"), ("2024-01-05", "2024-01-09"), ("2024-01-09", "2024-01-11")],+ ),+ ("2024-01-01", "2024-01-05", 4, [("2024-01-01", "2024-01-05")]),+ ("2024-01-01", "2024-01-02", 92, [("2024-01-01", "2024-01-02")]),+ # A start on or past the end asks AWS for nothing at all.+ ("2024-01-05", "2024-01-05", 92, []),+ ("2024-01-06", "2024-01-05", 92, []),+ ],+ )+ def test_windows_tile_the_range_without_gaps_or_overlap(+ self, start: str, end: str, window_days: int, expected: list[tuple[str, str]]+ ) -> None:+ windows = build_windows(dt.date.fromisoformat(start), dt.date.fromisoformat(end), window_days)++ assert [(w.start.isoformat(), w.end.isoformat()) for w in windows] == expected+++class TestResolveStartDate:+ END = dt.date(2024, 6, 1)++ def test_defaults_to_a_year_back_when_no_start_date_is_configured(self) -> None:+ assert resolve_start_date(None, COST_DAILY, False, None, self.END) == dt.date(2023, 6, 2)++ @pytest.mark.parametrize("configured", ["2024-01-01", "2024-01-01T00:00:00Z"])+ def test_uses_the_configured_start_date_on_a_full_refresh(self, configured: str) -> None:+ assert resolve_start_date(configured, COST_DAILY, False, None, self.END) == dt.date(2024, 1, 1)++ @pytest.mark.parametrize(+ "watermark",+ [+ "2024-05-20",+ dt.date(2024, 5, 20),+ dt.datetime(2024, 5, 20, 13, 45, tzinfo=dt.UTC),+ ],+ )+ def test_incremental_rewinds_behind_the_watermark_to_re_read_restated_periods(self, watermark: Any) -> None:+ # AWS keeps restating recent periods, so the window has to reach back behind the cursor.+ assert resolve_start_date("2024-01-01", COST_DAILY, True, watermark, self.END) == dt.date(2024, 5, 13)++ def test_incremental_never_reaches_before_the_configured_start_date(self) -> None:+ assert resolve_start_date("2024-05-15", COST_DAILY, True, "2024-05-16", self.END) == dt.date(2024, 5, 15)++ def test_monthly_rewinds_further_than_daily(self) -> None:+ monthly = AWS_COST_EXPLORER_ENDPOINTS["cost_and_usage_monthly"]++ assert resolve_start_date("2023-01-01", monthly, True, "2024-05-20", self.END) == dt.date(2024, 4, 5)++ def test_a_watermark_past_the_end_is_clamped_so_no_window_is_requested(self) -> None:+ assert resolve_start_date("2024-01-01", COST_DAILY, True, "2025-01-01", self.END) == self.END++ def test_ignores_an_unparseable_watermark(self) -> None:+ assert resolve_start_date("2024-01-01", COST_DAILY, True, "not-a-date", self.END) == dt.date(2024, 1, 1)+++class TestBuildPayload:+ WINDOW = aws_cost_explorer.TimeWindow(start=dt.date(2024, 3, 1), end=dt.date(2024, 4, 1))++ def test_cost_payload_carries_the_time_window_metrics_and_group_by(self) -> None:+ payload = build_payload(COST_DAILY, self.WINDOW, None)++ assert payload["TimePeriod"] == {"Start": "2024-03-01", "End": "2024-04-01"}+ assert payload["Granularity"] == "DAILY"+ assert payload["Metrics"] == list(COST_DAILY.metrics)+ assert payload["GroupBy"] == [+ {"Type": "DIMENSION", "Key": "SERVICE"},+ {"Type": "DIMENSION", "Key": "LINKED_ACCOUNT"},+ ]+ assert "NextPageToken" not in payload++ def test_page_token_is_sent_under_the_endpoints_own_key(self) -> None:+ assert build_payload(COST_DAILY, self.WINDOW, "tok")["NextPageToken"] == "tok"++ def test_endpoints_without_metrics_or_grouping_send_neither(self) -> None:+ payload = build_payload(RESERVATION, self.WINDOW, None)++ assert "Metrics" not in payload+ assert "GroupBy" not in payload++ def test_a_token_is_never_sent_to_an_operation_that_cannot_paginate(self) -> None:+ # GetSavingsPlansUtilization has no pagination; sending a token would be rejected.+ assert build_payload(SAVINGS_PLANS, self.WINDOW, "tok") == {+ "TimePeriod": {"Start": "2024-03-01", "End": "2024-04-01"},+ "Granularity": "DAILY",+ }+++class TestNormalizeResults:+ def test_grouped_costs_fan_out_one_row_per_group_with_dimensions_mapped_in_order(self) -> None:+ rows = normalize_results(+ COST_DAILY,+ cost_page(+ [+ {+ "Keys": ["Amazon Elastic Compute Cloud - Compute", "123456789012"],+ "Metrics": {+ "UnblendedCost": {"Amount": "12.5", "Unit": "USD"},+ "UsageQuantity": {"Amount": "3", "Unit": "Hrs"},+ },+ },+ {+ "Keys": ["AmazonS3", "210987654321"],+ "Metrics": {"UnblendedCost": {"Amount": "0.4", "Unit": "USD"}},+ },+ ]+ ),+ )++ assert len(rows) == 2+ assert rows[0]["period_start"] == dt.datetime(2024, 3, 1, tzinfo=dt.UTC)+ assert rows[0]["period_end"] == dt.datetime(2024, 3, 2, tzinfo=dt.UTC)+ assert rows[0]["granularity"] == "DAILY"+ assert rows[0]["estimated"] is False+ assert rows[0]["service"] == "Amazon Elastic Compute Cloud - Compute"+ assert rows[0]["linked_account"] == "123456789012"+ assert rows[0]["unblended_cost_amount"] == 12.5+ assert rows[0]["unblended_cost_unit"] == "USD"+ assert rows[0]["usage_quantity_amount"] == 3.0+ assert rows[1]["service"] == "AmazonS3"+ assert rows[1]["linked_account"] == "210987654321"++ def test_every_configured_metric_gets_a_column_even_when_aws_omits_it(self) -> None:+ # Otherwise the Arrow schema would shift between pages depending on which metrics AWS returned.+ rows = normalize_results(+ COST_DAILY,+ cost_page([{"Keys": ["AmazonS3", "1"], "Metrics": {"UnblendedCost": {"Amount": "1", "Unit": "USD"}}}]),+ )++ for metric_column in ("amortized_cost", "blended_cost", "net_amortized_cost", "net_unblended_cost"):+ assert rows[0][f"{metric_column}_amount"] is None+ assert rows[0][f"{metric_column}_unit"] is None++ def test_an_ungrouped_period_falls_back_to_the_period_total(self) -> None:+ rows = normalize_results(+ COST_DAILY,+ {+ "ResultsByTime": [+ {+ "TimePeriod": {"Start": "2024-03-01", "End": "2024-03-02"},+ "Estimated": True,+ "Groups": [],+ "Total": {"UnblendedCost": {"Amount": "9.75", "Unit": "USD"}},+ }+ ]+ },+ )++ assert len(rows) == 1+ assert rows[0]["service"] is None+ assert rows[0]["linked_account"] is None+ assert rows[0]["estimated"] is True+ assert rows[0]["unblended_cost_amount"] == 9.75+ assert rows[0]["unblended_cost_unit"] == "USD"++ def test_reservation_totals_are_flattened_into_snake_cased_columns(self) -> None:+ rows = normalize_results(+ RESERVATION,+ {+ "UtilizationsByTime": [+ {+ "TimePeriod": {"Start": "2024-03-01", "End": "2024-03-02"},+ "Total": {+ "UtilizationPercentage": "97.5",+ "NetRISavings": "120.25",+ "OnDemandCostOfRIHoursUsed": "400",+ "RICostForUnusedHours": "1.5",+ },+ }+ ]+ },+ )++ assert rows[0]["utilization_percentage"] == 97.5+ assert rows[0]["net_ri_savings"] == 120.25+ assert rows[0]["on_demand_cost_of_ri_hours_used"] == 400.0+ assert rows[0]["ri_cost_for_unused_hours"] == 1.5++ def test_savings_plans_sub_structures_flatten_into_non_colliding_columns(self) -> None:+ rows = normalize_results(+ SAVINGS_PLANS,+ {+ "SavingsPlansUtilizationsByTime": [+ {+ "TimePeriod": {"Start": "2024-03-01", "End": "2024-03-02"},+ "Utilization": {"TotalCommitment": "100", "UtilizationPercentage": "88"},+ "Savings": {"NetSavings": "12"},+ "AmortizedCommitment": {"TotalAmortizedCommitment": "100"},+ }+ ]+ },+ )++ assert rows[0]["total_commitment"] == 100.0+ assert rows[0]["utilization_percentage"] == 88.0+ assert rows[0]["savings_net_savings"] == 12.0+ assert rows[0]["amortized_commitment_total_amortized_commitment"] == 100.0++ def test_an_empty_response_yields_no_rows(self) -> None:+ assert normalize_results(COST_DAILY, {}) == []+++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, AwsCostExplorerThrottledError)+ assert f"AWS Cost Explorer request failed: {code}" in str(error)++ @pytest.mark.parametrize(+ "code",+ ["AccessDeniedException", "UnrecognizedClientException", "ExpiredTokenException", "DataUnavailableException"],+ )+ 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, AwsCostExplorerThrottledError)+ assert str(error) == f"AWS Cost Explorer 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 Explorer 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>"++ error = error_for_response(response)++ assert not isinstance(error, AwsCostExplorerThrottledError)+ assert "HTTP 503" in str(error)+++class TestSendOperation:+ def test_requests_are_sigv4_signed_and_dispatched_via_x_amz_target(self) -> None:+ session = mock.MagicMock(spec=requests.Session)+ session.post.return_value = make_response(200, {"ResultsByTime": []})+ credentials = aws_cost_explorer.Credentials("AKIAEXAMPLE", "secret")++ with freeze_time("2024-03-05T10:00:00Z"):+ send_operation(session, credentials, "GetCostAndUsage", {"Granularity": "DAILY"})++ _, kwargs = session.post.call_args+ assert session.post.call_args[0][0] == CE_ENDPOINT_URL+ assert kwargs["headers"]["X-Amz-Target"] == "AWSInsightsIndexService.GetCostAndUsage"+ assert kwargs["headers"]["Content-Type"] == "application/x-amz-json-1.1"+ assert kwargs["headers"]["X-Amz-Date"] == "20240305T100000Z"+ assert kwargs["headers"]["Authorization"].startswith(+ "AWS4-HMAC-SHA256 Credential=AKIAEXAMPLE/20240305/us-east-1/ce/aws4_request"+ )+ assert json.loads(kwargs["data"]) == {"Granularity": "DAILY"}++ 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_explorer.Credentials("AKIAEXAMPLE", "secret", "session-token")++ send_operation(session, credentials, "GetCostAndUsage", {})++ 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, {"ResultsByTime": []}),+ ]++ body = send_operation(session, aws_cost_explorer.Credentials("k", "s"), "GetCostAndUsage", {})++ assert body == {"ResultsByTime": []}+ 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(AwsCostExplorerError):+ send_operation(session, aws_cost_explorer.Credentials("k", "s"), "GetCostAndUsage", {})++ assert session.post.call_count == 1+++class TestValidateCredentials:+ def test_missing_credentials_short_circuit_without_a_billed_request(self) -> None:+ with mock.patch.object(aws_cost_explorer, "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(self) -> None:+ with mock.patch.object(aws_cost_explorer, "send_operation", return_value={"ResultsByTime": []}) as send:+ assert validate_credentials("key", "secret", None) == (True, None)++ assert send.call_args[0][2] == "GetCostAndUsage"++ def test_an_api_error_is_surfaced_to_the_user(self) -> None:+ error = AwsCostExplorerError("AWS Cost Explorer request failed: AccessDeniedException - denied")++ with mock.patch.object(aws_cost_explorer, "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_explorer, "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-03-03T12:00:00Z")+class TestGetRows:+ def _run(+ self,+ responses: list[dict[str, Any]],+ manager: FakeResumeManager,+ endpoint: str = "cost_and_usage_daily",+ start_date: Optional[str] = "2024-03-01",+ 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_explorer, "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,+ start_date=start_date,+ 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:+ manager = FakeResumeManager()++ batches, send = self._run(+ [+ cost_page([{"Keys": ["AmazonS3", "1"], "Metrics": {}}], next_page_token="page-2"),+ cost_page([{"Keys": ["AmazonEC2", "1"], "Metrics": {}}]),+ ],+ manager,+ )++ assert send.call_count == 2+ assert [row["service"] for batch in batches for row in batch] == ["AmazonS3", "AmazonEC2"]+ assert send.call_args_list[0][0][3].get("NextPageToken") is None+ assert send.call_args_list[1][0][3]["NextPageToken"] == "page-2"++ def test_state_is_saved_after_each_page_and_cleared_once_the_range_is_walked(self) -> None:+ manager = FakeResumeManager()++ self._run(+ [+ cost_page([{"Keys": ["AmazonS3", "1"], "Metrics": {}}], next_page_token="page-2"),+ cost_page([{"Keys": ["AmazonEC2", "1"], "Metrics": {}}]),+ ],+ manager,+ )++ assert manager.saved == [+ AwsCostExplorerResumeConfig(window_start="2024-03-01", next_page_token="page-2"),+ AwsCostExplorerResumeConfig(window_start="2024-03-01", next_page_token=None),+ ]+ assert manager.cleared is True++ def test_a_saved_state_resumes_the_same_window_at_the_saved_page(self) -> None:+ manager = FakeResumeManager(AwsCostExplorerResumeConfig(window_start="2024-03-01", next_page_token="page-7"))++ _, send = self._run([cost_page([{"Keys": ["AmazonS3", "1"], "Metrics": {}}])], manager)++ assert send.call_count == 1+ assert send.call_args_list[0][0][3]["NextPageToken"] == "page-7"++ def test_a_stale_saved_window_restarts_the_range_rather_than_skipping_data(self) -> None:+ # The window list shifts whenever the incremental watermark moves, so a token from a+ # window that no longer exists must not silently skip the windows before it.+ manager = FakeResumeManager(AwsCostExplorerResumeConfig(window_start="2019-01-01", next_page_token="stale"))++ _, send = self._run([cost_page([{"Keys": ["AmazonS3", "1"], "Metrics": {}}])], manager)++ assert send.call_args_list[0][0][3]["TimePeriod"] == {"Start": "2024-03-01", "End": "2024-03-04"}+ assert "NextPageToken" not in send.call_args_list[0][0][3]++ def test_the_window_ends_tomorrow_so_todays_partial_costs_are_included(self) -> None:+ manager = FakeResumeManager()++ _, send = self._run([cost_page([])], manager)++ assert send.call_args_list[0][0][3]["TimePeriod"]["End"] == "2024-03-04"++ def test_wide_ranges_are_split_into_windows_walked_oldest_first(self) -> None:+ manager = FakeResumeManager()++ _, send = self._run([cost_page([]), cost_page([]), cost_page([])], manager, start_date="2023-09-01")++ boundaries = [+ (call[0][3]["TimePeriod"]["Start"], call[0][3]["TimePeriod"]["End"]) for call in send.call_args_list+ ]+ assert boundaries == [+ ("2023-09-01", "2023-12-02"),+ ("2023-12-02", "2024-03-03"),+ ("2024-03-03", "2024-03-04"),+ ]++ def test_an_incremental_run_asks_aws_only_for_the_restated_tail(self) -> None:+ manager = FakeResumeManager()++ _, send = self._run(+ [cost_page([])],+ manager,+ start_date="2023-01-01",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-03-01",+ )++ assert send.call_count == 1+ assert send.call_args_list[0][0][3]["TimePeriod"] == {"Start": "2024-02-23", "End": "2024-03-04"}++ def test_an_operation_without_pagination_issues_exactly_one_request_per_window(self) -> None:+ manager = FakeResumeManager()++ batches, send = self._run(+ [+ {+ "SavingsPlansUtilizationsByTime": [+ {+ "TimePeriod": {"Start": "2024-03-01", "End": "2024-03-02"},+ "Utilization": {"TotalCommitment": "10"},+ }+ ],+ # A stray token must not restart the loop for an unpaginated operation.+ "NextPageToken": "ignored",+ }+ ],+ manager,+ endpoint="savings_plans_utilization_daily",+ )++ assert send.call_count == 1+ assert batches[0][0]["total_commitment"] == 10.0++ def test_nothing_is_requested_when_the_watermark_is_already_current(self) -> None:+ manager = FakeResumeManager()++ batches, send = self._run([], manager, start_date="2024-03-04")++ assert batches == []+ assert send.call_count == 0+ assert manager.cleared is Truediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer_source.pynew file mode 100644index 000000000000..fc851ea5af2a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer_source.py@@ -0,0 +1,210 @@+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.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer import (+ aws_cost_explorer as transport_module,+ source as source_module,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer.aws_cost_explorer import (+ AwsCostExplorerResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer.settings import (+ AWS_COST_EXPLORER_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cost_explorer.source import (+ AwsCostExplorerSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awscostexplorer import (+ AwsCostExplorerSourceConfig,+)+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="period_start",+ incremental_field_type=None,+ job_id="job-id",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestAwsCostExplorerSource:+ def setup_method(self) -> None:+ self.source = AwsCostExplorerSource()+ self.config = AwsCostExplorerSourceConfig(+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key="secret",+ aws_session_token=None,+ start_date="2024-01-01",+ )++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.AWSCOSTEXPLORER++ 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_explorer.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/aws-cost-explorer"++ def test_source_config_fields(self) -> None:+ fields = self.source.get_source_config.fields++ assert [field.name for field in fields] == [+ "aws_access_key_id",+ "aws_secret_access_key",+ "aws_session_token",+ "start_date",+ ]++ @pytest.mark.parametrize(+ "field_name,required,secret",+ [+ ("aws_access_key_id", True, False),+ ("aws_secret_access_key", True, True),+ ("aws_session_token", False, True),+ ("start_date", False, False),+ ],+ )+ 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_get_schemas_exposes_every_endpoint_as_incremental_on_the_period_start(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1)++ assert [schema.name for schema in schemas] == list(ENDPOINTS)+ for schema in schemas:+ assert schema.supports_incremental is True+ assert [field["field"] for field in schema.incremental_fields] == ["period_start"]+ assert schema.description++ def test_get_schemas_honors_the_schema_picker_filter(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["cost_and_usage_monthly"])++ assert [schema.name for schema in schemas] == ["cost_and_usage_monthly"]++ 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(AwsCostExplorerSourceConfig(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 Explorer request failed: AccessDeniedException - User is not authorized to perform ce:GetCostAndUsage",+ "AWS Cost Explorer request failed: UnrecognizedClientException - The security token included in the request is invalid",+ "AWS Cost Explorer request failed: ExpiredTokenException - The security token included in the request is expired",+ "AWS Cost Explorer request failed: SignatureDoesNotMatch - Signature expired",+ ],+ )+ 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 Explorer request failed: LimitExceededException - Rate exceeded",+ "AWS Cost Explorer 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_through(self) -> None:+ with mock.patch.object(source_module, "validate_aws_cost_explorer_credentials", return_value=(True, None)) as v:+ assert self.source.validate_credentials(self.config, team_id=1) == (True, None)++ assert v.call_args[0] == ("AKIAEXAMPLE", "secret", None)++ def test_validate_credentials_surfaces_the_transport_failure_reason(self) -> None:+ with mock.patch.object(source_module, "validate_aws_cost_explorer_credentials", return_value=(False, "denied")):+ assert self.source.validate_credentials(self.config, team_id=1) == (False, "denied")++ def test_resumable_manager_is_bound_to_the_sources_resume_dataclass(self) -> None:+ manager = self.source.get_resumable_source_manager(make_inputs("cost_and_usage_daily"))++ assert manager._data_class is AwsCostExplorerResumeConfig++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_source_for_pipeline_uses_the_endpoints_primary_key_and_a_stable_partition_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_EXPLORER_ENDPOINTS[endpoint].primary_key+ assert response.partition_keys == ["period_start"]+ assert response.partition_mode == "datetime"+ assert response.sort_mode == "asc"++ 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_explorer_source") as build:+ inputs = make_inputs("cost_and_usage_daily", 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("cost_and_usage_daily", 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+ assert build.call_args[1]["start_date"] == "2024-01-01"++ def test_items_are_lazy_so_building_the_response_bills_no_api_request(self) -> None:+ inputs = make_inputs("cost_and_usage_daily")+ 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/awscostexplorer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awscostexplorer.pyindex b094320c3579..9bdf8ab8c520 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awscostexplorer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awscostexplorer.py@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AwsCostExplorerSourceConfig(config.Config):- pass+ aws_access_key_id: str+ aws_secret_access_key: str+ aws_session_token: str | None = None+ start_date: str | None = None