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,571 @@
1
+ """Closed safe_moves body, reservation context, and the local pack."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from decimal import Decimal
6
+ from typing import Any
7
+
8
+ from maproom.analyze.catalog import SpecRow, published_network_rank
9
+ from maproom.analyze.cover_lookup import replace_unchecked_coverage
10
+ from maproom.analyze.safe_move import UNCHECKED_COVERAGE
11
+
12
+ REQUEST_TYPE = "safe_moves"
13
+
14
+ CHECKED_NONE = "No matching reservation coverage was found."
15
+ FREE_LINE = "Reservation coverage was checked. {instance} takes free reservation capacity."
16
+ SWAP_LINE = "Reservation coverage was checked. {instance} takes reservation capacity that was in use."
17
+ USED_LINE = "Reservation coverage was checked. {instance} stays on the reservation."
18
+
19
+ _AWS_FACTORS: dict[str, float] = {
20
+ "nano": 0.25,
21
+ "micro": 0.5,
22
+ "small": 1.0,
23
+ "medium": 2.0,
24
+ "large": 4.0,
25
+ "xlarge": 8.0,
26
+ "2xlarge": 16.0,
27
+ "3xlarge": 24.0,
28
+ "4xlarge": 32.0,
29
+ "6xlarge": 48.0,
30
+ "8xlarge": 64.0,
31
+ "9xlarge": 72.0,
32
+ "10xlarge": 80.0,
33
+ "12xlarge": 96.0,
34
+ "16xlarge": 128.0,
35
+ "18xlarge": 144.0,
36
+ "24xlarge": 192.0,
37
+ "32xlarge": 256.0,
38
+ "48xlarge": 384.0,
39
+ "56xlarge": 448.0,
40
+ "112xlarge": 896.0,
41
+ }
42
+ _DISK_RANK = {"none": 0, "hdd": 1, "ssd": 2, "nvme": 3}
43
+ _VPC_SUFFIX = " (Amazon VPC)"
44
+
45
+
46
+ def normalize_platform(value: str) -> str:
47
+ text = value.strip()
48
+ if text.endswith(_VPC_SUFFIX):
49
+ text = text[: -len(_VPC_SUFFIX)]
50
+ return text
51
+
52
+
53
+ def aws_normalization_factor(instance_type: str) -> float:
54
+ """AWS Linux size-flexibility factor. Unknown sizes count as one unit."""
55
+ _family, _sep, size = instance_type.strip().partition(".")
56
+ return _AWS_FACTORS.get(size, 1.0)
57
+
58
+
59
+ def azure_flexibility_group(instance_type: str) -> str:
60
+ """Series token shared by sizes in one Azure flexibility group.
61
+
62
+ Standard_D4s_v3 and Standard_D2s_v3 both become Ds_v3.
63
+ """
64
+ name = instance_type.strip()
65
+ if name.lower().startswith("standard_"):
66
+ name = name[9:]
67
+ index = 0
68
+ prefix: list[str] = []
69
+ while index < len(name) and name[index].isalpha():
70
+ prefix.append(name[index])
71
+ index += 1
72
+ while index < len(name) and name[index].isdigit():
73
+ index += 1
74
+ group = "".join(prefix) + name[index:]
75
+ return group or instance_type.strip()
76
+
77
+
78
+ def aws_size_flexible(record: dict[str, Any]) -> bool:
79
+ platform = normalize_platform(str(record.get("platform") or ""))
80
+ scope = str(record.get("scope") or "region").strip().lower()
81
+ tenancy = str(record.get("tenancy") or "default").strip().lower()
82
+ return platform == "Linux/UNIX" and scope == "region" and tenancy == "default"
83
+
84
+
85
+ def _counts(record: dict[str, Any]) -> tuple[float, float]:
86
+ quantity = record.get("quantity")
87
+ try:
88
+ total = float(quantity) if quantity is not None else 1.0
89
+ except (TypeError, ValueError):
90
+ total = 1.0
91
+ fraction = record.get("utilization_fraction")
92
+ if isinstance(fraction, bool) or not isinstance(fraction, (int, float)):
93
+ unused = record.get("unused_quantity")
94
+ if isinstance(unused, bool) or not isinstance(unused, (int, float)):
95
+ return 0.0, 0.0
96
+ unused_count = max(float(unused), 0.0)
97
+ return unused_count, max(total - unused_count, 0.0)
98
+ used_fraction = max(0.0, min(float(fraction), 1.0))
99
+ return total * (1.0 - used_fraction), total * used_fraction
100
+
101
+
102
+ def build_reservation_context(
103
+ records: list[dict[str, Any]],
104
+ *,
105
+ region: str,
106
+ provider: str,
107
+ ) -> dict[str, list[dict[str, Any]]]:
108
+ """Names only. Counts stay on the machine. One context per region."""
109
+ wanted = region.strip().lower()
110
+ cloud = provider.strip().lower()
111
+ free: dict[str, dict[str, set[str]]] = {}
112
+ used: dict[str, dict[str, set[str]]] = {}
113
+ for record in records:
114
+ if str(record.get("region") or "").strip().lower() != wanted:
115
+ continue
116
+ kind = str(record.get("kind") or "ec2_reserved_instance")
117
+ if cloud == "azure" and kind != "azure_reserved_vm":
118
+ continue
119
+ if cloud != "azure" and kind == "azure_reserved_vm":
120
+ continue
121
+ unused_count, used_count = _counts(record)
122
+ if cloud == "azure":
123
+ platform = "*"
124
+ flexible = bool(record.get("size_flexible"))
125
+ family = str(record.get("instance_family") or "")
126
+ exact = str(record.get("instance_type") or "")
127
+ else:
128
+ platform = normalize_platform(str(record.get("platform") or ""))
129
+ if not platform:
130
+ continue
131
+ flexible = aws_size_flexible(record)
132
+ family = str(record.get("instance_family") or "")
133
+ exact = str(record.get("instance_type") or "")
134
+ if unused_count > 0:
135
+ _add_name(free, platform, flexible, family, exact)
136
+ if used_count > 0:
137
+ _add_name(used, platform, flexible, family, exact)
138
+ return {"free": _blocks(free), "used": _blocks(used)}
139
+
140
+
141
+ def _add_name(
142
+ groups: dict[str, dict[str, set[str]]],
143
+ platform: str,
144
+ flexible: bool,
145
+ family: str,
146
+ exact: str,
147
+ ) -> None:
148
+ bucket = groups.setdefault(platform, {"families": set(), "instance_types": set()})
149
+ if flexible and family.strip():
150
+ bucket["families"].add(family.strip())
151
+ elif exact.strip():
152
+ bucket["instance_types"].add(exact.strip())
153
+
154
+
155
+ def _blocks(groups: dict[str, dict[str, set[str]]]) -> list[dict[str, Any]]:
156
+ blocks: list[dict[str, Any]] = []
157
+ for platform in sorted(groups):
158
+ families = sorted(groups[platform]["families"])
159
+ exact = sorted(groups[platform]["instance_types"])
160
+ if not families and not exact:
161
+ continue
162
+ block: dict[str, Any] = {"platform": platform}
163
+ if families:
164
+ block["families"] = families
165
+ if exact:
166
+ block["instance_types"] = exact
167
+ blocks.append(block)
168
+ return blocks
169
+
170
+
171
+ def context_is_empty(context: dict[str, Any]) -> bool:
172
+ return not context.get("free") and not context.get("used")
173
+
174
+
175
+ def build_safe_moves_body(
176
+ *,
177
+ provider: str,
178
+ region: str,
179
+ instance: str,
180
+ reservation_context: dict[str, Any] | None = None,
181
+ reservations_travel_in_context: bool = False,
182
+ ) -> dict[str, Any]:
183
+ body: dict[str, Any] = {
184
+ "request_type": REQUEST_TYPE,
185
+ "provider": provider.strip().lower(),
186
+ "region": region.strip(),
187
+ "instance": instance.strip(),
188
+ }
189
+ if reservations_travel_in_context:
190
+ if reservation_context is not None:
191
+ raise ValueError("reservation_context must be omitted when context carries reservations")
192
+ elif reservation_context is not None:
193
+ body["reservation_context"] = reservation_context
194
+ else:
195
+ raise ValueError("safe moves body needs reservation_context or reservations_travel_in_context")
196
+ _require_closed_body(body)
197
+ return body
198
+
199
+
200
+ def _require_closed_body(body: dict[str, Any]) -> None:
201
+ without_reservations = {"request_type", "provider", "region", "instance"}
202
+ with_reservations = {
203
+ "request_type",
204
+ "provider",
205
+ "region",
206
+ "instance",
207
+ "reservation_context",
208
+ }
209
+ keys = set(body)
210
+ if keys not in (without_reservations, with_reservations):
211
+ raise ValueError("safe moves body is not the closed key set")
212
+ if body.get("request_type") != REQUEST_TYPE:
213
+ raise ValueError("request_type must be safe_moves")
214
+ if body.get("provider") not in {"aws", "azure"}:
215
+ raise ValueError("provider must be aws or azure")
216
+ for key in ("region", "instance"):
217
+ value = body.get(key)
218
+ if not isinstance(value, str) or not value.strip():
219
+ raise ValueError("safe moves body has an empty field")
220
+ if "reservation_context" in body:
221
+ _require_context(body.get("reservation_context"))
222
+
223
+
224
+ def _require_context(context: object) -> None:
225
+ if not isinstance(context, dict) or set(context) != {"free", "used"}:
226
+ raise ValueError("reservation_context must have free and used")
227
+ for section in ("free", "used"):
228
+ blocks = context.get(section)
229
+ if not isinstance(blocks, list):
230
+ raise ValueError("reservation_context sections must be lists")
231
+ for block in blocks:
232
+ _require_block(block)
233
+
234
+
235
+ def _require_block(block: object) -> None:
236
+ if not isinstance(block, dict) or "platform" not in block:
237
+ raise ValueError("reservation block must name a platform")
238
+ extra = set(block) - {"platform", "families", "instance_types"}
239
+ if extra:
240
+ raise ValueError("reservation block has an extra key")
241
+ platform = block.get("platform")
242
+ if not isinstance(platform, str) or not platform.strip():
243
+ raise ValueError("reservation block has an empty platform")
244
+ families = block.get("families", [])
245
+ exact = block.get("instance_types", [])
246
+ if not isinstance(families, list) or not isinstance(exact, list):
247
+ raise ValueError("reservation block lists must be arrays")
248
+ if not families and not exact:
249
+ raise ValueError("reservation block is empty")
250
+ for name in families + exact:
251
+ if not isinstance(name, str) or not name.strip():
252
+ raise ValueError("reservation block has an empty name")
253
+
254
+
255
+ def require_safe_moves_response(payload: object) -> dict[str, Any]:
256
+ if not isinstance(payload, dict):
257
+ raise ValueError("safe moves response must be an object")
258
+ if payload.get("request_type") != REQUEST_TYPE:
259
+ raise ValueError("request_type must be safe_moves")
260
+ candidates = payload.get("candidates")
261
+ if not isinstance(candidates, list):
262
+ raise ValueError("safe moves response candidates must be a list")
263
+ for row in candidates:
264
+ if not isinstance(row, dict):
265
+ raise ValueError("safe moves candidate must be an object")
266
+ for key in ("platform", "instance", "from", "normalization_factor", "on_demand_price"):
267
+ if key not in row:
268
+ raise ValueError("safe moves candidate is missing a field")
269
+ if row.get("from") not in {"free", "used"}:
270
+ raise ValueError("safe moves candidate from must be free or used")
271
+ return payload
272
+
273
+
274
+ def platform_matches(instance_platform: str, block_platform: str) -> bool:
275
+ if block_platform.strip() == "*":
276
+ return True
277
+ return normalize_platform(instance_platform) == normalize_platform(block_platform)
278
+
279
+
280
+ def _resource_ok(current: SpecRow, candidate: SpecRow) -> bool:
281
+ if candidate.vcpu < current.vcpu or candidate.memory_gib < current.memory_gib:
282
+ return False
283
+ if current.gb_per_vcpu is not None and candidate.gb_per_vcpu is not None:
284
+ if candidate.gb_per_vcpu < current.gb_per_vcpu:
285
+ return False
286
+ if current.cpu_performance_rank is not None and candidate.cpu_performance_rank is not None:
287
+ if candidate.cpu_performance_rank < current.cpu_performance_rank:
288
+ return False
289
+ if not _disks_ok(current, candidate):
290
+ return False
291
+ current_network = published_network_rank(current.network_performance)
292
+ candidate_network = published_network_rank(candidate.network_performance)
293
+ if current_network is None or candidate_network is None:
294
+ return False
295
+ return candidate_network >= current_network
296
+
297
+
298
+ def _disks_ok(current: SpecRow, candidate: SpecRow) -> bool:
299
+ current_disk = current.ephemeral_disk_type or "none"
300
+ if current_disk == "none":
301
+ return True
302
+ candidate_disk = candidate.ephemeral_disk_type or "none"
303
+ if candidate_disk == "none":
304
+ return False
305
+ if candidate.ephemeral_disk_total_gb < current.ephemeral_disk_total_gb:
306
+ return False
307
+ return _DISK_RANK.get(candidate_disk, 0) >= _DISK_RANK.get(current_disk, 0)
308
+
309
+
310
+ def eligible_candidates(
311
+ response: dict[str, Any],
312
+ *,
313
+ current: SpecRow,
314
+ instance_platform: str,
315
+ specs: dict[tuple[str, str], SpecRow],
316
+ ) -> list[dict[str, Any]]:
317
+ kept: list[dict[str, Any]] = []
318
+ for row in response.get("candidates") or []:
319
+ if not isinstance(row, dict):
320
+ continue
321
+ if not platform_matches(instance_platform, str(row.get("platform") or "")):
322
+ continue
323
+ instance = str(row.get("instance") or "").strip()
324
+ target = specs.get((current.cloud, instance))
325
+ if target is None or not _resource_ok(current, target):
326
+ continue
327
+ kept.append(row)
328
+ return kept
329
+
330
+
331
+ def free_and_used_units(
332
+ records: list[dict[str, Any]],
333
+ *,
334
+ region: str,
335
+ provider: str,
336
+ specs: dict[tuple[str, str], SpecRow],
337
+ ) -> tuple[dict[tuple[str, str], float], dict[tuple[str, str], float]]:
338
+ """Map (platform, name) to free units and used units. Name is a family or an exact type."""
339
+ wanted = region.strip().lower()
340
+ cloud = provider.strip().lower()
341
+ free: dict[tuple[str, str], float] = {}
342
+ used: dict[tuple[str, str], float] = {}
343
+ for record in records:
344
+ if str(record.get("region") or "").strip().lower() != wanted:
345
+ continue
346
+ kind = str(record.get("kind") or "ec2_reserved_instance")
347
+ if cloud == "azure" and kind != "azure_reserved_vm":
348
+ continue
349
+ if cloud != "azure" and kind == "azure_reserved_vm":
350
+ continue
351
+ unused_count, used_count = _counts(record)
352
+ exact = str(record.get("instance_type") or "")
353
+ if cloud == "azure":
354
+ platform = "*"
355
+ flexible = bool(record.get("size_flexible"))
356
+ name = str(record.get("instance_family") or "") if flexible else exact
357
+ spec = specs.get(("azure", exact))
358
+ factor = float(spec.vcpu) if spec is not None and flexible else 1.0
359
+ else:
360
+ platform = normalize_platform(str(record.get("platform") or ""))
361
+ flexible = aws_size_flexible(record)
362
+ name = str(record.get("instance_family") or "") if flexible else exact
363
+ factor = aws_normalization_factor(exact) if flexible else 1.0
364
+ if not platform or not name:
365
+ continue
366
+ key = (platform, name)
367
+ if unused_count > 0:
368
+ free[key] = free.get(key, 0.0) + unused_count * factor
369
+ if used_count > 0:
370
+ used[key] = used.get(key, 0.0) + used_count * factor
371
+ return free, used
372
+
373
+
374
+ def _price_number(value: object) -> float:
375
+ try:
376
+ return float(value) # type: ignore[arg-type]
377
+ except (TypeError, ValueError):
378
+ return 0.0
379
+
380
+
381
+ def pack_assignments(
382
+ rows: list[dict[str, Any]],
383
+ *,
384
+ free_units: dict[tuple[str, str], float],
385
+ used_units: dict[tuple[str, str], float],
386
+ ) -> list[dict[str, Any] | None]:
387
+ """Assign free capacity, most expensive current type first. Counts are local."""
388
+ free_left = dict(free_units)
389
+ used_left = dict(used_units)
390
+ order = sorted(range(len(rows)), key=lambda index: _price_number(rows[index].get("shipped_price")), reverse=True)
391
+ chosen: list[dict[str, Any] | None] = [None] * len(rows)
392
+ for index in order:
393
+ row = rows[index]
394
+ candidates = [
395
+ candidate
396
+ for candidate in row.get("candidates") or []
397
+ if isinstance(candidate, dict) and candidate.get("from") == "free"
398
+ ]
399
+ candidates.sort(key=lambda candidate: (_price_number(candidate.get("normalization_factor")), _price_number(candidate.get("on_demand_price"))))
400
+ picked = _take(candidates, free_left, used_left, taker_price=_price_number(row.get("current_on_demand_price")))
401
+ if picked is not None:
402
+ chosen[index] = picked
403
+ continue
404
+ if _holds_used(row, used_left):
405
+ chosen[index] = {"keep": True, "instance": row.get("current_instance")}
406
+ return chosen
407
+
408
+
409
+ def _take(
410
+ candidates: list[dict[str, Any]],
411
+ free_left: dict[tuple[str, str], float],
412
+ used_left: dict[tuple[str, str], float],
413
+ *,
414
+ taker_price: float,
415
+ ) -> dict[str, Any] | None:
416
+ for candidate in candidates:
417
+ need = _price_number(candidate.get("normalization_factor"))
418
+ if need <= 0:
419
+ need = 1.0
420
+ keys = _pool_keys(candidate)
421
+ for key in keys:
422
+ if free_left.get(key, 0.0) + 1e-9 >= need:
423
+ free_left[key] = free_left.get(key, 0.0) - need
424
+ return {**candidate, "assignment": "free"}
425
+ for key in keys:
426
+ if used_left.get(key, 0.0) + 1e-9 < need:
427
+ continue
428
+ leaver_price = _price_number(candidate.get("on_demand_price"))
429
+ if taker_price <= leaver_price:
430
+ continue
431
+ used_left[key] = used_left.get(key, 0.0) - need
432
+ return {**candidate, "assignment": "used"}
433
+ return None
434
+
435
+
436
+ def _pool_keys(candidate: dict[str, Any]) -> list[tuple[str, str]]:
437
+ platform = str(candidate.get("platform") or "")
438
+ instance = str(candidate.get("instance") or "")
439
+ if not platform or not instance:
440
+ return []
441
+ keys = [(platform, instance)]
442
+ if "." in instance:
443
+ keys.append((platform, instance.split(".", 1)[0]))
444
+ else:
445
+ keys.append((platform, azure_flexibility_group(instance)))
446
+ return keys
447
+
448
+
449
+ def _holds_used(row: dict[str, Any], used_left: dict[tuple[str, str], float]) -> bool:
450
+ current = str(row.get("current_instance") or "")
451
+ platform = str(row.get("platform") or "")
452
+ if not current or not platform:
453
+ return False
454
+ names = [current]
455
+ if "." in current:
456
+ names.append(current.split(".", 1)[0])
457
+ else:
458
+ names.append(azure_flexibility_group(current))
459
+ return any(used_left.get((platform, name), 0.0) > 0 for name in names)
460
+
461
+
462
+ def coverage_line(chosen: dict[str, Any] | None, *, current_instance: str) -> str:
463
+ if not chosen:
464
+ return CHECKED_NONE
465
+ if chosen.get("keep"):
466
+ return USED_LINE.format(instance=current_instance)
467
+ instance = str(chosen.get("instance") or current_instance)
468
+ if chosen.get("assignment") == "used":
469
+ return SWAP_LINE.format(instance=instance)
470
+ if str(chosen.get("from") or "") == "free" or chosen.get("assignment") == "free":
471
+ return FREE_LINE.format(instance=instance)
472
+ return CHECKED_NONE
473
+
474
+
475
+ def apply_chosen_type(assessment: Any, instance_type: str, specs: dict[tuple[str, str], SpecRow], cloud: str) -> None:
476
+ recommendation = assessment.recommendation
477
+ if recommendation is None:
478
+ return
479
+ alternatives = recommendation.get("recommended_alternatives")
480
+ if not isinstance(alternatives, list) or not alternatives:
481
+ return
482
+ alternative = alternatives[0]
483
+ if not isinstance(alternative, dict):
484
+ return
485
+ alternative["instance_type"] = instance_type
486
+ lines = str(assessment.text or "").splitlines()
487
+ if lines and "->" in lines[0]:
488
+ label = lines[0].split("->", 1)[0].strip()
489
+ lines[0] = f"{label} -> {instance_type}"
490
+ assessment.text = "\n".join(lines)
491
+ assessment.recommendation["reservation_cover"] = {
492
+ "status": "returned",
493
+ "chosen_instance_type": instance_type,
494
+ }
495
+
496
+
497
+ def replace_coverage(text: str, line: str) -> str:
498
+ if UNCHECKED_COVERAGE not in text:
499
+ return text
500
+ return replace_unchecked_coverage(text, line)
501
+
502
+
503
+ def pack_fleet(
504
+ pending: list[tuple[Any, Any]],
505
+ *,
506
+ records: list[dict[str, Any]],
507
+ specs: dict[tuple[str, str], SpecRow],
508
+ responses: dict[int, dict[str, Any]],
509
+ pack_method: str = "fill",
510
+ now: Any = None,
511
+ ) -> dict[str, Any] | None:
512
+ """Pack after every instance has a response. Mutates assessment text and recommendations."""
513
+ from datetime import datetime, timezone
514
+
515
+ from maproom.analyze.reservation_pack import format_report, pack_region, prepare_instances
516
+ from maproom.analyze.safe_move import UNCHECKED_COVERAGE
517
+ from maproom.analyze.cover_lookup import replace_unchecked_coverage
518
+
519
+ prepared = prepare_instances(pending, responses, specs)
520
+ if not prepared and not records:
521
+ return None
522
+ moment = now or datetime.now(timezone.utc)
523
+ requested = pack_method if pack_method in {"fill", "restack"} else "fill"
524
+ by_region: dict[tuple[str, str], list[dict[str, Any]]] = {}
525
+ for row in prepared:
526
+ by_region.setdefault((str(row["cloud"]), str(row["region"]).lower()), []).append(row)
527
+ if not by_region:
528
+ regions = {
529
+ (str(record.get("kind") or ""), str(record.get("region") or "").lower())
530
+ for record in records
531
+ }
532
+ by_region = {("aws", region): [] for _kind, region in regions if region}
533
+ reports: list[dict[str, Any]] = []
534
+ region_groups = sorted(by_region.items())
535
+ for (cloud, region), group in region_groups:
536
+ reports.append(
537
+ pack_region(
538
+ group,
539
+ records,
540
+ region=region,
541
+ cloud=cloud,
542
+ specs=specs,
543
+ requested=requested,
544
+ now=moment,
545
+ )
546
+ )
547
+ if not reports:
548
+ return None
549
+ packing = {
550
+ "pack_method": (
551
+ "restack" if any(row["pack_method"] == "restack" for row in reports) else "fill"
552
+ ),
553
+ "as_is": sorted((row for report in reports for row in report["as_is"]), key=lambda item: str(item["name"])),
554
+ "moves": [group for report in reports for group in report["moves"]],
555
+ "to_be": sorted((row for report in reports for row in report["to_be"]), key=lambda item: str(item["name"])),
556
+ }
557
+ targets = {
558
+ instance["instance_id"]: instance["to_instance_type"]
559
+ for group in packing["moves"]
560
+ for instance in group.get("instances") or []
561
+ }
562
+ for index, (item, assessment) in enumerate(pending):
563
+ if item.instance_id in targets:
564
+ apply_chosen_type(assessment, targets[item.instance_id], specs, item.cloud)
565
+ if UNCHECKED_COVERAGE in str(assessment.text or ""):
566
+ assessment.text = replace_unchecked_coverage(assessment.text, "Reservation coverage was checked.")
567
+ report_text = format_report(packing)
568
+ if pending:
569
+ _item, assessment = pending[-1]
570
+ assessment.text = f"{assessment.text}\n\n{report_text}" if assessment.text else report_text
571
+ return packing
@@ -0,0 +1,127 @@
1
+ """Shipped safe-moves-v1.json used by product version 1.
2
+
3
+ Each move already records how the target compares with the source. Version 1
4
+ lists the moves for the current type in hourly savings order and copies that
5
+ comparison onto the recommendation.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from decimal import Decimal
12
+ from functools import lru_cache
13
+ from importlib import resources
14
+ from typing import Mapping, Sequence
15
+
16
+ DIMENSIONS = (
17
+ "architecture",
18
+ "instruction_sets",
19
+ "cpu",
20
+ "memory",
21
+ "local_disk",
22
+ "ebs_disk",
23
+ "network",
24
+ "price",
25
+ )
26
+
27
+
28
+ def money(value: object) -> Decimal:
29
+ if isinstance(value, Decimal):
30
+ return value
31
+ if isinstance(value, bool) or not isinstance(value, (int, float, str)):
32
+ raise ValueError("safe move price is not a number")
33
+ return Decimal(str(value))
34
+
35
+
36
+ def hourly_savings(move: Mapping[str, object]) -> Decimal:
37
+ """USD per hour kept by moving from source to target."""
38
+
39
+ return money(move["source_hourly_usd"]) - money(move["target_hourly_usd"])
40
+
41
+
42
+ def source_target_summary(move: Mapping[str, object]) -> dict[str, str]:
43
+ """The move node's source-to-target qualifications."""
44
+
45
+ summary = {
46
+ "source": str(move["source"]),
47
+ "target": str(move["target"]),
48
+ }
49
+ for name in DIMENSIONS:
50
+ summary[name] = str(move[name])
51
+ return summary
52
+
53
+
54
+ def format_summary(summary: Mapping[str, str]) -> str:
55
+ return ", ".join(f"{name} {summary[name]}" for name in DIMENSIONS)
56
+
57
+
58
+ _LABELS = {
59
+ "architecture": "Architecture",
60
+ "instruction_sets": "Instruction sets",
61
+ "cpu": "CPU",
62
+ "memory": "Memory",
63
+ "local_disk": "Local disk",
64
+ "ebs_disk": "EBS disk",
65
+ "network": "Network",
66
+ "price": "Price",
67
+ }
68
+
69
+
70
+ def _instruction_sets_sentence(value: str) -> str:
71
+ text = value.strip()
72
+ if not text:
73
+ return "Instruction sets: unchanged."
74
+ if text.startswith("-"):
75
+ names = [part.strip().lstrip("-") for part in text.split(",") if part.strip()]
76
+ if names:
77
+ joined = ", ".join(names)
78
+ return (
79
+ f"Target lacks AVX-512 ({joined}); "
80
+ "check software that needs those instruction sets."
81
+ )
82
+ return f"Instruction sets: {text}"
83
+
84
+
85
+ def format_summary_human(summary: Mapping[str, str]) -> str:
86
+ parts: list[str] = []
87
+ for name in DIMENSIONS:
88
+ value = summary.get(name, "")
89
+ if name == "instruction_sets":
90
+ parts.append(_instruction_sets_sentence(value))
91
+ continue
92
+ label = _LABELS.get(name, name.replace("_", " ").title())
93
+ parts.append(f"{label}: {value}")
94
+ return " ".join(parts)
95
+
96
+
97
+ def order_by_savings(moves: Sequence[Mapping[str, object]]) -> list[dict[str, object]]:
98
+ """Largest hourly savings first. Equal savings keep target-name order."""
99
+
100
+ rows = [dict(move) for move in moves]
101
+ rows.sort(key=lambda move: (-hourly_savings(move), str(move.get("target") or "")))
102
+ return rows
103
+
104
+
105
+ @lru_cache(maxsize=1)
106
+ def _by_source() -> dict[tuple[str, str], tuple[dict[str, object], ...]]:
107
+ raw = (
108
+ resources.files("maproom")
109
+ .joinpath("reference_data", "benchmarks", "safe-moves-v1.json")
110
+ .read_text(encoding="utf-8")
111
+ )
112
+ document = json.loads(raw)
113
+ if document.get("schema_version") != 2:
114
+ raise ValueError("shipped safe-moves-v1.json schema_version must be 2")
115
+ grouped: dict[tuple[str, str], list[dict[str, object]]] = {}
116
+ for move in document.get("moves") or []:
117
+ if not isinstance(move, dict):
118
+ continue
119
+ key = (str(move.get("cloud") or ""), str(move.get("source") or ""))
120
+ grouped.setdefault(key, []).append(move)
121
+ return {key: tuple(rows) for key, rows in grouped.items()}
122
+
123
+
124
+ def catalog_moves(cloud: str, source: str) -> tuple[dict[str, object], ...]:
125
+ """Moves whose source is this type, in file order. Empty when none exist."""
126
+
127
+ return _by_source().get((cloud, source), ())