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,644 @@
1
+ """Local MUV candidate engine (NEXT-1 W4)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from decimal import Decimal
7
+ from typing import Any, Literal
8
+
9
+ from maproom.analyze.specs import InstanceSpec, SpecCatalog
10
+ from maproom.pricing import PriceTable
11
+
12
+ ENGINE_VERSION = "muv-1"
13
+
14
+ REJECT_RULE_ORDER: tuple[str, ...] = (
15
+ "not_offered_in_region",
16
+ "no_price_in_file",
17
+ "accelerator_or_bare_metal",
18
+ "insufficient_memory",
19
+ "not_cheaper",
20
+ "below_savings_floor",
21
+ "insufficient_cpu",
22
+ "quota_blocked",
23
+ )
24
+
25
+ CURATED_REJECTED_LIMIT = 10
26
+
27
+ _CONFIDENCE_RANK = {"HIGH": 3, "MEDIUM": 2, "LOW": 1}
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class EngineSettings:
32
+ min_savings_usd_month: Decimal = Decimal("5")
33
+ cpu_headroom_pct: int = 70
34
+ consolidation_p95_pct: int = 50
35
+ max_recommendations: int = 3
36
+ max_conditional: int = 3
37
+ min_days_since_change: int = 7
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class UtilizationSummary:
42
+ cpu_p95_pct: float | None
43
+ downsize_cpu_reliable: bool = True
44
+
45
+
46
+ @dataclass
47
+ class Candidate:
48
+ instance_type: str
49
+ price_per_month_usd: Decimal
50
+ savings_per_month_usd: Decimal
51
+ savings_pct: int
52
+ confidence: Literal["HIGH", "MEDIUM", "LOW"]
53
+ migration_options: list[str]
54
+ validation_steps: list[str]
55
+ missing_evidence: list[str]
56
+ projected_cpu_p95_pct: float | None = None
57
+ burstable: bool = False
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class RejectedCandidate:
62
+ instance_type: str
63
+ reason: str
64
+ price_per_month_usd: Decimal | None = None
65
+
66
+
67
+ @dataclass
68
+ class EngineResult:
69
+ recommendations: list[Candidate]
70
+ conditional: list[Candidate]
71
+ rejected: list[RejectedCandidate]
72
+ rejected_total: int
73
+ rejected_by_reason: dict[str, int]
74
+ evaluated_total: int
75
+
76
+
77
+ def engine_settings_from_mapping(settings: dict[str, Any]) -> EngineSettings:
78
+ raw = settings.get("engine")
79
+ if not isinstance(raw, dict):
80
+ raw = {}
81
+ min_savings = raw.get("min_savings_usd_month", 5)
82
+ return EngineSettings(
83
+ min_savings_usd_month=Decimal(str(min_savings)),
84
+ cpu_headroom_pct=int(raw.get("cpu_headroom_pct", 70)),
85
+ consolidation_p95_pct=int(raw.get("consolidation_p95_pct", 50)),
86
+ max_recommendations=int(raw.get("max_recommendations", 3)),
87
+ max_conditional=int(raw.get("max_conditional", 3)),
88
+ min_days_since_change=int(raw.get("min_days_since_change", 7)),
89
+ )
90
+
91
+
92
+ def _quantize_usd(value: Decimal) -> Decimal:
93
+ return value.quantize(Decimal("0.01"))
94
+
95
+
96
+ def _usd_amount_str(value: Decimal) -> str:
97
+ rounded = _quantize_usd(value)
98
+ integral = rounded.to_integral_value()
99
+ if rounded == integral:
100
+ return str(int(integral))
101
+ text = format(rounded.normalize(), "f")
102
+ if "." in text:
103
+ text = text.rstrip("0").rstrip(".")
104
+ return text
105
+
106
+
107
+ def _savings_pct(current_monthly: Decimal, candidate_monthly: Decimal) -> int:
108
+ if current_monthly <= 0:
109
+ return int(round(0))
110
+ savings = current_monthly - candidate_monthly
111
+ return int(round(100 * savings / current_monthly))
112
+
113
+
114
+ def _projected_cpu_p95(
115
+ observed_p95: float,
116
+ current_vcpus: int,
117
+ candidate_vcpus: int,
118
+ ) -> float | None:
119
+ if candidate_vcpus <= 0 or current_vcpus <= 0:
120
+ return None
121
+ return observed_p95 * current_vcpus / candidate_vcpus
122
+
123
+
124
+ def _architectures_intersect(current: InstanceSpec, candidate: InstanceSpec) -> bool:
125
+ if not current.architectures or not candidate.architectures:
126
+ return True
127
+ return bool(set(current.architectures) & set(candidate.architectures))
128
+
129
+
130
+ def _arch_rebuild_condition(current: InstanceSpec, candidate: InstanceSpec) -> str | None:
131
+ if _architectures_intersect(current, candidate):
132
+ return None
133
+ current_arm = any(arch in ("arm64", "aarch64") for arch in current.architectures)
134
+ cand_arm = any(arch in ("arm64", "aarch64") for arch in candidate.architectures)
135
+ if cand_arm and not current_arm:
136
+ return "REBUILD_FOR_ARM"
137
+ if current_arm and not cand_arm:
138
+ return "REBUILD_FOR_X86"
139
+ return "REBUILD_FOR_ARM"
140
+
141
+
142
+ def _human_reason(reason_code: str, *, spec: InstanceSpec | None = None) -> str:
143
+ if reason_code == "not_offered_in_region":
144
+ return "not offered in target region"
145
+ if reason_code == "no_price_in_file":
146
+ return "no on-demand price in shipped file"
147
+ if reason_code == "accelerator_or_bare_metal":
148
+ if spec is None:
149
+ return "accelerator, bare metal, or missing instance spec"
150
+ if spec.bare_metal:
151
+ return "bare metal instance type"
152
+ if spec.accelerators:
153
+ return "accelerator instance type"
154
+ return "instance spec unavailable"
155
+ if reason_code == "insufficient_memory":
156
+ return "candidate memory below current type"
157
+ if reason_code == "not_cheaper":
158
+ return "on-demand price not lower than current"
159
+ if reason_code == "below_savings_floor":
160
+ return "monthly savings below configured floor"
161
+ if reason_code == "insufficient_cpu":
162
+ return "projected CPU p95 above headroom threshold"
163
+ if reason_code == "quota_blocked":
164
+ return "quota snapshot blocks launch"
165
+ if reason_code == "ranked_below_cutoff":
166
+ return "ranked below surfaced cutoff"
167
+ return reason_code
168
+
169
+
170
+ def _confidence_for(
171
+ *,
172
+ current: InstanceSpec,
173
+ candidate: InstanceSpec,
174
+ cpu_evidence: bool,
175
+ has_conditions: bool,
176
+ ) -> Literal["HIGH", "MEDIUM", "LOW"]:
177
+ if not cpu_evidence or has_conditions:
178
+ return "LOW"
179
+ cross_family = candidate.family != current.family
180
+ cross_generation = candidate.generation != current.generation
181
+ if cross_family or cross_generation:
182
+ return "MEDIUM"
183
+ return "HIGH"
184
+
185
+
186
+ def _sort_key(candidate: Candidate) -> tuple[Any, ...]:
187
+ burstable_rank = 1 if candidate.burstable else 0
188
+ return (
189
+ -candidate.savings_per_month_usd,
190
+ burstable_rank,
191
+ -_CONFIDENCE_RANK[candidate.confidence],
192
+ candidate.instance_type,
193
+ )
194
+
195
+
196
+ def evaluate_candidates(
197
+ current: InstanceSpec,
198
+ catalog: SpecCatalog,
199
+ prices: PriceTable,
200
+ utilization: UtilizationSummary,
201
+ settings: EngineSettings,
202
+ quota_blocked: set[str] | None = None,
203
+ ) -> EngineResult:
204
+ """Evaluate all offered types except the current instance."""
205
+ region = catalog.region
206
+ blocked = quota_blocked or set()
207
+ current_type = current.instance_type
208
+ current_monthly = prices.monthly(current_type, region)
209
+ if current_monthly is None:
210
+ current_monthly = Decimal("0")
211
+
212
+ cpu_observed = utilization.cpu_p95_pct
213
+ cpu_evidence = cpu_observed is not None and utilization.downsize_cpu_reliable
214
+
215
+ survivors: list[Candidate] = []
216
+ rejected: list[RejectedCandidate] = []
217
+
218
+ for instance_type in sorted(catalog.offered):
219
+ if instance_type == current_type:
220
+ continue
221
+
222
+ if instance_type not in catalog.offered:
223
+ rejected.append(
224
+ RejectedCandidate(
225
+ instance_type=instance_type,
226
+ reason="not_offered_in_region",
227
+ )
228
+ )
229
+ continue
230
+
231
+ monthly = prices.monthly(instance_type, region)
232
+ if monthly is None:
233
+ rejected.append(
234
+ RejectedCandidate(
235
+ instance_type=instance_type,
236
+ reason="no_price_in_file",
237
+ )
238
+ )
239
+ continue
240
+
241
+ spec = catalog.specs.get(instance_type)
242
+ if spec is None or spec.accelerators or spec.bare_metal:
243
+ rejected.append(
244
+ RejectedCandidate(
245
+ instance_type=instance_type,
246
+ reason="accelerator_or_bare_metal",
247
+ price_per_month_usd=monthly,
248
+ )
249
+ )
250
+ continue
251
+
252
+ if spec.memory_mib < current.memory_mib:
253
+ rejected.append(
254
+ RejectedCandidate(
255
+ instance_type=instance_type,
256
+ reason="insufficient_memory",
257
+ price_per_month_usd=monthly,
258
+ )
259
+ )
260
+ continue
261
+
262
+ if monthly >= current_monthly:
263
+ rejected.append(
264
+ RejectedCandidate(
265
+ instance_type=instance_type,
266
+ reason="not_cheaper",
267
+ price_per_month_usd=monthly,
268
+ )
269
+ )
270
+ continue
271
+
272
+ savings = current_monthly - monthly
273
+ if savings < settings.min_savings_usd_month:
274
+ rejected.append(
275
+ RejectedCandidate(
276
+ instance_type=instance_type,
277
+ reason="below_savings_floor",
278
+ price_per_month_usd=monthly,
279
+ )
280
+ )
281
+ continue
282
+
283
+ projected: float | None = None
284
+ if cpu_evidence and cpu_observed is not None:
285
+ projected = _projected_cpu_p95(
286
+ cpu_observed,
287
+ current.vcpus,
288
+ spec.vcpus,
289
+ )
290
+ if projected is not None and projected > settings.cpu_headroom_pct:
291
+ rejected.append(
292
+ RejectedCandidate(
293
+ instance_type=instance_type,
294
+ reason="insufficient_cpu",
295
+ price_per_month_usd=monthly,
296
+ )
297
+ )
298
+ continue
299
+
300
+ if instance_type in blocked:
301
+ rejected.append(
302
+ RejectedCandidate(
303
+ instance_type=instance_type,
304
+ reason="quota_blocked",
305
+ price_per_month_usd=monthly,
306
+ )
307
+ )
308
+ continue
309
+
310
+ conditions: list[str] = []
311
+ missing: list[str] = ["memory_utilization"]
312
+ if not cpu_evidence:
313
+ missing.append("cpu_utilization")
314
+
315
+ arch_cond = _arch_rebuild_condition(current, spec)
316
+ if arch_cond:
317
+ conditions.append(arch_cond)
318
+
319
+ if current.instance_storage and not spec.instance_storage:
320
+ conditions.append("MIGRATE_LOCAL_STORAGE")
321
+
322
+ if cpu_evidence and projected is not None:
323
+ halving_or_more = spec.vcpus <= current.vcpus / 2
324
+ # Live run F2: single-vCPU targets from multi-vCPU current need headroom check.
325
+ single_vcpu_downsize = spec.vcpus == 1 and current.vcpus > 1
326
+ if (
327
+ halving_or_more
328
+ or single_vcpu_downsize
329
+ or projected > settings.consolidation_p95_pct
330
+ ):
331
+ if "VERIFY_CPU_HEADROOM" not in conditions:
332
+ conditions.append("VERIFY_CPU_HEADROOM")
333
+ elif not cpu_evidence:
334
+ pass
335
+
336
+ if spec.burstable and not current.burstable:
337
+ conditions.append("VERIFY_BURST_CREDITS")
338
+
339
+ if not cpu_evidence and "VERIFY_CPU_HEADROOM" not in conditions:
340
+ conditions.append("VERIFY_CPU_HEADROOM")
341
+
342
+ has_conditions = bool(conditions) or not cpu_evidence
343
+ confidence = _confidence_for(
344
+ current=current,
345
+ candidate=spec,
346
+ cpu_evidence=cpu_evidence,
347
+ has_conditions=has_conditions,
348
+ )
349
+
350
+ validation_steps = ["RESIZE_WITH_DOWNTIME"]
351
+ if any(c.startswith("REBUILD_FOR_") for c in conditions):
352
+ validation_steps.append("VERIFY_ARCH_BUILD")
353
+
354
+ if cpu_evidence and not conditions:
355
+ migration_options = ["NO_MIGRATION"]
356
+ else:
357
+ migration_options = list(conditions)
358
+
359
+ survivors.append(
360
+ Candidate(
361
+ instance_type=instance_type,
362
+ price_per_month_usd=_quantize_usd(monthly),
363
+ savings_per_month_usd=_quantize_usd(savings),
364
+ savings_pct=_savings_pct(current_monthly, monthly),
365
+ confidence=confidence,
366
+ migration_options=migration_options,
367
+ validation_steps=validation_steps,
368
+ missing_evidence=missing,
369
+ projected_cpu_p95_pct=projected,
370
+ burstable=spec.burstable,
371
+ )
372
+ )
373
+
374
+ unconditional = [
375
+ c
376
+ for c in survivors
377
+ if c.migration_options == ["NO_MIGRATION"]
378
+ and "cpu_utilization" not in c.missing_evidence
379
+ ]
380
+ conditional = [c for c in survivors if c not in unconditional]
381
+
382
+ unconditional.sort(key=_sort_key)
383
+ conditional.sort(key=_sort_key)
384
+
385
+ recommendations = unconditional[: settings.max_recommendations]
386
+ conditional_out = conditional[: settings.max_conditional]
387
+
388
+ overflow: list[Candidate] = []
389
+ overflow.extend(unconditional[settings.max_recommendations :])
390
+ overflow.extend(conditional[settings.max_conditional :])
391
+ for cand in overflow:
392
+ rejected.append(
393
+ RejectedCandidate(
394
+ instance_type=cand.instance_type,
395
+ reason="ranked_below_cutoff",
396
+ price_per_month_usd=cand.price_per_month_usd,
397
+ )
398
+ )
399
+
400
+ rejected_by_reason: dict[str, int] = {}
401
+ for item in rejected:
402
+ rejected_by_reason[item.reason] = rejected_by_reason.get(item.reason, 0) + 1
403
+
404
+ evaluated = len(catalog.offered) - (1 if current_type in catalog.offered else 0)
405
+
406
+ return EngineResult(
407
+ recommendations=recommendations,
408
+ conditional=conditional_out,
409
+ rejected=rejected,
410
+ rejected_total=len(rejected),
411
+ rejected_by_reason=rejected_by_reason,
412
+ evaluated_total=evaluated,
413
+ )
414
+
415
+
416
+ def _instance_is_undersized(
417
+ utilization: UtilizationSummary,
418
+ settings: EngineSettings,
419
+ ) -> bool:
420
+ if utilization.cpu_p95_pct is None:
421
+ return False
422
+ return utilization.cpu_p95_pct > settings.cpu_headroom_pct
423
+
424
+
425
+ def evaluate_upsize_candidates(
426
+ current: InstanceSpec,
427
+ catalog: SpecCatalog,
428
+ prices: PriceTable,
429
+ utilization: UtilizationSummary,
430
+ settings: EngineSettings,
431
+ quota_blocked: set[str] | None = None,
432
+ ) -> list[Candidate]:
433
+ """Surface urgent upsize options when observed CPU p95 exceeds headroom."""
434
+ if not _instance_is_undersized(utilization, settings):
435
+ return []
436
+
437
+ region = catalog.region
438
+ blocked = quota_blocked or set()
439
+ current_type = current.instance_type
440
+ current_monthly = prices.monthly(current_type, region) or Decimal("0")
441
+ cpu_observed = utilization.cpu_p95_pct
442
+ assert cpu_observed is not None
443
+
444
+ survivors: list[Candidate] = []
445
+ for instance_type in sorted(catalog.offered):
446
+ if instance_type == current_type:
447
+ continue
448
+ monthly = prices.monthly(instance_type, region)
449
+ if monthly is None:
450
+ continue
451
+ spec = catalog.specs.get(instance_type)
452
+ if spec is None or spec.accelerators or spec.bare_metal:
453
+ continue
454
+ if spec.memory_mib < current.memory_mib:
455
+ continue
456
+ if spec.vcpus < current.vcpus:
457
+ continue
458
+ if monthly <= current_monthly and spec.vcpus <= current.vcpus:
459
+ continue
460
+ if instance_type in blocked:
461
+ continue
462
+
463
+ projected = _projected_cpu_p95(
464
+ cpu_observed,
465
+ current.vcpus,
466
+ spec.vcpus,
467
+ )
468
+ if projected is not None and projected > settings.cpu_headroom_pct:
469
+ continue
470
+
471
+ same_family_larger = (
472
+ spec.family == current.family
473
+ and spec.generation == current.generation
474
+ and spec.vcpus > current.vcpus
475
+ )
476
+ same_or_more_vcpu = spec.vcpus >= current.vcpus
477
+ if not (same_family_larger or same_or_more_vcpu):
478
+ continue
479
+
480
+ savings = current_monthly - monthly
481
+ conditions = ["URGENT_UPSIZE"]
482
+ arch_cond = _arch_rebuild_condition(current, spec)
483
+ if arch_cond:
484
+ conditions.append(arch_cond)
485
+ survivors.append(
486
+ Candidate(
487
+ instance_type=instance_type,
488
+ price_per_month_usd=_quantize_usd(monthly),
489
+ savings_per_month_usd=_quantize_usd(max(Decimal("0"), savings)),
490
+ savings_pct=max(0, _savings_pct(current_monthly, monthly)),
491
+ confidence="MEDIUM" if arch_cond else "HIGH",
492
+ migration_options=conditions,
493
+ validation_steps=["RESIZE_WITH_DOWNTIME"],
494
+ missing_evidence=["memory_utilization"],
495
+ projected_cpu_p95_pct=projected,
496
+ burstable=spec.burstable,
497
+ )
498
+ )
499
+
500
+ survivors.sort(key=_sort_key)
501
+ return survivors[: settings.max_recommendations]
502
+
503
+
504
+ def _tag_cooldown(candidate: Candidate) -> Candidate:
505
+ options = list(candidate.migration_options)
506
+ if "COOLDOWN_AFTER_CHANGE" not in options:
507
+ options.append("COOLDOWN_AFTER_CHANGE")
508
+ return Candidate(
509
+ instance_type=candidate.instance_type,
510
+ price_per_month_usd=candidate.price_per_month_usd,
511
+ savings_per_month_usd=candidate.savings_per_month_usd,
512
+ savings_pct=candidate.savings_pct,
513
+ confidence=candidate.confidence,
514
+ migration_options=options,
515
+ validation_steps=list(candidate.validation_steps),
516
+ missing_evidence=list(candidate.missing_evidence),
517
+ projected_cpu_p95_pct=candidate.projected_cpu_p95_pct,
518
+ burstable=candidate.burstable,
519
+ )
520
+
521
+
522
+ def _is_upsize_candidate(candidate: Candidate) -> bool:
523
+ return "URGENT_UPSIZE" in candidate.migration_options
524
+
525
+
526
+ def merge_upsize_results(
527
+ downsize_result: EngineResult,
528
+ upsizes: list[Candidate],
529
+ *,
530
+ max_recommendations: int,
531
+ ) -> EngineResult:
532
+ """Promote upsize survivors from rejected (not_cheaper) into recommendations."""
533
+ if not upsizes:
534
+ return downsize_result
535
+
536
+ upsize_types = {item.instance_type for item in upsizes}
537
+ rejected = [
538
+ item
539
+ for item in downsize_result.rejected
540
+ if item.instance_type not in upsize_types
541
+ ]
542
+ rejected_by_reason: dict[str, int] = {}
543
+ for item in rejected:
544
+ rejected_by_reason[item.reason] = rejected_by_reason.get(item.reason, 0) + 1
545
+
546
+ recommendations = (upsizes + downsize_result.recommendations)[:max_recommendations]
547
+
548
+ return EngineResult(
549
+ recommendations=recommendations,
550
+ conditional=downsize_result.conditional,
551
+ rejected=rejected,
552
+ rejected_total=len(rejected),
553
+ rejected_by_reason=rejected_by_reason,
554
+ evaluated_total=downsize_result.evaluated_total,
555
+ )
556
+
557
+
558
+ def apply_change_cooldown(
559
+ result: EngineResult,
560
+ *,
561
+ cooldown_active: bool,
562
+ max_conditional: int,
563
+ ) -> EngineResult:
564
+ """Move downsize recommendations into conditional while cooldown is active."""
565
+ if not cooldown_active:
566
+ return result
567
+
568
+ kept_recommendations: list[Candidate] = []
569
+ moved: list[Candidate] = []
570
+ for cand in result.recommendations:
571
+ if _is_upsize_candidate(cand):
572
+ kept_recommendations.append(cand)
573
+ elif cand.savings_per_month_usd > 0:
574
+ moved.append(_tag_cooldown(cand))
575
+ else:
576
+ kept_recommendations.append(cand)
577
+
578
+ conditional: list[Candidate] = []
579
+ for cand in result.conditional:
580
+ if cand.savings_per_month_usd > 0:
581
+ conditional.append(_tag_cooldown(cand))
582
+ else:
583
+ conditional.append(cand)
584
+ conditional = moved + conditional
585
+ conditional.sort(key=_sort_key)
586
+ conditional_cap = max(max_conditional, len(moved) + len(result.conditional))
587
+ conditional_out = conditional[:conditional_cap]
588
+
589
+ return EngineResult(
590
+ recommendations=kept_recommendations,
591
+ conditional=conditional_out,
592
+ rejected=result.rejected,
593
+ rejected_total=result.rejected_total,
594
+ rejected_by_reason=dict(result.rejected_by_reason),
595
+ evaluated_total=result.evaluated_total,
596
+ )
597
+
598
+
599
+ def engine_metadata(settings: EngineSettings) -> dict[str, Any]:
600
+ return {
601
+ "version": ENGINE_VERSION,
602
+ "rules": list(REJECT_RULE_ORDER) + ["ranked_below_cutoff"],
603
+ "settings": {
604
+ "min_savings_usd_month": _usd_amount_str(settings.min_savings_usd_month),
605
+ "cpu_headroom_pct": settings.cpu_headroom_pct,
606
+ "consolidation_p95_pct": settings.consolidation_p95_pct,
607
+ "max_recommendations": settings.max_recommendations,
608
+ "max_conditional": settings.max_conditional,
609
+ "min_days_since_change": settings.min_days_since_change,
610
+ },
611
+ }
612
+
613
+
614
+ def candidate_to_document_item(
615
+ candidate: Candidate,
616
+ *,
617
+ rank: int | None = None,
618
+ region: str,
619
+ ) -> dict[str, Any]:
620
+ payload: dict[str, Any] = {
621
+ "candidate_id": f"cand-{candidate.instance_type}",
622
+ "instance_type": candidate.instance_type,
623
+ "price_per_month_usd": _usd_amount_str(candidate.price_per_month_usd),
624
+ "savings_per_month_usd": _usd_amount_str(candidate.savings_per_month_usd),
625
+ "savings_pct": candidate.savings_pct,
626
+ "confidence": candidate.confidence,
627
+ "migration_options": list(candidate.migration_options),
628
+ "validation_steps": list(candidate.validation_steps),
629
+ }
630
+ if rank is not None:
631
+ payload["rank"] = rank
632
+ if candidate.projected_cpu_p95_pct is not None:
633
+ payload["projected_cpu_p95_pct"] = round(candidate.projected_cpu_p95_pct, 2)
634
+ if rank is None:
635
+ payload["region"] = region
636
+ return payload
637
+
638
+
639
+ def rejected_to_document_item(item: RejectedCandidate) -> dict[str, Any]:
640
+ return {
641
+ "instance_type": item.instance_type,
642
+ "reason_code": item.reason,
643
+ "reason": _human_reason(item.reason),
644
+ }