envloop-cli 1.33.0__py3-none-any.whl → 1.34.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.
envloop/_optional.py CHANGED
@@ -85,6 +85,15 @@ def require_data_dependencies():
85
85
  raise MissingFeatureError('data')
86
86
 
87
87
 
88
+ def missing_feature(error: BaseException) -> MissingFeatureError | None:
89
+ """Treat a deferred import of the public ANS dependency as the missing [data] extra."""
90
+ if isinstance(error, MissingFeatureError):
91
+ return error
92
+ if isinstance(error, ModuleNotFoundError) and isinstance(error.name, str) and error.name.partition('.')[0] == 'envhub':
93
+ return MissingFeatureError('data')
94
+ return None
95
+
96
+
88
97
  def feature_module(feature: str, module: str):
89
98
  if not available(feature):
90
99
  raise IncompleteInstallationError(feature)
envloop/cli_errors.py CHANGED
@@ -120,6 +120,7 @@ _register("REGISTRY_CREDENTIAL_EXISTS", "This project already has a credential f
120
120
  _register("REGISTRY_CREDENTIAL_LIMIT", "The project reached its registry credential limit. Remove an unused credential first.")
121
121
  _register("INVALID_REGISTRY_CREDENTIAL", "Use a registry host such as ghcr.io, a repository prefix such as my-org, a username without ':' and a non-empty token.")
122
122
  _register("REGISTRY_CREDENTIALS_UNAVAILABLE", "Registry credentials are unavailable on this deployment. Retry later or contact the platform operator.")
123
+ _register("REGISTRY_CREDENTIAL_SCOPE_REQUIRED", "This API key does not carry registry_credentials.write, and existing keys never gain permissions. Only a key issued by el auth login can manage registry credentials: as a project Admin, run el auth login again, then retry.")
123
124
  _register("CONCURRENCY_ABOVE_CEILING", "The limit is above the ceiling the platform operator set for this project. Check `el limit get`.")
124
125
  _register("INVALID_CONCURRENCY_LIMIT", "Use a whole number from 1 to 10000, or none to clear the project limit.")
125
126
  _register("INVALID_PROJECT_ID INVALID_WORKSPACE_ID", "The workspace or project ID has an invalid format.")
@@ -307,14 +308,14 @@ def validation_message(error: BaseException) -> str | None:
307
308
 
308
309
  def safe_error_code(error: Any) -> str:
309
310
  """Select a trusted CLI/report identifier without changing the SDK error."""
310
- from ._optional import MissingFeatureError
311
+ from ._optional import missing_feature
311
312
  from .config import ConfigError
312
313
  from .downloads import ArtifactError
313
314
  from .profile_secrets import InvalidProfileSecrets
314
315
  from .resources import CleanupError
315
316
 
316
- if isinstance(error, MissingFeatureError):
317
- return error.code
317
+ if (feature := missing_feature(error)) is not None:
318
+ return feature.code
318
319
  if isinstance(error, CleanupError):
319
320
  code = "CLEANUP_INCOMPLETE"
320
321
  elif isinstance(error, (RemoteError, ConfigError, ArtifactError, InvalidProfileSecrets)) or type(error).__module__ == 'envloop_rsi_loop.loops':
@@ -373,9 +374,9 @@ def error_block(code: str, message: str, *, status: int | None = None, guidance:
373
374
 
374
375
  def format_error(error: BaseException) -> str:
375
376
  """Render a human error; SDK exception attributes remain unchanged."""
376
- from ._optional import MissingFeatureError
377
- if isinstance(error, MissingFeatureError):
378
- return error_block(error.code, str(error))
377
+ from ._optional import missing_feature
378
+ if (feature := missing_feature(error)) is not None:
379
+ return error_block(feature.code, str(feature))
379
380
  code = safe_error_code(error)
380
381
  remote = error if isinstance(error, RemoteError) else None
381
382
  candidate = remote and remote.status_code
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: envloop-cli
3
- Version: 1.33.0
3
+ Version: 1.34.0
4
4
  Summary: EnvLoop CLI and Python SDK for jobs, training, checkpoints and inference
5
5
  Project-URL: Homepage, https://envloop.ai
6
6
  Project-URL: Documentation, https://docs.envloop.ai
@@ -21,17 +21,32 @@ Install the public client to run agent Jobs, inspect Trials, manage training and
21
21
  checkpoints, and deploy or call inference endpoints. The `el` and `envloop`
22
22
  commands are equivalent. The Python import package is `envloop`.
23
23
 
24
- ## Version 1.7
24
+ ## Release compatibility
25
25
 
26
- - Use published Runner resource shortcuts for Train Jobs and fixed Checkpoint inputs for Inference Jobs.
27
- - Pass `--json` explicitly to `job submit`; failures retain safe error codes and recovery guidance.
28
- - Submit training through Train Jobs. The retired interactive `envloop.training` interface is removed.
26
+ This page describes the current client source. Published 1.33.0 includes
27
+ `runner list|get|create|update|delete`, replacing the `list|register` commands in
28
+ 1.32.0. The enhancements below are not in published 1.33.0 and await a new
29
+ release. Check your installed `el --version` and `el COMMAND --help` before
30
+ following an example; the source package version alone does not identify
31
+ unreleased features.
29
32
 
30
- After upgrading, check `el --version` and `el job submit --help`. Execution also
31
- requires a matching platform, project permissions and published Runners; package
32
- installation alone does not establish those prerequisites. See the
33
+ | Unreleased source enhancement | Published 1.33.0 |
34
+ | --- | --- |
35
+ | Explicit `--json` for `el runner get\|create\|update\|delete` | These commands already output JSON; omit `--json` |
36
+ | `el data upload harbor --update-digests` | not available; set `[[tasks]] digest` values by hand |
37
+ | `el trial artifact download TRIAL_ID --output DIRECTORY` | positional `DIRECTORY` only |
38
+
39
+ Execution also requires a matching platform, project permissions and published
40
+ Runners; package installation alone does not establish those prerequisites. See the
33
41
  [PyPI release history](https://pypi.org/project/envloop-cli/#history) for published versions.
34
42
 
43
+ Profile v4 requires platform support from [EnvPlatform #1489](https://github.com/EnvLoop/EnvPlatform/pull/1489).
44
+ Running a v6 Runner in a Sandbox also requires the bootstrap fix in
45
+ [EnvPlatform #1490](https://github.com/EnvLoop/EnvPlatform/pull/1490).
46
+ Platform 1.71.0 contains neither change: upgrading the CLI alone does not enable
47
+ these features on that server version. Existing historical Profile formats remain
48
+ available while waiting for a compatible platform release.
49
+
35
50
  ## Install
36
51
 
37
52
  envloop-cli requires Python 3.12 or later; an existing compatible interpreter can
@@ -75,7 +90,7 @@ python -m pip install "envloop-cli[data]"
75
90
  python -m pip install "envloop-cli[data,experiment,rsi-loop]"
76
91
  ```
77
92
 
78
- Every installation includes the existing Job, Trial, Data and RSI Loop commands. The bare installation and `default`, `experiment`, `rsi-loop` groups have no runtime dependencies. `data` adds `envloop-envhub==1.23.0` for ANS parsing and verified directory downloads. Other Data API operations use the bundled client implementation. Missing ANS dependencies produce the `envloop-cli[data]` installation instruction.
93
+ Every installation includes the existing Job, Trial, Data and RSI Loop commands, and every `--help` works without extras. The bare installation and `default`, `experiment`, `rsi-loop` groups have no runtime dependencies. `data` adds `envloop-envhub==1.23.0` for ANS parsing, file-manifest publication and verified directory downloads. Other Data API operations use the bundled client implementation. A command that needs the missing ANS dependency stops with `FEATURE_NOT_INSTALLED` and the `envloop-cli[data]` installation instruction.
79
94
 
80
95
  Feature modules load lazily. Default imports, help and experiment operations do not require EnvHub or certifi. Only the single `envloop-cli` distribution owns the `el` / `envloop` scripts. The examples below require an authorized matching platform; installation does not grant permissions.
81
96
 
@@ -324,6 +339,8 @@ el data download DATA_ID --file FILE_ID --output ./dataset.tgz --resume --json
324
339
 
325
340
  Unified ANS CRUD supports Dataset, Runner, Recipe and HF model Checkpoint registrations through `el data` and `client.data`. Dataset/Runner/Recipe creation requires a native `--manifest` and exact `--directory`; a Recipe may instead be built from a directory holding a committed `recipe.toml` (`envloop.recipe/v2`) and `entrypoint.sh` with `el data create --type recipe --directory DIR [--revision REF]` (SDK `client.data.create(type="recipe", directory=DIR)`). For Dataset create/update/upload, `--ref` (SDK `ref`) is optional when `dataset.namespace`, `dataset.name` and `dataset.version` are present in the manifest; EnvHub derives the immutable Dataset URI. Other resource types and manifests without that identity still require an explicit ref. Explicit refs remain supported; the platform validates their consistency with the manifest. HF metadata registration uses `el data create --type checkpoint --model namespace/model --revision FULL_COMMIT`; SDK uses `create(kind="checkpoint", model=..., revision=...)`. HF weights are not downloaded, and artifact imports do not establish Model or Job checkpoint provenance. While native publication runs, `create`/`update` repeat the same idempotent request until ready (`--timeout`, default 3600 s); `--no-wait` / `wait=False` returns the pending `publishing` resource with resume instructions.
326
341
 
342
+ `el data upload harbor DIR --name NAMESPACE/NAME --version VERSION` (SDK `client.data.upload(DIR, dataset=..., version=...)`) checks the directory before uploading and lists every Task whose `[[tasks]] digest` in `dataset.toml` no longer matches its files. After reviewing the Task changes, add `--update-digests` (SDK `update_digests=True`) to rewrite only those digest values, using the same Task fingerprint that registration verifies; nothing is written when the digests already match or the directory fails any other check, and the rewrite is reported on stderr (`updated_digests` in the JSON). A version that was already published stays immutable on the platform: publish changed Tasks under a new version.
343
+
327
344
  `el runner create DIRECTORY [--revision FULL_COMMIT|BRANCH|TAG] [--source-ref main]` (default `--revision main`, resolved locally and refused unless the directory matches that commit) publishes a Runner package directory through the same Data API with the manifest built for you, then reads the catalog revision back. `el profile create|update|fork ... --secret NAME[=prompt|stdin|env:VAR|file:PATH]` stores write-only Secret parameters whose names follow the platform's credential rule or `secret_params`; values never come from the command line. `el setting model-access grant NAMESPACE/NAME --protocol anthropic [--revision FULL_COMMIT]` (project Admin) lets a published Runner receive the project's metered model key on Fly Trials; `list` and `revoke GRANT_ID` manage grants.
328
345
 
329
346
  Success follows native storage and original catalog readback and returns an `ans_` identity. Update publishes an explicit new revision. Delete checks active and unknown dependencies; Runner deletion covers all revisions. Historical bytes and quota usage remain. Commands default to the current login base URL/workspace/project, with no `--env`. Both Data grants and the corresponding resource capabilities are required.
@@ -1,10 +1,10 @@
1
1
  envloop/__init__.py,sha256=tX06Gh2EmufRr0J_3YKtjDeNrJ30auR3y3BJ3N3FHJY,421
2
- envloop/_optional.py,sha256=0V_FdfMT48gyPCcPat54SL7tK9ihMuPrcVXjq8KIBPA,9202
2
+ envloop/_optional.py,sha256=8MLz4yw0prkpxDCkIglW6NYh1l11uhh7ERDsull9PH0,9620
3
3
  envloop/auth_cli.py,sha256=xxMxvsBeeIRht0fWaXSV7tstMKlCzqBBVBcXEvNpwGU,17874
4
4
  envloop/auth_login.py,sha256=uOqPHqgzi0Y5eDMiZJH-EI_HxY55F9bRr8CoBb8OHfk,7231
5
5
  envloop/auth_workspace.py,sha256=g92Dok4eSp6P-Du5qkwzZG4JDeSrdYTXJbn5WCzCFMo,14927
6
6
  envloop/cli.py,sha256=VuNRlgP0TTZmqWADclgp3dU0LEL6gmySLd35hbINejE,14539
7
- envloop/cli_errors.py,sha256=VPw4x2w7FtfcVcSNF6Qw8WKfzTbYslFqcHxyHgoKNOc,45556
7
+ envloop/cli_errors.py,sha256=BDksqZ01A8QnDnWueKfSQ-Dlt44ZttrRqPXf1u7D0Vk,45846
8
8
  envloop/cli_output.py,sha256=VMJ-x0mfr5TDywrfUuQNIdLjPMpxE5053cxMOn4_aPY,6001
9
9
  envloop/client.py,sha256=OspRBxuKaJuQOomeYorrxWIrjlda-ROOZ58IqEF-Qks,3280
10
10
  envloop/config.py,sha256=1Wr2lNdNNZzsQDPNGsk-TsnEUvDqOtocy9TgUpmOZO0,22494
@@ -23,23 +23,23 @@ envloop_data/checkpoint_upload.py,sha256=gp6gOPZtpvOa1KljlLmBTxt5awn9TwrMibUN7Xa
23
23
  envloop_data/cli.py,sha256=dTtfanSE43VZP6xIS13Qkd7gu8sQVkJ-5NF694Rr5B0,10545
24
24
  envloop_data/cli_output.py,sha256=uDMDKlJPS5bjlt1e7m5eXAefJfRt02yujDdaaJBdOLs,8469
25
25
  envloop_data/client.py,sha256=ctb8Q9NKTA-XdXGqRyJ0N8TwTMNKh7RvmaRDZ7oiuuY,18292
26
- envloop_data/data.py,sha256=xmoC08GEASZc2m3_W3wqJD7WMfUkT1fHCZqItPCci4U,39723
27
- envloop_data/data_cli.py,sha256=IZGhdvWRRAiIdEj2vgf_zCLzf6Duf3pS_PRsU_3bReo,25717
28
- envloop_data/data_publications.py,sha256=3lFYYffxvNjobs-fvATwjJ5DK9VudCEkxiP6ozv-roo,9176
29
- envloop_data/data_upload.py,sha256=TBHK_wmS9K03gdgxOS5UIl9iK94jLPHM4oCDSAgJZ8o,14702
26
+ envloop_data/data.py,sha256=yKP_HVZcnR3kuLB68Ndk76qRcuAJAP-0GFF1-1dJY5g,40666
27
+ envloop_data/data_cli.py,sha256=BSlepoEfv5habhijYR_IqIfowoFUEJuZwq4jY2sh1L8,26707
28
+ envloop_data/data_publications.py,sha256=te4uWSdOz7Mr_RA6oJzIjJ4cUWKJn4oNfKL12CuDCc0,9177
29
+ envloop_data/data_upload.py,sha256=cyhWBZEmJ7oKGXtxfdEaW8n9o83FMJZEA514UORyE9M,19536
30
30
  envloop_data/http.py,sha256=4ovDUL-HHn8FHJVKvzTR9m8P-JnIo-W47Bda4aZo_Y0,7964
31
31
  envloop_data/navigation_resources.py,sha256=TILHIMuNbXIYWOQdv1JPssThJtZOAdkCjvb8VSk_-PU,14137
32
32
  envloop_data/profile_updates.py,sha256=M0KWqznDY6-MPPfjGNeL4FVTR86_yCRq6OyUJc-tUVY,3387
33
33
  envloop_data/recipe_packages.py,sha256=O19ogsMUPQv8j02UBnHAubF5yakfCAOkppGtvjCDWIM,5956
34
34
  envloop_data/recipes.py,sha256=We2TZWdRl-ialV-uLFvUSvJng9P2HGquqGtqKYKllgs,1442
35
- envloop_data/resource_cli.py,sha256=wApF7_URhyt_iqXXzSbbvr1aIV9eanfSVBLTJlVCB9I,11538
35
+ envloop_data/resource_cli.py,sha256=y8dwzJCVX3yREyXTrqcwVUoyc0D0jXNZ4ZgkiU-6yh8,11825
36
36
  envloop_data/runner_packages.py,sha256=ewxNc9LX8Ne_YlRky9Q4ZOMA7dGG_WQMwEsvzRdPASA,5444
37
37
  envloop_experiment/__init__.py,sha256=nKDGmzFNAQv2mq16YijiI3Q-gDL_smNyZD-AQaqoz7Y,68
38
- envloop_experiment/cli.py,sha256=917NCCy4XzVMpyzvNyCyEBFyOBOA33AmYKwy_wruR7Q,36192
38
+ envloop_experiment/cli.py,sha256=03JsRS6ZDu51mp-sWTbnKfOLSSbfeULn4ofnL2iYmvo,36780
39
39
  envloop_experiment/cli_output.py,sha256=-FojsqOMIIQuOnfhk2AaqMtwUz5skoWvLeNASm8An6Y,2689
40
40
  envloop_experiment/client.py,sha256=W9t06Sn8Y1BpE0Sa4rosK-MplU6CIeUsBiclc6Tc1m0,30099
41
41
  envloop_experiment/decision.py,sha256=HJTj-jSJJ5kcxQQzFXwrA9IICWXA6zSNBFL9EbbrxqI,918
42
- envloop_experiment/http.py,sha256=A_PHWVr7PV4eiP30lXmOITiljXf6GEIYGkJlr1KFz-Q,6110
42
+ envloop_experiment/http.py,sha256=DsYLuTeuEXHMPRfUzDhIlNAOgfAhZL11IaFWZ6Gli2Q,6649
43
43
  envloop_experiment/inference.py,sha256=qSObsdo9suHhG5i_xlCh6-lt-NJkhQzAoF9KzCdVWws,5640
44
44
  envloop_experiment/job_cost.py,sha256=gZB69-pdsJM4wManw44AIS9T3ZtsxxQTqrJs-cHjwJU,2214
45
45
  envloop_experiment/job_logs.py,sha256=RLipbj89e5hQdBeXtszsxSYYw7By1hscwSTGFQzQ3Qw,1340
@@ -61,7 +61,7 @@ envloop_rsi_loop/cli.py,sha256=egat_Keygh9V1VAYgfEmqBKDmntCWe7ES_SFjhh26Yg,4102
61
61
  envloop_rsi_loop/cli_output.py,sha256=o5XzAkcddBOZ2h_AQ-pUPqJIWUOIMfZPWaPxqm0AtUM,4840
62
62
  envloop_rsi_loop/loop_cli.py,sha256=V_LEyWTsps2G1UNuMiWhrDDRdO0H4Z1bXGuWsYTOo0c,4491
63
63
  envloop_rsi_loop/loops.py,sha256=MGVe3uXxGlnzT_Sc7OHU97kyYA_FSFpXIUtlpXQ8ha0,8924
64
- envloop_cli-1.33.0.dist-info/METADATA,sha256=XBmZ0hPDa3BFaOdD-svgmXEcHK0XdgoJzlxiMl6Xwyo,18382
65
- envloop_cli-1.33.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
66
- envloop_cli-1.33.0.dist-info/entry_points.txt,sha256=8aXOpgtVk4GndhChA4XNecShkb1w0xGHBHrKla78ofI,67
67
- envloop_cli-1.33.0.dist-info/RECORD,,
64
+ envloop_cli-1.34.0.dist-info/METADATA,sha256=w8jPlj4hVTQ03-vuTR-wcLSgp38_DxAGi2A7LXluL20,20106
65
+ envloop_cli-1.34.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
66
+ envloop_cli-1.34.0.dist-info/entry_points.txt,sha256=8aXOpgtVk4GndhChA4XNecShkb1w0xGHBHrKla78ofI,67
67
+ envloop_cli-1.34.0.dist-info/RECORD,,
envloop_data/data.py CHANGED
@@ -21,6 +21,8 @@ CHUNK_SIZE = 1024 * 1024
21
21
  PUBLICATION_TIMEOUT = 3600.0
22
22
  # Platform ACL levels of an ANS resource name: its project, its workspace, every workspace.
23
23
  VISIBILITIES = ('private', 'internal', 'public')
24
+ _PUBLISH_VISIBILITY = ('visibility on create/update applies only to Recipes and must be private, internal or public; '
25
+ 'change a Dataset, Runner or Checkpoint after publishing with set-visibility')
24
26
 
25
27
 
26
28
  @dataclass(frozen=True)
@@ -160,8 +162,11 @@ class Data:
160
162
  def list(self, *, type: Literal['dataset', 'artifact', 'checkpoint', 'runner', 'recipe'], ref: str | None = None, job_id: str | None = None, trial_id: str | None = None, limit: int = 25, cursor: str | None = None, visibility: str | None = None) -> dict[str, Any]:
161
163
  if type not in ('dataset', 'artifact', 'checkpoint', 'runner', 'recipe') or (type != 'artifact' and (job_id or trial_id)):
162
164
  raise ValueError('select a Data type and appropriate owner filters')
163
- if visibility is not None and (type != 'recipe' or visibility not in ('all', *VISIBILITIES)):
164
- raise ValueError('visibility filter requires a Recipe and all/private/internal/public')
165
+ if visibility is not None and type != 'recipe':
166
+ raise ValueError(f'the visibility filter (--visibility) applies only to Recipe lists (--type recipe), not --type {type}; '
167
+ 'list without it, and read the visibility of one Dataset, Runner or Checkpoint with get')
168
+ if visibility is not None and visibility not in ('all', *VISIBILITIES):
169
+ raise ValueError('the visibility filter must be all, private, internal or public')
165
170
  return self.transport.request('GET', self._query(self._path(), type=type, ref=ref, job_id=job_id, trial_id=trial_id, limit=limit, cursor=cursor,
166
171
  **({'visibility': visibility} if visibility is not None else {})))
167
172
 
@@ -259,13 +264,13 @@ class Data:
259
264
  if type != 'recipe' or any(value is not None for value in (ref, manifest, files, model)) or executables:
260
265
  raise ValueError('directory publishes a Recipe from recipe.toml, without ref, manifest, files, model or executables')
261
266
  if visibility is not None and visibility not in VISIBILITIES:
262
- raise ValueError('visibility requires a Recipe and private, internal or public')
267
+ raise ValueError(_PUBLISH_VISIBILITY)
263
268
  return self._create_recipe_package(directory, 'main' if revision is None else revision, dry_run=dry_run,
264
269
  idempotency_key=idempotency_key, visibility=visibility, **polling)
265
270
  source = hf_source(type, model, revision, ref=ref, manifest=manifest, files=files,
266
271
  executables=executables, dry_run=dry_run)
267
272
  if visibility is not None and (type != 'recipe' or visibility not in VISIBILITIES):
268
- raise ValueError('visibility requires a Recipe and private, internal or public')
273
+ raise ValueError(_PUBLISH_VISIBILITY)
269
274
  if source is not None:
270
275
  result = self.transport.request('POST', self._path(), source)
271
276
  return result if dry_run else self._settled(lambda: self.transport.request('POST', self._path(), source), result, type, **polling)
@@ -284,7 +289,7 @@ class Data:
284
289
  resource = self.get(data_id)
285
290
  # Visibility belongs to the Recipe name, so omitting it keeps the current value.
286
291
  if visibility is not None and (resource['type'] != 'recipe' or visibility not in VISIBILITIES):
287
- raise ValueError('visibility requires a Recipe and private, internal or public')
292
+ raise ValueError(_PUBLISH_VISIBILITY)
288
293
  if type is not None and type != resource['type']:
289
294
  raise ValueError('update must preserve the publication type')
290
295
  if source is not None:
@@ -513,21 +518,29 @@ class Data:
513
518
  yield stream
514
519
 
515
520
  def upload(self, source: Path, *, dataset: str, version: str, register: bool = False, runner: str | None = None,
516
- wait: bool = True, idempotency_key: str | None = None, progress: Callable[[Any], None] | None = None) -> dict[str, Any]:
521
+ wait: bool = True, idempotency_key: str | None = None, progress: Callable[[Any], None] | None = None,
522
+ update_digests: bool = False) -> dict[str, Any]:
517
523
  """Publish a Harbor Dataset directory or tar bundle; with `register`, add it to the catalog pinned to `runner`.
518
524
 
519
525
  Rerunning with the same content resumes the same upload. Returns
520
- {"publication": resource, "registration": registration or None}; only a `committed`
521
- registration means the version can run Jobs.
526
+ {"publication": resource, "registration": registration or None}; only a `committed` registration
527
+ means the version can run Jobs. `update_digests=True` (directories only) first rewrites stale
528
+ `[[tasks]].digest` values in dataset.toml and adds "updated_digests": [{"task", "previous", "digest"}];
529
+ without it a stale digest is refused before upload with every mismatching Task listed.
522
530
  """
523
531
  from envloop_data.data_upload import Registrations
524
532
  if register and not runner:
525
533
  raise ValueError('register requires runner')
526
534
  registrations = Registrations(self)
535
+ updated: list[dict[str, str]] = []
527
536
  resource = registrations.publish(source, dataset=dataset, version=version,
528
- idempotency_key=idempotency_key, progress=progress)
537
+ idempotency_key=idempotency_key, progress=progress,
538
+ update_digests=update_digests, digests=updated.extend)
529
539
  view = registrations.register(resource['data_id'], cast(str, runner), wait=wait, progress=progress) if register else None
530
- return {'publication': resource, 'registration': view}
540
+ result: dict[str, Any] = {'publication': resource, 'registration': view}
541
+ if update_digests:
542
+ result['updated_digests'] = updated
543
+ return result
531
544
 
532
545
  def register(self, data_id: str, runner: str, *, wait: bool = True, progress: Callable[[Any], None] | None = None) -> dict[str, Any]:
533
546
  """Register a Harbor Dataset publication for Jobs; the same Runner is idempotent."""
envloop_data/data_cli.py CHANGED
@@ -25,7 +25,8 @@ def add_commands(groups: "argparse._SubParsersAction[argparse.ArgumentParser]",
25
25
  data = groups.add_parser('data', help='Manage Project ANS resources and verified downloads').add_subparsers(dest='action', required=True)
26
26
  command = listing(data)
27
27
  command.add_argument('--type', required=True, choices=[*TYPES, 'artifact'])
28
- command.add_argument('--visibility', choices=('all', *VISIBILITIES), help='Recipe visibility filter, applied before pagination')
28
+ command.add_argument('--visibility', choices=('all', *VISIBILITIES),
29
+ help='Only with --type recipe: filter Recipes by visibility, applied before pagination')
29
30
  for option in ('ref', 'job-id', 'trial-id'):
30
31
  command.add_argument('--' + option)
31
32
  command.add_argument('--with-files', action='store_true',
@@ -46,8 +47,9 @@ def add_commands(groups: "argparse._SubParsersAction[argparse.ArgumentParser]",
46
47
  command.add_argument('data_id', metavar='DATA_ID')
47
48
  publication_arguments(command, source=True, recipe=action == 'create')
48
49
  command.add_argument('--visibility', choices=VISIBILITIES,
49
- help='Recipe visibility of the name: private (default for a new name), internal (this workspace) '
50
- 'or public (platform administrators only); omitted on update keeps the current value')
50
+ help='Only for Recipes: visibility of the name: private (default for a new name), internal (this workspace) '
51
+ 'or public (platform administrators only); omitted on update keeps the current value. '
52
+ 'Other types change visibility after publishing with set-visibility')
51
53
  command.add_argument('--idempotency-key', help='Reuse for a resumable multipart retry of the same input')
52
54
  command.add_argument('--wait', action=argparse.BooleanOptionalAction, default=True,
53
55
  help='Wait while the platform finishes native publication (default: wait)')
@@ -91,6 +93,9 @@ def add_commands(groups: "argparse._SubParsersAction[argparse.ArgumentParser]",
91
93
  command.add_argument('--runner', help='Existing Runner NAME@REVISION; required with --register')
92
94
  command.add_argument('--wait', action='store_true', help='With --register, wait until registration finishes (default: return after it starts)')
93
95
  command.add_argument('--idempotency-key', help='Stable upload key; identical input resumes by default')
96
+ command.add_argument('--update-digests', action='store_true',
97
+ help='Before uploading a directory, rewrite stale [[tasks]] digests in dataset.toml from the Task files '
98
+ '(written only if the whole directory then passes the local check)')
94
99
  command.add_argument('--json', action='store_true')
95
100
  command = data.add_parser('register', help='Register an uploaded Harbor Dataset snapshot for Jobs')
96
101
  command.add_argument('data_id', metavar='DATA_ID')
@@ -415,6 +420,15 @@ def upload(data: Any, args: argparse.Namespace):
415
420
  from envloop.http import RemoteError
416
421
  raise RemoteError('DATA_RUNNER_REQUIRED', message='--register requires --runner NAME@REVISION (an existing Runner revision).')
417
422
  from envloop.http import WaitTimeoutError
423
+ changes = None
424
+ if args.update_digests:
425
+ from envloop_data.data_upload import update_task_digests
426
+
427
+ changes = update_task_digests(args.source)
428
+ for change in changes:
429
+ print(f"updated dataset.toml digest of Task {change['task']}: {change['digest']}", file=sys.stderr)
430
+ if not changes:
431
+ print('dataset.toml Task digests already match their files; nothing rewritten', file=sys.stderr)
418
432
  try:
419
433
  result = data.upload(args.source, dataset=args.name, version=args.version, register=args.register, runner=args.runner,
420
434
  wait=args.wait, idempotency_key=args.idempotency_key, progress=_progress())
@@ -422,6 +436,8 @@ def upload(data: Any, args: argparse.Namespace):
422
436
  if isinstance(error.last, dict) and isinstance(error.last.get('data_id'), str):
423
437
  _still_running(error.last['data_id'])
424
438
  raise
439
+ if changes is not None:
440
+ result = {**result, 'updated_digests': changes}
425
441
  print(f"published {result['publication']['ref']} as {result['publication']['data_id']}", file=sys.stderr)
426
442
  if result['registration']:
427
443
  _registered(result['registration'])
@@ -54,6 +54,7 @@ def publication_ref(data_type: str, ref: str | None, manifest: Any) -> str | Non
54
54
 
55
55
  def storage_files(manifest: dict[str, Any]) -> list[dict[str, Any]]:
56
56
  from envloop._optional import require_data_dependencies
57
+
57
58
  require_data_dependencies()
58
59
  from envhub.ans.proto.schemas import canonical_schema
59
60
 
@@ -6,6 +6,7 @@ pins a Runner revision. Only a `committed` registration can run Jobs.
6
6
  """
7
7
  import hashlib
8
8
  import json
9
+ import os
9
10
  import re
10
11
  import stat
11
12
  import tarfile
@@ -92,8 +93,25 @@ def _task_archive_size(directory: Path):
92
93
  return counter.size
93
94
 
94
95
 
95
- def check_directory(root: str | Path):
96
- """Refuse before uploading what registration would reject; the Task digest error shows the expected value."""
96
+ def _task_digests(root: Path, document: dict[str, Any]):
97
+ """(name, declared, actual) for each declared Task whose directory is present, in directory order."""
98
+ declared = {task.get('name'): task.get('digest') for task in document.get('tasks', []) if isinstance(task, dict)}
99
+ found: list[tuple[str, Any, str]] = []
100
+ for child in sorted(root.iterdir()):
101
+ task = child / 'task.toml'
102
+ if not child.is_dir() or child.is_symlink() or not task.is_file():
103
+ continue
104
+ name = tomllib.loads(task.read_text()).get('task', {}).get('name')
105
+ if isinstance(name, str) and name in declared:
106
+ found.append((name, declared[name], _fingerprint(child)))
107
+ return found
108
+
109
+
110
+ def check_directory(root: str | Path, *, manifest_text: str | None = None):
111
+ """Refuse before uploading what registration would reject; Task digest errors list every expected value.
112
+
113
+ `manifest_text` checks a candidate dataset.toml instead of the one on disk (used before rewriting it).
114
+ """
97
115
  root = Path(root)
98
116
  manifest = root / 'dataset.toml'
99
117
  if manifest.is_symlink() or not manifest.is_file():
@@ -118,7 +136,7 @@ def check_directory(root: str | Path):
118
136
  raise _invalid(f'a Dataset may hold at most {MAX_MEMBERS} files and directories and {MAX_UNPACKED_BYTES} bytes')
119
137
  if (root / 'source.toml').exists():
120
138
  raise _invalid('external Dataset sources (source.toml) cannot be uploaded')
121
- document = tomllib.loads(manifest.read_text())
139
+ document = tomllib.loads(manifest.read_text() if manifest_text is None else manifest_text)
122
140
  identity = document.get('dataset', {})
123
141
  if identity.get('upload') is not True:
124
142
  raise _invalid('dataset.toml must declare upload = true')
@@ -126,19 +144,77 @@ def check_directory(root: str | Path):
126
144
  raise _invalid('uploaded Datasets are private; remove private = false from dataset.toml')
127
145
  if identity.get('type', 'environment') != 'environment':
128
146
  raise _invalid('only Harbor task Datasets (type environment) can be registered')
129
- declared = {task.get('name'): task.get('digest') for task in document.get('tasks', [])}
147
+ stale = [(name, declared, actual) for name, declared, actual in _task_digests(root, document) if declared != actual]
148
+ if stale:
149
+ error = _invalid(f'{len(stale)} Task digest(s) in dataset.toml do not match the Task files; '
150
+ 'review the changes, then re-run with --update-digests (SDK: update_digests=True) to write them')
151
+ error.details = [f'Task {name}: dataset.toml has {declared}; its files hash to {actual}' for name, declared, actual in stale]
152
+ raise error
130
153
  for child in sorted(root.iterdir()):
131
154
  task = child / 'task.toml'
132
155
  if not child.is_dir() or child.is_symlink() or not task.is_file():
133
156
  continue
134
157
  name = tomllib.loads(task.read_text()).get('task', {}).get('name')
135
- if name in declared and declared[name] != (actual := _fingerprint(child)):
136
- raise _invalid(f'Task {name} digest in dataset.toml is {declared[name]}; its files hash to {actual}')
137
158
  if (size := _task_archive_size(child)) > MAX_TASK_DELIVERY_BYTES:
138
159
  raise _invalid(f'Task {name} packs to {size} bytes; the Task delivery limit is {MAX_TASK_DELIVERY_BYTES} bytes '
139
160
  f'({MAX_TASK_DELIVERY_BYTES // 1024 ** 2} MiB). Put large static world files in the pinned world image.')
140
161
 
141
162
 
163
+ def update_task_digests(root: str | Path) -> list[dict[str, str]]:
164
+ """Rewrite stale `[[tasks]].digest` values in dataset.toml from the Task files; explicit opt-in only.
165
+
166
+ Only existing digest strings of declared Tasks change: no Task is added, removed or renamed, and
167
+ the rest of the file keeps its bytes. The whole directory is checked against the candidate file
168
+ first, and the file is replaced atomically, so a failed check or refusal leaves it untouched.
169
+ An unchanged directory is not written. Returns [{"task", "previous", "digest"}] for changed Tasks.
170
+ Content already published under a version stays immutable on the platform; publish changed
171
+ Tasks under a new version.
172
+ """
173
+ root = Path(root)
174
+ manifest = root / 'dataset.toml'
175
+ if not root.is_dir() or manifest.is_symlink() or not manifest.is_file():
176
+ raise _invalid('--update-digests needs a Dataset directory with dataset.toml at its root, not a tar bundle')
177
+ text = manifest.read_bytes().decode('utf-8')
178
+ document = tomllib.loads(text)
179
+ stale = [(name, declared, actual) for name, declared, actual in _task_digests(root, document) if declared != actual]
180
+ if not stale:
181
+ check_directory(root)
182
+ return []
183
+ manual = [f'Task {name}: set digest = "{actual}"' for name, _, actual in stale]
184
+ replacements: dict[str, str] = {}
185
+ for name, declared, actual in stale:
186
+ if not isinstance(declared, str) or not re.fullmatch(r'sha256:[0-9a-f]{64}', declared) or replacements.get(declared, actual) != actual:
187
+ error = _invalid(f'cannot rewrite the digest of Task {name} in place; dataset.toml was not changed. Set the values by hand')
188
+ error.details = manual
189
+ raise error
190
+ replacements[declared] = actual
191
+ declaring = [task.get('digest') for task in document.get('tasks', []) if isinstance(task, dict)]
192
+ candidate = text
193
+ for old, new in replacements.items():
194
+ if candidate.count(old) != declaring.count(old):
195
+ error = _invalid('dataset.toml repeats a Task digest outside [[tasks]]; it was not changed. Set the values by hand')
196
+ error.details = manual
197
+ raise error
198
+ candidate = candidate.replace(old, new)
199
+ expected = dict(document, tasks=[dict(task, digest=replacements.get(task.get('digest'), task.get('digest')))
200
+ if isinstance(task, dict) and 'digest' in task else task for task in document.get('tasks', [])])
201
+ if tomllib.loads(candidate) != expected:
202
+ error = _invalid('dataset.toml could not be rewritten without changing other values; it was not changed. Set the values by hand')
203
+ error.details = manual
204
+ raise error
205
+ check_directory(root, manifest_text=candidate)
206
+ descriptor, temporary = tempfile.mkstemp(prefix='.dataset.toml.', dir=root)
207
+ try:
208
+ with os.fdopen(descriptor, 'w', encoding='utf-8', newline='') as output:
209
+ output.write(candidate)
210
+ os.chmod(temporary, stat.S_IMODE(manifest.stat().st_mode))
211
+ os.replace(temporary, manifest)
212
+ except BaseException:
213
+ Path(temporary).unlink(missing_ok=True)
214
+ raise
215
+ return [{'task': name, 'previous': declared, 'digest': actual} for name, declared, actual in stale]
216
+
217
+
142
218
  def pack(root: str | Path, output: IO[bytes]):
143
219
  """Deterministic tar: sorted, numeric owner 0, mtime 0, 0644/0755 modes; .git is not uploaded."""
144
220
  root = Path(root)
@@ -211,11 +287,20 @@ class Registrations:
211
287
  details=cast(Any, {'data_id': data_id}))
212
288
  return view
213
289
 
214
- def publish(self, source: str | Path, *, dataset: str, version: str, idempotency_key: str | None = None, progress: Callable[[Any], None] | None = None):
215
- """Publish a directory or tar bundle through the resumable #990 upload; rerun resumes."""
290
+ def publish(self, source: str | Path, *, dataset: str, version: str, idempotency_key: str | None = None, progress: Callable[[Any], None] | None = None,
291
+ update_digests: bool = False, digests: Callable[[list[dict[str, str]]], None] | None = None):
292
+ """Publish a directory or tar bundle through the resumable #990 upload; rerun resumes.
293
+
294
+ `update_digests` first rewrites stale Task digests in the directory's dataset.toml (see `update_task_digests`);
295
+ `digests` receives the changed Tasks.
296
+ """
216
297
  if not isinstance(dataset, str) or not NAME.fullmatch(dataset):
217
298
  raise ValueError('dataset must be NAMESPACE/NAME')
218
299
  source = Path(source)
300
+ if update_digests:
301
+ changed = update_task_digests(source)
302
+ if digests:
303
+ digests(changed)
219
304
  with tempfile.TemporaryDirectory(prefix='envloop-upload-') as temporary:
220
305
  if source.is_dir():
221
306
  check_directory(source)
@@ -4,6 +4,8 @@ from typing import Any
4
4
 
5
5
  from envloop.resource_cli import listing
6
6
 
7
+ JSON_DEFAULT_HELP = 'Output the complete response as JSON (the default; accepted for consistency with list commands)'
8
+
7
9
 
8
10
  def add_resource_commands(groups: "argparse._SubParsersAction[argparse.ArgumentParser]"):
9
11
  datasets = groups.add_parser('dataset', help='Discover Datasets, revisions and tasks').add_subparsers(dest='action', required=True)
@@ -33,6 +35,7 @@ def add_resource_commands(groups: "argparse._SubParsersAction[argparse.ArgumentP
33
35
  command.add_argument('data_id', metavar='DATA_ID', help='Runner Data ID or immutable ANS URI')
34
36
  if action == 'delete':
35
37
  command.add_argument('--dry-run', action='store_true', help='Preview retirement without changing the resource')
38
+ command.add_argument('--json', action='store_true', help=JSON_DEFAULT_HELP)
36
39
  for action in ('create', 'update'):
37
40
  command = runners.add_parser(action, help='Create a Runner revision from a directory' if action == 'create' else 'Publish a new immutable revision of an existing Runner',
38
41
  description='Publish DIRECTORY through the same public Data API as el data create --type runner or el data update. '
@@ -43,6 +46,7 @@ def add_resource_commands(groups: "argparse._SubParsersAction[argparse.ArgumentP
43
46
  if action == 'update':
44
47
  command.add_argument('data_id', metavar='DATA_ID')
45
48
  runner_package_arguments(command)
49
+ command.add_argument('--json', action='store_true', help=JSON_DEFAULT_HELP)
46
50
 
47
51
  checkpoints = groups.add_parser('checkpoint', help='List, share and download saved training Checkpoints').add_subparsers(dest='action', required=True)
48
52
  upload = checkpoints.add_parser('upload', help='Upload actual saved checkpoint bytes from a managed Train worker')
envloop_experiment/cli.py CHANGED
@@ -251,9 +251,16 @@ def add_commands(groups: "argparse._SubParsersAction[argparse.ArgumentParser]"):
251
251
  artifact_list.add_argument("--json", action="store_true")
252
252
  download = artifacts.add_parser("download", help="Download all uploaded artifacts and verify their sizes and hashes")
253
253
  download.add_argument("trial_id", metavar="TRIAL_ID")
254
- download.add_argument("directory", metavar="DIRECTORY", type=Path)
254
+ download.add_argument("directory", metavar="DIRECTORY", type=Path, nargs="?",
255
+ help="Destination directory (same as --output)")
256
+ download.add_argument("--output", type=Path, metavar="DIRECTORY",
257
+ help="Destination directory, as in el data download --output; give it or DIRECTORY, not both")
255
258
 
256
259
  def validate(args: argparse.Namespace, cli: argparse.ArgumentParser):
260
+ if args.group == "trial" and args.action == "artifact" and args.artifact_action == "download":
261
+ if (args.directory is None) == (args.output is None):
262
+ cli.error("give the destination as DIRECTORY or --output DIRECTORY, exactly once")
263
+ args.directory = args.directory or args.output
257
264
  if args.group == "job" and args.action == "decision":
258
265
  from envloop_experiment.decision import DecisionClient
259
266
  try:
@@ -127,8 +127,22 @@ def configure_transport(transport: Any):
127
127
  cast(Any, transport)._request_policy = request_policy
128
128
 
129
129
 
130
+ READ_RETRY_DELAYS = (1.0, 2.0)
131
+ READ_RETRY_CODES = frozenset({'REQUEST_TIMEOUT', 'RESPONSE_INTERRUPTED'})
132
+
133
+
130
134
  def request_policy(self: Any, method: str, path: str, body: Any, headers: Any):
131
135
  from envloop import http as base_http
136
+ if method == 'GET':
137
+ import time
138
+ for delay in READ_RETRY_DELAYS:
139
+ try:
140
+ return self._send(method, path, body, headers, self.timeout)
141
+ except RemoteError as error:
142
+ if error.status_code is not None or error.code not in READ_RETRY_CODES:
143
+ raise
144
+ time.sleep(delay)
145
+ return self._send(method, path, body, headers, self.timeout)
132
146
  if method != 'POST' or path != '/v1/jobs':
133
147
  return self._send(method, path, body, headers, self.timeout)
134
148
  try: