aind-codeocean-dispatch 0.4.0__py3-none-any.whl → 0.6.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.
@@ -2,6 +2,7 @@
2
2
 
3
3
  from importlib.metadata import PackageNotFoundError, version
4
4
 
5
+ from .automation import capture_finished_run, read_only_retries
5
6
  from .capsule_git import capsule_head_commit, head_commit, run_owner_email
6
7
  from .capture import capture_as, capture_named_by_data_description, derived_name
7
8
  from .runner import (
@@ -13,6 +14,7 @@ from .runner import (
13
14
  Outcome,
14
15
  failed_without_results,
15
16
  job_key,
17
+ key_marker,
16
18
  key_tag,
17
19
  raise_for_failures,
18
20
  run_jobs,
@@ -28,13 +30,16 @@ __all__ = [
28
30
  "Outcome",
29
31
  "capsule_head_commit",
30
32
  "capture_as",
33
+ "capture_finished_run",
31
34
  "capture_named_by_data_description",
32
35
  "derived_name",
33
36
  "failed_without_results",
34
37
  "head_commit",
35
38
  "job_key",
39
+ "key_marker",
36
40
  "key_tag",
37
41
  "raise_for_failures",
42
+ "read_only_retries",
38
43
  "run_jobs",
39
44
  "run_owner_email",
40
45
  "succeeded",
@@ -0,0 +1,159 @@
1
+ """Capture a finished run as an internal data asset, from a Code Ocean post-run automation.
2
+
3
+ Code Ocean runs a pipeline's automation capsule after every run, passing the run as
4
+ ``CO_SOURCE_COMPUTATION_ID`` and ``CO_SOURCE_EXIT_CODE``. A capsule whose ``code/run`` is
5
+ ``python -m aind_codeocean_dispatch.automation`` captures that run whatever its results
6
+ hold: the name comes from a derived ``data_description.json`` when one declares it, and
7
+ otherwise from the first input asset and the capture time. It writes no external bucket
8
+ and no DocDB record, so it needs only a Code Ocean token, and it is no substitute for a
9
+ publishing automation that checks metadata before registering it.
10
+
11
+ Configured by the capsule's environment:
12
+
13
+ - ``CODEOCEAN_TOKEN`` (required) and ``CODEOCEAN_DOMAIN``.
14
+ - ``CAPTURE_TAGS``: comma-separated tags for the asset.
15
+ - ``CAPTURE_FAILED``: truthy to capture failed runs that left results.
16
+ - ``CAPTURE_PERMISSIONS``: a ``Permissions`` object as JSON, applied once the asset is Ready.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import logging
23
+ import os
24
+ import time
25
+ from collections.abc import Sequence
26
+ from typing import TYPE_CHECKING
27
+
28
+ from aind_code_ocean_pipeline_utils import parse_truthy
29
+ from codeocean import CodeOcean
30
+ from codeocean.components import Permissions
31
+ from codeocean.computation import Computation
32
+ from codeocean.data_asset import DataAsset, DataAssetState
33
+ from urllib3.util import Retry
34
+
35
+ from .capture import capture_named_by_data_description
36
+ from .runner import succeeded
37
+
38
+ if TYPE_CHECKING:
39
+ from collections.abc import Mapping
40
+
41
+ __all__ = ["capture_finished_run", "main", "read_only_retries"]
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+ DEFAULT_DOMAIN = "https://codeocean.allenneuraldynamics.org"
46
+
47
+ # Indirected so tests need not wait.
48
+ _sleep = time.sleep
49
+
50
+
51
+ def read_only_retries() -> Retry:
52
+ """Retry 429 and 5xx on GET only; a resent ``create_data_asset`` could duplicate the asset."""
53
+ return Retry(
54
+ total=5,
55
+ backoff_factor=2,
56
+ status_forcelist=[429, 500, 502, 503, 504],
57
+ allowed_methods=frozenset({"GET"}),
58
+ )
59
+
60
+
61
+ def capture_finished_run(
62
+ client: CodeOcean,
63
+ computation_id: str,
64
+ exit_code: int,
65
+ *,
66
+ tags: Sequence[str] = (),
67
+ capture_failed: bool = False,
68
+ permissions: Permissions | None = None,
69
+ poll_interval_s: float = 60.0,
70
+ ) -> DataAsset | None:
71
+ """Capture *computation_id*'s results and wait until the asset is Ready.
72
+
73
+ Parameters
74
+ ----------
75
+ client : CodeOcean
76
+ Authenticated client; see :func:`read_only_retries` for a safe ``retries``.
77
+ computation_id, exit_code
78
+ The finished run, as Code Ocean passes it to the automation.
79
+ tags : Sequence[str], optional
80
+ Tags for the asset.
81
+ capture_failed : bool, optional
82
+ Capture a failed run too, provided it left results.
83
+ permissions : Permissions, optional
84
+ Applied once the asset is Ready; ``None`` leaves Code Ocean's default.
85
+ poll_interval_s : float, optional
86
+ Seconds between checks of the asset's state.
87
+
88
+ Returns
89
+ -------
90
+ DataAsset or None
91
+ The Ready asset, or ``None`` when the run was skipped.
92
+
93
+ Raises
94
+ ------
95
+ RuntimeError
96
+ If the capture ends in the Failed state.
97
+ """
98
+ source = client.computations.get_computation(computation_id)
99
+ if not (exit_code == 0 and succeeded(source)) and not capture_failed:
100
+ logger.info("computation %s did not succeed (exit code %d); not capturing", computation_id, exit_code)
101
+ return None
102
+ if source.has_results is False:
103
+ logger.info("computation %s left no results; nothing to capture", computation_id)
104
+ return None
105
+ params = capture_named_by_data_description(client, _fallback_name(client, source), tags)(source)
106
+ created = client.data_assets.create_data_asset(params)
107
+ logger.info("capturing computation %s as %s (%s)", computation_id, created.id, params.name)
108
+ ready = _wait_until_settled(client, created.id, poll_interval_s)
109
+ if ready.state == DataAssetState.Failed:
110
+ raise RuntimeError(f"capture {created.id} of computation {computation_id} failed")
111
+ if permissions is not None:
112
+ client.data_assets.update_permissions(ready.id, permissions)
113
+ logger.info("captured computation %s as %s", computation_id, ready.id)
114
+ return ready
115
+
116
+
117
+ def _fallback_name(client: CodeOcean, source: Computation) -> str:
118
+ """Name a capture after the run's first input asset, or the run itself if it has none."""
119
+ if source.data_assets:
120
+ try:
121
+ return str(client.data_assets.get_data_asset(source.data_assets[0].id).name)
122
+ except Exception as exc: # noqa: BLE001 - the name is cosmetic; the capture is not
123
+ logger.warning("could not read input asset %s: %s", source.data_assets[0].id, exc)
124
+ return str(source.name)
125
+
126
+
127
+ def _wait_until_settled(client: CodeOcean, asset_id: str, poll_interval_s: float) -> DataAsset:
128
+ while True:
129
+ asset = client.data_assets.get_data_asset(asset_id)
130
+ if asset.state in (DataAssetState.Ready, DataAssetState.Failed):
131
+ return asset
132
+ _sleep(poll_interval_s)
133
+
134
+
135
+ def _client_from_env(env: Mapping[str, str]) -> CodeOcean:
136
+ return CodeOcean(
137
+ domain=env.get("CODEOCEAN_DOMAIN", DEFAULT_DOMAIN),
138
+ token=env["CODEOCEAN_TOKEN"],
139
+ retries=read_only_retries(),
140
+ )
141
+
142
+
143
+ def main(env: Mapping[str, str] | None = None) -> None:
144
+ """Capture the run Code Ocean names in the environment; see the module docstring."""
145
+ env = os.environ if env is None else env
146
+ logging.basicConfig(level=env.get("LOG_LEVEL", "INFO"))
147
+ raw_permissions = env.get("CAPTURE_PERMISSIONS")
148
+ capture_finished_run(
149
+ _client_from_env(env),
150
+ env["CO_SOURCE_COMPUTATION_ID"],
151
+ int(env["CO_SOURCE_EXIT_CODE"]),
152
+ tags=[tag.strip() for tag in env.get("CAPTURE_TAGS", "").split(",") if tag.strip()],
153
+ capture_failed=parse_truthy(env.get("CAPTURE_FAILED", "")),
154
+ permissions=Permissions.from_dict(json.loads(raw_permissions)) if raw_permissions else None,
155
+ )
156
+
157
+
158
+ if __name__ == "__main__":
159
+ main()
@@ -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,7 @@ class Outcome:
134
139
  computation_ids: tuple[str, ...] = ()
135
140
  error: str | None = None
136
141
  failure: Failure | None = None
142
+ resumed: bool = False
137
143
 
138
144
  @property
139
145
  def ok(self) -> bool:
@@ -203,6 +209,11 @@ def key_tag(key: str) -> str:
203
209
  return f"{_KEY_TAG_PREFIX}{key}"
204
210
 
205
211
 
212
+ def key_marker(key: str) -> str:
213
+ """Return the text a computation's name carries to be found again by resume *key*."""
214
+ return f"[{key_tag(key)}]"
215
+
216
+
206
217
  def job_key(run_params: RunParams, *, salt: str = "") -> str:
207
218
  """Return a resume key: 16 hex characters fingerprinting *run_params*.
208
219
 
@@ -247,6 +258,8 @@ def run_jobs(
247
258
  poll_interval_s: float = 60.0,
248
259
  timeout_s: float | None = None,
249
260
  cancel_on_failure: bool | Callable[[Outcome], bool] = False,
261
+ resume_owner: str | None = None,
262
+ on_outcome: Callable[[Outcome], None] | None = None,
250
263
  ) -> list[Outcome]:
251
264
  """Launch *jobs*, wait for each, capture its results, and report every outcome.
252
265
 
@@ -288,6 +301,17 @@ def run_jobs(
288
301
  Whether a failed job cancels the rest, or a predicate on its outcome. On
289
302
  cancel, pending jobs are not launched and running computations are stopped
290
303
  and deleted, all ending ``"cancelled"``; captures already under way finish.
304
+ resume_owner : str, optional
305
+ The caller's Code Ocean user id or email. When set, a keyed job whose
306
+ computation this owner launched earlier, and which is still running or
307
+ succeeded uncaptured, is followed from there instead of launched again; a
308
+ capture of it still in progress is waited on. Code Ocean lists every
309
+ user's computations and has no call naming the caller, hence the
310
+ argument. Needs codeocean 0.15 or later, whose computations carry an owner.
311
+ on_outcome : callable, optional
312
+ Called with each job's outcome as soon as it is reached, whatever the
313
+ status, so results can be used before the batch ends. An exception it
314
+ raises is logged and does not affect the batch.
291
315
 
292
316
  Returns
293
317
  -------
@@ -308,6 +332,7 @@ def run_jobs(
308
332
  start_retries=start_retries,
309
333
  start_retry_backoff_s=start_retry_backoff_s,
310
334
  capture_retries=capture_retries,
335
+ resume_owner=resume_owner,
311
336
  )
312
337
  return _Dispatcher(
313
338
  _without_transport_retries(client),
@@ -322,6 +347,8 @@ def run_jobs(
322
347
  poll_interval_s=poll_interval_s,
323
348
  timeout_s=timeout_s,
324
349
  cancel_on_failure=cancel_on_failure,
350
+ resume_owner=resume_owner,
351
+ on_outcome=on_outcome,
325
352
  ).run()
326
353
 
327
354
 
@@ -344,6 +371,7 @@ def _validate(
344
371
  start_retries: int,
345
372
  start_retry_backoff_s: float,
346
373
  capture_retries: int,
374
+ resume_owner: str | None,
347
375
  ) -> None:
348
376
  labels = [job.label for job in jobs]
349
377
  if len(set(labels)) != len(labels):
@@ -355,6 +383,8 @@ def _validate(
355
383
  raise ValueError(f"max_in_flight must be at least 1, got {max_in_flight}")
356
384
  if start_retries < 0 or capture_retries < 0 or start_retry_backoff_s < 0:
357
385
  raise ValueError("retry counts and back-off cannot be negative")
386
+ if resume_owner is not None and "owner" not in {f.name for f in dataclasses.fields(Computation)}:
387
+ raise ValueError("resume_owner needs codeocean 0.15 or later, whose computations carry an owner")
358
388
 
359
389
 
360
390
  def _prune(value: Any) -> Any:
@@ -422,6 +452,9 @@ class _Slot:
422
452
  start_retries_used: int = 0
423
453
  capture_retries_used: int = 0
424
454
  reuse_checked: bool = False
455
+ # Whether the current computation's name carries the key marker yet.
456
+ marked: bool = True
457
+ resumed: bool = False
425
458
  outcome: Outcome | None = None
426
459
 
427
460
 
@@ -441,6 +474,8 @@ class _Dispatcher:
441
474
  poll_interval_s: float,
442
475
  timeout_s: float | None,
443
476
  cancel_on_failure: bool | Callable[[Outcome], bool],
477
+ resume_owner: str | None,
478
+ on_outcome: Callable[[Outcome], None] | None,
444
479
  ) -> None:
445
480
  self.client = client
446
481
  self.slots = [_Slot(job) for job in jobs]
@@ -454,6 +489,10 @@ class _Dispatcher:
454
489
  self.poll_interval_s = poll_interval_s
455
490
  self.timeout_s = timeout_s
456
491
  self.cancel_on_failure = cancel_on_failure
492
+ self.resume_owner = resume_owner
493
+ self.on_outcome = on_outcome
494
+ # Per capsule or pipeline id: its computations carrying a key marker, by key.
495
+ self.resumable: dict[str, dict[str, list[Computation]]] = {}
457
496
  self.cancelled_by: str | None = None
458
497
  self.next_launch_at = 0.0
459
498
 
@@ -485,8 +524,8 @@ class _Dispatcher:
485
524
  for slot in self.slots:
486
525
  if slot.phase is not _Phase.PENDING or slot.next_at > _now():
487
526
  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
527
+ if self._searches_first() and slot.job.key is not None and not slot.reuse_checked:
528
+ continue # still waiting on its reuse or resume search
490
529
  if self.max_in_flight is not None and self._in_flight() >= self.max_in_flight:
491
530
  return
492
531
  if _now() < self.next_launch_at:
@@ -512,11 +551,18 @@ class _Dispatcher:
512
551
  computation_ids=tuple(slot.computation_ids),
513
552
  error=error,
514
553
  failure=failure,
554
+ resumed=slot.resumed,
515
555
  )
516
556
  if error is None:
517
557
  logger.info("%s: %s", slot.job.label, status)
518
558
  else:
519
559
  logger.error("%s: %s: %s", slot.job.label, status, error)
560
+ if self.on_outcome is not None:
561
+ try:
562
+ self.on_outcome(slot.outcome)
563
+ # Broad on purpose: the caller's hook must not orphan the other jobs' computations.
564
+ except Exception:
565
+ logger.exception("%s: on_outcome raised", slot.job.label)
520
566
  if status == "failed" and self.cancelled_by is None and self._should_cancel(slot.outcome):
521
567
  self._cancel_rest(slot.job.label)
522
568
 
@@ -571,9 +617,12 @@ class _Dispatcher:
571
617
 
572
618
  # -- phases -------------------------------------------------------------
573
619
 
620
+ def _searches_first(self) -> bool:
621
+ return self.reuse or self.resume_owner is not None
622
+
574
623
  def _check_reuse(self) -> None:
575
- """Resolve pending keyed jobs to existing captures, without using launch capacity."""
576
- if not self.reuse:
624
+ """Resolve pending keyed jobs to existing captures or computations, without using launch capacity."""
625
+ if not self._searches_first():
577
626
  return
578
627
  for slot in self.slots:
579
628
  if slot.phase is not _Phase.PENDING or slot.reuse_checked or slot.job.key is None:
@@ -590,20 +639,92 @@ class _Dispatcher:
590
639
  slot.api_errors += 1
591
640
  slot.next_at = _now() + delay
592
641
  continue
593
- # Reuse is an optimisation: launching is still correct.
642
+ # Reuse and resume are optimisations: launching is still correct.
594
643
  logger.warning("%s: reuse search failed (%s); launching", slot.job.label, exc)
595
644
  slot.reuse_checked = True
596
645
  continue
597
646
  slot.api_errors = 0
598
- slot.reuse_checked = True
599
647
  # 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
648
+ tagged: list[DataAsset] = [asset for asset in results.results if tag in (asset.tags or [])]
649
+ ready = [asset for asset in tagged if asset.state == DataAssetState.Ready]
650
+ capturing = [asset for asset in tagged if asset.state not in (DataAssetState.Ready, DataAssetState.Failed)]
651
+ if self.reuse and ready:
652
+ slot.reuse_checked = True
653
+ slot.asset_id = max(ready, key=lambda asset: asset.created).id
605
654
  logger.info("%s: reusing captured asset %s", slot.job.label, slot.asset_id)
606
655
  self._finish(slot, "reused")
656
+ elif self.resume_owner is not None and capturing:
657
+ slot.reuse_checked = True
658
+ slot.asset_id = max(capturing, key=lambda asset: asset.created).id
659
+ slot.resumed = True
660
+ slot.phase = _Phase.CAPTURING
661
+ slot.next_at = _now()
662
+ logger.info("%s: resuming capture %s", slot.job.label, slot.asset_id)
663
+ elif self.resume_owner is not None:
664
+ # A succeeded computation already captured is not resumed: with reuse
665
+ # off, the caller asked for a new run, not a second capture.
666
+ self._resume_computation(slot, finished_too=not ready)
667
+ else:
668
+ slot.reuse_checked = True
669
+
670
+ def _resume_computation(self, slot: _Slot, *, finished_too: bool) -> None:
671
+ """Follow the owner's running, or else succeeded, computation of *slot*'s job, if there is one."""
672
+ assert slot.job.key is not None
673
+ source = slot.job.run_params.capsule_id or slot.job.run_params.pipeline_id
674
+ if source is None:
675
+ slot.reuse_checked = True
676
+ return
677
+ if source not in self.resumable:
678
+ listing = self._list_resumable(slot, source)
679
+ if listing is None:
680
+ return # retrying, or done
681
+ self.resumable[source] = listing
682
+ slot.reuse_checked = True
683
+ candidates = self.resumable[source].get(slot.job.key, [])
684
+ live = [c for c in candidates if c.state not in (ComputationState.Completed, ComputationState.Failed)]
685
+ done = [c for c in candidates if succeeded(c)] if finished_too else []
686
+ if not (live or done):
687
+ return
688
+ # A live computation is newer than any finished one worth resuming.
689
+ computation = max(live or done, key=lambda c: c.created)
690
+ slot.computation_ids.append(computation.id)
691
+ slot.resumed = True
692
+ slot.phase = _Phase.RUNNING
693
+ # Timeouts count from here: how long it ran before is unknown to this batch.
694
+ slot.launched_at = _now()
695
+ slot.next_at = _now()
696
+ logger.info("%s: resuming computation %s (%s)", slot.job.label, computation.id, computation.state)
697
+
698
+ def _list_resumable(self, slot: _Slot, source: str) -> dict[str, list[Computation]] | None:
699
+ """Index the owner's computations of *source* by the key their name carries."""
700
+ lister = (
701
+ self.client.capsules.list_computations
702
+ if slot.job.run_params.capsule_id
703
+ else self.client.pipelines.list_computations
704
+ )
705
+ try:
706
+ computations = lister(source)
707
+ except (CodeOceanError, requests.RequestException) as exc:
708
+ delay = _retry_delay(exc, slot.api_errors, idempotent=True)
709
+ if delay is not None:
710
+ slot.api_errors += 1
711
+ slot.next_at = _now() + delay
712
+ return None
713
+ logger.warning("%s: listing computations of %s failed (%s); launching", slot.job.label, source, exc)
714
+ return {}
715
+ slot.api_errors = 0
716
+ keys = {job.key for job in (s.job for s in self.slots) if job.key is not None}
717
+ index: dict[str, list[Computation]] = {}
718
+ for computation in computations:
719
+ if self.resume_owner not in (
720
+ getattr(computation, "owner", None),
721
+ getattr(computation, "owner_email", None),
722
+ ):
723
+ continue
724
+ for key in keys:
725
+ if key_marker(key) in (computation.name or ""):
726
+ index.setdefault(key, []).append(computation)
727
+ return index
607
728
 
608
729
  def _launch(self, slot: _Slot) -> None:
609
730
  computation = self._call(
@@ -620,8 +741,29 @@ class _Dispatcher:
620
741
  slot.next_at = slot.launched_at + self.poll_interval_s
621
742
  self.next_launch_at = slot.launched_at + self.launch_interval_s
622
743
  logger.info("%s: launched %s (attempt %d)", slot.job.label, computation.id, len(slot.computation_ids))
744
+ slot.marked = slot.job.key is None
745
+ if not slot.marked:
746
+ self._mark(slot)
747
+
748
+ def _mark(self, slot: _Slot) -> None:
749
+ """Name the computation after its job and key, so a later batch can resume it.
750
+
751
+ Best effort: until it succeeds, each status check tries again, and a
752
+ computation left unnamed is relaunched rather than resumed.
753
+ """
754
+ assert slot.job.key is not None
755
+ computation_id = slot.computation_ids[-1]
756
+ name = f"{slot.job.label} {key_marker(slot.job.key)}"
757
+ try:
758
+ self.client.computations.rename_computation(computation_id, name)
759
+ except (CodeOceanError, requests.RequestException) as exc:
760
+ logger.warning("%s: naming computation %s failed (%s); trying again", slot.job.label, computation_id, exc)
761
+ return
762
+ slot.marked = True
623
763
 
624
764
  def _poll_computation(self, slot: _Slot) -> None:
765
+ if not slot.marked:
766
+ self._mark(slot)
625
767
  computation_id = slot.computation_ids[-1]
626
768
  computation = self._call(
627
769
  slot, "status check", lambda: self.client.computations.get_computation(computation_id), idempotent=True
@@ -0,0 +1,142 @@
1
+ Metadata-Version: 2.5
2
+ Name: aind-codeocean-dispatch
3
+ Version: 0.6.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
+ ## Usage
45
+
46
+ ### Running a batch of runs
47
+
48
+ `run_jobs` launches a batch of capsule or pipeline runs, waits for them from one polling
49
+ loop, and captures each successful run as a data asset:
50
+
51
+ ```python
52
+ from codeocean import CodeOcean
53
+ from codeocean.computation import DataAssetsRunParam, NamedRunParam, RunParams
54
+
55
+ from aind_codeocean_dispatch import Job, capture_as, job_key, raise_for_failures, run_jobs
56
+
57
+ client = CodeOcean(domain="https://codeocean.allenneuraldynamics.org", token=token)
58
+
59
+ jobs = []
60
+ for stream in streams:
61
+ params = RunParams(
62
+ capsule_id=WORKER_CAPSULE_ID,
63
+ data_assets=[DataAssetsRunParam(id=raw_asset_id, mount="raw")],
64
+ named_parameters=[NamedRunParam(param_name="stream", value=stream)],
65
+ )
66
+ jobs.append(
67
+ Job(
68
+ label=stream,
69
+ run_params=params,
70
+ capture=capture_as(f"{session}_{stream}_sorted", tags=["sorted"]),
71
+ key=job_key(params),
72
+ )
73
+ )
74
+
75
+ outcomes = run_jobs(client, jobs, launch_interval_s=1, start_retries=3, reuse=True)
76
+ raise_for_failures(outcomes)
77
+ asset_ids = {o.job.label: o.asset_id for o in outcomes}
78
+ ```
79
+
80
+ A failed job does not raise; each `Outcome` carries its `status`, `asset_id`, every
81
+ `computation_ids` attempt, and on failure an `error` and a `failure` kind.
82
+ `raise_for_failures` turns failures into one `DispatchFailed`.
83
+
84
+ Behaviour worth knowing:
85
+
86
+ - **Failed starts.** Code Ocean sometimes fails to start a run (`end_status=Failed`, no
87
+ results). Up to `start_retries` relaunches follow, after `start_retry_backoff_s` (60 s)
88
+ doubling each time, and every pending launch waits too, since the cause is usually
89
+ machine capacity.
90
+ - **Rate limits and errors.** 429s are retried honouring `Retry-After`. Other 5xx and
91
+ connection errors are retried on reads only: a launch or capture POST may already have
92
+ taken effect, so resending it could duplicate the computation or asset.
93
+ - **Pacing.** `max_in_flight` caps concurrent runs and `launch_interval_s` spaces
94
+ launches; both are off by default.
95
+ - **Reuse.** A job's `key` is added to its asset as a tag. With `reuse=True`, a Ready
96
+ asset you created with that tag is returned instead of launching. `job_key` fingerprints
97
+ the launch request; pass `salt=` for what the request cannot show, such as the commit
98
+ of an unreleased capsule (`capsule_head_commit(client, capsule_id)` reads it inside a
99
+ run).
100
+ - **Acting on each job as it finishes.** `on_outcome=` is called with each job's
101
+ `Outcome` as soon as it is reached, whatever its status, so a caller can register or
102
+ report results without waiting for the whole batch. An exception it raises is logged
103
+ and does not affect the other jobs.
104
+ - **Resuming a batch.** A keyed job's computation is renamed to its label plus
105
+ `key_marker(key)`. With `resume_owner=` set to your Code Ocean user id or email, a
106
+ later batch follows your computation of the same job instead of launching it again:
107
+ one still running is waited on, one that succeeded but was never captured is
108
+ captured, and a capture still in progress is waited on. A succeeded computation that
109
+ already has a Ready capture is resumed only through `reuse`. Code Ocean lists every
110
+ user's computations of a capsule and has no call naming the caller, hence the
111
+ argument; it needs codeocean 0.15 or later.
112
+ - **Cancelling a doomed batch.** `cancel_on_failure=True`, or a predicate on the failed
113
+ `Outcome` such as `lambda o: not o.transient`, stops launching and stops and deletes
114
+ running computations; captures already under way finish.
115
+ - **Capture names.** `capture_as` uses a fixed name. `capture_named_by_data_description`
116
+ uses the name a derived `data_description.json` in the results declares, and otherwise
117
+ a fallback name plus the capture time.
118
+
119
+ ### Capturing runs from a post-run automation
120
+
121
+ A Code Ocean pipeline can name an automation capsule that runs after every run. A capsule
122
+ whose `code/run` is
123
+
124
+ ```bash
125
+ #!/usr/bin/env bash
126
+ set -e
127
+ python -m aind_codeocean_dispatch.automation
128
+ ```
129
+
130
+ captures each successful run as an internal data asset, named by the results'
131
+ `data_description.json` when it declares a derived name and otherwise after the first
132
+ input asset. It needs only `CODEOCEAN_TOKEN`; `CAPTURE_TAGS`, `CAPTURE_FAILED` and
133
+ `CAPTURE_PERMISSIONS` adjust it. It registers nothing in DocDB and writes no external
134
+ bucket, so pipelines that publish use `asset-creation-capsule` instead.
135
+
136
+ ## Contributing
137
+
138
+ Setup, checks, tests and conventions are in [CONTRIBUTING.md](CONTRIBUTING.md).
139
+
140
+ ## License
141
+
142
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,10 @@
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/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
6
+ aind_codeocean_dispatch/runner.py,sha256=09WI4BYr9KBV7qH5VcNMCmFDUgKbuV9TKadLWGmxQNU,37096
7
+ aind_codeocean_dispatch-0.6.0.dist-info/METADATA,sha256=Bj1bUoPCTkFGqxv50F8qJAu81FTQNkBHj6UwDdDInUA,6722
8
+ aind_codeocean_dispatch-0.6.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
9
+ aind_codeocean_dispatch-0.6.0.dist-info/licenses/LICENSE,sha256=zMZxYbR1i_XxgyJP_rPSWKcxY7QtyxUOzbIpowHNjCs,1093
10
+ aind_codeocean_dispatch-0.6.0.dist-info/RECORD,,
@@ -1,73 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: aind-codeocean-dispatch
3
- Version: 0.4.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
- ## Development
52
-
53
- Please test your changes using the full linting and testing suite:
54
-
55
- ```bash
56
- ./scripts/run_linters_and_checks.sh -c
57
- ```
58
-
59
- Or run individual commands:
60
- ```bash
61
- uv run --frozen ruff format # Code formatting
62
- uv run --frozen ruff check # Linting
63
- uv run --frozen mypy # Type checking
64
- uv run --frozen interrogate -v src # Documentation coverage
65
- uv run --frozen codespell --check-filenames # Spell checking
66
- uv run --frozen pytest --cov aind_codeocean_dispatch # Tests with coverage
67
- ```
68
-
69
-
70
-
71
- ## License
72
-
73
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -1,9 +0,0 @@
1
- aind_codeocean_dispatch/__init__.py,sha256=iWzsXeODLf8-XLxMDQl2FNT351Usrl-Nd11-zLdiJSc,1042
2
- aind_codeocean_dispatch/capsule_git.py,sha256=BnUiGY1blXAFqnNAztBbYX0h5U5Mlsm5M2sFsOa4ICk,2762
3
- aind_codeocean_dispatch/capture.py,sha256=aj3dgLNtGRmKhUbVZeIcPjfbPP42YYiz6gwMGwZSlAg,3506
4
- aind_codeocean_dispatch/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
5
- aind_codeocean_dispatch/runner.py,sha256=heg62GPc8gx7loOicFgY1K46aP6jC_5jky4_8K_IzHI,29767
6
- aind_codeocean_dispatch-0.4.0.dist-info/METADATA,sha256=dki-UD71tzNI4GFQ6YQpQfJtbsuH5d9tTXj2OCAxrTQ,2797
7
- aind_codeocean_dispatch-0.4.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
8
- aind_codeocean_dispatch-0.4.0.dist-info/licenses/LICENSE,sha256=zMZxYbR1i_XxgyJP_rPSWKcxY7QtyxUOzbIpowHNjCs,1093
9
- aind_codeocean_dispatch-0.4.0.dist-info/RECORD,,