aind-codeocean-dispatch 0.5.0__py3-none-any.whl → 0.7.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.
@@ -14,6 +14,7 @@ from .runner import (
14
14
  Outcome,
15
15
  failed_without_results,
16
16
  job_key,
17
+ key_marker,
17
18
  key_tag,
18
19
  raise_for_failures,
19
20
  run_jobs,
@@ -35,6 +36,7 @@ __all__ = [
35
36
  "failed_without_results",
36
37
  "head_commit",
37
38
  "job_key",
39
+ "key_marker",
38
40
  "key_tag",
39
41
  "raise_for_failures",
40
42
  "read_only_retries",
@@ -0,0 +1,118 @@
1
+ """Bounded retrieval of worker-produced failure artifacts.
2
+
3
+ Install the ``diagnostics`` extra to use this module. Callers supply the stage
4
+ and unit rather than teaching the dispatcher their capsule parameter names.
5
+ Fetching diagnostics never changes whether a computation succeeded.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from dataclasses import dataclass, replace
12
+ from typing import Any
13
+
14
+ import requests
15
+ from codeocean.error import Error as CodeOceanError
16
+
17
+ from .runner import Outcome
18
+
19
+ REPORT_LIMIT = 2 * 1024 * 1024
20
+ FAILURE_LIMIT = 64 * 1024
21
+ _UNAVAILABLE = (CodeOceanError, requests.RequestException, OSError, ValueError, KeyError, TypeError, RecursionError)
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class WorkerFailure:
26
+ """An explanation and optional evidence from one failed computation."""
27
+
28
+ computation_id: str
29
+ filename: str
30
+ error: str
31
+ report: dict[str, Any] | None = None
32
+
33
+ def render(self) -> str:
34
+ """Include the worker and exact results artifact for follow-up."""
35
+ return f"{self.error}; worker {self.computation_id}; details: {self.filename} in worker results"
36
+
37
+
38
+ def result_json(client: Any, computation_id: str, filename: str, limit: int = REPORT_LIMIT) -> dict[str, Any]:
39
+ """Read a JSON object with bounded download size and request timeout.
40
+
41
+ This lower-level function propagates errors for callers that require the
42
+ artifact. Signed download URLs are used for the request and never logged.
43
+ """
44
+ if limit <= 0:
45
+ raise ValueError("An artifact byte limit must be positive")
46
+ urls = client.computations.get_result_file_urls(computation_id, filename)
47
+ with requests.get(urls.download_url, stream=True, timeout=30) as response:
48
+ response.raise_for_status()
49
+ content = bytearray()
50
+ for chunk in response.iter_content(chunk_size=4096):
51
+ content.extend(chunk)
52
+ if len(content) > limit:
53
+ raise ValueError("Worker artifact exceeds limit")
54
+ value = json.loads(content)
55
+ if not isinstance(value, dict):
56
+ raise TypeError("Worker artifact is not an object")
57
+ return value
58
+
59
+
60
+ def worker_diagnostic_report(
61
+ client: Any, computation_id: str, stage: str, unit: str | None, failure: dict[str, Any]
62
+ ) -> dict[str, Any] | None:
63
+ """Prefer full evidence, retaining a valid summary when detail is unavailable."""
64
+ from aind_code_ocean_pipeline_utils.failure_reporting import diagnostic_path
65
+ from aind_diagnostics import validate_report
66
+
67
+ packet = failure.get("diagnostic_summary")
68
+ if not isinstance(packet, dict):
69
+ return None
70
+ try:
71
+ fallback = validate_report({**packet, "diagnostics": []})
72
+ except _UNAVAILABLE:
73
+ return None
74
+ path = (diagnostic_path(stage, unit) / "report.json").as_posix()
75
+ if failure.get("diagnostic_report_file") == path:
76
+ try:
77
+ return validate_report(result_json(client, computation_id, path))
78
+ except _UNAVAILABLE:
79
+ pass
80
+ fallback["facts"]["diagnostic_details_available"] = False
81
+ return fallback
82
+
83
+
84
+ def worker_failure(client: Any, computation_id: str, stage: str, unit: str | None = None) -> WorkerFailure | None:
85
+ """Read new or legacy failure artifacts, returning None when unavailable.
86
+
87
+ Only the expected stage/unit report path is fetched. A producer cannot
88
+ redirect the orchestrator to an unrelated result file. Callers retain their
89
+ existing fallback for older workers with no structured artifacts.
90
+ """
91
+ from aind_code_ocean_pipeline_utils.failure_reporting import diagnostic_path, safe_text
92
+
93
+ try:
94
+ filename = (diagnostic_path(stage, unit) / "failure.json").as_posix()
95
+ failure = result_json(client, computation_id, filename, FAILURE_LIMIT)
96
+ if type(failure.get("schema_version")) is not int or failure["schema_version"] != 1:
97
+ raise ValueError("Unknown failure report version")
98
+ if not isinstance(failure.get("error"), str):
99
+ raise TypeError("Invalid failure explanation")
100
+ report = worker_diagnostic_report(client, computation_id, stage, unit, failure)
101
+ error = report["summary"] if report is not None else safe_text(failure["error"])
102
+ causes = failure.get("causes") or []
103
+ if report is None and len(causes) > 1:
104
+ cause = causes[-1]
105
+ error += safe_text(f"; caused by {cause['type']}: {cause['message']}")
106
+ return WorkerFailure(computation_id, filename, error, report)
107
+ except _UNAVAILABLE:
108
+ return None
109
+
110
+
111
+ def diagnose_outcome(client: Any, outcome: Outcome, stage: str, unit: str | None = None) -> Outcome:
112
+ """Attach worker evidence without changing status, retry class, or capture state."""
113
+ if outcome.status != "failed" or not outcome.computation_ids:
114
+ return outcome
115
+ failure = worker_failure(client, outcome.computation_ids[-1], stage, unit)
116
+ if failure is None:
117
+ return outcome
118
+ return replace(outcome, error=failure.render(), diagnostic_report=failure.report)
@@ -18,7 +18,8 @@ policy, and their exhausted retries raise without the status code it reads.
18
18
  - **Any other HTTP error** fails the job.
19
19
 
20
20
  Policy beyond that -- concurrency cap, launch pacing, relaunching failed starts,
21
- retrying failed captures, reusing captured results -- is opt-in.
21
+ retrying failed captures, reusing captured results, resuming computations a
22
+ previous batch left running -- is opt-in.
22
23
  """
23
24
 
24
25
  from __future__ import annotations
@@ -55,6 +56,7 @@ __all__ = [
55
56
  "Outcome",
56
57
  "failed_without_results",
57
58
  "job_key",
59
+ "key_marker",
58
60
  "key_tag",
59
61
  "raise_for_failures",
60
62
  "run_jobs",
@@ -104,8 +106,10 @@ class Job:
104
106
  can depend on it. ``None`` stops at a successful computation.
105
107
  key : str, optional
106
108
  Resume key (see :func:`job_key`), added to the captured asset as
107
- :func:`key_tag`. With ``reuse=True``, a Ready asset carrying it that the
108
- caller created is returned instead of launching. ``None`` never reuses.
109
+ :func:`key_tag` and to the computation's name as :func:`key_marker`. With
110
+ ``reuse=True``, a Ready asset carrying it that the caller created is
111
+ returned instead of launching; with ``resume_owner``, the caller's
112
+ computation carrying it is followed instead. ``None`` does neither.
109
113
  """
110
114
 
111
115
  label: str
@@ -124,8 +128,9 @@ class Outcome:
124
128
  """How one job ended.
125
129
 
126
130
  ``computation_ids`` lists every launch attempt in order, so a relaunched job's
127
- failed starts stay traceable. ``failure`` is set only when ``status`` is
128
- ``"failed"``.
131
+ failed starts stay traceable; ``resumed`` says the first of them was found
132
+ running, or finished, rather than launched by this batch. ``failure`` is set
133
+ only when ``status`` is ``"failed"``.
129
134
  """
130
135
 
131
136
  job: Job
@@ -134,6 +139,8 @@ class Outcome:
134
139
  computation_ids: tuple[str, ...] = ()
135
140
  error: str | None = None
136
141
  failure: Failure | None = None
142
+ resumed: bool = False
143
+ diagnostic_report: dict[str, Any] | None = None
137
144
 
138
145
  @property
139
146
  def ok(self) -> bool:
@@ -154,6 +161,14 @@ class DispatchFailed(RuntimeError):
154
161
  lines = [f"{len(self.failures)} job(s) failed:"]
155
162
  lines += [f" {o.job.label}: {o.error}" for o in self.failures]
156
163
  super().__init__("\n".join(lines))
164
+ reports = [outcome.diagnostic_report for outcome in self.failures if outcome.diagnostic_report is not None]
165
+ if reports:
166
+ try:
167
+ from aind_diagnostics import combined_report
168
+
169
+ self.diagnostic_report = combined_report(reports)
170
+ except (ImportError, ValueError, TypeError, KeyError, RecursionError):
171
+ logger.warning("Could not combine worker diagnostics; original dispatch failure is retained")
157
172
 
158
173
 
159
174
  class DispatchInterrupted(GracefulExit):
@@ -203,6 +218,11 @@ def key_tag(key: str) -> str:
203
218
  return f"{_KEY_TAG_PREFIX}{key}"
204
219
 
205
220
 
221
+ def key_marker(key: str) -> str:
222
+ """Return the text a computation's name carries to be found again by resume *key*."""
223
+ return f"[{key_tag(key)}]"
224
+
225
+
206
226
  def job_key(run_params: RunParams, *, salt: str = "") -> str:
207
227
  """Return a resume key: 16 hex characters fingerprinting *run_params*.
208
228
 
@@ -247,6 +267,8 @@ def run_jobs(
247
267
  poll_interval_s: float = 60.0,
248
268
  timeout_s: float | None = None,
249
269
  cancel_on_failure: bool | Callable[[Outcome], bool] = False,
270
+ resume_owner: str | None = None,
271
+ on_outcome: Callable[[Outcome], None] | None = None,
250
272
  ) -> list[Outcome]:
251
273
  """Launch *jobs*, wait for each, capture its results, and report every outcome.
252
274
 
@@ -288,6 +310,17 @@ def run_jobs(
288
310
  Whether a failed job cancels the rest, or a predicate on its outcome. On
289
311
  cancel, pending jobs are not launched and running computations are stopped
290
312
  and deleted, all ending ``"cancelled"``; captures already under way finish.
313
+ resume_owner : str, optional
314
+ The caller's Code Ocean user id or email. When set, a keyed job whose
315
+ computation this owner launched earlier, and which is still running or
316
+ succeeded uncaptured, is followed from there instead of launched again; a
317
+ capture of it still in progress is waited on. Code Ocean lists every
318
+ user's computations and has no call naming the caller, hence the
319
+ argument. Needs codeocean 0.15 or later, whose computations carry an owner.
320
+ on_outcome : callable, optional
321
+ Called with each job's outcome as soon as it is reached, whatever the
322
+ status, so results can be used before the batch ends. An exception it
323
+ raises is logged and does not affect the batch.
291
324
 
292
325
  Returns
293
326
  -------
@@ -308,6 +341,7 @@ def run_jobs(
308
341
  start_retries=start_retries,
309
342
  start_retry_backoff_s=start_retry_backoff_s,
310
343
  capture_retries=capture_retries,
344
+ resume_owner=resume_owner,
311
345
  )
312
346
  return _Dispatcher(
313
347
  _without_transport_retries(client),
@@ -322,6 +356,8 @@ def run_jobs(
322
356
  poll_interval_s=poll_interval_s,
323
357
  timeout_s=timeout_s,
324
358
  cancel_on_failure=cancel_on_failure,
359
+ resume_owner=resume_owner,
360
+ on_outcome=on_outcome,
325
361
  ).run()
326
362
 
327
363
 
@@ -344,6 +380,7 @@ def _validate(
344
380
  start_retries: int,
345
381
  start_retry_backoff_s: float,
346
382
  capture_retries: int,
383
+ resume_owner: str | None,
347
384
  ) -> None:
348
385
  labels = [job.label for job in jobs]
349
386
  if len(set(labels)) != len(labels):
@@ -355,6 +392,8 @@ def _validate(
355
392
  raise ValueError(f"max_in_flight must be at least 1, got {max_in_flight}")
356
393
  if start_retries < 0 or capture_retries < 0 or start_retry_backoff_s < 0:
357
394
  raise ValueError("retry counts and back-off cannot be negative")
395
+ if resume_owner is not None and "owner" not in {f.name for f in dataclasses.fields(Computation)}:
396
+ raise ValueError("resume_owner needs codeocean 0.15 or later, whose computations carry an owner")
358
397
 
359
398
 
360
399
  def _prune(value: Any) -> Any:
@@ -422,6 +461,9 @@ class _Slot:
422
461
  start_retries_used: int = 0
423
462
  capture_retries_used: int = 0
424
463
  reuse_checked: bool = False
464
+ # Whether the current computation's name carries the key marker yet.
465
+ marked: bool = True
466
+ resumed: bool = False
425
467
  outcome: Outcome | None = None
426
468
 
427
469
 
@@ -441,6 +483,8 @@ class _Dispatcher:
441
483
  poll_interval_s: float,
442
484
  timeout_s: float | None,
443
485
  cancel_on_failure: bool | Callable[[Outcome], bool],
486
+ resume_owner: str | None,
487
+ on_outcome: Callable[[Outcome], None] | None,
444
488
  ) -> None:
445
489
  self.client = client
446
490
  self.slots = [_Slot(job) for job in jobs]
@@ -454,6 +498,10 @@ class _Dispatcher:
454
498
  self.poll_interval_s = poll_interval_s
455
499
  self.timeout_s = timeout_s
456
500
  self.cancel_on_failure = cancel_on_failure
501
+ self.resume_owner = resume_owner
502
+ self.on_outcome = on_outcome
503
+ # Per capsule or pipeline id: its computations carrying a key marker, by key.
504
+ self.resumable: dict[str, dict[str, list[Computation]]] = {}
457
505
  self.cancelled_by: str | None = None
458
506
  self.next_launch_at = 0.0
459
507
 
@@ -485,8 +533,8 @@ class _Dispatcher:
485
533
  for slot in self.slots:
486
534
  if slot.phase is not _Phase.PENDING or slot.next_at > _now():
487
535
  continue
488
- if self.reuse and slot.job.key is not None and not slot.reuse_checked:
489
- continue # still waiting on its reuse search
536
+ if self._searches_first() and slot.job.key is not None and not slot.reuse_checked:
537
+ continue # still waiting on its reuse or resume search
490
538
  if self.max_in_flight is not None and self._in_flight() >= self.max_in_flight:
491
539
  return
492
540
  if _now() < self.next_launch_at:
@@ -512,11 +560,18 @@ class _Dispatcher:
512
560
  computation_ids=tuple(slot.computation_ids),
513
561
  error=error,
514
562
  failure=failure,
563
+ resumed=slot.resumed,
515
564
  )
516
565
  if error is None:
517
566
  logger.info("%s: %s", slot.job.label, status)
518
567
  else:
519
568
  logger.error("%s: %s: %s", slot.job.label, status, error)
569
+ if self.on_outcome is not None:
570
+ try:
571
+ self.on_outcome(slot.outcome)
572
+ # Broad on purpose: the caller's hook must not orphan the other jobs' computations.
573
+ except Exception:
574
+ logger.exception("%s: on_outcome raised", slot.job.label)
520
575
  if status == "failed" and self.cancelled_by is None and self._should_cancel(slot.outcome):
521
576
  self._cancel_rest(slot.job.label)
522
577
 
@@ -571,9 +626,12 @@ class _Dispatcher:
571
626
 
572
627
  # -- phases -------------------------------------------------------------
573
628
 
629
+ def _searches_first(self) -> bool:
630
+ return self.reuse or self.resume_owner is not None
631
+
574
632
  def _check_reuse(self) -> None:
575
- """Resolve pending keyed jobs to existing captures, without using launch capacity."""
576
- if not self.reuse:
633
+ """Resolve pending keyed jobs to existing captures or computations, without using launch capacity."""
634
+ if not self._searches_first():
577
635
  return
578
636
  for slot in self.slots:
579
637
  if slot.phase is not _Phase.PENDING or slot.reuse_checked or slot.job.key is None:
@@ -590,20 +648,92 @@ class _Dispatcher:
590
648
  slot.api_errors += 1
591
649
  slot.next_at = _now() + delay
592
650
  continue
593
- # Reuse is an optimisation: launching is still correct.
651
+ # Reuse and resume are optimisations: launching is still correct.
594
652
  logger.warning("%s: reuse search failed (%s); launching", slot.job.label, exc)
595
653
  slot.reuse_checked = True
596
654
  continue
597
655
  slot.api_errors = 0
598
- slot.reuse_checked = True
599
656
  # Tag search may tokenize, so confirm the exact tag client-side.
600
- matches: list[DataAsset] = [
601
- asset for asset in results.results if asset.state == DataAssetState.Ready and tag in (asset.tags or [])
602
- ]
603
- if matches:
604
- slot.asset_id = max(matches, key=lambda asset: asset.created).id
657
+ tagged: list[DataAsset] = [asset for asset in results.results if tag in (asset.tags or [])]
658
+ ready = [asset for asset in tagged if asset.state == DataAssetState.Ready]
659
+ capturing = [asset for asset in tagged if asset.state not in (DataAssetState.Ready, DataAssetState.Failed)]
660
+ if self.reuse and ready:
661
+ slot.reuse_checked = True
662
+ slot.asset_id = max(ready, key=lambda asset: asset.created).id
605
663
  logger.info("%s: reusing captured asset %s", slot.job.label, slot.asset_id)
606
664
  self._finish(slot, "reused")
665
+ elif self.resume_owner is not None and capturing:
666
+ slot.reuse_checked = True
667
+ slot.asset_id = max(capturing, key=lambda asset: asset.created).id
668
+ slot.resumed = True
669
+ slot.phase = _Phase.CAPTURING
670
+ slot.next_at = _now()
671
+ logger.info("%s: resuming capture %s", slot.job.label, slot.asset_id)
672
+ elif self.resume_owner is not None:
673
+ # A succeeded computation already captured is not resumed: with reuse
674
+ # off, the caller asked for a new run, not a second capture.
675
+ self._resume_computation(slot, finished_too=not ready)
676
+ else:
677
+ slot.reuse_checked = True
678
+
679
+ def _resume_computation(self, slot: _Slot, *, finished_too: bool) -> None:
680
+ """Follow the owner's running, or else succeeded, computation of *slot*'s job, if there is one."""
681
+ assert slot.job.key is not None
682
+ source = slot.job.run_params.capsule_id or slot.job.run_params.pipeline_id
683
+ if source is None:
684
+ slot.reuse_checked = True
685
+ return
686
+ if source not in self.resumable:
687
+ listing = self._list_resumable(slot, source)
688
+ if listing is None:
689
+ return # retrying, or done
690
+ self.resumable[source] = listing
691
+ slot.reuse_checked = True
692
+ candidates = self.resumable[source].get(slot.job.key, [])
693
+ live = [c for c in candidates if c.state not in (ComputationState.Completed, ComputationState.Failed)]
694
+ done = [c for c in candidates if succeeded(c)] if finished_too else []
695
+ if not (live or done):
696
+ return
697
+ # A live computation is newer than any finished one worth resuming.
698
+ computation = max(live or done, key=lambda c: c.created)
699
+ slot.computation_ids.append(computation.id)
700
+ slot.resumed = True
701
+ slot.phase = _Phase.RUNNING
702
+ # Timeouts count from here: how long it ran before is unknown to this batch.
703
+ slot.launched_at = _now()
704
+ slot.next_at = _now()
705
+ logger.info("%s: resuming computation %s (%s)", slot.job.label, computation.id, computation.state)
706
+
707
+ def _list_resumable(self, slot: _Slot, source: str) -> dict[str, list[Computation]] | None:
708
+ """Index the owner's computations of *source* by the key their name carries."""
709
+ lister = (
710
+ self.client.capsules.list_computations
711
+ if slot.job.run_params.capsule_id
712
+ else self.client.pipelines.list_computations
713
+ )
714
+ try:
715
+ computations = lister(source)
716
+ except (CodeOceanError, requests.RequestException) as exc:
717
+ delay = _retry_delay(exc, slot.api_errors, idempotent=True)
718
+ if delay is not None:
719
+ slot.api_errors += 1
720
+ slot.next_at = _now() + delay
721
+ return None
722
+ logger.warning("%s: listing computations of %s failed (%s); launching", slot.job.label, source, exc)
723
+ return {}
724
+ slot.api_errors = 0
725
+ keys = {job.key for job in (s.job for s in self.slots) if job.key is not None}
726
+ index: dict[str, list[Computation]] = {}
727
+ for computation in computations:
728
+ if self.resume_owner not in (
729
+ getattr(computation, "owner", None),
730
+ getattr(computation, "owner_email", None),
731
+ ):
732
+ continue
733
+ for key in keys:
734
+ if key_marker(key) in (computation.name or ""):
735
+ index.setdefault(key, []).append(computation)
736
+ return index
607
737
 
608
738
  def _launch(self, slot: _Slot) -> None:
609
739
  computation = self._call(
@@ -620,8 +750,29 @@ class _Dispatcher:
620
750
  slot.next_at = slot.launched_at + self.poll_interval_s
621
751
  self.next_launch_at = slot.launched_at + self.launch_interval_s
622
752
  logger.info("%s: launched %s (attempt %d)", slot.job.label, computation.id, len(slot.computation_ids))
753
+ slot.marked = slot.job.key is None
754
+ if not slot.marked:
755
+ self._mark(slot)
756
+
757
+ def _mark(self, slot: _Slot) -> None:
758
+ """Name the computation after its job and key, so a later batch can resume it.
759
+
760
+ Best effort: until it succeeds, each status check tries again, and a
761
+ computation left unnamed is relaunched rather than resumed.
762
+ """
763
+ assert slot.job.key is not None
764
+ computation_id = slot.computation_ids[-1]
765
+ name = f"{slot.job.label} {key_marker(slot.job.key)}"
766
+ try:
767
+ self.client.computations.rename_computation(computation_id, name)
768
+ except (CodeOceanError, requests.RequestException) as exc:
769
+ logger.warning("%s: naming computation %s failed (%s); trying again", slot.job.label, computation_id, exc)
770
+ return
771
+ slot.marked = True
623
772
 
624
773
  def _poll_computation(self, slot: _Slot) -> None:
774
+ if not slot.marked:
775
+ self._mark(slot)
625
776
  computation_id = slot.computation_ids[-1]
626
777
  computation = self._call(
627
778
  slot, "status check", lambda: self.client.computations.get_computation(computation_id), idempotent=True
@@ -0,0 +1,182 @@
1
+ Metadata-Version: 2.5
2
+ Name: aind-codeocean-dispatch
3
+ Version: 0.7.0
4
+ Summary: Launch, monitor, and capture batches of Code Ocean capsule runs
5
+ Project-URL: Repository, https://github.com/AllenNeuralDynamics/aind-codeocean-dispatch/
6
+ Project-URL: Issues, https://github.com/AllenNeuralDynamics/aind-codeocean-dispatch/issues
7
+ Project-URL: Changelog, https://github.com/AllenNeuralDynamics/aind-codeocean-dispatch/blob/main/CHANGELOG.md
8
+ Author: Allen Institute for Neural Dynamics
9
+ Author-email: Galen Lynch <galen@galenlynch.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.11
14
+ Requires-Dist: aind-code-ocean-pipeline-utils>=0.7.1
15
+ Requires-Dist: codeocean>=0.13
16
+ Provides-Extra: diagnostics
17
+ Requires-Dist: aind-code-ocean-pipeline-utils[diagnostics]<1,>=0.10.0; extra == 'diagnostics'
18
+ Requires-Dist: aind-diagnostics<1,>=0.2.0; extra == 'diagnostics'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # AIND Code Ocean dispatch
22
+
23
+ ![CI](https://github.com/AllenNeuralDynamics/aind-codeocean-dispatch/actions/workflows/ci-call.yml/badge.svg)
24
+ [![PyPI - Version](https://img.shields.io/pypi/v/aind-codeocean-dispatch)](https://pypi.org/project/aind-codeocean-dispatch/)
25
+ [![semantic-release: angular](https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
26
+ [![License](https://img.shields.io/badge/license-MIT-brightgreen)](LICENSE)
27
+ [![ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
28
+ [![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json)](https://github.com/astral-sh/uv)
29
+ [![Copier](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/copier-org/copier/master/img/badge/badge-grayscale-inverted-border.json)](https://github.com/copier-org/copier)
30
+
31
+ Launch, monitor, and capture batches of Code Ocean capsule runs
32
+
33
+ ## Installation
34
+
35
+ If you choose to clone the repository, you can install the package by running the following command from the root directory of the repository:
36
+
37
+ ```bash
38
+ pip install .
39
+ ```
40
+
41
+ Otherwise, you can use pip:
42
+
43
+ ```bash
44
+ pip install aind-codeocean-dispatch
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ ### Running a batch of runs
50
+
51
+ `run_jobs` launches a batch of capsule or pipeline runs, waits for them from one polling
52
+ loop, and captures each successful run as a data asset:
53
+
54
+ ```python
55
+ from codeocean import CodeOcean
56
+ from codeocean.computation import DataAssetsRunParam, NamedRunParam, RunParams
57
+
58
+ from aind_codeocean_dispatch import Job, capture_as, job_key, raise_for_failures, run_jobs
59
+
60
+ client = CodeOcean(domain="https://codeocean.allenneuraldynamics.org", token=token)
61
+
62
+ jobs = []
63
+ for stream in streams:
64
+ params = RunParams(
65
+ capsule_id=WORKER_CAPSULE_ID,
66
+ data_assets=[DataAssetsRunParam(id=raw_asset_id, mount="raw")],
67
+ named_parameters=[NamedRunParam(param_name="stream", value=stream)],
68
+ )
69
+ jobs.append(
70
+ Job(
71
+ label=stream,
72
+ run_params=params,
73
+ capture=capture_as(f"{session}_{stream}_sorted", tags=["sorted"]),
74
+ key=job_key(params),
75
+ )
76
+ )
77
+
78
+ outcomes = run_jobs(client, jobs, launch_interval_s=1, start_retries=3, reuse=True)
79
+ raise_for_failures(outcomes)
80
+ asset_ids = {o.job.label: o.asset_id for o in outcomes}
81
+ ```
82
+
83
+ A failed job does not raise; each `Outcome` carries its `status`, `asset_id`, every
84
+ `computation_ids` attempt, and on failure an `error` and a `failure` kind.
85
+ `raise_for_failures` turns failures into one `DispatchFailed`.
86
+
87
+ Behaviour worth knowing:
88
+
89
+ - **Failed starts.** Code Ocean sometimes fails to start a run (`end_status=Failed`, no
90
+ results). Up to `start_retries` relaunches follow, after `start_retry_backoff_s` (60 s)
91
+ doubling each time, and every pending launch waits too, since the cause is usually
92
+ machine capacity.
93
+ - **Rate limits and errors.** 429s are retried honouring `Retry-After`. Other 5xx and
94
+ connection errors are retried on reads only: a launch or capture POST may already have
95
+ taken effect, so resending it could duplicate the computation or asset.
96
+ - **Pacing.** `max_in_flight` caps concurrent runs and `launch_interval_s` spaces
97
+ launches; both are off by default.
98
+ - **Reuse.** A job's `key` is added to its asset as a tag. With `reuse=True`, a Ready
99
+ asset you created with that tag is returned instead of launching. `job_key` fingerprints
100
+ the launch request; pass `salt=` for what the request cannot show, such as the commit
101
+ of an unreleased capsule (`capsule_head_commit(client, capsule_id)` reads it inside a
102
+ run).
103
+ - **Acting on each job as it finishes.** `on_outcome=` is called with each job's
104
+ `Outcome` as soon as it is reached, whatever its status, so a caller can register or
105
+ report results without waiting for the whole batch. An exception it raises is logged
106
+ and does not affect the other jobs.
107
+ - **Resuming a batch.** A keyed job's computation is renamed to its label plus
108
+ `key_marker(key)`. With `resume_owner=` set to your Code Ocean user id or email, a
109
+ later batch follows your computation of the same job instead of launching it again:
110
+ one still running is waited on, one that succeeded but was never captured is
111
+ captured, and a capture still in progress is waited on. A succeeded computation that
112
+ already has a Ready capture is resumed only through `reuse`. Code Ocean lists every
113
+ user's computations of a capsule and has no call naming the caller, hence the
114
+ argument; it needs codeocean 0.15 or later.
115
+ - **Cancelling a doomed batch.** `cancel_on_failure=True`, or a predicate on the failed
116
+ `Outcome` such as `lambda o: not o.transient`, stops launching and stops and deletes
117
+ running computations; captures already under way finish.
118
+ - **Capture names.** `capture_as` uses a fixed name. `capture_named_by_data_description`
119
+ uses the name a derived `data_description.json` in the results declares, and otherwise
120
+ a fallback name plus the capture time.
121
+
122
+ ### Capturing runs from a post-run automation
123
+
124
+ A Code Ocean pipeline can name an automation capsule that runs after every run. A capsule
125
+ whose `code/run` is
126
+
127
+ ```bash
128
+ #!/usr/bin/env bash
129
+ set -e
130
+ python -m aind_codeocean_dispatch.automation
131
+ ```
132
+
133
+ captures each successful run as an internal data asset, named by the results'
134
+ `data_description.json` when it declares a derived name and otherwise after the first
135
+ input asset. It needs only `CODEOCEAN_TOKEN`; `CAPTURE_TAGS`, `CAPTURE_FAILED` and
136
+ `CAPTURE_PERMISSIONS` adjust it. It registers nothing in DocDB and writes no external
137
+ bucket, so pipelines that publish use `asset-creation-capsule` instead.
138
+
139
+ ## Contributing
140
+
141
+ Setup, checks, tests and conventions are in [CONTRIBUTING.md](CONTRIBUTING.md).
142
+
143
+ ## License
144
+
145
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
146
+
147
+ ## Worker diagnostics
148
+
149
+ Install `aind-codeocean-dispatch[diagnostics]` when workers emit structured
150
+ failure artifacts. The extra uses `aind-diagnostics` for the report contract and
151
+ `aind-code-ocean-pipeline-utils` for the shared artifact namespace.
152
+
153
+ Optional reporting dependencies load when the reporting helpers are used, so
154
+ importing the module also works with the base installation.
155
+
156
+ ```python
157
+ from aind_codeocean_dispatch import raise_for_failures, run_jobs
158
+ from aind_codeocean_dispatch.diagnostics import diagnose_outcome
159
+
160
+ outcomes = run_jobs(client, jobs)
161
+ outcomes = [diagnose_outcome(client, item, stage="ephys", unit=item.job.label) for item in outcomes]
162
+ raise_for_failures(outcomes)
163
+ ```
164
+
165
+ Supply the stage and unit that the worker used when saving its report; the
166
+ dispatcher does not infer capsule-specific parameter names. `diagnose_outcome`
167
+ adds `diagnostic_report` and a readable explanation to failed outcomes while
168
+ preserving their status, failure classification, and capture state. Successful
169
+ outcomes are unchanged. `DispatchFailed` combines attached reports and retains
170
+ the individual failures for per-worker facts and provenance.
171
+
172
+ `worker_failure` reads the small failure header and then its namespaced report.
173
+ It bounds downloads, validates the common schema and causal graph, accepts new
174
+ domain codes, and keeps the producer's summary when full evidence is missing,
175
+ malformed, or larger than 2 MiB. It returns `None` when no usable header exists,
176
+ so callers can retain their fallback for older workers. Result-file errors
177
+ cannot replace the original computation failure, and signed download URLs are
178
+ never included in the returned explanation.
179
+
180
+ For other required JSON artifacts, `result_json` provides the same bounded
181
+ reader but propagates retrieval errors. Domain facts such as manifest coverage
182
+ remain the caller's responsibility.
@@ -0,0 +1,11 @@
1
+ aind_codeocean_dispatch/__init__.py,sha256=v8QJf40j_JhvvabsZlLLfXtscdDkfTAw6KTIGwTsfxE,1193
2
+ aind_codeocean_dispatch/automation.py,sha256=_7yPA8dJee2zLOY1vcPhdfFLoqDtiNY60hdz6INj11Q,6120
3
+ aind_codeocean_dispatch/capsule_git.py,sha256=BnUiGY1blXAFqnNAztBbYX0h5U5Mlsm5M2sFsOa4ICk,2762
4
+ aind_codeocean_dispatch/capture.py,sha256=aj3dgLNtGRmKhUbVZeIcPjfbPP42YYiz6gwMGwZSlAg,3506
5
+ aind_codeocean_dispatch/diagnostics.py,sha256=6KsS6JR7mLBz-D9H3Boohs7AJ7skxd80U49RnKoWT-Q,4994
6
+ aind_codeocean_dispatch/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
7
+ aind_codeocean_dispatch/runner.py,sha256=kPJvNVHRoD-nYzvFPNScHxMN3DNoDzqNeAmG0GnVF3Q,37622
8
+ aind_codeocean_dispatch-0.7.0.dist-info/METADATA,sha256=Iw20-frOEGI3jiS5o09YN-K2_mlxszkvFAq9_wAymhk,8765
9
+ aind_codeocean_dispatch-0.7.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ aind_codeocean_dispatch-0.7.0.dist-info/licenses/LICENSE,sha256=zMZxYbR1i_XxgyJP_rPSWKcxY7QtyxUOzbIpowHNjCs,1093
11
+ aind_codeocean_dispatch-0.7.0.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.32.4
2
+ Generator: hatchling 1.33.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -1,90 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: aind-codeocean-dispatch
3
- Version: 0.5.0
4
- Summary: Launch, monitor, and capture batches of Code Ocean capsule runs
5
- Project-URL: Repository, https://github.com/AllenNeuralDynamics/aind-codeocean-dispatch/
6
- Project-URL: Issues, https://github.com/AllenNeuralDynamics/aind-codeocean-dispatch/issues
7
- Project-URL: Changelog, https://github.com/AllenNeuralDynamics/aind-codeocean-dispatch/blob/main/CHANGELOG.md
8
- Author: Allen Institute for Neural Dynamics
9
- Author-email: Galen Lynch <galen@galenlynch.com>
10
- License-Expression: MIT
11
- License-File: LICENSE
12
- Classifier: Programming Language :: Python :: 3
13
- Requires-Python: >=3.11
14
- Requires-Dist: aind-code-ocean-pipeline-utils>=0.7.1
15
- Requires-Dist: codeocean>=0.13
16
- Description-Content-Type: text/markdown
17
-
18
- # AIND Code Ocean dispatch
19
-
20
- ![CI](https://github.com/AllenNeuralDynamics/aind-codeocean-dispatch/actions/workflows/ci-call.yml/badge.svg)
21
- [![PyPI - Version](https://img.shields.io/pypi/v/aind-codeocean-dispatch)](https://pypi.org/project/aind-codeocean-dispatch/)
22
- [![semantic-release: angular](https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
23
- [![License](https://img.shields.io/badge/license-MIT-brightgreen)](LICENSE)
24
- [![ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
25
- [![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json)](https://github.com/astral-sh/uv)
26
- [![Copier](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/copier-org/copier/master/img/badge/badge-grayscale-inverted-border.json)](https://github.com/copier-org/copier)
27
-
28
- Launch, monitor, and capture batches of Code Ocean capsule runs
29
-
30
- ## Installation
31
-
32
- If you choose to clone the repository, you can install the package by running the following command from the root directory of the repository:
33
-
34
- ```bash
35
- pip install .
36
- ```
37
-
38
- Otherwise, you can use pip:
39
-
40
- ```bash
41
- pip install aind-codeocean-dispatch
42
- ```
43
-
44
-
45
-
46
- To develop the code, run:
47
- ```bash
48
- uv sync
49
- ```
50
-
51
- ## Capturing runs from a post-run automation
52
-
53
- A Code Ocean pipeline can name an automation capsule that runs after every run. A capsule
54
- whose `code/run` is
55
-
56
- ```bash
57
- #!/usr/bin/env bash
58
- set -e
59
- python -m aind_codeocean_dispatch.automation
60
- ```
61
-
62
- captures each successful run as an internal data asset, named by the results'
63
- `data_description.json` when it declares a derived name and otherwise after the first
64
- input asset. It needs only `CODEOCEAN_TOKEN`; `CAPTURE_TAGS`, `CAPTURE_FAILED` and
65
- `CAPTURE_PERMISSIONS` adjust it. It registers nothing in DocDB and writes no external
66
- bucket, so pipelines that publish use `asset-creation-capsule` instead.
67
-
68
- ## Development
69
-
70
- Please test your changes using the full linting and testing suite:
71
-
72
- ```bash
73
- ./scripts/run_linters_and_checks.sh -c
74
- ```
75
-
76
- Or run individual commands:
77
- ```bash
78
- uv run --frozen ruff format # Code formatting
79
- uv run --frozen ruff check # Linting
80
- uv run --frozen mypy # Type checking
81
- uv run --frozen interrogate -v src # Documentation coverage
82
- uv run --frozen codespell --check-filenames # Spell checking
83
- uv run --frozen pytest --cov aind_codeocean_dispatch # Tests with coverage
84
- ```
85
-
86
-
87
-
88
- ## License
89
-
90
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -1,10 +0,0 @@
1
- aind_codeocean_dispatch/__init__.py,sha256=LLDHa2K8ChYN1PeeflQJhb3ONuK9Wt8T7oDX1ZtHcT4,1159
2
- aind_codeocean_dispatch/automation.py,sha256=_7yPA8dJee2zLOY1vcPhdfFLoqDtiNY60hdz6INj11Q,6120
3
- aind_codeocean_dispatch/capsule_git.py,sha256=BnUiGY1blXAFqnNAztBbYX0h5U5Mlsm5M2sFsOa4ICk,2762
4
- aind_codeocean_dispatch/capture.py,sha256=aj3dgLNtGRmKhUbVZeIcPjfbPP42YYiz6gwMGwZSlAg,3506
5
- aind_codeocean_dispatch/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
6
- aind_codeocean_dispatch/runner.py,sha256=heg62GPc8gx7loOicFgY1K46aP6jC_5jky4_8K_IzHI,29767
7
- aind_codeocean_dispatch-0.5.0.dist-info/METADATA,sha256=wMZTyME-CGXIuy9kxLfeqcxDE3hcX0Eru2SAN4DeI9k,3445
8
- aind_codeocean_dispatch-0.5.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
9
- aind_codeocean_dispatch-0.5.0.dist-info/licenses/LICENSE,sha256=zMZxYbR1i_XxgyJP_rPSWKcxY7QtyxUOzbIpowHNjCs,1093
10
- aind_codeocean_dispatch-0.5.0.dist-info/RECORD,,