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 four aws compute optimizer tables (#116965)

Tom Owers49b1b5d95458
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 6a901d6e8f93..256c353d7081 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
@@ -1117,15 +1117,15 @@ Note: Parsed all read operations and response shapes in the official botocore se
## AWS Compute Optimizer — gaps
-Today (6): `auto_scaling_group_recommendations`, `ebs_volume_recommendations`, `ec2_instance_recommendations`, `ecs_service_recommendations`, `lambda_function_recommendations`, `recommendation_summaries`
+Today (10): `auto_scaling_group_recommendations`, `ebs_volume_recommendations`, `ec2_instance_recommendations`, `ec2_recommendation_projected_metrics`, `ecs_service_recommendation_projected_metrics`, `ecs_service_recommendations`, `idle_recommendations`, `lambda_function_recommendations`, `rds_database_recommendations`, `recommendation_summaries`
Diffed against: <https://raw.githubusercontent.com/boto/botocore/develop/botocore/data/compute-optimizer/2019-11-01/service-2.json>
-- [ ] `RDS database recommendations (GetRDSDatabaseRecommendations, POST /)` — identifies database instance and storage savings that the current compute recommendations do not cover (high)
-- [ ] `Idle resource recommendations (GetIdleRecommendations, POST /)` — identifies unused resources and their potential savings across resource types (high)
+- [x] `RDS database recommendations (GetRDSDatabaseRecommendations, POST /)` — identifies database instance and storage savings that the current compute recommendations do not cover (high)
+- [x] `Idle resource recommendations (GetIdleRecommendations, POST /)` — identifies unused resources and their potential savings across resource types (high)
- [ ] `License recommendations (GetLicenseRecommendations, POST /)` — shows license savings options for existing EC2 instances (medium)
-- [ ] `EC2 recommendation projected metrics (GetEC2RecommendationProjectedMetrics, POST /)` — provides projected CPU and memory time series to assess recommended instance sizes (medium)
-- [ ] `ECS service recommendation projected metrics (GetECSServiceRecommendationProjectedMetrics, POST /)` — provides projected utilization time series to assess recommended service capacity (medium)
+- [x] `EC2 recommendation projected metrics (GetEC2RecommendationProjectedMetrics, POST /)` — provides projected CPU and memory time series to assess recommended instance sizes (medium)
+- [x] `ECS service recommendation projected metrics (GetECSServiceRecommendationProjectedMetrics, POST /)` — provides projected utilization time series to assess recommended service capacity (medium)
- [ ] `RDS database recommendation projected metrics (GetRDSDatabaseRecommendationProjectedMetrics, POST /)` — provides projected utilization time series to assess recommended database sizes (medium)
Note: Compared the official botocore operation model with the static endpoint map and extraction code. JSON RPC reads use POST / and select operations through X-Amz-Target. Projected metrics require calls for each resource ARN and a time window. Enrollment, preferences, and export plumbing were excluded.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/aws_compute_optimizer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/aws_compute_optimizer.py
index c4c302b6228e..360147e6c75f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/aws_compute_optimizer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/aws_compute_optimizer.py
@@ -1,7 +1,7 @@
import re
import json
from collections.abc import Iterator
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from typing import Any
import requests
@@ -14,11 +14,16 @@ from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.aws_compute_optimizer.settings import (
API_VERSION,
+ DEFAULT_LOOKBACK_DAYS,
DEFAULT_REGION,
ENDPOINTS,
ERROR_MESSAGES,
PAGE_SIZE,
+ PROJECTED_METRICS_PERIOD_SECONDS,
+ PROJECTED_METRICS_STAT,
TARGET_PREFIXES,
+ Endpoint,
+ ProjectedMetricsFanout,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import BoundedRetry
@@ -42,6 +47,8 @@ TRANSPORT_RETRY = BoundedRetry(
class AwsComputeOptimizerResumeConfig:
next_token: str | None = None
complete: bool = False
+ # Unprocessed (ARN, lookback days) parents of a projected metrics page. next_token is the page after them.
+ pending: tuple[tuple[str, int], ...] = ()
class AwsComputeOptimizerError(Exception):
@@ -135,11 +142,15 @@ class AwsComputeOptimizerClient:
return result
+def _column(key: str) -> str:
+ return _CAMEL_BOUNDARY.sub("_", key).lower()
+
+
def normalize_row(item: dict[str, Any], region: str) -> dict[str, Any]:
def flatten(obj: dict[str, Any], prefix: str = "") -> dict[str, Any]:
row: dict[str, Any] = {}
for key, value in obj.items():
- column = prefix + _CAMEL_BOUNDARY.sub("_", key).lower()
+ column = prefix + _column(key)
if isinstance(value, dict):
row.update(flatten(value, column + "_"))
else:
@@ -154,6 +165,103 @@ def normalize_row(item: dict[str, Any], region: str) -> dict[str, Any]:
return row
+def projected_metric_rows(
+ result: dict[str, Any], arn_column: str, arn: str, result_key: str, region: str
+) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ for option in result.get(result_key) or []:
+ option_columns = {_column(key): value for key, value in option.items() if key != "projectedMetrics"}
+ for metric in option.get("projectedMetrics") or []:
+ # Each metric holds parallel lists: `values` for EC2, `upperBoundValues` and `lowerBoundValues` for ECS.
+ series = {
+ _column(key).removesuffix("s"): value
+ for key, value in metric.items()
+ if key not in {"name", "timestamps"} and isinstance(value, list)
+ }
+ for index, timestamp in enumerate(metric.get("timestamps") or []):
+ rows.append(
+ {
+ arn_column: arn,
+ **option_columns,
+ "metric_name": metric.get("name"),
+ "timestamp": datetime.fromtimestamp(timestamp, tz=UTC),
+ **{column: values[index] if index < len(values) else None for column, values in series.items()},
+ "region": region,
+ }
+ )
+ return rows
+
+
+def projected_metrics_payload(
+ fanout: ProjectedMetricsFanout, arn: str, lookback_days: int, end: datetime
+) -> dict[str, Any]:
+ return {
+ fanout.arn_field: arn,
+ "stat": PROJECTED_METRICS_STAT,
+ "period": PROJECTED_METRICS_PERIOD_SECONDS,
+ "startTime": int((end - timedelta(days=lookback_days)).timestamp()),
+ "endTime": int(end.timestamp()),
+ }
+
+
+def get_projected_metric_rows(
+ client: AwsComputeOptimizerClient,
+ settings: Endpoint,
+ fanout: ProjectedMetricsFanout,
+ manager: ResumableSourceManager[AwsComputeOptimizerResumeConfig],
+ state: AwsComputeOptimizerResumeConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ parent = ENDPOINTS[fanout.parent]
+ arn_column = _column(fanout.arn_field)
+ token = state.next_token
+ # The cursor keeps the unprocessed parents themselves, because a refetched page can drop or reorder resources.
+ pending = tuple((str(arn), int(lookback)) for arn, lookback in state.pending)
+ fetch_page = not pending
+ seen_tokens: set[str] = {token} if token else set()
+ end = datetime.now(UTC).replace(hour=0, minute=0, second=0, microsecond=0)
+ while True:
+ if fetch_page:
+ payload: dict[str, Any] = {"maxResults": PAGE_SIZE}
+ if token:
+ payload["nextToken"] = token
+ page = client.request(parent.operation, payload)
+ token = page.get("nextToken") or None
+ if token is not None:
+ if token in seen_tokens:
+ raise ValueError("AWS Compute Optimizer repeated a pagination token. Restart the sync.")
+ seen_tokens.add(token)
+ pending = tuple(
+ (item[fanout.arn_field], int(item.get(fanout.lookback_field) or DEFAULT_LOOKBACK_DAYS))
+ for item in page.get(parent.result_key) or []
+ if item.get(fanout.arn_field)
+ )
+ if not pending:
+ manager.save_state(AwsComputeOptimizerResumeConfig(next_token=token, complete=token is None))
+ manager.safe_point()
+ fetch_page = True
+ for index, (arn, lookback) in enumerate(pending):
+ rows: list[dict[str, Any]] = []
+ try:
+ result = client.request(settings.operation, projected_metrics_payload(fanout, arn, lookback, end))
+ except AwsComputeOptimizerError as error:
+ # The resource can disappear between the recommendation listing and this request.
+ if error.code != "ResourceNotFoundException":
+ raise
+ else:
+ rows = projected_metric_rows(result, arn_column, arn, settings.result_key, client.region)
+ remaining = pending[index + 1 :]
+ manager.save_state(
+ AwsComputeOptimizerResumeConfig(
+ next_token=token, pending=remaining, complete=token is None and not remaining
+ )
+ )
+ if rows:
+ yield rows
+ manager.safe_point()
+ if token is None:
+ return
+
+
def get_rows(
config: AwsComputeOptimizerSourceConfig,
endpoint: str,
@@ -168,6 +276,9 @@ def get_rows(
seen_tokens: set[str] = {token} if token else set()
client = AwsComputeOptimizerClient(config, api_version)
try:
+ if settings.fanout is not None:
+ yield from get_projected_metric_rows(client, settings, settings.fanout, manager, state)
+ return
while True:
payload: dict[str, Any] = {"maxResults": PAGE_SIZE}
if token:
@@ -198,12 +309,28 @@ def validate_credentials(
client = AwsComputeOptimizerClient(config, api_version)
except ValueError as error:
return False, str(error)
- operation = ENDPOINTS[schema_name].operation if schema_name is not None else "GetEnrollmentStatus"
+ operation = "GetEnrollmentStatus"
try:
- result = client.request(operation, {"maxResults": 1} if schema_name is not None else {})
- if schema_name is None and result.get("status") != "Active":
- return False, "Enable AWS Compute Optimizer for this account and wait until enrollment is active."
+ if schema_name is None:
+ result = client.request(operation, {})
+ if result.get("status") != "Active":
+ return False, "Enable AWS Compute Optimizer for this account and wait until enrollment is active."
+ else:
+ settings = ENDPOINTS[schema_name]
+ fanout = settings.fanout
+ # Projected metrics need a resource ARN, so take one from the recommendation listing they fan out from.
+ parent = ENDPOINTS[fanout.parent] if fanout else settings
+ operation = parent.operation
+ result = client.request(operation, {"maxResults": 1})
+ items = result.get(parent.result_key) or []
+ arn = items[0].get(fanout.arn_field) if fanout and items else None
+ if fanout and arn:
+ operation = settings.operation
+ end = datetime.now(UTC).replace(hour=0, minute=0, second=0, microsecond=0)
+ client.request(operation, projected_metrics_payload(fanout, arn, 1, end))
except AwsComputeOptimizerError as error:
+ if error.code == "ResourceNotFoundException" and schema_name is not None:
+ return True, None
if error.code in {"AccessDenied", "AccessDeniedException"}:
if schema_name is None:
return True, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/canonical_descriptions.py
index 746836aa5f18..c9368ba845c9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/canonical_descriptions.py
@@ -18,15 +18,20 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
for name, endpoint in ENDPOINTS.items()
}
-for name in ENDPOINTS:
- if name != "recommendation_summaries":
+for name, endpoint in ENDPOINTS.items():
+ if endpoint.fanout is None and name != "recommendation_summaries":
CANONICAL_DESCRIPTIONS[name]["columns"].update(
{
"finding": "Classification of the resource's optimization status.",
"last_refresh_timestamp": "Time when Compute Optimizer last refreshed the recommendation, in UTC.",
(
"lookback_period_in_days"
- if name in {"lambda_function_recommendations", "ecs_service_recommendations"}
+ if name
+ in {
+ "lambda_function_recommendations",
+ "ecs_service_recommendations",
+ "rds_database_recommendations",
+ }
else "look_back_period_in_days"
): "Number of days of utilization data used to generate the recommendation.",
"utilization_metrics": "Utilization measurements used to evaluate the resource.",
@@ -65,6 +70,50 @@ CANONICAL_DESCRIPTIONS["ebs_volume_recommendations"]["columns"].update(
"volume_recommendation_options": "Recommended volume configurations with performance risks and potential savings.",
}
)
+CANONICAL_DESCRIPTIONS["rds_database_recommendations"]["columns"].update(
+ {
+ "resource_arn": "Amazon Resource Name of the Aurora or RDS database.",
+ "engine": "Database engine of the instance.",
+ "current_db_instance_class": "DB instance class used by the database.",
+ "instance_finding": "Classification of the DB instance's optimization status.",
+ "storage_finding": "Classification of the DB storage's optimization status.",
+ "instance_recommendation_options": "Recommended DB instance classes with projected utilization and potential savings.",
+ "storage_recommendation_options": "Recommended storage configurations with potential savings.",
+ }
+)
+CANONICAL_DESCRIPTIONS["idle_recommendations"]["columns"].update(
+ {
+ "resource_arn": "Amazon Resource Name of the idle resource.",
+ "resource_id": "Unique identifier of the idle resource.",
+ "resource_type": "Type of the idle resource, such as an EC2 instance or EBS volume.",
+ "finding_description": "Explanation of why Compute Optimizer considers the resource idle.",
+ }
+)
+for name, endpoint in ENDPOINTS.items():
+ if endpoint.fanout is not None:
+ CANONICAL_DESCRIPTIONS[name]["columns"].update(
+ {
+ "metric_name": "Utilization metric that Compute Optimizer projects, such as Cpu or Memory.",
+ "timestamp": "Start of the one-day period of the projected data point, in UTC.",
+ }
+ )
+CANONICAL_DESCRIPTIONS["ec2_recommendation_projected_metrics"]["columns"].update(
+ {
+ "instance_arn": "Amazon Resource Name of the EC2 instance.",
+ "recommended_instance_type": "Recommended EC2 instance type the projection applies to.",
+ "rank": "Rank of the recommendation option. Rank 1 is the best option.",
+ "value": "Projected maximum utilization for the period if the instance used the recommended type.",
+ }
+)
+CANONICAL_DESCRIPTIONS["ecs_service_recommendation_projected_metrics"]["columns"].update(
+ {
+ "service_arn": "Amazon Resource Name of the ECS service.",
+ "recommended_cpu_units": "Recommended CPU units the projection applies to.",
+ "recommended_memory_size": "Recommended memory size, in MiB, the projection applies to.",
+ "upper_bound_value": "Upper bound of the projected maximum utilization for the period.",
+ "lower_bound_value": "Lower bound of the projected maximum utilization for the period.",
+ }
+)
CANONICAL_DESCRIPTIONS["recommendation_summaries"]["columns"].update(
{
"recommendation_resource_type": "Type of AWS resource covered by the summary.",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/settings.py
index b6e5106a81cc..78b6f9bf5ced 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/settings.py
@@ -5,6 +5,17 @@ API_DOCS_URL = "https://docs.aws.amazon.com/compute-optimizer/latest/APIReferenc
TARGET_PREFIXES = {API_VERSION: "ComputeOptimizerService"}
DEFAULT_REGION = "us-east-1"
PAGE_SIZE = 100
+# One daily peak per metric keeps the fan-out tables small while matching how Compute Optimizer sizes resources.
+PROJECTED_METRICS_STAT = "Maximum"
+PROJECTED_METRICS_PERIOD_SECONDS = 86400
+DEFAULT_LOOKBACK_DAYS = 14
+
+
+@frozen
+class ProjectedMetricsFanout:
+ parent: str
+ arn_field: str
+ lookback_field: str
@frozen
@@ -13,6 +24,7 @@ class Endpoint:
result_key: str
primary_keys: tuple[str, ...]
description: str
+ fanout: ProjectedMetricsFanout | None = None
ENDPOINTS: dict[str, Endpoint] = {
@@ -46,6 +58,36 @@ ENDPOINTS: dict[str, Endpoint] = {
primary_keys=("volume_arn",),
description="EBS volume recommendations with configuration options and estimated savings.",
),
+ "rds_database_recommendations": Endpoint(
+ operation="GetRDSDatabaseRecommendations",
+ result_key="rdsDBRecommendations",
+ primary_keys=("resource_arn",),
+ description="Aurora and RDS database recommendations for instance classes and storage, with estimated savings.",
+ ),
+ "idle_recommendations": Endpoint(
+ operation="GetIdleRecommendations",
+ result_key="idleRecommendations",
+ primary_keys=("resource_arn",),
+ description="Idle resources across resource types, with utilization metrics and estimated savings.",
+ ),
+ "ec2_recommendation_projected_metrics": Endpoint(
+ operation="GetEC2RecommendationProjectedMetrics",
+ result_key="recommendedOptionProjectedMetrics",
+ primary_keys=("instance_arn", "rank", "metric_name", "timestamp"),
+ description="Daily peak CPU and memory utilization projected for each recommended EC2 instance type.",
+ fanout=ProjectedMetricsFanout(
+ parent="ec2_instance_recommendations", arn_field="instanceArn", lookback_field="lookBackPeriodInDays"
+ ),
+ ),
+ "ecs_service_recommendation_projected_metrics": Endpoint(
+ operation="GetECSServiceRecommendationProjectedMetrics",
+ result_key="recommendedOptionProjectedMetrics",
+ primary_keys=("service_arn", "recommended_cpu_units", "recommended_memory_size", "metric_name", "timestamp"),
+ description="Daily peak CPU and memory utilization bounds projected for each recommended ECS service size.",
+ fanout=ProjectedMetricsFanout(
+ parent="ecs_service_recommendations", arn_field="serviceArn", lookback_field="lookbackPeriodInDays"
+ ),
+ ),
"recommendation_summaries": Endpoint(
operation="GetRecommendationSummaries",
result_key="recommendationSummaries",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/source.py
index b7dd6a20c73d..5e9b2029e46f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/source.py
@@ -109,6 +109,10 @@ Grant these permissions for the tables you select:
- `compute-optimizer:GetECSServiceRecommendations`
- `compute-optimizer:GetEBSVolumeRecommendations`
- `compute-optimizer:GetRecommendationSummaries`
+- `compute-optimizer:GetRDSDatabaseRecommendations`
+- `compute-optimizer:GetIdleRecommendations`
+- `compute-optimizer:GetEC2RecommendationProjectedMetrics` (also needs `GetEC2InstanceRecommendations`)
+- `compute-optimizer:GetECSServiceRecommendationProjectedMetrics` (also needs `GetECSServiceRecommendations`)
Each sync replaces the current recommendations. This source does not keep recommendation history.""",
iconPath="/static/services/aws_compute_optimizer.png",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/tests/test_aws_compute_optimizer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/tests/test_aws_compute_optimizer.py
index 2a6b96b70f8e..d4f4e1aa2566 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/tests/test_aws_compute_optimizer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_compute_optimizer/tests/test_aws_compute_optimizer.py
@@ -141,6 +141,20 @@ def test_signed_json_request(region: str | None, token: str | None, host: str) -
{"volumeArn": "arn:aws:ec2:eu-west-1:123456789012:volume/vol-example"},
["volume_arn"],
),
+ (
+ "rds_database_recommendations",
+ "GetRDSDatabaseRecommendations",
+ "rdsDBRecommendations",
+ {"resourceArn": "arn:aws:rds:eu-west-1:123456789012:db:example"},
+ ["resource_arn"],
+ ),
+ (
+ "idle_recommendations",
+ "GetIdleRecommendations",
+ "idleRecommendations",
+ {"resourceArn": "arn:aws:ec2:eu-west-1:123456789012:volume/vol-idle", "resourceType": "EBSVolume"},
+ ["resource_arn"],
+ ),
(
"recommendation_summaries",
"GetRecommendationSummaries",
@@ -187,6 +201,124 @@ def test_full_refresh_pagination(
session.close.assert_called_once()
+EC2_ARN = "arn:aws:ec2:eu-west-1:123456789012:instance/i-example"
+ECS_ARN = "arn:aws:ecs:eu-west-1:123456789012:service/example/service"
+
+
+ "endpoint,parent_operation,parent_key,arn_field,lookback_field,option,metric,expected",
+ [
+ (
+ "ec2_recommendation_projected_metrics",
+ "GetEC2InstanceRecommendations",
+ "instanceRecommendations",
+ "instanceArn",
+ "lookBackPeriodInDays",
+ {"recommendedInstanceType": "m7i.large", "rank": 1},
+ {"name": "Cpu", "timestamps": [1735689600, 1735776000], "values": [40.5, 12.0]},
+ [
+ {"instance_arn": EC2_ARN, "recommended_instance_type": "m7i.large", "rank": 1, "value": 40.5},
+ {"instance_arn": EC2_ARN, "recommended_instance_type": "m7i.large", "rank": 1, "value": 12.0},
+ ],
+ ),
+ (
+ "ecs_service_recommendation_projected_metrics",
+ "GetECSServiceRecommendations",
+ "ecsServiceRecommendations",
+ "serviceArn",
+ "lookbackPeriodInDays",
+ {"recommendedCpuUnits": 256, "recommendedMemorySize": 512},
+ {
+ "name": "Memory",
+ "timestamps": [1735689600, 1735776000],
+ "upperBoundValues": [70.0, 60.0],
+ "lowerBoundValues": [30.0],
+ },
+ [
+ {
+ "service_arn": ECS_ARN,
+ "recommended_cpu_units": 256,
+ "recommended_memory_size": 512,
+ "upper_bound_value": 70.0,
+ "lower_bound_value": 30.0,
+ },
+ {
+ "service_arn": ECS_ARN,
+ "recommended_cpu_units": 256,
+ "recommended_memory_size": 512,
+ "upper_bound_value": 60.0,
+ "lower_bound_value": None,
+ },
+ ],
+ ),
+ ],
+)
+def test_projected_metrics_fan_out_over_recommendations(
+ endpoint: str,
+ parent_operation: str,
+ parent_key: str,
+ arn_field: str,
+ lookback_field: str,
+ option: dict[str, Any],
+ metric: dict[str, Any],
+ expected: list[dict[str, Any]],
+) -> None:
+ arn = expected[0][transport._column(arn_field)]
+ result = driver().run(
+ endpoint,
+ [
+ ScriptedResponse(
+ json={parent_key: [{arn_field: "arn:gone"}, {arn_field: arn, lookback_field: 32}], "nextToken": "p2"}
+ ),
+ ScriptedResponse(status=400, json={"__type": "ResourceNotFoundException"}),
+ ScriptedResponse(json={"recommendedOptionProjectedMetrics": [{**option, "projectedMetrics": [metric]}]}),
+ ScriptedResponse(json={parent_key: [], "nextToken": None}),
+ ],
+ )
+ assert result.raised is None
+ timestamps = [datetime(2025, 1, 1, tzinfo=UTC), datetime(2025, 1, 2, tzinfo=UTC)]
+ assert result.rows == [
+ {**row, "metric_name": metric["name"], "timestamp": timestamp, "region": "eu-west-1"}
+ for row, timestamp in zip(expected, timestamps)
+ ]
+ bodies = [json.loads(request.body or b"{}") for request in result.requests]
+ targets = [request.headers["x-amz-target"].rsplit(".", 1)[-1] for request in result.requests]
+ assert targets[0] == targets[3] == parent_operation
+ assert bodies[0] == {"maxResults": 100}
+ assert bodies[3] == {"maxResults": 100, "nextToken": "p2"}
+ gone, child = bodies[1], bodies[2]
+ assert gone[arn_field] == "arn:gone"
+ assert gone["endTime"] - gone["startTime"] == 14 * 86400
+ assert child == {
+ arn_field: arn,
+ "stat": "Maximum",
+ "period": 86400,
+ "startTime": child["endTime"] - 32 * 86400,
+ "endTime": child["endTime"],
+ }
+ assert child["endTime"] % 86400 == 0
+ assert [
+ (state.next_token, [tuple(parent) for parent in state.pending], state.complete)
+ for state in result.committed_states
+ ] == [("p2", [(arn, 32)], False), ("p2", [], False), (None, [], True)]
+ assert result.completed_state is None
+
+
+def test_projected_metrics_resume_processes_pending_parents_without_refetching_page() -> None:
+ result = driver().run(
+ "ec2_recommendation_projected_metrics",
+ [ScriptedResponse(json={"recommendedOptionProjectedMetrics": []})],
+ resume_state=AwsComputeOptimizerResumeConfig(pending=((EC2_ARN, 14),)),
+ )
+ assert result.raised is None
+ assert [json.loads(request.body or b"{}").get("instanceArn") for request in result.requests] == [EC2_ARN]
+ assert (result.final_state.next_token, list(result.final_state.pending), result.final_state.complete) == (
+ None,
+ [],
+ True,
+ )
+
+
def test_completed_resume_does_not_refetch() -> None:
result = driver().run(
"ec2_instance_recommendations", [], resume_state=AwsComputeOptimizerResumeConfig(complete=True)
@@ -302,6 +434,37 @@ def test_missing_permission_at_creation_and_per_table(session: MagicMock, schema
session.close.assert_called_once()
+ "listing,metrics,valid,targets",
+ [
+ (
+ [{"instanceArn": EC2_ARN}],
+ ScriptedResponse(status=400, json={"__type": "AccessDeniedException"}),
+ False,
+ ["GetEC2InstanceRecommendations", "GetEC2RecommendationProjectedMetrics"],
+ ),
+ (
+ [{"instanceArn": EC2_ARN}],
+ ScriptedResponse(json={"recommendedOptionProjectedMetrics": []}),
+ True,
+ ["GetEC2InstanceRecommendations", "GetEC2RecommendationProjectedMetrics"],
+ ),
+ ([], None, True, ["GetEC2InstanceRecommendations"]),
+ ],
+)
+def test_projected_metrics_validation_probes_metrics_permission(
+ listing: list[dict[str, Any]], metrics: ScriptedResponse | None, valid: bool, targets: list[str]
+) -> None:
+ script = [ScriptedResponse(json={"instanceRecommendations": listing}), *([metrics] if metrics else [])]
+ with scripted_network(script) as network:
+ result, message = validate_credentials(config(), "ec2_recommendation_projected_metrics")
+ assert result is valid
+ assert (message is None) is valid
+ if not valid:
+ assert message and "compute-optimizer:GetEC2RecommendationProjectedMetrics" in message
+ assert [request.headers["x-amz-target"].rsplit(".", 1)[-1] for request in network.requests_log] == targets
+
+
@pytest.mark.parametrize("status,valid", [("Active", True), ("Inactive", False), ("Pending", False), ("Failed", False)])
def test_enrollment_validation(status: str, valid: bool) -> None:
with scripted_network([ScriptedResponse(json={"status": status})]) as network: