envloop-cli 2.0.0__py3-none-any.whl → 2.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
envloop/cli.py CHANGED
@@ -278,6 +278,9 @@ def _main(argv: list[str] | None = None):
278
278
  if args.group == 'setting' and args.action == 'update' and not any(getattr(args, key) is not None for key in ('name', 'slug', 'region')):
279
279
  cli.error('provide at least one of --name, --slug or --region')
280
280
  try:
281
+ if args.group == 'job' and args.action == 'chat':
282
+ from envloop_chat.client import require_dependencies
283
+ require_dependencies()
281
284
  if args.group == 'loop':
282
285
  from ._optional import feature_module
283
286
  feature_module('rsi-loop', 'loop_cli').validate(args)
envloop/cli_errors.py CHANGED
@@ -56,7 +56,7 @@ _register("RUNNER_PACKAGE_INVALID", "The Runner package directory is invalid. It
56
56
  _register("RUNNER_REVISION_INVALID", "Use the full lowercase 40- or 64-character source commit, or a local branch or tag name, as --revision and a NAMESPACE/NAME Runner name.")
57
57
  _register("RUNNER_REVISION_UNRESOLVED", "--revision names no local branch or tag in the Git checkout that holds DIRECTORY, or Git is unavailable. Fetch or create the branch, or pass the full source commit.")
58
58
  _register("RUNNER_PACKAGE_UNCOMMITTED", "DIRECTORY differs from the --revision commit: it has uncommitted changes, untracked files or ignored files, all of which would be published. Commit or remove them, or pass a full commit you vouch for.")
59
- _register("RUNNER_SOURCE_REF_INVALID", "Use a branch or tag name such as main or v1 with --source-ref-kind branch, tag or commit; HEAD, latest, default, release, '..', spaces and ~^:?*[\\ are not allowed.")
59
+ _register("RUNNER_COMMIT_METADATA_INVALID", "Git author and message must be single-line text of at most 256 and 4096 characters, respectively.")
60
60
  _register("RUNNER_REVISION_CONFLICT", "The platform catalog holds different package or index hashes for this Runner revision. Publish a new revision instead of changing an existing one.")
61
61
  _register("RECIPE_PACKAGE_INVALID RECIPE_DECLARATION_INVALID RECIPE_INVALID", "--directory must hold recipe.toml with schema_version = \"envloop.recipe/v3\" and the tables [recipe] name, types; [runner] name, abi; [source] paths, optional exclude and optional repository (a https://github.com/OWNER/REPO URL if given; omit it for a local-only repository); optional [inputs], [params], [outputs] and [dependencies]. No other top-level tables or keys are allowed.")
62
62
  _register("RECIPE_PACKAGE_SCHEMA_RETIRED", "recipe.toml uses the retired envloop.recipe-publication/v3 format. Rewrite it as schema_version = \"envloop.recipe/v3\" with [recipe], [runner] and [source] tables and add entrypoint.sh next to it; published Recipes stay readable.")
@@ -162,6 +162,8 @@ _register("RESOURCE_IN_USE", "Remove or release the listed references first. A r
162
162
  _register("PUBLIC_DEPENDENCY_UNAVAILABLE", "A shared resource needs dependencies at least as readable as itself: a public Recipe needs public dependencies, and an internal Recipe needs dependencies readable in this workspace (internal or public). Change the dependencies' visibility first (the owning resource set-visibility ASSET_ID), then retry; private dependencies are never shared automatically.")
163
163
  _register("PUBLIC_CONTENT_UNSAFE PUBLICATION_REVIEW_REQUIRED", "Content review failed for one of this name's current revisions, so it cannot be shared. Fix or retire the flagged revision, then retry.")
164
164
  _register("CHECKPOINT_AMBIGUOUS", "More than one checkpoint matches this selection.")
165
+ _register("CHECKPOINT_METADATA_PENDING", "Checkpoint files are committed, but their metadata is not complete. Retry checkpoint upload complete with the same OPERATION_ID; keep the original tags and do not upload the files again.")
166
+ _register("ASSET_PIN_CONFLICT", "This immutable asset already has different content or tags. Keep the existing publication unchanged and use a new immutable asset identity for a different publication.")
165
167
  _register("CHECKPOINT_UPLOAD_UNAVAILABLE", "The platform checkpoint upload service is unavailable. Ask a platform operator to check the upload service and temporary-credential configuration, then let the worker retry.")
166
168
  _register("CHECKPOINT_UPLOAD_FORBIDDEN", "Checkpoint publication requires the current Train worker's platform-issued credential in its own workspace and project. Check the worker connection and checkpoints.write permission.")
167
169
  _register("CHECKPOINT_UPLOAD_CLOSED", "The checkpoint upload session or its producing Trial is no longer open for publication. Check the Trial state and worker credential expiry; a stopped Trial cannot publish.")
@@ -174,6 +176,7 @@ _register("CHECKPOINT_FILES_UNAVAILABLE ARTIFACT_NOT_READY", "The requested down
174
176
  _register("CHECKPOINT_FILES_INVALID ARTIFACT_LISTING_INVALID ARTIFACT_NAME_UNSAFE UNSAFE_ARTIFACT_REDIRECT ARTIFACT_SIZE_MISMATCH ARTIFACT_HASH_MISMATCH", "The download failed a safety or integrity check.")
175
177
  _register("ARTIFACT_DOWNLOAD_FAILED", "The artifact download service rejected the request.")
176
178
  _register("ENDPOINT_NOT_READY", "The inference endpoint is not ready.")
179
+ _register("CHAT_TEXT_UNAVAILABLE", "The model did not return a text answer. Use --json to inspect the complete response.")
177
180
  _register("WAIT_TIMEOUT", "The resource did not reach the requested state before the wait timeout.")
178
181
  _register("CLEANUP_INCOMPLETE", "The persisted cleanup operation did not complete successfully.")
179
182
  _register("CLI_ERROR", "The command could not be completed.")
@@ -294,7 +297,7 @@ def _http_message(status: int | None) -> str:
294
297
  return _MESSAGES["HTTP_ERROR"]
295
298
 
296
299
 
297
- _OWN_PACKAGES = frozenset({"envloop", "envloop_asset", "envloop_experiment", "envloop_rsi_loop"})
300
+ _OWN_PACKAGES = frozenset({"envloop", "envloop_asset", "envloop_experiment", "envloop_rsi_loop", "envloop_chat"})
298
301
 
299
302
 
300
303
  def validation_message(error: BaseException) -> str | None:
envloop/http.py CHANGED
@@ -21,23 +21,25 @@ REDIRECT_STATUSES = {301, 302, 303, 307, 308}
21
21
  RESOLVED_OWNER_FIELDS = ("dataset_owners", "checkpoint_owners", "checkpoint_owner", "runner_owner", "runner_storage_prefix")
22
22
 
23
23
 
24
- def validate_public_execution(value: Any, *, allow_local_sandbox: bool = True) -> None:
25
- """Only an explicit top-level local Sandbox selection is public."""
24
+ def validate_public_execution(value: Any, *, allow_sandbox_provider: bool = True) -> None:
25
+ """Allow provider selection only on the outer Bench/Sandbox submit request."""
26
26
  if not isinstance(value, dict):
27
27
  return
28
- spec = value.get("spec")
29
- if any(key in value for key in RESOLVED_OWNER_FIELDS) or isinstance(spec, dict) and any(key in spec for key in RESOLVED_OWNER_FIELDS):
28
+ if any(key in value for key in RESOLVED_OWNER_FIELDS):
30
29
  raise ValueError("the owning project of each input is resolved by the platform; select a Dataset copy by its "
31
30
  "asset_id and remove dataset_owners, checkpoint_owners, checkpoint_owner and runner_owner")
32
31
  if any(key in value for key in ("executor", "backend")):
33
32
  raise ValueError("execution backend is configured by the server")
34
- if "provider" in value and not (allow_local_sandbox and value.get("type") == "sandbox" and value["provider"] == "local"):
35
- raise ValueError("provider must be local and requires a Sandbox Job")
33
+ if "provider" in value:
34
+ spec = value.get("spec")
35
+ kind = spec.get("type") if isinstance(spec, dict) and spec.get("schema") == "envloop.job/v2" else value.get("type")
36
+ if not (allow_sandbox_provider and kind in {"bench", "sandbox"} and value.get("type", kind) == kind):
37
+ raise ValueError("provider is only accepted as a top-level Bench/Sandbox Job submission field")
36
38
  execution = value.get("execution")
37
39
  if isinstance(execution, dict) and any(key in execution for key in ("executor", "provider", "backend")):
38
40
  raise ValueError("execution backend is configured by the server")
39
- for key in ("profile", "profile_overrides", "params"):
40
- validate_public_execution(value.get(key), allow_local_sandbox=False)
41
+ for key in ("spec", "overrides", "profile", "profile_overrides", "params"):
42
+ validate_public_execution(value.get(key), allow_sandbox_provider=False)
41
43
 
42
44
 
43
45
  class WaitTimeoutError(TimeoutError):
envloop_asset/assets.py CHANGED
@@ -167,6 +167,9 @@ class ContentResource:
167
167
  from .publications import INLINE_BYTES, hf_source, prepare, publication_ref
168
168
  if type(wait) is not bool or not 0 <= timeout < float('inf'):
169
169
  raise ValueError('wait must be boolean and timeout must be nonnegative')
170
+ if self.kind == 'checkpoint' and source.get('tags') is not None:
171
+ from .tags import validate_checkpoint_tags
172
+ source['tags'] = validate_checkpoint_tags(source['tags'])
170
173
  if self.kind == 'recipe' and version is not None:
171
174
  raise ValueError('Recipe versions are derived from content; omit --version')
172
175
  source_format = source.pop('format', None)
@@ -179,22 +182,24 @@ class ContentResource:
179
182
  if update_digests:
180
183
  raise ValueError('--update-digests requires --format harbor')
181
184
  if self.kind == 'checkpoint' and source.get('result') is not None:
182
- if name is not None or version is not None or any(value is not None for key,value in source.items() if key not in {'result','directory','checkpoint_name'}):
183
- raise ValueError('Worker Checkpoints accept only saved result, directory and checkpoint_name')
185
+ if name is not None or version is not None or any(value is not None for key,value in source.items() if key not in {'result','directory','checkpoint_name','tags'}):
186
+ raise ValueError('Worker Checkpoints accept only saved result, directory, checkpoint_name and tags')
184
187
  if parent is not None:
185
188
  raise ValueError('A worker publishes each new save with create, never update')
186
- from .direct_checkpoint import publish
189
+ from .direct_checkpoint import check_metadata, publish
187
190
  from .direct_storage import _DomainTransport
188
191
  adapter = _DomainTransport(self.transport,'checkpoints')
192
+ tags = source.pop('tags', None)
189
193
  try:
190
194
  receipt = publish(adapter, source.pop('directory'), result=source.pop('result'),
191
- checkpoint_name=source.pop('checkpoint_name', None), single=True,
195
+ checkpoint_name=source.pop('checkpoint_name', None), tags=tags, single=True,
192
196
  upload_path=scope(self.transport) + '/checkpoints/uploads')
197
+ value = self.get(receipt.get('asset_id') or receipt['uri'])
198
+ check_metadata(value, tags=tags)
193
199
  except BaseException as error:
194
200
  if adapter.last is not None:
195
201
  cast(Any,error).last = adapter.last
196
202
  raise
197
- value = self.get(receipt.get('asset_id') or receipt['uri'])
198
203
  asset = value['asset']
199
204
  asset['details'] = {**receipt, 'durable':True, 'upload_actor':'worker', **asset.get('details',{})}
200
205
  return value
@@ -408,7 +413,11 @@ class ContentResource:
408
413
  return envelope(self.transport.request('GET', self._operation_path(operation_id)))
409
414
 
410
415
  def upload_complete(self, operation_id: str) -> dict[str, Any]:
411
- return envelope(self.transport.request('POST', self._operation_path(operation_id) + '/complete'))
416
+ value = envelope(self.transport.request('POST', self._operation_path(operation_id) + '/complete'))
417
+ if self.kind == 'checkpoint':
418
+ from .direct_checkpoint import check_metadata
419
+ check_metadata(value)
420
+ return value
412
421
 
413
422
  def upload_abort(self, operation_id: str) -> dict[str, Any]:
414
423
  return envelope(self.transport.request('POST', self._operation_path(operation_id) + '/abort'))
@@ -46,8 +46,8 @@ def list_layout(items: list[dict[str, Any]], args: argparse.Namespace) -> tuple[
46
46
  # Like el dataset list: STATUS / UNAVAILABLE REASON appear when the page reports them, so a
47
47
  # Revision that differs between shared copies (RUNNER_REVISION_AMBIGUOUS) is visible in the table.
48
48
  states = tuple(field for field in ('status', 'unavailable_reason') if any(field in item for item in items))
49
- headers = ('NAME', 'REVISION', 'SOURCE REF', 'VISIBILITY', *(field.replace('_', ' ').upper() for field in states), *LIFECYCLE)
50
- render = lambda item: (item.get('name'), item.get('revision'), item.get('source_ref'),
49
+ headers = ('NAME', 'REVISION', 'AUTHOR', 'MESSAGE', 'VISIBILITY', *(field.replace('_', ' ').upper() for field in states), *LIFECYCLE)
50
+ render = lambda item: (item.get('name'), item.get('revision'), item.get('author'), item.get('message'),
51
51
  item.get('visibility'), *(item.get(field) for field in states), *lifecycle(item))
52
52
  empty = 'No runners found.'
53
53
  elif args.group == 'dataset' and args.action == 'list':
envloop_asset/client.py CHANGED
@@ -281,32 +281,29 @@ class Runners:
281
281
  from .execution_content import ExecutionContent
282
282
  return download_content(ExecutionContent(self._server,'runner'),ref,output,file_id=file_id,**selection)
283
283
 
284
- def create(self, directory: str | Path, *, revision: str, name: str | None = None,
285
- executables: Sequence[str] | None = None, source_ref: str | None = None,
286
- source_ref_kind: str = 'branch', dry_run: bool = False):
284
+ def create(self, directory: str | Path, *, revision: str = 'main', name: str | None = None,
285
+ executables: Sequence[str] | None = None, dry_run: bool = False):
287
286
  """Create an immutable Runner revision from a local package directory."""
288
287
  return self._publish(directory, revision=revision, name=name, executables=executables,
289
- source_ref=source_ref, source_ref_kind=source_ref_kind, dry_run=dry_run)
288
+ dry_run=dry_run)
290
289
 
291
- def update(self, asset_id: str, directory: str | Path, *, revision: str, name: str | None = None,
292
- executables: Sequence[str] | None = None, source_ref: str | None = None,
293
- source_ref_kind: str = 'branch', dry_run: bool = False):
290
+ def update(self, asset_id: str, directory: str | Path, *, revision: str = 'main', name: str | None = None,
291
+ executables: Sequence[str] | None = None, dry_run: bool = False):
294
292
  """Publish a new immutable revision of the same Runner, preserving historical bytes."""
295
293
  return self._publish(directory, revision=revision, name=name, executables=executables,
296
- source_ref=source_ref, source_ref_kind=source_ref_kind, dry_run=dry_run, asset_id=asset_id)
294
+ dry_run=dry_run, asset_id=asset_id)
297
295
 
298
296
  def _publish(self, directory: str | Path, *, revision: str, name: str | None = None,
299
- executables: Sequence[str] | None = None, source_ref: str | None = None,
300
- source_ref_kind: str = 'branch', dry_run: bool = False, asset_id: str | None = None):
297
+ executables: Sequence[str] | None = None, dry_run: bool = False, asset_id: str | None = None):
301
298
  """Publish a Runner package directory as the immutable revision NAME@REVISION.
302
299
 
303
300
  This is the Runner domain publication API with the native manifest built
304
301
  from `directory` (runner.toml plus its main.py or main.sh entrypoint): the
305
302
  platform stores the bytes, derives the package and index SHA-256, creates the
306
303
  Runner asset on first use and registers the revision. `revision` is the full
307
- source commit. `source_ref` (for example `main`) then points that name at the
308
- revision through POST /v1/runners/{name}/revisions, so `NAME@main` resolves to
309
- it. Returns `{'asset': publication, 'runner': catalog revision}`; a dry run
304
+ source commit or a local branch/tag, resolved once to its full commit. Branch
305
+ and tag names remain selectable after registration. Author and message
306
+ come from this commit; a detached package leaves unknown metadata empty. Returns `{'asset': publication, 'runner': catalog revision}`; a dry run
310
307
  returns the server's validation result without publishing.
311
308
  """
312
309
  from envloop.http import RemoteError
@@ -314,15 +311,22 @@ class Runners:
314
311
  from envloop_asset.runner_packages import (
315
312
  REFERENCE_KEYS,
316
313
  REVISION,
317
- SOURCE_REF_KINDS,
314
+ commit_metadata,
315
+ resolve_source_revision,
318
316
  runner_package,
319
- source_ref_valid,
320
317
  )
321
318
 
322
- if not isinstance(revision, str) or not REVISION.fullmatch(revision) or name is not None and not isinstance(name, str):
319
+ if not isinstance(revision, str) or name is not None and not isinstance(name, str):
323
320
  raise RemoteError('RUNNER_REVISION_INVALID')
324
- if source_ref is not None and (not source_ref_valid(source_ref) or source_ref_kind not in SOURCE_REF_KINDS):
325
- raise RemoteError('RUNNER_SOURCE_REF_INVALID')
321
+ requested_revision = None
322
+ if not REVISION.fullmatch(revision):
323
+ if len(revision) >= 40 and all(character in '0123456789abcdefABCDEF' for character in revision):
324
+ raise RemoteError('RUNNER_REVISION_INVALID')
325
+ selected = revision
326
+ revision, kind = resolve_source_revision(directory, selected)
327
+ prefix = 'refs/heads/' if kind == 'branch' else 'refs/tags/'
328
+ requested_revision = selected if selected.startswith(prefix) else prefix + selected
329
+ metadata = commit_metadata(directory, revision)
326
330
  name, manifest, files, executables = runner_package(directory, name=name, executables=executables)
327
331
  ref = f'envloop://runners/{name}@{revision}'
328
332
  data = ExecutionContent(self._server, 'runner')
@@ -339,11 +343,11 @@ class Runners:
339
343
  or any(not isinstance(pinned.get(key), str) for key in REFERENCE_KEYS)):
340
344
  raise RemoteError('INVALID_RESPONSE')
341
345
  reference = {key: pinned[key] for key in REFERENCE_KEYS}
342
- if source_ref is None:
346
+ if requested_revision is None and not metadata:
343
347
  runner = self._server.get_runner_revision(name, revision)
344
348
  else:
345
349
  runner = self._server.register_runner_revision(
346
- name, {**reference, 'source_ref': source_ref, 'source_ref_kind': source_ref_kind})
350
+ name, {**reference, **metadata, **({'requested_revision': requested_revision} if requested_revision else {})})
347
351
  # Both catalog views must name the same stored bytes.
