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,290 @@
1
+ """stop / restart / clone, shared by the three job modules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from infix_cli.domain import enums, refs, resolve
8
+ from infix_cli.errors import NotFoundError, UsageError
9
+
10
+ # Which backend verb a stop request becomes, by current state.
11
+ #
12
+ # The backend has two: /stop suspends (keeps the CRD, training can resume) and
13
+ # /cancel cancels (deletes the CRD). The PRD gives the user one `stop`, so the
14
+ # routing happens here and the resulting state — stopped or canceled — is
15
+ # whatever the backend reports.
16
+ #
17
+ # Training 和 Evaluation 的挂起接口均只接受 Running;初始化阶段走取消,
18
+ # 避免模型加载或镜像拉取期间无法通过 stop 释放资源。
19
+ _SUSPENDABLE = {
20
+ "training": frozenset({"running"}),
21
+ "evaluation": frozenset({"running"}),
22
+ }
23
+ _ALREADY_STOPPED = frozenset({"stopped", "canceled", "completed", "failed", "timeout"})
24
+
25
+
26
+ def stop(run: Any, module: str, job: dict) -> dict:
27
+ """Stop a job, choosing suspend or cancel from its current state."""
28
+ status = enums.status_to_cli(job.get("status"))
29
+ job_id = str(job.get("id"))
30
+ name = str(job.get("name") or job_id)
31
+
32
+ if status in _ALREADY_STOPPED:
33
+ raise UsageError(
34
+ f'{module.capitalize()} job "{name}" is already {status}.',
35
+ )
36
+
37
+ client = run.client()
38
+ if module == "spark":
39
+ return client.post(f"/data-processing/{job_id}/action", json={"action": "stop"}) or {}
40
+
41
+ verb = "stop" if status in _SUSPENDABLE.get(module, frozenset()) else "cancel"
42
+ return client.post(f"/{_module_path(module)}/{job_id}/{verb}") or {}
43
+
44
+
45
+ def restart(run: Any, module: str, job: dict) -> dict:
46
+ job_id = str(job.get("id"))
47
+ client = run.client()
48
+ if module == "spark":
49
+ return client.post(f"/data-processing/{job_id}/action", json={"action": "restart"}) or {}
50
+ return client.post(f"/{_module_path(module)}/{job_id}/restart") or {}
51
+
52
+
53
+ def _module_path(module: str) -> str:
54
+ return "training/jobs" if module == "training" else "evaluation/jobs"
55
+
56
+
57
+ # ── clone ───────────────────────────────────────────────────────────────────
58
+
59
+
60
+ def clone_name(dto: Any, override: str | None) -> str:
61
+ """New job name for a clone: ``--name`` or ``<original>-clone-1`` (PRD 3.7).
62
+
63
+ The name goes *into* the file rather than being passed as a flag at create
64
+ time, because ``--config`` supersedes the job flags — a config without a
65
+ name could not be submitted at all.
66
+ """
67
+ if override and override.strip():
68
+ return override.strip()
69
+ return f"{getattr(dto, 'name', '') or 'job'}-clone-1"
70
+
71
+
72
+ def _rescope(client: Any, kind: str, reference: str | None, asset_id: str | None) -> str | None:
73
+ """Point a reference at the namespace its asset actually lives in.
74
+
75
+ A job detail names its dataset and code without saying where they came
76
+ from, so the DTO can only guess ``workspace/``. An official asset carrying
77
+ that prefix fails to resolve when the config is submitted back, which broke
78
+ the clone-then-create loop the PRD calls for. Storage paths are already
79
+ unambiguous and are left alone.
80
+ """
81
+ if not reference or not asset_id or client is None:
82
+ return reference
83
+ if reference.startswith("storage/"):
84
+ return reference
85
+ bare = reference.split("/", 1)[1] if "/" in reference else reference
86
+ return f"{resolve.asset_scope_by_id(client, kind, asset_id)}/{bare}"
87
+
88
+
89
+ def _training_reference(
90
+ client: Any, kind: str, reference: str | None, asset_id: str | None, version_id: str | None,
91
+ ) -> str | None:
92
+ """把原任务锁定的资产版本转换为可重用的引用。"""
93
+ if not client or not version_id or (reference and reference.startswith("storage/")):
94
+ return reference if kind == "model" else _rescope(client, kind, reference, asset_id)
95
+
96
+ def unavailable(reason: str) -> UsageError:
97
+ return UsageError(
98
+ f'Cannot clone {kind} "{reference or asset_id}" at recorded version "{version_id}": {reason}.',
99
+ f"Select an available {kind} version and supply it explicitly in a new training configuration.",
100
+ details={"kind": kind, "asset_id": asset_id, "version_id": version_id},
101
+ )
102
+
103
+ try:
104
+ if asset_id:
105
+ asset = client.get(f"/assets/{resolve.asset_path(kind)}/{asset_id}")
106
+ if not isinstance(asset, dict):
107
+ raise unavailable("the asset metadata is unavailable")
108
+ if isinstance(asset.get("data"), dict):
109
+ asset = asset["data"]
110
+ else:
111
+ if not reference:
112
+ raise unavailable("the asset reference is missing")
113
+ ref = refs.parse_asset_ref(reference, kind=kind)
114
+ asset = resolve.find_asset(client, kind, ref.name, ref.scope)
115
+ asset_id = asset["id"]
116
+ versions = resolve.list_versions(client, kind, asset_id)
117
+ except NotFoundError as exc:
118
+ raise unavailable("the asset or version was not found") from exc
119
+
120
+ version = next((item for item in versions if str(item.get("id")) == version_id), None)
121
+ if not version or not version.get("version_number"):
122
+ raise unavailable("the original version is no longer listed")
123
+ if enums.ASSET_STATUS.to_cli(version.get("status")) != "available":
124
+ raise unavailable("the original version is unavailable")
125
+
126
+ source = asset.get("source") or asset.get("data_source") or asset.get("code_source")
127
+ official = source == "Official" or (not source and bool(reference and reference.startswith("official/")))
128
+ name = asset.get("name") or (reference or "").partition("/")[2]
129
+ if not name:
130
+ raise unavailable("the asset name is missing")
131
+ if official:
132
+ latest = next(
133
+ (item for item in versions if enums.ASSET_STATUS.to_cli(item.get("status")) == "available"),
134
+ None,
135
+ )
136
+ if latest is not version:
137
+ raise unavailable("official references select the latest version and the original version is older")
138
+ return f"official/{name}"
139
+ return f"workspace/{name}:{version['version_number']}"
140
+
141
+
142
+ def training_config(dto: Any, name: str, *, client: Any = None) -> dict:
143
+ """Reduce a training job to the options that would recreate it.
144
+
145
+ Keys match the create flags (hyphenated), so the output feeds straight into
146
+ ``training create --config``. 有客户端时,从任务记录恢复原始资产版本。
147
+ """
148
+ config = {
149
+ "name": name,
150
+ "base-model": _training_reference(
151
+ client, "model", dto.base_model, dto._base_model_asset_id, dto.base_model_version_id,
152
+ ),
153
+ "dataset": _training_reference(
154
+ client, "dataset", dto.dataset, dto._dataset_asset_id, dto.dataset_version_id,
155
+ ),
156
+ "code": _training_reference(
157
+ client, "code", dto.code, dto._code_asset_id, dto._code_version_id,
158
+ ),
159
+ "method": dto.method,
160
+ "task": dto.task,
161
+ "checkpoint-precision": dto.checkpoint_precision,
162
+ "hardware": dto.hardware,
163
+ "workers": dto.workers,
164
+ "image": dto.image,
165
+ "startup-command": dto.startup_command,
166
+ "tensorboard-log-path": dto.tensorboard_log_path,
167
+ "visibility": dto.visibility,
168
+ }
169
+ if dto.hyperparameters:
170
+ config["set"] = dict(dto.hyperparameters)
171
+ return _drop_empty(config)
172
+
173
+
174
+ def _evaluation_model(client: Any, dto: Any) -> tuple[str | None, str]:
175
+ """The ``--model`` reference and the ``--model-source`` that goes with it.
176
+
177
+ The backend keeps one value, ``assets_models``, for both namespaces, so a
178
+ job run against an official model reports the same source as a workspace
179
+ one. Asking the asset settles it, and the two flags then agree — a config
180
+ claiming ``model-source: workspace`` beside an ``official/`` reference is
181
+ rejected on submit.
182
+ """
183
+ source = dto.model_source
184
+ if source == "storage":
185
+ # Here the backend's model_id *is* the storage path, not an asset id.
186
+ path = str(dto._model_asset_id or dto.model or "").lstrip("/")
187
+ return (f"storage/{path}" if path else None), "storage"
188
+ if source == "endpoint":
189
+ # create accepts the service name as well as its URL (decision 28).
190
+ return dto.model, "endpoint"
191
+ if not dto.model:
192
+ return None, source
193
+ scope = (
194
+ resolve.asset_scope_by_id(client, "model", dto._model_asset_id)
195
+ if client and dto._model_asset_id
196
+ else source
197
+ )
198
+ return f"{scope}/{dto.model}", scope
199
+
200
+
201
+ def evaluation_config(dto: Any, name: str, *, client: Any = None) -> dict:
202
+ """Reduce an evaluation job to the options that would recreate it.
203
+
204
+ Pass ``client`` so the model and dataset carry the prefix ``create``
205
+ requires; without it they stay as the DTO rendered them.
206
+ """
207
+ model, model_source = _evaluation_model(client, dto)
208
+ dataset = dto.dataset
209
+ if dataset and client and dto._dataset_asset_id:
210
+ scope = resolve.asset_scope_by_id(client, "dataset", dto._dataset_asset_id)
211
+ dataset = f"{scope}/{dataset}"
212
+ config = {
213
+ "name": name,
214
+ "eval-type": dto.eval_type,
215
+ "custom-format": dto.custom_format,
216
+ "model-source": model_source,
217
+ "model": model,
218
+ "dataset": dataset,
219
+ "visibility": dto.visibility,
220
+ "chat-template": (dto.generation_params or {}).get("chat_template"),
221
+ }
222
+ return _drop_empty(config)
223
+
224
+
225
+ def spark_config(dto: Any, name: str, *, client: Any = None) -> dict:
226
+ """Reduce a Spark job to the options that would recreate it.
227
+
228
+ Pass ``client`` so each dataset and the code carry the namespace they
229
+ really belong to; without it they stay as the DTO rendered them.
230
+ """
231
+ datasets = [
232
+ _rescope(client, "dataset", ref, asset_id)
233
+ for ref, asset_id in zip(dto.datasets, _pad(dto._dataset_asset_ids, len(dto.datasets)))
234
+ ]
235
+ config = {
236
+ "name": name,
237
+ "dataset": datasets,
238
+ "code": _rescope(client, "code", dto.code, _first_id(dto._code_asset_ids)),
239
+ "main-script": dto.main_script,
240
+ "args": dto.args,
241
+ "hardware": dto.hardware,
242
+ "workers": dto.workers,
243
+ "image": dto.image,
244
+ "input-format": dto.input_format,
245
+ "output-path": dto.output_path,
246
+ "visibility": dto.visibility,
247
+ }
248
+ if dto.spark_conf:
249
+ config["spark-conf"] = dict(dto.spark_conf)
250
+ return _drop_empty(config)
251
+
252
+
253
+ def _pad(ids: Any, length: int) -> list:
254
+ """Line asset ids up with references, tolerating a shorter list.
255
+
256
+ Storage-sourced datasets contribute a reference but no asset id, so the two
257
+ lists need not be the same length.
258
+ """
259
+ values = list(ids or [])
260
+ return values + [None] * max(0, length - len(values))
261
+
262
+
263
+ def _first_id(ids: Any) -> str | None:
264
+ values = [i for i in (ids or []) if i]
265
+ return values[0] if values else None
266
+
267
+
268
+ def _drop_empty(config: dict) -> dict:
269
+ return {key: value for key, value in config.items() if value not in (None, "", [], {})}
270
+
271
+
272
+ def emit_clone(run: Any, config: dict, *, save: str | None, module: str) -> None:
273
+ """Print the config, or write it to a file."""
274
+ import json
275
+
276
+ from infix_cli import render
277
+
278
+ body = json.dumps(config, indent=2, ensure_ascii=False)
279
+ if save:
280
+ from pathlib import Path
281
+
282
+ target = Path(save).expanduser()
283
+ target.write_text(body + "\n", encoding="utf-8")
284
+ render.message(
285
+ run,
286
+ f'Wrote {target}. Create from it with "infix {module} create '
287
+ f'--config {target}".',
288
+ )
289
+ return
290
+ print(body)
@@ -0,0 +1,351 @@
1
+ """Request bodies for the three job-creation commands.
2
+
3
+ Same rationale as _register: the mapping from CLI words to backend fields is
4
+ where a wrong guess becomes a 422, so it lives in pure functions that take
5
+ already-resolved ids and return a body.
6
+
7
+ Resolution (name -> id, hardware -> spec) stays in the command layer, which is
8
+ the part that needs a client.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any
14
+
15
+ from infix_cli.domain import enums
16
+ from infix_cli.domain.dto.common import compact
17
+ from infix_cli.domain.refs import AssetRef, Ref, StorageRef
18
+ from infix_cli.errors import NotFoundError, UsageError
19
+
20
+
21
+ class Slot:
22
+ """One resolved resource reference, ready to be written into a payload.
23
+
24
+ A job slot is either a registered asset (ids) or a raw storage path, and
25
+ the two are mutually exclusive per slot on every backend request.
26
+ """
27
+
28
+ def __init__(self, ref: Ref, asset_id: str = "", version_id: str = "", name: str = "") -> None:
29
+ self.ref = ref
30
+ self.asset_id = asset_id
31
+ self.version_id = version_id
32
+ self.name = name
33
+
34
+ @property
35
+ def is_storage(self) -> bool:
36
+ return isinstance(self.ref, StorageRef)
37
+
38
+ @property
39
+ def is_official(self) -> bool:
40
+ return isinstance(self.ref, AssetRef) and self.ref.is_official
41
+
42
+ @property
43
+ def path(self) -> str:
44
+ return self.ref.path if isinstance(self.ref, StorageRef) else ""
45
+
46
+
47
+ def training_payload(
48
+ *,
49
+ name: str,
50
+ base_model: Slot,
51
+ dataset: Slot,
52
+ code: Slot | None,
53
+ method: str,
54
+ task: str,
55
+ checkpoint_precision: str | None,
56
+ computing_spec_id: str,
57
+ workers: int,
58
+ image: str | None = None,
59
+ startup_command: str | None = None,
60
+ tensorboard_log_path: str | None = None,
61
+ framework: str | None = None,
62
+ hyperparameters: dict[str, Any] | None = None,
63
+ visibility: str = "private",
64
+ description: str | None = None,
65
+ ) -> dict[str, Any]:
66
+ """``POST /training/jobs``."""
67
+ payload: dict[str, Any] = {
68
+ "name": name,
69
+ "task_type": enums.TASK_TYPE.to_backend(task),
70
+ "method": enums.TRAINING_METHOD.to_backend(method),
71
+ "computing_spec_id": computing_spec_id,
72
+ "num_workers": workers,
73
+ "visibility": enums.VISIBILITY.to_backend(visibility),
74
+ }
75
+ if description:
76
+ payload["description"] = description
77
+ if checkpoint_precision:
78
+ payload["ckpt_save_precision"] = enums.CKPT_PRECISION.to_backend(checkpoint_precision)
79
+ if framework:
80
+ payload["framework"] = framework[:1].upper() + framework[1:] if framework != "pytorch" else "PyTorch"
81
+
82
+ _slot_into(payload, base_model, asset_key="base_model_id",
83
+ version_key="base_model_version_id", path_key="base_model_workspace_path")
84
+ # The backend distinguishes an official base model from a workspace one by
85
+ # this field, not by the ids — it drives which catalogue the trainer reads.
86
+ if not base_model.is_storage:
87
+ payload["base_model_source"] = "Official" if base_model.is_official else "Manual"
88
+ _slot_into(payload, dataset, asset_key="dataset_id",
89
+ version_key="dataset_version_id", path_key="dataset_workspace_path")
90
+ if code is not None:
91
+ _slot_into(payload, code, asset_key="code_id",
92
+ version_key="code_version_id", path_key="code_workspace_path")
93
+ # The name field is DEPRECATED for resolution, but the custom-method
94
+ # validator still reads it: it rejects the request unless `code` or
95
+ # `code_workspace_path` is non-empty, and an asset reference fills
96
+ # neither. Sending the name alongside the ids satisfies it without
97
+ # affecting which asset is used (ids win).
98
+ if not code.is_storage and code.name:
99
+ payload["code"] = code.name
100
+
101
+ if image:
102
+ payload["container_image"] = image
103
+ if startup_command:
104
+ # One string in, two List[str] fields out. shlex.split would misread
105
+ # pipes, && and variable expansion; wrapping in `bash -c` keeps the
106
+ # semantics the user typed at their own shell.
107
+ payload["command"] = ["bash", "-c", startup_command]
108
+ payload["args"] = []
109
+ if tensorboard_log_path:
110
+ payload["tensor_board_path"] = tensorboard_log_path
111
+ if hyperparameters:
112
+ payload["hyperparameters"] = hyperparameters
113
+ return compact(payload)
114
+
115
+
116
+ def evaluation_payload(
117
+ *,
118
+ name: str,
119
+ eval_type: str,
120
+ custom_format: str | None,
121
+ model_source: str,
122
+ model_id: str,
123
+ model_version_id: str | None,
124
+ model_owner_user_id: str | None,
125
+ dataset: Slot,
126
+ endpoint_api_key: str | None = None,
127
+ visibility: str = "private",
128
+ ) -> dict[str, Any]:
129
+ """``POST /evaluation/jobs``."""
130
+ payload: dict[str, Any] = {
131
+ "name": name,
132
+ "eval_type": _eval_type(eval_type, custom_format),
133
+ "model_source": enums.MODEL_SOURCE_TO_BACKEND[model_source],
134
+ "model_id": model_id,
135
+ "model_version_id": model_version_id,
136
+ "model_owner_user_id": model_owner_user_id,
137
+ "model_service_api_key": endpoint_api_key,
138
+ "visibility": enums.VISIBILITY.to_backend(visibility),
139
+ }
140
+ if dataset.is_storage:
141
+ payload["dataset_source"] = "workspace_storage"
142
+ payload["dataset_id"] = dataset.path
143
+ else:
144
+ payload["dataset_source"] = "assets_datasets"
145
+ payload["dataset_id"] = dataset.asset_id
146
+ payload["dataset_version_id"] = dataset.version_id
147
+ return compact(payload)
148
+
149
+
150
+ def _eval_type(eval_type: str, custom_format: str | None) -> str:
151
+ """Two flags collapse into one backend enum."""
152
+ if eval_type == "official":
153
+ if custom_format:
154
+ raise UsageError("--custom-format applies only to --eval-type custom.")
155
+ return "official"
156
+ if eval_type != "custom":
157
+ raise UsageError(
158
+ f'Invalid --eval-type "{eval_type}".', "Valid: official, custom.",
159
+ )
160
+ if not custom_format:
161
+ raise UsageError(
162
+ "--custom-format is required with --eval-type custom.",
163
+ "Valid: single-choice, question-answering.",
164
+ )
165
+ if custom_format not in ("single-choice", "question-answering"):
166
+ raise UsageError(
167
+ f'Invalid --custom-format "{custom_format}".',
168
+ "Valid: single-choice, question-answering.",
169
+ )
170
+ return enums.EVAL_TYPE.to_backend(custom_format)
171
+
172
+
173
+ def spark_payload(
174
+ *,
175
+ name: str,
176
+ datasets: list[Slot],
177
+ code: Slot,
178
+ main_script: str,
179
+ resources: dict[str, int],
180
+ args: str | None = None,
181
+ spark_conf: dict[str, str] | None = None,
182
+ image: str | None = None,
183
+ input_format: str | None = None,
184
+ output_path: str | None = None,
185
+ visibility: str = "private",
186
+ ) -> dict[str, Any]:
187
+ """``POST /data-processing/``.
188
+
189
+ Note the visibility casing: this module stores it lowercase where every
190
+ other one capitalises it.
191
+ """
192
+ payload: dict[str, Any] = {
193
+ "name": name,
194
+ # Passed through verbatim — the GUI field behind startup_command is
195
+ # labelled "Main Script Path". No spark-submit assembly, no splitting.
196
+ "startup_command": main_script,
197
+ "visibility": visibility.lower(),
198
+ **resources,
199
+ }
200
+ dataset_version_ids = [s.version_id for s in datasets if not s.is_storage and s.version_id]
201
+ workspace_datasets = [{"path": s.path} for s in datasets if s.is_storage]
202
+ if dataset_version_ids:
203
+ payload["dataset_version_ids"] = dataset_version_ids
204
+ if workspace_datasets:
205
+ payload["workspace_dataset_paths"] = workspace_datasets
206
+
207
+ if code.is_storage:
208
+ payload["workspace_code_path"] = {"path": code.path}
209
+ else:
210
+ payload["code_version_ids"] = [code.version_id]
211
+
212
+ if args:
213
+ payload["application_args"] = args
214
+ if spark_conf:
215
+ payload["spark_conf"] = spark_conf
216
+ if image:
217
+ payload["container_image"] = image
218
+ if input_format:
219
+ payload["input_format"] = input_format
220
+ if output_path:
221
+ payload["output_path"] = output_path
222
+ return compact(payload)
223
+
224
+
225
+ def serving_payload(
226
+ *,
227
+ name: str,
228
+ workspace_id: str,
229
+ model: Slot,
230
+ model_uri: str,
231
+ spec: dict,
232
+ replicas: int,
233
+ engine: str,
234
+ engine_config: dict[str, Any] | None = None,
235
+ description: str | None = None,
236
+ visibility: str = "private",
237
+ container_image: str | None = None,
238
+ port: int | None = None,
239
+ ) -> dict:
240
+ """``POST /serving/services``.
241
+
242
+ The model is deployed from ``model_source.uri`` (the version's artifact
243
+ URL, as the GUI sends it); the asset and version ids are stored only so the
244
+ record can name the model. Likewise the spec id is stored for display, and
245
+ it is ``gpu_per_replica`` that sizes the pods and the resource check — so
246
+ both are sent, the GPU count taken from the spec.
247
+
248
+ ``workspace_id`` is required by the schema although the backend reads the
249
+ workspace from the header. ``container_image`` and ``port`` come only from
250
+ a cloned config: custom deployment has no flags yet (design D2).
251
+ """
252
+ return compact({
253
+ "name": name,
254
+ "workspace_id": workspace_id,
255
+ "engine": engine,
256
+ "model_source": {"type": "asset", "uri": model_uri},
257
+ "model_asset_id": model.asset_id or None,
258
+ "model_version_id": model.version_id or None,
259
+ "replicas": replicas,
260
+ "gpu_per_replica": int(spec.get("gpu_count") or 0),
261
+ "computing_spec_id": str(spec.get("id") or "") or None,
262
+ "visibility": visibility,
263
+ "description": description,
264
+ "engine_config": engine_config or None,
265
+ "container_image": container_image,
266
+ "port": port,
267
+ })
268
+
269
+
270
+ def _slot_into(payload: dict, slot: Slot, *, asset_key: str, version_key: str, path_key: str) -> None:
271
+ if slot.is_storage:
272
+ payload[path_key] = slot.path
273
+ return
274
+ payload[asset_key] = slot.asset_id
275
+ payload[version_key] = slot.version_id
276
+
277
+
278
+ def parse_key_values(pairs: list[str], *, flag: str) -> dict[str, str]:
279
+ """``--spark-conf k=v`` (repeatable) -> dict."""
280
+ parsed: dict[str, str] = {}
281
+ for pair in pairs or []:
282
+ key, sep, value = pair.partition("=")
283
+ key, value = key.strip(), value.strip()
284
+ if not sep or not key:
285
+ raise UsageError(
286
+ f'Invalid {flag} "{pair}".', f"Use {flag} key=value.",
287
+ )
288
+ parsed[key] = value
289
+ return parsed
290
+
291
+
292
+ # ── command-layer helpers (these need a client) ─────────────────────────────
293
+
294
+
295
+ def resolve_slot(
296
+ client: Any, value: str, *, kind: str, flag: str, check_storage: bool = False,
297
+ ) -> Slot:
298
+ """解析资产引用,并按需检查 Storage 路径是否可见。"""
299
+ from infix_cli.domain import refs, resolve
300
+
301
+ ref = refs.parse_ref(value, kind=kind, flag=flag)
302
+ if isinstance(ref, StorageRef):
303
+ if check_storage:
304
+ from infix_cli.commands import _storage_tree
305
+
306
+ if _storage_tree.stat(client, ref.path, dir_size=False) is None:
307
+ raise NotFoundError(
308
+ f'Storage path "{ref.path}" for {flag} was not found.',
309
+ 'Check the path and access with "infix storage list".',
310
+ details={"field": flag.removeprefix("--"), "path": ref.path},
311
+ )
312
+ return Slot(ref)
313
+ resolved = resolve.resolve_asset(client, ref)
314
+ return Slot(ref, resolved.asset_id, resolved.version_id or "", resolved.name)
315
+
316
+
317
+ def load_config(path: str | None) -> dict[str, Any]:
318
+ """读取并严格校验当前命令的完整任务配置。"""
319
+ from infix_cli.config_input import load_job_config
320
+
321
+ return load_job_config(path)
322
+
323
+
324
+ def pick(
325
+ flag_value: Any,
326
+ config: dict[str, Any],
327
+ key: str,
328
+ *,
329
+ default: Any = None,
330
+ required: bool = False,
331
+ flag: str | None = None,
332
+ ) -> Any:
333
+ """Resolve one job-spec value.
334
+
335
+ 配置文件描述整个任务;load_config 已拒绝与任务参数混用。
336
+ 无配置时采用显式参数,否则回退到默认值。
337
+ """
338
+ if config:
339
+ if key in config and config[key] not in (None, ""):
340
+ return config[key]
341
+ elif flag_value not in (None, (), []):
342
+ return flag_value
343
+ if required:
344
+ raise UsageError(
345
+ f"{flag or '--' + key.replace('_', '-')} is required.",
346
+ 'Add it to the config file — "--config" replaces the job-spec flags.'
347
+ if config
348
+ else None,
349
+ details={"field": key},
350
+ )
351
+ return default