aind-codeocean-dispatch 0.2.2__tar.gz → 0.4.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 (28) hide show
  1. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/CHANGELOG.md +17 -0
  2. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/PKG-INFO +1 -1
  3. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/pyproject.toml +1 -1
  4. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/src/aind_codeocean_dispatch/__init__.py +12 -0
  5. aind_codeocean_dispatch-0.4.0/src/aind_codeocean_dispatch/capsule_git.py +79 -0
  6. aind_codeocean_dispatch-0.4.0/src/aind_codeocean_dispatch/capture.py +89 -0
  7. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/src/aind_codeocean_dispatch/runner.py +114 -21
  8. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/tests/fakes.py +13 -1
  9. aind_codeocean_dispatch-0.4.0/tests/test_capsule_git.py +115 -0
  10. aind_codeocean_dispatch-0.4.0/tests/test_capture.py +110 -0
  11. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/tests/test_runner.py +116 -0
  12. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/uv.lock +1 -1
  13. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/.copier-answers.yml +0 -0
  14. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  15. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  16. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/.github/ISSUE_TEMPLATE/user-story.md +0 -0
  17. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/.github/dependabot.yml +0 -0
  18. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/.github/workflows/bump-call.yml +0 -0
  19. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/.github/workflows/ci-call.yml +0 -0
  20. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/.github/workflows/publish-call.yml +0 -0
  21. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/.gitignore +0 -0
  22. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/.python-version +0 -0
  23. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/CLAUDE.md +0 -0
  24. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/LICENSE +0 -0
  25. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/README.md +0 -0
  26. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/scripts/run_linters_and_checks.sh +0 -0
  27. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.0}/src/aind_codeocean_dispatch/py.typed +0 -0
  28. {aind_codeocean_dispatch-0.2.2 → aind_codeocean_dispatch-0.4.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.4.0 (2026-10-15)
9
+
10
+ ### Feat
11
+
12
+ - classify failures and optionally cancel the batch on one
13
+
14
+ ## v0.3.0 (2026-10-15)
15
+
16
+ ### Feat
17
+
18
+ - add capture-naming and capsule-commit helpers
19
+ - back off before relaunching a failed start
20
+
21
+ ### Fix
22
+
23
+ - recognise failed starts by end_status, not state
24
+
8
25
  ## v0.2.2 (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.2.2
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
@@ -13,7 +13,7 @@ authors = [
13
13
  ]
14
14
  classifiers = ["Programming Language :: Python :: 3"]
15
15
  readme = "README.md"
16
- version = "0.2.2"
16
+ version = "0.4.0"
17
17
 
18
18
  dependencies = [
19
19
  "aind-code-ocean-pipeline-utils>=0.7.1",
@@ -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 != "failed"
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
- A capsule that crashes before writing anything matches too, so a relaunch can be
176
- spent on a real bug; ``start_retries`` bounds that cost.
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.state == ComputationState.Failed and not computation.has_results
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 stops the others or raises; check the outcomes, or pass them
232
- to :func:`raise_for_failures`.
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(jobs, max_in_flight=max_in_flight, start_retries=start_retries, capture_retries=capture_retries)
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(jobs: Sequence[Job], *, max_in_flight: int | None, start_retries: int, capture_retries: int) -> None:
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: failed: %s", slot.job.label, error)
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
- note = " It may have taken effect anyway; check before rerunning." if _is_ambiguous(exc) else ""
482
- self._finish(slot, "failed", error=f"{what} failed: {exc}.{note}")
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.next_at = _now()
569
- logger.warning("%s: %s; relaunching", slot.job.label, _describe(computation))
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
- self._finish(slot, "failed", error=_describe(computation))
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(slot, "failed", error=f"capture callback raised for computation {computation.id}: {exc!r}")
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, "failed", error=f"capture {asset_id} of computation {slot.computation_ids[-1]} failed"
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
@@ -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
- FAILED_START = snapshot(ComputationState.Failed, end_status=ComputationEndStatus.Failed, has_results=False)
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
 
@@ -100,6 +104,8 @@ class FakeComputations:
100
104
  launch_errors: dict[str, list[Exception]] = field(default_factory=dict)
101
105
  launches: list[tuple[float, str, str]] = field(default_factory=list) # (time, capsule_id, computation_id)
102
106
  max_running: int = 0
107
+ deleted: list[str] = field(default_factory=list)
108
+ delete_errors: list[Exception] = field(default_factory=list)
103
109
  _ids: itertools.count[int] = field(default_factory=itertools.count)
104
110
  _scripts: dict[str, list[Any]] = field(default_factory=dict)
105
111
  _running: set[str] = field(default_factory=set)
@@ -115,6 +121,12 @@ class FakeComputations:
115
121
  self.max_running = max(self.max_running, len(self._running))
116
122
  return self._computation(computation_id, snapshot(ComputationState.Initializing))
117
123
 
124
+ def delete_computation(self, computation_id: str) -> None:
125
+ if self.delete_errors:
126
+ raise self.delete_errors.pop(0)
127
+ self.deleted.append(computation_id)
128
+ self._running.discard(computation_id)
129
+
118
130
  def get_computation(self, computation_id: str) -> Computation:
119
131
  script = self._scripts[computation_id]
120
132
  step = script.pop(0) if len(script) > 1 else script[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]
@@ -24,6 +24,7 @@ from aind_codeocean_dispatch import (
24
24
  from tests.fakes import (
25
25
  CRASHED,
26
26
  FAILED_START,
27
+ FAILED_STATE_START,
27
28
  RUNNING,
28
29
  SUCCEEDED,
29
30
  FakeClient,
@@ -109,6 +110,15 @@ def test_failed_start_is_relaunched_once_by_default(clock: FakeClock) -> None:
109
110
  assert outcome.computation_ids == ("comp-0", "comp-1")
110
111
 
111
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
+
112
122
  def test_failed_start_beyond_retries_fails_with_every_attempt(clock: FakeClock) -> None:
113
123
  client = make_client(clock, {"a": [[FAILED_START], [FAILED_START]]})
114
124
 
@@ -117,6 +127,30 @@ def test_failed_start_beyond_retries_fails_with_every_attempt(clock: FakeClock)
117
127
  assert outcome.status == "failed"
118
128
  assert outcome.computation_ids == ("comp-0", "comp-1")
119
129
  assert "has_results=False" in (outcome.error or "")
130
+ assert (outcome.failure, outcome.transient) == ("failed_start", True)
131
+
132
+
133
+ def test_failed_starts_back_off_and_hold_other_launches(clock: FakeClock) -> None:
134
+ client = make_client(clock, {"a": [[FAILED_START], [FAILED_START], [SUCCEEDED]], "b": [[SUCCEEDED]]})
135
+
136
+ outcomes = run_jobs(client, [job("a"), job("b")], start_retries=2, start_retry_backoff_s=60, poll_interval_s=5)
137
+
138
+ assert [o.status for o in outcomes] == ["captured", "captured"]
139
+ a_launches = [t for t, capsule, _ in client.computations.launches if capsule == "a"]
140
+ # Relaunches wait 60 s, then 120 s, after each failed start is seen.
141
+ assert a_launches[1] - a_launches[0] >= 60
142
+ assert a_launches[2] - a_launches[1] >= 120
143
+ assert len(client.computations.launches) == 4
144
+
145
+
146
+ def test_failed_start_holds_a_launch_still_pending(clock: FakeClock) -> None:
147
+ client = make_client(clock, {"a": [[FAILED_START], [SUCCEEDED]], "b": [[SUCCEEDED]]})
148
+
149
+ run_jobs(client, [job("a"), job("b")], max_in_flight=1, start_retry_backoff_s=60, poll_interval_s=5)
150
+
151
+ first_a = client.computations.launches[0][0]
152
+ (b_launch,) = [t for t, capsule, _ in client.computations.launches if capsule == "b"]
153
+ assert b_launch - first_a >= 60
120
154
 
121
155
 
122
156
  def test_start_retries_zero_disables_relaunch(clock: FakeClock) -> None:
@@ -135,6 +169,7 @@ def test_capsule_crash_is_not_relaunched(clock: FakeClock) -> None:
135
169
 
136
170
  assert [o.status for o in outcomes] == ["failed", "captured"]
137
171
  assert "exit_code=1" in (outcomes[0].error or "")
172
+ assert (outcomes[0].failure, outcomes[0].transient) == ("computation", False)
138
173
  assert len(client.computations.launches) == 2
139
174
 
140
175
 
@@ -160,6 +195,7 @@ def test_server_error_on_launch_is_not_retried(clock: FakeClock) -> None:
160
195
  assert outcome.status == "failed"
161
196
  assert "may have taken effect" in (outcome.error or "")
162
197
  assert client.computations.launches == []
198
+ assert (outcome.failure, outcome.transient) == ("api_unavailable", True)
163
199
 
164
200
 
165
201
  def test_transient_errors_on_status_checks_do_not_fail_a_running_job(clock: FakeClock) -> None:
@@ -178,6 +214,7 @@ def test_client_error_on_status_check_fails_the_job(clock: FakeClock) -> None:
178
214
  assert outcome.status == "failed"
179
215
  assert "status check failed" in (outcome.error or "")
180
216
  assert "may have taken effect" not in (outcome.error or "")
217
+ assert (outcome.failure, outcome.transient) == ("api_rejected", False)
181
218
 
182
219
 
183
220
  def test_rate_limited_capture_is_retried(clock: FakeClock) -> None:
@@ -229,6 +266,7 @@ def test_failed_capture_fails_the_job_by_default(clock: FakeClock) -> None:
229
266
 
230
267
  assert outcome.status == "failed"
231
268
  assert "capture asset-0" in (outcome.error or "")
269
+ assert (outcome.failure, outcome.transient) == ("capture", True)
232
270
 
233
271
 
234
272
  def test_timeout_fails_the_job_and_leaves_it_running(clock: FakeClock) -> None:
@@ -238,6 +276,83 @@ def test_timeout_fails_the_job_and_leaves_it_running(clock: FakeClock) -> None:
238
276
 
239
277
  assert outcome.status == "failed"
240
278
  assert "comp-0 left running" in (outcome.error or "")
279
+ assert (outcome.failure, outcome.transient) == ("timeout", False)
280
+
281
+
282
+ # -- cancelling on failure ----------------------------------------------------
283
+
284
+
285
+ def test_successful_outcomes_carry_no_failure(clock: FakeClock) -> None:
286
+ (outcome,) = run_jobs(make_client(clock, {"a": [[SUCCEEDED]]}), [job("a")])
287
+
288
+ assert (outcome.failure, outcome.transient, outcome.ok) == (None, False, True)
289
+
290
+
291
+ def test_failure_cancels_running_and_pending_jobs(clock: FakeClock) -> None:
292
+ client = make_client(clock, {"a": [[CRASHED]], "b": [[RUNNING]], "c": [[SUCCEEDED]]})
293
+
294
+ outcomes = run_jobs(client, [job("a"), job("b"), job("c")], max_in_flight=2, cancel_on_failure=True)
295
+
296
+ assert [o.status for o in outcomes] == ["failed", "cancelled", "cancelled"]
297
+ assert client.computations.deleted == ["comp-1"]
298
+ assert [capsule for _, capsule, _ in client.computations.launches] == ["a", "b"]
299
+ assert outcomes[1].computation_ids == ("comp-1",)
300
+ assert outcomes[2].computation_ids == ()
301
+ assert outcomes[1].error == "cancelled after a failed"
302
+ assert not outcomes[1].ok
303
+ assert outcomes[1].failure is None
304
+
305
+
306
+ def test_capture_under_way_finishes_when_cancelling(clock: FakeClock) -> None:
307
+ client = make_client(
308
+ clock,
309
+ {"a": [[RUNNING, CRASHED]], "b": [[SUCCEEDED]]},
310
+ capture_states=[[DataAssetState.Draft] * 10 + [DataAssetState.Ready]],
311
+ )
312
+
313
+ outcomes = run_jobs(client, [job("a"), job("b")], cancel_on_failure=True)
314
+
315
+ assert [o.status for o in outcomes] == ["failed", "captured"]
316
+ assert client.computations.deleted == []
317
+
318
+
319
+ def test_cancel_predicate_decides_per_failure(clock: FakeClock) -> None:
320
+ client = make_client(clock, {"a": [[FAILED_START]], "b": [[RUNNING, SUCCEEDED]]})
321
+
322
+ outcomes = run_jobs(
323
+ client, [job("a"), job("b")], start_retries=0, cancel_on_failure=lambda outcome: not outcome.transient
324
+ )
325
+
326
+ assert [o.status for o in outcomes] == ["failed", "captured"]
327
+
328
+
329
+ def test_failed_stop_is_reported_on_the_cancelled_job(clock: FakeClock) -> None:
330
+ client = make_client(clock, {"a": [[CRASHED]], "b": [[RUNNING]]})
331
+ client.computations.delete_errors = [http_error(503)]
332
+
333
+ outcomes = run_jobs(client, [job("a"), job("b")], cancel_on_failure=True)
334
+
335
+ assert outcomes[1].status == "cancelled"
336
+ assert "could not stop computation comp-1" in (outcomes[1].error or "")
337
+
338
+
339
+ def test_failures_continue_by_default(clock: FakeClock) -> None:
340
+ client = make_client(clock, {"a": [[CRASHED]], "b": [[RUNNING, SUCCEEDED]]})
341
+
342
+ outcomes = run_jobs(client, [job("a"), job("b")])
343
+
344
+ assert [o.status for o in outcomes] == ["failed", "captured"]
345
+ assert client.computations.deleted == []
346
+
347
+
348
+ def test_raise_for_failures_lists_cancelled_jobs(clock: FakeClock) -> None:
349
+ client = make_client(clock, {"a": [[CRASHED]], "b": [[RUNNING]]})
350
+ outcomes = run_jobs(client, [job("a"), job("b")], cancel_on_failure=True)
351
+
352
+ with pytest.raises(DispatchFailed) as info:
353
+ raise_for_failures(outcomes)
354
+
355
+ assert [o.job.label for o in info.value.failures] == ["a", "b"]
241
356
 
242
357
 
243
358
  # -- reuse --------------------------------------------------------------------
@@ -310,6 +425,7 @@ def test_capture_callback_error_fails_only_that_job(clock: FakeClock) -> None:
310
425
  outcomes = run_jobs(client, jobs)
311
426
 
312
427
  assert [o.status for o in outcomes] == ["failed", "captured"]
428
+ assert outcomes[0].failure == "capture_callback"
313
429
 
314
430
 
315
431
  def test_duplicate_labels_are_rejected(clock: FakeClock) -> None:
@@ -17,7 +17,7 @@ wheels = [
17
17
 
18
18
  [[package]]
19
19
  name = "aind-codeocean-dispatch"
20
- version = "0.2.2"
20
+ version = "0.4.0"
21
21
  source = { editable = "." }
22
22
  dependencies = [
23
23
  { name = "aind-code-ocean-pipeline-utils" },