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,368 @@
1
+ """Closed same_type_size_change body and the line printed from a fleetfit response."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from datetime import datetime, timezone
7
+ from decimal import Decimal
8
+ from typing import Any
9
+
10
+ from maproom.analyze.catalog import SpecRow, is_burstable_family, spec_architecture
11
+ from maproom.analyze.metric_format import format_human_metric
12
+ from maproom.analyze.safe_move import size_move_unchecked_footer
13
+ from maproom.analyze.utilization import METRIC_NAMES, SAMPLE_PERIOD_MINUTES, percentile_field
14
+
15
+ REQUEST_TYPE = "same_type_size_change"
16
+
17
+ _BASE_BODY_KEYS = (
18
+ "request_type",
19
+ "provider",
20
+ "region",
21
+ "instance",
22
+ "architecture",
23
+ "quota_family",
24
+ "sample_minutes",
25
+ "window_trimmed",
26
+ "desired_cpu_p99",
27
+ )
28
+
29
+ _FORBIDDEN_KEYS = frozenset(
30
+ {
31
+ "instance_id",
32
+ "name",
33
+ "account_id",
34
+ "volume_id",
35
+ "arn",
36
+ "spot_instance_request_id",
37
+ "reservation_id",
38
+ }
39
+ )
40
+
41
+ _INSTANCE_ID_RE = re.compile(r"i-[0-9a-f]{8,}", re.IGNORECASE)
42
+ _VOLUME_ID_RE = re.compile(r"vol-[0-9a-f]{8,}", re.IGNORECASE)
43
+ _ACCOUNT_ID_RE = re.compile(r"(?<!\d)\d{12}(?!\d)")
44
+
45
+ INCOMPLETE_LINE = "The size description was incomplete."
46
+ DECLINED_LINE = "The size lookup was declined."
47
+ NOT_SENT_LINE = "The size lookup was not sent."
48
+
49
+
50
+ def size_body_keys(*, period_minutes: int = SAMPLE_PERIOD_MINUTES) -> tuple[str, ...]:
51
+ metric_keys = tuple(percentile_field(name, period_minutes) for name in METRIC_NAMES)
52
+ return _BASE_BODY_KEYS + metric_keys
53
+
54
+
55
+ SIZE_BODY_KEYS: tuple[str, ...] = size_body_keys()
56
+
57
+
58
+ def size_body_period_minutes(body: dict[str, Any]) -> int:
59
+ """Infer CloudWatch period from the cpu p99 field name on a closed body."""
60
+ for period_minutes in (1, SAMPLE_PERIOD_MINUTES):
61
+ if percentile_field("cpu", period_minutes) in body:
62
+ return period_minutes
63
+ raise ValueError("size lookup body missing cpu p99 field")
64
+
65
+
66
+ def build_size_body(
67
+ *,
68
+ region: str,
69
+ instance: str,
70
+ architecture: str,
71
+ quota_family: str,
72
+ sample_minutes: int,
73
+ window_trimmed: bool,
74
+ desired_cpu_p99: float,
75
+ readings: dict[str, float | None],
76
+ period_minutes: int = SAMPLE_PERIOD_MINUTES,
77
+ ) -> dict[str, Any]:
78
+ """Build the closed body FleetFit parse_size_body accepts for one period."""
79
+ if sample_minutes <= 0:
80
+ raise ValueError("sample_minutes must be positive")
81
+ if desired_cpu_p99 <= 0:
82
+ raise ValueError("desired_cpu_p99 must be positive")
83
+ if readings.get("cpu") is None:
84
+ raise ValueError("cpu p99 is required")
85
+ body: dict[str, Any] = {
86
+ "request_type": REQUEST_TYPE,
87
+ "provider": "aws",
88
+ "region": region,
89
+ "instance": instance,
90
+ "architecture": architecture,
91
+ "quota_family": quota_family,
92
+ "sample_minutes": int(sample_minutes),
93
+ "window_trimmed": bool(window_trimmed),
94
+ "desired_cpu_p99": float(desired_cpu_p99),
95
+ }
96
+ for name in METRIC_NAMES:
97
+ field = percentile_field(name, period_minutes)
98
+ value = readings.get(name)
99
+ body[field] = None if value is None else float(value)
100
+ _require_closed_size_body(body, period_minutes=period_minutes)
101
+ return body
102
+
103
+
104
+ def prefer_reservation_type(*_args: object, **_kwargs: object) -> None:
105
+ """Version 4 hook. Does not read reservations at product version 3."""
106
+ return None
107
+
108
+
109
+ def _trim_suffix(changed_at: datetime | None) -> str:
110
+ if changed_at is None:
111
+ return ""
112
+ label = changed_at.astimezone(timezone.utc).strftime("%Y-%m-%d")
113
+ return (
114
+ f" Metrics prior to the previous instance type change on {label} were not used."
115
+ )
116
+
117
+
118
+ def _vcpu_label(count: int) -> str:
119
+ suffix = "vCPU" if count == 1 else "vCPUs"
120
+ return f"{count} {suffix}"
121
+
122
+
123
+ def format_size_downsize_hold(
124
+ *,
125
+ target_type: str,
126
+ min_days_since_change: int,
127
+ hold_until: datetime,
128
+ ) -> str:
129
+ """Operator line when a returned downsize is withheld during change cooldown."""
130
+ until_label = hold_until.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
131
+ return (
132
+ f"A downsize to {target_type} was withheld because "
133
+ f"engine.min_days_since_change ({min_days_since_change} days) has not elapsed, "
134
+ f"and downsizing is on hold until {until_label}."
135
+ )
136
+
137
+
138
+ def downsize_on_cooldown(
139
+ current: SpecRow,
140
+ target: SpecRow,
141
+ *,
142
+ cooldown_active: bool,
143
+ ) -> bool:
144
+ """True when an eligible half-vCPU target must be withheld during cooldown."""
145
+ if not cooldown_active:
146
+ return False
147
+ if not _eligible_target(current, target):
148
+ return False
149
+ return target.vcpu == current.vcpu // 2
150
+
151
+
152
+ def _predicted_cpu_label(approx: float) -> str:
153
+ if 90 <= approx < 100:
154
+ return "in the high 90s"
155
+ decade = int(approx // 10) * 10
156
+ if decade <= 0:
157
+ return "in the single digits"
158
+ return f"in the {decade}s"
159
+
160
+
161
+ def same_family_resize_move_line(line: str) -> bool:
162
+ """True when a Move from line stays within one instance family."""
163
+ stripped = line.strip()
164
+ if not stripped.startswith("Move from "):
165
+ return False
166
+ body = stripped.removeprefix("Move from ").strip()
167
+ to_marker = " to "
168
+ if to_marker not in body:
169
+ return False
170
+ left, right = body.split(to_marker, 1)
171
+ from_type = left.split("(", 1)[0].strip()
172
+ to_type = right.split("(", 1)[0].strip().rstrip(".")
173
+ if not from_type or not to_type or "." not in from_type or "." not in to_type:
174
+ return False
175
+ return from_type.split(".", 1)[0] == to_type.split(".", 1)[0]
176
+
177
+
178
+ def text_has_same_family_size_move(text: str) -> bool:
179
+ return any(same_family_resize_move_line(line) for line in (text or "").splitlines())
180
+
181
+
182
+ def _size_move_explanation(
183
+ current: SpecRow,
184
+ target: SpecRow,
185
+ target_type: str,
186
+ *,
187
+ cpu_p99: float,
188
+ desired_cpu_p99: float,
189
+ ) -> str:
190
+ approx = cpu_p99 * float(current.vcpu) / float(target.vcpu)
191
+ return (
192
+ f"Move from {current.instance_type} ({_vcpu_label(current.vcpu)}) to "
193
+ f"{target_type} ({_vcpu_label(target.vcpu)}). "
194
+ f"After the migration, CPU p99 will be {_predicted_cpu_label(approx)}, "
195
+ f"which is below the desired headroom setting of "
196
+ f"{format_human_metric(desired_cpu_p99)}%."
197
+ )
198
+
199
+
200
+ def format_size_result(
201
+ response: dict[str, Any],
202
+ *,
203
+ current: SpecRow,
204
+ specs: dict[tuple[str, str], SpecRow],
205
+ window_trimmed: bool,
206
+ changed_at: datetime | None = None,
207
+ cpu_p99: float | None = None,
208
+ desired_cpu_p99: float | None = None,
209
+ extra_lines: tuple[str, ...] = (),
210
+ ) -> str | None:
211
+ """Return one display line, or None when the row should be omitted."""
212
+ if not isinstance(response, dict):
213
+ raise ValueError("size lookup response must be an object")
214
+ prefer_reservation_type()
215
+ target_type = response.get("recommended_instance_type")
216
+ if not isinstance(target_type, str) or not target_type.strip():
217
+ return None
218
+ target_type = target_type.strip()
219
+ target = specs.get((current.cloud, target_type))
220
+ if target is None:
221
+ return None
222
+ if not _eligible_target(current, target):
223
+ return None
224
+ cpu = cpu_p99
225
+ desired = desired_cpu_p99
226
+ if cpu is None or isinstance(cpu, bool):
227
+ cpu = None
228
+ if desired is None or isinstance(desired, bool):
229
+ raw_desired = response.get("desired_cpu_p99")
230
+ if isinstance(raw_desired, (int, float)) and not isinstance(raw_desired, bool):
231
+ desired = float(raw_desired)
232
+ if cpu is None or desired is None:
233
+ explanation = _as_text(response.get("explanation"))
234
+ if not explanation:
235
+ return None
236
+ else:
237
+ explanation = _size_move_explanation(
238
+ current,
239
+ target,
240
+ target_type,
241
+ cpu_p99=float(cpu),
242
+ desired_cpu_p99=float(desired),
243
+ )
244
+ trimmed = _trim_suffix(changed_at) if window_trimmed else ""
245
+ footer = size_move_unchecked_footer(extra=extra_lines)
246
+ return f"{explanation}{trimmed}\n{footer}"
247
+
248
+
249
+ def _eligible_target(current: SpecRow, target: SpecRow) -> bool:
250
+ if is_burstable_family(target.family):
251
+ return False
252
+ family = (current.family or "").strip().lower()
253
+ vendor = (current.processor_vendor or "").strip().lower()
254
+ if not family or not vendor:
255
+ return False
256
+ if (target.family or "").strip().lower() != family:
257
+ return False
258
+ if (target.processor_vendor or "").strip().lower() != vendor:
259
+ return False
260
+ current_arch = spec_architecture(current)
261
+ target_arch = spec_architecture(target)
262
+ if not current_arch or not target_arch or current_arch != target_arch:
263
+ return False
264
+ if (current.quota_family or "").strip() != (target.quota_family or "").strip():
265
+ return False
266
+ half = current.vcpu // 2
267
+ next_up = current.vcpu * 2
268
+ return target.vcpu in {half, next_up}
269
+
270
+
271
+ def _require_closed_size_body(
272
+ body: dict[str, Any],
273
+ *,
274
+ period_minutes: int = SAMPLE_PERIOD_MINUTES,
275
+ ) -> None:
276
+ if not isinstance(body, dict):
277
+ raise ValueError("size lookup body must be an object")
278
+ keys = set(body)
279
+ expected = set(size_body_keys(period_minutes=period_minutes))
280
+ if keys - expected:
281
+ raise ValueError("size lookup body has an extra key")
282
+ if expected - keys:
283
+ raise ValueError("size lookup body is missing a key")
284
+ _reject_id_shaped(body)
285
+ if body.get("request_type") != REQUEST_TYPE:
286
+ raise ValueError("request_type must be same_type_size_change")
287
+ if body.get("provider") != "aws":
288
+ raise ValueError("provider must be aws")
289
+ for key in ("region", "instance", "architecture", "quota_family"):
290
+ value = body.get(key)
291
+ if not isinstance(value, str) or value.strip() == "":
292
+ raise ValueError("size lookup body has an empty field")
293
+ sample_minutes = body.get("sample_minutes")
294
+ if isinstance(sample_minutes, bool) or not isinstance(sample_minutes, int) or sample_minutes <= 0:
295
+ raise ValueError("sample_minutes must be a positive integer")
296
+ if not isinstance(body.get("window_trimmed"), bool):
297
+ raise ValueError("window_trimmed must be a boolean")
298
+ _store_number(body, "desired_cpu_p99", required=True)
299
+ if float(body["desired_cpu_p99"]) <= 0:
300
+ raise ValueError("desired_cpu_p99 must be positive")
301
+ cpu_key = percentile_field("cpu", period_minutes)
302
+ _store_number(body, cpu_key, required=True)
303
+ if float(body[cpu_key]) < 0:
304
+ raise ValueError("cpu p99 must be non-negative")
305
+ for name in METRIC_NAMES:
306
+ if name == "cpu":
307
+ continue
308
+ field = percentile_field(name, period_minutes)
309
+ _store_optional_number(body, field)
310
+
311
+
312
+ def _store_number(body: dict[str, Any], key: str, *, required: bool) -> None:
313
+ value = body.get(key)
314
+ if value is None:
315
+ if required:
316
+ raise ValueError(f"size lookup body has an invalid {key}")
317
+ return
318
+ if isinstance(value, bool):
319
+ raise ValueError(f"size lookup body has an invalid {key}")
320
+ if isinstance(value, (int, float, Decimal)):
321
+ body[key] = float(value)
322
+ return
323
+ raise ValueError(f"size lookup body has an invalid {key}")
324
+
325
+
326
+ def _store_optional_number(body: dict[str, Any], key: str) -> None:
327
+ value = body.get(key)
328
+ if value is None:
329
+ return
330
+ if isinstance(value, bool):
331
+ raise ValueError(f"size lookup body has an invalid {key}")
332
+ if isinstance(value, (int, float, Decimal)):
333
+ body[key] = float(value)
334
+ return
335
+ raise ValueError(f"size lookup body has an invalid {key}")
336
+
337
+
338
+ def _reject_id_shaped(value: object, *, key: object = None) -> None:
339
+ if isinstance(key, str) and key.lower() in _FORBIDDEN_KEYS:
340
+ raise ValueError("size lookup body contains a forbidden key")
341
+ if isinstance(value, dict):
342
+ for child_key, child in value.items():
343
+ _reject_id_shaped(child, key=child_key)
344
+ return
345
+ if isinstance(value, list):
346
+ for child in value:
347
+ _reject_id_shaped(child)
348
+ return
349
+ if isinstance(value, str):
350
+ if _INSTANCE_ID_RE.search(value) or _VOLUME_ID_RE.search(value) or _ACCOUNT_ID_RE.search(value):
351
+ raise ValueError("size lookup body contains a forbidden id")
352
+ return
353
+ if isinstance(value, int) and not isinstance(value, bool) and 10**11 <= abs(value) < 10**12:
354
+ raise ValueError("size lookup body contains a forbidden id")
355
+
356
+
357
+ def _as_text(value: object) -> str:
358
+ if isinstance(value, str):
359
+ return value.strip()
360
+ if isinstance(value, bool):
361
+ return ""
362
+ if isinstance(value, int):
363
+ return str(value)
364
+ if isinstance(value, float):
365
+ return format(value, "f")
366
+ if isinstance(value, Decimal):
367
+ return format(value, "f")
368
+ return ""
@@ -0,0 +1,325 @@
1
+ """Provider-read EC2 instance type catalog for analyze (NEXT-1 W3)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from dataclasses import dataclass
8
+ from typing import Any, Literal
9
+
10
+ from maproom.analyze.catalog import SpecRow, load_spec_rows
11
+ from maproom.analyze.accel_families import instance_type_has_accelerator_family
12
+ from maproom.cliio.runner import CliTimeoutError
13
+
14
+ from maproom.errors import AccessDeniedError, NotLoggedInError, MaproomParseError
15
+
16
+ _OFFERINGS_API = "aws_ec2_describe_instance_type_offerings"
17
+ _TYPES_API = "aws_ec2_describe_instance_types"
18
+
19
+
20
+ class SpecCatalogError(MaproomParseError):
21
+ """Instance spec catalog could not be loaded from the provider."""
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class InstanceSpec:
26
+ instance_type: str
27
+ family: str
28
+ generation: int | None
29
+ size: str
30
+ vcpus: int
31
+ memory_mib: int
32
+ architectures: list[str]
33
+ burstable: bool
34
+ bare_metal: bool
35
+ accelerators: bool
36
+ instance_storage: bool
37
+ network_performance: str
38
+ current_generation: bool
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class SpecCatalog:
43
+ offered: set[str]
44
+ specs: dict[str, InstanceSpec]
45
+ current: InstanceSpec
46
+ region: str
47
+ source: Literal["provider", "fixture", "shipped"]
48
+
49
+
50
+ def catalog_has_specs(spec_catalog: SpecCatalog | None) -> bool:
51
+ """True when the catalog carries full instance specs (provider or shipped tables)."""
52
+ return spec_catalog is not None and spec_catalog.source in ("provider", "shipped")
53
+
54
+
55
+ def parse_instance_type_name(instance_type: str) -> tuple[str, int | None, str]:
56
+ """Derive family, generation, and size from an EC2 instance type name."""
57
+ text = (instance_type or "").strip()
58
+ if "." not in text:
59
+ return text, None, ""
60
+ base, size = text.rsplit(".", 1)
61
+ match = re.search(r"\d+", base)
62
+ generation = int(match.group()) if match else None
63
+ return base, generation, size
64
+
65
+
66
+ def _stderr_lower(response: dict[str, Any]) -> str:
67
+ return str(response.get("stderr") or "").lower()
68
+
69
+
70
+ def _runner_document(result: Any) -> dict[str, Any]:
71
+ response: dict[str, Any] = {
72
+ "exit_code": result.exit_code,
73
+ "stdout_json": {},
74
+ "stderr": result.stderr,
75
+ }
76
+ if result.stdout.strip():
77
+ try:
78
+ response["stdout_json"] = json.loads(result.stdout)
79
+ except json.JSONDecodeError:
80
+ response["stdout_json"] = {"_raw_stdout": result.stdout}
81
+ return response
82
+
83
+
84
+ def _map_cli_error(
85
+ response: dict[str, Any],
86
+ *,
87
+ api_id: str,
88
+ cli_version: str | None,
89
+ operation: str,
90
+ ) -> None:
91
+ exit_code = int(response.get("exit_code", 0))
92
+ err = _stderr_lower(response)
93
+ if exit_code in (253, 255) and "credential" in err:
94
+ raise NotLoggedInError(
95
+ "not logged in to AWS CLI",
96
+ api_id=api_id,
97
+ cli_version=cli_version,
98
+ )
99
+ if exit_code != 0:
100
+ if (
101
+ "unauthorizedoperation" in err
102
+ or "accessdenied" in err
103
+ or "not authorized" in err
104
+ ):
105
+ raise AccessDeniedError(
106
+ f"{operation} denied",
107
+ api_id=api_id,
108
+ cli_version=cli_version,
109
+ )
110
+ raise SpecCatalogError(
111
+ f"{operation} failed (exit {exit_code})",
112
+ api_id=api_id,
113
+ cli_version=cli_version,
114
+ )
115
+
116
+
117
+ def parse_instance_type_offerings(
118
+ response: dict[str, Any],
119
+ *,
120
+ api_id: str = _OFFERINGS_API,
121
+ cli_version: str | None = None,
122
+ ) -> set[str]:
123
+ _map_cli_error(
124
+ response,
125
+ api_id=api_id,
126
+ cli_version=cli_version,
127
+ operation="ec2:DescribeInstanceTypeOfferings",
128
+ )
129
+ payload = response.get("stdout_json") or {}
130
+ offerings = payload.get("InstanceTypeOfferings")
131
+ if offerings is None:
132
+ raise SpecCatalogError(
133
+ "missing required field InstanceTypeOfferings",
134
+ api_id=api_id,
135
+ cli_version=cli_version,
136
+ path="$.InstanceTypeOfferings",
137
+ )
138
+ types: set[str] = set()
139
+ for row in offerings:
140
+ if isinstance(row, dict):
141
+ name = str(row.get("InstanceType") or "").strip()
142
+ if name:
143
+ types.add(name)
144
+ return types
145
+
146
+
147
+ def parse_instance_types(
148
+ response: dict[str, Any],
149
+ *,
150
+ api_id: str = _TYPES_API,
151
+ cli_version: str | None = None,
152
+ ) -> dict[str, InstanceSpec]:
153
+ _map_cli_error(
154
+ response,
155
+ api_id=api_id,
156
+ cli_version=cli_version,
157
+ operation="ec2:DescribeInstanceTypes",
158
+ )
159
+ payload = response.get("stdout_json") or {}
160
+ rows = payload.get("InstanceTypes")
161
+ if rows is None:
162
+ raise SpecCatalogError(
163
+ "missing required field InstanceTypes",
164
+ api_id=api_id,
165
+ cli_version=cli_version,
166
+ path="$.InstanceTypes",
167
+ )
168
+ specs: dict[str, InstanceSpec] = {}
169
+ for row in rows:
170
+ if not isinstance(row, dict):
171
+ continue
172
+ spec = _instance_spec_from_row(row)
173
+ if spec is not None:
174
+ specs[spec.instance_type] = spec
175
+ return specs
176
+
177
+
178
+ def _instance_spec_from_row(row: dict[str, Any]) -> InstanceSpec | None:
179
+ instance_type = str(row.get("InstanceType") or "").strip()
180
+ if not instance_type:
181
+ return None
182
+ family, generation, size = parse_instance_type_name(instance_type)
183
+ processor = row.get("ProcessorInfo") or {}
184
+ architectures = [
185
+ str(item)
186
+ for item in (processor.get("SupportedArchitectures") or [])
187
+ if str(item).strip()
188
+ ]
189
+ vcpu_info = row.get("VCpuInfo") or {}
190
+ memory_info = row.get("MemoryInfo") or {}
191
+ network_info = row.get("NetworkInfo") or {}
192
+ vcpus = int(vcpu_info.get("DefaultVCpus") or 0)
193
+ memory_mib = int(memory_info.get("SizeInMiB") or 0)
194
+ accelerators = any(
195
+ row.get(key) for key in ("GpuInfo", "InferenceAcceleratorInfo", "FpgaInfo")
196
+ )
197
+ return InstanceSpec(
198
+ instance_type=instance_type,
199
+ family=family,
200
+ generation=generation,
201
+ size=size,
202
+ vcpus=vcpus,
203
+ memory_mib=memory_mib,
204
+ architectures=architectures,
205
+ burstable=bool(row.get("BurstablePerformanceSupported")),
206
+ bare_metal=bool(row.get("BareMetal")),
207
+ accelerators=bool(accelerators),
208
+ instance_storage=bool(row.get("InstanceStorageSupported")),
209
+ network_performance=str(network_info.get("NetworkPerformance") or ""),
210
+ current_generation=bool(row.get("CurrentGeneration")),
211
+ )
212
+
213
+
214
+ def _minimal_instance_spec(instance_type: str) -> InstanceSpec:
215
+ family, generation, size = parse_instance_type_name(instance_type)
216
+ return InstanceSpec(
217
+ instance_type=instance_type,
218
+ family=family,
219
+ generation=generation,
220
+ size=size,
221
+ vcpus=0,
222
+ memory_mib=0,
223
+ architectures=[],
224
+ burstable=False,
225
+ bare_metal=size == "metal",
226
+ accelerators=False,
227
+ instance_storage=False,
228
+ network_performance="",
229
+ current_generation=False,
230
+ )
231
+
232
+
233
+ def _burstable_family(family: str) -> bool:
234
+ fam = (family or "").strip().lower()
235
+ return len(fam) >= 2 and fam[0] == "t" and fam[1].isdigit()
236
+
237
+
238
+ def _architectures_for_vendor(vendor: str) -> list[str]:
239
+ if "graviton" in (vendor or "").lower() or "arm" in (vendor or "").lower():
240
+ return ["arm64"]
241
+ return ["x86_64"]
242
+
243
+
244
+ def instance_spec_from_spec_row(row: SpecRow) -> InstanceSpec:
245
+ family, generation, size = parse_instance_type_name(row.instance_type)
246
+ if not family:
247
+ family = row.family
248
+ disk_type = (row.ephemeral_disk_type or "").strip().lower()
249
+ store_gb = float(row.ephemeral_disk_total_gb or 0)
250
+ return InstanceSpec(
251
+ instance_type=row.instance_type,
252
+ family=family,
253
+ generation=generation if generation is not None else row.generation,
254
+ size=size,
255
+ vcpus=row.vcpu,
256
+ memory_mib=int(row.memory_gib * 1024),
257
+ architectures=_architectures_for_vendor(row.processor_vendor),
258
+ burstable=_burstable_family(row.family or family),
259
+ bare_metal=size == "metal",
260
+ accelerators=instance_type_has_accelerator_family(row.instance_type),
261
+ instance_storage=store_gb > 0 or disk_type not in {"", "none"},
262
+ network_performance=row.network_performance or "",
263
+ current_generation=(generation or row.generation or 0) > 0,
264
+ )
265
+
266
+
267
+ def build_shipped_spec_catalog(region: str, current_instance_type: str) -> SpecCatalog:
268
+ """Build a region catalog from the shipped instance spec table (AWS only)."""
269
+
270
+ name = (current_instance_type or "").strip()
271
+ if not name:
272
+ raise SpecCatalogError(
273
+ "missing current instance type",
274
+ api_id="shipped_instance_specs",
275
+ )
276
+ specs_by_type: dict[str, InstanceSpec] = {}
277
+ for (cloud, instance_type), row in load_spec_rows().items():
278
+ if cloud != "aws":
279
+ continue
280
+ specs_by_type[instance_type] = instance_spec_from_spec_row(row)
281
+ if name not in specs_by_type:
282
+ raise SpecCatalogError(
283
+ f"shipped spec table has no row for {name}",
284
+ api_id="shipped_instance_specs",
285
+ )
286
+ return SpecCatalog(
287
+ offered=set(specs_by_type),
288
+ specs=specs_by_type,
289
+ current=specs_by_type[name],
290
+ region=region,
291
+ source="shipped",
292
+ )
293
+
294
+
295
+ def build_fixture_spec_catalog(region: str, current_instance_type: str) -> SpecCatalog:
296
+ current = _minimal_instance_spec(current_instance_type)
297
+ return SpecCatalog(
298
+ offered={current_instance_type},
299
+ specs={current_instance_type: current},
300
+ current=current,
301
+ region=region,
302
+ source="fixture",
303
+ )
304
+
305
+
306
+ def resolve_spec_catalog(
307
+ *,
308
+ region: str,
309
+ current_instance_type: str,
310
+ runner: Any,
311
+ local_only: bool,
312
+ ) -> tuple[SpecCatalog, list[str]]:
313
+ """Load shipped catalog or degrade to a minimal fixture catalog with warnings."""
314
+ _ = runner
315
+ warnings: list[str] = []
316
+ if local_only:
317
+ warnings.append("instance_specs_unavailable: local-only")
318
+ return build_fixture_spec_catalog(region, current_instance_type), warnings
319
+ try:
320
+ catalog = build_shipped_spec_catalog(region, current_instance_type)
321
+ return catalog, warnings
322
+ except SpecCatalogError as exc:
323
+ reason = str(exc).split(";")[0].strip() or type(exc).__name__
324
+ warnings.append(f"instance_specs_unavailable: {reason}")
325
+ return build_fixture_spec_catalog(region, current_instance_type), warnings