aind-codeocean-dispatch 0.5.0__tar.gz → 0.6.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 (34) hide show
  1. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/.copier-answers.yml +1 -1
  2. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/CHANGELOG.md +6 -0
  3. aind_codeocean_dispatch-0.6.0/CLAUDE.md +10 -0
  4. aind_codeocean_dispatch-0.6.0/CONTRIBUTING.md +61 -0
  5. aind_codeocean_dispatch-0.6.0/PKG-INFO +142 -0
  6. aind_codeocean_dispatch-0.6.0/README.md +125 -0
  7. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/pyproject.toml +1 -1
  8. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/src/aind_codeocean_dispatch/__init__.py +2 -0
  9. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/src/aind_codeocean_dispatch/runner.py +158 -16
  10. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/tests/fakes.py +52 -4
  11. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/tests/test_runner.py +195 -0
  12. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/uv.lock +1 -1
  13. aind_codeocean_dispatch-0.5.0/CLAUDE.md +0 -48
  14. aind_codeocean_dispatch-0.5.0/PKG-INFO +0 -90
  15. aind_codeocean_dispatch-0.5.0/README.md +0 -73
  16. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  17. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  18. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/.github/ISSUE_TEMPLATE/user-story.md +0 -0
  19. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/.github/dependabot.yml +0 -0
  20. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/.github/workflows/bump-call.yml +0 -0
  21. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/.github/workflows/ci-call.yml +0 -0
  22. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/.github/workflows/publish-call.yml +0 -0
  23. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/.gitignore +0 -0
  24. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/.python-version +0 -0
  25. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/LICENSE +0 -0
  26. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/scripts/run_linters_and_checks.sh +0 -0
  27. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/src/aind_codeocean_dispatch/automation.py +0 -0
  28. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/src/aind_codeocean_dispatch/capsule_git.py +0 -0
  29. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/src/aind_codeocean_dispatch/capture.py +0 -0
  30. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/src/aind_codeocean_dispatch/py.typed +0 -0
  31. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/tests/__init__.py +0 -0
  32. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/tests/test_automation.py +0 -0
  33. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/tests/test_capsule_git.py +0 -0
  34. {aind_codeocean_dispatch-0.5.0 → aind_codeocean_dispatch-0.6.0}/tests/test_capture.py +0 -0
@@ -1,5 +1,5 @@
1
1
  # Changes here will be overwritten by Copier; NEVER EDIT MANUALLY
2
- _commit: 0.1.18
2
+ _commit: 0.1.19
3
3
  _src_path: /home/galen.lynch/Documents/Code/aind-python-copier-template
4
4
  author_email: galen@galenlynch.com
5
5
  author_fullname: Galen Lynch
@@ -5,6 +5,12 @@ 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.6.0 (2026-10-21)
9
+
10
+ ### Feat
11
+
12
+ - report each job's outcome as it finishes and resume running computations by key
13
+
8
14
  ## v0.5.0 (2026-10-15)
9
15
 
10
16
  ### Feat
