aind-codeocean-dispatch 0.2.1__tar.gz → 0.3.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.
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/CHANGELOG.md +17 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/PKG-INFO +1 -1
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/pyproject.toml +1 -1
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/src/aind_codeocean_dispatch/__init__.py +8 -0
- aind_codeocean_dispatch-0.3.0/src/aind_codeocean_dispatch/capsule_git.py +79 -0
- aind_codeocean_dispatch-0.3.0/src/aind_codeocean_dispatch/capture.py +89 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/src/aind_codeocean_dispatch/runner.py +53 -12
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/tests/fakes.py +6 -1
- aind_codeocean_dispatch-0.3.0/tests/test_capsule_git.py +115 -0
- aind_codeocean_dispatch-0.3.0/tests/test_capture.py +110 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/tests/test_runner.py +62 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/uv.lock +1 -1
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.copier-answers.yml +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.github/ISSUE_TEMPLATE/user-story.md +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.github/dependabot.yml +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.github/workflows/bump-call.yml +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.github/workflows/ci-call.yml +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.github/workflows/publish-call.yml +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.gitignore +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.python-version +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/CLAUDE.md +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/LICENSE +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/README.md +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/scripts/run_linters_and_checks.sh +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/src/aind_codeocean_dispatch/py.typed +0 -0
- {aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/tests/__init__.py +0 -0
|
@@ -5,6 +5,23 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## v0.3.0 (2026-10-15)
|
|
9
|
+
|
|
10
|
+
### Feat
|
|
11
|
+
|
|
12
|
+
- add capture-naming and capsule-commit helpers
|
|
13
|
+
- back off before relaunching a failed start
|
|
14
|
+
|
|
15
|
+
### Fix
|
|
16
|
+
|
|
17
|
+
- recognise failed starts by end_status, not state
|
|
18
|
+
|
|
19
|
+
## v0.2.2 (2026-10-15)
|
|
20
|
+
|
|
21
|
+
### Fix
|
|
22
|
+
|
|
23
|
+
- run on a non-retrying copy of the caller's client
|
|
24
|
+
|
|
8
25
|
## v0.2.1 (2026-10-15)
|
|
9
26
|
|
|
10
27
|
### Fix
|
|
@@ -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
|
|
@@ -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
|
|
@@ -6,7 +6,9 @@ counters rather than locks, and no thread is parked per job.
|
|
|
6
6
|
|
|
7
7
|
Error policy
|
|
8
8
|
------------
|
|
9
|
-
|
|
9
|
+
Every 429 or 5xx must surface here, so :func:`run_jobs` works on a copy of the
|
|
10
|
+
client with ``retries=0``: transport-level retries would resend POSTs below this
|
|
11
|
+
policy, and their exhausted retries raise without the status code it reads.
|
|
10
12
|
|
|
11
13
|
- **429** is retried on every call, honouring ``Retry-After``: the server rejected
|
|
12
14
|
the request without acting on it.
|
|
@@ -170,10 +172,13 @@ def succeeded(computation: Computation) -> bool:
|
|
|
170
172
|
def failed_without_results(computation: Computation) -> bool:
|
|
171
173
|
"""Whether a computation looks like it never started: failed, with no results.
|
|
172
174
|
|
|
173
|
-
|
|
174
|
-
|
|
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.
|
|
175
180
|
"""
|
|
176
|
-
return computation.
|
|
181
|
+
return computation.end_status == ComputationEndStatus.Failed and not computation.has_results
|
|
177
182
|
|
|
178
183
|
|
|
179
184
|
def key_tag(key: str) -> str:
|
|
@@ -218,6 +223,7 @@ def run_jobs(
|
|
|
218
223
|
max_in_flight: int | None = None,
|
|
219
224
|
launch_interval_s: float = 0.0,
|
|
220
225
|
start_retries: int = 1,
|
|
226
|
+
start_retry_backoff_s: float = 60.0,
|
|
221
227
|
is_failed_start: Callable[[Computation], bool] = failed_without_results,
|
|
222
228
|
capture_retries: int = 0,
|
|
223
229
|
reuse: bool = False,
|
|
@@ -232,7 +238,8 @@ def run_jobs(
|
|
|
232
238
|
Parameters
|
|
233
239
|
----------
|
|
234
240
|
client : CodeOcean
|
|
235
|
-
Authenticated client.
|
|
241
|
+
Authenticated client. Its own ``retries`` setting is overridden on a copy;
|
|
242
|
+
the caller's client is left unchanged.
|
|
236
243
|
jobs : Sequence[Job]
|
|
237
244
|
Launched in order, subject to the cap and pacing.
|
|
238
245
|
max_in_flight : int, optional
|
|
@@ -242,6 +249,10 @@ def run_jobs(
|
|
|
242
249
|
regardless; this only spreads the burst.
|
|
243
250
|
start_retries : int, optional
|
|
244
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.
|
|
245
256
|
is_failed_start : callable, optional
|
|
246
257
|
Classifies a failed computation as a platform start failure.
|
|
247
258
|
capture_retries : int, optional
|
|
@@ -269,13 +280,20 @@ def run_jobs(
|
|
|
269
280
|
When a shutdown signal arrives (handlers installed by the caller, see
|
|
270
281
|
:func:`aind_code_ocean_pipeline_utils.process.install_shutdown_handlers`).
|
|
271
282
|
"""
|
|
272
|
-
_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
|
+
)
|
|
273
290
|
return _Dispatcher(
|
|
274
|
-
client,
|
|
291
|
+
_without_transport_retries(client),
|
|
275
292
|
jobs,
|
|
276
293
|
max_in_flight=max_in_flight,
|
|
277
294
|
launch_interval_s=launch_interval_s,
|
|
278
295
|
start_retries=start_retries,
|
|
296
|
+
start_retry_backoff_s=start_retry_backoff_s,
|
|
279
297
|
is_failed_start=is_failed_start,
|
|
280
298
|
capture_retries=capture_retries,
|
|
281
299
|
reuse=reuse,
|
|
@@ -284,7 +302,26 @@ def run_jobs(
|
|
|
284
302
|
).run()
|
|
285
303
|
|
|
286
304
|
|
|
287
|
-
def
|
|
305
|
+
def _without_transport_retries(client: CodeOcean) -> CodeOcean:
|
|
306
|
+
"""Return *client*, or a copy with ``retries=0`` if it retries requests itself.
|
|
307
|
+
|
|
308
|
+
The copy opens a new session, so anything mounted on the original's ``session``
|
|
309
|
+
by hand is not carried over.
|
|
310
|
+
"""
|
|
311
|
+
if client.retries in (0, None):
|
|
312
|
+
return client
|
|
313
|
+
logger.info("using a copy of the client with retries=0 (was %r); run_jobs retries what is safe", client.retries)
|
|
314
|
+
return dataclasses.replace(client, retries=0)
|
|
315
|
+
|
|
316
|
+
|
|
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:
|
|
288
325
|
labels = [job.label for job in jobs]
|
|
289
326
|
if len(set(labels)) != len(labels):
|
|
290
327
|
raise ValueError(f"job labels must be unique: {sorted(labels)}")
|
|
@@ -293,8 +330,8 @@ def _validate(jobs: Sequence[Job], *, max_in_flight: int | None, start_retries:
|
|
|
293
330
|
raise ValueError("job keys must be unique within a batch")
|
|
294
331
|
if max_in_flight is not None and max_in_flight < 1:
|
|
295
332
|
raise ValueError(f"max_in_flight must be at least 1, got {max_in_flight}")
|
|
296
|
-
if start_retries < 0 or capture_retries < 0:
|
|
297
|
-
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")
|
|
298
335
|
|
|
299
336
|
|
|
300
337
|
def _prune(value: Any) -> Any:
|
|
@@ -374,6 +411,7 @@ class _Dispatcher:
|
|
|
374
411
|
max_in_flight: int | None,
|
|
375
412
|
launch_interval_s: float,
|
|
376
413
|
start_retries: int,
|
|
414
|
+
start_retry_backoff_s: float,
|
|
377
415
|
is_failed_start: Callable[[Computation], bool],
|
|
378
416
|
capture_retries: int,
|
|
379
417
|
reuse: bool,
|
|
@@ -385,6 +423,7 @@ class _Dispatcher:
|
|
|
385
423
|
self.max_in_flight = max_in_flight
|
|
386
424
|
self.launch_interval_s = launch_interval_s
|
|
387
425
|
self.start_retries = start_retries
|
|
426
|
+
self.start_retry_backoff_s = start_retry_backoff_s
|
|
388
427
|
self.is_failed_start = is_failed_start
|
|
389
428
|
self.capture_retries = capture_retries
|
|
390
429
|
self.reuse = reuse
|
|
@@ -550,8 +589,10 @@ class _Dispatcher:
|
|
|
550
589
|
elif self.is_failed_start(computation) and slot.start_retries_used < self.start_retries:
|
|
551
590
|
slot.start_retries_used += 1
|
|
552
591
|
slot.phase = _Phase.PENDING
|
|
553
|
-
slot.
|
|
554
|
-
|
|
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)
|
|
555
596
|
else:
|
|
556
597
|
self._finish(slot, "failed", error=_describe(computation))
|
|
557
598
|
|
|
@@ -74,7 +74,11 @@ RUNNING = snapshot(ComputationState.Running)
|
|
|
74
74
|
SUCCEEDED = snapshot(
|
|
75
75
|
ComputationState.Completed, end_status=ComputationEndStatus.Succeeded, exit_code=0, has_results=True
|
|
76
76
|
)
|
|
77
|
-
|
|
77
|
+
# The shape Code Ocean reports for a run that never started.
|
|
78
|
+
FAILED_START = snapshot(
|
|
79
|
+
ComputationState.Completed, end_status=ComputationEndStatus.Failed, exit_code=0, has_results=False
|
|
80
|
+
)
|
|
81
|
+
FAILED_STATE_START = snapshot(ComputationState.Failed, end_status=ComputationEndStatus.Failed, has_results=False)
|
|
78
82
|
CRASHED = snapshot(ComputationState.Completed, end_status=ComputationEndStatus.Failed, exit_code=1, has_results=True)
|
|
79
83
|
|
|
80
84
|
|
|
@@ -166,3 +170,4 @@ class FakeDataAssets:
|
|
|
166
170
|
class FakeClient:
|
|
167
171
|
computations: FakeComputations
|
|
168
172
|
data_assets: FakeDataAssets
|
|
173
|
+
retries: Any = 0
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
import requests
|
|
7
|
+
|
|
8
|
+
from aind_codeocean_dispatch import capsule_git
|
|
9
|
+
from aind_codeocean_dispatch.capsule_git import capsule_head_commit, head_commit, run_owner_email
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _pkt(payload: bytes) -> bytes:
|
|
13
|
+
return b"%04x" % (len(payload) + 4) + payload
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
SHA = "0123456789abcdef0123456789abcdef01234567"
|
|
17
|
+
REFS = (
|
|
18
|
+
_pkt(b"# service=git-upload-pack\n")
|
|
19
|
+
+ b"0000"
|
|
20
|
+
+ _pkt(SHA.encode() + b" HEAD\0multi_ack symref=HEAD:refs/heads/master\n")
|
|
21
|
+
+ _pkt(SHA.encode() + b" refs/heads/master\n")
|
|
22
|
+
+ b"0000"
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class _Response:
|
|
27
|
+
def __init__(self, content: bytes = b"", status: int = 200, payload: Any = None) -> None:
|
|
28
|
+
self.content = content
|
|
29
|
+
self.status = status
|
|
30
|
+
self.payload = payload
|
|
31
|
+
|
|
32
|
+
def json(self) -> Any:
|
|
33
|
+
return self.payload
|
|
34
|
+
|
|
35
|
+
def raise_for_status(self) -> None:
|
|
36
|
+
if self.status >= 400:
|
|
37
|
+
raise requests.HTTPError(str(self.status))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _Session:
|
|
41
|
+
def __init__(self) -> None:
|
|
42
|
+
self.paths: list[str] = []
|
|
43
|
+
|
|
44
|
+
def get(self, path: str) -> _Response:
|
|
45
|
+
self.paths.append(path)
|
|
46
|
+
return _Response(payload={"owner_email": "someone@example.org"})
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class _Capsules:
|
|
50
|
+
def get_capsule(self, capsule_id: str) -> Any:
|
|
51
|
+
return type("Capsule", (), {"slug": "1234567"})()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class _Client:
|
|
55
|
+
domain = "https://example.org"
|
|
56
|
+
token = "token"
|
|
57
|
+
|
|
58
|
+
def __init__(self) -> None:
|
|
59
|
+
self.capsules = _Capsules()
|
|
60
|
+
self.session = _Session()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_head_commit_reads_the_advertisement():
|
|
64
|
+
assert head_commit(REFS) == SHA
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_head_commit_without_head():
|
|
68
|
+
assert head_commit(_pkt(b"# service=git-upload-pack\n") + b"0000") is None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_run_owner_email_reads_this_run(monkeypatch):
|
|
72
|
+
monkeypatch.setenv("CO_COMPUTATION_ID", "comp-1")
|
|
73
|
+
client = _Client()
|
|
74
|
+
assert run_owner_email(client) == "someone@example.org" # type: ignore[arg-type]
|
|
75
|
+
assert client.session.paths == ["computations/comp-1"]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_run_owner_email_off_code_ocean(monkeypatch):
|
|
79
|
+
monkeypatch.delenv("CO_COMPUTATION_ID", raising=False)
|
|
80
|
+
with pytest.raises(ValueError, match="CO_COMPUTATION_ID"):
|
|
81
|
+
run_owner_email(_Client()) # type: ignore[arg-type]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_capsule_head_commit_authenticates_as_the_run_owner(monkeypatch):
|
|
85
|
+
monkeypatch.setenv("CO_COMPUTATION_ID", "comp-1")
|
|
86
|
+
seen: dict[str, Any] = {}
|
|
87
|
+
|
|
88
|
+
def fake_get(url: str, **kwargs: Any) -> _Response:
|
|
89
|
+
seen.update(kwargs, url=url)
|
|
90
|
+
return _Response(REFS)
|
|
91
|
+
|
|
92
|
+
monkeypatch.setattr(capsule_git.requests, "get", fake_get)
|
|
93
|
+
assert capsule_head_commit(_Client(), "capsule-id") == SHA # type: ignore[arg-type]
|
|
94
|
+
assert seen["url"] == "https://example.org/capsule-1234567.git/info/refs"
|
|
95
|
+
assert seen["params"] == {"service": "git-upload-pack"}
|
|
96
|
+
assert seen["auth"] == ("someone@example.org", "token")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def test_capsule_head_commit_with_explicit_username(monkeypatch):
|
|
100
|
+
monkeypatch.delenv("CO_COMPUTATION_ID", raising=False)
|
|
101
|
+
seen: dict[str, Any] = {}
|
|
102
|
+
|
|
103
|
+
def fake_get(url: str, **kwargs: Any) -> _Response:
|
|
104
|
+
seen.update(kwargs)
|
|
105
|
+
return _Response(REFS)
|
|
106
|
+
|
|
107
|
+
monkeypatch.setattr(capsule_git.requests, "get", fake_get)
|
|
108
|
+
assert capsule_head_commit(_Client(), "capsule-id", username="me@example.org") == SHA # type: ignore[arg-type]
|
|
109
|
+
assert seen["auth"] == ("me@example.org", "token")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def test_capsule_head_commit_raises_on_auth_failure(monkeypatch):
|
|
113
|
+
monkeypatch.setattr(capsule_git.requests, "get", lambda url, **kw: _Response(status=401))
|
|
114
|
+
with pytest.raises(requests.HTTPError):
|
|
115
|
+
capsule_head_commit(_Client(), "capsule-id", username="me@example.org") # type: ignore[arg-type]
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
from codeocean.computation import Computation, ComputationState
|
|
11
|
+
|
|
12
|
+
from aind_codeocean_dispatch import capture
|
|
13
|
+
from aind_codeocean_dispatch.capture import capture_as, capture_named_by_data_description, derived_name
|
|
14
|
+
from tests.fakes import build
|
|
15
|
+
|
|
16
|
+
DERIVED = "SmartSPIM_1_2026-01-02_03-04-05_preprocessed_2026-02-03_04-05-06"
|
|
17
|
+
COMPUTATION = build(
|
|
18
|
+
Computation, id="comp-1", created=0, name="comp-1", owner="owner", run_time=0, state=ComputationState.Completed
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class _Item:
|
|
24
|
+
path: str
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class _Computations:
|
|
29
|
+
files: dict[str, bytes]
|
|
30
|
+
error: Exception | None = None
|
|
31
|
+
reads: list[str] = field(default_factory=list)
|
|
32
|
+
|
|
33
|
+
def list_computation_results(self, computation_id: str, path: str = "") -> Any:
|
|
34
|
+
if self.error is not None:
|
|
35
|
+
raise self.error
|
|
36
|
+
return type("Folder", (), {"items": [_Item(p) for p in self.files]})()
|
|
37
|
+
|
|
38
|
+
def get_result_file_urls(self, computation_id: str, path: str) -> Any:
|
|
39
|
+
self.reads.append(path)
|
|
40
|
+
return type("FileURLs", (), {"download_url": f"mem://{path}"})()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class _Client:
|
|
45
|
+
computations: _Computations
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@pytest.fixture
|
|
49
|
+
def client(monkeypatch) -> _Client:
|
|
50
|
+
fake = _Client(_Computations({}))
|
|
51
|
+
monkeypatch.setattr(
|
|
52
|
+
capture.urllib.request,
|
|
53
|
+
"urlopen",
|
|
54
|
+
lambda url, timeout: io.BytesIO(fake.computations.files[url.removeprefix("mem://")]),
|
|
55
|
+
)
|
|
56
|
+
return fake
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _description(**values: Any) -> bytes:
|
|
60
|
+
return json.dumps(values).encode()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_capture_as_targets_the_computation():
|
|
64
|
+
params = capture_as("name", ["t"], mount="m")(COMPUTATION)
|
|
65
|
+
assert (params.name, params.mount, params.tags) == ("name", "m", ["t"])
|
|
66
|
+
assert params.source.computation.id == "comp-1"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_capture_as_mounts_under_the_name_by_default():
|
|
70
|
+
assert capture_as("name", [])(COMPUTATION).mount == "name"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@pytest.mark.parametrize(
|
|
74
|
+
("description", "expected"),
|
|
75
|
+
[
|
|
76
|
+
({"data_level": "derived", "name": DERIVED}, DERIVED),
|
|
77
|
+
({"data_level": "raw", "name": DERIVED}, None),
|
|
78
|
+
({"data_level": "derived", "name": "not_a_derived_name"}, None),
|
|
79
|
+
({"data_level": "derived"}, None),
|
|
80
|
+
],
|
|
81
|
+
)
|
|
82
|
+
def test_derived_name(description, expected):
|
|
83
|
+
assert derived_name(description) == expected
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_named_by_data_description(client):
|
|
87
|
+
client.computations.files["data_description.json"] = _description(data_level="derived", name=DERIVED)
|
|
88
|
+
params = capture_named_by_data_description(client, "fallback", ["t"])(COMPUTATION) # type: ignore[arg-type]
|
|
89
|
+
assert (params.name, params.mount, params.tags) == (DERIVED, DERIVED, ["t"])
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _assert_fallback(name: str) -> None:
|
|
93
|
+
assert re.fullmatch(r"fallback_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}", name), name
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def test_falls_back_without_a_data_description(client):
|
|
97
|
+
params = capture_named_by_data_description(client, "fallback", [])(COMPUTATION) # type: ignore[arg-type]
|
|
98
|
+
_assert_fallback(params.name)
|
|
99
|
+
assert params.mount == params.name
|
|
100
|
+
assert client.computations.reads == []
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def test_falls_back_on_an_unusable_data_description(client):
|
|
104
|
+
client.computations.files["data_description.json"] = _description(data_level="raw", name=DERIVED)
|
|
105
|
+
_assert_fallback(capture_named_by_data_description(client, "fallback", [])(COMPUTATION).name) # type: ignore[arg-type]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def test_falls_back_when_results_cannot_be_read(client):
|
|
109
|
+
client.computations.error = RuntimeError("boom")
|
|
110
|
+
_assert_fallback(capture_named_by_data_description(client, "fallback", [])(COMPUTATION).name) # type: ignore[arg-type]
|
|
@@ -5,9 +5,11 @@ from typing import Any
|
|
|
5
5
|
import pytest
|
|
6
6
|
import requests
|
|
7
7
|
from aind_code_ocean_pipeline_utils.process import GracefulExit
|
|
8
|
+
from codeocean import CodeOcean
|
|
8
9
|
from codeocean.components import Ownership
|
|
9
10
|
from codeocean.computation import Computation, DataAssetsRunParam, NamedRunParam, RunParams
|
|
10
11
|
from codeocean.data_asset import DataAssetParams, DataAssetState
|
|
12
|
+
from urllib3.util import Retry
|
|
11
13
|
|
|
12
14
|
from aind_codeocean_dispatch import (
|
|
13
15
|
DispatchFailed,
|
|
@@ -22,6 +24,7 @@ from aind_codeocean_dispatch import (
|
|
|
22
24
|
from tests.fakes import (
|
|
23
25
|
CRASHED,
|
|
24
26
|
FAILED_START,
|
|
27
|
+
FAILED_STATE_START,
|
|
25
28
|
RUNNING,
|
|
26
29
|
SUCCEEDED,
|
|
27
30
|
FakeClient,
|
|
@@ -107,6 +110,15 @@ def test_failed_start_is_relaunched_once_by_default(clock: FakeClock) -> None:
|
|
|
107
110
|
assert outcome.computation_ids == ("comp-0", "comp-1")
|
|
108
111
|
|
|
109
112
|
|
|
113
|
+
def test_failed_start_reported_as_failed_state_is_relaunched(clock: FakeClock) -> None:
|
|
114
|
+
client = make_client(clock, {"a": [[FAILED_STATE_START], [SUCCEEDED]]})
|
|
115
|
+
|
|
116
|
+
(outcome,) = run_jobs(client, [job("a")])
|
|
117
|
+
|
|
118
|
+
assert outcome.status == "captured"
|
|
119
|
+
assert outcome.computation_ids == ("comp-0", "comp-1")
|
|
120
|
+
|
|
121
|
+
|
|
110
122
|
def test_failed_start_beyond_retries_fails_with_every_attempt(clock: FakeClock) -> None:
|
|
111
123
|
client = make_client(clock, {"a": [[FAILED_START], [FAILED_START]]})
|
|
112
124
|
|
|
@@ -117,6 +129,29 @@ def test_failed_start_beyond_retries_fails_with_every_attempt(clock: FakeClock)
|
|
|
117
129
|
assert "has_results=False" in (outcome.error or "")
|
|
118
130
|
|
|
119
131
|
|
|
132
|
+
def test_failed_starts_back_off_and_hold_other_launches(clock: FakeClock) -> None:
|
|
133
|
+
client = make_client(clock, {"a": [[FAILED_START], [FAILED_START], [SUCCEEDED]], "b": [[SUCCEEDED]]})
|
|
134
|
+
|
|
135
|
+
outcomes = run_jobs(client, [job("a"), job("b")], start_retries=2, start_retry_backoff_s=60, poll_interval_s=5)
|
|
136
|
+
|
|
137
|
+
assert [o.status for o in outcomes] == ["captured", "captured"]
|
|
138
|
+
a_launches = [t for t, capsule, _ in client.computations.launches if capsule == "a"]
|
|
139
|
+
# Relaunches wait 60 s, then 120 s, after each failed start is seen.
|
|
140
|
+
assert a_launches[1] - a_launches[0] >= 60
|
|
141
|
+
assert a_launches[2] - a_launches[1] >= 120
|
|
142
|
+
assert len(client.computations.launches) == 4
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def test_failed_start_holds_a_launch_still_pending(clock: FakeClock) -> None:
|
|
146
|
+
client = make_client(clock, {"a": [[FAILED_START], [SUCCEEDED]], "b": [[SUCCEEDED]]})
|
|
147
|
+
|
|
148
|
+
run_jobs(client, [job("a"), job("b")], max_in_flight=1, start_retry_backoff_s=60, poll_interval_s=5)
|
|
149
|
+
|
|
150
|
+
first_a = client.computations.launches[0][0]
|
|
151
|
+
(b_launch,) = [t for t, capsule, _ in client.computations.launches if capsule == "b"]
|
|
152
|
+
assert b_launch - first_a >= 60
|
|
153
|
+
|
|
154
|
+
|
|
120
155
|
def test_start_retries_zero_disables_relaunch(clock: FakeClock) -> None:
|
|
121
156
|
client = make_client(clock, {"a": [[FAILED_START]]})
|
|
122
157
|
|
|
@@ -315,6 +350,33 @@ def test_duplicate_labels_are_rejected(clock: FakeClock) -> None:
|
|
|
315
350
|
run_jobs(make_client(clock, {}), [job("a"), job("a")])
|
|
316
351
|
|
|
317
352
|
|
|
353
|
+
@pytest.mark.parametrize("retries", [3, Retry(total=5, allowed_methods=["POST"])])
|
|
354
|
+
def test_client_that_retries_itself_still_runs(clock: FakeClock, retries: Any) -> None:
|
|
355
|
+
client = make_client(clock, {"a": [[SUCCEEDED]]})
|
|
356
|
+
client.retries = retries
|
|
357
|
+
|
|
358
|
+
outcomes = run_jobs(client, [job("a")])
|
|
359
|
+
|
|
360
|
+
assert [o.status for o in outcomes] == ["captured"]
|
|
361
|
+
assert client.retries is retries
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def test_retrying_client_is_copied_without_retries() -> None:
|
|
365
|
+
original = CodeOcean(domain="https://codeocean.example", token="x", retries=Retry(total=5))
|
|
366
|
+
|
|
367
|
+
copy = runner._without_transport_retries(original)
|
|
368
|
+
|
|
369
|
+
assert copy is not original and copy.session is not original.session
|
|
370
|
+
assert (copy.retries, copy.domain, copy.token) == (0, original.domain, original.token)
|
|
371
|
+
assert isinstance(original.retries, Retry)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def test_non_retrying_client_is_used_as_is() -> None:
|
|
375
|
+
client = CodeOcean(domain="https://codeocean.example", token="x")
|
|
376
|
+
|
|
377
|
+
assert runner._without_transport_retries(client) is client
|
|
378
|
+
|
|
379
|
+
|
|
318
380
|
def test_invalid_key_is_rejected() -> None:
|
|
319
381
|
with pytest.raises(ValueError, match="key"):
|
|
320
382
|
job("a", key="has space")
|
|
File without changes
|
{aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.github/ISSUE_TEMPLATE/bug_report.md
RENAMED
|
File without changes
|
|
File without changes
|
{aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.github/ISSUE_TEMPLATE/user-story.md
RENAMED
|
File without changes
|
|
File without changes
|
{aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.github/workflows/bump-call.yml
RENAMED
|
File without changes
|
{aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.github/workflows/ci-call.yml
RENAMED
|
File without changes
|
{aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/.github/workflows/publish-call.yml
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/scripts/run_linters_and_checks.sh
RENAMED
|
File without changes
|
{aind_codeocean_dispatch-0.2.1 → aind_codeocean_dispatch-0.3.0}/src/aind_codeocean_dispatch/py.typed
RENAMED
|
File without changes
|
|
File without changes
|