aind-codeocean-dispatch 0.4.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.4.0 → aind_codeocean_dispatch-0.6.0}/.copier-answers.yml +1 -1
  2. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/CHANGELOG.md +16 -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.4.0 → aind_codeocean_dispatch-0.6.0}/pyproject.toml +1 -1
  8. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/scripts/run_linters_and_checks.sh +24 -12
  9. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/src/aind_codeocean_dispatch/__init__.py +5 -0
  10. aind_codeocean_dispatch-0.6.0/src/aind_codeocean_dispatch/automation.py +159 -0
  11. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/src/aind_codeocean_dispatch/runner.py +158 -16
  12. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/tests/fakes.py +52 -4
  13. aind_codeocean_dispatch-0.6.0/tests/test_automation.py +181 -0
  14. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/tests/test_runner.py +195 -0
  15. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/uv.lock +1 -1
  16. aind_codeocean_dispatch-0.4.0/CLAUDE.md +0 -48
  17. aind_codeocean_dispatch-0.4.0/PKG-INFO +0 -73
  18. aind_codeocean_dispatch-0.4.0/README.md +0 -56
  19. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  20. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  21. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/.github/ISSUE_TEMPLATE/user-story.md +0 -0
  22. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/.github/dependabot.yml +0 -0
  23. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/.github/workflows/bump-call.yml +0 -0
  24. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/.github/workflows/ci-call.yml +0 -0
  25. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/.github/workflows/publish-call.yml +0 -0
  26. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/.gitignore +0 -0
  27. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/.python-version +0 -0
  28. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/LICENSE +0 -0
  29. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/src/aind_codeocean_dispatch/capsule_git.py +0 -0
  30. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/src/aind_codeocean_dispatch/capture.py +0 -0
  31. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/src/aind_codeocean_dispatch/py.typed +0 -0
  32. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/tests/__init__.py +0 -0
  33. {aind_codeocean_dispatch-0.4.0 → aind_codeocean_dispatch-0.6.0}/tests/test_capsule_git.py +0 -0
  34. {aind_codeocean_dispatch-0.4.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,22 @@ 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
+
14
+ ## v0.5.0 (2026-10-15)
15
+
16
+ ### Feat
17
+
18
+ - add a post-run automation that captures runs as internal assets
19
+
20
+ ### Fix
21
+
22
+ - make check script exit nonzero when any step fails
23
+
8
24
  ## v0.4.0 (2026-10-15)
9
25
 
10
26
  ### 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.4.0"
16
+ version = "0.6.0"
17
17
 
18
18
  dependencies = [
19
19
  "aind-code-ocean-pipeline-utils>=0.7.1",
@@ -41,24 +41,36 @@ main() {
41
41
  run() { uv run $UV_ARGS -- "$@"; }
42
42
  fi
43
43
 
44
- echo "+ ruff format"
45
- run ruff format
44
+ # Every step runs even after a failure so one pass reports all problems;
45
+ # the exit status is nonzero if any step failed.
46
+ FAILED=""
47
+ step() {
48
+ name="$1"
49
+ shift
50
+ echo "+ $name"
51
+ run "$@" || FAILED="$FAILED
52
+ $name"
53
+ }
54
+
55
+ step "ruff format" ruff format
46
56
 
47
57
  if [ "$CHECKS" = true ]; then
48
- echo "+ ruff check"
49
- run ruff check
50
- echo "+ mypy"
51
- run mypy
52
- echo "+ interrogate -v src"
53
- run interrogate -v src
54
- echo "+ codespell --check-filenames"
55
- run codespell --check-filenames
56
- echo "+ pytest --cov aind_codeocean_dispatch$([ -n "$PYTEST_ARGS" ] && printf ' -- %s' "$PYTEST_ARGS")"
58
+ step "ruff check" ruff check
59
+ step "mypy" mypy
60
+ step "interrogate -v src" interrogate -v src
61
+ step "codespell --check-filenames" codespell --check-filenames
57
62
  # shellcheck disable=SC2086
58
- run pytest --cov aind_codeocean_dispatch $PYTEST_ARGS
63
+ step "pytest --cov aind_codeocean_dispatch$([ -n "$PYTEST_ARGS" ] && printf ' -- %s' "$PYTEST_ARGS")" \
64
+ pytest --cov aind_codeocean_dispatch $PYTEST_ARGS
59
65
  else
60
66
  echo "(checks skipped; pass -c or --checks to enable)"
61
67
  fi
68
+
69
+ if [ -n "$FAILED" ]; then
70
+ echo "FAILED:$FAILED" >&2
71
+ return 1
72
+ fi
73
+ echo "All steps passed."
62
74
  }
63
75
 
64
76
  main "$@"
@@ -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()