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,97 @@
1
+ """Unitless CPU order from a family-performance model.
2
+
3
+ Rates come from the CPU benchmark section: work per second at full utilization,
4
+ scaled by each size's vCPU count through the published size_model. A
5
+ proportional model is ``factor`` times that vCPU count. ``cpu_order`` turns
6
+ those rates into a dense rank: the slowest distinct rate is 1, equal rates
7
+ share a number, and a higher number is faster. The work rate itself is not
8
+ returned.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from decimal import Decimal
14
+ from typing import Mapping
15
+
16
+
17
+ def cpu_order(document: Mapping[str, object], vcpus: Mapping[str, int]) -> dict[str, Decimal]:
18
+ """Return a dense rank for each modeled size whose vCPU count is known."""
19
+
20
+ rates = _full_cpu_rates(document, vcpus)
21
+ distinct = sorted(set(rates.values()))
22
+ index = {value: Decimal(place) for place, value in enumerate(distinct, start=1)}
23
+ return {name: index[value] for name, value in rates.items()}
24
+
25
+
26
+ def format_rank(value: Decimal) -> str:
27
+ text = format(value, "f")
28
+ if "." in text:
29
+ text = text.rstrip("0").rstrip(".")
30
+ return text
31
+
32
+
33
+ def _full_cpu_rates(document: Mapping[str, object], vcpus: Mapping[str, int]) -> dict[str, Decimal]:
34
+ rates: dict[str, Decimal] = {}
35
+ benchmarks = document.get("benchmarks")
36
+ if not isinstance(benchmarks, list):
37
+ return rates
38
+ for benchmark in benchmarks:
39
+ if not isinstance(benchmark, dict) or benchmark.get("benchmark") != "cpu":
40
+ continue
41
+ rows = benchmark.get("rates")
42
+ if not isinstance(rows, list):
43
+ continue
44
+ for rate in rows:
45
+ if not _is_cpu_rate_row(rate):
46
+ continue
47
+ families = rate.get("families")
48
+ if not isinstance(families, list):
49
+ continue
50
+ for family in families:
51
+ if not isinstance(family, dict):
52
+ continue
53
+ models = family.get("models")
54
+ if not isinstance(models, list):
55
+ continue
56
+ for model in models:
57
+ if not isinstance(model, dict):
58
+ continue
59
+ sizes = model.get("applies_to_sizes")
60
+ size_model = model.get("size_model")
61
+ if not isinstance(sizes, list) or not isinstance(size_model, dict):
62
+ continue
63
+ for size in sizes:
64
+ name = str(size).strip()
65
+ count = vcpus.get(name)
66
+ if not name or not count:
67
+ continue
68
+ value = _size_rate(size_model, count)
69
+ previous = rates.get(name)
70
+ if previous is not None and previous != value:
71
+ raise ValueError(f"{name} has conflicting cpu rank rates")
72
+ rates[name] = value
73
+ return rates
74
+
75
+
76
+ def _is_cpu_rate_row(rate: object) -> bool:
77
+ if not isinstance(rate, dict):
78
+ return False
79
+ return rate.get("unit") == "work_per_sec" and rate.get("size_variable") == "vcpus"
80
+
81
+
82
+ def _size_rate(size_model: Mapping[str, object], vcpus: int) -> Decimal:
83
+ form = str(size_model.get("form") or "")
84
+ count = Decimal(vcpus)
85
+ if form == "proportional":
86
+ return Decimal(str(size_model["factor"])) * count
87
+ if form == "constant":
88
+ return Decimal(str(size_model["c"]))
89
+ if form == "linear":
90
+ return Decimal(str(size_model["a"])) * count + Decimal(str(size_model["b"]))
91
+ if form == "quadratic":
92
+ return (
93
+ Decimal(str(size_model["a"])) * count * count
94
+ + Decimal(str(size_model["b"])) * count
95
+ + Decimal(str(size_model["c"]))
96
+ )
97
+ raise ValueError(f"unknown size_model form {form!r}")
@@ -0,0 +1,422 @@
1
+ """Select the single try-first recommendation from product_version."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from maproom.analyze.catalog import SpecRow
8
+ from maproom.analyze.safe_move import PRICE_ASSUMPTION, UNCHECKED_COVERAGE
9
+ from maproom.analyze.workset import WorkItem
10
+
11
+ _RESERVATION_MARKERS = (
12
+ "Reservation coverage",
13
+ "No matching reservation",
14
+ UNCHECKED_COVERAGE,
15
+ "reservation coverage",
16
+ "unused reservation",
17
+ "takes free reservation",
18
+ "takes reservation capacity",
19
+ "stays on the reservation",
20
+ "Reserved Instance",
21
+ )
22
+
23
+ _SAFE_DETAIL_PREFIXES = (
24
+ "Architecture:",
25
+ "Instruction sets:",
26
+ "CPU:",
27
+ "Memory:",
28
+ "Local disk:",
29
+ "EBS disk:",
30
+ "Network:",
31
+ "Price:",
32
+ "CPU performance",
33
+ "Target lacks",
34
+ )
35
+
36
+
37
+ def _is_reservation_line(line: str) -> bool:
38
+ lowered = line.lower()
39
+ for marker in _RESERVATION_MARKERS:
40
+ if marker.lower() in lowered:
41
+ return True
42
+ return False
43
+
44
+
45
+ def _is_move_line(line: str) -> bool:
46
+ stripped = line.strip()
47
+ return stripped.startswith("Move to ") or stripped.startswith("Move from ")
48
+
49
+
50
+ def _is_safe_detail_line(line: str) -> bool:
51
+ stripped = line.strip()
52
+ return any(stripped.startswith(prefix) for prefix in _SAFE_DETAIL_PREFIXES)
53
+
54
+
55
+ def strip_reservation_lines(text: str) -> str:
56
+ """Drop reservation coverage / unchecked lines from assessment text."""
57
+ kept: list[str] = []
58
+ for line in (text or "").splitlines():
59
+ if _is_reservation_line(line):
60
+ continue
61
+ kept.append(line)
62
+ return "\n".join(kept).strip()
63
+
64
+
65
+ def _banner_lines(text: str, *, keep_reservations: bool) -> list[str]:
66
+ banners: list[str] = []
67
+ for line in (text or "").splitlines():
68
+ stripped = line.strip()
69
+ if not stripped:
70
+ continue
71
+ if _is_move_line(stripped) or _is_safe_detail_line(stripped):
72
+ continue
73
+ if PRICE_ASSUMPTION in stripped:
74
+ continue
75
+ if _is_reservation_line(stripped):
76
+ if keep_reservations:
77
+ banners.append(stripped)
78
+ continue
79
+ if stripped.startswith("warning:"):
80
+ banners.append(stripped)
81
+ continue
82
+ # Provider / spot lookup lines that are not competing moves.
83
+ if stripped.startswith("Spot ") or "spot lookup" in stripped.lower():
84
+ banners.append(stripped)
85
+ return banners
86
+
87
+
88
+ def _set_text(assessment: Any, primary: str, banners: list[str]) -> None:
89
+ parts = [primary.strip()] if primary.strip() else []
90
+ parts.extend(banners)
91
+ assessment.text = "\n".join(parts).strip()
92
+
93
+
94
+ def _fleetfit_block(
95
+ *,
96
+ current: SpecRow | None,
97
+ target: SpecRow | None,
98
+ ) -> dict[str, Any]:
99
+ """Schema-valid justification for a try-first type change."""
100
+ from maproom.analyze.safe_move import PRICE_ASSUMPTION
101
+
102
+ block: dict[str, Any] = {
103
+ "effective_price": {
104
+ "price_id": "aws_ec2_ondemand_linux",
105
+ "reading": "relative_order_only",
106
+ "units": "USD/hour",
107
+ "current": "unread",
108
+ "targeted": "unread",
109
+ "assumption": PRICE_ASSUMPTION,
110
+ }
111
+ }
112
+ if (
113
+ current is not None
114
+ and target is not None
115
+ and current.cpu_performance_rank is not None
116
+ and target.cpu_performance_rank is not None
117
+ ):
118
+ block["cpu_performance_rank"] = {
119
+ "direction": "higher_is_faster",
120
+ "current": str(current.cpu_performance_rank),
121
+ "targeted": str(target.cpu_performance_rank),
122
+ }
123
+ return {"fleetfit_recommended_safe_move": block}
124
+
125
+
126
+ def _rewrite_alternatives(
127
+ assessment: Any,
128
+ *,
129
+ instance_type: str | None,
130
+ justification: dict[str, Any],
131
+ current: SpecRow | None,
132
+ specs: dict[tuple[str, str], SpecRow] | None = None,
133
+ cloud: str | None = None,
134
+ ) -> None:
135
+ if assessment.recommendation is None:
136
+ return
137
+ if not instance_type:
138
+ assessment.recommendation["recommended_alternatives"] = []
139
+ assessment.cross_family_target = None
140
+ return
141
+ alts = assessment.recommendation.get("recommended_alternatives")
142
+ if isinstance(alts, list) and alts and isinstance(alts[0], dict):
143
+ existing = dict(alts[0])
144
+ existing["instance_type"] = instance_type
145
+ just = existing.get("justification")
146
+ if not isinstance(just, dict) or "fleetfit_recommended_safe_move" not in just:
147
+ target = None
148
+ if specs is not None and cloud is not None:
149
+ target = specs.get((cloud, instance_type))
150
+ existing["justification"] = _fleetfit_block(current=current, target=target)
151
+ assessment.recommendation["recommended_alternatives"] = [existing]
152
+ else:
153
+ target = None
154
+ if specs is not None and cloud is not None:
155
+ target = specs.get((cloud, instance_type))
156
+ # Prefer a schema-valid block; callers may pass fleetfit_recommended_safe_move.
157
+ if "fleetfit_recommended_safe_move" in justification:
158
+ block = justification
159
+ else:
160
+ block = _fleetfit_block(current=current, target=target)
161
+ assessment.recommendation["recommended_alternatives"] = [
162
+ {
163
+ "rank": 1,
164
+ "instance_type": instance_type,
165
+ "justification": block,
166
+ "how_to_migrate_to_new_type": "stop_and_restart_on_new_type",
167
+ "migration_reason": None,
168
+ }
169
+ ]
170
+ if current is not None and "." in instance_type:
171
+ family = instance_type.split(".", 1)[0]
172
+ if family.strip().lower() != (current.family or "").strip().lower():
173
+ assessment.cross_family_target = instance_type
174
+ else:
175
+ assessment.cross_family_target = None
176
+ else:
177
+ assessment.cross_family_target = None
178
+
179
+
180
+ def _series_payload(row: dict[str, Any] | None) -> dict[str, Any] | None:
181
+ if not isinstance(row, dict):
182
+ return None
183
+ for key in ("utilization_metrics", "series_fit"):
184
+ payload = row.get(key)
185
+ if isinstance(payload, dict):
186
+ return payload
187
+ return None
188
+
189
+
190
+ def _promote_series(
191
+ assessment: Any,
192
+ series: dict[str, Any],
193
+ *,
194
+ item: WorkItem,
195
+ specs: dict[tuple[str, str], SpecRow],
196
+ keep_reservations: bool,
197
+ ) -> None:
198
+ detail = str(series.get("detail") or "").strip()
199
+ banners = _banner_lines(str(assessment.text or ""), keep_reservations=keep_reservations)
200
+ _set_text(assessment, detail, banners)
201
+ named = series.get("instance_type")
202
+ type_name = named.strip() if isinstance(named, str) else ""
203
+ current = specs.get((item.cloud, item.instance_type))
204
+ if series.get("passed") and type_name:
205
+ _rewrite_alternatives(
206
+ assessment,
207
+ instance_type=type_name,
208
+ justification={},
209
+ current=current,
210
+ specs=specs,
211
+ cloud=item.cloud,
212
+ )
213
+ else:
214
+ _rewrite_alternatives(
215
+ assessment,
216
+ instance_type=None,
217
+ justification={},
218
+ current=current,
219
+ )
220
+
221
+
222
+ def _promote_size(
223
+ assessment: Any,
224
+ size: dict[str, Any],
225
+ *,
226
+ item: WorkItem,
227
+ specs: dict[tuple[str, str], SpecRow],
228
+ keep_reservations: bool,
229
+ ) -> bool:
230
+ if size.get("omitted"):
231
+ return False
232
+ explanation = size.get("explanation")
233
+ display = ""
234
+ for line in str(assessment.text or "").splitlines():
235
+ stripped = line.strip()
236
+ if stripped.startswith("Move from "):
237
+ display = stripped
238
+ break
239
+ if not display:
240
+ if not isinstance(explanation, str) or not explanation.strip():
241
+ return False
242
+ if not explanation.strip().startswith("Move from "):
243
+ return False
244
+ display = explanation.strip()
245
+ banners = _banner_lines(str(assessment.text or ""), keep_reservations=keep_reservations)
246
+ _set_text(assessment, display, banners)
247
+ named = size.get("instance_type")
248
+ type_name = named.strip() if isinstance(named, str) else ""
249
+ current = specs.get((item.cloud, item.instance_type))
250
+ if type_name:
251
+ _rewrite_alternatives(
252
+ assessment,
253
+ instance_type=type_name,
254
+ justification={},
255
+ current=current,
256
+ specs=specs,
257
+ cloud=item.cloud,
258
+ )
259
+ return True
260
+
261
+
262
+ def _promote_spot(
263
+ assessment: Any,
264
+ spot: dict[str, Any],
265
+ *,
266
+ item: WorkItem,
267
+ specs: dict[tuple[str, str], SpecRow],
268
+ keep_reservations: bool,
269
+ ) -> bool:
270
+ detail = spot.get("detail") or spot.get("explanation") or spot.get("line")
271
+ if not isinstance(detail, str) or not detail.strip():
272
+ return False
273
+ named = spot.get("instance_type") or spot.get("recommended_instance_type")
274
+ type_name = named.strip() if isinstance(named, str) else ""
275
+ if not type_name and "Move" not in detail:
276
+ return False
277
+ banners = _banner_lines(str(assessment.text or ""), keep_reservations=keep_reservations)
278
+ _set_text(assessment, detail.strip(), banners)
279
+ current = specs.get((item.cloud, item.instance_type))
280
+ if type_name:
281
+ _rewrite_alternatives(
282
+ assessment,
283
+ instance_type=type_name,
284
+ justification={},
285
+ current=current,
286
+ specs=specs,
287
+ cloud=item.cloud,
288
+ )
289
+ return True
290
+
291
+
292
+ def finalize_primary_recommendation(
293
+ assessment: Any,
294
+ *,
295
+ product_version: int,
296
+ item: WorkItem,
297
+ specs: dict[tuple[str, str], SpecRow],
298
+ ) -> None:
299
+ """Make assessment.text / recommended_alternatives match product_version."""
300
+ keep_reservations = product_version >= 5
301
+ if not keep_reservations:
302
+ assessment.text = strip_reservation_lines(str(assessment.text or ""))
303
+
304
+ row = assessment.recommendation or assessment.examined
305
+ series = _series_payload(row if isinstance(row, dict) else None)
306
+ size = row.get("size_lookup") if isinstance(row, dict) else None
307
+ spot = row.get("spot_lookup") if isinstance(row, dict) else None
308
+
309
+ if product_version >= 4:
310
+ if isinstance(series, dict) and series.get("status") == "returned":
311
+ _promote_series(
312
+ assessment,
313
+ series,
314
+ item=item,
315
+ specs=specs,
316
+ keep_reservations=keep_reservations,
317
+ )
318
+ return
319
+ if product_version >= 5:
320
+ cover = row.get("reservation_cover") if isinstance(row, dict) else None
321
+ if isinstance(cover, dict) and cover.get("status") == "returned":
322
+ banners = _banner_lines(
323
+ str(assessment.text or ""), keep_reservations=True
324
+ )
325
+ chosen = cover.get("chosen_instance_type")
326
+ chosen_name = (
327
+ chosen.strip() if isinstance(chosen, str) and chosen.strip() else ""
328
+ )
329
+ primary_lines = [
330
+ line.strip()
331
+ for line in str(assessment.text or "").splitlines()
332
+ if line.strip().startswith("Move to ")
333
+ or line.strip().startswith("Stay on ")
334
+ or "->" in line.strip()
335
+ ]
336
+ if primary_lines:
337
+ _set_text(assessment, primary_lines[0], banners)
338
+ else:
339
+ assessment.text = "\n".join(
340
+ [
341
+ line
342
+ for line in str(assessment.text or "").splitlines()
343
+ if not line.strip().startswith("Move from ")
344
+ ]
345
+ ).strip()
346
+ if chosen_name:
347
+ current = specs.get((item.cloud, item.instance_type))
348
+ _rewrite_alternatives(
349
+ assessment,
350
+ instance_type=chosen_name,
351
+ justification={},
352
+ current=current,
353
+ specs=specs,
354
+ cloud=item.cloud,
355
+ )
356
+ return
357
+ # Fallback: #3 Spot-to-Spot, then #2 local size.
358
+ if isinstance(spot, dict) and _promote_spot(
359
+ assessment,
360
+ spot,
361
+ item=item,
362
+ specs=specs,
363
+ keep_reservations=keep_reservations,
364
+ ):
365
+ return
366
+ if isinstance(size, dict) and _promote_size(
367
+ assessment,
368
+ size,
369
+ item=item,
370
+ specs=specs,
371
+ keep_reservations=keep_reservations,
372
+ ):
373
+ return
374
+ # Keep safe-move text but without reservation lines / competing size lines.
375
+ banners = _banner_lines(
376
+ str(assessment.text or ""), keep_reservations=keep_reservations
377
+ )
378
+ primary_lines = [
379
+ line.strip()
380
+ for line in str(assessment.text or "").splitlines()
381
+ if line.strip().startswith("Move to ")
382
+ ]
383
+ if primary_lines:
384
+ _set_text(assessment, primary_lines[0], banners)
385
+ return
386
+
387
+ if product_version == 3:
388
+ if isinstance(spot, dict) and _promote_spot(
389
+ assessment,
390
+ spot,
391
+ item=item,
392
+ specs=specs,
393
+ keep_reservations=False,
394
+ ):
395
+ return
396
+ # Non-spot: local safe-move; drop size Move-from lines.
397
+ lines = [
398
+ line
399
+ for line in str(assessment.text or "").splitlines()
400
+ if not line.strip().startswith("Move from ")
401
+ ]
402
+ assessment.text = "\n".join(lines).strip()
403
+ return
404
+
405
+ if product_version == 2:
406
+ if isinstance(size, dict) and _promote_size(
407
+ assessment,
408
+ size,
409
+ item=item,
410
+ specs=specs,
411
+ keep_reservations=False,
412
+ ):
413
+ return
414
+ return
415
+
416
+ # v1: safe-move only; drop size Move-from if present.
417
+ lines = [
418
+ line
419
+ for line in str(assessment.text or "").splitlines()
420
+ if not line.strip().startswith("Move from ")
421
+ ]
422
+ assessment.text = "\n".join(lines).strip()