maproom 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. maproom/__init__.py +14 -0
  2. maproom/__main__.py +10 -0
  3. maproom/analyze/__init__.py +1 -0
  4. maproom/analyze/accel_families.py +45 -0
  5. maproom/analyze/account_azure_activity.py +260 -0
  6. maproom/analyze/account_azure_quota_requests.py +177 -0
  7. maproom/analyze/account_cloudtrail.py +316 -0
  8. maproom/analyze/account_quota_requests.py +180 -0
  9. maproom/analyze/analyze_v1_orchestration.py +1194 -0
  10. maproom/analyze/catalog.py +353 -0
  11. maproom/analyze/change_detection.py +652 -0
  12. maproom/analyze/context_client.py +99 -0
  13. maproom/analyze/context_lookup.py +142 -0
  14. maproom/analyze/cover_analyze.py +344 -0
  15. maproom/analyze/cover_client.py +65 -0
  16. maproom/analyze/cover_lookup.py +242 -0
  17. maproom/analyze/engine.py +644 -0
  18. maproom/analyze/fleetfit_endpoints.py +217 -0
  19. maproom/analyze/fleetfit_policy.py +66 -0
  20. maproom/analyze/instance_price_analyze.py +221 -0
  21. maproom/analyze/instance_price_client.py +108 -0
  22. maproom/analyze/instance_price_lookup.py +60 -0
  23. maproom/analyze/local_reads.py +484 -0
  24. maproom/analyze/lookup_http.py +280 -0
  25. maproom/analyze/metric_format.py +20 -0
  26. maproom/analyze/migration_method.py +130 -0
  27. maproom/analyze/move_list.py +93 -0
  28. maproom/analyze/operator_context.py +156 -0
  29. maproom/analyze/performance_rank.py +97 -0
  30. maproom/analyze/primary_recommendation.py +422 -0
  31. maproom/analyze/provider_comparison.py +401 -0
  32. maproom/analyze/quota_analyze.py +481 -0
  33. maproom/analyze/quota_client.py +75 -0
  34. maproom/analyze/quota_lookup.py +110 -0
  35. maproom/analyze/quota_outcome_steer.py +105 -0
  36. maproom/analyze/recommend_batch.py +199 -0
  37. maproom/analyze/recommend_client.py +362 -0
  38. maproom/analyze/recommend_share.py +118 -0
  39. maproom/analyze/recommendation.py +591 -0
  40. maproom/analyze/reservation_pack.py +883 -0
  41. maproom/analyze/reservation_read.py +461 -0
  42. maproom/analyze/safe_analyze.py +1134 -0
  43. maproom/analyze/safe_move.py +195 -0
  44. maproom/analyze/safe_moves.py +571 -0
  45. maproom/analyze/safe_moves_catalog.py +127 -0
  46. maproom/analyze/safe_moves_client.py +70 -0
  47. maproom/analyze/series_analyze.py +491 -0
  48. maproom/analyze/series_client.py +106 -0
  49. maproom/analyze/series_lookup.py +663 -0
  50. maproom/analyze/shape.py +254 -0
  51. maproom/analyze/size_analyze.py +883 -0
  52. maproom/analyze/size_client.py +81 -0
  53. maproom/analyze/size_keep.py +409 -0
  54. maproom/analyze/size_lookup.py +368 -0
  55. maproom/analyze/specs.py +325 -0
  56. maproom/analyze/spot_analyze.py +392 -0
  57. maproom/analyze/spot_client.py +74 -0
  58. maproom/analyze/spot_lookup.py +213 -0
  59. maproom/analyze/token_client.py +97 -0
  60. maproom/analyze/utilization.py +190 -0
  61. maproom/analyze/workload.py +104 -0
  62. maproom/analyze/workset.py +762 -0
  63. maproom/aws_region.py +78 -0
  64. maproom/cache/__init__.py +1 -0
  65. maproom/cache/catalog.py +372 -0
  66. maproom/cache/commands.py +215 -0
  67. maproom/cache/instances.py +460 -0
  68. maproom/cli.py +2084 -0
  69. maproom/cli_argv.py +329 -0
  70. maproom/cli_floors.py +89 -0
  71. maproom/cliio/__init__.py +1 -0
  72. maproom/cliio/registry.py +377 -0
  73. maproom/cliio/runner.py +489 -0
  74. maproom/consent/__init__.py +33 -0
  75. maproom/consent/gate.py +238 -0
  76. maproom/consent/policy.py +20 -0
  77. maproom/consent/prompt.py +61 -0
  78. maproom/consent/service_upload_gate.py +318 -0
  79. maproom/consent/service_upload_prompt.py +62 -0
  80. maproom/consent/stdin.py +45 -0
  81. maproom/consent/storage.py +24 -0
  82. maproom/consent/write_token.py +29 -0
  83. maproom/contracts/__init__.py +6 -0
  84. maproom/contracts/schema_diff.py +119 -0
  85. maproom/contracts/validate.py +113 -0
  86. maproom/data/__init__.py +1 -0
  87. maproom/data/clear.py +76 -0
  88. maproom/data/commands.py +14 -0
  89. maproom/doctor/__init__.py +1 -0
  90. maproom/doctor/aws_session.py +226 -0
  91. maproom/doctor/checks.py +701 -0
  92. maproom/doctor/context.py +32 -0
  93. maproom/doctor/display.py +96 -0
  94. maproom/doctor/inventory_display.py +377 -0
  95. maproom/doctor/runner.py +1467 -0
  96. maproom/errors.py +43 -0
  97. maproom/exitcodes.py +70 -0
  98. maproom/inventory/__init__.py +1 -0
  99. maproom/inventory/account_identity.py +79 -0
  100. maproom/inventory/accounts.py +155 -0
  101. maproom/inventory/command.py +961 -0
  102. maproom/inventory/messages.py +264 -0
  103. maproom/inventory/reservations_refresh.py +37 -0
  104. maproom/mock_environment/__init__.py +28 -0
  105. maproom/mock_environment/load.py +241 -0
  106. maproom/mock_environment/runner.py +387 -0
  107. maproom/output/__init__.py +1 -0
  108. maproom/output/json_envelope.py +241 -0
  109. maproom/output/redact.py +11 -0
  110. maproom/output/terminal.py +129 -0
  111. maproom/parsers.py +284 -0
  112. maproom/paths.py +105 -0
  113. maproom/plan/__init__.py +1 -0
  114. maproom/plan/accept.py +59 -0
  115. maproom/plan/analysis_context.py +78 -0
  116. maproom/plan/analyze_selection.py +279 -0
  117. maproom/plan/commands.py +586 -0
  118. maproom/plan/current.py +59 -0
  119. maproom/plan/errors.py +10 -0
  120. maproom/plan/export.py +36 -0
  121. maproom/plan/formatting.py +91 -0
  122. maproom/plan/ids.py +13 -0
  123. maproom/plan/migration_options.py +75 -0
  124. maproom/plan/model.py +265 -0
  125. maproom/plan/names.py +24 -0
  126. maproom/plan/store.py +193 -0
  127. maproom/plan/tty.py +34 -0
  128. maproom/pricing/__init__.py +5 -0
  129. maproom/pricing/prices.py +119 -0
  130. maproom/privacy/__init__.py +6 -0
  131. maproom/privacy/commands.py +159 -0
  132. maproom/privacy/delete_uploads.py +204 -0
  133. maproom/privacy/fleetfit_policy.py +125 -0
  134. maproom/privacy/fleetfit_statement.py +104 -0
  135. maproom/privacy/format.py +76 -0
  136. maproom/privacy/manifests.py +342 -0
  137. maproom/privacy/statement.py +58 -0
  138. maproom/quotas/__init__.py +21 -0
  139. maproom/quotas/aws.py +204 -0
  140. maproom/quotas/azure.py +75 -0
  141. maproom/quotas/commands.py +240 -0
  142. maproom/quotas/family_coverage.py +122 -0
  143. maproom/quotas/fetch.py +124 -0
  144. maproom/quotas/load.py +41 -0
  145. maproom/quotas/model.py +178 -0
  146. maproom/quotas/outcome_ledger.py +245 -0
  147. maproom/quotas/quota_request_sync.py +221 -0
  148. maproom/quotas/show.py +73 -0
  149. maproom/quotas/status.py +206 -0
  150. maproom/quotas/store.py +161 -0
  151. maproom/redaction.py +157 -0
  152. maproom/reference_data/__init__.py +1 -0
  153. maproom/reference_data/aws/aws_prices.csv +25562 -0
  154. maproom/reference_data/aws/capabilities.csv +1346 -0
  155. maproom/reference_data/aws/instance_types.csv +1346 -0
  156. maproom/reference_data/azure/azure_prices.csv +1 -0
  157. maproom/reference_data/azure/vm_types.csv +1 -0
  158. maproom/reference_data/benchmarks/cpu-lscpu-v2-instances.json +27 -0
  159. maproom/reference_data/benchmarks/safe-moves-v1.json +328 -0
  160. maproom/reference_data/manifest.json +174 -0
  161. maproom/reference_data/manifest.py +69 -0
  162. maproom/reservations/__init__.py +17 -0
  163. maproom/reservations/aws.py +76 -0
  164. maproom/reservations/azure.py +36 -0
  165. maproom/reservations/commands.py +149 -0
  166. maproom/reservations/load.py +41 -0
  167. maproom/reservations/model.py +316 -0
  168. maproom/reservations/show.py +64 -0
  169. maproom/reservations/status.py +181 -0
  170. maproom/reservations/store.py +391 -0
  171. maproom/resources.py +54 -0
  172. maproom/root_help.py +251 -0
  173. maproom/saving_plans/__init__.py +15 -0
  174. maproom/saving_plans/aws.py +73 -0
  175. maproom/saving_plans/commands.py +122 -0
  176. maproom/saving_plans/load.py +41 -0
  177. maproom/saving_plans/model.py +101 -0
  178. maproom/saving_plans/show.py +64 -0
  179. maproom/saving_plans/status.py +118 -0
  180. maproom/saving_plans/store.py +173 -0
  181. maproom/secret_egress_gate.py +108 -0
  182. maproom/service/install_id.py +60 -0
  183. maproom/settings/__init__.py +1 -0
  184. maproom/settings/defaults.py +73 -0
  185. maproom/settings/init.py +143 -0
  186. maproom/settings/model.py +105 -0
  187. maproom/settings/product_version_change.py +343 -0
  188. maproom/settings/product_versions.py +68 -0
  189. maproom/settings/set.py +347 -0
  190. maproom/settings/show.py +227 -0
  191. maproom/settings/write.py +273 -0
  192. maproom/snapshot_time.py +27 -0
  193. maproom-0.2.0.dist-info/METADATA +263 -0
  194. maproom-0.2.0.dist-info/RECORD +199 -0
  195. maproom-0.2.0.dist-info/WHEEL +5 -0
  196. maproom-0.2.0.dist-info/entry_points.txt +2 -0
  197. maproom-0.2.0.dist-info/licenses/LICENSE +201 -0
  198. maproom-0.2.0.dist-info/licenses/NOTICE +72 -0
  199. maproom-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,663 @@