@@ -0,0 +1,10 @@
1
+ # CLAUDE.md
2
+
3
+ Instructions for coding agents in this repository. [CONTRIBUTING.md](CONTRIBUTING.md) holds setup,
4
+ checks, tests and conventions, and applies to agents as to people: read it before running or
5
+ changing anything. [README.md](README.md) documents use.
6
+
7
+ - Run every command through `uv`; never bare `pip` or `python`.
8
+ - Before calling a change done, run `./scripts/run_linters_and_checks.sh -c`.
9
+ - Keep this file to what only an agent needs; development practice belongs in CONTRIBUTING.md and
10
+ usage in README.md.
@@ -0,0 +1,61 @@
1
+ # Contributing to AIND Code Ocean dispatch
2
+
3
+ This document is for people changing aind-codeocean-dispatch: setting up, running the checks and tests,
4
+ and the conventions a change follows. Using the package is documented in [README.md](README.md).
5
+
6
+ ## Setup
7
+
8
+ ```bash
9
+ uv sync
10
+ ```
11
+
12
+ `uv sync` creates `.venv` holding the package and the dev group. `uv` manages the environment and
13
+ the lockfile, `uv.lock`: run commands with `uv run`, add a dependency with `uv add <package>` and a
14
+ development tool with `uv add --group dev <package>`, and never install with bare `pip`. The
15
+ jupyter group adds a kernel (`uv sync --group jupyter`).
16
+
17
+ ## Checks
18
+
19
+ ```bash
20
+ ./scripts/run_linters_and_checks.sh -c
21
+ ```
22
+
23
+ Without `-c` the script only formats. With it, the script also runs ruff's linter, mypy, interrogate,
24
+ codespell and pytest with coverage, passing any arguments after `--` to pytest. It runs in the
25
+ existing `.venv` and does not sync it.
26
+
27
+ The same checks, one at a time:
28
+
29
+ ```bash
30
+ uv run --frozen ruff format
31
+ uv run --frozen ruff check
32
+ uv run --frozen mypy
33
+ uv run --frozen interrogate -v src
34
+ uv run --frozen codespell --check-filenames
35
+ uv run --frozen pytest --cov aind_codeocean_dispatch
36
+ ```
37
+
38
+ ## Tests
39
+
40
+ ```bash
41
+ uv run pytest # the whole suite
42
+ uv run pytest tests/test_example.py # one file
43
+ uv run pytest -k "version" # tests whose names match
44
+ ```
45
+
46
+ ## Conventions
47
+
48
+ - Source lives in `src/aind_codeocean_dispatch/` and tests in `tests/`; hatchling builds the
49
+ wheel.
50
+ - ruff sets a line length of 120 and numpy-style docstrings, and exempts tests from the
51
+ docstring and annotation rules. interrogate fails below 30%
52
+ docstring coverage of `src`.
53
+ - mypy checks `src/aind_codeocean_dispatch` in strict mode.
54
+ - Comments and docstrings say what the code does not: why it is written this way, and what breaks
55
+ otherwise. They carry no history; the reason for a change belongs in its commit message.
56
+ - `scratch/` is gitignored and excluded from the linters, for work that is not kept.
57
+ - Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/) (`feat:`,
58
+ `fix:`, `docs:`, `chore:`): an imperative title, and a body giving what changed and why. After CI
59
+ passes on `main`, the bump workflow uses commitizen to bump the version from them and update
60
+ `CHANGELOG.md`.
61
+ - A change a user would notice updates README.md in the same commit.
@@ -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,125 @@
1
+ # AIND Code Ocean dispatch
2
+
3
+ ![CI](https://github.com/AllenNeuralDynamics/aind-codeocean-dispatch/actions/workflows/ci-call.yml/badge.svg)
4
+ [![PyPI - Version](https://img.shields.io/pypi/v/aind-codeocean-dispatch)](https://pypi.org/project/aind-codeocean-dispatch/)
5
+ [![semantic-release: angular](https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
6
+ [![License](https://img.shields.io/badge/license-MIT-brightgreen)](LICENSE)
7
+ [![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)
8
+ [![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)
9
+ [![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)
10
+
11
+ Launch, monitor, and capture batches of Code Ocean capsule runs
12
+
13
+ ## Installation
14
+
15
+ If you choose to clone the repository, you can install the package by running the following command from the root directory of the repository:
16
+
17
+ ```bash
18
+ pip install .
19
+ ```
20
+
21
+ Otherwise, you can use pip:
22
+
23
+ ```bash
24
+ pip install aind-codeocean-dispatch
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ### Running a batch of runs
30
+
31
+ `run_jobs` launches a batch of capsule or pipeline runs, waits for them from one polling
32
+ loop, and captures each successful run as a data asset:
33
+
34
+ ```python
35
+ from codeocean import CodeOcean
36
+ from codeocean.computation import DataAssetsRunParam, NamedRunParam, RunParams
37
+
38
+ from aind_codeocean_dispatch import Job, capture_as, job_key, raise_for_failures, run_jobs
39
+
40
+ client = CodeOcean(domain="https://codeocean.allenneuraldynamics.org", token=token)
41
+
42
+ jobs = []
43
+ for stream in streams:
44
+ params = RunParams(
45
+ capsule_id=WORKER_CAPSULE_ID,
46
+ data_assets=[DataAssetsRunParam(id=raw_asset_id, mount="raw")],
47
+ named_parameters=[NamedRunParam(param_name="stream", value=stream)],
48
+ )
49
+ jobs.append(
50
+ Job(
51
+ label=stream,
52
+ run_params=params,
53
+ capture=capture_as(f"{session}_{stream}_sorted", tags=["sorted"]),
54
+ key=job_key(params),
55
+ )
56
+ )
57
+
58
+ outcomes = run_jobs(client, jobs, launch_interval_s=1, start_retries=3, reuse=True)
59
+ raise_for_failures(outcomes)
60
+ asset_ids = {o.job.label: o.asset_id for o in outcomes}
61
+ ```
62
+
63
+ A failed job does not raise; each `Outcome` carries its `status`, `asset_id`, every
64
+ `computation_ids` attempt, and on failure an `error` and a `failure` kind.
65
+ `raise_for_failures` turns failures into one `DispatchFailed`.
66
+
67
+ Behaviour worth knowing:
68
+
69
+ - **Failed starts.** Code Ocean sometimes fails to start a run (`end_status=Failed`, no
70
+ results). Up to `start_retries` relaunches follow, after `start_retry_backoff_s` (60 s)
71
+ doubling each time, and every pending launch waits too, since the cause is usually
72
+ machine capacity.
73
+ - **Rate limits and errors.** 429s are retried honouring `Retry-After`. Other 5xx and
74
+ connection errors are retried on reads only: a launch or capture POST may already have
75
+ taken effect, so resending it could duplicate the computation or asset.
76
+ - **Pacing.** `max_in_flight` caps concurrent runs and `launch_interval_s` spaces
77
+ launches; both are off by default.
78
+ - **Reuse.** A job's `key` is added to its asset as a tag. With `reuse=True`, a Ready
79
+ asset you created with that tag is returned instead of launching. `job_key` fingerprints
80
+ the launch request; pass `salt=` for what the request cannot show, such as the commit
81
+ of an unreleased capsule (`capsule_head_commit(client, capsule_id)` reads it inside a
82
+ run).
83
+ - **Acting on each job as it finishes.** `on_outcome=` is called with each job's
84
+ `Outcome` as soon as it is reached, whatever its status, so a caller can register or
85
+ report results without waiting for the whole batch. An exception it raises is logged
86
+ and does not affect the other jobs.
87
+ - **Resuming a batch.** A keyed job's computation is renamed to its label plus
88
+ `key_marker(key)`. With `resume_owner=` set to your Code Ocean user id or email, a
89
+ later batch follows your computation of the same job instead of launching it again:
90
+ one still running is waited on, one that succeeded but was never captured is
91
+ captured, and a capture still in progress is waited on. A succeeded computation that
92
+ already has a Ready capture is resumed only through `reuse`. Code Ocean lists every
93
+ user's computations of a capsule and has no call naming the caller, hence the
94
+ argument; it needs codeocean 0.15 or later.
95
+ - **Cancelling a doomed batch.** `cancel_on_failure=True`, or a predicate on the failed
96
+ `Outcome` such as `lambda o: not o.transient`, stops launching and stops and deletes
97
+ running computations; captures already under way finish.
98
+ - **Capture names.** `capture_as` uses a fixed name. `capture_named_by_data_description`
99
+ uses the name a derived `data_description.json` in the results declares, and otherwise
100
+ a fallback name plus the capture time.
101
+
102
+ ### Capturing runs from a post-run automation
103
+
104
+ A Code Ocean pipeline can name an automation capsule that runs after every run. A capsule
105
+ whose `code/run` is
106
+
107
+ ```bash
108
+ #!/usr/bin/env bash
109
+ set -e
110
+ python -m aind_codeocean_dispatch.automation
111
+ ```
112
+
113
+ captures each successful run as an internal data asset, named by the results'
114
+ `data_description.json` when it declares a derived name and otherwise after the first
115
+ input asset. It needs only `CODEOCEAN_TOKEN`; `CAPTURE_TAGS`, `CAPTURE_FAILED` and
116
+ `CAPTURE_PERMISSIONS` adjust it. It registers nothing in DocDB and writes no external
117
+ bucket, so pipelines that publish use `asset-creation-capsule` instead.
118
+
119
+ ## Contributing
120
+
121
+ Setup, checks, tests and conventions are in [CONTRIBUTING.md](CONTRIBUTING.md).
122
+
123
+ ## License
124
+
125
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -13,7 +13,7 @@ authors = [
13
13
  ]
14
14
  classifiers = ["Programming Language :: Python :: 3"]
15
15
  readme = "README.md"
16
- version = "0.5.0"
16
+ version = "0.6.0"
17
17
 
18
18
  dependencies = [
19
19
  "aind-code-ocean-pipeline-utils>=0.7.1",
@@ -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",
@@ -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
@@ -3,7 +3,8 @@
3
3
  Each launch of a capsule consumes the next *attempt* scripted for its ``capsule_id``:
4
4
  a list of computation snapshots (or exceptions) returned by successive status checks,
5
5
  the last repeating. Captures and asset status checks are scripted the same way, in
6
- creation order.
6
+ creation order. Computations a batch did not launch, for it to resume, are added with
7
+ :meth:`FakeComputations.existing`.
7
8
  """
8
9
 
9
10
  from __future__ import annotations
@@ -106,9 +107,36 @@ class FakeComputations:
106
107
  max_running: int = 0
107
108
  deleted: list[str] = field(default_factory=list)
108
109
  delete_errors: list[Exception] = field(default_factory=list)
110
+ names: dict[str, str] = field(default_factory=dict)
111
+ rename_errors: list[Exception] = field(default_factory=list)
112
+ list_errors: list[Exception] = field(default_factory=list)
113
+ listings: list[str] = field(default_factory=list)
109
114
  _ids: itertools.count[int] = field(default_factory=itertools.count)
110
115
  _scripts: dict[str, list[Any]] = field(default_factory=dict)
111
116
  _running: set[str] = field(default_factory=set)
117
+ _listed: dict[str, list[tuple[str, str, int]]] = field(default_factory=dict) # source -> (id, owner, created)
118
+
119
+ def existing(
120
+ self, source: str, computation_id: str, script: list[Any], *, name: str, owner: str = "me", created: int = 0
121
+ ) -> None:
122
+ """Add a computation launched before the batch, listed under *source*."""
123
+ self._scripts[computation_id] = list(script)
124
+ self.names[computation_id] = name
125
+ self._listed.setdefault(source, []).append((computation_id, owner, created))
126
+
127
+ def list_computations(self, source: str) -> list[Computation]:
128
+ self.listings.append(source)
129
+ if self.list_errors:
130
+ raise self.list_errors.pop(0)
131
+ return [
132
+ self._computation(computation_id, self._scripts[computation_id][0], owner=owner, created=created)
133
+ for computation_id, owner, created in self._listed.get(source, [])
134
+ ]
135
+
136
+ def rename_computation(self, computation_id: str, name: str) -> None:
137
+ if self.rename_errors:
138
+ raise self.rename_errors.pop(0)
139
+ self.names[computation_id] = name
112
140
 
113
141
  def run_capsule(self, run_params: RunParams) -> Computation:
114
142
  errors = self.launch_errors.get(run_params.capsule_id, [])
@@ -136,9 +164,11 @@ class FakeComputations:
136
164
  self._running.discard(computation_id)
137
165
  return self._computation(computation_id, step)
138
166
 
139
- @staticmethod
140
- def _computation(computation_id: str, step: dict[str, Any]) -> Computation:
141
- return build(Computation, id=computation_id, created=0, name=computation_id, owner="owner", run_time=0, **step)
167
+ def _computation(
168
+ self, computation_id: str, step: dict[str, Any], *, owner: str = "me", created: int = 0
169
+ ) -> Computation:
170
+ name = self.names.get(computation_id, computation_id)
171
+ return build(Computation, id=computation_id, created=created, name=name, owner=owner, run_time=0, **step)
142
172
 
143
173
 
144
174
  @dataclass
@@ -174,8 +204,26 @@ class FakeDataAssets:
174
204
  return DataAssetSearchResults(has_more=False, results=list(self.existing))
175
205
 
176
206
 
207
+ @dataclass
208
+ class FakeListing:
209
+ """``client.capsules`` or ``client.pipelines``: both list computations the same way."""
210
+
211
+ computations: FakeComputations
212
+
213
+ def list_computations(self, source_id: str) -> list[Computation]:
214
+ return self.computations.list_computations(source_id)
215
+
216
+
177
217
  @dataclass
178
218
  class FakeClient:
179
219
  computations: FakeComputations
180
220
  data_assets: FakeDataAssets
181
221
  retries: Any = 0
222
+
223
+ @property
224
+ def capsules(self) -> FakeListing:
225
+ return FakeListing(self.computations)
226
+
227
+ @property
228
+ def pipelines(self) -> FakeListing:
229
+ return FakeListing(self.computations)
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import dataclasses
3
4
  from typing import Any
4
5
 
5
6
  import pytest
@@ -15,7 +16,9 @@ from aind_codeocean_dispatch import (
15
16
  DispatchFailed,
16
17
  DispatchInterrupted,
17
18
  Job,
19
+ Outcome,
18
20
  job_key,
21
+ key_marker,
19
22
  key_tag,
20
23
  raise_for_failures,
21
24
  run_jobs,
@@ -394,6 +397,198 @@ def test_reuse_off_never_searches(clock: FakeClock) -> None:
394
397
  assert client.data_assets.searches == []
395
398
 
396
399
 
400
+ # -- on_outcome -------------------------------------------------------------------
401
+
402
+
403
+ def test_on_outcome_sees_each_job_as_it_finishes(clock: FakeClock) -> None:
404
+ existing = [asset("old", DataAssetState.Ready, tags=[key_tag("k1")])]
405
+ client = make_client(clock, {"slow": [[RUNNING] * 5 + [SUCCEEDED]], "crash": [[CRASHED]]}, existing=existing)
406
+ seen: list[tuple[Outcome, float]] = []
407
+
408
+ outcomes = run_jobs(
409
+ client,
410
+ [job("slow"), job("crash"), job("cached", key="k1")],
411
+ reuse=True,
412
+ poll_interval_s=10,
413
+ on_outcome=lambda outcome: seen.append((outcome, clock.t)),
414
+ )
415
+
416
+ assert [(o.job.label, o.status) for o, _ in seen] == [
417
+ ("cached", "reused"),
418
+ ("crash", "failed"),
419
+ ("slow", "captured"),
420
+ ]
421
+ # Each is reported when reached, not when the batch ends.
422
+ assert seen[1][1] < seen[2][1]
423
+ assert sorted((o for o, _ in seen), key=lambda o: o.job.label) == sorted(outcomes, key=lambda o: o.job.label)
424
+
425
+
426
+ def test_on_outcome_sees_cancelled_jobs(clock: FakeClock) -> None:
427
+ client = make_client(clock, {"a": [[CRASHED]], "b": [[RUNNING]]})
428
+ seen: list[Outcome] = []
429
+
430
+ run_jobs(client, [job("a"), job("b")], cancel_on_failure=True, on_outcome=seen.append)
431
+
432
+ assert [(o.job.label, o.status) for o in seen] == [("a", "failed"), ("b", "cancelled")]
433
+
434
+
435
+ def test_on_outcome_error_does_not_affect_the_batch(clock: FakeClock) -> None:
436
+ client = make_client(clock, {"a": [[SUCCEEDED]], "b": [[RUNNING, SUCCEEDED]]})
437
+
438
+ def broken(outcome: Outcome) -> None:
439
+ raise RuntimeError("hook")
440
+
441
+ outcomes = run_jobs(client, [job("a"), job("b")], on_outcome=broken)
442
+
443
+ assert [o.status for o in outcomes] == ["captured", "captured"]
444
+
445
+
446
+ # -- resume -------------------------------------------------------------------------
447
+
448
+
449
+ def test_keyed_computations_are_named_for_resume(clock: FakeClock) -> None:
450
+ client = make_client(clock, {"a": [[SUCCEEDED]], "b": [[SUCCEEDED]]})
451
+
452
+ run_jobs(client, [job("a", key="k1"), job("b")])
453
+
454
+ assert client.computations.names == {"comp-0": f"a {key_marker('k1')}"}
455
+
456
+
457
+ def test_failed_naming_is_tried_again(clock: FakeClock) -> None:
458
+ client = make_client(clock, {"a": [[RUNNING, RUNNING, SUCCEEDED]]})
459
+ client.computations.rename_errors = [http_error(429)]
460
+
461
+ (outcome,) = run_jobs(client, [job("a", key="k1")])
462
+
463
+ assert outcome.status == "captured"
464
+ assert client.computations.names["comp-0"] == f"a {key_marker('k1')}"
465
+
466
+
467
+ def test_resume_follows_the_owners_running_computation(clock: FakeClock) -> None:
468
+ client = make_client(clock, {})
469
+ client.computations.existing("a", "earlier", [RUNNING, SUCCEEDED], name=f"a {key_marker('k1')}")
470
+
471
+ (outcome,) = run_jobs(client, [job("a", key="k1")], resume_owner="me")
472
+
473
+ assert (outcome.status, outcome.resumed, outcome.computation_ids) == ("captured", True, ("earlier",))
474
+ assert client.computations.launches == []
475
+
476
+
477
+ def test_resume_matches_the_owner_by_email(clock: FakeClock) -> None:
478
+ client = make_client(clock, {})
479
+ client.computations.existing("a", "earlier", [SUCCEEDED], name=f"a {key_marker('k1')}", owner="me@x.org")
480
+
481
+ (outcome,) = run_jobs(client, [job("a", key="k1")], resume_owner="me@x.org")
482
+
483
+ assert outcome.resumed
484
+
485
+
486
+ def test_resume_ignores_other_owners_failed_runs_and_other_keys(clock: FakeClock) -> None:
487
+ client = make_client(clock, {"a": [[SUCCEEDED]]})
488
+ client.computations.existing("a", "theirs", [RUNNING], name=f"a {key_marker('k1')}", owner="someone")
489
+ client.computations.existing("a", "failed", [CRASHED], name=f"a {key_marker('k1')}")
490
+ client.computations.existing("a", "longer", [RUNNING], name=f"a {key_marker('k10')}")
491
+
492
+ (outcome,) = run_jobs(client, [job("a", key="k1")], resume_owner="me")
493
+
494
+ assert (outcome.status, outcome.resumed, outcome.computation_ids) == ("captured", False, ("comp-0",))
495
+
496
+
497
+ def test_resume_prefers_a_live_computation_to_a_finished_one(clock: FakeClock) -> None:
498
+ client = make_client(clock, {})
499
+ marker = key_marker("k1")
500
+ client.computations.existing("a", "done", [SUCCEEDED], name=f"a {marker}", created=5)
501
+ client.computations.existing("a", "live", [RUNNING, SUCCEEDED], name=f"a {marker}", created=1)
502
+
503
+ (outcome,) = run_jobs(client, [job("a", key="k1")], resume_owner="me")
504
+
505
+ assert outcome.computation_ids == ("live",)
506
+
507
+
508
+ def test_resume_captures_a_succeeded_uncaptured_computation(clock: FakeClock) -> None:
509
+ client = make_client(clock, {})
510
+ client.computations.existing("a", "earlier", [SUCCEEDED], name=f"a {key_marker('k1')}")
511
+
512
+ (outcome,) = run_jobs(client, [job("a", key="k1")], resume_owner="me")
513
+
514
+ assert (outcome.status, outcome.resumed) == ("captured", True)
515
+ assert [p.name for p in client.data_assets.created] == ["a-earlier"]
516
+
517
+
518
+ def test_resume_does_not_capture_a_succeeded_computation_again(clock: FakeClock) -> None:
519
+ existing = [asset("old", DataAssetState.Ready, tags=[key_tag("k1")])]
520
+ client = make_client(clock, {"a": [[SUCCEEDED]]}, existing=existing)
521
+ client.computations.existing("a", "earlier", [SUCCEEDED], name=f"a {key_marker('k1')}")
522
+
523
+ (outcome,) = run_jobs(client, [job("a", key="k1")], resume_owner="me")
524
+
525
+ assert (outcome.status, outcome.resumed, outcome.computation_ids) == ("captured", False, ("comp-0",))
526
+
527
+
528
+ def test_resume_waits_on_a_capture_in_progress(clock: FakeClock) -> None:
529
+ client = make_client(clock, {}, existing=[asset("capturing", DataAssetState.Draft, tags=[key_tag("k1")])])
530
+ client.data_assets._scripts["capturing"] = [DataAssetState.Draft, DataAssetState.Ready]
531
+
532
+ (outcome,) = run_jobs(client, [job("a", key="k1")], resume_owner="me")
533
+
534
+ assert (outcome.status, outcome.asset_id, outcome.resumed) == ("captured", "capturing", True)
535
+ assert client.computations.launches == []
536
+ assert client.data_assets.created == []
537
+
538
+
539
+ def test_resume_lists_each_capsule_once(clock: FakeClock) -> None:
540
+ client = make_client(clock, {"a": [[SUCCEEDED], [SUCCEEDED]]})
541
+ jobs = [Job(label, RunParams(capsule_id="a"), capture=capture_as(label), key=label) for label in ("x", "y")]
542
+
543
+ run_jobs(client, jobs, resume_owner="me")
544
+
545
+ assert client.computations.listings == ["a"]
546
+
547
+
548
+ def test_resume_lists_a_pipelines_computations(clock: FakeClock) -> None:
549
+ client = make_client(clock, {})
550
+ client.computations.existing("p", "earlier", [SUCCEEDED], name=f"p {key_marker('k1')}")
551
+
552
+ (outcome,) = run_jobs(
553
+ client, [Job("p", RunParams(pipeline_id="p"), capture=capture_as("p"), key="k1")], resume_owner="me"
554
+ )
555
+
556
+ assert outcome.computation_ids == ("earlier",)
557
+
558
+
559
+ def test_rate_limited_listing_is_retried(clock: FakeClock) -> None:
560
+ client = make_client(clock, {})
561
+ client.computations.existing("a", "earlier", [SUCCEEDED], name=f"a {key_marker('k1')}")
562
+ client.computations.list_errors = [http_error(429)]
563
+
564
+ (outcome,) = run_jobs(client, [job("a", key="k1")], resume_owner="me")
565
+
566
+ assert outcome.resumed
567
+ assert client.computations.listings == ["a", "a"]
568
+
569
+
570
+ def test_failed_listing_falls_back_to_launching(clock: FakeClock) -> None:
571
+ client = make_client(clock, {"a": [[SUCCEEDED]]})
572
+ client.computations.list_errors = [http_error(403)]
573
+
574
+ (outcome,) = run_jobs(client, [job("a", key="k1")], resume_owner="me")
575
+
576
+ assert (outcome.status, outcome.resumed) == ("captured", False)
577
+
578
+
579
+ def test_resume_needs_an_sdk_whose_computations_carry_an_owner(
580
+ clock: FakeClock, monkeypatch: pytest.MonkeyPatch
581
+ ) -> None:
582
+ @dataclasses.dataclass
583
+ class OldComputation:
584
+ id: str
585
+
586
+ monkeypatch.setattr(runner, "Computation", OldComputation)
587
+
588
+ with pytest.raises(ValueError, match="0.15"):
589
+ run_jobs(make_client(clock, {}), [job("a", key="k1")], resume_owner="me")
590
+
591
+
397
592
  # -- interruption and misuse --------------------------------------------------
398
593
 
399
594
 
@@ -17,7 +17,7 @@ wheels = [
17
17
 
18
18
  [[package]]
19
19
  name = "aind-codeocean-dispatch"
20
- version = "0.5.0"
20
+ version = "0.6.0"
21
21
  source = { editable = "." }
22
22
  dependencies = [
23
23
  { name = "aind-code-ocean-pipeline-utils" },
@@ -1,48 +0,0 @@
1
- # CLAUDE.md
2
-
3
- This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
-
5
- ## Commands
6
-
7
- ```bash
8
- # Install dependencies
9
- uv sync
10
-
11
- # Run all checks (formatting, linting, type checking, tests)
12
- ./scripts/run_linters_and_checks.sh -c
13
-
14
- # Run tests
15
- uv run pytest
16
-
17
- # Run a single test file
18
- uv run pytest tests/test_example.py
19
-
20
- # Run a single test by name
21
- uv run pytest -k "test_name"
22
-
23
- # Formatting
24
- uv run ruff format
25
-
26
- # Linting
27
- uv run ruff check
28
- uv run ruff check --fix
29
-
30
- # Type checking
31
- uv run mypy
32
-
33
- # Spell checking
34
- uv run codespell --check-filenames
35
-
36
- ```
37
-
38
- Always use `uv run` to execute commands, `uv add` to add dependencies, and `uv sync` to set up the environment. Never use bare `pip` or `python`.
39
-
40
- ## Architecture
41
-
42
- This is a Python package using a `src/` layout. Source code lives in `src/aind_codeocean_dispatch/`, tests in `tests/`.
43
-
44
- - Build system: hatchling
45
- - Formatting/linting: ruff (line length 120, numpy docstring convention)
46
- - Testing: pytest with coverage reporting
47
- - Type checking: mypy (strict mode)
48
- - Versioning: commitizen (semantic versioning via conventional commits)
@@ -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,73 +0,0 @@
1
- # AIND Code Ocean dispatch
2
-
3
- ![CI](https://github.com/AllenNeuralDynamics/aind-codeocean-dispatch/actions/workflows/ci-call.yml/badge.svg)
4
- [![PyPI - Version](https://img.shields.io/pypi/v/aind-codeocean-dispatch)](https://pypi.org/project/aind-codeocean-dispatch/)
5
- [![semantic-release: angular](https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
6
- [![License](https://img.shields.io/badge/license-MIT-brightgreen)](LICENSE)
7
- [![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)
8
- [![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)
9
- [![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)
10
-
11
- Launch, monitor, and capture batches of Code Ocean capsule runs
12
-
13
- ## Installation
14
-
15
- If you choose to clone the repository, you can install the package by running the following command from the root directory of the repository:
16
-
17
- ```bash
18
- pip install .
19
- ```
20
-
21
- Otherwise, you can use pip:
22
-
23
- ```bash
24
- pip install aind-codeocean-dispatch
25
- ```
26
-
27
-
28
-
29
- To develop the code, run:
30
- ```bash
31
- uv sync
32
- ```
33
-
34
- ## Capturing runs from a post-run automation
35
-
36
- A Code Ocean pipeline can name an automation capsule that runs after every run. A capsule
37
- whose `code/run` is
38
-
39
- ```bash
40
- #!/usr/bin/env bash
41
- set -e
42
- python -m aind_codeocean_dispatch.automation
43
- ```
44
-
45
- captures each successful run as an internal data asset, named by the results'
46
- `data_description.json` when it declares a derived name and otherwise after the first
47
- input asset. It needs only `CODEOCEAN_TOKEN`; `CAPTURE_TAGS`, `CAPTURE_FAILED` and
48
- `CAPTURE_PERMISSIONS` adjust it. It registers nothing in DocDB and writes no external
49
- bucket, so pipelines that publish use `asset-creation-capsule` instead.
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.