agentleFS
aicell-labaicell-lab/bioengine/.claude/skills/bioengine-maintainer/SKILL.md

bioengine-maintainer

Skill9 starsChanged 4 days agoMITView on GitHub

Reference material for agents helping maintain the BioEngine codebase — architecture map, dev image testing workflow, cleanup rules, Hypha platform invariants, issue and PR writing style. Loaded on demand by Claude Code in addition to the always-on rules in CLAUDE.md.

  • Reads credentials
  • Installs packages

The file

Show its rules and text

We split this skill into the rules it gives an agent

17 rules. About 0 are common, 8 are distinctive, and 9 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈8

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 9

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Every BioEngine app is a folder containing manifest.yaml and the app's Python files at the root.

    line 137
  2. Very specific:

    Only after both modes are green: bump pyproject.toml to the canonical version in a separate commit, push, gh pr ready <PR>.

    line 267
  3. Distinctive:

    After merge + canonical image published:

    line 268
  4. Very specific:

    Delete every dev image tag from GHCR.

    line 271
  5. Distinctive:

    After a canonical release, list every dev tag and DELETE via GHCR API.

    line 277
  6. Very specific:

    Don't blanket-delete: dev tags + :latest move-tags are intentional.

    line 288
  7. Distinctive:

    Promoting to production: When the dev version is validated:

    line 344
  8. Very specific:

    After the production restart picks up the new version, worker.stop_app(application_id="<app>-dev") to reclaim cluster resources.

    line 346
  9. Very specific:

    Cleanup on abandon: If the dev version is abandoned rather than promoted, still worker.stop_app("<app>-dev") to free the replica slot.

    line 348
  10. Distinctive:

    After testing an app is complete, stop and delete temporary apps on the live worker:

    line 356
  11. Very specific:

    Don't leave test/throwaway deployments on bioimage-io/bioengine-worker — they consume shared cluster resources.

    line 363
  12. Very specific:

    When a Hypha service maintains per-replica state on local disk (cellpose-finetuning training sessions in the actor's workdir, model …

    line 383
  13. Distinctive:

    Stale-pin recovery: if the call throws (replica gone — Ray Serve roll, worker eviction), clear the pin and let the next call re-resolve a …

    line 393
  14. Distinctive:

    Read those two runs together before drawing a conclusion from either:

    line 417
  15. Distinctive:

    After the lede: how it was observed or reproduced, the evidence that localises it, and any candidate fix with its caveats.

    line 479
  16. Distinctive:

    When skill content changes:

    line 564
  17. Very specific:

    Adding a new app skill: create apps/<app-name>.md (or apps/<app-name>/ for multi-file) and add an entry to the app skills table in SKILL.md.

    line 568

≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

BioEngine maintainer skill

Reference material for agents helping maintain aicell-lab/bioengine. The always-on hard rules (sync-first, PR-vs-push gates, version bumps, the application_id vs artifact_id distinction, hypha_token parameter, cleanup) live in CLAUDE.md at the repo root. This skill holds the slower-moving reference content.

For the user-facing agent skill (for agents using BioEngine to deploy apps) see ../bioimage.io/public/skills/bioengine/SKILL.md (cloned as a sibling of this repo) or the published copy at https://bioimage.io/skills/bioengine/SKILL.md.

Repository ecosystem

BioEngine spans three GitHub repositories:

RepositoryRoleStatus
aicell-lab/bioengineThis repo — Python package, worker, CLI, apps, Docker image. Canonical implementation. Previously named aicell-lab/bioengine-worker.Active
bioimage-io/bioimage.ioBioImage.IO website — UIs (worker dashboard, deployment wizard, app manager, BioEngineGuide.tsx) and agent skills under public/skills/bioengine/.Active
bioimage-io/bioengineOriginal Triton-based BioEngine. All links redirect here.Archived

The website repo is expected as a sibling directory:

workspace/
├── bioengine/          ← this repo
└── bioimage.io/        ← bioimage-io/bioimage.io

Also added as a git remote bioimage-io:

git remote add bioimage-io git@github.com:bioimage-io/bioimage.io.git

What lives where:

Architecture

┌────────────────────────────────────────┐
│            Hypha Server                │
│   (RPC, service discovery, artifacts)  │
└────────────┬───────────────────────────┘
             │ WebSocket / RPC
┌────────────▼───────────────────────────┐
│         BioEngineWorker                │  ← bioengine/worker/worker.py
│  ┌─────────────────────────────────┐   │
│  │  RayCluster                     │   │  ← bioengine/cluster/ray_cluster.py
│  │  (SLURM / single / external)    │   │
│  └─────────────────────────────────┘   │
│  ┌─────────────────────────────────┐   │
│  │  AppsManager                    │   │  ← bioengine/apps/manager.py
│  │  (Ray Serve lifecycle +         │   │
│  │   artifact management)          │   │
│  └─────────────────────────────────┘   │
│  ┌─────────────────────────────────┐   │
│  │  BioEngineDatasets              │   │  ← bioengine/datasets/
│  │  (Zarr HTTP streaming)          │   │
│  └─────────────────────────────────┘   │
└────────────────────────────────────────┘
ComponentFileResponsibility
BioEngineWorkerbioengine/worker/worker.pyMain orchestrator; Hypha service registration
AppsManagerbioengine/apps/manager.pyApplication lifecycle (deploy/stop/status)
AppBuilderbioengine/apps/builder.pyBuild Ray Serve apps from artifacts
RayClusterbioengine/cluster/ray_cluster.pyRay cluster lifecycle (SLURM / single-machine / external)
BioEngineDatasetsbioengine/datasets/datasets.pyZarr dataset streaming
Artifact utilitiesbioengine/utils/artifact_utils.pyHypha artifact CRUD helpers

The end-to-end deploy_app flow is documented step-by-step in docs/deploy_app_flow.md.

Key file locations

  • bioengine/cli/ — bioengine CLI; entry point bioengine.cli.cli:main
  • bioengine/utils/artifact_utils.py — Hypha artifact CRUD helpers
  • bioengine/apps/manager.py — deploy_app, upload_app, lifecycle
  • bioengine/apps/builder.py — build() constructs Ray Serve app from artifact
  • bioengine/_app/bootstrap.py — introspect_app_in_ray_task, build_and_run_application
  • bioengine/_app/replica_init.py — replica-side source materialisation
  • bioengine/_app/decorators.py — @bioengine.app / @bioengine.method / lifecycle hooks + _scan_class (no @bioengine.cached since 0.11.24 — see "No framework GPU model cache")
  • apps/demo-app/ — reference single-deployment app (keep at version 1.0.0)
  • apps/composition-demo/ — reference multi-deployment app (keep at version 1.0.0)
  • apps/model-runner/ — production model-runner
  • apps/cellpose-finetuning/ — Cellpose fine-tuning
  • pyproject.toml — package version + deps
  • ../bioimage.io/public/skills/bioengine/ — user-facing agent skill (sibling repo)

Development setup

conda activate bioengine
pip install -e ".[worker,cli,dev]"

HYPHA_TOKEN: get one from https://hypha.aicell.io, then echo "HYPHA_TOKEN=<your-token>" > .env && source .env.

Run locally

python -m bioengine.worker \
    --mode single-machine \
    --head-num-gpus 1 \
    --head-num-cpus 4 \
    --workspace-dir ~/.bioengine \
    --debug

Local artifact development: export BIOENGINE_LOCAL_ARTIFACT_PATH=/path/to/bioengine/tests.

Run tests

pytest tests/                  # offline tests only
pytest tests/end_to_end/ -v --live   # deploys to and calls a real cluster

Tests that act on a live cluster are deselected without --live, so the end-to-end command above exits 5 ("no tests collected") if you omit it. Whenever a credential resolves, the run prints the server, the workspace each token is scoped to, and how many live-reaching tests are enabled — with or without --live, so a finished run's log says what it could have touched.

Test organisation:

  • tests/end_to_end/ — integration tests for the core worker
  • tests/apps/ — per-app tests, one subdirectory per app (tests/apps/cellpose/, …)

Application manifest (v0.11 / format_version: 0.6.0)

Every BioEngine app is a folder containing manifest.yaml and the app's Python files at the root. The whole folder is uploaded to the Hypha artifact; the worker ships the same root via runtime_env.py_modules, excluding non-Python content.

my-app/                       ← artifact root + Python module directory
├── manifest.yaml
├── README.md                 ← stays in artifact (excluded from py_modules)
├── frontend/index.html       ← Hypha hosts statically (excluded from py_modules)
└── deployment.py             ← @bioengine.app class

Required manifest fields:

name: My Application
id: my-application                       # Unique lowercase ID (hyphens only)
id_emoji: "🔬"
description: "..."
type: ray-serve
format_version: 0.6.0                    # v0.11 gate
entry: deployment:MyApp                  # module:Class

Optional fields: frontend_entry, version, authorized_users (['*'] or {method_name: [users], "*": [users]}), authors, license, documentation, tutorial, tags.

Multi-file apps put files at the artifact root and use plain top-level imports (apps/composition-demo/ is the reference).

The decorator-module import rule. Modules containing @bioengine.app (and what they transitively import at top level) MUST be importable with just bioengine[worker] and the standard library. The worker introspects them in a clean baseline runtime_env. Heavy deps go in @bioengine.app(pip=…); their imports live inside method bodies or in helper modules the decorator file lazy-imports. See apps/composition-demo/numpy_ops.py + runtimes/b.py.

Local validation:

bioengine apps validate ./my-app

The CLI runs the same validator the worker uses — legacy manifests fail fast with a migration hint without a round-trip.

Deployment modes

ModeDescription
single-machineLocal Ray cluster (dev, small-scale)
external-clusterConnect to existing Ray cluster (e.g. KubeRay)
slurmAuto-scaling via SLURM job scheduler (HPC)

Production deployments (external-cluster mode) — example targets

Production BioEngine only runs in external-cluster mode. The active production deployments as of 0.11.22 are on KTH (SciLifeLab 2) and deNBI. The bioimage.io UI pins its canonical worker to KTH. NOT every maintainer will have credentials to these clusters — the notes below describe the shape so a maintainer with access can act, and let a maintainer without access hand off cleanly.

Different maintainers may run production on entirely different clusters — the pattern (KubeRay + helm chart with values.yaml image.tag + startup-application pins) is what generalizes; the specific repos below are the current KTH/deNBI examples.

TargetCompute backendWorker service ID patternHelm chartNotes
KTH (SciLifeLab 2 K8s)KubeRay on scilifelab-2-dev cluster, hypha namespace + ray-cluster namespacebioimage-io/bioengine-worker-kth-<hash>:bioengine-workeraicell-lab/kth-k8s repo, chart at bioengine-worker/. values.yaml image.tag + startup-app pins; Chart.yaml appVersion mirrors the bioengine version. helm upgrade bioengine-worker-kth <chart> -f values.yaml -n hyphaSplit PVCs (hypha bioengine-pvc 10 GiB, ray-cluster bioengine-pvc 500 GiB Trident RWX NFS) — Entry↔Runtime can share HOME cross-node. Canonical production endpoint the bioimage.io UI pins to bioimage-io/bioengine-worker-kth-*:bioengine-worker — flip only when necessary.
deNBI cloud K8s + RaydeNBI K8sbioimage-io/bioengine-worker-denbi-<hash>:bioengine-workerdenbi-k8s repo (NOT aicell-lab/kth-k8s). Uses the startup-application mechanism — apps are pinned in values.yaml and cycled with the worker. helm upgrade -f values.yaml is REQUIRED (a plain helm upgrade silently reuses stored user-supplied values and drops the new pins)Manila NFS RWX for HOME — Entry↔Runtime env sharing works cross-node. If the maintainer doesn't own denbi-k8s, the change is a coordination task: describe the values.yaml bump (image tag + startup-app version) and hand off.

Coordinated framework + app upgrades. A bioengine version bump that changes app-facing API (0.11.22's rename @bioengine.multiplexed → @bioengine.cached was one) requires a matching app version bump landing at the same helm upgrade. On a single-commit helm upgrade the worker pod cycles → boots the new worker image → deploys the new app version → all in one atomic hop. Bumping the worker image alone would boot on 0.11.22 and immediately AttributeError while trying to deploy an app that still uses the removed API. The clean-break style used in 0.11.22 (no deprecation shim) makes this coordination mandatory rather than merely advisable.

Verify the official model-runner has full functionality after deploy

From 1.19.0 the model-runner no longer hard-fails when HYPHA_TOKEN is absent — it connects anonymously and runs in public read-only mode (search / RDF / validate / test / infer on public models, but get_upload_url and test-report publishing disabled). This is deliberate, so users can self-deploy a runner without minting a token, but it means a misconfigured official deployment (missing / expired / wrong-scoped token — see the worker-token-expiry failure mode) now degrades silently instead of crash-looping. After deploying or upgrading the production model-runner that the bioimage.io UI pins, assert it is fully functional and fail loudly if not:

status = await (await server.get_service("bioimage-io/model-runner")).get_status()
assert status["test_reports_writable"], (
    f"model-runner is NOT fully functional: {status}. The injected token lacks "
    f"read-write scope on the bioimage-io workspace — test reports will not be "
    f"published. Fix the token (k8s secret / startup-app hypha_token) and redeploy."
)

get_status() returns {workspace, is_anonymous, s3_upload_available, test_reports_writable} — capability flags only; artifact/version identity comes from the worker's get_app_status, not here. A tokenless self-deploy is fine to leave anonymous; the assertion is only mandatory for the website-driving production instance.

Other deployment modes — dev and HPC examples

Beyond the production external-cluster deployments, the other two supported modes each have their own workflow. Concrete targets vary per maintainer — the examples below happen to be the current maintainer's setup.

  • single-machine mode — local Ray cluster on a workstation. Used for dev validation of the ray.init(...) path (different code path from KubeRay-mode; regressions in one won't necessarily show in the other). Launch with python -m bioengine.worker --mode single-machine or via docker-compose. Typically this is a maintainer's own workstation.
  • slurm mode — on-demand worker per SLURM job on an HPC cluster, launched via apptainer. The bioengine version is picked up from bioengine[worker]==<version> in the job's env at submission time — no persistent helm, no active push required for framework bumps. Watch out for cluster-specific apptainer gotchas: e.g. apptainer build sif may fail on newer apptainer versions with yama.ptrace_scope=2 — apptainer build --sandbox is the workaround (and the start_hpc_worker.sh script accepts sandbox dirs from 0.9.8+). Example: the current maintainer runs this on NSC's Berzelius (A100-SXM4-80GB); other maintainers will have their own HPC.

No framework GPU model cache (removed in 0.11.24)

There is no @bioengine.cached / bioengine.cache / bioengine/_app/cache.py any more. The in-memory GPU pipeline cache was removed in bioengine 0.11.24 (PR #141). Don't reach for it, and don't reintroduce a framework-level GPU cache.

Why it was removed. The cache's only GPU cleanup was torch.cuda.empty_cache(), so it silently assumed a torch runtime. It could not reclaim TensorFlow's whole-GPU grab or onnxruntime's CUDA arena — those leaked until replica restart — and BioEngine apps don't require torch, so a torch-only GPU cache was the wrong primitive to bake into the framework. (It also evicted by model count, not VRAM, so a big model OOM'd while the cache still had free slots.)

What replaced it. The only consumer was apps/model-runner. From 1.15.8 it runs each inference in a child process (RuntimeApp._run_prediction_subprocess), mirroring the test path: the OS reclaims the entire CUDA context on process exit, which frees VRAM framework-agnostically (torch / TF / ONNX) with no accumulation. If a future GPU app needs "no VRAM left over between calls," use subprocess isolation — not a resurrected cache.

Historical context (git-archaeology). @bioengine.cached itself replaced the even-older @bioengine.multiplexed (→ ray.serve.multiplexed) in 0.11.22; that path leaked ~200 MB VRAM per evicted model because Ray's unload_model_lru never called empty_cache(). Both are gone now — the lineage is multiplexed (≤0.11.21) → cached (0.11.22–0.11.23) → subprocess isolation in the app, no framework cache (0.11.24+).

Worker service API

The BioEngineWorker registers as a Hypha service. Key methods:

MethodAdminDescription
get_statusOverall worker status
check_accessCheck caller permissions
list_apps✓List deployed applications
deploy_app✓Deploy an application from artifact; returns {application_id, artifact_id, version, version_source}
stop_app✓Stop a running application
get_app_statusStatus of specific application
upload_app✓Create/update application artifact
get_app_manifest✓Get manifest for an application
delete_app✓Delete an application artifact
run_code✓Run Python code in Ray task
list_datasetsAvailable datasets
request_admin_accessAsk to become an admin. Public; only registered with --enable-access-requests
get_admin_access_requestRead your own request. Same flag
list_access_requests✓All requests. Same flag
resolve_access_request✓grant / deny / clear a request. Same flag

The worker admin list does not honour a "*" entry — it is dropped at startup, so no admin-gated worker method authorizes an anonymous caller. App manifests may still use authorized_users: ['*']; that is a separate list. The users named in --admin-users cannot be removed on a running worker.

Dev image testing workflow

For deployment-side PRs (changes under bioengine/**, bioengine/cluster/**, bioengine/apps/builder.py, bioengine/_app/bootstrap.py, runtime_env transport, Ray client/server plumbing, Hypha service registration in the worker), validate on a live cluster before marking the PR ready. CI catches unit failures; it doesn't catch deployment topology issues. Validation must cover both modes — external-cluster and single-machine — because they exercise different code paths (the KubeRay-mode worker delegates to a remote Ray cluster carrying its own deps, the single-machine worker runs ray.init in-process). A change that's green on one mode can be broken on the other (e.g. an in-process ray.init exposes pip-resolved dep skew the kuberay pod hides).

Never validate on the production worker. Both modes run against the dedicated bioengine-devtest Hypha workspace, never bioimage-io. Changing a production worker — bioengine-worker-kth in namespace hypha, or the deNBI equivalent — needs explicit permission from the maintainer each time, even when this workflow would otherwise call for it. A dev image on the production worker exposes every real consumer to unmerged code, and it stays exposed until someone remembers to roll it back.

  1. Pick the next bioengine version (one above current pyproject.toml on main AND the latest published GHCR tag — bump from the higher) and append -devN. Example: next release 0.11.5 → ghcr.io/aicell-lab/bioengine-worker:0.11.5-dev1. Bump the suffix (-dev2, …) for each follow-up fix in the PR cycle.
  2. Build + push directly with docker buildx build --builder multiarch-builder --platform linux/amd64 -f docker/worker.Dockerfile -t ghcr.io/aicell-lab/bioengine-worker:<version>-devN --push . using GITHUB_PAT. Bypasses docker-publish-worker.yml (which enforces strictly-increasing canonical tags). Build single-arch only (--platform linux/amd64) — both KTH and the single-machine test host are amd64. Multi-arch (linux/amd64,linux/arm64) adds ~25 min of QEMU cross-compile to the dev cycle for zero validation value; the canonical CI build covers arm64 once the PR is merged.
  3. External-cluster validation (KTH): deploy a second worker side-by-side with production — a separate helm release (bioengine-worker-devtest) in namespace hypha running the dev tag, with --workspace=bioengine-devtest, that workspace's admin token, its own --client-id, and its own --workspace-dir. Point it at the same Ray head (ray://raycluster-kuberay-head-svc.ray-cluster.svc.cluster.local:10001) so it exercises the real cluster topology. Leave the production release alone. The dev tag lives only in the devtest release's values — never in the production values.yaml on kth-k8s main.

    Two constraints the shared Ray cluster imposes:

    • application_id is a cluster-wide Ray Serve name, not workspace-scoped. manager.py resolves it against serve_status.applications, which spans the whole Ray cluster, so a devtest deployment named model-runner would collide with production's. Suffix devtest deployments (model-runner-devtest) even though Hypha already isolates them by workspace.
    • Don't give the devtest worker GPU startup apps. The GPU nodes can't fit production's apps plus a second full set, so a devtest GPU app starves the production one. Use a CPU-only app, or agree in advance to stop the production app under test.

    Smoke-verify through the devtest worker: deploy an app, confirm RUNNING, call it over the Hypha proxy.

  4. Single-machine validation (local docker): run the dev image as docker run … python -m bioengine.worker --mode single-machine … against the same bioengine-devtest workspace. Deploy a small CPU-only @bioengine.app and confirm it reaches RUNNING and serves over the Hypha proxy. This catches ray.init / replica-startup regressions the external-cluster path doesn't exercise. The worker requires an admin token — worker.py rejects a merely read-write one with "Provided token does not have admin permissions" — so use the devtest workspace's admin token.
  5. Only after both modes are green: bump pyproject.toml to the canonical version in a separate commit, push, gh pr ready <PR>. CI publishes the canonical image.
  6. After merge + canonical image published:
    • Upgrade the production workers to the canonical tag — KTH and deNBI in the same session, per model_runner_kth_denbi_sync.md. This touches production, so get the maintainer's go-ahead first.
    • helm upgrade the devtest release to the canonical tag, or tear it down if no further dev cycle is imminent.
    • Delete every dev image tag from GHCR. The PAT has delete:packages.

The side-by-side devtest release replaced an older instruction to helm upgrade the production KTH worker to the dev tag. It has not yet been exercised end to end — the first run should confirm the two releases don't contend over the bioengine-pvc mount or the Ray cluster's resource pool.

Cleaning up test GHCR images

After a canonical release, list every dev tag and DELETE via GHCR API. Pattern:

curl -s -H "Authorization: Bearer $GITHUB_PAT" \
  "https://api.github.com/orgs/aicell-lab/packages/container/bioengine-worker/versions?per_page=100" \
  | python3 -c "import json,sys; [print(v['id'], t) for v in json.load(sys.stdin) for t in v.get('metadata',{}).get('container',{}).get('tags',[]) if t.startswith('<version>-dev')]"
# Then for each id:
curl -X DELETE -H "Authorization: Bearer $GITHUB_PAT" \
  "https://api.github.com/orgs/aicell-lab/packages/container/bioengine-worker/versions/<id>"

Don't blanket-delete: dev tags + :latest move-tags are intentional. Only purge what you explicitly created.

Dev app testing workflow

For app-side changes (anything under apps/<name>/** that changes the deployment's API surface or behaviour — e.g. a new method signature, changed return shape, a new dependency), validate on a live cluster by running the dev version SIDE-BY-SIDE with production, not by replacing it. The pattern:

Running scripts/upload_app.py — the two things that are not in --help

set -a; . ./.env; set +a    # from the repo root
python3 scripts/upload_app.py \
  -d apps/<name> --workspace bioimage-io --token "$BIOIMAGE_IO_TOKEN"

PYTHONPATH is no longer needed since PR #341 — the script appends the repo root to sys.path itself, and runs from any cwd. Before that it died with ModuleNotFoundError: No module named 'bioengine' even in a good checkout, because running a script puts the script's directory on sys.path and not the cwd. If you meet that error, you are on an older checkout; the workaround was PYTHONPATH="$(pwd -P)".

  1. --workspace bioimage-io is required. The flag is passed to connect_to_server, and the script then rebinds workspace = server.config.workspace from the live connection and publishes there. The workspace is encoded in the token, so the flag does not select a destination — it asserts one, and a mismatch is refused before anything is written: Current workspace encoded in the token (ws-user-…) does not match the specified workspace (bioimage-io). Omit it and you silently publish into whatever workspace the token carries, while reporting success. With $BIOIMAGE_IO_TOKEN that happens to be bioimage-io and no harm is done; with $HYPHA_TOKEN it is your personal workspace. An artifact version is immutable, so a rung burned that way is unrecoverable — which is why you pass the flag every time rather than reasoning about which token you have.
  2. Use --token "$BIOIMAGE_IO_TOKEN", not HYPHA_TOKEN. The script falls back to os.environ["HYPHA_TOKEN"] and then to an interactive login(), neither of which is what you want in a worktree. Together with (1) this is belt and braces: the wrong token alone fails loudly, and the missing flag alone is harmless with the right token — it takes both mistakes to publish to the wrong place quietly.

Then assert the workspace from the script's own log rather than trusting exit 0 — INFO - Connected to workspace bioimage-io as user …, followed by Editing existing artifact 'bioimage-io/<name>' (new version: X.Y.Z) and Successfully committed artifact … (version=X.Y.Z).

And verify the publish by CONTENT, not by the version string — sha256 each published file against the tree, with the previous version as a discriminating control, because equal hashes prove nothing if ?version= is being ignored:

curl -sL "https://hypha.aicell.io/bioimage-io/artifacts/<name>/files/<file>?version=<v>"

upload_app.py has no --version flag — the version comes from the manifest, so edit apps/<name>/manifest.yaml FIRST and upload second.

Always build the files list by directory glob, never by hand. The canonical scripts/upload_app.py calls create_file_list_from_directory(apps/<name>) (then strips __pycache__), so it picks up every file — including nested subpackages like model_cache/. A hand-curated files=[...] list passed straight to worker.upload_app silently omits whatever you forget, and this bites hard because upload_app commits the version without importing it — the import/introspection check only runs later at deploy_app. So a partial upload lands as a real, permanent artifact version and the failure surfaces one step too late (this is how a broken model-runner 1.15.6 missing model_cache/ got committed, forcing a skip to 1.15.7). Use scripts/upload_app.py, or replicate its create_file_list_from_directory glob in an ad-hoc script — don't enumerate files manually.

The manifest id is resolved workspace-wide, and apps list cannot tell you whether it is free. stage_artifact builds the id as <workspace>/<manifest id>, while apps live in <workspace>/applications, so the id can already belong to something that is not an app — a dataset, a model, a collection — which bioengine apps list never shows because it enumerates only the app collection. An upload onto such an id is refused at any manifest version by a worker at 0.16.142 or later (anything at or below 0.16.141 DELETES it instead, so check the worker's bioengine_version), with an error naming the artifact and telling you to change the id; the version-monotonicity error you may be expecting never appears, because that check only runs for an artifact the upload keeps. An artifact that is an app but sits outside the collection is migrated into it instead. An absent or unrecognised artifact type is refused as well, deliberately failing closed. Note that the artifact type for an app is application, while its manifest type is ray-serve — these are different fields and mistaking one for the other inverts the check.

  1. One artifact, many versions. bioimage-io/<app> holds every version the artifact has ever shipped. worker.upload_app appends a new committed version to the same artifact — it does not create a separate artifact per version. Never make a bioimage-io/<app>-v2 or bioimage-io/<app>-dev artifact; that fragments history and breaks the version-comparison stories consumers rely on.
  2. Distinct application_id for the dev deployment. application_id is a deployment identity (Ray Serve service name + Hypha service alias), not an artifact identity. Production keeps application_id="<app>" pinned to the current released version. The dev deployment uses a distinct id — the canonical name is application_id="<app>-dev" — pinned to the new version. Both come from the same artifact.

    # Production — pinned via the startup-app list in kth-k8s / denbi-k8s
    # values.yaml. Untouched during dev.
    {"artifact_id": "bioimage-io/model-runner",
     "application_id": "model-runner", "version": "1.14.0", ...}
    
    # Dev — deployed manually, side-by-side, same artifact, new version
    await worker.deploy_app(
        artifact_id="bioimage-io/model-runner",
        application_id="model-runner-dev",   # ← distinct
        version="1.15.0",                    # ← new
        hypha_token=os.environ["BIOIMAGE_IO_TOKEN"],
    )
  3. Registration. The dev app registers as bioimage-io/<app>-dev on Hypha. Consumers that call bioimage-io/<app> stay on the production version until you promote. Iterate against bioimage-io/<app>-dev directly.
  4. Iteration is a fresh upload + redeploy. For each dev iteration bump the apps/<app>/manifest.yaml version (the artifact rejects re-uploading the same version), worker.upload_app again, then worker.deploy_app(artifact_id, application_id="<app>-dev", version=<new>). The application_id is stable across iterations, so deploy_app updates the existing dev deployment in place rather than spawning a new random-name instance (see the application_id ≠ artifact_id warning in CLAUDE.md).
  5. Promoting to production. When the dev version is validated:
    • Bump the pin in kth-k8s/bioengine-worker/values.yaml (and denbi-k8s/…/values.yaml) to the new version. Commit + helm upgrade -f values.yaml. Per model_runner_kth_denbi_sync.md these two sites must ship in the same session.
    • After the production restart picks up the new version, worker.stop_app(application_id="<app>-dev") to reclaim cluster resources. The dev version stays in the artifact history — do NOT delete versions off the artifact.
  6. Cleanup on abandon. If the dev version is abandoned rather than promoted, still worker.stop_app("<app>-dev") to free the replica slot. Leave the version on the artifact; artifact-version deletes rewrite history and break consumers of worker.list_apps(...).artifact_versions.

Compare with the worker-side dev image workflow above: that pattern varies the image tag (0.11.5-dev1), this pattern varies the application_id (<app>-dev). Both let you drive a live-cluster smoke test without disturbing the running production surface, at different layers of the stack.

Cleanup rules

Test deployments

After testing an app is complete, stop and delete temporary apps on the live worker:

await worker.stop_app(application_id=app_id)   # stops the Ray Serve deployment
await worker.delete_app(artifact_id=app_id)    # deletes the Hypha artifact

Don't leave test/throwaway deployments on bioimage-io/bioengine-worker — they consume shared cluster resources.

Failed deployments

When a deploy fails, leave it in place while diagnosing — get_app_status(application_ids=[...]) → deployments.<name>.logs is the primary debug signal, and stop_app discards that history. Only after the fix is verified working: stop_app the failed instance (and delete_app if it was a throwaway test artifact; for production artifacts only stop_app — leave the artifact). Failed deploys consume Ray Serve retry capacity and clutter list_apps.

Orphan apps before helm upgrade

Ray Serve state is cluster-wide and survives worker pod restarts. A new worker pod, on boot, recovers every app it finds in serve.status() that's stamped with its workspace marker. Before any helm upgrade that changes the deployed app set: list current apps, identify orphans (apps not in the new bootstrap config), stop_app them. Otherwise the new pod adopts them and they reappear in list_apps after the upgrade, surprising everyone.

Hypha platform invariants

Re-resolve service handles per call, never cache

A long-captured server.get_service(...) handle expires mid-session with Method expired or not found — even when the service is healthy in the registry. Resolve a fresh handle on every method call from any long-lived client (browser tab, dashboard, agent that stays connected for more than a few minutes). Only use the connect-time resolution as a probe (set xxxAvailable for UI gating).

Why: Hypha proxies each call through the server. Each get_service(...) returns a current-valid proxy stub. Re-resolution is cheap (no network beyond the lookup) and immune to whatever caches its expiry.

Pin replica per session for stateful services

When a Hypha service maintains per-replica state on local disk (cellpose-finetuning training sessions in the actor's workdir, model checkpoints, downloaded artifact caches), the default mode:'random' / mode:'last' bouncing calls between replicas is silently wrong:

  • start_training(session_id=...) lands on worker A → A writes /home/.bioengine/sessions/<id>/...
  • get_training_status(session_id=...) lands on worker B → B sees nothing → "session not found"

Fix shape:

  1. First call: server.getService('<workspace>/<service>', {mode: 'random'}) → returns a handle whose .id is the concrete per-replica id.
  2. Stash that concrete id in sessionStorage keyed by service name.
  3. Subsequent calls: server.getService(<pinned-id>) — exact-id lookup, lands the same replica every time.
  4. Stale-pin recovery: if the call throws (replica gone — Ray Serve roll, worker eviction), clear the pin and let the next call re-resolve a fresh random replica. Don't get stuck on a dead pin.

sessionStorage per tab is the right storage scope: long-running training + polling stay on the same replica across page navigations; each tab gets its own pin; pin clears with the tab. localStorage is wrong (cross-tab + persists past worker death).

Apply to: services that maintain per-session disk state. Inference-only services with no per-session state are fine on default routing.

Resolve a service by HTTP, not by RPC listing — list_services can hang, the HTTP listing does not

api.list_services() against a busy workspace hangs. Measured against bioimage-io, with each figure attributed to the run it came from, because these are not one simultaneous triple:

run A, 09:26:42Z, one RPC connection, both arms in the same run:
  list_services("bioimage-io")                          TIMED OUT after 75s
  get_service(<exact id>) + get_status + get_app_status  OK in 0.7s
  control: get_service("<ws>/zzz-cannot-exist-0000:bioengine-worker")  REFUSED in 0.0s

run B, 09:50:35Z, ~24 min later, four arms in one run on one connection:
  control  bogus id                           REFUSED  in 0.01s
  exact id get_service + get_status            OK       in 0.02s   version 0.16.130
  RPC      list_services("bioimage-io")        ANSWERED in 0.05s,  25 entries
  HTTP     GET /bioimage-io/services           HTTP 200 in 2.844s, 25 entries

Read those two runs together before drawing a conclusion from either:

  • The hang is intermittent, and run B is what "it answered today" looks like. It has been seen to clear by itself in ~25 minutes. A run where the listing answers says nothing about the next one, so it is not evidence the bug is gone.
  • The HTTP listing is not the faster route, it is the route that does not hang. In run B it was 57× slower than the RPC listing (2.844s vs 0.05s) and has also been measured at 0.127s. Do not switch to it for latency; switch to it because a 75s hang has no upper bound and 2.8s does.

The defect is upstream, in hypha-rpc or hypha-server — not in the data and not in our workers. A worker whose management calls "stop answering" is very often a caller stuck in a listing while the worker is perfectly healthy: check by exact id before concluding anything about the worker, and read the pod's log with kubectl, which does not go through Hypha at all.

Resolve by HTTP, then call by exact id. Both halves matter, and both have a silent trap:

import json, os, urllib.request

def worker_service_id(workspace: str, match: str, server="https://hypha.aicell.io") -> str:
    """Resolve a worker's fully-qualified service id without enumerating by RPC."""
    # TRAP 3: send a token only if you HAVE one. A public workspace's listing answers 200
    # anonymously, and an invalid token answers 401 -- so an absent variable
    # works where a wrong one does not. A valid token scoped to another workspace
    # answered 200, so a 200 does not mean the token belongs to this workspace. An unconditional os.environ[...] raises KeyError.
    headers = {}
    token = os.environ.get("BIOIMAGE_IO_TOKEN") or os.environ.get("HYPHA_TOKEN")
    if token:
        headers["Authorization"] = f"Bearer {token}"
    req = urllib.request.Request(f"{server}/{workspace}/services", headers=headers)
    with urllib.request.urlopen(req, timeout=30) as resp:
        raw = resp.read()
    if not raw:                      # TRAP 1: 307 with a zero-byte body
        raise RuntimeError("empty body — follow redirects (curl needs -L); this is NOT 'no services'")
    ids = [s["id"] for s in json.loads(raw)]
    hits = [i for i in ids if i.endswith(":bioengine-worker") and match in i]
    if len(hits) != 1:               # never pick one silently; two sites is when guessing hurts
        raise RuntimeError(f"{len(hits)} workers match {match!r}: {hits}")
    return f"{workspace}/{hits[0]}"   # TRAP 2: HTTP ids are NOT workspace-prefixed
  • Trap 1 — the URL answers 307 with a zero-byte body. A caller that does not follow redirects sees an empty listing, not an error, so "no services" and "you forgot -L" are the same bytes. requests and urllib follow by default; curl does not.
  • Trap 2 — HTTP ids are not workspace-prefixed. The listing returns <client-id>:<name>; get_service wants <workspace>/<client-id>:<name>. Substituting one for the other fails with a not-found when your client is connected to a DIFFERENT workspace (from a bioimage-io connection the unprefixed id resolves). Always prefix.
  • Never hard-code a pod hash. A worker's client id contains its pod name, so an example citing one works today and dies at the next pod replacement — which is how a documented recipe rots into a false "service not found". Match on a stable substring (bioengine-worker-kth) and let the suffix do the rest.
  • Trap 3 — the token is optional, and a wrong one is worse than none. Measured 09:50:35Z against bioimage-io: no token at all → HTTP 200, 25 entries; a bogus token → HTTP 401; a valid workspace token → HTTP 200, 25 entries. So requiring a token makes the recipe unrunnable for a caller that holds none, or holds one scoped elsewhere, on a route that would have worked for them.
  • Two listings can disagree. Measured within one hour: the RPC listing returned 25 entries naming one worker pod's services while the HTTP listing returned 28 naming a different pod's — and ~24 minutes later both returned 25 and agreed. So a listing is not usable evidence that a service is absent, only an exact-id lookup is, and agreement on one run does not retire the problem. Asserting an absence from the RPC listing produced a false "production app is unreachable" report and an unnecessary escalation.

Whatever wraps this, keep a bogus-id control beside it: a lookup that succeeds proves nothing unless an id that cannot exist is shown to fail. A runnable four-arm harness in exactly this shape — control, exact id, RPC listing, HTTP listing, one run, one connection — is the right thing to paste beside any claim about this bug.

Writing issues and PR descriptions

Issues and PR bodies on this repo are standalone documentation. An issue is triaged by someone who didn't follow the conversation that produced it; a PR body is read months later by a maintainer who didn't follow the review. Assume the reader knows only how BioEngine is built.

The test every line has to pass: would this parse for someone who has never seen the conversation, the internal tracker, or the people involved? If it needs any of the three, cut it. The lists below are that test failing in the ways it usually fails — they're examples, not the rule.

Open with a lede a cold reader understands

The first paragraph is plain prose: what is broken (or what this changes), what breaks because of it, and roughly where. No log excerpts, no symbol names, no file.py:NNN. Name the user-visible consequence before the mechanism — "the worker restarts every 20 minutes and takes all three apps down with it" comes before "the liveness probe curls Hypha". If the first sentence contains a function or symbol name, rewrite it.

The title follows the same rule: one sentence, consequence first, readable on its own in a list.

Everything after the lede is for the reader who has already decided to act. Dense is fine — timelines, file.py:NNN, measured numbers, candidate fixes, caveats. Don't thin the evidence to keep it short; the two halves have different jobs. The lede buys a reader's attention, the detail is what makes the work actionable.

Issues

After the lede: how it was observed or reproduced, the evidence that localises it, and any candidate fix with its caveats. Attributing a finding to whoever made it is useful here.

PR descriptions

Include, after the lede:

  • Problem / motivation
  • Solution
  • New features or behavioural changes
  • Migration notes (if breaking)
  • Test plan
  • File-level summary

Do not include:

  • "Design choice — alternative considered …"
  • Pending follow-ups and after-merge / deployment steps — file those as issues instead
  • "Pairs with PR #N …" beyond a single Depends on #N line when there's a real ordering constraint
  • "Per the recent discussion …", "As we agreed", "After I tested X" — any direct reference to the conversation flow

"Validation still to come" notes are pending follow-ups too. While a PR is a draft they belong in a PR comment; the body's Test plan records what was validated, in its final state.

Every identifier must resolve for the reader

#N means a GitHub issue or PR in this repo and nothing else. Never write an identifier from a private tracker into a body — not bare, not zero-padded as #026, not annotated "(internal issue tracker)". The annotation is the tell: if you have to explain that the reader can't follow a reference, the reference doesn't belong there. The same goes for any link only you can open.

Closes / Fixes / Resolves is reserved for a GitHub issue in this repo that this PR really closes, written unpadded. Zero-padding silently disarms it, so it is not a safe way to write a reference you don't mean: Closes #026 arms nothing, Closes #26 closes whatever #26 turns out to be.

Don't quote or attribute people

State a requirement as a requirement, in your own words. Never quote a person — not from chat, not relayed, not copied out of an internal tracker — and don't name who asked for the change. These repos are public, so a quote publishes private words; and a design that is only defensible because someone asked for it has a hole in it that citing them hides. Attributing a finding in an issue is still fine (§Issues above); requirements and design rationale are not.

Close evidence must assert an invariant, not close-day state

An evidence item is re-run by whoever audits the close later, so it has to still mean something then. Assert the property the fix established, not the state of the world on the day you closed it:

instead ofwrite
a version pin — version: 0.27.5a floor — version >= 0.27.5
a message string — grep stderr for mutually exclusivethe exit status the guard produces
a line being present — export FOO is in the scriptabsence-or-replacement — export FOO is gone or the replacement is wired
a branch ref — git show origin/fix/my-branch:filethe landed state — origin/main contains the merge commit, and the twins agree on main

The branch-ref row is the one that catches people, because the repo deletes the branch for you. delete_branch_on_merge: true means every item naming a ref other than origin/main expires within hours of the merge — and a re-run then exits 128, which reads as a close that was false rather than as a ref that is gone. PR-readiness rows are where this bites hardest: the deliverable only ever lived on a branch, so naming the branch is the natural thing to write. So an item naming any ref other than origin/main must either be restated against origin/main once the merge lands, or carry a decay note saying the ref will be deleted. Measured 2026-11-05 across the 36 issues closed since this convention landed: 33 clean, two naming a deleted branch and exiting 128 on all six items between them — and the convention's text above had not mentioned refs at all, so the gap was in what it said rather than in anyone's discipline.

A snapshot assertion fails the moment later legitimate work moves past it, and a reviewer re-running it reads that failure as a close that was false. Four such items were measured on 2026-11-02: a version bumped ten times since, a config pin a later fix deliberately removed, a flag that got renamed, and a discrimination control that stopped discriminating because the cluster changed. None of the four closes was wrong; all four now exit non-zero.

Where an assertion genuinely cannot be made durable — a live cluster reading, an ambient condition a control depends on — say so on the item and name the decay you expect, so a future re-run recognises it instead of discovering it as a regression.

The same rule applies to an issue's acceptance criterion, and the commonest way it breaks there is a line number. A criterion that says manager.py:3184 is unrunnable by whoever reads it next: measured 2026-11-05, every line number in one row's criterion had already moved — manager.py:3184 was 3387, manager.py:1047/1052 were 1157/1162, and worker.py:1408 no longer carried the symbol at all. Name file + symbol + the mutation that must redden a test, never a line. A mutation survives renumbering because it is defined by behaviour rather than position, and it is also the only form that says what would have made the result RED.

Previously-merged PRs and existing issues that violate this style stay as-is; apply going forward only.

Finding a test that cannot fail — the discriminator, and why the obvious one does not work

A test that re-implements a production predicate inside its own assertion is true by construction, so it reads as coverage of exactly the property it cannot test. The known instance is test_the_private_package_dir_is_not_leaked_to_the_caller at 536a767^, which filtered underscore keys out itself and then asserted none were present — green no matter what get_export_status did.

"Look for a test that makes no call to the unit under test" does NOT find it. Measured 2026-11-05 with .dev/sweep-0233-instrument.py against that exact file: the no-prod-sourced-assert arm scores 0 of 11. The test calls training.write_export and training.get_export, so "calls no production symbol" is false for it — and the subject of its assertion is a value production code returned, so tightening the rule to "no production-sourced value in the asserted expression" scores 0 as well. The unit actually under test was get_export_status, named in the test's own name and never called. The rule has to be per-unit (does this test call the thing its name claims), not per-module (does it touch production at all) — and that mapping is a naming convention rather than a fact about the code, so it is not reliably mechanical.

What does find it: a comprehension carrying an if filter inside an assert — that is where a re-implemented predicate hides. On the pre-fix file that arm flags 1 of 11, the right one.

It is a candidate generator, not a verdict, and the false-positive rate is real. The same arm flags the fixed version of that same test, which is legitimate because the thing it filters is what get_export_status returned. Across one full sweep it produced 46 flags over 407 test functions, every one of which had to be read. Budget the reading; do not expect an automated answer.

The decisive check is a mutation, not a static rule. Delete or weaken the production guard and see whether any test reddens — a surviving mutant with an apparently-covering test is the signal, and the static arms only narrow where to look. See Close evidence must assert an invariant above for the same principle applied to evidence: name the mutation that must redden a test.

The repair has a shape, and it is three assertions rather than one. Assert on what the function returns, not on a value the test built. Add a positive control — assert that some field you expect really is present — so that the absence you care about reads as filtered rather than not-found; without it, a method that returned {} or raised would pass. And assert over a serialisation of the whole result (json.dumps) so the value cannot come back under a different key. The fixed form of the instance above does all three.

Pin the sweep to a ref, and assert what it opened before you read what it found. Scan git archive <ref> … into a temp dir rather than the working tree, and fail the run if the module count is not what you expect. A checkout a few commits behind presents fewer and shorter files, so the sweep returns a smaller answer that is internally consistent and wrong — measured 2026-11-05, the same sweep read 7 modules and a 943-line test_broker_core.py from a tree 3 commits behind, against 10 modules and 1758 lines on origin/main, and the stale numbers were briefly believed over the correct ones. For the same reason, a sweep tool that takes paths as arguments must refuse an empty argument list instead of reporting TOTAL 0 tests — a clean result from an instrument that opened nothing is the defect in this section applied to the search for it.

BioEngine skills

Skills live in ../bioimage.io/public/skills/bioengine/ (sibling repo). They're Markdown documents describing BioEngine to a user-facing AI agent, published at https://bioimage.io/skills/bioengine/SKILL.md.

bioimage.io/public/skills/bioengine/
├── SKILL.md                        # Main entry point — load first
├── references/
│   ├── manifest_reference.md
│   └── cli_reference.md
└── apps/                           # App-specific subskills
    ├── model-runner/
    ├── cellpose-finetuning.md
    └── cell-image-search.md

CLI lives in bioengine/cli/ in this repo. Install with pip install "bioengine[cli] @ git+https://github.com/aicell-lab/bioengine.git" or pip install -e ".[cli]" for development.

When skill content changes:

  • Main skill (SKILL.md) — update when the worker API, CLI commands, manifest format, or deployment rules change.
  • App subskills — update when the corresponding app's service API changes (parameters, status fields, export options, known pitfalls discovered during testing).
  • Adding a new app skill: create apps/<app-name>.md (or apps/<app-name>/ for multi-file) and add an entry to the app skills table in SKILL.md.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.