blobhub-cli 0.5.0__tar.gz → 0.6.0__tar.gz

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 (60) hide show
  1. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/PKG-INFO +1 -1
  2. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/__init__.py +1 -1
  3. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/api/client.py +28 -8
  4. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/api/commands.py +2 -15
  5. blobhub_cli-0.6.0/src/blobhub_cli/api/errors.py +90 -0
  6. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/cli/app.py +5 -5
  7. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/codes.py +1 -1
  8. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/commands/blob.py +14 -25
  9. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/commands/execute.py +24 -10
  10. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/commands/scheduler.py +43 -43
  11. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/commands/workflow.py +2 -5
  12. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/compiler/allowlist.py +23 -18
  13. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/compiler/sandbox.py +3 -3
  14. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/console.py +2 -0
  15. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/exit.py +4 -2
  16. blobhub_cli-0.6.0/src/blobhub_cli/limits.py +47 -0
  17. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/scheduler/references.py +9 -11
  18. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/workflow/definitions.py +4 -4
  19. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/workflow/executions.py +19 -3
  20. blobhub_cli-0.5.0/src/blobhub_cli/api/errors.py +0 -51
  21. blobhub_cli-0.5.0/src/blobhub_cli/limits.py +0 -32
  22. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/.gitignore +0 -0
  23. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/LICENSE +0 -0
  24. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/README.md +0 -0
  25. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/pyproject.toml +0 -0
  26. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/__main__.py +0 -0
  27. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/api/__init__.py +0 -0
  28. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/blob/__init__.py +0 -0
  29. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/blob/reference.py +0 -0
  30. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/cli/__init__.py +0 -0
  31. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/commands/__init__.py +0 -0
  32. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/commands/auth.py +0 -0
  33. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/commands/completion.py +0 -0
  34. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/commands/doctor.py +0 -0
  35. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/commands/eject.py +0 -0
  36. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/compiler/__init__.py +0 -0
  37. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/compiler/emit.py +0 -0
  38. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/compiler/graph.py +0 -0
  39. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/config/__init__.py +0 -0
  40. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/config/credentials.py +0 -0
  41. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/config/settings.py +0 -0
  42. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/config/sources.py +0 -0
  43. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/definition/__init__.py +0 -0
  44. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/definition/drift.py +0 -0
  45. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/definition/eject.py +0 -0
  46. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/definition/hashing.py +0 -0
  47. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/definition/model.py +0 -0
  48. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/formats/__init__.py +0 -0
  49. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/formats/io.py +0 -0
  50. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/ids.py +0 -0
  51. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/manifest/__init__.py +0 -0
  52. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/manifest/base.py +0 -0
  53. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/manifest/resolver.py +0 -0
  54. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/manifest/scheduler.py +0 -0
  55. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/manifest/workflow.py +0 -0
  56. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/scheduler/__init__.py +0 -0
  57. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/scheduler/schedules.py +0 -0
  58. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/statestore.py +0 -0
  59. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/workflow/__init__.py +0 -0
  60. {blobhub_cli-0.5.0 → blobhub_cli-0.6.0}/src/blobhub_cli/workflow/reference.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: blobhub-cli
3
- Version: 0.5.0
3
+ Version: 0.6.0
4
4
  Summary: BlobHub command line interface — work with blobs, revisions, and their contents from the terminal
5
5
  Project-URL: Homepage, https://blobhub.io/
6
6
  Project-URL: Documentation, https://docs.blobhub.io/
@@ -5,4 +5,4 @@ Contract: this module is the sole source of the package version — hatchling re
5
5
  Invariant: no other file in this package defines `__version__`.
6
6
  """
7
7
 
8
- __version__ = "0.5.0"
8
+ __version__ = "0.6.0"
@@ -3,6 +3,8 @@
3
3
  Contract: `get`, `query`, `command`, and `raw_query` route every response through `_handle`,
4
4
  which maps HTTP status and the body's `status` field onto the `api.errors` hierarchy;
5
5
  `raw_query` alone skips the status gate, and `probe` skips both the gate and the retry loop.
6
+ `get`, `query` and `raw_query` retry every transient failure; `command` retries only
7
+ `errors.NEVER_RAN`, because any other failure can follow a write the platform already committed.
6
8
  Neither `query`, `command`, nor `raw_query` names which component serves a data-channel call --
7
9
  the target revision's blob type decides that server-side, so there is nothing for a caller to
8
10
  supply here at all, even for a scheduler `deploy` that legitimately writes schedules against one
@@ -20,19 +22,29 @@ import time
20
22
  import httpx
21
23
 
22
24
  from blobhub_cli.api.errors import (
25
+ NEVER_RAN,
26
+ TRANSIENT,
23
27
  ApiAuthError,
24
28
  ApiCommandError,
29
+ ApiConnectError,
30
+ ApiLimitExceeded,
25
31
  ApiNetworkError,
26
32
  ApiRateLimited,
27
33
  ApiTransientError,
28
34
  )
29
35
 
30
- _TRANSIENT = (ApiRateLimited, ApiTransientError, ApiNetworkError)
31
36
  _ATTEMPTS = 3
32
37
  _BASE_DELAY = 0.5
33
38
  _MAX_DELAY = 8.0
34
39
 
35
40
 
41
+ def _network_error(exc: httpx.TransportError) -> ApiNetworkError:
42
+ """The transport failure as an `ApiNetworkError`, or an `ApiConnectError` when nothing was sent."""
43
+ error_type = ApiConnectError if isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)) else ApiNetworkError
44
+ # str() of an httpx transport error is often empty (ReadError("")); the class name is then the only cause.
45
+ return error_type(str(exc) or type(exc).__name__)
46
+
47
+
36
48
  class Client:
37
49
  def __init__(
38
50
  self,
@@ -62,7 +74,7 @@ class Client:
62
74
  # parameters instead of ignoring them, so `?limit=` or `?cursor=None` is a 400.
63
75
  if params is not None:
64
76
  params = {key: value for key, value in params.items() if value is not None}
65
- return self._send("GET", path, gate_status=True, params=params or None)
77
+ return self._send("GET", path, gate_status=True, idempotent=True, params=params or None)
66
78
 
67
79
  def probe(self, path: str = "/users/me") -> tuple[int, float]:
68
80
  """One unretried request, returning (status_code, elapsed_ms) without gating the body.
@@ -75,7 +87,7 @@ class Client:
75
87
  try:
76
88
  resp = self._http.request("GET", path)
77
89
  except httpx.TransportError as exc:
78
- raise ApiNetworkError(str(exc)) from exc
90
+ raise _network_error(exc) from exc
79
91
  return resp.status_code, (time.monotonic() - start) * 1000
80
92
 
81
93
  def query(self, revision_id: str, command: str, **args: object) -> dict:
@@ -92,20 +104,26 @@ class Client:
92
104
  ) -> dict:
93
105
  path = f"/revisions/{revision_id}/data/{channel}"
94
106
  body = {"command": command, **args}
95
- return self._send("POST", path, gate_status=gate_status, json=body)
107
+ return self._send("POST", path, gate_status=gate_status, idempotent=(channel == "query"), json=body)
96
108
 
97
- def _send(self, method: str, path: str, *, gate_status: bool, **kwargs: object) -> dict:
109
+ def _send(
110
+ self, method: str, path: str, *, gate_status: bool, idempotent: bool, **kwargs: object
111
+ ) -> dict:
112
+ # A write retries only what proves it never ran (docs/specs/2026-10-06-safe-retries.md).
113
+ retryable = TRANSIENT if idempotent else NEVER_RAN
98
114
  last_error: Exception
99
115
  for attempt in range(_ATTEMPTS):
100
116
  try:
101
117
  resp = self._http.request(method, path, **kwargs)
102
118
  except httpx.TransportError as exc:
103
- last_error = ApiNetworkError(str(exc))
119
+ last_error = _network_error(exc)
104
120
  else:
105
121
  try:
106
122
  return self._handle(resp, gate_status=gate_status)
107
- except _TRANSIENT as exc:
123
+ except TRANSIENT as exc:
108
124
  last_error = exc
125
+ if not isinstance(last_error, retryable):
126
+ break
109
127
  if attempt < _ATTEMPTS - 1:
110
128
  self._sleep(random.random() * min(_MAX_DELAY, _BASE_DELAY * 2**attempt))
111
129
  raise last_error
@@ -122,5 +140,7 @@ class Client:
122
140
  except ValueError as exc:
123
141
  raise ApiTransientError(f"non-JSON response: HTTP {resp.status_code}") from exc
124
142
  if gate_status and data.get("status") != "success":
125
- raise ApiCommandError(data.get("error", "unknown"), data.get("message", ""))
143
+ if data.get("error") == "limit_exceeded":
144
+ raise ApiLimitExceeded(data.get("message", ""), data.get("limit"))
145
+ raise ApiCommandError(data.get("error", "unknown"), data.get("message", ""), data.get("limit"))
126
146
  return data
@@ -41,8 +41,8 @@ class Api:
41
41
  f"/blobs/{org}/{blob}/revisions", {"limit": limit, "cursor": cursor})
42
42
  return body["revisions"], body["cursor"]
43
43
 
44
- def get_blob_limits(self, org: str, blob: str) -> dict:
45
- return self._client.get(f"/blobs/{org}/{blob}/limits")["limits"]
44
+ def get_blob_limits(self, org: str, blob: str) -> list[dict]:
45
+ return self._client.get(f"/blobs/{org}/{blob}/limits")["groups"]
46
46
 
47
47
  def list_definitions(self, revision_id: str, category: str) -> list[dict]:
48
48
  return self._client.query(revision_id, "list_definitions", category=category)["definitions"]
@@ -103,19 +103,6 @@ class Api:
103
103
  args["limit"] = limit
104
104
  return self._client.query(revision_id, "list_execution_events", **args)["execution_events"]
105
105
 
106
- def list_executions(
107
- self, revision_id: str, session_id: str, *, start_execution_id: str | None = None
108
- ) -> tuple[list[dict], str | None]:
109
- # start_execution_id is omitted rather than sent as null, same reason list_schedules omits
110
- # start_schedule_id: LIST_EXECUTIONS_SCHEMA is additionalProperties: false. One page and the
111
- # next cursor -- this method deliberately does not loop; the loop belongs to the caller that
112
- # knows why it's paging (deploy's saturation count stops early on purpose).
113
- args: dict[str, object] = {"session_id": session_id}
114
- if start_execution_id is not None:
115
- args["start_execution_id"] = start_execution_id
116
- body = self._client.query(revision_id, "list_executions", **args)
117
- return body["executions"], body["last_execution_id"]
118
-
119
106
  def create_schedule(self, revision_id: str, **fields: object) -> dict:
120
107
  return self._client.command(revision_id, "create_schedule", **fields)["schedule"]
121
108
 
@@ -0,0 +1,90 @@
1
+ """Error hierarchy raised by `client.Client`.
2
+
3
+ Contract: every failure raised is one of these classes, each carrying a `code` class attribute
4
+ from `blobhub_cli.codes`; `ApiCommandError` additionally carries `.error`, the server's
5
+ machine-readable failure string, kept separate from the human-readable `.message`, and `.limit`,
6
+ the served limit object any refusal may carry -- `ApiLimitExceeded` is the `limit_exceeded` one.
7
+ `outcome_unknown` says which failures leave a write's outcome unknown (the SDK-modernization
8
+ epic's D5, `docs/specs/2026-10-06-safe-retries.md`).
9
+ Invariant: no instance of any of these classes ever carries the API key — the client that
10
+ raises them holds the only copy, and it is never included in a message here.
11
+ """
12
+
13
+ import json
14
+
15
+ from blobhub_cli import codes
16
+
17
+
18
+ class ApiError(Exception):
19
+ """Base class for every error `Client` raises."""
20
+
21
+ code = "API_ERROR"
22
+
23
+
24
+ class ApiAuthError(ApiError):
25
+ """The API key was rejected or the resource is forbidden (HTTP 401/403)."""
26
+
27
+ code = codes.AUTH_INVALID
28
+
29
+
30
+ class ApiRateLimited(ApiError):
31
+ """API Gateway throttled the request (HTTP 429) before anything ran. Retried for every request."""
32
+
33
+ code = codes.API_RATE_LIMITED
34
+
35
+
36
+ class ApiTransientError(ApiError):
37
+ """A server-side or malformed-response failure (HTTP 5xx, non-JSON body). Retried for reads only."""
38
+
39
+ code = codes.API_TRANSIENT_ERROR
40
+
41
+
42
+ class ApiNetworkError(ApiError):
43
+ """A transport failure: no usable response arrived. Retried for reads only."""
44
+
45
+ code = codes.API_NETWORK_ERROR
46
+
47
+
48
+ class ApiConnectError(ApiNetworkError):
49
+ """The connection was never established, so the request was never sent. Retried for every request."""
50
+
51
+
52
+ class ApiCommandError(ApiError):
53
+ """A successful HTTP response whose body reports `status` other than `success`."""
54
+
55
+ code = codes.API_COMMAND_FAILED
56
+
57
+ def __init__(self, error: str, message: str = "", limit: dict | None = None) -> None:
58
+ message = with_limit(message, limit)
59
+ super().__init__(message or error)
60
+ self.error = error
61
+ self.message = message or error
62
+ self.limit = limit
63
+
64
+
65
+ class ApiLimitExceeded(ApiCommandError):
66
+ """A `limit_exceeded` refusal: a quota or a configurable ceiling has been reached."""
67
+
68
+ code = codes.LIMIT_EXCEEDED
69
+
70
+ def __init__(self, message: str = "", limit: dict | None = None) -> None:
71
+ super().__init__("limit_exceeded", message, limit)
72
+
73
+
74
+ def with_limit(message: str, limit: dict | None) -> str:
75
+ """`message` with the served limit appended, as `(limit <id>: value <v>[, held <h>])`."""
76
+ if not limit:
77
+ return message
78
+ held = f", held {json.dumps(limit['held'])}" if "held" in limit else ""
79
+ named = f"limit {limit.get('id')}: value {json.dumps(limit.get('value'))}{held}"
80
+ return f"{message} ({named})" if message else named
81
+
82
+
83
+ TRANSIENT = (ApiRateLimited, ApiTransientError, ApiNetworkError)
84
+ # A write may retry only these: a 429 is refused before any handler runs, and a failed connect sent nothing.
85
+ NEVER_RAN = (ApiRateLimited, ApiConnectError)
86
+
87
+
88
+ def outcome_unknown(error: BaseException) -> bool:
89
+ """Whether a failed request may still have been carried out by the platform."""
90
+ return isinstance(error, TRANSIENT) and not isinstance(error, NEVER_RAN)
@@ -12,7 +12,7 @@ import typer
12
12
  from typer.completion import completion_init
13
13
 
14
14
  from blobhub_cli import __version__, codes, console
