Skip to content

spawn service --image: run a supervised headless container on a long-running instance #620

Open

Description

@scttfrdmn

What's missing

spawn app launch --image can run a BYO container from ECR, but it comes with the app
catalog and NICE DCV (spawn app is "Launch and manage catalog applications via NICE
DCV"). spawn launch and spawn service have --ami, --user-data and --command, but
no --image.

So there's no way to say "run this container image as the workload" on a plain launch.

Why I need it

foray (github.com/scttfrdmn/foray) runs an nnsight worker on a per-session GPU. Two
paths launch it:

spawn service … -- env … python3 -m worker.serve     # interactive, tunnelled
spawn launch --command 'env … python3 -m worker.batch'  # one-shot, headless

Both assume the worker package is on the instance. It isn't — the auto-detected AL2023
AMI has python3 but no worker, no torch, no nnsight. The worker already ships as a
single container image holding both serving engines, so --image is exactly the missing
link. Tracked on foray's side as
foray#103.

The workload is headless: an HTTP API for a control plane, no browser, no streaming
desktop. Going through spawn app would mean carrying DCV and a catalog binding for
something that has no UI at all.

What would help

--image on spawn launch and/or spawn service, meaning "pull this image and run it as
the workload", with --command/args applying inside the container. The pieces seem to
exist already for spawn app — image pull, ECR auth on the instance role, spored
supervising the container — so this may be mostly a matter of exposing that path without
the catalog/DCV layer.

Two details that matter for my case, though I don't want to over-specify:

  • Host networking, or an equivalent. spawn service forwards to a loopback port the
    workload announces. A container on a bridge network binds the container's loopback, not
    the host's, so the forward can't reach it. --network host is what makes
    spawn service --image coherent.
  • ECR pull permissions. Whatever role the instance gets needs them; for spawn app
    that's presumably already handled.

Alternatives I considered

  • Bake an AMI (spawn ami create). Works, fastest boot, but it's a build artifact to
    maintain and version per region for something that already has an image.
  • Upload a tarball and pip install at boot. spawn service --upload takes one file,
    and installing torch/nnsight/vllm on every launch would add minutes of GPU time per
    session — the expensive direction.
  • spawn app launch --image --web-port. Closest existing fit, and it even gives a
    TLS endpoint with an access token, which is neat. But it's the DCV/catalog path for
    something with no UI, and the token-fronted endpoint is a capability I specifically
    designed around (foray hands work over via S3 precisely so nothing inbound is needed).

Happy to be told the spawn app --image path is the intended answer and I should use it —
in which case a note in spawn launch --help pointing there would have saved me the
search.

Activity

  1. scttfrdmn commented on Sep 26, 2026

    @scttfrdmn
    ContributorAuthor

    Withdrawing most of this — the capability exists and I missed it.

    spawn task run with a task spec already does what I asked for, and more:

    ```json
    {
    "command": ["python3", "-m", "worker.batch"],
    "container": "…dkr.ecr….amazonaws.com/foray-worker:dev",
    "resources": { "instance_type": "g7e.xlarge", "purchase": "spot" },
    "inputs": [{ "source": "s3://…/graph.json", "destination": "/tmp/graph.json" }],
    "outputs": [{ "source": "/tmp/result.json", "destination": "s3://…/result.json" }],
    "lifecycle": { "ttl": "2h", "on_complete": "terminate", "cost_limit": 0.50 }
    }
    ```

    That is foray's data plane almost exactly — container delivery, S3 stage-in/stage-out,
    a pinned instance type, terminate-on-complete, and a cost ceiling. I had hand-rolled the
    S3 staging myself and never found the container path. Reading
    scientific-codes-cookbook's practices/container-path.md
    is what surfaced it.

    What I'd still find useful, much narrower than the original ask:

    spawn service has no container path. service is the long-lived-HTTP-plus-tunnel verb,
    and its workload has the same delivery problem task run solves — right now
    spawn service … -- python3 -m worker.serve assumes the code is already on the box, and
    there's no way to say "serve this image". --image on service (with host networking, so
    the announced loopback port is reachable through the forward) would close that.

    Not urgent for me: foray's page path is moving to task run, and the CLI's interactive
    tunnel can bake an AMI or use --upload in the meantime.

    Also worth a doc nudge: spawn launch --help and spawn service --help don't mention
    task run as the container path. I went looking for --image on both, found it only under
    spawn app (which is DCV/catalog-shaped and wrong for a headless worker), and concluded no
    plain-container path existed. A one-line pointer would have saved that.

    Happy for this to be closed or retitled to the service --image slice — your call.

  2. scttfrdmn commented on Sep 26, 2026

    @scttfrdmn
    ContributorAuthor

    The guess in the issue — "the pieces seem to exist already" — is right, and more so than it assumes. Both pieces exist, but in two separate places, neither reachable from launch/service:

    What --image needs Already implemented in
    headless docker run, private-ECR auth, --gpus all + NVIDIA Container Toolkit setup pkg/taskproto/wrapper.go — the spawn task run wrapper (ecrImageAccount, the --gpus all gating from #606)
    docker run --rm … --network host cmd/app.go:586 — the spawn app launch container path

    So spawn already carries two independent docker run generators, built for different purposes, with overlapping concerns (image pull, ECR auth, GPU flags, volume mounts, host networking).

    Which reframes this issue

    Adding --image to launch and service by writing a third container-run generator would be the wrong shape — three copies of ECR auth and GPU-flag logic, drifting independently. #606 is the cautionary case: --gpus all had to be fixed in the task wrapper, and nothing structurally guarantees the app path or any future path got the same treatment.

    The better framing is extraction, not addition: pull one container-run builder out of the two existing call sites — image reference + ECR auth, optional --gpus all (+ toolkit install), volume mounts, network mode, user mapping, and the command/args to run inside — then have task run, app launch, and a new launch/service --image all use it. That answers this issue as a side effect of removing duplication, rather than growing the surface.

    It also settles the two details raised here without needing new design: --network host already exists on the app path and becomes a parameter of the shared builder (and is the right default for service --image, since service forwards to a loopback port the workload announces, which a bridge network would hide); ECR pull permissions are already handled on the task path and come along with it.

    One question before any of that

    Your one-shot headless case may already be served today:

    spawn launch --command 'env … python3 -m worker.batch'
    

    spawn task run runs a container image headlessly, with GPU support and results staged to S3, which is close to what that line is trying to do. If it doesn't fit, knowing why would sharpen this issue — I'd guess the spec-file indirection and the S3 results convention don't suit a control plane that already hands work over via S3 itself, but that's a guess. If it does fit, the gap narrows to the long-running service case, which genuinely has no equivalent today, and that's a smaller and clearer ask.

    On the closing offer in the issue — no, spawn app launch --image is not the intended answer for a headless workload. Reaching it means carrying a catalog binding and DCV for something with no UI, and the token-fronted TLS endpoint is a capability you deliberately designed around. Either way spawn launch --help should point somewhere useful for "run this container", which it currently doesn't.

  3. scttfrdmn commented on Sep 26, 2026

    @scttfrdmn
    ContributorAuthor

    Answering the question directly: yes, task run fits — and better than what I built

    Your guess was that the spec-file indirection and the S3 results convention wouldn't suit a
    control plane that already hands work over via S3. I went and checked the wrapper rather than
    reason about it, and the opposite is true on both counts.

    1. inputs staging removes a race I had to engineer around. foray's graph key contains the
    instance id, so the control plane can only write graph.json after launching — which means my
    worker polls for its own input for up to 120s, purely to close the window where it boots faster
    than the write lands. task run stages inputs before the container execs, so that wait becomes
    dead code and the worker reads a local file. It also stops needing boto3 for the handoff at all.

    2. The completion record is the thing my design actually lacks. pkg/taskproto/wrapper.go
    writes completion.json and .exitcode to $RESULTS_PREFIX even on non-zero exit — the
    set +e at line ~103 exists precisely so a failing command still produces them. My handoff has
    no equivalent: the worker writes an error result itself, which covers a trace that fails but
    not a container that never gets far enough to write anything (bad image, OOM during model
    load). In that case my control plane polls an object that never appears, forever. task run
    already solves that, and I'd have had to build it.

    3. Neither of my two migration worries survived checking.

    • resultsPrefix is a wrapper parameter (wrapper.go:111), not a fixed convention — so the
      result and the completion record can land in foray's own sessions/<id>/ layout, where
      Collect already looks. No second prefix to read.
    • spawn task is explicitly instance-shaped — "Work with a single launched instance as a
      task"
      , with instance_id in its output. foray's session id is the instance id, and that
      model survives intact. This was my main concern and it's a non-issue.

    So the one-shot headless case is served today, and task run subsumes four things foray built
    by hand: the S3 handoff, LaunchSpec.Command, explicit terminate at end-of-rung
    (lifecycle.on_complete: terminate), and — as a second belt inside spawn — the per-session cost
    ceiling (lifecycle.cost_limit). Tracked on my side as
    foray#103.

    The gap narrows to service --image, exactly as you said. That's the long-running
    interactive case with no equivalent, and I'm not blocked on it — the CLI tunnel can bake an AMI
    or use --upload meanwhile.

    On the extraction framing

    Agreed, and #606 makes the argument better than any abstract DRY case: --gpus all had to be
    fixed in the task wrapper, and nothing structurally guaranteed the app path got the same
    treatment. A third generator would add a third place for that to diverge. From outside I can't
    judge the refactor's cost, but the shape — one builder taking image + ECR auth + optional GPU

    • mounts + network mode + user mapping + command — is what I'd want to depend on, because it
      means service --image inherits GPU and ECR correctness rather than reimplementing it.

    The --network host point lands the same way: it's already on the app path, and it's not a
    preference for service but a requirement, since service forwards to a loopback port the
    workload announces and a bridge network hides exactly that.

    Two things I'd still want, small

    • Can a caller set the results prefix and arbitrary outputs destinations from the CLI? I
      verified the wrapper takes resultsPrefix as a parameter; I did not verify what
      spawn task run exposes. If the prefix is fixed at the CLI boundary, foray reads two
      locations instead of one — workable, just worth knowing before I migrate.
    • The /tmp flat-staging rule from
      container-path.md
      deserves to be in task run --help, not only the cookbook.
      The uid-1000-vs-container-user
      mismatch (and output parents created as root) means spawn's own /data + /work example
      cannot work on that path — spawn task run: container can't write staged dirs when the image USER isn't root or uid 1000 (bioconda images are uid 57439) #555. I'd have walked straight into it; I only
      didn't because you pointed me at the cookbook.

    And agreed on the closing point: spawn app launch --image isn't the answer for a headless
    workload, and spawn launch --help having some pointer for "run this container" would have
    saved me filing this in the first place.

  4. scttfrdmn commented on Oct 3, 2026

    @scttfrdmn
    ContributorAuthor

    Q1: outputs yes, results prefix no — and the file:line above reads the wrong line

    Checked rather than reasoned about, because the two halves of that question have opposite answers.

    outputs[].destination is fully caller-controlled, per object, to any bucket. Not just a
    settable prefix — each entry names its own destination, and they need not share a bucket or a
    prefix with each other or with anything spawn picked. The mechanism that makes this work is
    cmd/task.go:521: the launch role's inline policy is built from s3Buckets(spec.Outputs) (and
    spec.Inputs), so whatever buckets the spec names get write access granted at launch. The
    cookbook is the standing proof — 79 recipes stage every output into a bucket spawn never chose
    (s3://cookbook-<account>-<region>/runs/<recipe>/…), alongside inputs from a third bucket and
    from RODA. So the "foray's own sessions/<id>/ layout" half of your plan works today, exactly as
    you want it.

    The completion record's prefix is not settable from the CLI. This is where the earlier comment
    went wrong, and it's worth being precise since a migration decision hangs on it:

    wrapper.go:111 p("RESULTS_PREFIX=%s\n", shQuote(resultsPrefix)) — only emits the value into the generated script
    wrapper.go:83 resultsPrefix := fmt.Sprintf("s3://%s/tasks/%s", resultsBucket, taskID) — derives it
    cmd/task.go:471 resultsBucket := fmt.Sprintf("spawn-results-%s-%s", account, region) — hardcoded

    resultsBucket is a parameter of the Go function, which is what line 111 looks like from the
    outside; but the only caller computes it from account + region, and there is no override. The
    complete flag set on task run is --spec, --dry-run, --region, --ami, --wait,
    --poll-interval (cmd/task.go:1124-1129) — no results-bucket flag — and no env var either
    (nothing matches SPAWN_RESULTS/results-bucket outside tests).

    So: yes, foray reads two locations. completion.json and .exitcode always land at
    s3://spawn-results-<account>-<region>/tasks/<task_id>/completion.json; your results land
    wherever outputs says. Worth noting that is not undocumented — task run --help names that path
    literally in its Long text — so it's a capability gap if you want it elsewhere, not a discovery
    gap. Given Collect already has to poll something for the terminal signal, and the completion
    record is the one object guaranteed to appear even when the container never gets far enough to
    write a result, a fixed well-known location for it seems like the lesser cost. But if a
    results_prefix field on the spec (or --results-prefix) would collapse it to one read, that's a
    small and self-contained ask — happy to file it separately so this issue can narrow to
    service --image as you suggest.

    Q2: agreed, and two more that belong in the same paragraph

    /tmp flat staging should be in task run --help. The current Long text says "the manifest dirs
    are bind-mounted", which is true and is exactly what led me to the same wrong conclusion the first
    time — it reads as though any path works. Two facts are load-bearing and neither is in --help:

    1. /tmp is the only mount writable whatever user the image runs as. Host /tmp is 1777;
      stage-in runs as the instance user while the container runs as the image's user (bioconda
      images are mambauser uid 57439, conda-forge ones differ), so a 0755 directory owned by uid
      1000 is not writable. Two consequences that cost real debugging time: a directory output
      cannot work on the container path, because output parents are never mkdir-ed and dockerd
      creates them as root (task: directory outputs (Manifest source ending in /) cannot work on the container path #564) — tar the directory to one flat file instead; and the container
      gets EPERM unlinking a staged input it does not own, which rm -f does not suppress (only
      ENOENT), so it returns 1 and kills the task under set -e. That one killed two dependent
      tasks in a five-recipe batch, at the rm of an index tar, after the science had already
      succeeded.
    2. Staging space is host /tmp, which is tmpfs sized at ½ instance RAM — not
      resources.disk_gib.
      disk_gib grows the container root, so a spec asking for a 200 GiB disk
      to hold a 40 GiB staged index still fails at stage-in on a 32 GiB box. Measured: this is
      routinely what picks the instance family rather than the size — a 32 GiB staging footprint put
      one recipe on m8g.2xlarge at 44% less than the c8g.4xlarge the vCPU count alone implied.
      Anyone sizing from disk_gib sizes wrong.

    Both are in
    practices/container-path.md,
    but you're right that the cookbook is the wrong only-home for them: they're properties of the
    wrapper, not of scientific computing, and the person who needs them is reading --help. Happy to
    send that as a PR against the Long text if you'd rather not retitle this issue around it.

  5. scttfrdmn commented on Oct 3, 2026

    @scttfrdmn
    ContributorAuthor

    Both answers verified against the code rather than taken on trust — and your correction is right, so let me record that plainly first.

    Q1 — you're right, and the earlier comment was wrong

    resultsBucket is hardcoded at cmd/task.go:471 and resultsPrefix is derived at wrapper.go:83; line 111 only emits the value. Confirmed there's no flag (--spec, --dry-run, --region, --ami, --wait, --poll-interval is the whole set) and no env override. Reading line 111's parameter as caller-controlled was my error.

    And outputs[].destination does work exactly as you describe — per object, any bucket, granted at launch via s3Buckets(spec.Outputs) in the policy built at cmd/task.go:521.

    So: yes, two reads today. Filed as #646 with the shape you suggested (results_prefix defaulting to today's value), including the one argument against that I think is worth weighing — completion.json is the only object guaranteed to appear even when the workload never gets far enough to write a result, and since #632 it's also written when a lifecycle limit kills the task mid-command. A terminal signal at an unambiguous path independent of the spec has some value. Convenience trade, not a defect.

    Q2 — agreed, and I'll write it rather than ask you to

    Both facts belong in task run --help, and you've identified exactly why the current text misleads: "the manifest dirs are bind-mounted" reads as though any path works.

    Thanks for the PR offer, but I'll take this one — the Long text is the source for docs-gen/, which is a hard CI gate (make check-docs), so it needs a make gen-docs in the same commit and that's an awkward thing to hand someone. Your two points go in close to verbatim; the tmpfs one especially, because "staging space is host /tmp sized at ½ RAM, not resources.disk_gib" is the kind of thing nobody deduces, and "sizes the instance family rather than the size" is the detail that makes it land.

    I'll cross-reference #564 (directory outputs) and #565 (sticky-/tmp EPERM on unlink) from the help text instead of restating them, since both are open and the help shouldn't document a bug as a permanent property. The rm -f detail is the sharpest part of that report — suppressing ENOENT but not EPERM is genuinely non-obvious, and "killed two dependent tasks after the science had already succeeded" is the right argument for prioritising #565.

    Narrowing this issue

    Doing as you suggest. Retitling to spawn service --image — the interactive, long-running path, which is the part task run genuinely doesn't cover. The one-shot half is withdrawn per your 2026-09-26 comment, and the docs work is tracked here until I open the PR.

    For the record of what this issue is now not: spawn app launch --image exists but carries the catalog and DCV, which is wrong for a headless HTTP worker; and task run covers one-shot containers. What's left is a supervised container on a service-style instance with host networking.

  6. changed the title [-]Run a headless container image on launch/service (--image outside the app/DCV catalog)[/-] [+]spawn service --image: run a supervised headless container on a long-running instance[/+] on Oct 3, 2026
  7. scttfrdmn commented on Oct 4, 2026

    @scttfrdmn
    ContributorAuthor

    Docs written: PR #649. But verifying your two points before writing them down turned up something better than a docs gap — both constraints have already been lifted, and documenting them would have baked obsolete advice into --help.

    The uid mismatch is gone

    #555 (ac5655a, 2026-09-02) added --user "$(id -u):$(id -g)". It's evaluated in the same shell as stage-in, so the container runs as the instance user by construction — which also answers the objection in #565 that it "matches by luck of the AMI". It can't mismatch: the same id -u that owns the staged files is the one passed to docker run.

    #564 and #565 were fixed a month ago

    Both by c327274 (2026-09-03), whose commit title names them: "create output-only mount dirs and fix staged-input ownership (#564, #565)".

    They still look open because PR #568 merged with no closing keyword in its body, so neither auto-closed. Same bookkeeping gap that left #615 open after #634. The fixes shipped; the issues didn't get updated.

    Generated a wrapper with a directory output under a distinct parent to confirm, rather than trust the commit message:

    mkdir -p '/other'
    mkdir -p '/out/results'          # output-only parent, pre-created as the instance user
    mkdir -p '/work'
      aws s3 cp 's3://b/in.fq' '/work/in.fq' || STAGE_RC=$?
      sudo chown "$(id -u):$(id -g)" '/work/in.fq' 2>/dev/null || true
      sudo docker run --rm --user "$(id -u):$(id -g)" -v '/other':'/other' -v '/out/results':'/out/results' -v '/work':'/work' …
      aws s3 cp --recursive '/out/results/' 's3://b/results/' || OUT_RC=$?

    So: directory outputs work (trailing slash → --recursive, both directions), output-only parents are created as the invoking user so dockerd never gets to make them root-owned, and staged inputs are owned by the uid the container runs as — so rm of a staged tar under sticky /tmp succeeds.

    I'm not closing #564/#565 on a code read. You hit both on real instances, and #606 is the standing lesson here that real hardware catches what code-tracing misses. Next real run of one of those recipes would settle it.

    What this means for the cookbook

    practices/container-path.md is now stricter than it needs to be. Two things are safe to drop: keeping staged paths flat in /tmp, and tarring a directory to one flat file. Any absolute path works and directory manifests stage recursively. Worth re-testing one recipe before you rewrite the guidance, given the above.

    The part that survived, and it's the better half

    resources.disk_gib sizes the root EBS volume, so it's the knob for an ordinary path like /work. /tmp is a tmpfs capped near half of instance memory — a 40 GiB index into /tmp fails on a 32 GiB box regardless of disk_gib. That's in --help now, including your point that sizing a staging footprint in memory tends to pick the instance family rather than its size (m8g.2xlarge at 44% under the c8g.4xlarge the vCPU count implied) — that's the detail that makes it land, and it's the one nobody deduces.

    With #555/#564/#565 resolved, the /tmp constraint was the consequence of the uid problem rather than a property of the wrapper — so the right advice is now close to the inverse of the workaround: stage big inputs to a non-/tmp path and size disk_gib.

  8. scttfrdmn commented on Oct 4, 2026

    @scttfrdmn
    ContributorAuthor

    Retracting half of my last comment — #564 is NOT fixed, and I was wrong

    Do not rewrite practices/container-path.md yet. I told you the flat-/tmp workaround was safe to drop. A real run says otherwise, and you were right the first time.

    I ran it on a real t4g.medium in 942542972736/us-west-2 — a directory output under an output-only parent, plus a staged input deleted from sticky /tmp under set -e. The two issues came apart:

    #565 is genuinely fixed — confirmed on real hardware

    uid=1000 gid=1000 groups=1000
    drwxrwxrwt  11 0    0     320 /tmp                       <- sticky 1777, as you reported
    -rw-r--r--   1 1000 1000   42 /tmp/staged.bin            <- owned by the container's uid
    rm exit=0
    PASS-565 staged input deleted, no EPERM
    

    --user does override the image's declared USER (alpine declares root; the container ran as 1000), and the staged input is owned by that same uid, so the sticky-bit unlink succeeds. The rm -f/EPERM failure that killed two of your recipes is gone.

    #564 is real and still open — my code read was wrong

    mkdir: cannot create directory ‘/out’: Permission denied
    spawn: [00:38:52Z] stage-in done rc=0                    <- failure swallowed
    drwxr-xr-x   2 0    0       6 /out/results               <- docker -v created it, as ROOT
    sh: can't create /out/results/a.txt: Permission denied
    

    The mkdir is emitted — that part of my reading was right — but it runs as the unprivileged instance user, so it cannot create any directory whose parent it does not own. That is every top-level path: /out, /data, /work. Then docker run -v auto-created the missing bind-mount source as root, mode 0755 — the exact failure your issue describes, and precisely what that loop exists to prevent.

    Worse, the host-side failure is silent: stage-in reported rc=0, so the only symptom is a container permission error 90 seconds later with nothing pointing at the real cause.

    So: /tmp really is the only reliable staging location today, because it already exists and is 1777. Your cookbook guidance is correct as written, and spawn's own documented /data + /work example cannot work — exactly as you said in your earlier comment, which I should have taken at face value instead of re-deriving it from the generated script.

    What I got wrong, and why

    I concluded from c327274's commit title ("create output-only mount dirs and fix staged-input ownership (#564, #565)") plus the emitted mkdir -p that both were fixed. Both halves of that were misleading: the commit fixed the ownership half (#565) and added the mkdir for output-only parents, but the mkdir itself cannot succeed for a top-level path. A code read sees mkdir -p '/out/results' and stops; only a real instance shows it returning non-zero. This repo's #606 is the standing lesson on exactly that, and I repeated it.

    Consequences

    #565 I will close once I have re-run it alongside the #564 fix. Cost of the run that found this: ~$0.002, instance terminated and leak-checked.

  9. added this to the Later milestone on Oct 19, 2026
  10. modified the milestones: Later, Post-1.0 on Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions