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,1194 @@
1
+ """Named stages for product version 1 analyze orchestration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextvars
6
+ import os
7
+ import sys
8
+ from dataclasses import dataclass, field
9
+ from datetime import datetime, timezone
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import maproom.analyze.safe_analyze as _v1
14
+ from maproom.analyze.safe_analyze import (
15
+ AnalyzeRunBanners,
16
+ SUCCESS,
17
+ UNCHECKED_COVERAGE,
18
+ WorkItem,
19
+ _Assessment,
20
+ _LATER_HINTS,
21
+ _OFFERED,
22
+ _coverage_warnings,
23
+ _fail,
24
+ _fail_listing,
25
+ _listing,
26
+ _price_entries,
27
+ _run_version,
28
+ _strip_human_only_analyze_row,
29
+ accept_next_product_version,
30
+ assess_item,
31
+ interactive_conclusion,
32
+ NO_RECOMMENDATION_HEADLINE,
33
+ )
34
+ from maproom.analyze.workset import RegionDescribeFailure
35
+ from maproom.cliio.runner import CliBelowFloorError
36
+ from maproom.output.json_envelope import (
37
+ build_document,
38
+ command_metadata,
39
+ error_item,
40
+ finish_consent_gate,
41
+ print_error_envelope,
42
+ print_json,
43
+ warning_item,
44
+ )
45
+ from maproom.plan.errors import PlanError
46
+ from maproom.redaction import redact_text
47
+
48
+
49
+ @dataclass
50
+ class _AnalyzeV1Context:
51
+ args: Any
52
+ now_utc: Any
53
+ spot_lookup: bool
54
+ size_lookup: bool
55
+ reservation_reorder: bool
56
+ reservation_pack: str
57
+ series_lookup: bool
58
+ quota_management: bool
59
+ shape: Any
60
+
61
+ started_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
62
+ as_json: bool = False
63
+ runner: Any = None
64
+ parsed: Any = None
65
+ cloud: str = ""
66
+ region: str | None = None
67
+ interactive: bool = False
68
+ items: list[WorkItem] = field(default_factory=list)
69
+ block_devices: dict[str, list[dict[str, Any]]] = field(default_factory=dict)
70
+ specs: dict[tuple[str, str], Any] = field(default_factory=dict)
71
+
72
+ price_run: Any = None
73
+ service_run: Any = None
74
+ spot_run: Any = None
75
+ size_run: Any = None
76
+ series_run: Any = None
77
+ quota_run: Any = None
78
+ cover_run: Any = None
79
+ cover_session: Any = None
80
+
81
+ recommendations: list[dict[str, Any]] = field(default_factory=list)
82
+ examined: list[dict[str, Any]] = field(default_factory=list)
83
+ held: list[tuple[Any, Any]] = field(default_factory=list)
84
+ safe_responses: dict[int, dict[str, Any]] = field(default_factory=dict)
85
+ errors: list[dict[str, Any]] = field(default_factory=list)
86
+ spec_counts: dict[tuple[str, str], int] = field(default_factory=dict)
87
+ offering_skips: dict[tuple[str, str], dict[str, Any]] = field(default_factory=dict)
88
+ scored: bool = False
89
+ saw_outside_quota_family: bool = False
90
+ lookup_run_banners: AnalyzeRunBanners = field(default_factory=AnalyzeRunBanners)
91
+ interactive_blocks: list[tuple[WorkItem, _Assessment]] = field(default_factory=list)
92
+ run_version: int = 1
93
+ series_will_run: bool = False
94
+ coverage_checked: bool = False
95
+ warnings: list[dict[str, Any]] = field(default_factory=list)
96
+ listing_cache_state: str = "absent"
97
+ listing_region: str | None = None
98
+ share_groups: set[str] = field(default_factory=set)
99
+ operator_context_run: Any = None
100
+ operator_context_warned: bool = False
101
+
102
+
103
+ def _recommend_sections_planned(ctx: _AnalyzeV1Context, item: WorkItem) -> int:
104
+ from maproom.analyze.size_analyze import size_applies_to
105
+ from maproom.analyze.spot_analyze import is_spot_instance
106
+
107
+ count = 0
108
+ if (
109
+ ctx.spot_run is not None
110
+ and ctx.spot_lookup
111
+ and is_spot_instance(item)
112
+ and ctx.spot_run.upload_allowed
113
+ and ctx.spot_run.destination
114
+ ):
115
+ count += 1
116
+ if (
117
+ ctx.size_run is not None
118
+ and ctx.size_lookup
119
+ and size_applies_to(item)
120
+ and ctx.size_run.upload_allowed
121
+ and ctx.size_run.destination
122
+ ):
123
+ count += 1
124
+ if (
125
+ ctx.series_run is not None
126
+ and ctx.series_lookup
127
+ and ctx.series_run.upload_allowed
128
+ and ctx.series_run.destination
129
+ ):
130
+ count += 1
131
+ if ctx.quota_run is not None and ctx.quota_management and ctx.quota_run.destination:
132
+ count += 1
133
+ if (
134
+ ctx.reservation_reorder
135
+ and ctx.cover_run is not None
136
+ and ctx.cover_run.upload_allowed
137
+ and ctx.cover_run.destination
138
+ ):
139
+ count += 1
140
+ return count
141
+
142
+
143
+ def _recommend_settings(ctx: _AnalyzeV1Context) -> dict[str, Any] | None:
144
+ if ctx.service_run is not None:
145
+ return ctx.service_run.settings
146
+ if ctx.cover_run is not None:
147
+ return ctx.cover_run.settings
148
+ if ctx.price_run is not None:
149
+ return ctx.price_run.settings
150
+ return None
151
+
152
+
153
+ def _stage_prepare_gates(ctx: _AnalyzeV1Context) -> int | None:
154
+ """Parse selectors, consent, and CLI floors before any cloud read."""
155
+ ctx.as_json = bool(getattr(ctx.args, "json", False))
156
+ parsed = _v1.parse_analyze_selectors(list(getattr(ctx.args, "selectors", None) or []))
157
+ if isinstance(parsed, PlanError):
158
+ return _fail(parsed.message, as_json=ctx.as_json, code="usage")
159
+ ctx.parsed = parsed
160
+
161
+ try:
162
+ ctx.runner = _v1.command_runner()
163
+ except _v1.MockEnvironmentError as exc:
164
+ return _fail(exc.message, as_json=ctx.as_json, code="runtime")
165
+
166
+ gate = _v1.require_cloud_read_consent(
167
+ consent_cloud_reads=bool(getattr(ctx.args, "consent_cloud_reads", False)),
168
+ quiet=ctx.as_json,
169
+ )
170
+ if not gate.allowed:
171
+ return finish_consent_gate(gate, as_json=ctx.as_json, invoked="analyze")
172
+
173
+ from maproom.analyze.recommend_share import share_groups_from_args
174
+ from maproom.settings.model import product_version as _settings_product_version
175
+
176
+ ctx.share_groups = share_groups_from_args(_settings_product_version(), ctx.args)
177
+
178
+ try:
179
+ _v1.ensure_cli_floors(runner=ctx.runner)
180
+ except CliBelowFloorError as exc:
181
+ if ctx.as_json:
182
+ return print_error_envelope(
183
+ "runtime", _v1.format_below_floor(exc), invoked="analyze"
184
+ )
185
+ return _v1.fail_cli_floor(exc, as_json=False)
186
+ except Exception as exc:
187
+ return _fail(str(exc), as_json=ctx.as_json, code="runtime")
188
+ return None
189
+
190
+
191
+ def _stage_resolve_cloud(ctx: _AnalyzeV1Context) -> int | None:
192
+ ctx.region = (getattr(ctx.args, "region", None) or "").strip() or None
193
+ logged_in = _v1.detect_logged_in_clouds(ctx.runner)
194
+ resolved = _v1.resolve_cloud(
195
+ ctx.parsed.cloud, logged_in, resource_cloud=ctx.parsed.resource_cloud
196
+ )
197
+ if isinstance(resolved, PlanError):
198
+ return _fail(
199
+ resolved.message,
200
+ as_json=ctx.as_json,
201
+ code=_v1.resolve_cloud_error_code(resolved.message),
202
+ )
203
+ ctx.cloud = resolved
204
+ return None
205
+
206
+
207
+ def _stage_list_and_filter(ctx: _AnalyzeV1Context) -> int | None:
208
+ ctx.interactive = _v1._stdout_is_interactive(as_json=ctx.as_json)
209
+ region_failures: list[RegionDescribeFailure] = []
210
+ if ctx.interactive and ctx.cloud == "aws":
211
+ _v1.print_interactive_aws_scope(
212
+ reservation_reorder=ctx.reservation_reorder,
213
+ product_version=_run_version(
214
+ spot_lookup=ctx.spot_lookup,
215
+ size_lookup=ctx.size_lookup,
216
+ reservation_reorder=ctx.reservation_reorder,
217
+ series_lookup=ctx.series_lookup,
218
+ quota_management=ctx.quota_management,
219
+ ),
220
+ )
221
+ if not ctx.interactive:
222
+ if ctx.region:
223
+ _v1.note_progress(
224
+ f"Analyze will visit every instance in {ctx.region}. "
225
+ "Optional *text argument keeps instances whose id, name, type, or region contains that text."
226
+ )
227
+ elif ctx.cloud == "aws":
228
+ _v1.note_progress(
229
+ "Analyze will visit the current AWS region. --region chooses another region."
230
+ )
231
+ else:
232
+ _v1.note_progress(
233
+ "Analyze will visit every enabled region. --region limits it to one region."
234
+ )
235
+
236
+ from maproom.analyze.local_reads import analyze_cache_refresh
237
+ from maproom.analyze.workset import AwsInstanceList
238
+ from maproom.cache.instances import fresh_listing, listing_cache_state, save_listed_instances
239
+ from maproom.settings.model import cache_max_age_hours
240
+
241
+ refresh = analyze_cache_refresh() or bool(getattr(ctx.args, "refresh", False))
242
+ max_age = 0 if refresh else cache_max_age_hours()
243
+ listed: Any = None
244
+ if max_age > 0:
245
+ region_for_cache = ctx.region
246
+ if ctx.cloud == "aws" and not region_for_cache:
247
+ from maproom.aws_region import resolve_current_aws_region
248
+
249
+ region_for_cache = resolve_current_aws_region(ctx.runner)
250
+ cached = fresh_listing(
251
+ ctx.cloud,
252
+ region_for_cache,
253
+ max_age_hours=max_age,
254
+ runner=ctx.runner,
255
+ )
256
+ if cached is not None:
257
+ cached_items, cached_devices, note = cached
258
+ print(note, file=sys.stderr)
259
+ if ctx.spot_lookup and cached_devices:
260
+ ctx.block_devices.update(cached_devices)
261
+ listed = _listing(
262
+ AwsInstanceList(
263
+ items=cached_items,
264
+ region=(region_for_cache or "").strip(),
265
+ block_devices=cached_devices,
266
+ )
267
+ )
268
+ ctx.listing_cache_state = "fresh"
269
+ ctx.listing_region = region_for_cache
270
+
271
+ if listed is None:
272
+ if max_age > 0 and ctx.listing_cache_state != "fresh":
273
+ region_for_state = ctx.listing_region or region_for_cache or ctx.region
274
+ if ctx.cloud == "aws" and not region_for_state:
275
+ from maproom.aws_region import resolve_current_aws_region
276
+
277
+ region_for_state = resolve_current_aws_region(ctx.runner)
278
+ ctx.listing_cache_state = listing_cache_state(
279
+ ctx.cloud,
280
+ region_for_state,
281
+ max_age_hours=max_age,
282
+ runner=ctx.runner,
283
+ )
284
+ ctx.listing_region = region_for_state
285
+ if ctx.cloud == "aws":
286
+ if ctx.spot_lookup:
287
+ listed = _listing(
288
+ _v1.list_aws_instances(
289
+ ctx.runner, region=ctx.region, block_devices=ctx.block_devices
290
+ )
291
+ )
292
+ else:
293
+ listed = _listing(_v1.list_aws_instances(ctx.runner, region=ctx.region))
294
+ else:
295
+ listed_azure = _v1.list_azure_instances(ctx.runner)
296
+ listed = (
297
+ listed_azure if isinstance(listed_azure, PlanError) else _listing(listed_azure)
298
+ )
299
+ if isinstance(listed, PlanError):
300
+ return _fail_listing(listed, as_json=ctx.as_json, started_at=ctx.started_at)
301
+ listed_items, region_failures, listed_region, listed_devices = listed
302
+ save_listed_instances(
303
+ ctx.cloud,
304
+ listed_items,
305
+ block_devices=ctx.block_devices if ctx.spot_lookup else listed_devices,
306
+ region=listed_region or (ctx.region or ""),
307
+ runner=ctx.runner,
308
+ )
309
+ else:
310
+ if isinstance(listed, PlanError):
311
+ return _fail_listing(listed, as_json=ctx.as_json, started_at=ctx.started_at)
312
+ listed_items, region_failures, listed_region, listed_devices = listed
313
+
314
+ items = _v1.filter_contains(listed_items, ctx.parsed.contains)
315
+ if ctx.region and ctx.cloud == "azure":
316
+ wanted = ctx.region.strip().lower()
317
+ items = [item for item in items if item.region.lower() == wanted]
318
+ if ctx.parsed.resource:
319
+ needle = ctx.parsed.resource.lower()
320
+ items = [
321
+ item
322
+ for item in items
323
+ if item.instance_id.lower() == needle or item.name.lower() == needle
324
+ ]
325
+ ctx.items = items
326
+ ctx.errors = [
327
+ error_item(
328
+ "region_not_described",
329
+ failure.message,
330
+ cloud=failure.cloud,
331
+ region=failure.region,
332
+ )
333
+ for failure in region_failures
334
+ ]
335
+ return None
336
+
337
+
338
+ def _stage_load_specs(ctx: _AnalyzeV1Context) -> int | None:
339
+ try:
340
+ ctx.specs = _v1.load_spec_rows()
341
+ except OSError as exc:
342
+ return _fail(
343
+ f"spec table could not be read: {exc.filename or exc}",
344
+ as_json=ctx.as_json,
345
+ code="runtime",
346
+ )
347
+ move_list = os.environ.get("MAPROOM_MOVE_LIST", "").strip()
348
+ if move_list and not Path(move_list).is_file():
349
+ return _fail(
350
+ f"MAPROOM_MOVE_LIST could not be read: {move_list}",
351
+ as_json=ctx.as_json,
352
+ code="runtime",
353
+ )
354
+ return None
355
+
356
+
357
+ def _stage_prepare_lookup_runs(ctx: _AnalyzeV1Context) -> None:
358
+ from maproom.settings.model import product_version as _product_version
359
+
360
+ if _product_version() == 1:
361
+ from maproom.analyze.instance_price_analyze import prepare_instance_price_run
362
+
363
+ ctx.price_run = prepare_instance_price_run(ctx.items, ctx.args, as_json=ctx.as_json)
364
+ lookup_enabled = bool(
365
+ ctx.spot_lookup
366
+ or ctx.size_lookup
367
+ or ctx.reservation_reorder
368
+ or ctx.series_lookup
369
+ or ctx.quota_management
370
+ )
371
+ if not lookup_enabled:
372
+ from maproom.analyze.operator_context import prepare_operator_context_run
373
+
374
+ ctx.operator_context_run = prepare_operator_context_run(
375
+ ctx.args,
376
+ as_json=ctx.as_json,
377
+ cloud=ctx.cloud,
378
+ )
379
+ return
380
+ from maproom.analyze.size_analyze import (
381
+ prepare_service_upload_run,
382
+ prepare_size_run_from_service,
383
+ prepare_spot_run_from_service,
384
+ )
385
+
386
+ ctx.service_run = prepare_service_upload_run(
387
+ ctx.items,
388
+ ctx.args,
389
+ as_json=ctx.as_json,
390
+ spot_enabled=ctx.spot_lookup,
391
+ size_enabled=ctx.size_lookup,
392
+ cover_enabled=ctx.reservation_reorder,
393
+ series_enabled=ctx.series_lookup,
394
+ quota_enabled=ctx.quota_management,
395
+ specs=ctx.specs,
396
+ )
397
+ if ctx.spot_lookup:
398
+ ctx.spot_run = prepare_spot_run_from_service(ctx.service_run)
399
+ if ctx.size_lookup:
400
+ ctx.size_run = prepare_size_run_from_service(ctx.service_run)
401
+ if ctx.series_lookup:
402
+ from maproom.analyze.series_analyze import prepare_series_run_from_service
403
+
404
+ ctx.series_run = prepare_series_run_from_service(ctx.service_run, ctx.shape)
405
+ if ctx.quota_management:
406
+ from maproom.analyze.quota_analyze import prepare_quota_run_from_service
407
+
408
+ ctx.quota_run = prepare_quota_run_from_service(ctx.service_run)
409
+ if ctx.reservation_reorder:
410
+ from maproom.analyze.cover_analyze import CoverSession, prepare_cover_run
411
+
412
+ ctx.cover_session = CoverSession()
413
+ ctx.cover_run = prepare_cover_run(
414
+ ctx.items,
415
+ ctx.args,
416
+ as_json=ctx.as_json,
417
+ runner=ctx.runner,
418
+ enabled=True,
419
+ service_run=ctx.service_run,
420
+ )
421
+ from maproom.analyze.operator_context import prepare_operator_context_run
422
+
423
+ ctx.operator_context_run = prepare_operator_context_run(
424
+ ctx.args,
425
+ as_json=ctx.as_json,
426
+ cloud=ctx.cloud,
427
+ )
428
+
429
+
430
+ def _stage_operator_context(ctx: _AnalyzeV1Context) -> None:
431
+ from maproom.analyze.operator_context import run_operator_context_phase
432
+ from maproom.analyze.reservation_read import read_analyze_reservation_records
433
+ from maproom.settings.model import product_version as _product_version
434
+
435
+ records = None
436
+ if ctx.cover_run is not None and ctx.cover_run.read_ok:
437
+ records = ctx.cover_run.records
438
+ elif _product_version() >= 5 and ctx.items:
439
+ aws_regions = (
440
+ {
441
+ item.region.strip()
442
+ for item in ctx.items
443
+ if item.cloud == "aws" and item.region.strip()
444
+ }
445
+ if ctx.cloud == "aws"
446
+ else set()
447
+ )
448
+ azure_regions = {
449
+ item.region.strip()
450
+ for item in ctx.items
451
+ if item.cloud == "azure" and item.region.strip()
452
+ }
453
+ if aws_regions or azure_regions:
454
+ reservation_read = read_analyze_reservation_records(
455
+ ctx.runner,
456
+ aws_regions,
457
+ azure_regions=azure_regions,
458
+ as_json=ctx.as_json,
459
+ now=ctx.started_at,
460
+ )
461
+ if reservation_read.read_ok:
462
+ records = reservation_read.records
463
+ run_operator_context_phase(ctx, reservation_records=records)
464
+
465
+
466
+ def _stage_interactive_preamble(ctx: _AnalyzeV1Context) -> None:
467
+ ctx.run_version = _run_version(
468
+ spot_lookup=ctx.spot_lookup,
469
+ size_lookup=ctx.size_lookup,
470
+ reservation_reorder=ctx.reservation_reorder,
471
+ series_lookup=ctx.series_lookup,
472
+ quota_management=ctx.quota_management,
473
+ )
474
+ ctx.series_will_run = bool(
475
+ ctx.series_run
476
+ and ctx.series_run.upload_allowed
477
+ and ctx.series_run.destination
478
+ )
479
+ if ctx.interactive and ctx.items:
480
+ if ctx.cloud == "aws":
481
+ from maproom.settings.model import product_version as _product_version
482
+
483
+ _v1.print_interactive_analyze_command_list(
484
+ cloud=ctx.cloud,
485
+ product_version=ctx.run_version,
486
+ size_lookup=ctx.size_lookup,
487
+ series_lookup=ctx.series_lookup,
488
+ account_context=_product_version() >= 3,
489
+ )
490
+ else:
491
+ regions_in_scope = tuple(
492
+ dict.fromkeys(item.region for item in ctx.items if item.region)
493
+ )
494
+ _v1.print_interactive_analyze_preambles(
495
+ cloud=ctx.cloud,
496
+ region=ctx.region,
497
+ regions_in_scope=regions_in_scope,
498
+ reservation_reorder=ctx.reservation_reorder,
499
+ product_version=ctx.run_version,
500
+ size_lookup=ctx.size_lookup,
501
+ series_lookup=ctx.series_lookup,
502
+ )
503
+ from maproom.analyze.local_reads import (
504
+ analyze_cache_refresh,
505
+ interactive_local_cloud_reads_notice,
506
+ )
507
+ from maproom.settings.model import cache_max_age_hours
508
+
509
+ max_age = cache_max_age_hours()
510
+ if not analyze_cache_refresh() and max_age > 0:
511
+ notice = interactive_local_cloud_reads_notice(
512
+ ctx.cloud,
513
+ ctx.listing_region or ctx.region,
514
+ max_age_hours=max_age,
515
+ runner=ctx.runner,
516
+ listing_state=ctx.listing_cache_state,
517
+ )
518
+ if notice:
519
+ print(notice, flush=True)
520
+ print(flush=True)
521
+ if ctx.interactive and ctx.series_will_run and not ctx.reservation_reorder:
522
+ _v1._print_active_shapes(ctx.shape)
523
+
524
+
525
+ def _stage_apply_lookups_for_item(
526
+ ctx: _AnalyzeV1Context,
527
+ item: WorkItem,
528
+ assessment: _Assessment,
529
+ *,
530
+ recommend_envelope: dict[str, Any] | None = None,
531
+ attach_only: bool = False,
532
+ skip_finalize: bool = False,
533
+ ) -> None:
534
+ if ctx.price_run is not None and not attach_only:
535
+ from maproom.analyze.instance_price_analyze import apply_instance_price_lookup
536
+
537
+ apply_instance_price_lookup(item, assessment, run=ctx.price_run, specs=ctx.specs)
538
+ if ctx.spot_run is not None:
539
+ from maproom.analyze.spot_analyze import apply_spot_lookup
540
+
541
+ apply_spot_lookup(
542
+ item,
543
+ assessment,
544
+ run=ctx.spot_run,
545
+ block_devices=ctx.block_devices,
546
+ as_json=ctx.as_json,
547
+ run_banners=ctx.lookup_run_banners,
548
+ recommend_envelope=recommend_envelope,
549
+ attach_only=attach_only,
550
+ )
551
+ if ctx.size_run is not None:
552
+ from maproom.analyze.size_analyze import apply_size_lookup
553
+
554
+ apply_size_lookup(
555
+ item,
556
+ assessment,
557
+ run=ctx.size_run,
558
+ runner=ctx.runner,
559
+ specs=ctx.specs,
560
+ as_json=ctx.as_json,
561
+ now_utc=ctx.now_utc,
562
+ run_banners=ctx.lookup_run_banners,
563
+ recommend_envelope=recommend_envelope,
564
+ attach_only=attach_only,
565
+ )
566
+ if ctx.series_run is not None:
567
+ from maproom.analyze.series_analyze import apply_series_lookup
568
+
569
+ apply_series_lookup(
570
+ item,
571
+ assessment,
572
+ run=ctx.series_run,
573
+ runner=ctx.runner,
574
+ specs=ctx.specs,
575
+ as_json=ctx.as_json,
576
+ now_utc=ctx.now_utc,
577
+ run_banners=ctx.lookup_run_banners,
578
+ recommend_envelope=recommend_envelope,
579
+ attach_only=attach_only,
580
+ )
581
+ row = assessment.recommendation or assessment.examined
582
+ if isinstance(row, dict):
583
+ from maproom.settings.model import product_version as effective_product_version
584
+
585
+ from maproom.analyze.quota_outcome_steer import apply_quota_outcome_steering
586
+
587
+ settings = ctx.series_run.settings if ctx.series_run is not None else None
588
+ apply_quota_outcome_steering(
589
+ row,
590
+ product_version=effective_product_version(),
591
+ item=item,
592
+ specs=ctx.specs,
593
+ settings=settings,
594
+ )
595
+ series = row.get("series_fit") or row.get("utilization_metrics")
596
+ if isinstance(series, dict) and series.get("passed"):
597
+ detail = str(series.get("detail") or "")
598
+ if "outside the current quota family" in detail.lower():
599
+ ctx.saw_outside_quota_family = True
600
+ if not ctx.reservation_reorder and not skip_finalize:
601
+ from maproom.analyze.primary_recommendation import finalize_primary_recommendation
602
+
603
+ finalize_primary_recommendation(
604
+ assessment,
605
+ product_version=ctx.run_version,
606
+ item=item,
607
+ specs=ctx.specs,
608
+ )
609
+
610
+
611
+ def _stage_attach_safe_moves_from_envelope(
612
+ ctx: _AnalyzeV1Context,
613
+ envelope: dict[str, Any],
614
+ item: WorkItem,
615
+ ) -> None:
616
+ if not ctx.reservation_reorder or not ctx.held:
617
+ return
618
+ idx = len(ctx.held) - 1
619
+ held_item, held_assessment = ctx.held[idx]
620
+ if held_item is not item or idx in ctx.safe_responses:
621
+ return
622
+ from maproom.analyze.recommend_client import KIND_SAFE_MOVES, RecommendError, unwrap_kind_section
623
+ from maproom.analyze.safe_moves import require_safe_moves_response
624
+
625
+ kinds = envelope.get("kinds")
626
+ if not isinstance(kinds, list) or KIND_SAFE_MOVES not in kinds:
627
+ return
628
+ try:
629
+ section = unwrap_kind_section(envelope, kind=KIND_SAFE_MOVES)
630
+ ctx.safe_responses[idx] = require_safe_moves_response(section)
631
+ except (RecommendError, ValueError) as exc:
632
+ warning = f"warning: Safe moves lookup failed: {redact_text(str(exc))}"
633
+ if ctx.as_json:
634
+ print(warning, file=sys.stderr)
635
+ held_assessment.text = (
636
+ f"{held_assessment.text}\n{warning}" if held_assessment.text else warning
637
+ )
638
+
639
+
640
+ def _stage_reservation_lookup_post(
641
+ ctx: _AnalyzeV1Context,
642
+ item: WorkItem,
643
+ assessment: _Assessment,
644
+ ) -> None:
645
+ if not ctx.reservation_reorder:
646
+ return
647
+ ctx.held.append((item, assessment))
648
+ if (
649
+ ctx.cover_run is None
650
+ or not ctx.cover_run.upload_allowed
651
+ or not ctx.cover_run.destination
652
+ or not ctx.cover_run.read_ok
653
+ ):
654
+ return
655
+ from maproom.analyze.safe_moves_client import SafeMovesLookupError, post_safe_moves
656
+ from maproom.analyze.safe_moves import (
657
+ build_reservation_context,
658
+ build_safe_moves_body,
659
+ context_is_empty,
660
+ )
661
+ from maproom.analyze.spot_analyze import is_spot_instance
662
+
663
+ on_demand = (
664
+ not is_spot_instance(item)
665
+ and str(item.lifecycle or "").strip().lower() != "spot"
666
+ )
667
+ if not (on_demand and item.instance_type.strip() and item.region.strip()):
668
+ return
669
+ reservations_travel_in_context = bool(
670
+ ctx.operator_context_run is not None and ctx.operator_context_run.context_id
671
+ )
672
+ reservation_context = None
673
+ if not reservations_travel_in_context:
674
+ reservation_context = build_reservation_context(
675
+ list(ctx.cover_run.records),
676
+ region=item.region,
677
+ provider=item.cloud,
678
+ )
679
+ if context_is_empty(reservation_context):
680
+ return
681
+ try:
682
+ body = build_safe_moves_body(
683
+ provider=item.cloud,
684
+ region=item.region,
685
+ instance=item.instance_type,
686
+ reservation_context=reservation_context,
687
+ reservations_travel_in_context=reservations_travel_in_context,
688
+ )
689
+ response = post_safe_moves(body, ctx.cover_run.settings)
690
+ if response is not None:
691
+ ctx.safe_responses[len(ctx.held) - 1] = response
692
+ except (SafeMovesLookupError, ValueError) as exc:
693
+ warning = f"warning: Safe moves lookup failed: {redact_text(str(exc))}"
694
+ if ctx.as_json:
695
+ print(warning, file=sys.stderr)
696
+ assessment.text = f"{assessment.text}\n{warning}" if assessment.text else warning
697
+
698
+
699
+ def _stage_record_assessment_outcome(
700
+ ctx: _AnalyzeV1Context,
701
+ item: WorkItem,
702
+ assessment: _Assessment,
703
+ ) -> None:
704
+ if assessment.recommendation is not None:
705
+ ctx.recommendations.append(assessment.recommendation)
706
+ ctx.scored = True
707
+ elif assessment.examined is not None:
708
+ ctx.examined.append(assessment.examined)
709
+ if assessment.scored:
710
+ ctx.scored = True
711
+ elif assessment.spec_missing:
712
+ key = (item.cloud, item.instance_type)
713
+ ctx.spec_counts[key] = ctx.spec_counts.get(key, 0) + 1
714
+ elif assessment.offerings_message is not None:
715
+ key = (item.cloud, item.region)
716
+ slot = ctx.offering_skips.setdefault(
717
+ key, {"message": assessment.offerings_message, "count": 0}
718
+ )
719
+ slot["count"] += 1
720
+
721
+
722
+ def _stage_examine_items(ctx: _AnalyzeV1Context) -> None:
723
+ from maproom.analyze.recommend_client import analyze_recommend_banners_scope
724
+
725
+ total = len(ctx.items)
726
+ use_catalog = not (
727
+ ctx.spot_lookup
728
+ or ctx.size_lookup
729
+ or ctx.reservation_reorder
730
+ or ctx.series_lookup
731
+ or ctx.quota_management
732
+ )
733
+ from maproom.analyze.recommend_client import recommend_run_context_scope
734
+
735
+ context_id = None
736
+ if ctx.operator_context_run is not None and ctx.operator_context_run.context_id:
737
+ context_id = ctx.operator_context_run.context_id
738
+ with analyze_recommend_banners_scope(ctx.lookup_run_banners):
739
+ with recommend_run_context_scope(context_id):
740
+ _stage_examine_items_loop(ctx, total, use_catalog)
741
+
742
+
743
+ def _stage_examine_items_loop(
744
+ ctx: _AnalyzeV1Context, total: int, use_catalog: bool
745
+ ) -> None:
746
+ from maproom.analyze.recommend_client import (
747
+ RecommendError,
748
+ lookup_message_is_unreachable_host,
749
+ )
750
+
751
+ for index, item in enumerate(ctx.items, start=1):
752
+ if ctx.interactive:
753
+ _v1.note_examining(item)
754
+ else:
755
+ _v1.note_progress(f"Checking {item.label()} ({index}/{total})...")
756
+ assessment = assess_item(
757
+ item,
758
+ runner=ctx.runner,
759
+ specs=ctx.specs,
760
+ use_catalog=use_catalog,
761
+ product_version=ctx.run_version,
762
+ )
763
+ settings = _recommend_settings(ctx)
764
+ planned = _recommend_sections_planned(ctx, item) if settings is not None else 0
765
+ if settings is not None and planned >= 1:
766
+ from maproom.analyze.recommend_batch import (
767
+ recommend_batch_scope,
768
+ recommend_staging_scope,
769
+ )
770
+
771
+ envelope: dict[str, Any] | None = None
772
+ batch_failed = False
773
+ batch_error: RecommendError | None = None
774
+ try:
775
+ with recommend_batch_scope(settings, flush_after_sections=planned) as batch:
776
+ with recommend_staging_scope():
777
+ _stage_apply_lookups_for_item(
778
+ ctx, item, assessment, skip_finalize=True
779
+ )
780
+ _stage_reservation_lookup_post(ctx, item, assessment)
781
+ if batch._staged_section_count:
782
+ envelope = batch.ensure_response()
783
+ except RecommendError as exc:
784
+ batch_failed = True
785
+ batch_error = exc
786
+ msg = str(exc)
787
+ unreachable = (
788
+ lookup_message_is_unreachable_host(msg)
789
+ or ctx.lookup_run_banners.recommend_unreachable_line is not None
790
+ )
791
+ if not unreachable:
792
+ warning = f"warning: recommend lookup failed: {redact_text(msg)}"
793
+ if ctx.as_json:
794
+ print(warning, file=sys.stderr)
795
+ assessment.text = (
796
+ f"{assessment.text}\n{warning}" if assessment.text else warning
797
+ )
798
+ if envelope is not None:
799
+ _stage_attach_safe_moves_from_envelope(ctx, envelope, item)
800
+ _stage_apply_lookups_for_item(
801
+ ctx,
802
+ item,
803
+ assessment,
804
+ recommend_envelope=envelope,
805
+ attach_only=True,
806
+ )
807
+ elif batch_failed:
808
+ msg = str(batch_error) if batch_error is not None else ""
809
+ if (
810
+ ctx.lookup_run_banners.recommend_unreachable_line is not None
811
+ or lookup_message_is_unreachable_host(msg)
812
+ ):
813
+ _stage_apply_lookups_for_item(ctx, item, assessment)
814
+ elif not batch_failed:
815
+ _stage_apply_lookups_for_item(ctx, item, assessment)
816
+ else:
817
+ _stage_apply_lookups_for_item(ctx, item, assessment)
818
+ _stage_reservation_lookup_post(ctx, item, assessment)
819
+ if not ctx.reservation_reorder and not ctx.as_json:
820
+ if ctx.interactive:
821
+ ctx.interactive_blocks.append((item, assessment))
822
+ else:
823
+ if index > 1:
824
+ print()
825
+ conclusion = interactive_conclusion(item, assessment.text)
826
+ row = assessment.recommendation or assessment.examined
827
+ if (
828
+ conclusion.strip() == NO_RECOMMENDATION_HEADLINE
829
+ and isinstance(row, dict)
830
+ and isinstance(row.get("size_lookup"), dict)
831
+ and row["size_lookup"].get("omitted")
832
+ ):
833
+ conclusion = ""
834
+ if conclusion.strip():
835
+ print(conclusion, flush=True)
836
+ _stage_record_assessment_outcome(ctx, item, assessment)
837
+
838
+
839
+ def _stage_collect_errors(ctx: _AnalyzeV1Context) -> None:
840
+ for (offering_cloud, offering_region), slot in ctx.offering_skips.items():
841
+ ctx.errors.append(
842
+ error_item(
843
+ "offerings_not_read",
844
+ str(slot["message"]),
845
+ cloud=offering_cloud,
846
+ region=offering_region,
847
+ skipped_instance_count=int(slot["count"]),
848
+ )
849
+ )
850
+ for (spec_cloud, instance_type), count in ctx.spec_counts.items():
851
+ ctx.errors.append(
852
+ error_item(
853
+ "spec_row_missing",
854
+ f"{instance_type} is missing from the spec table.",
855
+ cloud=spec_cloud,
856
+ instance_type=instance_type,
857
+ count=count,
858
+ )
859
+ )
860
+
861
+
862
+ def _stage_reservation_pack(ctx: _AnalyzeV1Context) -> None:
863
+ if not (ctx.reservation_reorder and ctx.cover_run is not None and ctx.cover_session is not None):
864
+ ctx.coverage_checked = bool(ctx.cover_session and ctx.cover_session.coverage_checked)
865
+ return
866
+ if ctx.safe_responses:
867
+ from maproom.analyze.safe_moves import pack_fleet
868
+
869
+ ctx.cover_session.preference = pack_fleet(
870
+ ctx.held,
871
+ records=list(ctx.cover_run.records),
872
+ specs=ctx.specs,
873
+ responses=ctx.safe_responses,
874
+ pack_method=ctx.reservation_pack,
875
+ now=ctx.now_utc() if ctx.now_utc is not None else None,
876
+ )
877
+ ctx.cover_session.coverage_checked = True
878
+ elif (
879
+ ctx.cover_run.read_ok
880
+ and ctx.cover_run.upload_allowed
881
+ and ctx.cover_run.destination
882
+ ):
883
+ ctx.cover_session.coverage_checked = True
884
+ ctx.coverage_checked = bool(ctx.cover_session and ctx.cover_session.coverage_checked)
885
+ if ctx.reservation_reorder and ctx.held:
886
+ from maproom.analyze.primary_recommendation import finalize_primary_recommendation
887
+
888
+ for held_item, held_assessment in ctx.held:
889
+ finalize_primary_recommendation(
890
+ held_assessment,
891
+ product_version=ctx.run_version,
892
+ item=held_item,
893
+ specs=ctx.specs,
894
+ )
895
+ if (
896
+ ctx.reservation_reorder
897
+ and ctx.cover_run is not None
898
+ and ctx.cover_session is not None
899
+ and not ctx.safe_responses
900
+ and ctx.cover_run.read_ok
901
+ and ctx.cover_run.upload_allowed
902
+ and ctx.cover_run.destination
903
+ ):
904
+ from maproom.analyze.cover_analyze import mark_checked_empty_coverage
905
+
906
+ mark_checked_empty_coverage([assessment for _item, assessment in ctx.held])
907
+
908
+
909
+ def _stage_tty_format(ctx: _AnalyzeV1Context) -> None:
910
+ if not ctx.as_json and not ctx.reservation_reorder and ctx.interactive and ctx.interactive_blocks:
911
+ _v1._print_interactive_results(
912
+ ctx.interactive_blocks,
913
+ product_version=ctx.run_version,
914
+ )
915
+ if not ctx.as_json and not ctx.reservation_reorder:
916
+ _v1._print_lookup_run_banners(ctx.lookup_run_banners)
917
+
918
+ if ctx.reservation_reorder and not ctx.as_json:
919
+ if ctx.interactive:
920
+ if ctx.series_will_run:
921
+ _v1._print_active_shapes(ctx.shape)
922
+ _v1._print_interactive_results(ctx.held, product_version=ctx.run_version)
923
+ _v1._print_lookup_run_banners(ctx.lookup_run_banners)
924
+ if not ctx.coverage_checked:
925
+ if ctx.cover_run is None or not ctx.cover_run.read_ok:
926
+ print(
927
+ "Reservation packing did not run: reservations could not be read."
928
+ )
929
+ elif not ctx.cover_run.upload_allowed:
930
+ reason = (ctx.service_run.upload_reason if ctx.service_run else "") or ""
931
+ if reason == "upload_missing_policy":
932
+ from maproom.analyze.fleetfit_policy import fleetfit_policy_accept_hint
933
+
934
+ print(
935
+ "Reservation packing did not run: the FleetFit handling policy "
936
+ f"is not accepted. {fleetfit_policy_accept_hint()}"
937
+ )
938
+ else:
939
+ print(
940
+ "Reservation packing did not run: the safe-moves lookup was "
941
+ "not sent."
942
+ )
943
+ elif not ctx.cover_run.destination:
944
+ print(
945
+ "Reservation packing did not run: no safe-moves destination is set."
946
+ )
947
+ else:
948
+ for held_index, (_held_item, held_assessment) in enumerate(ctx.held):
949
+ if held_index:
950
+ print()
951
+ print(
952
+ interactive_conclusion(_held_item, held_assessment.text),
953
+ flush=True,
954
+ )
955
+ _v1._print_lookup_run_banners(ctx.lookup_run_banners)
956
+
957
+
958
+ def _stage_build_warnings(ctx: _AnalyzeV1Context) -> None:
959
+ ctx.warnings = _coverage_warnings(
960
+ ctx.scored,
961
+ coverage_checked=ctx.coverage_checked,
962
+ reservations_in_scope=ctx.run_version >= 5 or ctx.reservation_reorder,
963
+ quotas_in_scope=ctx.run_version >= 6 or ctx.quota_management,
964
+ )
965
+ if ctx.reservation_reorder and ctx.cover_run is not None:
966
+ from maproom.analyze.cover_analyze import stale_inventory_notice
967
+
968
+ notice = stale_inventory_notice(ctx.cover_run)
969
+ if notice:
970
+ ctx.warnings.append(warning_item("reservation_inventory_stale", notice))
971
+ if not ctx.as_json:
972
+ if not ctx.items:
973
+ print("No instances matched.")
974
+ for warning in ctx.warnings:
975
+ message = warning["message"]
976
+ if message == UNCHECKED_COVERAGE:
977
+ continue
978
+ print(message)
979
+
980
+
981
+ def _stage_sync_quota_outcomes(ctx: _AnalyzeV1Context) -> int | None:
982
+ from maproom.settings.model import product_version as effective_product_version
983
+
984
+ version = effective_product_version()
985
+ if version < 7:
986
+ return None
987
+ from maproom.quotas.quota_request_sync import (
988
+ QuotaOutcomeRecordingRequired,
989
+ sync_terminal_quota_denials,
990
+ )
991
+
992
+ try:
993
+ sync_terminal_quota_denials(
994
+ ctx.runner,
995
+ product_version=version,
996
+ specs=ctx.specs,
997
+ )
998
+ except QuotaOutcomeRecordingRequired as exc:
999
+ return _fail(redact_text(str(exc)), as_json=ctx.as_json, code="usage")
1000
+ return None
1001
+
1002
+
1003
+ def _stage_quota_finish(ctx: _AnalyzeV1Context) -> None:
1004
+ if ctx.quota_management and ctx.quota_run is not None:
1005
+ from maproom.analyze.quota_analyze import finish_quota_management
1006
+ from maproom.settings.model import product_version as effective_product_version
1007
+
1008
+ finish_quota_management(
1009
+ ctx.recommendations + ctx.examined,
1010
+ run=ctx.quota_run,
1011
+ runner=ctx.runner,
1012
+ specs=ctx.specs,
1013
+ as_json=ctx.as_json,
1014
+ product_version=effective_product_version(),
1015
+ )
1016
+
1017
+
1018
+ def _stage_interactive_hints(ctx: _AnalyzeV1Context) -> int | None:
1019
+ if (
1020
+ not ctx.as_json
1021
+ and ctx.interactive
1022
+ and ctx.items
1023
+ and ctx.saw_outside_quota_family
1024
+ and _run_version(
1025
+ spot_lookup=ctx.spot_lookup,
1026
+ size_lookup=ctx.size_lookup,
1027
+ reservation_reorder=ctx.reservation_reorder,
1028
+ series_lookup=ctx.series_lookup,
1029
+ quota_management=ctx.quota_management,
1030
+ )
1031
+ in (4, 5)
1032
+ ):
1033
+ hint = _LATER_HINTS.get(5)
1034
+ if hint:
1035
+ print()
1036
+ print(hint)
1037
+ if not ctx.as_json and ctx.interactive and ctx.items:
1038
+ chosen = accept_next_product_version(
1039
+ _run_version(
1040
+ spot_lookup=ctx.spot_lookup,
1041
+ size_lookup=ctx.size_lookup,
1042
+ reservation_reorder=ctx.reservation_reorder,
1043
+ series_lookup=ctx.series_lookup,
1044
+ quota_management=ctx.quota_management,
1045
+ ),
1046
+ ctx.items,
1047
+ )
1048
+ if chosen is not None:
1049
+ ctx.args.consent_fleetfit_recommendations = True
1050
+ return cmd_analyze_v1(
1051
+ ctx.args,
1052
+ now_utc=ctx.now_utc,
1053
+ reservation_pack=ctx.reservation_pack,
1054
+ shape=ctx.shape,
1055
+ spot_lookup=chosen >= 3,
1056
+ size_lookup=chosen >= 2,
1057
+ reservation_reorder=chosen >= 5,
1058
+ series_lookup=chosen >= 4,
1059
+ quota_management=chosen >= 6,
1060
+ )
1061
+ return None
1062
+
1063
+
1064
+ def _stage_emit_json_document(ctx: _AnalyzeV1Context) -> None:
1065
+ if not ctx.as_json:
1066
+ return
1067
+ end = ctx.now_utc() if ctx.now_utc is not None else None
1068
+ payload: dict[str, Any] = {
1069
+ "finish": "partial" if ctx.errors else "complete",
1070
+ "recommendations": [
1071
+ _strip_human_only_analyze_row(row) for row in ctx.recommendations
1072
+ ],
1073
+ "info": {
1074
+ "examined": [_strip_human_only_analyze_row(row) for row in ctx.examined]
1075
+ },
1076
+ }
1077
+ if ctx.cover_session and ctx.cover_session.preference is not None:
1078
+ payload["info"]["reservation_packing"] = ctx.cover_session.preference
1079
+ if ctx.operator_context_run is not None and ctx.operator_context_run.context_id:
1080
+ payload["info"]["operator_context_id"] = ctx.operator_context_run.context_id
1081
+ elif ctx.operator_context_run is not None and ctx.operator_context_run.attempted:
1082
+ payload["info"]["operator_context_id"] = None
1083
+ if ctx.cover_run is not None and ctx.cover_run.read_ok:
1084
+ reservation_meta: dict[str, Any] = {}
1085
+ if ctx.cover_run.loaded_as_of:
1086
+ reservation_meta["loaded_as_of"] = ctx.cover_run.loaded_as_of
1087
+ if ctx.cover_run.inventory_stale:
1088
+ reservation_meta["inventory_stale"] = True
1089
+ if ctx.cover_run.used_snapshot:
1090
+ reservation_meta["used_snapshot"] = True
1091
+ if reservation_meta:
1092
+ payload["info"]["reservation_inventory"] = reservation_meta
1093
+ document = build_document(
1094
+ schema_type="analyze_results",
1095
+ schema_id="maproom.analyze",
1096
+ metadata=command_metadata(
1097
+ "analyze",
1098
+ started_at=ctx.started_at,
1099
+ now=end,
1100
+ extra={"prices": _price_entries(ctx.cloud, ctx.items)},
1101
+ ),
1102
+ errors=ctx.errors,
1103
+ warnings=ctx.warnings,
1104
+ payload=payload,
1105
+ )
1106
+ print_json(document)
1107
+
1108
+
1109
+ def cmd_analyze_v1(
1110
+ args: Any,
1111
+ *,
1112
+ now_utc: Any = None,
1113
+ spot_lookup: bool = False,
1114
+ size_lookup: bool = False,
1115
+ reservation_reorder: bool = False,
1116
+ reservation_pack: str = "fill",
1117
+ series_lookup: bool = False,
1118
+ quota_management: bool = False,
1119
+ shape: Any = None,
1120
+ ) -> int:
1121
+ """List instances and name one try-first recommendation.
1122
+
1123
+ Product version 2 enables ``size_lookup``. Version 3 enables
1124
+ ``spot_lookup``. Version 4 enables ``series_lookup`` (cross-family Analyze).
1125
+ Version 5 adds ``reservation_reorder``. Version 6 adds ``quota_management``.
1126
+ Version 7 consults the quota-request outcome ledger when steering series fit.
1127
+ With no ``shape``, every attribute except burstable may change on series;
1128
+ burstable stays fixed unless the shape names ``modify_burstable``.
1129
+ A ``shape``
1130
+ limits the lookup to the attributes the operator named.
1131
+ """
1132
+ from maproom.analyze.local_reads import (
1133
+ begin_analyze_cache_account,
1134
+ begin_analyze_cache_hit_tracking,
1135
+ reset_analyze_cache_account,
1136
+ reset_analyze_cache_hit_tracking,
1137
+ reset_analyze_cache_refresh,
1138
+ set_analyze_cache_refresh,
1139
+ )
1140
+
1141
+ _OFFERED.clear()
1142
+ refresh = bool(getattr(args, "refresh", False))
1143
+ refresh_token = set_analyze_cache_refresh(refresh)
1144
+ hit_token = begin_analyze_cache_hit_tracking()
1145
+ account_token: contextvars.Token[Any] | None = None
1146
+ try:
1147
+ ctx = _AnalyzeV1Context(
1148
+ args=args,
1149
+ now_utc=now_utc,
1150
+ spot_lookup=spot_lookup,
1151
+ size_lookup=size_lookup,
1152
+ reservation_reorder=reservation_reorder,
1153
+ reservation_pack=reservation_pack,
1154
+ series_lookup=series_lookup,
1155
+ quota_management=quota_management,
1156
+ shape=shape,
1157
+ started_at=datetime.now(timezone.utc),
1158
+ )
1159
+
1160
+ for stage in (
1161
+ _stage_prepare_gates,
1162
+ _stage_resolve_cloud,
1163
+ _stage_list_and_filter,
1164
+ _stage_load_specs,
1165
+ ):
1166
+ code = stage(ctx)
1167
+ if code is not None:
1168
+ return code
1169
+ if account_token is None and getattr(ctx, "cloud", None):
1170
+ account_token = begin_analyze_cache_account(ctx.cloud, ctx.runner)
1171
+
1172
+ _stage_prepare_lookup_runs(ctx)
1173
+ _stage_interactive_preamble(ctx)
1174
+ _stage_operator_context(ctx)
1175
+ quota_sync = _stage_sync_quota_outcomes(ctx)
1176
+ if quota_sync is not None:
1177
+ return quota_sync
1178
+ _stage_examine_items(ctx)
1179
+ _stage_collect_errors(ctx)
1180
+ _stage_reservation_pack(ctx)
1181
+ _stage_tty_format(ctx)
1182
+ _stage_build_warnings(ctx)
1183
+ _stage_quota_finish(ctx)
1184
+ relaunch = _stage_interactive_hints(ctx)
1185
+ if relaunch is not None:
1186
+ return relaunch
1187
+ _stage_emit_json_document(ctx)
1188
+ ctx.block_devices.clear()
1189
+ return SUCCESS
1190
+ finally:
1191
+ if account_token is not None:
1192
+ reset_analyze_cache_account(account_token)
1193
+ reset_analyze_cache_hit_tracking(hit_token)
1194
+ reset_analyze_cache_refresh(refresh_token)