aind-codeocean-dispatch 0.2.2__py3-none-any.whl → 0.3.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 +8 -0
- aind_codeocean_dispatch/capsule_git.py +79 -0
- aind_codeocean_dispatch/capture.py +89 -0
- aind_codeocean_dispatch/runner.py +35 -9
- {aind_codeocean_dispatch-0.2.2.dist-info → aind_codeocean_dispatch-0.3.0.dist-info}/METADATA +1 -1
- aind_codeocean_dispatch-0.3.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.3.0.dist-info}/WHEEL +0 -0
- {aind_codeocean_dispatch-0.2.2.dist-info → aind_codeocean_dispatch-0.3.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -2,6 +2,8 @@
|
|
|
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 (
|
|
6
8
|
DispatchFailed,
|
|
7
9
|
DispatchInterrupted,
|
|
@@ -20,11 +22,17 @@ __all__ = [
|
|
|
20
22
|
"DispatchInterrupted",
|
|
21
23
|
"Job",
|
|
22
24
|
"Outcome",
|
|
25
|
+
"capsule_head_commit",
|
|
26
|
+
"capture_as",
|
|
27
|
+
"capture_named_by_data_description",
|
|
28
|
+
"derived_name",
|
|
23
29
|
"failed_without_results",
|
|
30
|
+
"head_commit",
|
|
24
31
|
"job_key",
|
|
25
32
|
"key_tag",
|
|
26
33
|
"raise_for_failures",
|
|
27
34
|
"run_jobs",
|
|
35
|
+
"run_owner_email",
|
|
28
36
|
"succeeded",
|
|
29
37
|
]
|
|
30
38
|
|
|
@@ -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
|
|
@@ -172,10 +172,13 @@ def succeeded(computation: Computation) -> bool:
|
|
|
172
172
|
def failed_without_results(computation: Computation) -> bool:
|
|
173
173
|
"""Whether a computation looks like it never started: failed, with no results.
|
|
174
174
|
|
|
175
|
-
|
|
176
|
-
|
|
175
|
+
Code Ocean reports a failed start as ``state=Completed`` with
|
|
176
|
+
``end_status=Failed``, ``exit_code=0`` and no results, so this keys on
|
|
177
|
+
``end_status``, not ``state``. A capsule that crashes before writing anything
|
|
178
|
+
can match too, so a relaunch can be spent on a real bug; ``start_retries``
|
|
179
|
+
bounds that cost.
|
|
177
180
|
"""
|
|
178
|
-
return computation.
|
|
181
|
+
return computation.end_status == ComputationEndStatus.Failed and not computation.has_results
|
|
179
182
|
|
|
180
183
|
|
|
181
184
|
def key_tag(key: str) -> str:
|
|
@@ -220,6 +223,7 @@ def run_jobs(
|
|
|
220
223
|
max_in_flight: int | None = None,
|
|
221
224
|
launch_interval_s: float = 0.0,
|
|
222
225
|
start_retries: int = 1,
|
|
226
|
+
start_retry_backoff_s: float = 60.0,
|
|
223
227
|
is_failed_start: Callable[[Computation], bool] = failed_without_results,
|
|
224
228
|
capture_retries: int = 0,
|
|
225
229
|
reuse: bool = False,
|
|
@@ -245,6 +249,10 @@ def run_jobs(
|
|
|
245
249
|
regardless; this only spreads the burst.
|
|
246
250
|
start_retries : int, optional
|
|
247
251
|
Relaunches allowed per job when *is_failed_start* matches.
|
|
252
|
+
start_retry_backoff_s : float, optional
|
|
253
|
+
Wait before the first relaunch, doubling for each later one. Every pending
|
|
254
|
+
launch is held too: a start failure usually means machine capacity ran out,
|
|
255
|
+
and the runs holding it will not free it at once.
|
|
248
256
|
is_failed_start : callable, optional
|
|
249
257
|
Classifies a failed computation as a platform start failure.
|
|
250
258
|
capture_retries : int, optional
|
|
@@ -272,13 +280,20 @@ def run_jobs(
|
|
|
272
280
|
When a shutdown signal arrives (handlers installed by the caller, see
|
|
273
281
|
:func:`aind_code_ocean_pipeline_utils.process.install_shutdown_handlers`).
|
|
274
282
|
"""
|
|
275
|
-
_validate(
|
|
283
|
+
_validate(
|
|
284
|
+
jobs,
|
|
285
|
+
max_in_flight=max_in_flight,
|
|
286
|
+
start_retries=start_retries,
|
|
287
|
+
start_retry_backoff_s=start_retry_backoff_s,
|
|
288
|
+
capture_retries=capture_retries,
|
|
289
|
+
)
|
|
276
290
|
return _Dispatcher(
|
|
277
291
|
_without_transport_retries(client),
|
|
278
292
|
jobs,
|
|
279
293
|
max_in_flight=max_in_flight,
|
|
280
294
|
launch_interval_s=launch_interval_s,
|
|
281
295
|
start_retries=start_retries,
|
|
296
|
+
start_retry_backoff_s=start_retry_backoff_s,
|
|
282
297
|
is_failed_start=is_failed_start,
|
|
283
298
|
capture_retries=capture_retries,
|
|
284
299
|
reuse=reuse,
|
|
@@ -299,7 +314,14 @@ def _without_transport_retries(client: CodeOcean) -> CodeOcean:
|
|
|
299
314
|
return dataclasses.replace(client, retries=0)
|
|
300
315
|
|
|
301
316
|
|
|
302
|
-
def _validate(
|
|
317
|
+
def _validate(
|
|
318
|
+
jobs: Sequence[Job],
|
|
319
|
+
*,
|
|
320
|
+
max_in_flight: int | None,
|
|
321
|
+
start_retries: int,
|
|
322
|
+
start_retry_backoff_s: float,
|
|
323
|
+
capture_retries: int,
|
|
324
|
+
) -> None:
|
|
303
325
|
labels = [job.label for job in jobs]
|
|
304
326
|
if len(set(labels)) != len(labels):
|
|
305
327
|
raise ValueError(f"job labels must be unique: {sorted(labels)}")
|
|
@@ -308,8 +330,8 @@ def _validate(jobs: Sequence[Job], *, max_in_flight: int | None, start_retries:
|
|
|
308
330
|
raise ValueError("job keys must be unique within a batch")
|
|
309
331
|
if max_in_flight is not None and max_in_flight < 1:
|
|
310
332
|
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")
|
|
333
|
+
if start_retries < 0 or capture_retries < 0 or start_retry_backoff_s < 0:
|
|
334
|
+
raise ValueError("retry counts and back-off cannot be negative")
|
|
313
335
|
|
|
314
336
|
|
|
315
337
|
def _prune(value: Any) -> Any:
|
|
@@ -389,6 +411,7 @@ class _Dispatcher:
|
|
|
389
411
|
max_in_flight: int | None,
|
|
390
412
|
launch_interval_s: float,
|
|
391
413
|
start_retries: int,
|
|
414
|
+
start_retry_backoff_s: float,
|
|
392
415
|
is_failed_start: Callable[[Computation], bool],
|
|
393
416
|
capture_retries: int,
|
|
394
417
|
reuse: bool,
|
|
@@ -400,6 +423,7 @@ class _Dispatcher:
|
|
|
400
423
|
self.max_in_flight = max_in_flight
|
|
401
424
|
self.launch_interval_s = launch_interval_s
|
|
402
425
|
self.start_retries = start_retries
|
|
426
|
+
self.start_retry_backoff_s = start_retry_backoff_s
|
|
403
427
|
self.is_failed_start = is_failed_start
|
|
404
428
|
self.capture_retries = capture_retries
|
|
405
429
|
self.reuse = reuse
|
|
@@ -565,8 +589,10 @@ class _Dispatcher:
|
|
|
565
589
|
elif self.is_failed_start(computation) and slot.start_retries_used < self.start_retries:
|
|
566
590
|
slot.start_retries_used += 1
|
|
567
591
|
slot.phase = _Phase.PENDING
|
|
568
|
-
slot.
|
|
569
|
-
|
|
592
|
+
backoff_s = self.start_retry_backoff_s * 2 ** (slot.start_retries_used - 1)
|
|
593
|
+
slot.next_at = _now() + backoff_s
|
|
594
|
+
self.next_launch_at = max(self.next_launch_at, slot.next_at)
|
|
595
|
+
logger.warning("%s: %s; relaunching in %.0f s", slot.job.label, _describe(computation), backoff_s)
|
|
570
596
|
else:
|
|
571
597
|
self._finish(slot, "failed", error=_describe(computation))
|
|
572
598
|
|
{aind_codeocean_dispatch-0.2.2.dist-info → aind_codeocean_dispatch-0.3.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.3.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=PGmzsqDdguM1t8RvC1u8zTXTTCZgE77Cwl_-3-JIrPA,964
|
|
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=6YtBhiR59qKPoSgMqrnTz4EfT8Xt49PxkGyouprPy6I,26376
|
|
6
|
+
aind_codeocean_dispatch-0.3.0.dist-info/METADATA,sha256=lYuFf_NAFxAAvZEjwisQ4Z79670W7Hn84xUTZ6Kbuuk,2797
|
|
7
|
+
aind_codeocean_dispatch-0.3.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
8
|
+
aind_codeocean_dispatch-0.3.0.dist-info/licenses/LICENSE,sha256=zMZxYbR1i_XxgyJP_rPSWKcxY7QtyxUOzbIpowHNjCs,1093
|
|
9
|
+
aind_codeocean_dispatch-0.3.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.3.0.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|