1
+ """Utilization recommend body/response for product version 5 (unified FleetFit contract)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import re
8
+ from dataclasses import dataclass
9
+ from functools import lru_cache
10
+ from importlib import resources
11
+ from typing import Any, Mapping
12
+
13
+ from maproom.analyze.catalog import SpecRow, is_burstable_family, spec_architecture
14
+ from maproom.analyze.fleetfit_policy import fleetfit_policy_accept_hint
15
+ from maproom.analyze.shape import SHAPE_ATTRIBUTES
16
+ from maproom.consent.service_upload_prompt import ENABLE_UPLOADS_HINT
17
+ from maproom.settings.defaults import DEFAULT_SETTINGS
18
+
19
+ WINDOW_DAYS = 7
20
+ SAMPLE_MINUTES = 1
21
+ DEFAULT_CPU_HEADROOM = float(DEFAULT_SETTINGS["desired_cpu_p99"])
22
+ DEFAULT_MEMORY_HEADROOM = float(DEFAULT_SETTINGS["desired_memory_p99"])
23
+ DEFAULT_NETWORK_HEADROOM_PCT = float(DEFAULT_SETTINGS["desired_network_headroom_pct"])
24
+ DEFAULT_DISK_HEADROOM_PCT = float(DEFAULT_SETTINGS["desired_disk_headroom_pct"])
25
+ GIB_PER_SEC = 1024.0**3
26
+ _NETWORK_IOPS_PER_GBPS = 50_000.0
27
+
28
+ _FILTER_NAMES = frozenset(item.name for item in SHAPE_ATTRIBUTES)
29
+
30
+ KEEP_FLAGS = (
31
+ "keep_region",
32
+ "keep_az",
33
+ "keep_cpu_architecture",
34
+ "keep_instance_family",
35
+ "keep_instance_generation",
36
+ "keep_instance_size",
37
+ "keep_burstable",
38
+ "keep_has_instance_disks",
39
+ "keep_is_spot",
40
+ )
41
+
42
+ RESPONSE_KEYS = frozenset(
43
+ {
44
+ "schema_version",
45
+ "recommended_instance_type",
46
+ "projected_fit",
47
+ "credit_result",
48
+ "credit_holds",
49
+ "fits_while_bursting",
50
+ "sustained",
51
+ "quota_family",
52
+ "latest_hourly",
53
+ "explanation",
54
+ "metrics",
55
+ }
56
+ )
57
+
58
+ _FORBIDDEN_KEYS = frozenset(
59
+ {
60
+ "instance_id",
61
+ "account_id",
62
+ "volume_id",
63
+ "arn",
64
+ "spot_instance_request_id",
65
+ "reservation_id",
66
+ }
67
+ )
68
+ _INSTANCE_ID_RE = re.compile(r"i-[0-9a-f]{8,}", re.IGNORECASE)
69
+ _VOLUME_ID_RE = re.compile(r"vol-[0-9a-f]{8,}", re.IGNORECASE)
70
+ _ACCOUNT_ID_RE = re.compile(r"(?<!\d)\d{12}(?!\d)")
71
+ _DECIMAL_RE = re.compile(r"^\d+(\.\d+)?$")
72
+ _METRIC_RE = re.compile(r"^(p99|max|min)-(\d+)min$")
73
+
74
+ DECLINED_DETAIL = "The utilization lookup was declined."
75
+ DECLINED_LINE = f"{DECLINED_DETAIL} {ENABLE_UPLOADS_HINT}"
76
+ MISSING_POLICY_LINE = (
77
+ "The utilization lookup was not sent: the FleetFit handling policy is not accepted. "
78
+ + fleetfit_policy_accept_hint()
79
+ )
80
+ NOT_SENT_LINE = "The utilization lookup was not sent."
81
+ NOT_CONFIGURED_LINE = (
82
+ "Cross-family utilization fit was skipped: it would compare CloudWatch metrics "
83
+ "across instance families, but no FleetFit recommend endpoint is configured. "
84
+ "Run maproom settings show or set cloud_analyze_protocol_hostname_port to enable it."
85
+ )
86
+ NOT_IMPLEMENTED_LINE = (
87
+ "Cross-family utilization fit was skipped: the FleetFit recommend endpoint has "
88
+ "not implemented utilization recommend yet."
89
+ )
90
+ INCOMPLETE_LINE = "The week of metrics was incomplete."
91
+ BURST_LINE = "It fits while bursting."
92
+ CREDIT_LINE = "The credit balance does not hold for the week."
93
+ UNKNOWN_TYPE_LINE = "The returned type is not in the spec table."
94
+ QUOTA_FAMILY_MISMATCH_LINE = "The returned quota family does not match the spec table."
95
+ OUTSIDE_QUOTA_LINE = "This type is outside the current quota family. Quota was not read."
96
+
97
+
98
+ class SeriesNotImplementedError(ValueError):
99
+ """FleetFit returned a not-implemented stub."""
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class SeriesJudgment:
104
+ line: str
105
+ passed: bool
106
+ instance_type: str | None
107
+ projected_fit: str | None
108
+ grade_gap_log: str | None
109
+ credit_result: str | None
110
+ fits_while_bursting: bool
111
+ quota_family: str | None
112
+ omitted: bool
113
+
114
+
115
+ def is_series_stub(payload: object) -> bool:
116
+ if not isinstance(payload, dict):
117
+ return False
118
+ keys = set(payload)
119
+ if keys == {"passed", "detail"}:
120
+ return isinstance(payload.get("passed"), bool) and isinstance(payload.get("detail"), str)
121
+ if keys == {"status"}:
122
+ return payload.get("status") == "not_implemented"
123
+ return False
124
+
125
+
126
+ def _positive_setting(settings: Mapping[str, Any] | None, key: str, default: float) -> float:
127
+ raw = default if settings is None else settings.get(key, default)
128
+ if isinstance(raw, bool) or not isinstance(raw, (int, float)):
129
+ return default
130
+ number = float(raw)
131
+ if not math.isfinite(number) or number <= 0:
132
+ return default
133
+ return number
134
+
135
+
136
+ def _percent_setting(settings: Mapping[str, Any] | None, key: str, default: float) -> float:
137
+ number = _positive_setting(settings, key, default)
138
+ if number > 100:
139
+ return default
140
+ return number
141
+
142
+
143
+ @lru_cache(maxsize=1)
144
+ def _safe_move_instance_types() -> dict[str, dict[str, Any]]:
145
+ raw = (
146
+ resources.files("maproom")
147
+ .joinpath("reference_data", "benchmarks", "safe-moves-v1.json")
148
+ .read_text(encoding="utf-8")
149
+ )
150
+ document = json.loads(raw)
151
+ rows = document.get("instance_types")
152
+ if not isinstance(rows, dict):
153
+ return {}
154
+ out: dict[str, dict[str, Any]] = {}
155
+ for name, row in rows.items():
156
+ if isinstance(name, str) and isinstance(row, dict):
157
+ out[name] = row
158
+ return out
159
+
160
+
161
+ def _optional_capacity(row: Mapping[str, Any], key: str) -> float | None:
162
+ raw = row.get(key)
163
+ if isinstance(raw, bool) or not isinstance(raw, (int, float)):
164
+ return None
165
+ number = float(raw)
166
+ if not math.isfinite(number) or number <= 0:
167
+ return None
168
+ return number
169
+
170
+
171
+ def build_desired_headroom(
172
+ settings: Mapping[str, Any] | None = None,
173
+ *,
174
+ instance_type: str | None = None,
175
+ has_memory_metric: bool = False,
176
+ ) -> dict[str, float]:
177
+ """Operator headroom for utilization recommend, calibrated to current type."""
178
+ cpu = _positive_setting(settings, "desired_cpu_p99", DEFAULT_CPU_HEADROOM)
179
+ headroom: dict[str, float] = {
180
+ "max_cpu_percent_p99_1min_with_headroom": float(cpu),
181
+ }
182
+ if has_memory_metric:
183
+ memory = _positive_setting(
184
+ settings, "desired_memory_p99", DEFAULT_MEMORY_HEADROOM
185
+ )
186
+ headroom["max_memory_percent_p99_1min_with_headroom"] = float(memory)
187
+
188
+ name = (instance_type or "").strip()
189
+ row = _safe_move_instance_types().get(name) if name else None
190
+ if row is None:
191
+ return headroom
192
+
193
+ net_pct = _percent_setting(
194
+ settings, "desired_network_headroom_pct", DEFAULT_NETWORK_HEADROOM_PCT
195
+ )
196
+ disk_pct = _percent_setting(
197
+ settings, "desired_disk_headroom_pct", DEFAULT_DISK_HEADROOM_PCT
198
+ )
199
+ net_scale = net_pct / 100.0
200
+ disk_scale = disk_pct / 100.0
201
+
202
+ net_bits = _optional_capacity(row, "network_max_bits_per_sec")
203
+ if net_bits is not None:
204
+ gbps = net_bits / 1_000_000_000.0
205
+ headroom["network_iops_1min"] = gbps * _NETWORK_IOPS_PER_GBPS * net_scale
206
+ headroom["network_throughput_gib_per_sec_1min"] = (
207
+ (net_bits / 8.0) / GIB_PER_SEC
208
+ ) * net_scale
209
+
210
+ disk_iops = _optional_capacity(row, "ebs_max_iops")
211
+ if disk_iops is not None:
212
+ headroom["disk_iops_1min"] = disk_iops * disk_scale
213
+
214
+ disk_bytes = _optional_capacity(row, "ebs_max_throughput_bytes_per_sec")
215
+ if disk_bytes is not None:
216
+ headroom["disk_throughput_gib_per_sec_1min"] = (
217
+ disk_bytes / GIB_PER_SEC
218
+ ) * disk_scale
219
+
220
+ return headroom
221
+
222
+
223
+ def shape_to_recommendation_shape(
224
+ *,
225
+ modify: frozenset[str] | set[str],
226
+ keep: frozenset[str] | set[str],
227
+ keep_region: bool = True,
228
+ keep_az: bool = True,
229
+ keep_is_spot: bool = True,
230
+ cpu_headroom: float | None = None,
231
+ desired_headroom: Mapping[str, float] | None = None,
232
+ settings: Mapping[str, Any] | None = None,
233
+ instance_type: str | None = None,
234
+ has_memory_metric: bool = False,
235
+ quantity_min: int = 1,
236
+ quantity_max: int = 1,
237
+ ) -> dict[str, Any]:
238
+ """Map Maproom --shape modify/keep into closed recommendation_shape."""
239
+ keep_set = set(keep)
240
+ modify_set = set(modify)
241
+ # Attribute may change if in modify (and not keep). Omitted --shape keeps burstable; others may change.
242
+ def _keep_attr(name: str) -> bool:
243
+ if name in keep_set:
244
+ return True
245
+ if name in modify_set:
246
+ return False
247
+ return True
248
+
249
+ if desired_headroom is not None:
250
+ headroom = {key: float(value) for key, value in desired_headroom.items()}
251
+ else:
252
+ headroom = build_desired_headroom(
253
+ settings,
254
+ instance_type=instance_type,
255
+ has_memory_metric=has_memory_metric,
256
+ )
257
+ if cpu_headroom is not None:
258
+ headroom["max_cpu_percent_p99_1min_with_headroom"] = float(cpu_headroom)
259
+
260
+ return {
261
+ "keep_region": bool(keep_region),
262
+ "keep_az": bool(keep_az),
263
+ "keep_cpu_architecture": _keep_attr("processor_architecture"),
264
+ "keep_instance_family": _keep_attr("instance_family"),
265
+ "keep_instance_generation": _keep_attr("instance_generation"),
266
+ "keep_instance_size": _keep_attr("instance_size"),
267
+ "keep_burstable": _keep_attr("burstable"),
268
+ "keep_has_instance_disks": _keep_attr("has_instance_disks"),
269
+ "keep_is_spot": bool(keep_is_spot),
270
+ "instance_quantity_min": int(quantity_min),
271
+ "instance_quantity_max": int(quantity_max),
272
+ "desired_headroom": headroom,
273
+ }
274
+
275
+
276
+ def summary_to_utilization_metrics(summary: dict[str, Any]) -> list[dict[str, Any]]:
277
+ """Convert legacy week summary dict into metric children (1-minute samples)."""
278
+ cpu_p99 = summary.get("cpu_p99")
279
+ if cpu_p99 is None:
280
+ raise ValueError("summary missing cpu_p99")
281
+ metrics: list[dict[str, Any]] = [
282
+ {
283
+ "name": "cpu",
284
+ "sample_minutes": SAMPLE_MINUTES,
285
+ "metric": "p99-1min",
286
+ "value": float(cpu_p99),
287
+ },
288
+ ]
289
+ cpu_max = summary.get("cpu_max")
290
+ if cpu_max is not None:
291
+ metrics.append(
292
+ {
293
+ "name": "cpu",
294
+ "sample_minutes": SAMPLE_MINUTES,
295
+ "metric": "max-1min",
296
+ "value": float(cpu_max),
297
+ }
298
+ )
299
+ memory_p99 = summary.get("memory_p99")
300
+ if memory_p99 is not None:
301
+ metrics.append(
302
+ {
303
+ "name": "memory",
304
+ "sample_minutes": SAMPLE_MINUTES,
305
+ "metric": "p99-1min",
306
+ "value": float(memory_p99),
307
+ }
308
+ )
309
+ net_p99 = summary.get("network_bytes_per_second_p99")
310
+ if net_p99 is not None:
311
+ metrics.append(
312
+ {
313
+ "name": "network_throughput",
314
+ "sample_minutes": SAMPLE_MINUTES,
315
+ "metric": "p99-1min",
316
+ "value": float(net_p99),
317
+ }
318
+ )
319
+ net_iops = summary.get("network_iops_p99")
320
+ if net_iops is not None:
321
+ metrics.append(
322
+ {
323
+ "name": "network_iops",
324
+ "sample_minutes": SAMPLE_MINUTES,
325
+ "metric": "p99-1min",
326
+ "value": float(net_iops),
327
+ }
328
+ )
329
+ disk_p99 = summary.get("disk_bytes_per_second_p99")
330
+ if disk_p99 is not None:
331
+ metrics.append(
332
+ {
333
+ "name": "disk_throughput",
334
+ "sample_minutes": SAMPLE_MINUTES,
335
+ "metric": "p99-1min",
336
+ "value": float(disk_p99),
337
+ }
338
+ )
339
+ disk_iops = summary.get("disk_iops_p99")
340
+ if disk_iops is not None:
341
+ metrics.append(
342
+ {
343
+ "name": "disk_iops",
344
+ "sample_minutes": SAMPLE_MINUTES,
345
+ "metric": "p99-1min",
346
+ "value": float(disk_iops),
347
+ }
348
+ )
349
+ balance = summary.get("credit_balance_min")
350
+ if balance is not None:
351
+ metrics.append(
352
+ {
353
+ "name": "credit_balance",
354
+ "sample_minutes": SAMPLE_MINUTES,
355
+ "metric": "min-1min",
356
+ "value": float(balance),
357
+ }
358
+ )
359
+ usage = summary.get("credit_usage_p99")
360
+ if usage is not None:
361
+ metrics.append(
362
+ {
363
+ "name": "credit_usage",
364
+ "sample_minutes": SAMPLE_MINUTES,
365
+ "metric": "p99-1min",
366
+ "value": float(usage),
367
+ }
368
+ )
369
+ return metrics
370
+
371
+
372
+ def build_utilization_body(
373
+ *,
374
+ instance_type: str,
375
+ region: str,
376
+ az: str,
377
+ is_spot: bool,
378
+ utilization_metrics: list[dict[str, Any]],
379
+ recommendation_shape: dict[str, Any],
380
+ ) -> dict[str, Any]:
381
+ body = {
382
+ "provider": "aws",
383
+ "instance_type": instance_type.strip(),
384
+ "region": region.strip(),
385
+ "az": az.strip(),
386
+ "is_spot": bool(is_spot),
387
+ "utilization_metrics": list(utilization_metrics),
388
+ "recommendation_shape": recommendation_shape,
389
+ }
390
+ require_utilization_body(body)
391
+ return body
392
+
393
+
394
+ def require_utilization_body(body: dict[str, Any]) -> None:
395
+ if not isinstance(body, dict):
396
+ raise ValueError("utilization body must be an object")
397
+ expected = {
398
+ "provider",
399
+ "instance_type",
400
+ "region",
401
+ "az",
402
+ "is_spot",
403
+ "utilization_metrics",
404
+ "recommendation_shape",
405
+ }
406
+ if set(body) != expected:
407
+ raise ValueError("utilization body keys are closed")
408
+ _reject_id_shaped(body)
409
+ if body.get("provider") != "aws":
410
+ raise ValueError("provider must be aws")
411
+ for key in ("instance_type", "region", "az"):
412
+ value = body.get(key)
413
+ if not isinstance(value, str) or not value.strip():
414
+ raise ValueError("utilization body has an empty field")
415
+ if not isinstance(body.get("is_spot"), bool):
416
+ raise ValueError("is_spot must be a boolean")
417
+ _require_metrics(body.get("utilization_metrics"))
418
+ _require_shape(body.get("recommendation_shape"))
419
+
420
+
421
+ def require_series_response(payload: object) -> dict[str, Any]:
422
+ """Accept FleetFit utilization closed response (name kept for call sites)."""
423
+ if not isinstance(payload, dict):
424
+ raise ValueError("utilization response must be an object")
425
+ if is_series_stub(payload):
426
+ detail = payload.get("detail") if isinstance(payload.get("detail"), str) else NOT_IMPLEMENTED_LINE
427
+ raise SeriesNotImplementedError(str(detail))
428
+ missing = RESPONSE_KEYS - set(payload)
429
+ if missing:
430
+ raise ValueError("utilization response keys are closed")
431
+ extra = set(payload) - RESPONSE_KEYS
432
+ if extra:
433
+ for key in extra:
434
+ if key.lower() in _FORBIDDEN_KEYS:
435
+ raise ValueError("utilization response contains a forbidden key")
436
+ _reject_id_shaped(payload)
437
+ payload = {key: payload[key] for key in RESPONSE_KEYS}
438
+ _reject_id_shaped(payload)
439
+ if payload.get("schema_version") != 1:
440
+ raise ValueError("schema_version must be 1")
441
+ recommended = payload.get("recommended_instance_type")
442
+ if recommended is not None and (not isinstance(recommended, str) or not recommended.strip()):
443
+ raise ValueError("recommended_instance_type must be a type name or null")
444
+ for key in ("projected_fit", "explanation", "quota_family"):
445
+ value = payload.get(key)
446
+ if not isinstance(value, str) or not value.strip():
447
+ raise ValueError(f"utilization response has an empty {key}")
448
+ credit = payload.get("credit_result")
449
+ if credit is not None and not isinstance(credit, str):
450
+ raise ValueError("credit_result must be a string or null")
451
+ for key in ("credit_holds", "fits_while_bursting", "sustained"):
452
+ if not isinstance(payload.get(key), bool):
453
+ raise ValueError(f"{key} must be a boolean")
454
+ hourly = payload.get("latest_hourly")
455
+ if hourly is not None:
456
+ if not isinstance(hourly, str) or _DECIMAL_RE.match(hourly) is None:
457
+ raise ValueError("latest_hourly must be a decimal string or null")
458
+ metrics = payload.get("metrics")
459
+ if not isinstance(metrics, list):
460
+ raise ValueError("metrics must be a list")
461
+ return payload
462
+
463
+
464
+ def judge_series_response(
465
+ response: dict[str, Any],
466
+ *,
467
+ current: SpecRow,
468
+ specs: dict[tuple[str, str], SpecRow],
469
+ modify: frozenset[str],
470
+ keep: frozenset[str],
471
+ price_table_stale: bool = False,
472
+ ) -> SeriesJudgment:
473
+ del price_table_stale
474
+ require_series_response(response)
475
+ projected = str(response["projected_fit"]).strip()
476
+ explanation = str(response["explanation"]).strip()
477
+ credit_result = response.get("credit_result")
478
+ credit_text = credit_result.strip() if isinstance(credit_result, str) else None
479
+ fits_while_bursting = bool(response["fits_while_bursting"])
480
+ sustained = bool(response["sustained"])
481
+ recommended = response.get("recommended_instance_type")
482
+ named = recommended.strip() if isinstance(recommended, str) else ""
483
+
484
+ def _omit(line: str, *, instance_type: str | None = None, quota_family: str | None = None) -> SeriesJudgment:
485
+ return SeriesJudgment(
486
+ line=line,
487
+ passed=False,
488
+ instance_type=instance_type,
489
+ projected_fit=projected,
490
+ grade_gap_log=None,
491
+ credit_result=credit_text,
492
+ fits_while_bursting=fits_while_bursting,
493
+ quota_family=quota_family,
494
+ omitted=True,
495
+ )
496
+
497
+ if not named:
498
+ return _omit(explanation)
499
+ target = specs.get((current.cloud, named))
500
+ if target is None:
501
+ return _omit(UNKNOWN_TYPE_LINE)
502
+ if (target.quota_family or "").strip() != str(response["quota_family"]).strip():
503
+ return _omit(QUOTA_FAMILY_MISMATCH_LINE)
504
+ blocked = _blocked_shape_attribute(current, target, modify=modify, keep=keep)
505
+ if blocked:
506
+ line = f"The returned type changes {blocked}, which --shape did not allow."
507
+ return _omit(line, instance_type=named, quota_family=target.quota_family)
508
+ if fits_while_bursting and not sustained:
509
+ return _omit(f"{explanation} {BURST_LINE}", instance_type=named, quota_family=target.quota_family)
510
+ if is_burstable_family(target.family) and not response["credit_holds"]:
511
+ return _omit(f"{explanation} {CREDIT_LINE}", instance_type=named, quota_family=target.quota_family)
512
+
513
+ parts = [explanation, projected]
514
+ if credit_text and is_burstable_family(target.family):
515
+ parts.append(credit_text)
516
+ if (current.quota_family or "").strip() != (target.quota_family or "").strip():
517
+ parts.append(OUTSIDE_QUOTA_LINE)
518
+ hourly = response.get("latest_hourly")
519
+ if isinstance(hourly, str) and hourly.strip():
520
+ parts.append(f"USD {hourly}/hour for the named type.")
521
+ return SeriesJudgment(
522
+ line=" ".join(parts),
523
+ passed=True,
524
+ instance_type=named,
525
+ projected_fit=projected,
526
+ grade_gap_log=None,
527
+ credit_result=credit_text,
528
+ fits_while_bursting=fits_while_bursting,
529
+ quota_family=(target.quota_family or "").strip() or None,
530
+ omitted=False,
531
+ )
532
+
533
+
534
+ def _blocked_shape_attribute(
535
+ current: SpecRow,
536
+ target: SpecRow,
537
+ *,
538
+ modify: frozenset[str],
539
+ keep: frozenset[str],
540
+ ) -> str | None:
541
+ changed = _changed_attributes(current, target)
542
+ for attr in sorted(changed):
543
+ if attr in keep:
544
+ return attr
545
+ if modify:
546
+ disallowed = changed - modify
547
+ if disallowed:
548
+ return sorted(disallowed)[0]
549
+ return None
550
+
551
+
552
+ def _changed_attributes(current: SpecRow, target: SpecRow) -> set[str]:
553
+ changed: set[str] = set()
554
+ if current.family != target.family:
555
+ changed.add("instance_family")
556
+ if current.generation != target.generation:
557
+ changed.add("instance_generation")
558
+ if _size_suffix(current.instance_type) != _size_suffix(target.instance_type):
559
+ changed.add("instance_size")
560
+ if spec_architecture(current) != spec_architecture(target):
561
+ changed.add("processor_architecture")
562
+ if (current.ephemeral_disk_total_gb > 0) != (target.ephemeral_disk_total_gb > 0):
563
+ changed.add("has_instance_disks")
564
+ if is_burstable_family(current.family) != is_burstable_family(target.family):
565
+ changed.add("burstable")
566
+ return changed
567
+
568
+
569
+ def _size_suffix(instance_type: str) -> str:
570
+ if "." not in instance_type:
571
+ return ""
572
+ return instance_type.split(".", 1)[1]
573
+
574
+
575
+ def _require_metrics(raw: object) -> None:
576
+ if not isinstance(raw, list) or not raw:
577
+ raise ValueError("utilization_metrics must be a non-empty list")
578
+ seen: set[tuple[str, str]] = set()
579
+ for item in raw:
580
+ if not isinstance(item, dict) or set(item) != {"name", "sample_minutes", "metric", "value"}:
581
+ raise ValueError("utilization metric child is closed")
582
+ name = item["name"]
583
+ metric = item["metric"]
584
+ sample = item["sample_minutes"]
585
+ if not isinstance(name, str) or not isinstance(metric, str):
586
+ raise ValueError("utilization metric child is invalid")
587
+ match = _METRIC_RE.match(metric)
588
+ if match is None or not isinstance(sample, int) or isinstance(sample, bool):
589
+ raise ValueError("utilization metric child is invalid")
590
+ if int(match.group(2)) != sample:
591
+ raise ValueError("utilization metric sample_minutes mismatch")
592
+ key = (name, metric)
593
+ if key in seen:
594
+ raise ValueError("duplicate utilization metric")
595
+ seen.add(key)
596
+ if not any(
597
+ isinstance(item, dict)
598
+ and item.get("name") == "cpu"
599
+ and str(item.get("metric", "")).startswith("p99-")
600
+ for item in raw
601
+ ):
602
+ raise ValueError("cpu p99 metric is required")
603
+
604
+
605
+ def _require_shape(raw: object) -> None:
606
+ if not isinstance(raw, dict):
607
+ raise ValueError("recommendation_shape must be an object")
608
+ required = set(KEEP_FLAGS) | {
609
+ "instance_quantity_min",
610
+ "instance_quantity_max",
611
+ "desired_headroom",
612
+ }
613
+ if set(raw) != required:
614
+ raise ValueError("recommendation_shape keys are closed")
615
+ for key in KEEP_FLAGS:
616
+ if not isinstance(raw.get(key), bool):
617
+ raise ValueError(f"{key} must be a boolean")
618
+ qmin = raw.get("instance_quantity_min")
619
+ qmax = raw.get("instance_quantity_max")
620
+ if not isinstance(qmin, int) or isinstance(qmin, bool) or qmin <= 0:
621
+ raise ValueError("instance_quantity_min is invalid")
622
+ if not isinstance(qmax, int) or isinstance(qmax, bool) or qmax < qmin:
623
+ raise ValueError("instance_quantity_max is invalid")
624
+ headroom = raw.get("desired_headroom")
625
+ if not isinstance(headroom, dict) or (
626
+ "max_cpu_percent_p99_1min_with_headroom" not in headroom
627
+ ):
628
+ raise ValueError(
629
+ "desired_headroom requires max_cpu_percent_p99_1min_with_headroom"
630
+ )
631
+
632
+
633
+ def _reject_id_shaped(value: object, *, key: object = None) -> None:
634
+ if isinstance(key, str) and key.lower() in _FORBIDDEN_KEYS:
635
+ raise ValueError("utilization body contains a forbidden key")
636
+ if isinstance(value, dict):
637
+ for child_key, child in value.items():
638
+ _reject_id_shaped(child, key=child_key)
639
+ return
640
+ if isinstance(value, list):
641
+ for child in value:
642
+ _reject_id_shaped(child)
643
+ return
644
+ if isinstance(value, str):
645
+ if _INSTANCE_ID_RE.search(value) or _VOLUME_ID_RE.search(value) or _ACCOUNT_ID_RE.search(value):
646
+ raise ValueError("utilization body contains a forbidden id")
647
+
648
+
649
+ # Back-compat aliases used by older imports/tests during migration
650
+ def build_series_body(**kwargs: Any) -> dict[str, Any]:
651
+ raise ValueError("build_series_body was removed; use build_utilization_body")
652
+
653
+
654
+ def require_series_body(body: dict[str, Any]) -> None:
655
+ require_utilization_body(body)
656
+
657
+
658
+ def build_grade(*_args: Any, **_kwargs: Any) -> dict[str, Any]:
659
+ raise ValueError("grade was removed from utilization recommend")
660
+
661
+
662
+ def price_table_is_stale(_settings: dict[str, Any] | None = None) -> bool:
663
+ return False