348
352
  if not isinstance(runner, dict) or any(runner.get(key) != value for key, value in reference.items()):
349
353
  raise RemoteError('RUNNER_REVISION_CONFLICT')
@@ -2,8 +2,9 @@
2
2
  import json
3
3
  import re
4
4
  import stat
5
+ from collections.abc import Mapping
5
6
  from pathlib import Path
6
- from typing import Any
7
+ from typing import Any, cast
7
8
 
8
9
  from envloop.http import RemoteError
9
10
 
@@ -17,6 +18,7 @@ from .direct_storage import (
17
18
  _Storage,
18
19
  )
19
20
  from .publications import open_file
21
+ from .tags import validate_checkpoint_tags, validate_tags
20
22
 
21
23
 
22
24
  def _inventory(saved: Path) -> list[dict[str, Any]]:
@@ -99,7 +101,40 @@ def _receipt(value: Any, *, step: int, uri: str | None = None) -> dict[str, Any]
99
101
  return receipt
100
102
 
101
103
 
102
- def publish(transport: Any, directory: str | Path, *, result: str | Path | dict[str, Any], upload_path: str, checkpoint_name: str | None = None, single: bool = False) -> dict[str, Any]:
104
+ def check_metadata(value: dict[str, Any], *, tags: Mapping[str, str] | None = None) -> dict[str, Any]:
105
+ """A byte receipt alone does not finish a labelled publication."""
106
+ operation = value.get('operation')
107
+ operation = operation if isinstance(operation, dict) else {}
108
+ upload = operation.get('upload')
109
+ upload = upload if isinstance(upload, dict) else {}
110
+ state = upload.get('state')
111
+ failure = operation.get('error')
112
+ code = failure.get('code') if isinstance(failure, dict) else None
113
+ if state == 'metadata_conflict' or code == 'ASSET_PIN_CONFLICT':
114
+ error = RemoteError('ASSET_PIN_CONFLICT', 409)
115
+ elif (state == 'metadata_pending' or code == 'CHECKPOINT_METADATA_PENDING'
116
+ or state == 'committed' and operation.get('status') != 'succeeded'):
117
+ error = RemoteError('CHECKPOINT_METADATA_PENDING', 503)
118
+ else:
119
+ labels = tags if tags is not None else upload.get('tags') if state == 'committed' else None
120
+ try:
121
+ labels = validate_tags(labels) if labels is not None else {}
122
+ except ValueError:
123
+ error = RemoteError('INVALID_RESPONSE')
124
+ else:
125
+ asset = value.get('asset')
126
+ details = asset.get('details') if isinstance(asset, dict) else None
127
+ actual = (details.get('tags') if isinstance(details, dict) and 'tags' in details
128
+ else asset.get('tags') if isinstance(asset, dict) else None)
129
+ if not labels or isinstance(actual, dict) and all(actual.get(key) == item for key, item in labels.items()):
130
+ return value
131
+ error = RemoteError('CHECKPOINT_METADATA_PENDING', 503)
132
+ cast(Any, error).last = value
133
+ raise error
134
+
135
+
136
+ def publish(transport: Any, directory: str | Path, *, result: str | Path | dict[str, Any], upload_path: str, checkpoint_name: str | None = None, tags: Mapping[str, str] | None = None, single: bool = False) -> dict[str, Any]:
137
+ labels = validate_checkpoint_tags(tags) if tags is not None else None
103
138
  prepared = _prepare(directory, result)
