Skip to main content

AIND Code Ocean dispatch

CI PyPI - Version semantic-release: angular License ruff uv Copier

Launch, monitor, and capture batches of Code Ocean capsule runs

Installation

If you choose to clone the repository, you can install the package by running the following command from the root directory of the repository:

pip install .

Otherwise, you can use pip:

pip install aind-codeocean-dispatch

Usage

Running a batch of runs

run_jobs launches a batch of capsule or pipeline runs, waits for them from one polling loop, and captures each successful run as a data asset:

from codeocean import CodeOcean
from codeocean.computation import DataAssetsRunParam, NamedRunParam, RunParams

from aind_codeocean_dispatch import Job, capture_as, job_key, raise_for_failures, run_jobs

client = CodeOcean(domain="https://codeocean.allenneuraldynamics.org", token=token)

jobs = []
for stream in streams:
    params = RunParams(
        capsule_id=WORKER_CAPSULE_ID,
        data_assets=[DataAssetsRunParam(id=raw_asset_id, mount="raw")],
        named_parameters=[NamedRunParam(param_name="stream", value=stream)],
    )
    jobs.append(
        Job(
            label=stream,
            run_params=params,
            capture=capture_as(f"{session}_{stream}_sorted", tags=["sorted"]),
            key=job_key(params),
        )
    )

outcomes = run_jobs(client, jobs, launch_interval_s=1, start_retries=3, reuse=True)
raise_for_failures(outcomes)
asset_ids = {o.job.label: o.asset_id for o in outcomes}

A failed job does not raise; each Outcome carries its status, asset_id, every computation_ids attempt, and on failure an error and a failure kind. raise_for_failures turns failures into one DispatchFailed.

Behaviour worth knowing:

  • Failed starts. Code Ocean sometimes fails to start a run (end_status=Failed, no results). Up to start_retries relaunches follow, after start_retry_backoff_s (60 s) doubling each time, and every pending launch waits too, since the cause is usually machine capacity.
  • Rate limits and errors. 429s are retried honouring Retry-After. Other 5xx and connection errors are retried on reads only: a launch or capture POST may already have taken effect, so resending it could duplicate the computation or asset.
  • Pacing. max_in_flight caps concurrent runs and launch_interval_s spaces launches; both are off by default.
  • Reuse. A job's key is added to its asset as a tag. With reuse=True, a Ready asset you created with that tag is returned instead of launching. job_key fingerprints the launch request; pass salt= for what the request cannot show, such as the commit of an unreleased capsule (capsule_head_commit(client, capsule_id) reads it inside a run).
  • Acting on each job as it finishes. on_outcome= is called with each job's Outcome as soon as it is reached, whatever its status, so a caller can register or report results without waiting for the whole batch. An exception it raises is logged and does not affect the other jobs.
  • Resuming a batch. A keyed job's computation is renamed to its label plus key_marker(key). With resume_owner= set to your Code Ocean user id or email, a later batch follows your computation of the same job instead of launching it again: one still running is waited on, one that succeeded but was never captured is captured, and a capture still in progress is waited on. A succeeded computation that already has a Ready capture is resumed only through reuse. Code Ocean lists every user's computations of a capsule and has no call naming the caller, hence the argument; it needs codeocean 0.15 or later.
  • Cancelling a doomed batch. cancel_on_failure=True, or a predicate on the failed Outcome such as lambda o: not o.transient, stops launching and stops and deletes running computations; captures already under way finish.
  • Capture names. capture_as uses a fixed name. capture_named_by_data_description uses the name a derived data_description.json in the results declares, and otherwise a fallback name plus the capture time.

Capturing runs from a post-run automation

A Code Ocean pipeline can name an automation capsule that runs after every run. A capsule whose code/run is

#!/usr/bin/env bash
set -e
python -m aind_codeocean_dispatch.automation

captures each successful run as an internal data asset, named by the results' data_description.json when it declares a derived name and otherwise after the first input asset. It needs only CODEOCEAN_TOKEN; CAPTURE_TAGS, CAPTURE_FAILED and CAPTURE_PERMISSIONS adjust it. It registers nothing in DocDB and writes no external bucket, so pipelines that publish use asset-creation-capsule instead.

Contributing

Setup, checks, tests and conventions are in CONTRIBUTING.md.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Worker diagnostics

Install aind-codeocean-dispatch[diagnostics] when workers emit structured failure artifacts. The extra uses aind-diagnostics for the report contract and aind-code-ocean-pipeline-utils for the shared artifact namespace.

Optional reporting dependencies load when the reporting helpers are used, so importing the module also works with the base installation.

from aind_codeocean_dispatch import raise_for_failures, run_jobs
from aind_codeocean_dispatch.diagnostics import diagnose_outcome

outcomes = run_jobs(client, jobs)
outcomes = [diagnose_outcome(client, item, stage="ephys", unit=item.job.label) for item in outcomes]
raise_for_failures(outcomes)

Supply the stage and unit that the worker used when saving its report; the dispatcher does not infer capsule-specific parameter names. diagnose_outcome adds diagnostic_report and a readable explanation to failed outcomes while preserving their status, failure classification, and capture state. Successful outcomes are unchanged. DispatchFailed combines attached reports and retains the individual failures for per-worker facts and provenance.

worker_failure reads the small failure header and then its namespaced report. It bounds downloads, validates the common schema and causal graph, accepts new domain codes, and keeps the producer's summary when full evidence is missing, malformed, or larger than 2 MiB. It returns None when no usable header exists, so callers can retain their fallback for older workers. Result-file errors cannot replace the original computation failure, and signed download URLs are never included in the returned explanation.

For other required JSON artifacts, result_json provides the same bounded reader but propagates retrieval errors. Domain facts such as manifest coverage remain the caller's responsibility.

Metadata

Release files for aind-codeocean-dispatch 0.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aind-codeocean-dispatch 0.7.0
File Size Uploaded Provenance Actions
aind_codeocean_dispatch-0.7.0.tar.gz 143.8 kB Without provenance Details for aind_codeocean_dispatch-0.7.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for aind-codeocean-dispatch 0.7.0
File Interpreter ABI Platform Actions
aind_codeocean_dispatch-0.7.0-py3-none-any.whl Python 3 none any Details for aind_codeocean_dispatch-0.7.0-py3-none-any.whl

Total release size: 168.3 kB

Release files / aind_codeocean_dispatch-0.7.0.tar.gz

Download URL aind_codeocean_dispatch-0.7.0.tar.gz
Size 143.8 kB
Tags Source
SHA-256 checksum
How to use checksums
5c490e12de0bf1d691aeab1a20ea25db4431fbdae44cccd356ab63c3733939de
BLAKE2b-256 checksum
How to use checksums
395e513240a1a4a1c1693eb4f406d5013e3707355bdf42fdafcf5a9463658c9e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.11 {"installer":{"name":"uv","version":"0.13.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / aind_codeocean_dispatch-0.7.0-py3-none-any.whl

Download URL aind_codeocean_dispatch-0.7.0-py3-none-any.whl
Size 24.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
57ce0bec5a38900e6d9a46461ca566e9d56d603e82c0a17aef73d6ae99c16093
BLAKE2b-256 checksum
How to use checksums
dfee1cc0538974aaf759126540bf2042e98ab1c8af3f729396305cc8f5c221cc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.11 {"installer":{"name":"uv","version":"0.13.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for aind-codeocean-dispatch 0.7.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page