Skip to content

: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.

feat(data-warehouse): add savings plans offerings, rates, and recommendations tables (#117712)

Tom Owers74bbc321bdf1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index b8aa29279bf0..c8cd2971f35d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1281,10 +1281,10 @@ Today (4): `coverage_daily`, `savings_plans`, `utilization_daily`, `utilization_
Diffed against: <https://raw.githubusercontent.com/boto/botocore/develop/botocore/data/savingsplans/2019-06-28/service-2.json>
-- [ ] `Savings Plans offerings (DescribeSavingsPlansOfferings, POST /DescribeSavingsPlansOfferings)` — resolve offeringId on synced plans to service, usage type, and offering properties (high)
-- [ ] `Savings Plan rates (DescribeSavingsPlanRates, POST /DescribeSavingsPlanRates)` — compare contracted rates by service, usage type, operation, and billing unit (medium)
-- [ ] `Savings Plans purchase recommendations (GetSavingsPlansPurchaseRecommendation, POST / on Cost Explorer)` — evaluate recommended commitments and expected savings against current utilization and coverage (medium)
-- [ ] `Savings Plan purchase recommendation details (GetSavingsPlanPurchaseRecommendationDetails, POST / on Cost Explorer)` — analyze hourly cost, coverage, and utilization estimates behind each recommendation (medium)
+- [x] `Savings Plans offerings (DescribeSavingsPlansOfferings, POST /DescribeSavingsPlansOfferings)` — resolve offeringId on synced plans to service, usage type, and offering properties (high)
+- [x] `Savings Plan rates (DescribeSavingsPlanRates, POST /DescribeSavingsPlanRates)` — compare contracted rates by service, usage type, operation, and billing unit (medium)
+- [x] `Savings Plans purchase recommendations (GetSavingsPlansPurchaseRecommendation, POST / on Cost Explorer)` — evaluate recommended commitments and expected savings against current utilization and coverage (medium)
+- [x] `Savings Plan purchase recommendation details (GetSavingsPlanPurchaseRecommendationDetails, POST / on Cost Explorer)` — analyze hourly cost, coverage, and utilization estimates behind each recommendation (medium)
- [ ] `Savings Plans offering rates (DescribeSavingsPlansOfferingRates, POST /DescribeSavingsPlansOfferingRates)` — compare prospective contract prices with current plan rates before a purchase (medium)
Note: The Savings Plans SDK model was compared with the static table map. The official ce/2017-10-25/service-2.json model also verifies both missing recommendation operations. Daily coverage and utilization already include the core savings metrics; plan rates require a request for each plan. Recommendations must already exist, while generation, purchase, cancellation, and tagging operations are excluded.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/aws_savings_plans.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/aws_savings_plans.py
index 2dc2a3231f43..20bb4ab56265 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/aws_savings_plans.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/aws_savings_plans.py
@@ -1,6 +1,7 @@
import re
import json
import datetime as dt
+import itertools
from collections.abc import Iterator
from decimal import Decimal
from typing import Any
@@ -18,6 +19,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.aws_saving
DEFAULT_LOOKBACK_DAYS,
ENDPOINTS,
ERROR_MESSAGES,
+ RECOMMENDATION_DECIMAL_FIELDS,
+ RECOMMENDATION_OPTIONS,
RESTATEMENT_DAYS,
SAVINGS_PLANS_API_VERSION,
SIGNING_REGION,
@@ -48,6 +51,7 @@ class AwsSavingsPlansResumeConfig:
window_start: str | None = None
window_end: str | None = None
end_date: str | None = None
+ parent_id: str | None = None
completed: bool = False
@@ -127,8 +131,8 @@ def parse_date(value: Any) -> dt.date | None:
def build_payload(
endpoint: SavingsPlansEndpoint, start: dt.date | None = None, end: dt.date | None = None
) -> dict[str, Any]:
- if endpoint.service == "savingsplans":
- return {"maxResults": 100}
+ if not endpoint.windowed:
+ return {endpoint.page_size_key: endpoint.page_size} if endpoint.page_size_key else {}
if start is None or end is None:
raise ValueError("Cost Explorer requires a start date and an end date")
payload: dict[str, Any] = {"TimePeriod": {"Start": start.isoformat(), "End": end.isoformat()}}
@@ -141,15 +145,47 @@ def build_payload(
return payload
+def snake_case(item: dict[str, Any]) -> dict[str, Any]:
+ return {CAMEL_BOUNDARY.sub("_", key).lower(): value for key, value in item.items()}
+
+
+def recommendation_details(body: dict[str, Any]) -> list[dict[str, Any]]:
+ return (body.get("SavingsPlansPurchaseRecommendation") or {}).get("SavingsPlansPurchaseRecommendationDetails") or []
+
+
+def normalize_recommendation(row: dict[str, Any]) -> dict[str, Any]:
+ row.update(snake_case(row.pop("savings_plans_details", None) or {}))
+ for field in RECOMMENDATION_DECIMAL_FIELDS:
+ if field in row:
+ row[field] = Decimal(row[field]) if row[field] not in (None, "") else None
+ for field in ("generation_timestamp", "latest_usage_timestamp"):
+ if row.get(field):
+ row[field] = dt.datetime.fromisoformat(row[field].replace("Z", "+00:00"))
+ return row
+
+
def normalize_rows(endpoint: SavingsPlansEndpoint, body: dict[str, Any]) -> list[dict[str, Any]]:
+ if endpoint.operation == "GetSavingsPlansPurchaseRecommendation":
+ recommendation = body.get(endpoint.result_key) or {}
+ shared = {
+ key: value
+ for key, value in snake_case({**recommendation, **(body.get("Metadata") or {})}).items()
+ if not isinstance(value, dict | list)
+ }
+ return [normalize_recommendation({**shared, **snake_case(item)}) for item in recommendation_details(body)]
+ if endpoint.operation == "GetSavingsPlanPurchaseRecommendationDetails":
+ detail = body.get(endpoint.result_key)
+ if not detail:
+ return []
+ return [normalize_recommendation(snake_case(detail))]
rows = []
for item in body.get(endpoint.result_key, []):
- row = {CAMEL_BOUNDARY.sub("_", key).lower(): value for key, value in item.items()}
+ row = snake_case(item)
if endpoint.service == "savingsplans":
for field in ("start", "end", "returnable_until"):
if row.get(field):
row[field] = dt.datetime.fromisoformat(row[field].replace("Z", "+00:00"))
- for field in ("commitment", "recurring_payment_amount", "upfront_payment_amount"):
+ for field in ("commitment", "recurring_payment_amount", "upfront_payment_amount", "rate"):
if row.get(field) is not None:
row[field] = Decimal(row[field])
else:
@@ -167,6 +203,72 @@ def normalize_rows(endpoint: SavingsPlansEndpoint, body: dict[str, Any]) -> list
return rows
+def recommendation_options() -> list[tuple[str, dict[str, str]]]:
+ combinations = [
+ dict(zip(options, values))
+ for options in RECOMMENDATION_OPTIONS
+ for values in itertools.product(*options.values())
+ ]
+ return sorted(("|".join(options.values()), options) for options in combinations)
+
+
+def iter_pages(
+ client: AwsSavingsPlansClient,
+ endpoint: SavingsPlansEndpoint,
+ payload: dict[str, Any],
+ manager: ResumableSourceManager[AwsSavingsPlansResumeConfig],
+) -> Iterator[dict[str, Any]]:
+ token = None
+ while True:
+ body = client.request(
+ endpoint, {**payload, endpoint.token_key: token} if token and endpoint.token_key else payload
+ )
+ manager.safe_point()
+ yield body
+ next_token = body.get(endpoint.token_key) if endpoint.token_key else None
+ if not next_token:
+ return
+ if next_token == token:
+ raise ValueError("AWS returned a repeated pagination token")
+ token = next_token
+
+
+def list_parents(
+ client: AwsSavingsPlansClient,
+ endpoint: SavingsPlansEndpoint,
+ manager: ResumableSourceManager[AwsSavingsPlansResumeConfig],
+) -> list[tuple[str, dict[str, Any]]]:
+ if endpoint.fan_out == "savings_plans":
+ plans = ENDPOINTS["savings_plans"]
+ ids = {
+ plan["savingsPlanId"]
+ for body in iter_pages(client, plans, build_payload(plans), manager)
+ for plan in body.get(plans.result_key, [])
+ }
+ return [(plan_id, {"savingsPlanId": plan_id}) for plan_id in sorted(ids)]
+ if endpoint.fan_out == "recommendation_options":
+ return recommendation_options()
+ recommendations = ENDPOINTS["purchase_recommendations"]
+ detail_ids = {
+ detail["RecommendationDetailId"]
+ for _, options in recommendation_options()
+ for body in iter_pages(client, recommendations, {**build_payload(recommendations), **options}, manager)
+ for detail in recommendation_details(body)
+ }
+ return [(detail_id, {"RecommendationDetailId": detail_id}) for detail_id in sorted(detail_ids)]
+
+
+def first_parent(client: AwsSavingsPlansClient, endpoint: SavingsPlansEndpoint) -> dict[str, Any] | None:
+ if endpoint.fan_out == "savings_plans":
+ plans = client.request(ENDPOINTS["savings_plans"], {"maxResults": 1}).get("savingsPlans") or []
+ return {"savingsPlanId": plans[0]["savingsPlanId"]} if plans else None
+ options = recommendation_options()[0][1]
+ if endpoint.fan_out == "recommendation_options":
+ return options
+ details = recommendation_details(client.request(ENDPOINTS["purchase_recommendations"], {**options, "PageSize": 1}))
+ return {"RecommendationDetailId": details[0]["RecommendationDetailId"]} if details else None
+
+
def validation_error(code: str, endpoint: SavingsPlansEndpoint) -> str:
if code.startswith("AccessDenied") or code == "UnauthorizedException":
return f"AWS denied access. Grant {endpoint.service}:{endpoint.operation} to the IAM user or role."
@@ -195,8 +297,16 @@ def validate_credentials(
end = dt.datetime.now(dt.UTC).date() - dt.timedelta(days=1)
payload = build_payload(endpoint, end - dt.timedelta(days=1), end)
if endpoint.token_key:
- payload["maxResults" if endpoint.service == "savingsplans" else "MaxResults"] = 1
- client.request(endpoint, payload)
+ payload[endpoint.page_size_key or "MaxResults"] = 1
+ # A fan-out table can only check its own permission once a parent exists.
+ parent: dict[str, Any] | None = {}
+ if endpoint.fan_out:
+ try:
+ parent = first_parent(client, endpoint)
+ except AwsSavingsPlansError as error:
+ return False, validation_error(error.code, ENDPOINTS.get(endpoint.fan_out, endpoint))
+ if parent is not None:
+ client.request(endpoint, {**payload, **parent})
except AwsSavingsPlansError as error:
if schema_name is None and (error.code.startswith("AccessDenied") or error.code == "UnauthorizedException"):
return True, None
@@ -224,7 +334,7 @@ def get_rows(
end = end or (dt.datetime.now(dt.UTC).date() - dt.timedelta(days=1))
history_floor = end - dt.timedelta(days=DEFAULT_LOOKBACK_DAYS)
floor = max(parse_date(config.start_date) or history_floor, history_floor)
- watermark = parse_date(last_value) if incremental and endpoint.service == "ce" else None
+ watermark = parse_date(last_value) if incremental and endpoint.windowed else None
start = max(floor, watermark - dt.timedelta(days=RESTATEMENT_DAYS)) if watermark else floor
start = (parse_date(resume.window_start) or start) if resume else start
stop = (parse_date(resume.window_end) if resume else None) or min(
@@ -233,7 +343,10 @@ def get_rows(
token = resume.next_token if resume else None
client = AwsSavingsPlansClient(config, api_version)
try:
- while endpoint.service == "savingsplans" or start < end:
+ if endpoint.fan_out:
+ yield from get_fan_out_rows(client, endpoint, manager, resume)
+ return
+ while not endpoint.windowed or start < end:
payload = build_payload(endpoint, start, stop)
if token and endpoint.token_key:
payload[endpoint.token_key] = token
@@ -242,7 +355,7 @@ def get_rows(
next_token = body.get(endpoint.token_key) if endpoint.token_key else None
if next_token and next_token == token:
raise ValueError("AWS returned a repeated pagination token")
- completed = not next_token and (endpoint.service == "savingsplans" or stop >= end)
+ completed = not next_token and (not endpoint.windowed or stop >= end)
next_start = start if next_token else stop
next_stop = stop if next_token else min(stop + dt.timedelta(days=endpoint.window_days), end)
manager.save_state(
@@ -264,6 +377,48 @@ def get_rows(
client.close()
+def get_fan_out_rows(
+ client: AwsSavingsPlansClient,
+ endpoint: SavingsPlansEndpoint,
+ manager: ResumableSourceManager[AwsSavingsPlansResumeConfig],
+ resume: AwsSavingsPlansResumeConfig | None,
+) -> Iterator[list[dict[str, Any]]]:
+ resume_parent = resume.parent_id if resume else None
+ resume_token = resume.next_token if resume else None
+ # Parents are sorted, so a resumed run skips every parent that an earlier attempt finished.
+ parents = [
+ (key, params)
+ for key, params in list_parents(client, endpoint, manager)
+ if resume_parent is None or key > resume_parent or (key == resume_parent and resume_token)
+ ]
+ for index, (key, params) in enumerate(parents):
+ token = resume_token if key == resume_parent else None
+ while True:
+ payload = {**build_payload(endpoint), **params}
+ if token and endpoint.token_key:
+ payload[endpoint.token_key] = token
+ body = client.request(endpoint, payload)
+ rows = normalize_rows(endpoint, body)
+ if endpoint.parent_column:
+ rows = [{**row, endpoint.parent_column: key} for row in rows]
+ next_token = body.get(endpoint.token_key) if endpoint.token_key else None
+ if next_token and next_token == token:
+ raise ValueError("AWS returned a repeated pagination token")
+ manager.save_state(
+ AwsSavingsPlansResumeConfig(
+ parent_id=key,
+ next_token=next_token,
+ completed=not next_token and index == len(parents) - 1,
+ )
+ )
+ if rows:
+ yield rows
+ manager.safe_point()
+ if not next_token:
+ break
+ token = next_token
+
+
def aws_savings_plans_source(
config: AwsSavingsPlansSourceConfig,
endpoint_name: str,
@@ -273,7 +428,7 @@ def aws_savings_plans_source(
api_version: str,
) -> SourceResponse:
endpoint = ENDPOINTS[endpoint_name]
- metrics = endpoint.service == "ce"
+ metrics = endpoint.windowed
return SourceResponse(
name=endpoint_name,
items=lambda: get_rows(config, endpoint, manager, incremental, last_value, api_version),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/canonical_descriptions.py
index 22f9c7cafd77..0cbeb84832ce 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/canonical_descriptions.py
@@ -59,4 +59,68 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"coverage_total_cost": "Total eligible spend during the period.",
},
},
+ "savings_plan_offerings": {
+ "description": "Savings Plans offerings that AWS sells, with their plan type, term, payment option, and properties.",
+ "docs_url": "https://docs.aws.amazon.com/savingsplans/latest/APIReference/API_SavingsPlanOffering.html",
+ "columns": {
+ "offering_id": "Identifier of the offering. Matches offering_id on purchased Savings Plans.",
+ "product_types": "Products that the offering applies to.",
+ "plan_type": "Plan type of the offering.",
+ "description": "Description of the offering.",
+ "payment_option": "Payment option of the offering.",
+ "duration_seconds": "Duration of the offering in seconds.",
+ "currency": "Currency of the offering.",
+ "service_code": "Service code of the offering.",
+ "usage_type": "Usage type of the offering.",
+ "operation": "Operation of the offering.",
+ "properties": "Offering properties, such as the Region and instance family.",
+ },
+ },
+ "savings_plan_rates": {
+ "description": "Contracted rates of each Savings Plan by product, service, usage type, and operation.",
+ "docs_url": "https://docs.aws.amazon.com/savingsplans/latest/APIReference/API_SavingsPlanRate.html",
+ "columns": {
+ "savings_plan_id": "Identifier of the Savings Plan that the rate belongs to.",
+ "rate": "Rate of the Savings Plan for the usage.",
+ "currency": "Currency of the rate.",
+ "unit": "Billing unit of the rate.",
+ "product_type": "Product type that the rate applies to.",
+ "service_code": "Service that the rate applies to.",
+ "usage_type": "Usage type that the rate applies to.",
+ "operation": "Operation that the rate applies to.",
+ "properties": "Rate properties, such as the Region, instance type, and tenancy.",
+ },
+ },
+ "purchase_recommendations": {
+ "description": "Recommended Savings Plans purchases for each plan type, term, payment option, and lookback period.",
+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetSavingsPlansPurchaseRecommendation.html",
+ "columns": {
+ "recommendation_detail_id": "Identifier of the recommendation detail.",
+ "recommendation_id": "Identifier of the recommendation set.",
+ "generation_timestamp": "Time when AWS generated the recommendation.",
+ "savings_plans_type": "Savings Plans type of the recommendation.",
+ "term_in_years": "Term of the recommended Savings Plan.",
+ "payment_option": "Payment option of the recommended Savings Plan.",
+ "lookback_period_in_days": "Usage period that AWS analyzed for the recommendation.",
+ "account_scope": "Accounts that the recommendation covers.",
+ "account_id": "Account that the recommendation applies to.",
+ "offering_id": "Identifier of the recommended offering.",
+ "hourly_commitment_to_purchase": "Recommended hourly commitment.",
+ "estimated_savings_amount": "Estimated savings during the lookback period.",
+ "estimated_monthly_savings_amount": "Estimated monthly savings.",
+ "estimated_average_utilization": "Estimated average utilization of the recommended commitment.",
+ },
+ },
+ "purchase_recommendation_details": {
+ "description": "Estimated cost, coverage, and utilization behind each Savings Plans purchase recommendation.",
+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_RecommendationDetailData.html",
+ "columns": {
+ "recommendation_detail_id": "Identifier of the recommendation detail.",
+ "existing_hourly_commitment": "Hourly commitment of the Savings Plans that the account already has.",
+ "current_average_coverage": "Average Savings Plans coverage before the recommended purchase.",
+ "estimated_average_coverage": "Estimated average Savings Plans coverage after the recommended purchase.",
+ "latest_usage_timestamp": "Time of the latest usage that AWS used for the recommendation.",
+ "metrics_over_lookback_period": "Hourly estimates of on-demand cost, coverage, and utilization during the lookback period.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/settings.py
index 3c8fce509fc9..7893073ebaf9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/settings.py
@@ -21,6 +21,14 @@ class SavingsPlansEndpoint:
token_key: str | None = "NextToken"
window_days: int = 92
granularity: str | None = "DAILY"
+ page_size_key: str | None = None
+ page_size: int = 100
+ fan_out: Literal["savings_plans", "recommendation_options", "purchase_recommendations"] | None = None
+ parent_column: str | None = None
+
+ @property
+ def windowed(self) -> bool:
+ return self.service == "ce" and self.fan_out is None
ENDPOINTS: dict[str, SavingsPlansEndpoint] = {
@@ -31,6 +39,7 @@ ENDPOINTS: dict[str, SavingsPlansEndpoint] = {
service="savingsplans",
token_key="nextToken",
granularity=None,
+ page_size_key="maxResults",
),
"utilization_daily": SavingsPlansEndpoint(
operation="GetSavingsPlansUtilization",
@@ -50,10 +59,87 @@ ENDPOINTS: dict[str, SavingsPlansEndpoint] = {
result_key="SavingsPlansCoverages",
primary_keys=("period_start",),
),
+ "savings_plan_offerings": SavingsPlansEndpoint(
+ operation="DescribeSavingsPlansOfferings",
+ result_key="searchResults",
+ primary_keys=("offering_id",),
+ service="savingsplans",
+ token_key="nextToken",
+ granularity=None,
+ page_size_key="maxResults",
+ page_size=1000,
+ ),
+ "savings_plan_rates": SavingsPlansEndpoint(
+ operation="DescribeSavingsPlanRates",
+ result_key="searchResults",
+ primary_keys=("savings_plan_id", "product_type", "service_code", "usage_type", "operation"),
+ service="savingsplans",
+ token_key="nextToken",
+ granularity=None,
+ page_size_key="maxResults",
+ page_size=1000,
+ fan_out="savings_plans",
+ parent_column="savings_plan_id",
+ ),
+ "purchase_recommendations": SavingsPlansEndpoint(
+ operation="GetSavingsPlansPurchaseRecommendation",
+ result_key="SavingsPlansPurchaseRecommendation",
+ primary_keys=("recommendation_detail_id",),
+ token_key="NextPageToken",
+ granularity=None,
+ page_size_key="PageSize",
+ fan_out="recommendation_options",
+ ),
+ "purchase_recommendation_details": SavingsPlansEndpoint(
+ operation="GetSavingsPlanPurchaseRecommendationDetails",
+ result_key="RecommendationDetailData",
+ primary_keys=("recommendation_detail_id",),
+ token_key=None,
+ granularity=None,
+ fan_out="purchase_recommendations",
+ parent_column="recommendation_detail_id",
+ ),
}
+# Cost Explorer only returns recommendations for one combination per request.
+# The legacy *_UTILIZATION payment options apply to Reserved Instances, not Savings Plans.
+# AWS sells Database Savings Plans only with a 1-year term and no upfront payment.
+RECOMMENDATION_OPTIONS: tuple[dict[str, tuple[str, ...]], ...] = (
+ {
+ "SavingsPlansType": ("COMPUTE_SP", "EC2_INSTANCE_SP", "SAGEMAKER_SP"),
+ "TermInYears": ("ONE_YEAR", "THREE_YEARS"),
+ "PaymentOption": ("NO_UPFRONT", "PARTIAL_UPFRONT", "ALL_UPFRONT"),
+ "LookbackPeriodInDays": ("SEVEN_DAYS", "THIRTY_DAYS", "SIXTY_DAYS"),
+ },
+ {
+ "SavingsPlansType": ("DATABASE_SP",),
+ "TermInYears": ("ONE_YEAR",),
+ "PaymentOption": ("NO_UPFRONT",),
+ "LookbackPeriodInDays": ("SEVEN_DAYS", "THIRTY_DAYS", "SIXTY_DAYS"),
+ },
+)
+
+RECOMMENDATION_DECIMAL_FIELDS = (
+ "upfront_cost",
+ "estimated_roi",
+ "estimated_sp_cost",
+ "estimated_on_demand_cost",
+ "estimated_on_demand_cost_with_current_commitment",
+ "estimated_savings_amount",
+ "estimated_savings_percentage",
+ "hourly_commitment_to_purchase",
+ "existing_hourly_commitment",
+ "estimated_average_utilization",
+ "estimated_monthly_savings_amount",
+ "current_minimum_hourly_on_demand_spend",
+ "current_maximum_hourly_on_demand_spend",
+ "current_average_hourly_on_demand_spend",
+ "current_average_coverage",
+ "estimated_average_coverage",
+)
+
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
- name: [incremental_field("period_start")] for name, endpoint in ENDPOINTS.items() if endpoint.service == "ce"
+ name: [incremental_field("period_start")] for name, endpoint in ENDPOINTS.items() if endpoint.windowed
}
ENDPOINT_DESCRIPTIONS = {
@@ -61,6 +147,10 @@ ENDPOINT_DESCRIPTIONS = {
"utilization_daily": "Daily commitment use and savings across Savings Plans.",
"utilization_details_daily": "Daily commitment use and savings for each Savings Plan.",
"coverage_daily": "Daily spend covered by Savings Plans and remaining on-demand spend.",
+ "savings_plan_offerings": "Savings Plans offerings with their plan type, term, payment option, and properties.",
+ "savings_plan_rates": "Contracted rates of each Savings Plan by service, usage type, and operation.",
+ "purchase_recommendations": "Recommended Savings Plans purchases with their expected cost and savings.",
+ "purchase_recommendation_details": "Estimated cost, coverage, and utilization behind each purchase recommendation.",
}
ERROR_MESSAGES = {
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/source.py
index 44b115d84c40..32d156de5146 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/source.py
@@ -113,13 +113,19 @@ class AwsSavingsPlansSource(ResumableSource[AwsSavingsPlansSourceConfig, AwsSavi
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
label="AWS Savings Plans",
caption=(
- "Sync Savings Plans, commitment use, and coverage into the PostHog Data warehouse. "
+ "Sync Savings Plans, rates, commitment use, coverage, and purchase recommendations into the PostHog Data warehouse. "
"Grant `savingsplans:DescribeSavingsPlans` for plan inventory. "
"Grant `ce:GetSavingsPlansUtilization` for daily utilization. "
"Grant `ce:GetSavingsPlansUtilizationDetails` for utilization details. "
"Grant `ce:GetSavingsPlansCoverage` for daily coverage. "
+ "Grant `savingsplans:DescribeSavingsPlansOfferings` for offerings. "
+ "Grant `savingsplans:DescribeSavingsPlanRates` for plan rates. "
+ "Grant `ce:GetSavingsPlansPurchaseRecommendation` for purchase recommendations. "
+ "Grant `ce:GetSavingsPlanPurchaseRecommendationDetails` for recommendation details. "
"Enable Cost Explorer for the metric tables. AWS charges for Cost Explorer requests. "
"Daily utilization details require at least one request per day. "
+ "Purchase recommendations need one request for each of 57 plan type, term, payment, and lookback combinations. "
+ "Recommendation details also need one request for each recommendation. "
"This source uses the global endpoints in the standard AWS partition. "
"Metric imports cover up to 365 days and read the previous seven days again during incremental syncs."
),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/tests/test_aws_savings_plans.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/tests/test_aws_savings_plans.py
index 624b12300c8a..c81a6b5ecf2b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/tests/test_aws_savings_plans.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/tests/test_aws_savings_plans.py
@@ -95,7 +95,178 @@ def run_source(
return [row for batch in cast(Iterable[Any], source.items()) for row in batch]
[email protected]("name", list(ENDPOINTS))
+FAN_OUT_ENDPOINTS = [name for name, endpoint in ENDPOINTS.items() if endpoint.fan_out]
+RECOMMENDED_OPTIONS = ("COMPUTE_SP", "ONE_YEAR", "NO_UPFRONT", "THIRTY_DAYS")
+
+
+def operation(request: RecordedRequest) -> str:
+ return request.headers.get("x-amz-target", request.path).rsplit(".", 1)[-1].lstrip("/")
+
+
+def assert_matches_service_model(request: RecordedRequest) -> None:
+ service = "ce" if "x-amz-target" in request.headers else "savingsplans"
+ input_shape = get_session().get_service_model(service).operation_model(operation(request)).input_shape
+ assert input_shape is not None
+ assert set(input_shape.required_members) <= set(request.json()) <= set(input_shape.members)
+
+
+def fan_out_answer(request: RecordedRequest) -> ScriptedResponse:
+ payload = request.json()
+ match operation(request):
+ case "DescribeSavingsPlans":
+ return ScriptedResponse(json={"savingsPlans": [{"savingsPlanId": "plan-b"}, {"savingsPlanId": "plan-a"}]})
+ case "DescribeSavingsPlanRates":
+ rate = {"rate": "0.05", "usageType": "USE1-BoxUsage:c5.large", "operation": "RunInstances"}
+ if "nextToken" in payload:
+ return ScriptedResponse(json={"searchResults": [{**rate, "usageType": "USE1-Fargate-vCPU-Hours"}]})
+ return ScriptedResponse(json={"searchResults": [rate], "nextToken": "page-2"})
+ case "GetSavingsPlansPurchaseRecommendation":
+ options = tuple(
+ payload[key] for key in ("SavingsPlansType", "TermInYears", "PaymentOption", "LookbackPeriodInDays")
+ )
+ if options != RECOMMENDED_OPTIONS:
+ return ScriptedResponse(json={"Metadata": {"RecommendationId": "empty"}})
+ detail_id = "detail-2" if "NextPageToken" in payload else "detail-1"
+ return ScriptedResponse(
+ json={
+ "Metadata": {"RecommendationId": "rec", "GenerationTimestamp": "2025-01-11T00:00:00Z"},
+ "SavingsPlansPurchaseRecommendation": {
+ "SavingsPlansType": options[0],
+ "LookbackPeriodInDays": options[3],
+ "SavingsPlansPurchaseRecommendationSummary": {"EstimatedROI": "1"},
+ "SavingsPlansPurchaseRecommendationDetails": [
+ {
+ "RecommendationDetailId": detail_id,
+ "SavingsPlansDetails": {"Region": "us-east-1", "OfferingId": "offering"},
+ "AccountId": "001234567890",
+ "EstimatedROI": "12.5",
+ "UpfrontCost": "",
+ }
+ ],
+ },
+ **({} if "NextPageToken" in payload else {"NextPageToken": "page-2"}),
+ }
+ )
+ case "GetSavingsPlanPurchaseRecommendationDetails":
+ return ScriptedResponse(
+ json={
+ "RecommendationDetailId": payload["RecommendationDetailId"],
+ "RecommendationDetailData": {
+ "CurrentAverageCoverage": "40.5",
+ "LatestUsageTimestamp": "2025-01-10T23:00:00Z",
+ "MetricsOverLookbackPeriod": [{"StartTime": "2025-01-10T00:00:00Z", "CurrentCoverage": "40"}],
+ },
+ }
+ )
+ raise AssertionError(f"unexpected request {request.path}")
+
+
+ "name,expected",
+ [
+ (
+ "savings_plan_rates",
+ [
+ ("plan-a", "USE1-BoxUsage:c5.large", Decimal("0.05")),
+ ("plan-a", "USE1-Fargate-vCPU-Hours", Decimal("0.05")),
+ ("plan-b", "USE1-BoxUsage:c5.large", Decimal("0.05")),
+ ("plan-b", "USE1-Fargate-vCPU-Hours", Decimal("0.05")),
+ ],
+ ),
+ (
+ "purchase_recommendations",
+ [
+ ("detail-1", "COMPUTE_SP", "us-east-1", "001234567890", Decimal("12.5"), None, "rec"),
+ ("detail-2", "COMPUTE_SP", "us-east-1", "001234567890", Decimal("12.5"), None, "rec"),
+ ],
+ ),
+ (
+ "purchase_recommendation_details",
+ [
+ ("detail-1", Decimal("40.5"), dt.datetime(2025, 1, 10, 23, tzinfo=dt.UTC), "40"),
+ ("detail-2", Decimal("40.5"), dt.datetime(2025, 1, 10, 23, tzinfo=dt.UTC), "40"),
+ ],
+ ),
+ ],
+)
+def test_fan_out_walks_every_parent_and_child_page(name: str, expected: list[tuple[Any, ...]]) -> None:
+ result = driver().run(name, fan_out_answer)
+ assert result.raised is None
+ for request in result.requests:
+ assert_matches_service_model(request)
+ rows = result.rows
+ actual: list[tuple[Any, ...]]
+ if name == "savings_plan_rates":
+ actual = [(row["savings_plan_id"], row["usage_type"], row["rate"]) for row in rows]
+ elif name == "purchase_recommendations":
+ assert rows[0]["generation_timestamp"] == dt.datetime(2025, 1, 11, tzinfo=dt.UTC)
+ assert "savings_plans_purchase_recommendation_summary" not in rows[0]
+ actual = [
+ (
+ row["recommendation_detail_id"],
+ row["savings_plans_type"],
+ row["region"],
+ row["account_id"],
+ row["estimated_roi"],
+ row["upfront_cost"],
+ row["recommendation_id"],
+ )
+ for row in rows
+ ]
+ else:
+ actual = [
+ (
+ row["recommendation_detail_id"],
+ row["current_average_coverage"],
+ row["latest_usage_timestamp"],
+ row["metrics_over_lookback_period"][0]["CurrentCoverage"],
+ )
+ for row in rows
+ ]
+ assert actual == expected
+ assert result.committed_states[-1].completed
+
+
+ "resume_token,expected",
+ [
+ ("page-2", [("plan-a", "page-2"), ("plan-b", None), ("plan-b", "page-2")]),
+ (None, [("plan-b", None), ("plan-b", "page-2")]),
+ ],
+)
+def test_fan_out_resumes_after_finished_parents(resume_token: str | None, expected: list[tuple[str, Any]]) -> None:
+ result = driver().run(
+ "savings_plan_rates",
+ fan_out_answer,
+ resume_state=AwsSavingsPlansResumeConfig(parent_id="plan-a", next_token=resume_token),
+ )
+ assert result.raised is None
+ rate_requests = [request.json() for request in result.requests if operation(request) == "DescribeSavingsPlanRates"]
+ assert [(payload["savingsPlanId"], payload.get("nextToken")) for payload in rate_requests] == expected
+
+
+ "name,answer,expected",
+ [
+ ("savings_plan_rates", fan_out_answer, ["DescribeSavingsPlans", "DescribeSavingsPlanRates"]),
+ ("savings_plan_rates", lambda _: ScriptedResponse(json={}), ["DescribeSavingsPlans"]),
+ ("purchase_recommendations", fan_out_answer, ["GetSavingsPlansPurchaseRecommendation"]),
+ (
+ "purchase_recommendation_details",
+ lambda _: ScriptedResponse(json={}),
+ ["GetSavingsPlansPurchaseRecommendation"],
+ ),
+ ],
+)
+def test_fan_out_validation_probes_child_with_a_parent(name: str, answer: Any, expected: list[str]) -> None:
+ with scripted_network(answer) as network:
+ assert validate_credentials(config(), name) == (True, None)
+ assert [operation(request) for request in network.requests_log] == expected
+ for request in network.requests_log:
+ assert_matches_service_model(request)
+
+
[email protected]("name", [name for name in ENDPOINTS if name not in FAN_OUT_ENDPOINTS])
def test_signed_protocol_and_payload_match_service_model(transport: MagicMock, manager: MagicMock, name: str) -> None:
run_source(manager, name, start_date="2025-01-10")
call = transport.return_value.post.call_args
@@ -112,10 +283,10 @@ def test_signed_protocol_and_payload_match_service_model(transport: MagicMock, m
assert headers["X-Amz-Date"]
assert call.kwargs["timeout"] == 60
if endpoint.service == "savingsplans":
- assert call.args[0] == "https://savingsplans.amazonaws.com/DescribeSavingsPlans"
+ assert call.args[0] == f"https://savingsplans.amazonaws.com/{endpoint.operation}"
assert headers["Content-Type"] == "application/json"
assert "X-Amz-Target" not in headers
- assert payload == {"maxResults": 100}
+ assert payload == {"maxResults": endpoint.page_size}
else:
assert call.args[0] == "https://ce.us-east-1.amazonaws.com/"
assert headers["Content-Type"] == "application/x-amz-json-1.1"
@@ -326,6 +497,7 @@ def test_error_parsing_and_no_duplicate_status_retry(
("AccessDeniedException", "coverage_daily", False, "ce:GetSavingsPlansCoverage"),
("UnauthorizedException", None, True, None),
("UnauthorizedException", "savings_plans", False, "savingsplans:DescribeSavingsPlans"),
+ ("AccessDeniedException", "savings_plan_rates", False, "savingsplans:DescribeSavingsPlans"),
("InvalidSignatureException", None, False, "signature"),
("UnrecognizedClientException", None, False, "credentials"),
("ExpiredTokenException", None, False, "expired"),