infixspeed-cli 0.0.16__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 (85) hide show
  1. infix_cli/__init__.py +5 -0
  2. infix_cli/__main__.py +6 -0
  3. infix_cli/agent-guide.txt +71 -0
  4. infix_cli/cli_framework.py +96 -0
  5. infix_cli/command_contract.py +157 -0
  6. infix_cli/commands/__init__.py +1 -0
  7. infix_cli/commands/_artifacts.py +142 -0
  8. infix_cli/commands/_comparison.py +443 -0
  9. infix_cli/commands/_confirm.py +26 -0
  10. infix_cli/commands/_control.py +290 -0
  11. infix_cli/commands/_create.py +351 -0
  12. infix_cli/commands/_create_output.py +139 -0
  13. infix_cli/commands/_delete.py +288 -0
  14. infix_cli/commands/_download.py +459 -0
  15. infix_cli/commands/_fusion_common.py +191 -0
  16. infix_cli/commands/_fusion_config.py +394 -0
  17. infix_cli/commands/_fusion_feedback.py +319 -0
  18. infix_cli/commands/_fusion_tasks.py +507 -0
  19. infix_cli/commands/_fusion_tensorboard.py +132 -0
  20. infix_cli/commands/_jobs.py +312 -0
  21. infix_cli/commands/_logs.py +210 -0
  22. infix_cli/commands/_publish.py +123 -0
  23. infix_cli/commands/_register.py +600 -0
  24. infix_cli/commands/_register_output.py +231 -0
  25. infix_cli/commands/_storage_tree.py +62 -0
  26. infix_cli/commands/admin.py +668 -0
  27. infix_cli/commands/asset.py +2012 -0
  28. infix_cli/commands/auth.py +246 -0
  29. infix_cli/commands/deploy.py +850 -0
  30. infix_cli/commands/evaluation.py +360 -0
  31. infix_cli/commands/examples.py +138 -0
  32. infix_cli/commands/fusion.py +1842 -0
  33. infix_cli/commands/merge.py +709 -0
  34. infix_cli/commands/resource.py +127 -0
  35. infix_cli/commands/spark.py +347 -0
  36. infix_cli/commands/storage.py +329 -0
  37. infix_cli/commands/training.py +748 -0
  38. infix_cli/config.py +311 -0
  39. infix_cli/config_input.py +217 -0
  40. infix_cli/context.py +84 -0
  41. infix_cli/discovery.py +459 -0
  42. infix_cli/domain/__init__.py +1 -0
  43. infix_cli/domain/dto/__init__.py +6 -0
  44. infix_cli/domain/dto/admin.py +413 -0
  45. infix_cli/domain/dto/asset.py +390 -0
  46. infix_cli/domain/dto/common.py +136 -0
  47. infix_cli/domain/dto/evaluation.py +296 -0
  48. infix_cli/domain/dto/logs.py +98 -0
  49. infix_cli/domain/dto/resource.py +108 -0
  50. infix_cli/domain/dto/serving.py +156 -0
  51. infix_cli/domain/dto/spark.py +241 -0
  52. infix_cli/domain/dto/storage.py +75 -0
  53. infix_cli/domain/dto/training.py +272 -0
  54. infix_cli/domain/enums.py +359 -0
  55. infix_cli/domain/hyperparams.py +190 -0
  56. infix_cli/domain/refs.py +108 -0
  57. infix_cli/domain/resolve.py +619 -0
  58. infix_cli/errors.py +158 -0
  59. infix_cli/example_data/__init__.py +1 -0
  60. infix_cli/example_data/fusion/README.md +128 -0
  61. infix_cli/example_data/fusion/fusion.json +149 -0
  62. infix_cli/example_data/fusion/prompts/code.jsonl +16 -0
  63. infix_cli/example_data/fusion/prompts/math.jsonl +16 -0
  64. infix_cli/example_data/fusion.zip +0 -0
  65. infix_cli/example_data/merge/README.md +89 -0
  66. infix_cli/example_data/merge/merge.json +26 -0
  67. infix_cli/example_data/merge.zip +0 -0
  68. infix_cli/http/__init__.py +1 -0
  69. infix_cli/http/browser_auth.py +160 -0
  70. infix_cli/http/client.py +575 -0
  71. infix_cli/http/pagination.py +84 -0
  72. infix_cli/http/upload.py +254 -0
  73. infix_cli/main.py +432 -0
  74. infix_cli/pipeline_config_schema.py +122 -0
  75. infix_cli/render/__init__.py +79 -0
  76. infix_cli/render/json_out.py +123 -0
  77. infix_cli/render/progress.py +62 -0
  78. infix_cli/render/text.py +233 -0
  79. infix_cli/update_check.py +177 -0
  80. infix_cli/waiter.py +93 -0
  81. infix_cli/workspace.py +158 -0
  82. infixspeed_cli-0.0.16.dist-info/METADATA +58 -0
  83. infixspeed_cli-0.0.16.dist-info/RECORD +85 -0
  84. infixspeed_cli-0.0.16.dist-info/WHEEL +4 -0
  85. infixspeed_cli-0.0.16.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,507 @@