104
139
  if single:
105
140
  if checkpoint_name is None and len(prepared) != 1:
@@ -112,7 +147,10 @@ def publish(transport: Any, directory: str | Path, *, result: str | Path | dict[
112
147
  for item, saved, entries in prepared:
113
148
  descriptor = {key: item[key] for key in ('step', 'kind', 'model', 'model_revision', 'directory', 'format') if key in item}
114
149
  descriptor['name'] = f"checkpoint-{item['step']}"
115
- session = _request(transport, upload_path, dict(type='checkpoint', checkpoint=descriptor, files=entries),
150
+ body = dict(type='checkpoint', checkpoint=descriptor, files=entries)
151
+ if labels is not None:
152
+ body['tags'] = labels
153
+ session = _request(transport, upload_path, body,
116
154
  phase='checkpoint_upload_init')
117
155
  if isinstance(session, dict) and session.get('state') == 'committed':
118
156
  receipt = _receipt(session, step=item['step'])
@@ -1,14 +1,54 @@
1
1
  """Coordinate Checkpoint upload plans, provider strategies and metadata-only completion."""
2
2
  import hashlib
3
3
  import re
4
+ import socket
5
+ import ssl
4
6
  from typing import Any
5
- from urllib.error import HTTPError
7
+ from urllib.error import HTTPError, URLError
6
8
  from urllib.parse import urlencode
7
9
 
8
10
  from envloop.http import RemoteError
9
11
  from envloop_asset.upload_strategy import strategy_for
10
12
 
11
13
 
14
+ def storage_failure(error: Exception) -> RemoteError:
15
+ reason = error.reason if isinstance(error, URLError) else error
16
+ response = getattr(error, 'response', None)
17
+ response = response if isinstance(response, dict) else {}
18
+ storage_error = response.get('Error')
19
+ storage_error = storage_error if isinstance(storage_error, dict) else {}
20
+ metadata = response.get('ResponseMetadata')
21
+ metadata = metadata if isinstance(metadata, dict) else {}
22
+ transport_kind = {'ConnectTimeoutError': 'timeout', 'ReadTimeoutError': 'timeout',
23
+ 'SSLError': 'tls_error', 'EndpointConnectionError': 'connection_error',
24
+ 'ConnectionClosedError': 'connection_error', 'ProxyConnectionError': 'connection_error'}
25
+ kind = ('http_error' if isinstance(error, HTTPError) or storage_error else
26
+ transport_kind[type(error).__name__] if type(error).__name__ in transport_kind else
27
+ 'timeout' if isinstance(reason, TimeoutError) else
28
+ 'tls_error' if isinstance(reason, ssl.SSLError) else
29
+ 'dns_error' if isinstance(reason, socket.gaierror) else
30
+ 'connection_error' if isinstance(reason, ConnectionError) else 'transport_error')
31
+ details = ['Storage failure: ' + kind]
32
+ allowed = {'SignatureDoesNotMatch', 'AccessDenied', 'ExpiredToken', 'RequestTimeTooSkewed',
33
+ 'RequestExpired', 'SlowDown', 'ServiceUnavailable', 'InternalError',
34
+ 'XAmzContentSHA256Mismatch', 'InvalidRequest', 'EntityTooLarge',
35
+ 'AuthorizationQueryParametersError', 'RequestTimeout'}
36
+ status = error.code if isinstance(error, HTTPError) else metadata.get('HTTPStatusCode')
37
+ if type(status) is int and 400 <= status <= 599:
38
+ details.append('Storage HTTP status: ' + str(status))
39
+ code = storage_error.get('Code')
40
+ if isinstance(error, HTTPError):
41
+ try:
42
+ body = error.read(4096)
43
+ except Exception:
44
+ body = b''
45
+ match = re.search(rb'<Code>([A-Za-z][A-Za-z0-9]{0,63})</Code>', body)
46
+ code = match.group(1).decode('ascii') if match is not None else None
47
+ if isinstance(code, str) and code in allowed:
48
+ details.append('Storage error code: ' + code)
49
+ return RemoteError('CHECKPOINT_STORAGE_UPLOAD_FAILED', details=details)
50
+
51
+
12
52
  def upload_part(transport: Any, upload_path: str, number: int, content: bytes) -> dict[str, Any]:
13
53
  digest = hashlib.sha256(content).hexdigest()
14
54
  path = upload_path + f'/parts/{number}'
@@ -30,16 +70,14 @@ def upload_part(transport: Any, upload_path: str, number: int, content: bytes) -
30
70
  try:
31
71
  strategy_for(plan.get('provider')).upload(plan, content, api_base=transport.base)
32
72
  except Exception as error:
73
+ failure = error if isinstance(error, RemoteError) else storage_failure(error)
33
74
  if isinstance(error, HTTPError):
34
75
  error.close()
35
76
  try:
36
77
  report('failed')
37
78
  except Exception:
38
79
  pass
39
- if isinstance(error, RemoteError):
40
- raise
41
- # Storage exceptions can contain the signed URL. Never include their message in a CLI error.
42
- raise RemoteError('CHECKPOINT_STORAGE_UPLOAD_FAILED') from None
80
+ raise failure from None
43
81
  result = report('stored')
44
82
  if result != expected:
45
83
  raise RemoteError('INVALID_RESPONSE')
@@ -153,8 +153,9 @@ class _Storage:
153
153
  if code in ('ExpiredToken', 'ExpiredTokenException', 'InvalidToken') and attempt < 2:
154
154
  self.renew()
155
155
  continue
156
- # Storage exceptions may contain signed URLs, headers or credential material.
157
- raise RemoteError(self.kind.upper() + '_STORAGE_UPLOAD_FAILED', phase=self.kind + '_upload_storage') from None
156
+ from .direct_publication import storage_failure
157
+ raise RemoteError(self.kind.upper() + '_STORAGE_UPLOAD_FAILED', phase=self.kind + '_upload_storage',
158
+ details=storage_failure(error).details) from None
158
159
  raise RemoteError(self.kind.upper() + '_STORAGE_UPLOAD_FAILED', phase=self.kind + '_upload_storage')
159
160
 
160
161
  def send(self, saved: Path, entry: dict[str, Any]) -> None:
@@ -229,6 +230,9 @@ class _DomainTransport:
229
230
  if not isinstance(value,dict) or 'asset' not in value:
230
231
  return value
231
232
  self.last = value
233
+ if self.collection == 'checkpoints':
234
+ from .direct_checkpoint import check_metadata
235
+ check_metadata(value)
232
236
  operation = value.get('operation')
233
237
  if isinstance(operation,dict) and isinstance(operation.get('upload'),dict):
234
238
  upload_id, operation_id = operation['upload'].get('upload_id'), operation.get('operation_id')
@@ -12,7 +12,7 @@ from pathlib import Path
12
12
  from typing import Any
13
13
 
14
14
  from envloop.http import RemoteError
15
- from envloop_asset.runner_packages import REVISION, source_ref_valid
15
+ from envloop_asset.runner_packages import REVISION, revision_valid
16
16
 
17
17
  DECLARATION = 'recipe.toml'
18
18
  GIT_TIMEOUT = 60
@@ -56,7 +56,7 @@ class _Repository:
56
56
  if found.returncode == 0 and found.stdout.decode().strip() == ref:
57
57
  return ref, 'commit'
58
58
  raise RemoteError('RECIPE_REVISION_UNRESOLVED')
59
- if not source_ref_valid(ref):
59
+ if not revision_valid(ref):
60
60
  raise RemoteError('RECIPE_REVISION_INVALID')
61
61
  for kind, prefix in (('branch', 'refs/heads/'), ('tag', 'refs/tags/')):
62
62
  found = self.git('rev-parse', '--verify', '--quiet', f'{prefix}{ref}^{{commit}}')
@@ -46,7 +46,7 @@ def add_resource_commands(groups: "argparse._SubParsersAction[argparse.ArgumentP
46
46
  command.add_argument('--revision', help='Full immutable source commit')
47
47
  command.add_argument('--idempotency-key')
48
48
  command.add_argument('--ref', dest='publication_ref', help='Exact immutable ANS reference; must agree with the declaration')
49
- command.add_argument('--tags', help='Custom key:value labels')
49
+ command.add_argument('--tags', help='String labels as key:value,key:value or a JSON object')
50
50
  if kind == 'dataset':
51
51
  command.add_argument('--format', choices=('harbor',), help='Convert a native Harbor Dataset before publication')
52
52
  command.add_argument('--update-digests', action='store_true')
@@ -300,10 +300,6 @@ def runner_package_arguments(command: argparse.ArgumentParser):
300
300
  command.add_argument('--name', help='NAMESPACE/NAME; must equal [runner] name in runner.toml (default: that name)')
301
301
  command.add_argument('--executable', action='append', dest='executables', metavar='PATH',
302
302
  help='Declare an executable file; repeat for each. Default: files with an execute bit')
303
- command.add_argument('--source-ref', metavar='REF', help='Also point this branch or tag name (for example main) at the revision, '
304
- 'so NAME@REF resolves to it (default: the branch or tag given as --revision)')
305
- command.add_argument('--source-ref-kind', choices=['branch', 'tag', 'commit'],
306
- help='Kind of --source-ref (default: branch, or the kind of the --revision branch or tag)')
307
303
  command.add_argument('--dry-run', action='store_true', help='Validate the package and authorization without publishing')
308
304
 
309
305
 
@@ -323,26 +319,20 @@ def publish_runner(client: Any, args: argparse.Namespace):
323
319
  import sys
324
320
 
325
321
  from envloop.http import RemoteError
326
- from envloop_asset.runner_packages import REVISION, resolve_source_revision
322
+ from envloop_asset.runner_packages import REVISION
327
323
 
328
- revision, source_ref, source_ref_kind = args.revision, args.source_ref, args.source_ref_kind
329
- if not REVISION.fullmatch(revision):
330
- revision, kind = resolve_source_revision(args.directory, args.revision)
331
- if source_ref is None:
332
- source_ref, source_ref_kind = args.revision, kind
333
- print(f'resolved {kind} {args.revision} to {revision}', file=sys.stderr)
334
324
  try:
335
325
  operation = client.runners.create if args.action == 'create' else client.runners.update
336
326
  positional = (args.directory,) if args.action == 'create' else (args.asset_id, args.directory)
337
- result = operation(*positional, revision=revision, name=args.name,
338
- executables=args.executables, source_ref=source_ref,
339
- source_ref_kind=source_ref_kind or 'branch', dry_run=args.dry_run)
327
+ result = operation(*positional, revision=args.revision, name=args.name,
328
+ executables=args.executables, dry_run=args.dry_run)
340
329
  except RemoteError as error:
341
330
  if error.code in {'ACCESS_DENIED', 'ASSET_ACCESS_REQUIRED'} and not error.hint:
342
331
  error.hint = RUNNER_WRITE_HINT
343
332
  raise
344
333
  if not args.dry_run:
345
334
  runner = result['runner']
346
- moved = f"; {runner['source_ref']} now resolves to it" if runner.get('source_ref') else ''
347
- print(f"{'created' if args.action == 'create' else 'updated'} {runner['uri']} (package sha256 {runner['sha256']}){moved}", file=sys.stderr)
335
+ if not REVISION.fullmatch(args.revision):
336
+ print(f'resolved revision {args.revision} to {runner["revision"]}', file=sys.stderr)
337
+ print(f"{'created' if args.action == 'create' else 'updated'} {runner['uri']} (package sha256 {runner['sha256']})", file=sys.stderr)
348
338
  return result
@@ -15,13 +15,12 @@ from envloop.http import RemoteError
15
15
  NAME = re.compile(r'[a-zA-Z0-9][a-zA-Z0-9._-]*/[a-zA-Z0-9][a-zA-Z0-9._-]*')
16
16
  REVISION = re.compile(r'[a-f0-9]{40}|[a-f0-9]{64}')
17
17
  SEGMENT = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_.-]*')
18
- SOURCE_REF_KINDS = ('branch', 'tag', 'commit')
19
18
  MAX_FILES = 100
20
19
  MAX_BYTES = 8 * 1024 * 1024
21
20
  REFERENCE_KEYS = ('uri', 'name', 'revision', 'sha256', 'index_sha256')
22
21
 
23
22
 
24
- def source_ref_valid(value: Any) -> bool:
23
+ def revision_valid(value: Any) -> bool:
25
24
  return (isinstance(value, str) and bool(value) and value not in ('HEAD', 'latest', 'default', 'release')
26
25
  and not re.search(r'@\{|[~^:?*\[\\\s]', value) and '..' not in value and not value.startswith('-'))
27
26
 
@@ -88,7 +87,7 @@ def resolve_source_revision(directory: str | Path, ref: str) -> tuple[str, str]:
88
87
  the bytes of that commit: tracked changes, untracked files and ignored files
89
88
  are refused rather than published under the commit's name.
90
89
  """
91
- if not source_ref_valid(ref):
90
+ if not revision_valid(ref):
92
91
  raise RemoteError('RUNNER_REVISION_INVALID')
93
92
  root = Path(directory).absolute()
94
93
  if root.is_symlink() or not root.is_dir():
@@ -101,7 +100,10 @@ def resolve_source_revision(directory: str | Path, ref: str) -> tuple[str, str]:
101
100
  raise RemoteError('RUNNER_REVISION_UNRESOLVED') from None
102
101
 
103
102
  for kind, prefix in (('branch', 'refs/heads/'), ('tag', 'refs/tags/')):
104
- resolved = git('rev-parse', '--verify', '--quiet', f'{prefix}{ref}^{{commit}}')
103
+ if ref.startswith(('refs/heads/', 'refs/tags/')) and not ref.startswith(prefix):
104
+ continue
105
+ selector = ref if ref.startswith(prefix) else prefix + ref
106
+ resolved = git('rev-parse', '--verify', '--quiet', f'{selector}^{{commit}}')
105
107
  if resolved.returncode == 0 and REVISION.fullmatch(commit := resolved.stdout.strip()):
106
108
  break
107
109
  else:
@@ -111,3 +113,24 @@ def resolve_source_revision(directory: str | Path, ref: str) -> tuple[str, str]:
111
113
  if changed.returncode != 0 or extra.returncode != 0 or extra.stdout.strip():
112
114
  raise RemoteError('RUNNER_PACKAGE_UNCOMMITTED')
113
115
  return commit, kind
116
+
117
+
118
+ def commit_metadata(directory: str | Path, revision: str) -> dict[str, str]:
119
+ """Read display metadata from the selected commit; a detached package has none."""
120
+ try:
121
+ result = subprocess.run(['git', '-C', str(Path(directory).absolute()), 'show', '--no-patch',
122
+ '--no-notes', '--format=%an%x00%s', revision, '--'],
123
+ capture_output=True, text=True, errors='replace', timeout=30)
124
+ except (OSError, subprocess.TimeoutExpired):
125
+ return {}
126
+ if result.returncode != 0:
127
+ return {}
128
+ values = result.stdout.rstrip('\n').split('\x00', 1)
129
+ if len(values) != 2:
130
+ return {}
131
+ metadata = dict(zip(('author', 'message'), values, strict=True))
132
+ for key, limit in (('author', 256), ('message', 4096)):
133
+ value = metadata[key]
134
+ if len(value) > limit or re.search(r'[\x00-\x1f\x7f]', value):
135
+ raise RemoteError('RUNNER_COMMIT_METADATA_INVALID')
136
+ return {key: value for key, value in metadata.items() if value.strip()}
envloop_asset/tags.py CHANGED
@@ -1,5 +1,6 @@
1
1
  """Generic string labels, kept outside content manifests."""
2
2
 
3
+ import json
3
4
  from collections.abc import Mapping
4
5
 
5
6
 
@@ -16,7 +17,26 @@ def validate_tags(value: object) -> dict[str, str]:
16
17
  return result
17
18
 
18
19
 
20
+ def validate_checkpoint_tags(value: object) -> dict[str, str]:
21
+ labels = validate_tags(value)
22
+ if 'decision-model' in labels and labels['decision-model'] not in ('true', 'false'):
23
+ raise ValueError('tags decision-model must be the string true or false')
24
+ return labels
25
+
26
+
19
27
  def parse_tags(text: str) -> dict[str, str]:
28
+ if text.lstrip().startswith('{'):
29
+ def unique(pairs: list[tuple[str, object]]) -> dict[str, object]:
30
+ value: dict[str, object] = {}
31
+ for key, item in pairs:
32
+ if key in value:
33
+ raise ValueError('tags JSON must use unique keys')
34
+ value[key] = item
35
+ return value
36
+ try:
37
+ return validate_tags(json.loads(text, object_pairs_hook=unique))
38
+ except json.JSONDecodeError:
39
+ raise ValueError('tags must be a valid JSON string mapping') from None
20
40
  result: dict[str, str] = {}
21
41
  for entry in text.split(','):
22
42
  key, separator, value = entry.partition(':')