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,883 @@
1
+ """Local reservation packing. Counts stay on the machine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ from itertools import combinations
7
+ from typing import Any, Callable
8
+
9
+ from maproom.analyze.catalog import SpecRow
10
+ from maproom.analyze.safe_moves import (
11
+ _resource_ok,
12
+ aws_normalization_factor,
13
+ aws_size_flexible,
14
+ azure_flexibility_group,
15
+ eligible_candidates,
16
+ free_and_used_units,
17
+ normalize_platform,
18
+ )
19
+
20
+ _KIND_ORDER = {
21
+ "reservation_to_ondemand": 0,
22
+ "reservation_to_reservation": 1,
23
+ "ondemand_to_reservation": 2,
24
+ }
25
+ _MAX_SEARCH = 8
26
+ def months_remaining(end: str, now: datetime) -> int | None:
27
+ text = (end or "").strip()
28
+ if not text:
29
+ return None
30
+ try:
31
+ parsed = datetime.fromisoformat(text.replace("Z", "+00:00"))
32
+ except ValueError:
33
+ return None
34
+ if parsed.tzinfo is None:
35
+ parsed = parsed.replace(tzinfo=timezone.utc)
36
+ now_utc = now if now.tzinfo else now.replace(tzinfo=timezone.utc)
37
+ if parsed <= now_utc:
38
+ months_left = 0
39
+ return months_left
40
+ months = (parsed.year - now_utc.year) * 12 + (parsed.month - now_utc.month)
41
+ if parsed.day < now_utc.day:
42
+ months -= 1
43
+ return max(months, 0)
44
+
45
+
46
+ def _number(value: object) -> float | None:
47
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
48
+ return None
49
+ return float(value)
50
+
51
+
52
+ def _price_or_none(value: object) -> float | None:
53
+ number = _number(value)
54
+ if number is not None:
55
+ return number if number >= 0 else None
56
+ if isinstance(value, str):
57
+ text = value.strip()
58
+ if not text:
59
+ return None
60
+ try:
61
+ parsed = float(text)
62
+ except ValueError:
63
+ return None
64
+ return parsed if parsed >= 0 else None
65
+ return None
66
+
67
+
68
+ def _price(value: object) -> float:
69
+ number = _price_or_none(value)
70
+ return 0.0 if number is None else number
71
+
72
+
73
+ def pool_draw(record: dict[str, Any], specs: dict[tuple[str, str], SpecRow], *, cloud: str) -> tuple[bool, str, float]:
74
+ """Return flexible, pool name, and the unit factor of one reserved instance."""
75
+ exact = str(record.get("instance_type") or "")
76
+ if cloud == "azure":
77
+ flexible = bool(record.get("size_flexible"))
78
+ name = str(record.get("instance_family") or "") if flexible else exact
79
+ spec = specs.get(("azure", exact))
80
+ factor = float(spec.vcpu) if spec is not None and flexible else 1.0
81
+ return flexible, name, factor
82
+ flexible = aws_size_flexible(record)
83
+ name = str(record.get("instance_family") or "") if flexible else exact
84
+ factor = aws_normalization_factor(exact) if flexible else 1.0
85
+ return flexible, name, factor
86
+
87
+
88
+ def instance_draw(instance_type: str, *, flexible: bool, cloud: str, specs: dict[tuple[str, str], SpecRow]) -> float:
89
+ if not flexible:
90
+ return 1.0
91
+ if cloud == "azure":
92
+ spec = specs.get(("azure", instance_type))
93
+ return float(spec.vcpu) if spec is not None else 1.0
94
+ return aws_normalization_factor(instance_type)
95
+
96
+
97
+ def family_of(instance_type: str, *, cloud: str) -> str:
98
+ if cloud == "azure":
99
+ return azure_flexibility_group(instance_type)
100
+ family, sep, _size = instance_type.partition(".")
101
+ return family if sep else instance_type
102
+
103
+
104
+ def as_is_rows(
105
+ records: list[dict[str, Any]],
106
+ *,
107
+ region: str,
108
+ cloud: str,
109
+ specs: dict[tuple[str, str], SpecRow],
110
+ now: datetime,
111
+ ) -> list[dict[str, Any]]:
112
+ wanted = region.strip().lower()
113
+ rows: list[dict[str, Any]] = []
114
+ for record in records:
115
+ if str(record.get("region") or "").strip().lower() != wanted:
116
+ continue
117
+ kind = str(record.get("kind") or "ec2_reserved_instance")
118
+ if cloud == "azure" and kind != "azure_reserved_vm":
119
+ continue
120
+ if cloud != "azure" and kind == "azure_reserved_vm":
121
+ continue
122
+ exact = str(record.get("instance_type") or "")
123
+ if not exact:
124
+ continue
125
+ flexible, _name, _factor = pool_draw(record, specs, cloud=cloud)
126
+ try:
127
+ quantity = int(record.get("quantity") or 1)
128
+ except (TypeError, ValueError):
129
+ quantity = 1
130
+ spec = specs.get((cloud if cloud == "azure" else "aws", exact))
131
+ vcpus = float(spec.vcpu) * quantity if spec is not None else 0.0
132
+ platform = "*" if cloud == "azure" else normalize_platform(str(record.get("platform") or ""))
133
+ name = str(record.get("name") or record.get("subscription_id") or exact)
134
+ row: dict[str, Any] = {
135
+ "name": name,
136
+ "months_remaining": months_remaining(str(record.get("end") or ""), now),
137
+ "instance_type": exact,
138
+ "os_flexible": platform == "*",
139
+ "size_flexible": flexible,
140
+ "vcpus": vcpus,
141
+ "occupancy_24h": _number(record.get("occupancy_24h")),
142
+ "occupancy_7d": _number(record.get("occupancy_7d")),
143
+ "occupancy_30d": _number(record.get("occupancy_30d")),
144
+ }
145
+ rows.append(row)
146
+ rows.sort(key=lambda item: str(item["name"]))
147
+ return rows
148
+
149
+
150
+ def _sorted_candidates(candidates: list[dict[str, Any]]) -> list[dict[str, Any]]:
151
+ return sorted(
152
+ candidates,
153
+ key=lambda row: (
154
+ _price(row.get("normalization_factor")) or 1.0,
155
+ _price(row.get("on_demand_price")),
156
+ str(row.get("instance") or ""),
157
+ ),
158
+ )
159
+
160
+
161
+ def format_report(packing: dict[str, Any]) -> str:
162
+ lines = ["Reservations as-is"]
163
+ for row in packing.get("as_is") or []:
164
+ flex = "size-flexible" if row.get("size_flexible") else "size-fixed"
165
+ os_text = "OS flexible" if row.get("os_flexible") else "OS fixed"
166
+ months = row.get("months_remaining")
167
+ months_text = (
168
+ "end date unread" if months is None else f"{months} months left"
169
+ )
170
+ lines.append(
171
+ f" {row.get('name')} {row.get('instance_type')} {row.get('vcpus')} vCPUs "
172
+ f"{months_text}"
173
+ )
174
+ lines.append(f" {flex}, {os_text}")
175
+ lines.append(
176
+ " occupied {h} in 24h, {w} in 7d, {m} in 30d".format(
177
+ h=_occ(row.get("occupancy_24h")),
178
+ w=_occ(row.get("occupancy_7d")),
179
+ m=_occ(row.get("occupancy_30d")),
180
+ )
181
+ )
182
+ lines.append("")
183
+ lines.append("Moves")
184
+ if not packing.get("moves"):
185
+ lines.append(" none")
186
+ for group in packing.get("moves") or []:
187
+ lines.append(f" {group.get('from_family')} -> {group.get('to_family')}")
188
+ for instance in group.get("instances") or []:
189
+ lines.append(
190
+ f" {instance.get('instance_name')} {instance.get('instance_id')} {instance.get('units')}"
191
+ )
192
+ lines.append("")
193
+ lines.append("Reservations to-be")
194
+ for row in packing.get("to_be") or []:
195
+ lines.append(f" {row.get('name')} {row.get('capacity_units')} units")
196
+ for occupant in row.get("occupants") or []:
197
+ lines.append(
198
+ f" {occupant.get('instance_name')} {occupant.get('instance_id')} "
199
+ f"{occupant.get('instance_type')} {occupant.get('units')}"
200
+ )
201
+ lines.append(f" idle {row.get('idle_units')}")
202
+ return "\n".join(lines)
203
+
204
+
205
+ def _occ(value: object) -> str:
206
+ number = _number(value)
207
+ if number is None:
208
+ return "unread"
209
+ return f"{number:.2f}"
210
+
211
+
212
+ def _pool_key(platform: str, name: str) -> tuple[str, str]:
213
+ return (platform, name)
214
+
215
+
216
+ def attribute_occupants(
217
+ instances: list[dict[str, Any]],
218
+ *,
219
+ free_units: dict[tuple[str, str], float],
220
+ used_units: dict[tuple[str, str], float],
221
+ flexible_names: set[tuple[str, str]],
222
+ ) -> dict[str, tuple[str, str]]:
223
+ """Map instance id to the pool whose used units cover it. Exact pools first."""
224
+ claimed: dict[str, tuple[str, str]] = {}
225
+ remaining = dict(used_units)
226
+ exact = [key for key in remaining if key not in flexible_names]
227
+ flexible = [key for key in remaining if key in flexible_names]
228
+ for key in exact + flexible:
229
+ platform, name = key
230
+ matched = []
231
+ for instance in instances:
232
+ if instance["id"] in claimed:
233
+ continue
234
+ if instance["platform"] != platform:
235
+ continue
236
+ if key in flexible_names:
237
+ if instance["family"] != name:
238
+ continue
239
+ elif instance["instance_type"] != name:
240
+ continue
241
+ matched.append(instance)
242
+ matched.sort(key=lambda row: (row["draw"].get(key, 1.0), row["id"]))
243
+ left = remaining.get(key, 0.0)
244
+ for instance in matched:
245
+ draw = instance["draw"].get(key, 1.0)
246
+ if left + 1e-9 < draw:
247
+ continue
248
+ left -= draw
249
+ claimed[instance["id"]] = key
250
+ remaining[key] = left
251
+ return claimed
252
+
253
+
254
+ def pack_region(
255
+ instances: list[dict[str, Any]],
256
+ records: list[dict[str, Any]],
257
+ *,
258
+ region: str,
259
+ cloud: str,
260
+ specs: dict[tuple[str, str], SpecRow],
261
+ requested: str,
262
+ now: datetime,
263
+ ) -> dict[str, Any]:
264
+ """Pack one region. ``requested`` is ignored; fill and restack share one rule. pack_method is fill or restack."""
265
+ provider = "azure" if cloud == "azure" else "aws"
266
+ free_units, used_units = free_and_used_units(records, region=region, provider=provider, specs=specs)
267
+ flexible_names: set[tuple[str, str]] = set()
268
+ for record in records:
269
+ if str(record.get("region") or "").strip().lower() != region.strip().lower():
270
+ continue
271
+ flexible, name, _factor = pool_draw(record, specs, cloud=cloud)
272
+ platform = "*" if cloud == "azure" else normalize_platform(str(record.get("platform") or ""))
273
+ if flexible and platform and name:
274
+ flexible_names.add((platform, name))
275
+ prepared = []
276
+ for instance in instances:
277
+ draws: dict[tuple[str, str], float] = {}
278
+ platform = instance["platform"]
279
+ family = instance["family"]
280
+ exact = instance["instance_type"]
281
+ for key in list(free_units) + list(used_units):
282
+ if key[0] != platform:
283
+ continue
284
+ flexible = key in flexible_names
285
+ if flexible and key[1] == family:
286
+ draws[key] = instance_draw(exact, flexible=True, cloud=cloud, specs=specs)
287
+ elif not flexible and key[1] == exact:
288
+ draws[key] = 1.0
289
+ instance = {**instance, "draw": draws}
290
+ prepared.append(instance)
291
+ occupants = attribute_occupants(
292
+ prepared,
293
+ free_units=free_units,
294
+ used_units=used_units,
295
+ flexible_names=flexible_names,
296
+ )
297
+ moves, method = _choose_moves(
298
+ prepared,
299
+ occupants=occupants,
300
+ free_units=free_units,
301
+ used_units=used_units,
302
+ flexible_names=flexible_names,
303
+ cloud=cloud,
304
+ specs=specs,
305
+ )
306
+ as_is = as_is_rows(records, region=region, cloud=cloud, specs=specs, now=now)
307
+ to_be = _to_be(
308
+ as_is,
309
+ records,
310
+ prepared,
311
+ occupants,
312
+ moves,
313
+ region=region,
314
+ cloud=cloud,
315
+ specs=specs,
316
+ flexible_names=flexible_names,
317
+ )
318
+ return {"pack_method": method, "as_is": as_is, "moves": moves, "to_be": to_be}
319
+
320
+
321
+ def _spec_cloud(cloud: str) -> str:
322
+ return "azure" if cloud == "azure" else "aws"
323
+
324
+
325
+ def _run_type_fits(
326
+ instance: dict[str, Any],
327
+ run_type: str,
328
+ *,
329
+ cloud: str,
330
+ specs: dict[tuple[str, str], SpecRow],
331
+ ) -> bool:
332
+ provider = _spec_cloud(cloud)
333
+ current = specs.get((provider, instance["instance_type"]))
334
+ target = specs.get((provider, run_type))
335
+ if current is None or target is None:
336
+ return False
337
+ return _resource_ok(current, target)
338
+
339
+
340
+ def _pool_capacity(
341
+ free_units: dict[tuple[str, str], float],
342
+ used_units: dict[tuple[str, str], float],
343
+ ) -> dict[tuple[str, str], float]:
344
+ merged: dict[tuple[str, str], float] = {}
345
+ for key in set(free_units) | set(used_units):
346
+ merged[key] = free_units.get(key, 0.0) + used_units.get(key, 0.0)
347
+ return merged
348
+
349
+
350
+ def _candidate_price(instance: dict[str, Any], instance_type: str) -> float | None:
351
+ for row in instance.get("candidates") or []:
352
+ if str(row.get("instance") or "") == instance_type:
353
+ return _price_or_none(row.get("on_demand_price"))
354
+ if instance_type == instance["instance_type"]:
355
+ return _price_or_none(instance.get("price"))
356
+ return None
357
+
358
+
359
+ def _cheapest_spill(
360
+ instance: dict[str, Any],
361
+ source: tuple[str, str],
362
+ flexible_names: set[tuple[str, str]],
363
+ *,
364
+ cloud: str,
365
+ specs: dict[tuple[str, str], SpecRow],
366
+ ) -> tuple[str, float] | None:
367
+ """Cheapest priced on-demand type that fits and does not draw from ``source``."""
368
+ best: tuple[float, str] | None = None
369
+ for row in instance.get("candidates") or []:
370
+ target = str(row.get("instance") or "")
371
+ price = _price_or_none(row.get("on_demand_price"))
372
+ if not target or price is None:
373
+ continue
374
+ family = family_of(target, cloud=cloud)
375
+ platform = str(row.get("platform") or instance["platform"])
376
+ pool = (platform, family) if (platform, family) in flexible_names else (platform, target)
377
+ if pool == source:
378
+ continue
379
+ if not _run_type_fits(instance, target, cloud=cloud, specs=specs):
380
+ continue
381
+ if best is None or (price, target) < best:
382
+ best = (price, target)
383
+ if best is None:
384
+ return None
385
+ return best[1], best[0]
386
+
387
+
388
+ def _build_eviction(
389
+ instance: dict[str, Any],
390
+ occupants: dict[str, tuple[str, str]],
391
+ flexible_names: set[tuple[str, str]],
392
+ pools: set[tuple[str, str]],
393
+ *,
394
+ cloud: str,
395
+ specs: dict[tuple[str, str], SpecRow],
396
+ ) -> dict[str, Any] | None:
397
+ home = occupants.get(instance["id"])
398
+ if home is None:
399
+ return None
400
+ target = instance.get("cross_family_target")
401
+ to_type = str(target if target else instance["instance_type"])
402
+ target_fits = _run_type_fits(instance, to_type, cloud=cloud, specs=specs)
403
+ if not target_fits:
404
+ to_type = instance["instance_type"]
405
+ dest: tuple[str, str] | None = None
406
+ to_units: float | None = None
407
+ if target_fits and target and family_of(to_type, cloud=cloud) != instance["family"]:
408
+ dest = _destination_pool(
409
+ to_type,
410
+ instance["platform"],
411
+ flexible_names,
412
+ pools,
413
+ cloud=cloud,
414
+ )
415
+ if dest is not None:
416
+ to_units = _dest_draw(to_type, dest, flexible_names, cloud=cloud, specs=specs)
417
+ if dest is not None:
418
+ spill_price = 0.0
419
+ else:
420
+ current_price = _price_or_none(instance.get("price"))
421
+ fallback_price = _candidate_price(instance, to_type)
422
+ spill_price = current_price if fallback_price is None else fallback_price
423
+ cheapest = _cheapest_spill(instance, home, flexible_names, cloud=cloud, specs=specs)
424
+ if cheapest is not None and (
425
+ not target_fits or spill_price is None or cheapest[1] < spill_price
426
+ ):
427
+ to_type, spill_price = cheapest
428
+ elif not target_fits or spill_price is None:
429
+ return None
430
+ return {
431
+ "instance": instance,
432
+ "source": home,
433
+ "units": instance["draw"].get(home, 1.0),
434
+ "to_type": to_type,
435
+ "dest": dest,
436
+ "to_units": to_units,
437
+ "spill_price": spill_price,
438
+ }
439
+
440
+
441
+ def _choose_best_landing(
442
+ instance: dict[str, Any],
443
+ available: dict[tuple[str, str], float],
444
+ flexible_names: set[tuple[str, str]],
445
+ *,
446
+ cloud: str,
447
+ specs: dict[tuple[str, str], SpecRow],
448
+ ) -> dict[str, Any] | None:
449
+ for candidate in _sorted_candidates(instance.get("candidates") or []):
450
+ target = str(candidate.get("instance") or "")
451
+ platform = str(candidate.get("platform") or instance["platform"])
452
+ family = family_of(target, cloud=cloud)
453
+ pool = (platform, family) if (platform, family) in flexible_names else (platform, target)
454
+ if not _run_type_fits(instance, target, cloud=cloud, specs=specs):
455
+ continue
456
+ draw = instance_draw(target, flexible=pool in flexible_names, cloud=cloud, specs=specs)
457
+ if available.get(pool, 0.0) + 1e-9 < draw:
458
+ continue
459
+ return {
460
+ "instance": instance,
461
+ "pool": pool,
462
+ "units": draw,
463
+ "to_type": target,
464
+ }
465
+ return None
466
+
467
+
468
+ def _available_after_evictions(
469
+ free_units: dict[tuple[str, str], float],
470
+ evict_set: list[dict[str, Any]],
471
+ ) -> dict[tuple[str, str], float] | None:
472
+ available = dict(free_units)
473
+ for item in evict_set:
474
+ available[item["source"]] = available.get(item["source"], 0.0) + item["units"]
475
+ dest = item.get("dest")
476
+ if dest is not None:
477
+ available[dest] = available.get(dest, 0.0) - float(item.get("to_units") or 0.0)
478
+ if available[dest] < -1e-6:
479
+ return None
480
+ return available
481
+
482
+
483
+ def _used_after_plan(
484
+ used_units: dict[tuple[str, str], float],
485
+ evict_set: list[dict[str, Any]],
486
+ placed: list[dict[str, Any]],
487
+ ) -> dict[tuple[str, str], float]:
488
+ used = dict(used_units)
489
+ for item in evict_set:
490
+ used[item["source"]] = used.get(item["source"], 0.0) - item["units"]
491
+ dest = item.get("dest")
492
+ if dest is not None:
493
+ used[dest] = used.get(dest, 0.0) + float(item.get("to_units") or 0.0)
494
+ for landing in placed:
495
+ pool = landing["pool"]
496
+ used[pool] = used.get(pool, 0.0) + landing["units"]
497
+ return used
498
+
499
+
500
+ def _total_idle(
501
+ capacity: dict[tuple[str, str], float],
502
+ used_after: dict[tuple[str, str], float],
503
+ ) -> float:
504
+ idle = 0.0
505
+ for pool, cap in capacity.items():
506
+ idle += max(cap - used_after.get(pool, 0.0), 0.0)
507
+ return idle
508
+
509
+
510
+ def _spill_cost(
511
+ instances: list[dict[str, Any]],
512
+ occupants: dict[str, tuple[str, str]],
513
+ evict_set: list[dict[str, Any]],
514
+ placed_ids: set[str],
515
+ ) -> float:
516
+ """On-demand cost of every priced workload left off reservation by this plan."""
517
+ evicted = {item["instance"]["id"]: item for item in evict_set}
518
+ cost = 0.0
519
+ for instance in instances:
520
+ item = evicted.get(instance["id"])
521
+ if item is not None:
522
+ if item.get("dest") is None:
523
+ cost += float(item["spill_price"])
524
+ continue
525
+ if instance["id"] in occupants or instance["id"] in placed_ids:
526
+ continue
527
+ price = _price_or_none(instance.get("price"))
528
+ if price is not None:
529
+ cost += price
530
+ return cost
531
+
532
+
533
+ def _place_subset(
534
+ entrants: list[dict[str, Any]],
535
+ available: dict[tuple[str, str], float],
536
+ flexible_names: set[tuple[str, str]],
537
+ *,
538
+ cloud: str,
539
+ specs: dict[tuple[str, str], SpecRow],
540
+ skip_unplaced: bool = False,
541
+ ) -> list[dict[str, Any]] | None:
542
+ order = sorted(entrants, key=lambda row: (-_price(row.get("price")), row["id"]))
543
+ avail = dict(available)
544
+ placed: list[dict[str, Any]] = []
545
+ for instance in order:
546
+ landing = _choose_best_landing(instance, avail, flexible_names, cloud=cloud, specs=specs)
547
+ if landing is None:
548
+ if skip_unplaced:
549
+ continue
550
+ return None
551
+ avail[landing["pool"]] = avail.get(landing["pool"], 0.0) - landing["units"]
552
+ placed.append(landing)
553
+ return placed
554
+
555
+
556
+ def _choose_moves(
557
+ instances: list[dict[str, Any]],
558
+ *,
559
+ occupants: dict[str, tuple[str, str]],
560
+ free_units: dict[tuple[str, str], float],
561
+ used_units: dict[tuple[str, str], float],
562
+ flexible_names: set[tuple[str, str]],
563
+ cloud: str,
564
+ specs: dict[tuple[str, str], SpecRow],
565
+ ) -> tuple[list[dict[str, Any]], str]:
566
+ capacity = _pool_capacity(free_units, used_units)
567
+ pools = set(capacity)
568
+ priced = [row for row in instances if _price_or_none(row.get("price")) is not None]
569
+ on_reservation = [row for row in priced if row["id"] in occupants]
570
+ off_reservation = [row for row in priced if row["id"] not in occupants]
571
+ evictions = [
572
+ item
573
+ for row in on_reservation
574
+ if (item := _build_eviction(row, occupants, flexible_names, pools, cloud=cloud, specs=specs)) is not None
575
+ ]
576
+
577
+ def evaluate(
578
+ evict_set: list[dict[str, Any]],
579
+ place_set: list[dict[str, Any]],
580
+ *,
581
+ skip_unplaced: bool,
582
+ ) -> tuple[tuple[float, float, str], list[dict[str, Any]]] | None:
583
+ available = _available_after_evictions(free_units, evict_set)
584
+ if available is None:
585
+ return None
586
+ placed = _place_subset(
587
+ place_set,
588
+ available,
589
+ flexible_names,
590
+ cloud=cloud,
591
+ specs=specs,
592
+ skip_unplaced=skip_unplaced,
593
+ )
594
+ if placed is None:
595
+ return None
596
+ used_after = _used_after_plan(used_units, evict_set, placed)
597
+ if any(used_after.get(pool, 0.0) > capacity.get(pool, 0.0) + 1e-6 for pool in capacity):
598
+ return None
599
+ placed_ids = {item["instance"]["id"] for item in placed}
600
+ idle = _total_idle(capacity, used_after)
601
+ spill = _spill_cost(instances, occupants, evict_set, placed_ids)
602
+ return (idle, spill, str(_moves_from(evict_set, placed))), placed
603
+
604
+ best: tuple[tuple[float, float, str], list[dict[str, Any]], list[dict[str, Any]]] | None = None
605
+ if len(evictions) > _MAX_SEARCH or len(off_reservation) > _MAX_SEARCH:
606
+ best = _hill_climb(evictions, off_reservation, evaluate)
607
+ else:
608
+ for evict_set in _subsets(evictions):
609
+ for place_set in _subsets(off_reservation):
610
+ scored = evaluate(evict_set, place_set, skip_unplaced=False)
611
+ if scored is None:
612
+ continue
613
+ if best is None or scored[0] < best[0]:
614
+ best = (scored[0], evict_set, scored[1])
615
+ if best is None:
616
+ return [], "fill"
617
+ method = "restack" if best[1] else "fill"
618
+ return _moves_from(best[1], best[2]), method
619
+
620
+
621
+ def _hill_climb(
622
+ evictions: list[dict[str, Any]],
623
+ entrants: list[dict[str, Any]],
624
+ evaluate: Callable[..., Any],
625
+ ) -> tuple[tuple[float, float, str], list[dict[str, Any]], list[dict[str, Any]]] | None:
626
+ """Bounded search for fleets too large to enumerate: toggle one eviction at a time.
627
+
628
+ Entrants are placed greedily (most expensive first, skipping any that do not fit),
629
+ so spillover and restack are still weighed instead of falling back to fill only.
630
+ """
631
+ chosen: list[dict[str, Any]] = []
632
+ scored = evaluate(chosen, entrants, skip_unplaced=True)
633
+ if scored is None:
634
+ return None
635
+ best = (scored[0], list(chosen), scored[1])
636
+ improved = True
637
+ while improved:
638
+ improved = False
639
+ for item in evictions:
640
+ present = any(row is item for row in chosen)
641
+ trial = [row for row in chosen if row is not item] if present else [*chosen, item]
642
+ result = evaluate(trial, entrants, skip_unplaced=True)
643
+ if result is not None and result[0] < best[0]:
644
+ chosen = trial
645
+ best = (result[0], list(trial), result[1])
646
+ improved = True
647
+ return best
648
+
649
+
650
+ def _destination_pool(
651
+ instance_type: str,
652
+ platform: str,
653
+ flexible_names: set[tuple[str, str]],
654
+ pools: set[tuple[str, str]],
655
+ *,
656
+ cloud: str,
657
+ ) -> tuple[str, str] | None:
658
+ family = family_of(instance_type, cloud=cloud)
659
+ if (platform, family) in flexible_names:
660
+ return (platform, family)
661
+ exact = (platform, instance_type)
662
+ if exact in pools and exact not in flexible_names:
663
+ return exact
664
+ return None
665
+
666
+
667
+ def _dest_draw(
668
+ instance_type: str,
669
+ dest: tuple[str, str] | None,
670
+ flexible_names: set[tuple[str, str]],
671
+ *,
672
+ cloud: str,
673
+ specs: dict[tuple[str, str], SpecRow],
674
+ ) -> float:
675
+ if dest is None:
676
+ return 0.0
677
+ return instance_draw(instance_type, flexible=dest in flexible_names, cloud=cloud, specs=specs)
678
+
679
+
680
+ def _subsets(rows: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
681
+ found: list[list[dict[str, Any]]] = []
682
+ for size in range(len(rows) + 1):
683
+ found.extend(list(group) for group in combinations(rows, size))
684
+ return found
685
+
686
+
687
+ def _moves_from(bad: list[dict[str, Any]], entrants: list[dict[str, Any]]) -> list[dict[str, Any]]:
688
+ raw: list[dict[str, Any]] = []
689
+ for item in bad:
690
+ instance = item["instance"]
691
+ kind = "reservation_to_reservation" if item.get("dest") else "reservation_to_ondemand"
692
+ row: dict[str, Any] = {
693
+ "instance_id": instance["id"],
694
+ "instance_name": instance["name"],
695
+ "from_instance_type": instance["instance_type"],
696
+ "to_instance_type": item["to_type"],
697
+ "units": item["units"],
698
+ "from_family": instance["family"],
699
+ "to_family": family_of(str(item["to_type"]), cloud=instance["cloud"]),
700
+ "kind": kind,
701
+ }
702
+ if kind == "reservation_to_reservation":
703
+ row["to_units"] = item.get("to_units")
704
+ raw.append(row)
705
+ for item in entrants:
706
+ instance = item["instance"]
707
+ raw.append(
708
+ {
709
+ "instance_id": instance["id"],
710
+ "instance_name": instance["name"],
711
+ "from_instance_type": instance["instance_type"],
712
+ "to_instance_type": item["to_type"],
713
+ "units": item["units"],
714
+ "from_family": instance["family"],
715
+ "to_family": family_of(str(item["to_type"]), cloud=instance["cloud"]),
716
+ "kind": "ondemand_to_reservation",
717
+ }
718
+ )
719
+ raw.sort(
720
+ key=lambda row: (
721
+ _KIND_ORDER.get(str(row["kind"]), 9),
722
+ str(row["from_family"]),
723
+ str(row["to_family"]),
724
+ -_price(row.get("units")),
725
+ str(row["instance_id"]),
726
+ )
727
+ )
728
+ grouped: list[dict[str, Any]] = []
729
+ for row in raw:
730
+ key = (row["kind"], row["from_family"], row["to_family"])
731
+ if not grouped or (
732
+ grouped[-1]["kind"],
733
+ grouped[-1]["from_family"],
734
+ grouped[-1]["to_family"],
735
+ ) != key:
736
+ grouped.append(
737
+ {
738
+ "from_family": row["from_family"],
739
+ "to_family": row["to_family"],
740
+ "kind": row["kind"],
741
+ "instances": [],
742
+ }
743
+ )
744
+ instance = {
745
+ "instance_id": row["instance_id"],
746
+ "instance_name": row["instance_name"],
747
+ "from_instance_type": row["from_instance_type"],
748
+ "to_instance_type": row["to_instance_type"],
749
+ "units": row["units"],
750
+ }
751
+ if "to_units" in row:
752
+ instance["to_units"] = row["to_units"]
753
+ grouped[-1]["instances"].append(instance)
754
+ return grouped
755
+
756
+
757
+ def _to_be(
758
+ as_is: list[dict[str, Any]],
759
+ records: list[dict[str, Any]],
760
+ instances: list[dict[str, Any]],
761
+ occupants: dict[str, tuple[str, str]],
762
+ moves: list[dict[str, Any]],
763
+ *,
764
+ region: str,
765
+ cloud: str,
766
+ specs: dict[tuple[str, str], SpecRow],
767
+ flexible_names: set[tuple[str, str]],
768
+ ) -> list[dict[str, Any]]:
769
+ by_id = {row["id"]: row for row in instances}
770
+ leaving = {
771
+ instance["instance_id"]
772
+ for group in moves
773
+ for instance in group.get("instances") or []
774
+ if group.get("kind") != "ondemand_to_reservation"
775
+ }
776
+ entering: dict[tuple[str, str], list[dict[str, Any]]] = {}
777
+ for group in moves:
778
+ for instance in group.get("instances") or []:
779
+ if group.get("kind") == "reservation_to_ondemand":
780
+ continue
781
+ target = str(instance.get("to_instance_type") or "")
782
+ platform = by_id.get(instance["instance_id"], {}).get("platform", "")
783
+ family = family_of(target, cloud=cloud)
784
+ pool = (platform, family) if (platform, family) in flexible_names else (platform, target)
785
+ entering.setdefault(pool, []).append(instance)
786
+ rows: list[dict[str, Any]] = []
787
+ for reservation in as_is:
788
+ record = next(
789
+ (
790
+ item
791
+ for item in records
792
+ if str(item.get("name") or item.get("subscription_id") or item.get("instance_type"))
793
+ == reservation["name"]
794
+ and str(item.get("region") or "").strip().lower() == region.strip().lower()
795
+ ),
796
+ None,
797
+ )
798
+ if record is None:
799
+ continue
800
+ flexible, name, factor = pool_draw(record, specs, cloud=cloud)
801
+ platform = "*" if cloud == "azure" else normalize_platform(str(record.get("platform") or ""))
802
+ try:
803
+ quantity = float(record.get("quantity") or 1)
804
+ except (TypeError, ValueError):
805
+ quantity = 1.0
806
+ capacity = quantity * factor
807
+ pool = (platform, name)
808
+ stayers = []
809
+ for instance in instances:
810
+ if occupants.get(instance["id"]) != pool or instance["id"] in leaving:
811
+ continue
812
+ stayers.append(instance)
813
+ stayers.sort(key=lambda row: row["id"])
814
+ occupants_out = [
815
+ {
816
+ "instance_id": row["id"],
817
+ "instance_name": row["name"],
818
+ "instance_type": row["instance_type"],
819
+ "units": row["draw"].get(pool, 1.0),
820
+ }
821
+ for row in stayers
822
+ ]
823
+ for instance in entering.get(pool, []):
824
+ occupants_out.append(
825
+ {
826
+ "instance_id": instance["instance_id"],
827
+ "instance_name": instance["instance_name"],
828
+ "instance_type": instance["to_instance_type"],
829
+ "units": instance.get("to_units", instance.get("units")),
830
+ }
831
+ )
832
+ used = sum(_price(row.get("units")) for row in occupants_out)
833
+ rows.append(
834
+ {
835
+ "name": reservation["name"],
836
+ "capacity_units": capacity,
837
+ "idle_units": max(capacity - used, 0.0),
838
+ "occupants": occupants_out,
839
+ }
840
+ )
841
+ return rows
842
+
843
+
844
+ def prepare_instances(
845
+ pending: list[tuple[Any, Any]],
846
+ responses: dict[int, dict[str, Any]],
847
+ specs: dict[tuple[str, str], SpecRow],
848
+ ) -> list[dict[str, Any]]:
849
+ from maproom.analyze.spot_analyze import is_spot_instance
850
+
851
+ prepared: list[dict[str, Any]] = []
852
+ for index, (item, assessment) in enumerate(pending):
853
+ if is_spot_instance(item) or str(item.lifecycle or "").strip().lower() == "spot":
854
+ continue
855
+ response = responses.get(index)
856
+ if response is None:
857
+ continue
858
+ current = specs.get((item.cloud, item.instance_type))
859
+ if current is None:
860
+ continue
861
+ candidates = eligible_candidates(
862
+ response,
863
+ current=current,
864
+ instance_platform=str(item.platform or ""),
865
+ specs=specs,
866
+ )
867
+ cloud = "azure" if item.cloud == "azure" else "aws"
868
+ prepared.append(
869
+ {
870
+ "index": index,
871
+ "id": item.instance_id,
872
+ "name": item.name or item.instance_id,
873
+ "instance_type": item.instance_type,
874
+ "family": family_of(item.instance_type, cloud=cloud),
875
+ "platform": "*" if cloud == "azure" else normalize_platform(str(item.platform or "")),
876
+ "cloud": cloud,
877
+ "region": item.region,
878
+ "price": response.get("current_on_demand_price"),
879
+ "candidates": candidates,
880
+ "cross_family_target": getattr(assessment, "cross_family_target", None),
881
+ }
882
+ )
883
+ return prepared