1
+ """两个模型模块共用任务查询、执行意图、日志和独立副本登记。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import deque
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ from types import SimpleNamespace
10
+
11
+ import typer
12
+
13
+ from infix_cli import render
14
+ from infix_cli.commands import _confirm, _control
15
+ from infix_cli.commands._fusion_common import (
16
+ finish_execution,
17
+ output,
18
+ request_key,
19
+ run_number,
20
+ segment,
21
+ wait_execution,
22
+ )
23
+ from infix_cli.errors import ApiError, CliError, UsageError
24
+ from infix_cli.waiter import parse_timeout, wait_until_terminal
25
+
26
+ PATH = "/fusion-tasks"
27
+
28
+
29
+ def details(client, name, kind, *, run=None, stage=None):
30
+ value = client.get(
31
+ f"{PATH}/{segment(name)}/details",
32
+ params={"run": run_number(run), "stage": stage},
33
+ )
34
+ if value["summary"]["type"] != kind:
35
+ raise UsageError(
36
+ f"This task belongs to {value['summary']['type']}; use that module."
37
+ )
38
+ return value
39
+
40
+
41
+ def require_idle(value):
42
+ summary = value["summary"]
43
+ execution = value.get("execution") or summary.get("current_execution") or {}
44
+ if (
45
+ summary.get("active_run_id")
46
+ or execution.get("status") in {"queued", "running"}
47
+ or summary.get("control_pending")
48
+ ):
49
+ raise UsageError(
50
+ "A stage, pipeline, or cleanup is still active. Wait for it to finish or stop the task first."
51
+ )
52
+
53
+
54
+ def execution_output(run, client, task, kind, payload, *, waited=False):
55
+ from infix_cli.commands._fusion_feedback import execution_feedback
56
+
57
+ execution = payload.get("execution") or {}
58
+ if waited and "details" not in payload and (
59
+ (run.output != "json" and not run.quiet)
60
+ or execution.get("status") in {"failed", "stopped"}
61
+ ):
62
+ try:
63
+ payload["details"] = details(client, task, kind, run=str(execution["number"]))
64
+ except ApiError:
65
+ render.note(run, "Stage summary is unavailable; inspect the task again with get.")
66
+ if run.output == "json" or run.quiet:
67
+ output(run, payload)
68
+ execution_feedback(run, payload, kind=kind, task=task)
69
+ if waited:
70
+ finish_execution(execution, details=payload.get("details"), hint=f"infix {kind} logs {task}")
71
+
72
+
73
+ def create(
74
+ run,
75
+ kind,
76
+ document,
77
+ *,
78
+ name,
79
+ visibility="private",
80
+ description=None,
81
+ output_name=None,
82
+ reference_labels=None,
83
+ dry_run=False,
84
+ wait=False,
85
+ timeout=None,
86
+ ):
87
+ if not isinstance(name, str) or not name.strip():
88
+ raise UsageError("Provide a task name through configuration or --name.")
89
+ if name != name.strip() or len(name) > 200:
90
+ raise UsageError(
91
+ "Task name must be at most 200 characters without leading or trailing whitespace."
92
+ )
93
+ if not isinstance(visibility, str) or visibility not in {"private", "public"}:
94
+ raise UsageError("visibility must be private/public.")
95
+ if description is not None and (
96
+ not isinstance(description, str) or len(description) > 10000
97
+ ):
98
+ raise UsageError("description must be a string of at most 10000 characters.")
99
+ if output_name is not None and (
100
+ not isinstance(output_name, str)
101
+ or not output_name.strip()
102
+ or len(output_name) > 200
103
+ ):
104
+ raise UsageError("output-name must be a string of 1–200 characters.")
105
+ parse_timeout(timeout)
106
+ client = run.client()
107
+ preview = client.post(
108
+ "/fusion/pipeline-preview",
109
+ json={"task_type": kind, "config": document, "name": name},
110
+ )
111
+ if dry_run:
112
+ output(
113
+ run, {
114
+ "name": name, "dry_run": True, "plan": preview, "config": document,
115
+ **({"description": description} if description is not None else {}),
116
+ **({"reference_labels": reference_labels} if reference_labels else {}),
117
+ }
118
+ )
119
+ return
120
+ task = client.post(
121
+ PATH,
122
+ json={
123
+ "type": kind,
124
+ "name": name,
125
+ "visibility": visibility,
126
+ "description": description,
127
+ "output_name": output_name,
128
+ },
129
+ )
130
+ try:
131
+ revision = client.post(
132
+ f"{PATH}/{segment(task['id'])}/config-revisions",
133
+ json={"expected_revision": 0, "config": document},
134
+ )
135
+ prepared = client.post(
136
+ f"{PATH}/{segment(task['id'])}/executions/prepare",
137
+ json={"config_revision": revision["revision"], "request_key": request_key()},
138
+ )
139
+ execution = client.post(
140
+ f"{PATH}/{segment(task['id'])}/executions/{segment(prepared['id'])}/start"
141
+ )
142
+ except CliError as exc:
143
+ exc.details = {"task_id": task["id"], "name": name, "cause": exc.details}
144
+ exc.hint = f"Inspect infix {kind} get {task['id']} before retrying; the task was already created."
145
+ raise
146
+ if wait:
147
+ execution = wait_execution(run, client, task["id"], execution, timeout=timeout, kind=kind)
148
+ result = {
149
+ "name": name,
150
+ "id": task["id"],
151
+ "status": execution["status"],
152
+ "execution": execution,
153
+ "output_name": task.get("output_name"),
154
+ }
155
+ if wait:
156
+ result["details"] = details(
157
+ client, task["id"], kind, run=str(execution["number"])
158
+ )
159
+ execution_output(run, client, task["id"], kind, result, waited=wait)
160
+
161
+
162
+ def listing(run, kind, **params):
163
+ value = run.client().get(PATH, params={"type": kind, **params})
164
+ if run.output == "json":
165
+ output(run, value)
166
+ elif run.quiet:
167
+ for row in value["items"]:
168
+ print(row["name"])
169
+ else:
170
+ columns = [("NAME", "name"), ("STATUS", "status"), ("STAGE", "stage")]
171
+ if kind == "fusion":
172
+ columns += [
173
+ ("STUDENT", "student_label"),
174
+ ("TEACHERS", "teacher_count"),
175
+ ("PROGRESS", "progress_label"),
176
+ ]
177
+ else:
178
+ columns += [("METHOD", "method")]
179
+ columns += [("ELAPSED", "elapsed_label"), ("CREATOR", "creator_id")]
180
+ items = []
181
+ for row in value["items"]:
182
+ model, progress = row.get("student") or {}, row.get("stage_progress") or {}
183
+ items.append(
184
+ SimpleNamespace(
185
+ **{
186
+ **row,
187
+ "student_label": model.get("asset")
188
+ or model.get("snapshot")
189
+ or model.get("path")
190
+ or "—",
191
+ "teacher_count": row.get("teacher_count", 0),
192
+ "progress_label": f"{progress.get('completed_count', len(progress.get('current_successes', [])))} done, {progress.get('skipped_count', 0)} skipped, {progress.get('pending_count', 0)} pending",
193
+ "elapsed_label": f"{row['elapsed_seconds']:.1f}s"
194
+ if row.get("elapsed_seconds") is not None
195
+ else "—",
196
+ }
197
+ )
198
+ )
199
+ render.render_list(
200
+ run,
201
+ items,
202
+ columns,
203
+ page=value["page"],
204
+ page_size=value["page_size"],
205
+ total=value["total"],
206
+ )
207
+
208
+
209
+ def get(run, kind, name, *, number=None, stage=None):
210
+ value = details(run.client(), name, kind, run=number, stage=stage)
211
+ if number is None and value.get("execution") is None:
212
+ current_execution = value["summary"].get("current_execution")
213
+ if current_execution is not None:
214
+ value["execution"] = current_execution
215
+ if run.output == "json" or run.quiet:
216
+ output(run, value, quiet_value=value["summary"]["name"])
217
+ else:
218
+ output(run, value["summary"])
219
+ for slot in value["stages"]:
220
+ item = slot.get("run") or {}
221
+ render.render_object(
222
+ run,
223
+ slot,
224
+ [
225
+ (slot["stage_type"], slot["status"]),
226
+ ("StageRun", str(slot.get("stage_run_id") or "—")),
227
+ ("Outputs", str(item.get("outputs") or "—")),
228
+ (
229
+ "Resources",
230
+ str(item.get("resource_plan") or item.get("resources") or "—"),
231
+ ),
232
+ ("Parameters", str(item.get("params") or "—")),
233
+ ("Summary", str(item.get("summary") or "—")),
234
+ ("Error", str(item.get("error_message") or "—")),
235
+ ],
236
+ )
237
+ for record in value.get("registrations", []):
238
+ render.render_object(run, record, [
239
+ ("Registered model", str(record.get("asset_name") or record["asset_id"])),
240
+ ("Asset ID", record["asset_id"]), ("Version ID", record["version_id"]),
241
+ ("Version", str(record.get("version_number") or "—")),
242
+ ("Registration status", record["status"]),
243
+ ("Asset status", str(record.get("asset_version_status") or "—")),
244
+ ("Source StageRun", record["stage_run_id"]),
245
+ ("Logical run", str(record.get("execution_number") or "—")),
246
+ ("Checkpoint", str(record.get("checkpoint") or "—")),
247
+ ("Registered at", str(record.get("created_at") or "—")),
248
+ ("Error", str(record.get("error_message") or "—")),
249
+ ])
250
+ if value.get("registrations_truncated"):
251
+ render.note(run, "Showing the latest 100 registrations. Use --run or --stage to narrow the results.")
252
+
253
+
254
+ def stop(run, kind, name):
255
+ details(run.client(), name, kind)
256
+ output(run, run.client().post(f"{PATH}/{segment(name)}/stop"), quiet_value=name)
257
+
258
+
259
+ def share(run, kind, name, *, yes=False):
260
+ value = details(run.client(), name, kind)
261
+ _confirm.require(
262
+ run,
263
+ title="Share task information permanently within this workspace",
264
+ rows=[
265
+ ("Task", value["summary"]["name"]),
266
+ ("Inputs and outputs", "Keep their existing access permissions"),
267
+ ],
268
+ yes=yes,
269
+ flag="--yes",
270
+ )
271
+ output(
272
+ run,
273
+ run.client().post(f"{PATH}/{segment(name)}/share", json={"confirmed": True}),
274
+ quiet_value=name,
275
+ )
276
+
277
+
278
+ def delete(run, kind, name, *, force=False, purge=False):
279
+ value = details(run.client(), name, kind)
280
+ rows = [("Task", value["summary"]["name"])]
281
+ if purge:
282
+ preview = run.client().get(f"{PATH}/{segment(name)}/purge-preview")
283
+ if not preview["can_purge"]:
284
+ raise UsageError(
285
+ "Outputs are still referenced. Release the references shown by purge-preview before deleting."
286
+ )
287
+ rows += [
288
+ (item["path"], str(item["size_bytes"]) + " bytes (estimate)")
289
+ for item in preview["paths"]
290
+ ]
291
+ _confirm.require(
292
+ run,
293
+ title="Delete task and preserve all run files"
294
+ if not purge
295
+ else "Delete task and permanently purge its run files",
296
+ rows=rows,
297
+ yes=force,
298
+ flag="--force",
299
+ )
300
+ output(
301
+ run,
302
+ run.client().delete(f"{PATH}/{segment(name)}", params={"purge": purge}),
303
+ quiet_value=name,
304
+ )
305
+
306
+
307
+ def clone(run, kind, name, *, new_name=None, save=None, number=None):
308
+ details(run.client(), name, kind, run=number)
309
+ value = run.client().get(
310
+ f"{PATH}/{segment(name)}/config/export",
311
+ params={"view": "effective", "run": run_number(number)},
312
+ )
313
+ config = {
314
+ **value["config"],
315
+ "name": new_name or value["name"] + "-copy",
316
+ "visibility": "private",
317
+ }
318
+ for issue in value.get("unresolved", []):
319
+ render.note(run, issue["field"] + ": " + issue["reason"])
320
+ if save is None and run.output != "json" and not run.quiet:
321
+ filename = config["name"]
322
+ if Path(filename).name != filename or "\\" in filename or filename in {".", ".."} or any(ord(char) < 32 for char in filename):
323
+ raise UsageError("The task name cannot be used as a local filename. Specify --save or --output json.")
324
+ save = filename + ".json"
325
+ if save:
326
+ target = Path(save).expanduser()
327
+ try:
328
+ with target.open("x", encoding="utf-8") as stream:
329
+ json.dump(config, stream, indent=2, ensure_ascii=False)
330
+ stream.write("\n")
331
+ except FileExistsError as exc:
332
+ raise UsageError("The configuration file exists. Choose a different --save path.") from exc
333
+ except OSError as exc:
334
+ raise UsageError("Cannot write the configuration file. Check the destination path.") from exc
335
+ if run.output == "json":
336
+ output(run, config)
337
+ elif run.quiet:
338
+ print(str(target))
339
+ else:
340
+ from infix_cli.commands._fusion_feedback import command
341
+ action = "run" if kind == "fusion" else "create"
342
+ render.message(run, f"Wrote {target}. Next: " + command("infix", kind, action, "--config", target))
343
+ return
344
+ _control.emit_clone(run, config, save=save, module=kind)
345
+
346
+
347
+ def register(
348
+ run,
349
+ kind,
350
+ task,
351
+ *,
352
+ name,
353
+ checkpoint=None,
354
+ number=None,
355
+ version="v1.0.0",
356
+ tags=None,
357
+ description=None,
358
+ visibility="private",
359
+ wait=False,
360
+ timeout=None,
361
+ ):
362
+ if kind == "fusion" and not checkpoint:
363
+ raise UsageError("Fusion registration requires --checkpoint.")
364
+ if kind == "merge" and (checkpoint is not None or number is not None):
365
+ raise UsageError("Merge registration does not accept checkpoint/run selection.")
366
+ seconds = parse_timeout(timeout)
367
+ client = run.client()
368
+ details(client, task, kind, run=number)
369
+ value = client.post(
370
+ f"{PATH}/{segment(task)}/registrations",
371
+ json={
372
+ "request_key": request_key(),
373
+ "name": name,
374
+ "checkpoint": checkpoint,
375
+ "run": run_number(number),
376
+ "version": version,
377
+ "tags": tags or [],
378
+ "description": description,
379
+ "visibility": visibility,
380
+ },
381
+ )
382
+ if wait:
383
+ path = f"{PATH}/{segment(task)}/registrations/{segment(value['version_id'])}"
384
+
385
+ def fetch():
386
+ current = client.get(path)
387
+ return current["status"], current
388
+
389
+ _, value = wait_until_terminal(
390
+ fetch,
391
+ terminal=frozenset({"ready", "failed", "canceled", "cancelled"}),
392
+ ctx=run,
393
+ timeout=seconds,
394
+ label="Model registration",
395
+ recheck_hint=f"infix {kind} get {task}",
396
+ )
397
+ output(run, value, quiet_value=value["version_id"])
398
+ if wait and value["status"] != "ready":
399
+ raise typer.Exit(1)
400
+
401
+
402
+ def logs(
403
+ run,
404
+ kind,
405
+ task,
406
+ *,
407
+ stage=None,
408
+ number=None,
409
+ teacher=None,
410
+ worker=None,
411
+ tail=500,
412
+ follow=False,
413
+ keyword=None,
414
+ download=False,
415
+ save=None,
416
+ ):
417
+ if download and follow:
418
+ raise UsageError("--download and --follow are mutually exclusive.")
419
+ if save and not download:
420
+ raise UsageError("--save requires --download.")
421
+ client = run.client()
422
+ details(client, task, kind, run=number, stage=stage)
423
+ params = {
424
+ "stage": stage,
425
+ "run": run_number(number),
426
+ "teacher": teacher,
427
+ "worker": worker,
428
+ "tail": tail,
429
+ "keyword": keyword,
430
+ }
431
+ path = f"{PATH}/{segment(task)}/logs"
432
+ if download:
433
+ target = Path(save or f"{kind}-logs.zip")
434
+ if target.exists():
435
+ raise UsageError(
436
+ "The download destination exists. Choose a different --save path."
437
+ )
438
+ partial = target.with_name(target.name + ".part")
439
+ try:
440
+ with partial.open("xb") as stream:
441
+ size = client.download(path + "/download", stream, params=params)
442
+ # 同目录原子发布;校验后出现的同名文件也不能被覆盖。
443
+ os.link(partial, target)
444
+ partial.unlink()
445
+ except OSError as exc:
446
+ raise UsageError(
447
+ "Cannot write the log archive. Check the destination path."
448
+ ) from exc
449
+ output(run, {"path": str(target), "bytes": size}, quiet_value=str(target))
450
+ return
451
+ if not follow:
452
+ value = client.get(path, params=params)
453
+ if value.get("history_limited"):
454
+ render.note(run, "Log history is limited by the retention window.")
455
+ if value.get("truncated"):
456
+ render.note(
457
+ run, "Logs were truncated; narrow the filters or download the archive."
458
+ )
459
+ if run.output == "json":
460
+ output(run, value)
461
+ else:
462
+ for line in value["items"]:
463
+ print(line["timestamp"] + " " + line["message"])
464
+ return
465
+ # 首次固定实际执行身份,连接期限到达后的重连不会切到新 run。
466
+ source = client.get(
467
+ path + "/sources",
468
+ params={key: value for key, value in params.items() if key != "tail"},
469
+ )
470
+ if params["run"] is None and source.get("execution_number") is not None:
471
+ params["run"] = source["execution_number"]
472
+ elif params["run"] is None and len(source.get("run_ids", [])) == 1:
473
+ params["stage_run_id"] = source["run_ids"][0]
474
+ if not source.get("run_ids"):
475
+ output(run, source)
476
+ return
477
+ seen = set()
478
+ recent = deque()
479
+ while True:
480
+ event, event_id = "message", None
481
+ done = None
482
+ for line in client.stream_lines("GET", path + "/stream", params=params):
483
+ if line.startswith("event:"):
484
+ event = line[6:].strip()
485
+ elif line.startswith("id:"):
486
+ event_id = line[3:].strip()
487
+ elif line.startswith("data:"):
488
+ value = json.loads(line[5:].strip())
489
+ if event == "error":
490
+ raise ApiError(value.get("message") or "Log streaming failed.")
491
+ if event == "done":
492
+ done = value
493
+ if event != "log" or event_id in seen:
494
+ continue
495
+ if event_id:
496
+ seen.add(event_id)
497
+ recent.append(event_id)
498
+ if len(recent) > 10000:
499
+ seen.discard(recent.popleft())
500
+ if run.output == "json":
501
+ print(json.dumps(value, ensure_ascii=False))
502
+ else:
503
+ print(value["timestamp"] + " " + value["message"])
504
+ if done is None:
505
+ raise ApiError("Log connection interrupted. Follow the same run again.")
506
+ if done.get("reason") != "time_limit":
507
+ return
@@ -0,0 +1,132 @@
1
+ """按精确历史阶段启动平台已有的按需 TensorBoard 会话。"""
2
+
3
+ from urllib.parse import urljoin
4
+
5
+ import typer
6
+
7
+ from infix_cli.commands import _fusion_tasks as tasks
8
+ from infix_cli.commands._fusion_common import output, run_number, segment
9
+ from infix_cli.commands._fusion_config import stage_name
10
+ from infix_cli.errors import UsageError
11
+ from infix_cli.waiter import parse_timeout, wait_until_terminal
12
+
13
+
14
+ def tensorboard(
15
+ ctx: typer.Context,
16
+ name: str = typer.Argument(
17
+ ..., help="Fusion task name or ID in the current workspace."
18
+ ),
19
+ stage: str = typer.Option(
20
+ "warmup",
21
+ "--stage",
22
+ help="Training stage: warmup (native alias: sft) or opd; default: warmup.",
23
+ ),
24
+ run: str | None = typer.Option(
25
+ None,
26
+ "--run",
27
+ help="Historical logical execution number, e.g. 2 or run-2; default: current execution.",
28
+ ),
29
+ status: bool = typer.Option(
30
+ False,
31
+ "--status",
32
+ help="Only inspect the viewer session; cannot combine with --stop or --wait.",
33
+ ),
34
+ stop: bool = typer.Option(
35
+ False,
36
+ "--stop",
37
+ help="Stop only the TensorBoard session; training continues. Cannot combine with --status.",
38
+ ),
39
+ size: str = typer.Option(
40
+ "small",
41
+ "--size",
42
+ help="Viewer resource size: small, medium or large; default: small. Used only when starting.",
43
+ ),
44
+ ttl_seconds: int = typer.Option(
45
+ 1800,
46
+ "--ttl-seconds",
47
+ min=300,
48
+ max=7200,
49
+ help="Viewer lifetime in seconds, 300-7200; default: 1800. Used only when starting.",
50
+ ),
51
+ wait: bool = typer.Option(
52
+ False,
53
+ "--wait",
54
+ help="Wait for the viewer to become Ready or disappear after --stop; unavailable with --status.",
55
+ ),
56
+ timeout: str | None = typer.Option(
57
+ None,
58
+ "--timeout",
59
+ metavar="DURATION",
60
+ help="Local wait limit, e.g. 90, 30m or 2h; default: 30s. Does not stop training or the viewer.",
61
+ ),
62
+ ):
63
+ """Open, inspect or stop TensorBoard for a fixed warmup/OPD run.
64
+
65
+ Target NAME is a Fusion task name or ID. Without --status or --stop, start an on-demand
66
+ viewer for the exact training stage selected by --run and --stage. Training logs must
67
+ already exist and you need access to the task and its Storage files. --wait returns the
68
+ actual published URL when Ready; no URL is guessed. Stopping the viewer does not stop
69
+ training. Use fusion logs to inspect a stage that has no TensorBoard data yet.
70
+
71
+ Examples:
72
+
73
+ infix fusion tensorboard fusion-business --stage warmup --wait
74
+
75
+ infix fusion tensorboard fusion-business --stage opd --run 2 --status
76
+
77
+ infix fusion tensorboard fusion-business --stage opd --run 2 --stop --wait
78
+ """
79
+ selected = stage_name(stage)
80
+ if selected not in {"sft", "opd"} or size not in {"small", "medium", "large"}:
81
+ raise UsageError(
82
+ "TensorBoard requires warmup/opd and a small/medium/large size."
83
+ )
84
+ if status and stop:
85
+ raise UsageError("--status and --stop are mutually exclusive.")
86
+ if status and wait:
87
+ raise UsageError(
88
+ "--wait is only available when starting or stopping a session."
89
+ )
90
+ seconds = parse_timeout(timeout)
91
+ client = ctx.obj.client()
92
+ detail = tasks.details(client, name, "fusion", run=run, stage=selected)
93
+ slot = next(
94
+ (slot for slot in detail.get("stages", []) if slot["stage_type"] == selected),
95
+ {},
96
+ )
97
+ run_id = slot.get("stage_run_id") or (slot.get("run") or {}).get("id")
98
+ if not run_id:
99
+ raise UsageError(
100
+ "The selected history has no training run. Check fusion get/artifacts first."
101
+ )
102
+ path = f"{tasks.PATH}/{segment(detail['summary']['id'])}/runs/{segment(run_id)}/tensorboard"
103
+ if status:
104
+ result = client.get(path)
105
+ elif stop:
106
+ result = client.delete(path)
107
+ else:
108
+ result = client.post(path, json={"size": size, "ttl_seconds": ttl_seconds})
109
+ if wait:
110
+
111
+ def fetch():
112
+ value = client.get(path)
113
+ return value["phase"], value
114
+
115
+ _, result = wait_until_terminal(
116
+ fetch,
117
+ terminal=frozenset({"NotFound"})
118
+ if stop
119
+ else frozenset({"Ready", "Failed", "NotFound"}),
120
+ ctx=ctx.obj,
121
+ timeout=seconds,
122
+ label="TensorBoard",
123
+ recheck_hint=f"infix fusion tensorboard {name} --stage {stage} --status",
124
+ )
125
+ if result.get("url"):
126
+ result = {**result, "url": urljoin(ctx.obj.profile.api_url, result["url"])}
127
+ output(
128
+ ctx.obj,
129
+ {"name": name, "stage_run_id": run_id, "run": run_number(run), **result},
130
+ )
131
+ if wait and not stop and result["phase"] != "Ready":
132
+ raise typer.Exit(1)