15
- from blobhub_cli.api.errors import ApiError
15
+ from blobhub_cli.api.errors import ApiCommandError, ApiError
16
16
  from blobhub_cli.commands.completion import Shell as CompletionShell
17
17
  from blobhub_cli.config import settings
18
18
  from blobhub_cli.exit import CliExit
@@ -175,7 +175,7 @@ def build_app() -> typer.Typer:
175
175
  blob: str = typer.Argument(..., help="Blob as '<org>/<name>', or a bare name with --org."),
176
176
  refresh: bool = typer.Option(False, "--refresh", help="Also refresh the compiler's local allowlist cache."),
177
177
  ) -> None:
178
- """Show a blob's limits, including the import allowlist. Requires an admin-scoped key."""
178
+ """Show a blob's limits by group: id, holding, source and value."""
179
179
  from blobhub_cli.commands import blob as blob_cmd
180
180
 
181
181
  blob_cmd.limits(blob, refresh)
@@ -234,13 +234,12 @@ def build_app() -> typer.Typer:
234
234
  manifest: Path = typer.Option(..., "-f", "--file", help="Path to the workflow manifest."), # noqa: B008
235
235
  definition: list[str] = typer.Option([], "--definition", help="Limit to this alias, repeatable."), # noqa: B008
236
236
  force: bool = typer.Option(False, "--force", help="Overwrite code edited outside the CLI."),
237
- strict_imports: bool = typer.Option(False, "--strict-imports", help="Treat an unverifiable import as fatal."),
238
237
  dry_run: bool = typer.Option(False, "--dry-run", help="Report the intended calls and perform none."),
239
238
  ) -> None:
240
239
  """Build, upload only what changed, and check the workflow definitions that were uploaded."""
241
240
  from blobhub_cli.commands import workflow
242
241
 
243
- workflow.deploy(manifest, tuple(definition), force, strict_imports, dry_run)
242
+ workflow.deploy(manifest, tuple(definition), force, dry_run)
244
243
 
245
244
  @workflow_app.command("eject")
246
245
  def workflow_eject(
@@ -381,7 +380,8 @@ def main(argv: list[str] | None = None) -> int:
381
380
  # so wrap it in a CliExit rather than let a raw traceback reach the user. Only AUTH_INVALID
382
381
  # has a hint that's genuinely a runnable command; inventing one for the rest would be prose.
383
382
  hint = "blobhub login" if exc.code == codes.AUTH_INVALID else ""
384
- console.error(CliExit(exc.code, str(exc), hint))
383
+ limit = exc.limit if isinstance(exc, ApiCommandError) else None
384
+ console.error(CliExit(exc.code, str(exc), hint, limit=limit))
385
385
  return 1
386
386
  except Exception as exc: # usage errors carry exit_code; anything else is a real bug
387
387
  # Typer >=0.24 vendors its own click fork under `typer._click` rather than
@@ -31,7 +31,6 @@ MANIFEST_VERSION_UNSUPPORTED = "MANIFEST_VERSION_UNSUPPORTED"
31
31
  BLOB_REFERENCE_INVALID = "BLOB_REFERENCE_INVALID"
32
32
  BLOB_NOT_ACCESSIBLE = "BLOB_NOT_ACCESSIBLE"
33
33
  BLOB_NOT_WORKFLOW = "BLOB_NOT_WORKFLOW"
34
- LIMITS_NOT_ACCESSIBLE = "LIMITS_NOT_ACCESSIBLE"
35
34
  REVISION_NOT_ACCESSIBLE = "REVISION_NOT_ACCESSIBLE"
36
35
  REVISION_NOT_WRITABLE = "REVISION_NOT_WRITABLE"
37
36
 
@@ -82,6 +81,7 @@ SESSION_NOT_ACCESSIBLE = "SESSION_NOT_ACCESSIBLE"
82
81
  SESSION_NOT_OPEN = "SESSION_NOT_OPEN"
83
82
  DEFINITION_NOT_EXECUTABLE = "DEFINITION_NOT_EXECUTABLE"
84
83
  EXECUTION_FAILED = "EXECUTION_FAILED"
84
+ EXECUTION_OUTCOME_UNKNOWN = "EXECUTION_OUTCOME_UNKNOWN"
85
85
 
86
86
  # Schedules
87
87
  SCHEDULE_ALIAS_REQUIRED = "SCHEDULE_ALIAS_REQUIRED"
@@ -7,10 +7,11 @@ Those are right for a command about to drive a workflow blob and wrong for an in
7
7
  in an unusable phase is precisely what someone runs `blob show` to diagnose.
8
8
  """
9
9
 
10
+ import json
10
11
  from collections.abc import Callable
11
12
  from datetime import UTC, datetime
12
13
 
13
- from blobhub_cli import codes, console
14
+ from blobhub_cli import console
14
15
  from blobhub_cli.api.client import Client
15
16
  from blobhub_cli.api.commands import Api
16
17
  from blobhub_cli.api.errors import ApiAuthError, ApiError
@@ -19,7 +20,6 @@ from blobhub_cli.blob.reference import BlobRef
19
20
  from blobhub_cli.compiler import allowlist
20
21
  from blobhub_cli.config import settings
21
22
  from blobhub_cli.config.settings import Settings
22
- from blobhub_cli.exit import CliExit
23
23
 
24
24
 
25
25
  def _default_api_factory(resolved: Settings) -> Api:
@@ -135,11 +135,14 @@ def revisions(ref_text: str, *, api_factory: Callable[[Settings], Api] = _defaul
135
135
 
136
136
  def _render_limits(payload: dict) -> None:
137
137
  print(f"Limits for {payload['blob']}")
138
- for name, entry in sorted(payload["limits"].items()):
139
- fields = (
140
- ", ".join(f"{key}={entry[key]}" for key in sorted(entry)) if isinstance(entry, dict) else str(entry)
141
- )
142
- print(f" {name:<40} {fields}")
138
+ ids = [entry["id"] for group in payload["groups"] for entry in group["limits"]]
139
+ width = max(map(len, ids), default=2)
140
+ print(f" {'ID':<{width}} {'HELD':<8} {'SOURCE':<8} VALUE")
141
+ for group in payload["groups"]:
142
+ print(f"{group['label']} ({group['group']})")
143
+ for entry in group["limits"]:
144
+ print(f" {entry['id']:<{width}} {entry.get('held', '')!s:<8} {entry['source']:<8} "
145
+ f"{json.dumps(entry['value'])}")
143
146
  if payload["refreshed"]:
144
147
  print(f"Allowlist cache written to {payload['cache_path']}")
145
148
 
@@ -147,28 +150,14 @@ def _render_limits(payload: dict) -> None:
147
150
  def limits(ref_text: str, refresh: bool, *, api_factory: Callable[[Settings], Api] = _default_api_factory) -> dict:
148
151
  ref, resolved = _resolve_ref(ref_text, "blob limits")
149
152
  api = api_factory(resolved)
150
-
151
- # A hard failure, not a degradation to cache -- deliberately unlike `allowlist.fetch`, which
152
- # swallows this same 403. The difference is what the caller asked for: `build` wants imports
153
- # validated and a cached answer serves that; this command wants the limits, and a partial
154
- # answer silently sourced from a week-old file is worse than a clear refusal.
155
153
  try:
156
- record = api.get_blob_limits(ref.org, ref.name)
154
+ groups = api.get_blob_limits(ref.org, ref.name)
157
155
  except ApiAuthError as exc:
158
- # The same handler 403s an unknown blob (spec §1.1), so the message must not assert a cause
159
- # it cannot know -- sending someone off to mint an admin key over a typo'd blob name is a
160
- # worse failure than saying plainly that the platform conflates the two.
161
- raise CliExit(
162
- codes.LIMITS_NOT_ACCESSIBLE,
163
- f"limits for {ref.label()} are not readable: reading limits needs an admin-scoped key "
164
- f"(the read/write keys recommended for automation cannot), or the blob is absent -- "
165
- f"the platform returns the same 403 for both",
166
- "blobhub whoami",
167
- ) from exc
156
+ raise reference.not_accessible(ref) from exc
168
157
 
169
158
  cache_path = None
170
159
  if refresh:
171
- modules = set(record.get(allowlist.LIMIT_KEY, {}).get("value", []))
160
+ modules = allowlist.modules_from(groups)
172
161
  # Keyed on the raw positional text, exactly as `build`/`diff`/`deploy` key on the manifest's
173
162
  # `blob:` field as written: `normalize_cache_key` org-qualifies precisely when its input
174
163
  # does, so keying on `ref.label()` here would write `acme/flow.yaml` for the bare reference
@@ -176,6 +165,6 @@ def limits(ref_text: str, refresh: bool, *, api_factory: Callable[[Settings], Ap
176
165
  cache_key = allowlist.normalize_cache_key(ref_text)
177
166
  cache_path = str(allowlist.store(cache_key, modules, datetime.now(UTC).isoformat(), ref.org, ref.name))
178
167
 
179
- payload = {"blob": ref.label(), "limits": record, "refreshed": refresh, "cache_path": cache_path}
168
+ payload = {"blob": ref.label(), "groups": groups, "refreshed": refresh, "cache_path": cache_path}
180
169
  console.result(payload, _render_limits)
181
170
  return payload
@@ -22,7 +22,7 @@ from pathlib import Path
22
22
  from blobhub_cli import codes, console
23
23
  from blobhub_cli.api.client import Client
24
24
  from blobhub_cli.api.commands import Api
25
- from blobhub_cli.api.errors import ApiAuthError, ApiCommandError
25
+ from blobhub_cli.api.errors import ApiAuthError, ApiCommandError, ApiError, outcome_unknown
26
26
  from blobhub_cli.config import settings
27
27
  from blobhub_cli.config.settings import Settings
28
28
  from blobhub_cli.exit import CliExit
@@ -72,7 +72,18 @@ def _check_local_definition(api: Api, target: resolver.Target, manifest: workflo
72
72
  )
73
73
 
74
74
 
75
- def _create_execution(api: Api, revision_id: str, session_id: str, ref: WorkflowRef) -> dict:
75
+ def _debugger_url(target: resolver.Target, session_id: str, execution_id: str | None = None) -> str:
76
+ """The web debugger's page for a session, or for one of its executions."""
77
+ path = f"{DEBUGGER_BASE_URL}/{target.org_id}/{target.blob_id}/debugger/{session_id}"
78
+ if execution_id is not None:
79
+ path = f"{path}/{execution_id}"
80
+ # `?revision=` carries the RESOLVED id, never the manifest's symbol: an execution lives in one
81
+ # revision, and a link without it opens on whatever revision the reader last chose, where this
82
+ # session does not exist. blobhub-web drops the parameter itself once it names the default.
83
+ return f"{path}?revision={target.revision_id}"
84
+
85
+
86
+ def _create_execution(api: Api, revision_id: str, session_id: str, ref: WorkflowRef, session_url: str) -> dict:
76
87
  try:
77
88
  return api.create_execution(revision_id, target={"session": session_id}, workflow=ref.to_object())
78
89
  except ApiAuthError as exc:
@@ -89,6 +100,15 @@ def _create_execution(api: Api, revision_id: str, session_id: str, ref: Workflow
89
100
  codes.DEFINITION_NOT_EXECUTABLE,
90
101
  f"{ref.path()!r} is a playground definition, and the platform executes workflow definitions only",
91
102
  ) from exc
103
+ except ApiError as exc:
104
+ if not outcome_unknown(exc):
105
+ raise
106
+ raise CliExit(
107
+ codes.EXECUTION_OUTCOME_UNKNOWN,
108
+ f"creating the execution of {ref.path()!r} failed after the request may have reached the platform "
109
+ f"({exc}), so a run may have started. Check session {session_id} for it before running the command "
110
+ f"again: {session_url}",
111
+ ) from exc
92
112
 
93
113
 
94
114
  def execute(
@@ -112,15 +132,9 @@ def execute(
112
132
  _check_local_definition(api, target, manifest, ref.definition)
113
133
 
114
134
  session_id, session_created = executions.resolve_session(api, target.revision_id, session)
115
- execution = _create_execution(api, target.revision_id, session_id, ref)
135
+ execution = _create_execution(api, target.revision_id, session_id, ref, _debugger_url(target, session_id))
116
136
 
117
- # `?revision=` carries the RESOLVED id, never the manifest's symbol: an execution lives in one
118
- # revision, and a link without it opens on whatever revision the reader last chose, where this
119
- # session does not exist. blobhub-web drops the parameter itself once it names the default.
120
- url = (
121
- f"{DEBUGGER_BASE_URL}/{target.org_id}/{target.blob_id}/debugger/{session_id}/{execution['id']}"
122
- f"?revision={target.revision_id}"
123
- )
137
+ url = _debugger_url(target, session_id, execution["id"])
124
138
  # Launching a browser is a side effect, not output -- there is no `console.stream()` call this
125
139
  # could route through -- so it is the one place this command asks `console.json_mode()` directly.
126
140
  if open_browser and not console.json_mode():
@@ -33,6 +33,9 @@ manifest that fails on a later entry can still leave earlier entries' sessions b
33
33
  an empty session fires nothing and the corrected re-run reuses it (spec §7). The sessions pass 1
34
34
  created are reported under `sessions_created` only when the deploy succeeds; a later entry's failure
35
35
  leaves them behind and reports nothing.
36
+ Before pass 1 resolves anything, `deploy` refuses a manifest that would leave the revision holding more schedules
37
+ than the served `scheduler.schedules_per_revision` (`LIMIT_EXCEEDED`), so nothing -- no schedule, no session -- is
38
+ written.
36
39
 
37
40
  The second pass reuses `_differing` -- the same per-field comparison `diff` uses -- both to decide
38
41
  create/update/unchanged and to skip an `update_schedule` call entirely when nothing differs, which is
@@ -42,12 +45,12 @@ still runs, including session creation -- the one place `diff` and `deploy --dry
42
45
  differ in cost (spec §4.2), since `diff` must never create runtime state and `deploy --dry-run` is
43
46
  explicitly allowed to.
44
47
 
45
- The session-saturation check (spec §8) runs for every entry regardless of create/update/unchanged,
46
- since it is about the *session*'s own execution count, not about what `deploy` is about to do to the
47
- schedule record. It is skipped outright for `one_time` schedules (one more execution cannot saturate
48
- anything) and pages `Api.list_executions` with an early exit the moment the running count exceeds
49
- `SATURATION_THRESHOLD` -- a saturated session, the exact case the warning exists for, is also the
50
- most expensive one to count in full, so the loop must never do that.
48
+ The session-saturation advisory runs for every recurring entry regardless of create/update/unchanged, since it
49
+ is about the *session*'s holding, not about what `deploy` does to the schedule record. It compares what the
50
+ target session holds (its `held` map, from `get_session`) with the served `workflow.executions_per_session`,
51
+ and warns at `SATURATION_SHARE` of it -- two reads, never a count of executions. It is skipped for `one_time`
52
+ schedules and for a session pass 1 just created, and stays silent when either read fails, because an advisory
53
+ never guesses (docs/specs/2026-10-06-limits-groups.md §7).
51
54
  """
52
55
 
53
56
  from collections.abc import Callable
@@ -56,7 +59,7 @@ from pathlib import Path
56
59
  from blobhub_cli import codes, console, limits
57
60
  from blobhub_cli.api.client import Client
58
61
  from blobhub_cli.api.commands import Api
59
- from blobhub_cli.api.errors import ApiAuthError
62
+ from blobhub_cli.api.errors import ApiAuthError, ApiError, with_limit
60
63
  from blobhub_cli.config import settings
61
64
  from blobhub_cli.config.settings import Settings
62
65
  from blobhub_cli.exit import CliExit
@@ -65,12 +68,8 @@ from blobhub_cli.manifest import base, resolver, scheduler
65
68
  from blobhub_cli.scheduler import references, schedules
66
69
  from blobhub_cli.workflow import reference
67
70
 
68
- # Spec §8: the real workflow_executions_per_session maximum needs an admin key most callers don't
69
- # have (limits.read_optional degrades to None for exactly that reason), so this is a fixed,
70
- # deliberately conservative absolute count rather than a fraction of an (often unreadable)
71
- # configured maximum -- the warning still has to fire on *something* concrete.
72
- SATURATION_THRESHOLD = 500
73
- _EXECUTIONS_PER_SESSION_LIMIT = "workflow_executions_per_session"
71
+ # Of the target session's served workflow.executions_per_session: the advisory's own policy, not a platform value.
72
+ SATURATION_SHARE = 0.8
74
73
 
75
74
 
76
75
  def _default_api_factory(resolved: Settings) -> Api:
@@ -391,40 +390,25 @@ def _schedule_fields(
391
390
  return fields
392
391
 
393
392
 
394
- def _session_execution_count(api: Api, revision_id: str, session_id: str, threshold: int) -> int:
395
- """Pages `list_executions` for `session_id`, stopping the moment the running count exceeds
396
- `threshold`. The return value is an exact count only when it is `<= threshold`; past that it is
397
- a lower bound that already proves saturation -- a saturated session is exactly the case where
398
- finishing a full scan would be most expensive, so the loop must never do that (spec §8).
399
- """
400
- count = 0
401
- cursor: str | None = None
402
- while True:
403
- page, cursor = api.list_executions(revision_id, session_id, start_execution_id=cursor)
404
- count += len(page)
405
- if count > threshold or cursor is None:
406
- return count
407
-
408
-
409
393
  def _warn_if_near_saturation(api: Api, entry: scheduler.ScheduleEntry, resolved: references.ResolvedTarget) -> None:
410
- if entry.repeat != "recurring_cron":
411
- return # one_time: one more execution can never saturate anything (spec §8)
412
-
413
- count = _session_execution_count(api, resolved.revision_id, resolved.session_id, SATURATION_THRESHOLD)
414
- if count <= SATURATION_THRESHOLD:
394
+ if entry.repeat != "recurring_cron" or resolved.session_created:
395
+ return
396
+ served = limits.read_optional(api, resolved.org_id, resolved.blob_id)
397
+ maximum = limits.value(served, limits.EXECUTIONS_PER_SESSION)
398
+ if maximum is None:
399
+ return
400
+ try:
401
+ session = api.get_session(resolved.revision_id, resolved.session_id)
402
+ except ApiError:
403
+ return
404
+ held = limits.held(session, limits.EXECUTIONS_PER_SESSION)
405
+ if held < maximum * SATURATION_SHARE:
415
406
  return
416
-
417
- # blob_id passed for both positions: get_blob_limits resolves blob by primary key and never
418
- # consults org once blob is a real id, so this works regardless of which org the target blob
419
- # actually lives in.
420
- target_limits = limits.read_optional(api, resolved.blob_id, resolved.blob_id)
421
- maximum = limits.maximum(target_limits, _EXECUTIONS_PER_SESSION_LIMIT)
422
- detail = f", against a configured maximum of {maximum}" if maximum is not None else ""
423
407
  console.advisory(
424
408
  codes.SESSION_NEAR_SATURATION,
425
- f"{entry.alias}: target session already carries at least {count} execution(s){detail} -- "
426
- "every fire appends one more, and workflow_executions_per_session is enforced at creation, "
427
- "so this schedule will eventually start failing silently with an invocation_error",
409
+ f"{entry.alias}: target session holds {held} of its {maximum} executions "
410
+ f"({limits.EXECUTIONS_PER_SESSION}) -- every fire adds one, and a fire past the limit is refused and "
411
+ "recorded as refused until retention removes old executions",
428
412
  )
429
413
 
430
414
 
@@ -444,6 +428,21 @@ def _render_deploy(payload: dict) -> None:
444
428
  print(f"unchanged {alias}")
445
429
 
446
430
 
431
+ def _check_schedule_quota(api: Api, target: resolver.Target, set_: schedules.ScheduleSet) -> None:
432
+ """Raises `LIMIT_EXCEEDED` when the deploy would leave more schedules than the served per-revision cap."""
433
+ groups = limits.read_optional(api, target.org_id, target.blob_id)
434
+ value = limits.value(groups, limits.SCHEDULES_PER_REVISION)
435
+ if value is None:
436
+ return
437
+ # Deploy never deletes, so every listed schedule stays; it creates exactly the entries with no remote alias.
438
+ held = len(set_.records)
439
+ final = held + sum(1 for entry in set_.entries if entry.alias not in set_.remote)
440
+ if final > value:
441
+ limit = {"id": limits.SCHEDULES_PER_REVISION, "value": value, "held": held}
442
+ prose = f"this deploy would leave {final} schedules on revision {target.revision_id}; nothing was written"
443
+ raise CliExit(codes.LIMIT_EXCEEDED, with_limit(prose, limit), limit=limit)
444
+
445
+
447
446
  def deploy(
448
447
  manifest_path: Path,
449
448
  dry_run: bool,
@@ -458,6 +457,7 @@ def deploy(
458
457
  default_org=resolved_settings.org,
459
458
  )
460
459
  set_ = schedules.load_set(api, target.revision_id, manifest)
460
+ _check_schedule_quota(api, target, set_)
461
461
 
462
462
  # Pass 1: resolve and validate every target before writing anything. A failure here -- on any
463
463
  # entry -- must raise before the first entry's create_schedule/update_schedule call ever runs
@@ -31,7 +31,6 @@ _ERROR_CODE_MAP = {
31
31
  "invalid_layout": codes.PLAYGROUND_LAYOUT_IMMUTABLE,
32
32
  "invalid_component_position": codes.PLAYGROUND_POSITION_INVALID,
33
33
  "alias_in_use": codes.ALIAS_IN_USE,
34
- "limit_exceeded": codes.LIMIT_EXCEEDED,
35
34
  }
36
35
 
37
36
  PAYLOAD_WARN_BYTES = 8 * 1024 * 1024
@@ -424,8 +423,7 @@ def diff(
424
423
  def _live_allowlist(api: Api, target: Target, manifest: WorkflowManifest) -> allowlist.Allowlist:
425
424
  # Unlike `_cached_allowlist` (`build`/`diff`, offline by contract), `deploy` holds a live `Api`
426
425
  # and an already-resolved blob, so it re-validates against the platform on every run rather than
427
- # trusting whatever a previous `fetch` last wrote. `fetch` itself degrades to the cache on a
428
- # `403` (spec §9.5) -- this wrapper only adds printing the advisories, exactly like the cached path.
426
+ # trusting whatever a previous `fetch` last wrote.
429
427
  cache_key = allowlist.normalize_cache_key(manifest.base.blob)
430
428
  result = allowlist.fetch(api, target.org_id, target.blob_id, cache_key)
431
429
  for code, message in result.advisories:
@@ -489,7 +487,6 @@ def deploy(
489
487
  manifest_path: Path,
490
488
  only: tuple[str, ...],
491
489
  force: bool,
492
- strict_imports: bool,
493
490
  dry_run: bool,
494
491
  api_factory: Callable[[Settings], Api] = _default_api_factory,
495
492
  ) -> dict:
@@ -537,7 +534,7 @@ def deploy(
537
534
  name=binding.component_name)
538
535
  if binding.code is not None:
539
536
  try:
540
- _build_code(component, binding.code, allowlist_result.modules, strict=strict_imports,
537
+ _build_code(component, binding.code, allowlist_result.modules, strict=True,
541
538
  force=force, hint=hint)
542
539
  except CliExit as exc:
543
540
  augmented = _augment_import_error(exc, allowlist_result.modules)
@@ -1,9 +1,10 @@
1
- """Reads the workflow_component_code_imports allowlist, with a local cache and 403 degradation.
1
+ """Reads the `workflow.code_imports` allowlist live, and caches it for the commands that never call the API.
2
2
 
3
3
  Contract: `Allowlist.modules` is `None` exactly when the allowlist could not be determined, never
4
- confused with an empty set. `normalize_cache_key` is the one place a manifest's `blob:` reference
5
- becomes a cache key, shared by every caller so `build`/`diff`/`deploy` land on one cache file, and
6
- `cached` alone decides `ALLOWLIST_UNREADABLE`/`ALLOWLIST_STALE`.
4
+ confused with an empty set -- only `cached` can answer that, since `fetch` reads at the `read` standing
5
+ any key that resolved the blob already holds. `normalize_cache_key` is the one place a manifest's `blob:`
6
+ reference becomes a cache key, shared by every caller so `build`/`diff`/`deploy` land on one cache file,
7
+ and `cached` alone decides `ALLOWLIST_UNREADABLE`/`ALLOWLIST_STALE`.
7
8
  Invariant: entry-level advisories run over every known module set, whether it is live or cached.
8
9
  """
9
10
 
@@ -12,15 +13,19 @@ from dataclasses import dataclass, field
12
13
  from datetime import UTC, datetime
13
14
  from pathlib import Path, PurePosixPath
14
15
 
15
- from blobhub_cli import codes, statestore
16
+ from blobhub_cli import codes, limits, statestore
16
17
  from blobhub_cli.api.commands import Api
17
18
  from blobhub_cli.api.errors import ApiAuthError
19
+ from blobhub_cli.blob import reference
20
+ from blobhub_cli.blob.reference import BlobRef
18
21
  from blobhub_cli.compiler import sandbox
19
22
  from blobhub_cli.exit import CliExit
20
23
 
21
- LIMIT_KEY = "workflow_component_code_imports"
22
24
  STALE_AFTER_DAYS = 7
23
25
 
26
+ # The Sandbox's directive to import every listed module eagerly (blobhub-infra sandbox/runtime.py); not a module.
27
+ IMPORT_EVERYTHING = "*"
28
+
24
29
  # Every name already bound in exec_globals before the allowlist is merged in -- an allowlist entry
25
30
  # matching one of these shadows it (spec §9.5 / §1.5), because the merge order puts the allowlist
26
31
  # last.
@@ -48,10 +53,8 @@ def normalize_cache_key(blob: str) -> str:
48
53
  #
49
54
  # Limitation: two manifests that both use a *bare* blob name for identically-named blobs in
50
55
  # different orgs collide on this key and share one cache entry. This is accepted rather than
51
- # solved -- the allowlist is advisory whenever it can't be verified live, and any command
52
- # holding an admin key re-validates live regardless (`fetch`); a bare-name manifest is exactly
53
- # the case where the caller often doesn't have the org handy anyway. Qualifying the manifest's
54
- # `blob:` with `org/` avoids the collision entirely.
56
+ # solved -- only the offline commands (`build`, `diff`, `deploy --dry-run`) read the cache, and `deploy`
57
+ # re-validates live (`fetch`). Qualifying the manifest's `blob:` with `org/` avoids the collision entirely.
55
58
  key = blob.lower()
56
59
  # The key becomes a path segment under ~/.blobhub/cache/allowlist/, and a manifest's `blob:` is
57
60
  # user-supplied text that `manifest.base` only checks for holding at most one "/" -- so
@@ -79,16 +82,18 @@ def store(cache_key: str, modules: set[str], fetched_at: str, org: str, blob: st
79
82
  return path
80
83
 
81
84
 
85
+ def modules_from(groups: list[dict]) -> set[str]:
86
+ """The modules `workflow.code_imports` allows; an unserved limit is an empty allowlist."""
87
+ return set(limits.value(groups, limits.CODE_IMPORTS) or []) - {IMPORT_EVERYTHING}
88
+
89
+
82
90
  def fetch(api: Api, org: str, blob: str, cache_key: str, *, now: Callable[[], datetime] = _utc_now) -> Allowlist:
83
91
  try:
84
- limits = api.get_blob_limits(org, blob)
85
- except ApiAuthError:
86
- # Reading limits requires an admin key (spec §1.6, §9.5); read/write keys -- the platform's
87
- # own recommendation for automation -- get exactly this 403. Fall back to whatever cache
88
- # exists rather than treating it as a hard failure.
89
- return cached(cache_key, now=now)
90
-
91
- modules = set(limits.get(LIMIT_KEY, {}).get("value", []))
92
+ groups = api.get_blob_limits(org, blob)
93
+ except ApiAuthError as exc:
94
+ raise reference.not_accessible(BlobRef(org=org, name=blob)) from exc
95
+
96
+ modules = modules_from(groups)
92
97
  fetched_at = now().isoformat()
93
98
  store(cache_key, modules, fetched_at, org, blob)
94
99
  return Allowlist(modules=modules, source="live", fetched_at=fetched_at, advisories=_entry_advisories(modules))
@@ -16,12 +16,12 @@ STDLIB_MODULES: frozenset[str] = frozenset({
16
16
 
17
17
  TYPING_NAMES: frozenset[str] = frozenset({"typing", "Union", "Literal"})
18
18
 
19
- # The three built-in exceptions plus the six session-domain exceptions the sandbox pre-binds so
20
- # they are catchable in orchestrator code.
19
+ # The three built-in exceptions plus the seven session-domain exceptions the sandbox pre-binds so
20
+ # they are catchable in orchestrator code; `LimitExceeded` is what a write refused by a limit raises.
21
21
  EXCEPTION_NAMES: frozenset[str] = frozenset({
22
22
  "Exception", "ValueError", "IndexError",
23
23
  "GraphMutationConflict", "GraphTraversalLimitExceeded", "InvalidGraphQuery",
24
- "InvalidSessionObjectAlias", "InvalidThreadEnvelope", "InvalidGraphEnvelope",
24
+ "InvalidSessionObjectAlias", "InvalidThreadEnvelope", "InvalidGraphEnvelope", "LimitExceeded",
25
25
  })
26
26
 
27
27
  # Every built-in function bound directly as a sandbox global (the `__builtins__` dict itself holds
@@ -66,6 +66,8 @@ def result(payload: dict, render: Callable[[dict], None]) -> None:
66
66
  def error(exc: CliExit) -> None:
67
67
  if _json:
68
68
  envelope = {"error": exc.message, "hint": exc.hint, "code": exc.code, "schema_version": SCHEMA_VERSION}
69
+ if exc.limit is not None:
70
+ envelope["limit"] = exc.limit
69
71
  print(json.dumps(envelope), file=sys.stderr)
70
72
  return
71
73
  print(f"error: {exc.code}: {exc.message}", file=sys.stderr)
@@ -1,7 +1,8 @@
1
1
  """The CLI's error carrier.
2
2
 
3
3
  Contract: every failure the user can act on is a CliExit with a catalogued code and, where one
4
- exists, a hint that is directly actionable rather than a description of what to do.
4
+ exists, a hint that is directly actionable rather than a description of what to do. `limit`, when
5
+ set, is a refused limit's served object, which the `--json` envelope carries beside the code.
5
6
  Invariant: the hint is a command **or a code fragment** the user can paste, or empty — never
6
7
  prose. The compiler's hints are the code-fragment kind (`from pkg.mod import <name>`); a
7
8
  remediation that can only be described in words belongs in the message.
@@ -9,8 +10,9 @@ remediation that can only be described in words belongs in the message.
9
10
 
10
11
 
11
12
  class CliExit(Exception):
12
- def __init__(self, code: str, message: str = "", hint: str = "") -> None:
13
+ def __init__(self, code: str, message: str = "", hint: str = "", *, limit: dict | None = None) -> None:
13
14
  super().__init__(message or code)
14
15
  self.code = code
15
16
  self.message = message or code
16
17
  self.hint = hint
18
+ self.limit = limit
@@ -0,0 +1,47 @@
1
+ """A blob's served limits catalog, read by limit id -- and the one module that names the ids this CLI reads.
2
+
3
+ Contract: `read_optional` returns the blob's `groups`, or None for every failure mode -- rate limit,
4
+ network error, a vanished blob, or missing coordinates -- so a caller can treat limits purely as
5
+ enrichment; `value` finds one limit by id across every served group, and `held` reads a holding off
6
+ its holder's record.
7
+ Invariant: it never guesses coordinates. Absent org or blob means the read is skipped, not
8
+ approximated from something else, because calling `get_blob_limits` with the wrong org would
9
+ answer confidently and wrongly.
10
+ """
11
+
12
+ from blobhub_cli.api.commands import Api
13
+ from blobhub_cli.api.errors import ApiError
14
+
15
+ CODE_IMPORTS = "workflow.code_imports"
16
+ EXECUTIONS_PER_SESSION = "workflow.executions_per_session"
17
+ DEFINITIONS_PER_REVISION = {
18
+ "workflow": "workflow.definitions_per_revision",
19
+ "playground": "workflow.playgrounds_per_revision",
20
+ }
21
+ SCHEDULES_PER_REVISION = "scheduler.schedules_per_revision"
22
+
23
+
24
+ def read_optional(api: Api, org: str | None, blob: str | None) -> list[dict] | None:
25
+ # There is no revision-scoped limits route, so only the caller's own resolver can supply these coordinates.
26
+ if org is None or blob is None:
27
+ return None
28
+ try:
29
+ return api.get_blob_limits(org, blob)
30
+ except ApiError:
31
+ return None
32
+
33
+
34
+ def value(groups: list[dict] | None, limit_id: str) -> object | None:
35
+ """The served value of `limit_id`, or None when the catalog was not read or does not serve it."""
36
+ if groups is None:
37
+ return None
38
+ for group in groups:
39
+ for entry in group["limits"]:
40
+ if entry["id"] == limit_id:
41
+ return entry["value"]
42
+ return None
43
+
44
+
45
+ def held(record: dict, limit_id: str) -> int:
46
+ """How much of `limit_id` the record holds; the platform charges from zero, so an absent holding is 0."""
47
+ return record.get("held", {}).get(limit_id, 0)
@@ -15,10 +15,8 @@ reference, matching the code's documented scope; a session failure is not folded
15
15
  Invariant: a target revision must admit writes (`{draft, managed}`), because the schedule's whole
16
16
  purpose is to write an execution into it and the platform checks that phase at save time.
17
17
 
18
- `ResolvedTarget.blob_id` exists only so `deploy`'s saturation check can read the target
19
- blob's limits without a second resolution: `get_blob_limits` ignores `org` once `blob` is a real id,
20
- so passing `blob_id` for both positions works regardless of which org the target actually lives in --
21
- no human-readable org handle is needed at all.
18
+ `ResolvedTarget.blob_id` and `org_id` exist only so `deploy`'s saturation check can read the target
19
+ blob's limits without a second resolution.
22
20
 
23
21
  `preview_target` is `resolve_target`'s read-only counterpart, for `diff`: it shares `resolve_target`'s
24
22
  blob/revision resolution and workflow resolution (`_resolve_blob`/`resolve_workflow`, so
@@ -50,7 +48,6 @@ from blobhub_cli.workflow import executions
50
48
  from blobhub_cli.workflow.reference import WorkflowRef
51
49
 
52
50
  WORKFLOW_CATEGORY = "workflow"
53
- _WORKFLOW_DEFINITIONS_LIMIT = "workflow_definitions_per_revision"
54
51
 
55
52
 
56
53
  @dataclass(frozen=True)
@@ -69,9 +66,8 @@ class ResolvedTarget:
69
66
  session_id: str
70
67
  session_created: bool
71
68
  workflow: ResolvedWorkflow
72
- blob_id: str # the target blob's id -- `deploy`'s saturation check reads its limits by id,
73
- # and `get_blob_limits` ignores `org` once `blob` is a real id, so no human-readable org handle
74
- # is needed for a target that may live in a different org entirely.
69
+ blob_id: str
70
+ org_id: str # the target blob's own org, which may differ from the scheduler blob's
75
71
 
76
72
 
77
73
  def check_definition_not_id_under_default(invocation_target: InvocationTarget, *, alias: str) -> None:
@@ -147,7 +143,8 @@ def resolve_workflow(api: Api, ref: WorkflowRef, *, local: Target) -> ResolvedWo
147
143
  return ResolvedWorkflow(reference=ref, definition_id=match["id"], definition_alias=match["alias"])
148
144
 
149
145
  # `list_definitions` cannot page, so a listing at its cap cannot prove absence (AGENTS.md).
150
- maximum = limits.maximum(limits.read_optional(api, source.org_id, source.blob_id), _WORKFLOW_DEFINITIONS_LIMIT)
146
+ served = limits.read_optional(api, source.org_id, source.blob_id)
147
+ maximum = limits.value(served, limits.DEFINITIONS_PER_REVISION[WORKFLOW_CATEGORY])
151
148
  if maximum is not None and len(listing) >= maximum:
152
149
  console.advisory(
153
150
  codes.DEFINITION_LIST_TRUNCATED,
@@ -158,8 +155,8 @@ def resolve_workflow(api: Api, ref: WorkflowRef, *, local: Target) -> ResolvedWo
158
155
  return ResolvedWorkflow(reference=ref, definition_id=None, definition_alias=None)
159
156
 
160
157
  unverified = "" if maximum is not None else (
161
- " -- note the source blob's limits are not readable with this key, so the definition listing "
162
- "could not be confirmed complete; if the workflow does exist, an admin-scoped key will say so"
158
+ " -- note the source blob's limits could not be read, so the definition listing could not be confirmed "
159
+ "complete"
163
160
  )
164
161
  raise CliExit(
165
162
  codes.SCHEDULE_TARGET_INVALID,
@@ -186,6 +183,7 @@ def resolve_target(api: Api, invocation_target: InvocationTarget) -> ResolvedTar
186
183
  session_created=session_created,
187
184
  workflow=workflow,
188
185
  blob_id=resolved.blob_id,
186
+ org_id=resolved.org_id,
189
187
  )
190
188
 
191
189
 
@@ -39,8 +39,8 @@ class DefinitionSet:
39
39
  drift: list[RemoteDefinition]
40
40
 
41
41
 
42
- def _warn_if_truncated(category: str, count: int, limits: dict | None) -> None:
43
- maximum = limits_module.maximum(limits, f"{category}_definitions_per_revision")
42
+ def _warn_if_truncated(category: str, count: int, groups: list[dict] | None) -> None:
43
+ maximum = limits_module.value(groups, limits_module.DEFINITIONS_PER_REVISION[category])
44
44
  if maximum is not None and count >= maximum:
45
45
  console.advisory(
46
46
  codes.DEFINITION_LIST_TRUNCATED,
@@ -91,11 +91,11 @@ def load_set(
91
91
  org: str | None = None,
92
92
  blob: str | None = None,
93
93
  ) -> DefinitionSet:
94
- limits = limits_module.read_optional(api, org, blob)
94
+ groups = limits_module.read_optional(api, org, blob)
95
95
  remote: dict[tuple[str, str], RemoteDefinition] = {}
96
96
  for category in CATEGORIES:
97
97
  records = api.list_definitions(revision_id, category)
98
- _warn_if_truncated(category, len(records), limits)
98
+ _warn_if_truncated(category, len(records), groups)
99
99
  for record in records:
100
100
  alias = record["alias"]
101
101
  remote[(category, alias)] = RemoteDefinition(id=record["id"], alias=alias, category=category)
@@ -18,7 +18,7 @@ from collections.abc import Callable
18
18
 
19
19
  from blobhub_cli import codes, console, ids
20
20
  from blobhub_cli.api.commands import Api
21
- from blobhub_cli.api.errors import ApiAuthError
21
+ from blobhub_cli.api.errors import ApiAuthError, ApiError, outcome_unknown
22
22
  from blobhub_cli.exit import CliExit
23
23
 
24
24
  OPEN = "open"
@@ -41,9 +41,25 @@ def require_open(session: dict, reference: str) -> None:
41
41
  )
42
42
 
43
43
 
44
+ def _create_session(api: Api, revision_id: str, alias: str | None = None) -> str:
45
+ """Create a session and return its id, saying plainly when the platform may have created it anyway."""
46
+ kwargs = {} if alias is None else {"alias": alias}
47
+ try:
48
+ return api.create_session(revision_id, **kwargs)["id"]
49
+ except ApiError as exc:
50
+ if not outcome_unknown(exc):
51
+ raise
52
+ name = "a session" if alias is None else f"session {alias!r}"
53
+ raise CliExit(
54
+ exc.code,
55
+ f"creating {name} on revision {revision_id} failed after the request may have reached the platform "
56
+ f"({exc}). The session may exist now, but nothing has run in it, so running the command again is safe",
57
+ ) from exc
58
+
59
+
44
60
  def resolve_session(api: Api, revision_id: str, reference: str | None) -> tuple[str, bool]:
45
61
  if reference is None:
46
- return api.create_session(revision_id)["id"], True
62
+ return _create_session(api, revision_id), True
47
63
 
48
64
  try:
49
65
  session = api.get_session(revision_id, reference)
@@ -58,7 +74,7 @@ def resolve_session(api: Api, revision_id: str, reference: str | None) -> tuple[
58
74
  f"session {reference} is absent or not accessible with this key",
59
75
  "blobhub workflow execute -f <manifest> --definition <alias> --session <alias>",
60
76
  ) from exc
61
- return api.create_session(revision_id, alias=reference)["id"], True
77
+ return _create_session(api, revision_id, reference), True
62
78
 
63
79
  require_open(session, reference)
64
80
  return session["id"], False
@@ -1,51 +0,0 @@
1
- """Error hierarchy raised by `client.Client`.
2
-
3
- Contract: every failure raised is one of these classes, each carrying a `code` class attribute
4
- from `blobhub_cli.codes`; `ApiCommandError` additionally carries `.error`, the server's
5
- machine-readable failure string, kept separate from the human-readable `.message`.
6
- Invariant: no instance of any of these classes ever carries the API key — the client that
7
- raises them holds the only copy, and it is never included in a message here.
8
- """
9
-
10
- from blobhub_cli import codes
11
-
12
-
13
- class ApiError(Exception):
14
- """Base class for every error `Client` raises."""
15
-
16
- code = "API_ERROR"
17
-
18
-
19
- class ApiAuthError(ApiError):
20
- """The API key was rejected or the resource is forbidden (HTTP 401/403)."""
21
-
22
- code = codes.AUTH_INVALID
23
-
24
-
25
- class ApiRateLimited(ApiError):
26
- """The server asked the caller to slow down (HTTP 429). Retried."""
27
-
28
- code = codes.API_RATE_LIMITED
29
-
30
-
31
- class ApiTransientError(ApiError):
32
- """A server-side or malformed-response failure (HTTP 5xx, non-JSON body). Retried."""
33
-
34
- code = codes.API_TRANSIENT_ERROR
35
-
36
-
37
- class ApiNetworkError(ApiError):
38
- """The request never reached the server (DNS, connection, timeout). Retried."""
39
-
40
- code = codes.API_NETWORK_ERROR
41
-
42
-
43
- class ApiCommandError(ApiError):
44
- """A successful HTTP response whose body reports `status` other than `success`."""
45
-
46
- code = codes.API_COMMAND_FAILED
47
-
48
- def __init__(self, error: str, message: str = "") -> None:
49
- super().__init__(message or error)
50
- self.error = error
51
- self.message = message or error
@@ -1,32 +0,0 @@
1
- """Optional reads of a blob's limits, for callers that must survive not being allowed to read them.
2
-
3
- Contract: `read_optional` returns None for every failure mode -- no admin key, rate limit, network
4
- error, or missing coordinates -- so a caller can treat limits purely as enrichment.
5
- Invariant: it never guesses coordinates. Absent org or blob means the read is skipped, not
6
- approximated from something else, because calling `get_blob_limits` with the wrong org would
7
- answer confidently and wrongly.
8
- """
9
-
10
- from blobhub_cli.api.commands import Api
11
- from blobhub_cli.api.errors import ApiError
12
-
13
-
14
- def read_optional(api: Api, org: str | None, blob: str | None) -> dict | None:
15
- # Limits require an admin key (F1 spec §1.6); a read/write key gets a 403 here. There is no
16
- # revision-scoped limits route, so the caller must supply coordinates its own resolver already
17
- # produced -- a bare blob name in a manifest has no org without the resolver's default-org
18
- # logic, and guessing would risk asking about the wrong blob entirely. Limits are optional
19
- # enrichment, so ANY ApiError -- not just a 403 -- degrades to "skip", rather than letting a
20
- # rate limit or network blip propagate out of a listing for the sake of an advisory.
21
- if org is None or blob is None:
22
- return None
23
- try:
24
- return api.get_blob_limits(org, blob)
25
- except ApiError:
26
- return None
27
-
28
-
29
- def maximum(limits: dict | None, limit_id: str) -> int | None:
30
- if limits is None:
31
- return None
32
- return limits.get(limit_id, {}).get("maximum")
File without changes
File without changes
File without changes
File without changes