<!-- Source: https://docs.biosimulant.com/runtime/lab-environment -->

# Lab environment

A Lab can describe its software environment by reference: where each package
comes from and the hash it must match. Use this when a Lab needs packages from
outside PyPI (such as DGL's CUDA wheels), a CUDA or other base image, or reruns
that install exactly the same files. Labs without it keep installing the exact
pins in each [`model.yaml`](/runtime/model-manifest)
`runtime.dependencies.packages`, as before.

The recipe lives in the manifests the Lab already has. The Lab never holds
wheels, binaries or toolchains.

| Where | Written by | Contents |
| --- | --- | --- |
| [`lab.yaml`](/runtime/lab-manifest) `runtime.environment` | You or your agent | Base image, named sources, which sources a package may come from, packages only the Lab needs, check commands |
| `model.yaml` `runtime.dependencies.packages` | You or your agent | Each component's exact pins, unchanged. Every one is installed. |
| `environment.lock`, next to `lab.yaml` | A run, then saved into the Lab | Every file to install: name, version, sha256 and the URL it came from |

Every managed run fetches from the listed sources and verifies every hash.
Biosimulant keeps no copies, registry or cache of its own. Modal may reuse an
identical earlier image build on its side; nothing depends on that.

## lab.yaml runtime.environment

```yaml
runtime:
  python_version: "3.12"
  environment:
    base: nvidia/cuda:12.4.1-cudnn-runtime-ubuntu22.04@sha256:<64 hex>   # optional
    sources:
      pytorch: { index: https://download.pytorch.org/whl/cu124 }
      dgl: { find_links: https://data.dgl.ai/wheels/torch-2.4/cu124/repo.html }
      dgl-mirror: { find_links: https://mirror.example.org/dgl/ }
    packages:
      - { name: torch, from: [pytorch] }
      - { name: dgl, from: [dgl, dgl-mirror] }
      - "se3-transformer @ git+https://github.com/RosettaCommons/RFdiffusion@<40-character commit>#subdirectory=env/SE3Transformer"
    check:
      - python -c "import torch, dgl, se3_transformer"
```

```yaml
# models/<component>/model.yaml
runtime:
  dependencies:
    packages: [torch==2.4.0, dgl==2.4.0+cu124, e3nn==0.3.3]
```

| Key | Rules |
| --- | --- |
| `base` | Optional. An image reference pinned by digest, `name:tag@sha256:<64 hex>`, with a Debian or Ubuntu userland. Without it, runs start from plain Python. System software that is not a Python wheel comes from here. |
| `sources` | Name to `{index: URL}` (a PEP 503 simple index) or `{find_links: URL}` (a page of wheel links). https only, no credentials. `pypi` is built in. |
| `packages` | `{name: pkg, from: [sources]}` chooses where a package a `model.yaml` pins comes from. A pin string or `{pin: pkg==1.2.3, from: [...]}` adds a package only the Lab needs. Git URLs with a full 40-character commit and https archive URLs ending in `#sha256=<64 hex>` go here. |
| `from` | The sources a package may come from, in order. The first is used; the rest are fallbacks that must serve a file with the locked sha256. Defaults to `pypi`. |
| `check` | Up to 10 commands run when the image is built, without a GPU. Use import checks. |

The Python version is `runtime.python_version` (3.10 to 3.14). Pins in
`model.yaml` stay plain `name==version` strings, and components must agree on
versions. `biosimulant` is provided by the platform and is not listed.

## environment.lock

The first run of a Lab without a lock resolves the recipe and returns the lock
it made: `lab_environment.generated_lock` from MCP `run_get`, with the path to
save it as. Save that content unchanged as `environment.lock` next to
`lab.yaml`. Later runs install exactly the locked files, or fail and say which
file is missing.

The lock is bound to the base, Python and pins, not to the sources. You can add
or change a source or fallback without refreshing the lock; the hashes still
decide whether a file is the same. Changing a pin, the base or Python makes the
lock stale, and runs refuse it with `lab_environment_lock_stale`. Delete the
lock in the same change, run once and save the new one.

**Info:**

  Do not edit `environment.lock` by hand. Save the content a run returns.

## When a source breaks

If every listed source for a locked file is unreachable or serves different
bytes, the run fails with `lab_environment_fetch_failed`, naming the package,
file, sha256 and each source tried. Add another source that serves the same
file and list it in that package's `from`, then run again.

## What runs record

Each run records the recipe hash (covering `runtime.environment`, the Python
version and the model pins), the lock hash, the pins hash, the base image
reference and any fallbacks used. MCP `run_get` returns them as
`lab_environment`.

## Limits

- Labs with `runtime.environment` run on Modal compute.
- Runs are Linux x86_64; environment markers are not supported.
- Private sources that need credentials are not supported yet.
- System packages (apt) cannot be listed yet; use a base image that has them.
- Local `biosimulant labs run` ignores `runtime.environment` and keeps
  installing `model.yaml` pins.
- An earlier `environment.yaml` file is no longer read; runs refuse a Lab that
  still has one (`lab_environment_moved`).

## See also

- [lab.yaml schema](/runtime/lab-manifest)
- [model.yaml schema](/runtime/model-manifest)

## Explicit software setup

`biosimulant` 0.0.44 introduces optional `lab.yaml` `runtime.setup`. It prepares
software before Lab/model dependency installation and model imports. No extra
file or Dockerfile is required:

```yaml
runtime:
  python_version: "3.12"
  setup:
    command:
      - python
      - -c
      - |
          import os
          from pathlib import Path
          prefix = Path(os.environ["BIOSIM_ENV_PREFIX"])
          (prefix / "bin").mkdir(parents=True, exist_ok=True)
          print("Preparing tools in", prefix, flush=True)
    timeout_seconds: 900
```

Use `[python, scripts/prepare.py]` for a file, or explicitly invoke a shell,
such as `[bash, -eu, scripts/install.sh]` or
`[powershell, -NonInteractive, -File, scripts/install.ps1]`. `command` must be a
nonempty argument list; there is no implicit shell, interpolation, or elevation.
The executable `python` selects the Lab interpreter, including on Windows.
Timeout defaults to 900 seconds, accepts 1–3600, and shares an overall one-hour
preparation deadline with dependency installation. Failure stops the run.

The working directory is the declaring Lab. `BIOSIM_LAB_ROOT` names it;
`BIOSIM_ENV_PREFIX` is the prepared environment's installation prefix. Install
user-space tools there (`bin` on POSIX, `Scripts` on Windows); its executable
directory is on the run's PATH. Use the platform's package manager only where
the execution environment permits it. Python orchestration does not make apt,
Homebrew, PowerShell, or their privileges available on every OS. Setup has no
GPU during hosted image construction.

Setup should use Python's standard library until dependencies are installed.
Keep Python package requirements in model manifests. Dataset downloads,
sample-specific indexes and work that depends on run inputs belong in model
execution, including `once_before_run` modules. Setup subprocess environment
exports do not change the runner. Relative build scratch files are temporary;
install persistent tools/assets into the environment prefix.

## Execution and composition

`labs run` and package execution prepare a fresh isolated environment even with
no Python requirements. `labs serve` defers setup until an explicit run and
executes it in an isolated child; merely viewing a Lab does not run setup.
Validation, capability inspection, packaging and previews do not execute setup.
Live-object APIs require a matching prepared environment and never install in
the caller's interpreter. `--no-install-deps` does not bypass this check.

Embedded child Labs run setup dependency-first, then their parent. Shared child
paths run once. For Hub/package-backed children, export with the existing
`--vendor-dependencies` option, then run the vendored package: setup needs all
source files in the immutable context. A setup plan with unresolved
package-backed children is rejected rather than skipped. All components still
share one compatible Python environment.

The source context includes the complete Lab source (up to 32 MiB/5000 files),
not just the directly named script. Helpers therefore invalidate preparation.
Operational state, caches, `.env*`, generated `environment.lock`, and bytecode
are excluded. Per-run runtime settings and instance parameter overrides do not
change software identity. Source symlinks are not allowed in setup context.
Write generated assets outside the source context so setup cannot invalidate
its own preparation. No background process may outlive setup.

Successful preparation is recorded with setup identity, interpreter, OS,
architecture, exit codes and durations. A boolean environment flag does not
prove preparation. Local results include `environment.setup`; cloud results
retain setup identity and execution in Lab environment provenance. Failures and
interrupted environments are never considered prepared. Scripts must tolerate
retry after partial failure; exactly-once execution across rebuilds is not
guaranteed.

## Hosted environments and locks

The platform builds setup inside the existing isolated Modal image preparation,
before Lab dependency resolution/installation, then reuses successful provider
image layers when available. Setup-only Labs also use this preparation path.
The selected hosted runtime must support 0.0.44; older runtimes/providers return
a blocker. Release availability and deployment are separate from source support.

`environment.lock` still exists. `environment.yaml` was retired. Setup-bearing
hosted environments use a version-2 Python lock bound to setup source and target
platform as well as pins/base/Python; legacy environments keep version-1 locks.
After adding/changing setup, regenerate and save the returned lock unchanged.
The lock covers Python distributions, not arbitrary apt packages or files fetched
by setup. Pin external versions and verify download checksums where practical;
identical script bytes alone do not guarantee identical remote downloads.

Local execution supports setup plus ordinary model package pins. The platform's
`runtime.environment` source/base/lock resolver remains a hosted capability;
local runs reject those declarations instead of silently ignoring them. Do not claim local/cloud parity for them. Preview the actual run
target and its supported capabilities before execution. Arbitrary setup remains
code execution and must be described accurately to users and plugin reviewers.
