aind-codeocean-dispatch 0.2.2__py3-none-any.whl → 0.4.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.
- aind_codeocean_dispatch/__init__.py +12 -0
- aind_codeocean_dispatch/capsule_git.py +79 -0
- aind_codeocean_dispatch/capture.py +89 -0
- aind_codeocean_dispatch/runner.py +114 -21
- {aind_codeocean_dispatch-0.2.2.dist-info → aind_codeocean_dispatch-0.4.0.dist-info}/METADATA +1 -1
- aind_codeocean_dispatch-0.4.0.dist-info/RECORD +9 -0
- aind_codeocean_dispatch-0.2.2.dist-info/RECORD +0 -7
- {aind_codeocean_dispatch-0.2.2.dist-info → aind_codeocean_dispatch-0.4.0.dist-info}/WHEEL +0 -0
- {aind_codeocean_dispatch-0.2.2.dist-info → aind_codeocean_dispatch-0.4.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -2,9 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
from importlib.metadata import PackageNotFoundError, version
|
|
4
4
|
|
|
5
|
+
from .capsule_git import capsule_head_commit, head_commit, run_owner_email
|
|
6
|
+
from .capture import capture_as, capture_named_by_data_description, derived_name
|
|
5
7
|
from .runner import (
|
|
8
|
+
TRANSIENT_FAILURES,
|
|
6
9
|
DispatchFailed,
|
|
7
10
|
DispatchInterrupted,
|
|
11
|
+
Failure,
|
|
8
12
|
Job,
|
|
9
13
|
Outcome,
|
|
10
14
|
failed_without_results,
|
|
@@ -16,15 +20,23 @@ from .runner import (
|
|
|
16
20
|
)
|
|
17
21
|
|
|
18
22
|
__all__ = [
|
|
23
|
+
"TRANSIENT_FAILURES",
|
|
19
24
|
"DispatchFailed",
|
|
20
25
|
"DispatchInterrupted",
|
|
26
|
+
"Failure",
|
|
21
27
|
"Job",
|
|
22
28
|
"Outcome",
|
|
29
|
+
"capsule_head_commit",
|
|
30
|
+
"capture_as",
|
|
31
|
+
"capture_named_by_data_description",
|
|
32
|
+
"derived_name",
|
|
23
33
|
"failed_without_results",
|
|
34
|
+
"head_commit",
|
|
24
35
|
"job_key",
|
|
25
36
|
"key_tag",
|
|
26
37
|
"raise_for_failures",
|
|
27
38
|
"run_jobs",
|
|
39
|
+
"run_owner_email",
|
|
28
40
|
"succeeded",
|
|
29
41
|
]
|
|
30
42
|
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Identify the code a capsule will run when no release is pinned.
|
|
2
|
+
|
|
3
|
+
The REST API exposes only released versions, so an unreleased capsule's commit has
|
|
4
|
+
to be read from its Code Ocean git repo.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
import requests
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from codeocean import CodeOcean
|
|
16
|
+
|
|
17
|
+
__all__ = ["capsule_head_commit", "head_commit", "run_owner_email"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def head_commit(refs_advertisement: bytes) -> str | None:
|
|
21
|
+
"""Return the ``HEAD`` sha from a git smart-HTTP ref advertisement, if any."""
|
|
22
|
+
pos = 0
|
|
23
|
+
while pos + 4 <= len(refs_advertisement):
|
|
24
|
+
size = int(refs_advertisement[pos : pos + 4], 16)
|
|
25
|
+
if size < 4: # flush / delimiter packets carry no ref
|
|
26
|
+
pos += 4
|
|
27
|
+
continue
|
|
28
|
+
line = refs_advertisement[pos + 4 : pos + size].split(b"\0")[0].strip()
|
|
29
|
+
pos += size
|
|
30
|
+
sha, _, ref = line.partition(b" ")
|
|
31
|
+
if ref == b"HEAD":
|
|
32
|
+
return sha.decode()
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def run_owner_email(client: CodeOcean, computation_id: str | None = None) -> str:
|
|
37
|
+
"""Login email of whoever launched *computation_id*, by default this run.
|
|
38
|
+
|
|
39
|
+
Inside a run, that is whose token the run holds; no API route names a token's
|
|
40
|
+
owner directly. Read raw because SDKs before 0.17 drop ``owner_email``.
|
|
41
|
+
|
|
42
|
+
Raises
|
|
43
|
+
------
|
|
44
|
+
ValueError
|
|
45
|
+
If no id is given and ``CO_COMPUTATION_ID`` is unset (not on Code Ocean).
|
|
46
|
+
"""
|
|
47
|
+
computation_id = computation_id or os.environ.get("CO_COMPUTATION_ID")
|
|
48
|
+
if not computation_id:
|
|
49
|
+
raise ValueError("CO_COMPUTATION_ID is unset; not running on Code Ocean")
|
|
50
|
+
response = client.session.get(f"computations/{computation_id}")
|
|
51
|
+
response.raise_for_status()
|
|
52
|
+
return str(response.json()["owner_email"])
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def capsule_head_commit(
|
|
56
|
+
client: CodeOcean, capsule_id: str, *, username: str | None = None, timeout_s: float = 60.0
|
|
57
|
+
) -> str | None:
|
|
58
|
+
"""Return the HEAD commit of a capsule's Code Ocean git repo, or ``None`` if it has none.
|
|
59
|
+
|
|
60
|
+
Git, unlike the API, authenticates with the token owner's login email as the
|
|
61
|
+
username; *username* defaults to :func:`run_owner_email`, which works only inside
|
|
62
|
+
a run.
|
|
63
|
+
|
|
64
|
+
Raises
|
|
65
|
+
------
|
|
66
|
+
codeocean.error.Error, requests.RequestException
|
|
67
|
+
If the capsule or its repo cannot be read.
|
|
68
|
+
ValueError
|
|
69
|
+
If *username* is omitted outside a Code Ocean run.
|
|
70
|
+
"""
|
|
71
|
+
slug = client.capsules.get_capsule(capsule_id).slug
|
|
72
|
+
response = requests.get(
|
|
73
|
+
f"{client.domain}/capsule-{slug}.git/info/refs",
|
|
74
|
+
params={"service": "git-upload-pack"},
|
|
75
|
+
auth=(username or run_owner_email(client), client.token),
|
|
76
|
+
timeout=timeout_s,
|
|
77
|
+
)
|
|
78
|
+
response.raise_for_status()
|
|
79
|
+
return head_commit(response.content)
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Builders for :attr:`Job.capture <aind_codeocean_dispatch.Job.capture>`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import re
|
|
8
|
+
import urllib.request
|
|
9
|
+
from collections.abc import Callable, Sequence
|
|
10
|
+
from datetime import UTC, datetime
|
|
11
|
+
from typing import TYPE_CHECKING, Any
|
|
12
|
+
|
|
13
|
+
from codeocean.computation import Computation
|
|
14
|
+
from codeocean.data_asset import ComputationSource, DataAssetParams, Source
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from codeocean import CodeOcean
|
|
18
|
+
|
|
19
|
+
__all__ = ["capture_as", "capture_named_by_data_description", "derived_name"]
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
_DATA_DESCRIPTION = "data_description.json"
|
|
24
|
+
_DATETIME = r"\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}"
|
|
25
|
+
# aind-data-schema-models ``DataRegex.DERIVED``: <input>_<datetime>_<process>_<datetime>.
|
|
26
|
+
_DERIVED_NAME = re.compile(rf"^.+?_{_DATETIME}_.+?_{_DATETIME}")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def capture_as(name: str, tags: Sequence[str], *, mount: str | None = None) -> Callable[[Computation], DataAssetParams]:
|
|
30
|
+
"""Capture a computation's results under a fixed *name*, mounted as *mount* (default *name*)."""
|
|
31
|
+
|
|
32
|
+
def build(computation: Computation) -> DataAssetParams:
|
|
33
|
+
return DataAssetParams(
|
|
34
|
+
name=name,
|
|
35
|
+
tags=list(tags),
|
|
36
|
+
mount=mount or name,
|
|
37
|
+
source=Source(computation=ComputationSource(id=computation.id)),
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
return build
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def derived_name(data_description: dict[str, Any]) -> str | None:
|
|
44
|
+
"""Return the asset name a derived ``data_description.json`` declares, or ``None``.
|
|
45
|
+
|
|
46
|
+
Only a ``derived`` level whose name follows the AIND derived-data pattern counts;
|
|
47
|
+
anything else would mislabel the asset.
|
|
48
|
+
"""
|
|
49
|
+
name = data_description.get("name")
|
|
50
|
+
if data_description.get("data_level") != "derived" or not isinstance(name, str):
|
|
51
|
+
return None
|
|
52
|
+
return name if _DERIVED_NAME.match(name) else None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def capture_named_by_data_description(
|
|
56
|
+
client: CodeOcean, fallback_name: str, tags: Sequence[str]
|
|
57
|
+
) -> Callable[[Computation], DataAssetParams]:
|
|
58
|
+
"""Capture under the name the results' top-level ``data_description.json`` declares.
|
|
59
|
+
|
|
60
|
+
Without a usable one (see :func:`derived_name`), the name is *fallback_name* plus
|
|
61
|
+
the UTC capture time, ``<fallback_name>_YYYY-MM-DD_HH-MM-SS``. The mount is the
|
|
62
|
+
name. A failed read falls back rather than failing the capture, since the name
|
|
63
|
+
is cosmetic and the results are not.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def build(computation: Computation) -> DataAssetParams:
|
|
67
|
+
name = None
|
|
68
|
+
try:
|
|
69
|
+
name = _declared_name(client, computation.id)
|
|
70
|
+
except Exception as exc: # noqa: BLE001 - see docstring
|
|
71
|
+
logger.warning("could not read %s of computation %s: %s", _DATA_DESCRIPTION, computation.id, exc)
|
|
72
|
+
if name is None:
|
|
73
|
+
name = f"{fallback_name}_{datetime.now(UTC):%Y-%m-%d_%H-%M-%S}"
|
|
74
|
+
return capture_as(name, tags)(computation)
|
|
75
|
+
|
|
76
|
+
return build
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _declared_name(client: CodeOcean, computation_id: str) -> str | None:
|
|
80
|
+
results = client.computations.list_computation_results(computation_id)
|
|
81
|
+
if _DATA_DESCRIPTION not in {item.path for item in results.items}:
|
|
82
|
+
return None
|
|
83
|
+
url = client.computations.get_result_file_urls(computation_id, _DATA_DESCRIPTION).download_url
|
|
84
|
+
with urllib.request.urlopen(url, timeout=60) as fh:
|
|
85
|
+
data_description = json.load(fh)
|
|
86
|
+
name = derived_name(data_description)
|
|
87
|
+
if name is None:
|
|
88
|
+
logger.warning("%s of computation %s declares no derived name", _DATA_DESCRIPTION, computation_id)
|
|
89
|
+
return name
|
|
@@ -47,8 +47,10 @@ if TYPE_CHECKING:
|
|
|
47
47
|
from codeocean import CodeOcean
|
|
48
48
|
|
|
49
49
|
__all__ = [
|
|
50
|
+
"TRANSIENT_FAILURES",
|
|
50
51
|
"DispatchFailed",
|
|
51
52
|
"DispatchInterrupted",
|
|
53
|
+
"Failure",
|
|
52
54
|
"Job",
|
|
53
55
|
"Outcome",
|
|
54
56
|
"failed_without_results",
|
|
@@ -75,7 +77,15 @@ _TRANSIENT_SERVER = frozenset({500, 502, 503, 504})
|
|
|
75
77
|
_KEY_PATTERN = re.compile(r"[A-Za-z0-9_.-]{1,64}")
|
|
76
78
|
_KEY_TAG_PREFIX = "dispatch-"
|
|
77
79
|
|
|
78
|
-
Status = Literal["captured", "completed", "reused", "failed"]
|
|
80
|
+
Status = Literal["captured", "completed", "reused", "failed", "cancelled"]
|
|
81
|
+
#: Why a job failed. ``failed_start`` means the relaunch budget ran out;
|
|
82
|
+
#: ``computation`` that it ran and failed; ``api_rejected`` a 4xx other than 429;
|
|
83
|
+
#: ``api_unavailable`` a 5xx or connection error on a call that cannot be retried.
|
|
84
|
+
Failure = Literal[
|
|
85
|
+
"failed_start", "computation", "timeout", "capture", "capture_callback", "api_rejected", "api_unavailable"
|
|
86
|
+
]
|
|
87
|
+
#: Failures on the platform's side, which a rerun of the same job can get past.
|
|
88
|
+
TRANSIENT_FAILURES: frozenset[Failure] = frozenset({"failed_start", "capture", "api_unavailable"})
|
|
79
89
|
_T = TypeVar("_T")
|
|
80
90
|
|
|
81
91
|
|
|
@@ -114,7 +124,8 @@ class Outcome:
|
|
|
114
124
|
"""How one job ended.
|
|
115
125
|
|
|
116
126
|
``computation_ids`` lists every launch attempt in order, so a relaunched job's
|
|
117
|
-
failed starts stay traceable.
|
|
127
|
+
failed starts stay traceable. ``failure`` is set only when ``status`` is
|
|
128
|
+
``"failed"``.
|
|
118
129
|
"""
|
|
119
130
|
|
|
120
131
|
job: Job
|
|
@@ -122,11 +133,17 @@ class Outcome:
|
|
|
122
133
|
asset_id: str | None = None
|
|
123
134
|
computation_ids: tuple[str, ...] = ()
|
|
124
135
|
error: str | None = None
|
|
136
|
+
failure: Failure | None = None
|
|
125
137
|
|
|
126
138
|
@property
|
|
127
139
|
def ok(self) -> bool:
|
|
128
140
|
"""Whether the job produced what was asked of it."""
|
|
129
|
-
return self.status
|
|
141
|
+
return self.status not in ("failed", "cancelled")
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def transient(self) -> bool:
|
|
145
|
+
"""Whether the job failed for a platform reason a rerun can get past."""
|
|
146
|
+
return self.failure in TRANSIENT_FAILURES
|
|
130
147
|
|
|
131
148
|
|
|
132
149
|
class DispatchFailed(RuntimeError):
|
|
@@ -172,10 +189,13 @@ def succeeded(computation: Computation) -> bool:
|
|
|
172
189
|
def failed_without_results(computation: Computation) -> bool:
|
|
173
190
|
"""Whether a computation looks like it never started: failed, with no results.
|
|
174
191
|
|
|
175
|
-
|
|
176
|
-
|
|
192
|
+
Code Ocean reports a failed start as ``state=Completed`` with
|
|
193
|
+
``end_status=Failed``, ``exit_code=0`` and no results, so this keys on
|
|
194
|
+
``end_status``, not ``state``. A capsule that crashes before writing anything
|
|
195
|
+
can match too, so a relaunch can be spent on a real bug; ``start_retries``
|
|
196
|
+
bounds that cost.
|
|
177
197
|
"""
|
|
178
|
-
return computation.
|
|
198
|
+
return computation.end_status == ComputationEndStatus.Failed and not computation.has_results
|
|
179
199
|
|
|
180
200
|
|
|
181
201
|
def key_tag(key: str) -> str:
|
|
@@ -220,16 +240,18 @@ def run_jobs(
|
|
|
220
240
|
max_in_flight: int | None = None,
|
|
221
241
|
launch_interval_s: float = 0.0,
|
|
222
242
|
start_retries: int = 1,
|
|
243
|
+
start_retry_backoff_s: float = 60.0,
|
|
223
244
|
is_failed_start: Callable[[Computation], bool] = failed_without_results,
|
|
224
245
|
capture_retries: int = 0,
|
|
225
246
|
reuse: bool = False,
|
|
226
247
|
poll_interval_s: float = 60.0,
|
|
227
248
|
timeout_s: float | None = None,
|
|
249
|
+
cancel_on_failure: bool | Callable[[Outcome], bool] = False,
|
|
228
250
|
) -> list[Outcome]:
|
|
229
251
|
"""Launch *jobs*, wait for each, capture its results, and report every outcome.
|
|
230
252
|
|
|
231
|
-
A job's failure never
|
|
232
|
-
|
|
253
|
+
A job's failure never raises; check the outcomes, or pass them to
|
|
254
|
+
:func:`raise_for_failures`.
|
|
233
255
|
|
|
234
256
|
Parameters
|
|
235
257
|
----------
|
|
@@ -245,6 +267,10 @@ def run_jobs(
|
|
|
245
267
|
regardless; this only spreads the burst.
|
|
246
268
|
start_retries : int, optional
|
|
247
269
|
Relaunches allowed per job when *is_failed_start* matches.
|
|
270
|
+
start_retry_backoff_s : float, optional
|
|
271
|
+
Wait before the first relaunch, doubling for each later one. Every pending
|
|
272
|
+
launch is held too: a start failure usually means machine capacity ran out,
|
|
273
|
+
and the runs holding it will not free it at once.
|
|
248
274
|
is_failed_start : callable, optional
|
|
249
275
|
Classifies a failed computation as a platform start failure.
|
|
250
276
|
capture_retries : int, optional
|
|
@@ -258,6 +284,10 @@ def run_jobs(
|
|
|
258
284
|
timeout_s : float, optional
|
|
259
285
|
Give up waiting on an attempt after this long. The computation is left
|
|
260
286
|
running, not stopped. ``None`` waits indefinitely.
|
|
287
|
+
cancel_on_failure : bool or callable, optional
|
|
288
|
+
Whether a failed job cancels the rest, or a predicate on its outcome. On
|
|
289
|
+
cancel, pending jobs are not launched and running computations are stopped
|
|
290
|
+
and deleted, all ending ``"cancelled"``; captures already under way finish.
|
|
261
291
|
|
|
262
292
|
Returns
|
|
263
293
|
-------
|
|
@@ -272,18 +302,26 @@ def run_jobs(
|
|
|
272
302
|
When a shutdown signal arrives (handlers installed by the caller, see
|
|
273
303
|
:func:`aind_code_ocean_pipeline_utils.process.install_shutdown_handlers`).
|
|
274
304
|
"""
|
|
275
|
-
_validate(
|
|
305
|
+
_validate(
|
|
306
|
+
jobs,
|
|
307
|
+
max_in_flight=max_in_flight,
|
|
308
|
+
start_retries=start_retries,
|
|
309
|
+
start_retry_backoff_s=start_retry_backoff_s,
|
|
310
|
+
capture_retries=capture_retries,
|
|
311
|
+
)
|
|
276
312
|
return _Dispatcher(
|
|
277
313
|
_without_transport_retries(client),
|
|
278
314
|
jobs,
|
|
279
315
|
max_in_flight=max_in_flight,
|
|
280
316
|
launch_interval_s=launch_interval_s,
|
|
281
317
|
start_retries=start_retries,
|
|
318
|
+
start_retry_backoff_s=start_retry_backoff_s,
|
|
282
319
|
is_failed_start=is_failed_start,
|
|
283
320
|
capture_retries=capture_retries,
|
|
284
321
|
reuse=reuse,
|
|
285
322
|
poll_interval_s=poll_interval_s,
|
|
286
323
|
timeout_s=timeout_s,
|
|
324
|
+
cancel_on_failure=cancel_on_failure,
|
|
287
325
|
).run()
|
|
288
326
|
|
|
289
327
|
|
|
@@ -299,7 +337,14 @@ def _without_transport_retries(client: CodeOcean) -> CodeOcean:
|
|
|
299
337
|
return dataclasses.replace(client, retries=0)
|
|
300
338
|
|
|
301
339
|
|
|
302
|
-
def _validate(
|
|
340
|
+
def _validate(
|
|
341
|
+
jobs: Sequence[Job],
|
|
342
|
+
*,
|
|
343
|
+
max_in_flight: int | None,
|
|
344
|
+
start_retries: int,
|
|
345
|
+
start_retry_backoff_s: float,
|
|
346
|
+
capture_retries: int,
|
|
347
|
+
) -> None:
|
|
303
348
|
labels = [job.label for job in jobs]
|
|
304
349
|
if len(set(labels)) != len(labels):
|
|
305
350
|
raise ValueError(f"job labels must be unique: {sorted(labels)}")
|
|
@@ -308,8 +353,8 @@ def _validate(jobs: Sequence[Job], *, max_in_flight: int | None, start_retries:
|
|
|
308
353
|
raise ValueError("job keys must be unique within a batch")
|
|
309
354
|
if max_in_flight is not None and max_in_flight < 1:
|
|
310
355
|
raise ValueError(f"max_in_flight must be at least 1, got {max_in_flight}")
|
|
311
|
-
if start_retries < 0 or capture_retries < 0:
|
|
312
|
-
raise ValueError("retry counts cannot be negative")
|
|
356
|
+
if start_retries < 0 or capture_retries < 0 or start_retry_backoff_s < 0:
|
|
357
|
+
raise ValueError("retry counts and back-off cannot be negative")
|
|
313
358
|
|
|
314
359
|
|
|
315
360
|
def _prune(value: Any) -> Any:
|
|
@@ -389,22 +434,27 @@ class _Dispatcher:
|
|
|
389
434
|
max_in_flight: int | None,
|
|
390
435
|
launch_interval_s: float,
|
|
391
436
|
start_retries: int,
|
|
437
|
+
start_retry_backoff_s: float,
|
|
392
438
|
is_failed_start: Callable[[Computation], bool],
|
|
393
439
|
capture_retries: int,
|
|
394
440
|
reuse: bool,
|
|
395
441
|
poll_interval_s: float,
|
|
396
442
|
timeout_s: float | None,
|
|
443
|
+
cancel_on_failure: bool | Callable[[Outcome], bool],
|
|
397
444
|
) -> None:
|
|
398
445
|
self.client = client
|
|
399
446
|
self.slots = [_Slot(job) for job in jobs]
|
|
400
447
|
self.max_in_flight = max_in_flight
|
|
401
448
|
self.launch_interval_s = launch_interval_s
|
|
402
449
|
self.start_retries = start_retries
|
|
450
|
+
self.start_retry_backoff_s = start_retry_backoff_s
|
|
403
451
|
self.is_failed_start = is_failed_start
|
|
404
452
|
self.capture_retries = capture_retries
|
|
405
453
|
self.reuse = reuse
|
|
406
454
|
self.poll_interval_s = poll_interval_s
|
|
407
455
|
self.timeout_s = timeout_s
|
|
456
|
+
self.cancel_on_failure = cancel_on_failure
|
|
457
|
+
self.cancelled_by: str | None = None
|
|
408
458
|
self.next_launch_at = 0.0
|
|
409
459
|
|
|
410
460
|
def run(self) -> list[Outcome]:
|
|
@@ -453,7 +503,7 @@ class _Dispatcher:
|
|
|
453
503
|
return
|
|
454
504
|
_sleep(min(_MAX_SLEEP_S, min(due) - now))
|
|
455
505
|
|
|
456
|
-
def _finish(self, slot: _Slot, status: Status, *, error: str | None = None) -> None:
|
|
506
|
+
def _finish(self, slot: _Slot, status: Status, *, error: str | None = None, failure: Failure | None = None) -> None:
|
|
457
507
|
slot.phase = _Phase.DONE
|
|
458
508
|
slot.outcome = Outcome(
|
|
459
509
|
job=slot.job,
|
|
@@ -461,11 +511,36 @@ class _Dispatcher:
|
|
|
461
511
|
asset_id=slot.asset_id,
|
|
462
512
|
computation_ids=tuple(slot.computation_ids),
|
|
463
513
|
error=error,
|
|
514
|
+
failure=failure,
|
|
464
515
|
)
|
|
465
516
|
if error is None:
|
|
466
517
|
logger.info("%s: %s", slot.job.label, status)
|
|
467
518
|
else:
|
|
468
|
-
logger.error("%s:
|
|
519
|
+
logger.error("%s: %s: %s", slot.job.label, status, error)
|
|
520
|
+
if status == "failed" and self.cancelled_by is None and self._should_cancel(slot.outcome):
|
|
521
|
+
self._cancel_rest(slot.job.label)
|
|
522
|
+
|
|
523
|
+
def _should_cancel(self, outcome: Outcome) -> bool:
|
|
524
|
+
if callable(self.cancel_on_failure):
|
|
525
|
+
return self.cancel_on_failure(outcome)
|
|
526
|
+
return self.cancel_on_failure
|
|
527
|
+
|
|
528
|
+
def _cancel_rest(self, failed_label: str) -> None:
|
|
529
|
+
"""Stop every job not yet past its computation; captures under way finish."""
|
|
530
|
+
self.cancelled_by = failed_label
|
|
531
|
+
to_cancel = [slot for slot in self.slots if slot.phase in (_Phase.PENDING, _Phase.RUNNING)]
|
|
532
|
+
if to_cancel:
|
|
533
|
+
logger.warning("%s failed; cancelling %d other job(s)", failed_label, len(to_cancel))
|
|
534
|
+
for slot in to_cancel:
|
|
535
|
+
error = f"cancelled after {failed_label} failed"
|
|
536
|
+
if slot.phase is _Phase.RUNNING:
|
|
537
|
+
computation_id = slot.computation_ids[-1]
|
|
538
|
+
try:
|
|
539
|
+
# Code Ocean has no stop call; deleting stops a running computation.
|
|
540
|
+
self.client.computations.delete_computation(computation_id)
|
|
541
|
+
except (CodeOceanError, requests.RequestException) as exc:
|
|
542
|
+
error += f"; could not stop computation {computation_id}: {exc}"
|
|
543
|
+
self._finish(slot, "cancelled", error=error)
|
|
469
544
|
|
|
470
545
|
def _call(self, slot: _Slot, what: str, fn: Callable[[], _T], *, idempotent: bool) -> _T | None:
|
|
471
546
|
"""Run one API call for *slot*; on error, schedule a retry or fail the job.
|
|
@@ -478,8 +553,14 @@ class _Dispatcher:
|
|
|
478
553
|
except (CodeOceanError, requests.RequestException) as exc:
|
|
479
554
|
delay = _retry_delay(exc, slot.api_errors, idempotent=idempotent)
|
|
480
555
|
if delay is None:
|
|
481
|
-
|
|
482
|
-
|
|
556
|
+
ambiguous = _is_ambiguous(exc)
|
|
557
|
+
note = " It may have taken effect anyway; check before rerunning." if ambiguous else ""
|
|
558
|
+
self._finish(
|
|
559
|
+
slot,
|
|
560
|
+
"failed",
|
|
561
|
+
error=f"{what} failed: {exc}.{note}",
|
|
562
|
+
failure="api_unavailable" if ambiguous else "api_rejected",
|
|
563
|
+
)
|
|
483
564
|
return None
|
|
484
565
|
slot.api_errors += 1
|
|
485
566
|
slot.next_at = _now() + delay
|
|
@@ -553,6 +634,7 @@ class _Dispatcher:
|
|
|
553
634
|
slot,
|
|
554
635
|
"failed",
|
|
555
636
|
error=f"timed out after {self.timeout_s:.0f} s; computation {computation_id} left running",
|
|
637
|
+
failure="timeout",
|
|
556
638
|
)
|
|
557
639
|
else:
|
|
558
640
|
slot.next_at = _now() + self.poll_interval_s
|
|
@@ -565,10 +647,13 @@ class _Dispatcher:
|
|
|
565
647
|
elif self.is_failed_start(computation) and slot.start_retries_used < self.start_retries:
|
|
566
648
|
slot.start_retries_used += 1
|
|
567
649
|
slot.phase = _Phase.PENDING
|
|
568
|
-
slot.
|
|
569
|
-
|
|
650
|
+
backoff_s = self.start_retry_backoff_s * 2 ** (slot.start_retries_used - 1)
|
|
651
|
+
slot.next_at = _now() + backoff_s
|
|
652
|
+
self.next_launch_at = max(self.next_launch_at, slot.next_at)
|
|
653
|
+
logger.warning("%s: %s; relaunching in %.0f s", slot.job.label, _describe(computation), backoff_s)
|
|
570
654
|
else:
|
|
571
|
-
|
|
655
|
+
failure: Failure = "failed_start" if self.is_failed_start(computation) else "computation"
|
|
656
|
+
self._finish(slot, "failed", error=_describe(computation), failure=failure)
|
|
572
657
|
|
|
573
658
|
def _start_capture(self, slot: _Slot, computation: Computation) -> None:
|
|
574
659
|
assert slot.job.capture is not None
|
|
@@ -577,7 +662,12 @@ class _Dispatcher:
|
|
|
577
662
|
# Broad on purpose: one job's bad callback must not orphan the others' computations.
|
|
578
663
|
except Exception as exc:
|
|
579
664
|
logger.exception("%s: capture callback raised", slot.job.label)
|
|
580
|
-
self._finish(
|
|
665
|
+
self._finish(
|
|
666
|
+
slot,
|
|
667
|
+
"failed",
|
|
668
|
+
error=f"capture callback raised for computation {computation.id}: {exc!r}",
|
|
669
|
+
failure="capture_callback",
|
|
670
|
+
)
|
|
581
671
|
return
|
|
582
672
|
if slot.job.key is not None and key_tag(slot.job.key) not in params.tags:
|
|
583
673
|
params = dataclasses.replace(params, tags=[*params.tags, key_tag(slot.job.key)])
|
|
@@ -618,7 +708,10 @@ class _Dispatcher:
|
|
|
618
708
|
logger.warning("%s: capture %s failed; capturing again", slot.job.label, asset_id)
|
|
619
709
|
else:
|
|
620
710
|
self._finish(
|
|
621
|
-
slot,
|
|
711
|
+
slot,
|
|
712
|
+
"failed",
|
|
713
|
+
error=f"capture {asset_id} of computation {slot.computation_ids[-1]} failed",
|
|
714
|
+
failure="capture",
|
|
622
715
|
)
|
|
623
716
|
else:
|
|
624
717
|
slot.next_at = _now() + _ASSET_POLL_S
|
{aind_codeocean_dispatch-0.2.2.dist-info → aind_codeocean_dispatch-0.4.0.dist-info}/METADATA
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: aind-codeocean-dispatch
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Launch, monitor, and capture batches of Code Ocean capsule runs
|
|
5
5
|
Project-URL: Repository, https://github.com/AllenNeuralDynamics/aind-codeocean-dispatch/
|
|
6
6
|
Project-URL: Issues, https://github.com/AllenNeuralDynamics/aind-codeocean-dispatch/issues
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
aind_codeocean_dispatch/__init__.py,sha256=iWzsXeODLf8-XLxMDQl2FNT351Usrl-Nd11-zLdiJSc,1042
|
|
2
|
+
aind_codeocean_dispatch/capsule_git.py,sha256=BnUiGY1blXAFqnNAztBbYX0h5U5Mlsm5M2sFsOa4ICk,2762
|
|
3
|
+
aind_codeocean_dispatch/capture.py,sha256=aj3dgLNtGRmKhUbVZeIcPjfbPP42YYiz6gwMGwZSlAg,3506
|
|
4
|
+
aind_codeocean_dispatch/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
5
|
+
aind_codeocean_dispatch/runner.py,sha256=heg62GPc8gx7loOicFgY1K46aP6jC_5jky4_8K_IzHI,29767
|
|
6
|
+
aind_codeocean_dispatch-0.4.0.dist-info/METADATA,sha256=dki-UD71tzNI4GFQ6YQpQfJtbsuH5d9tTXj2OCAxrTQ,2797
|
|
7
|
+
aind_codeocean_dispatch-0.4.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
8
|
+
aind_codeocean_dispatch-0.4.0.dist-info/licenses/LICENSE,sha256=zMZxYbR1i_XxgyJP_rPSWKcxY7QtyxUOzbIpowHNjCs,1093
|
|
9
|
+
aind_codeocean_dispatch-0.4.0.dist-info/RECORD,,
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
aind_codeocean_dispatch/__init__.py,sha256=NcdbegNPvYKWVRArhlkdEL7HP9kof1OOiH8aRcrcszY,660
|
|
2
|
-
aind_codeocean_dispatch/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
3
|
-
aind_codeocean_dispatch/runner.py,sha256=Zwfvt7NuLxrCrV6t8KPfgiqkdBlV8e6XlcXkkJKwKHk,25344
|
|
4
|
-
aind_codeocean_dispatch-0.2.2.dist-info/METADATA,sha256=LMBckmvXZjxfWyeGaIw-siS4aDAYETmCEnVcWwVWYyg,2797
|
|
5
|
-
aind_codeocean_dispatch-0.2.2.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
6
|
-
aind_codeocean_dispatch-0.2.2.dist-info/licenses/LICENSE,sha256=zMZxYbR1i_XxgyJP_rPSWKcxY7QtyxUOzbIpowHNjCs,1093
|
|
7
|
-
aind_codeocean_dispatch-0.2.2.dist-info/RECORD,,
|
|
File without changes
|
{aind_codeocean_dispatch-0.2.2.dist-info → aind_codeocean_dispatch-0.4.0.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|