diff --git a/deploy/README.md b/deploy/README.md index ced4ba5..480efbe 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -223,7 +223,9 @@ concurrency); adding a type is a new entry, not a code change. Concurrency is reactive live-admission by default — the count is derived from live host headroom, not configured, and the only knob is `reserve` percent ([ADR-0005](../doc/adr/0005-reactive-live-admission.md)); a GPU type opts into -device-count sizing with `mode: auto`. The Go listener is the authoritative +shared-GPU admission by declared VRAM with `mode: vram` +([ADR-0007](../doc/adr/0007-declared-job-vram.md)), and the older one-job-per-GPU +device-count sizing (`mode: auto`) stays valid. The Go listener is the authoritative parser ([ADR-0003](../doc/adr/0003-go-bash-boundary.md)). **Declaring job cores (cpu types, [ADR-0006](../doc/adr/0006-declared-job-cores.md)).** @@ -261,6 +263,42 @@ sudo systemctl start scaleset-listener@cpu `scaleset-admin sync-labels` tries an in-place update first and fails, naming these steps, when GitHub keeps the old labels. +**Declaring job VRAM (gpu types, [ADR-0007](../doc/adr/0007-declared-job-vram.md)).** +A gpu job under `mode: vram` tells the listener how much VRAM it uses with one +`runs-on` label, so several jobs can share one GPU: + +```yaml +runs-on: [self-hosted, linux, x64, gpu, vram-gb-4] # 4 GiB, shares a GPU +runs-on: [self-hosted, linux, x64, gpu, vram-gb-all] # the whole GPU +runs-on: [self-hosted, linux, x64, gpu] # no label: the whole GPU +``` + +The supported values are 1, 2, 4, 8, 16, 32, 64, 128 and `all`. Labels +are case-insensitive. When several labels are set, the largest wins. Jobs +without a VRAM label hold an entire GPU. Each GPU has a budget of `floor(vram_gib * (1 - reserve / 100))` +GiB (25 on an RTX 5090, 12 on an RTX 2000 Ada, at the default reserve of 20, +which is also the minimum). The listener starts a job on the lowest-index GPU +where what is running plus its declaration fits the budget and the live free +VRAM `nvidia-smi` reports, which also counts work the listener did not start, +is still at least `reserve`. A value above a GPU's budget takes that whole GPU. +The job receives `NVIDIA_VISIBLE_DEVICES=` and only its +`/dev/nvidia` node plus shared control nodes. List every GPU's device +node in the type's `devices` and configure the NVIDIA runtime as in the +sample. If the probe fails, admission falls back to one whole-GPU job per +previously detected GPU. Before the first successful reading, one unpinned +job can run at a time, and it retains exclusive access until exit. +The scale set must advertise the `vram-gb-*` labels. Recreate the gpu set +while idle as above (`--type gpu`). + +Nothing caps a job's real VRAM use (the fleet's GPUs have no MIG, and MPS or +HAMi limits only CUDA while Isaac/Kit render through Vulkan), shared jobs also +share the GPU's compute and run slower, and Isaac jobs need `pid: host` (#80). +The job history ledger records `gpu_index`, `vram_charged_gb` (after +clamping), `gpu_used_peak_mib` and `vram_peak_scope=whole_gpu` for pinned jobs. +The peak may include other jobs, display usage, and driver usage. To estimate +a job's own usage, sample it on an otherwise idle GPU. If sampling fails the +peak is empty. Unpinned fallback jobs record `vram_peak_scope=unavailable`. + ```sh sudo install -m 0644 deploy/runner-types.sample.yaml \ /etc/github-runner-listener/runner-types.yaml diff --git a/deploy/runner-types.sample.yaml b/deploy/runner-types.sample.yaml index da12f43..b1ff271 100644 --- a/deploy/runner-types.sample.yaml +++ b/deploy/runner-types.sample.yaml @@ -70,15 +70,27 @@ # not configured (ADR-0005, #163) # reserve: N reactive, keep N% free # (upward-only, minimum 10) -# mode: auto size from detected GPU -# count (#113; reactive -# GPU/VRAM is #164) +# mode: vram shared GPU: admit gpu +# jobs by the VRAM they +# declare (vram-gb-), +# several per GPU when +# they fit (ADR-0007, #180) +# reserve: N (vram) keep N% of each GPU free +# (upward-only, minimum 20) +# The older device-count mode (auto, one job per +# detected GPU, #113) stays valid. # There is no fixed operator count. runner_types: - # --- First concrete type: GPU (#113) ------------------------------------- - # Auto concurrency = detected GPU count (the listener runs nvidia-smi -L and - # sizes its worker pool to one slot per GPU). Devices are passed through + # --- First concrete type: GPU (#113, #180) ------------------------------- + # Shared-GPU concurrency (ADR-0007): a job declares the VRAM it needs with + # one runs-on label, vram-gb- or vram-gb-all; several jobs share a GPU + # while their declarations fit the GPU's VRAM less the reserve, and the + # live free VRAM (nvidia-smi, which also counts work the listener did not + # start) still keeps the reserve. A job with no vram-gb label holds the + # whole GPU, so undeclared jobs still run one per GPU. Nothing caps a job's + # real VRAM use: declare honestly, using the gpu_used_peak_mib the job + # history ledger records. Devices are passed through # precisely (no --privileged); the baseline container hardening + the ADR-0011 # approval gate keep unapproved untrusted code off this rootful device host. - name: gpu @@ -88,7 +100,9 @@ runner_types: scale_set: gpu # This host's runner group. Omitted = Default. # runner_group: ci- - labels: [self-hosted, linux, x64, gpu, cuda] + # Every vram-gb-* value a job may declare must be a scale-set label, since + # a job's runs-on labels must all be on the scale set. + labels: [self-hosted, linux, x64, gpu, cuda, vram-gb-1, vram-gb-2, vram-gb-4, vram-gb-8, vram-gb-16, vram-gb-32, vram-gb-64, vram-gb-128, vram-gb-all] # Self-built GPU image (#121): the CUDA/device stack layered on the SEC-5 # base (images/runner-gpu.Dockerfile -> images/runner-base.Dockerfile, whose # runner tarball passed verify_runner_tarball before being baked in). It @@ -99,6 +113,9 @@ runner_types: # and pin that digest instead. # actions-runner 2.338.2 image: ghcr.io/ycpss91255-lab/gpu-runner@sha256:2846d90a90e9e9bc7b4baecd856600445786d9bd2af63297ebd167910e467cd8 + # List every /dev/nvidia on the host. A pinned job receives the + # node matching its GPU minor, plus the shared control nodes. + # NVIDIA_VISIBLE_DEVICES is set to the GPU index. devices: - /dev/nvidia0 - /dev/nvidiactl @@ -108,8 +125,11 @@ runner_types: # sets no daemonless build_tool. Enabling the socket is ROOT-EQUIVALENT on # the host: enable only for trusted jobs (ADR-0011 approval gate). # docker_socket: /var/run/docker.sock + # If nvidia-smi fails, admit one whole-GPU job per known GPU, or one + # unpinned job total before the first good reading. concurrency: - mode: auto + mode: vram + reserve: 20 # --- A second type, shown to prove "two types, no code change" (#112) ----- # The CPU sample pins the published ghcr.io/ycpss91255-lab/runner-cpu image diff --git a/doc/adr/0007-declared-job-vram.md b/doc/adr/0007-declared-job-vram.md new file mode 100644 index 0000000..23193f8 --- /dev/null +++ b/doc/adr/0007-declared-job-vram.md @@ -0,0 +1,105 @@ +# 0007 — GPU jobs declare their VRAM + +> Serves: Invariant 2 — Defaults fall towards safety + +- **Status**: Accepted +- **Date**: 2026-11-29 + +## Context + +The gpu type sized its pool to the GPU count (`mode: auto`, #113): one job per +GPU, whatever the job needs. A lint or a small CUDA test then holds a 32 GB +RTX 5090 alone while other gpu jobs queue. #104 asked for reactive admission +on VRAM, and #80 for several runners on one GPU. + +Two facts shape the answer. Nothing on the fleet's GPUs can cap a job's VRAM: +the RTX 5090 and the RTX 2000 Ada have no MIG, and MPS or HAMi limit only CUDA +allocations, while Isaac Sim / Kit jobs render through Vulkan. And a VRAM +overshoot is not a slowdown, as CPU oversubscription is, but an out-of-memory +failure of whichever job allocates last. + +ADR-0006 already lets a cpu job declare its cores and RAM with a label. The +owner chose (2026-11-29, #180) the same shape for VRAM, backed by a live check +of the GPU. + +## Decision + +**A gpu job declares its VRAM with one runs-on label, the listener charges it +against a per-GPU budget, checks the GPU's live free VRAM, and pins the job to +the GPU it chose.** + +- **Mode.** A runner type opts in with `concurrency: mode: vram`. Its + `reserve` defaults to 20 and is upward-only with a floor of 20, stricter + than the cpu default and floor of 10. `mode: auto` stays valid. +- **Label.** `vram-gb-` (1, 2, 4 ... 64, 128) or `vram-gb-all`, matched + case-insensitively. When several labels are set, the largest wins. A job + without a VRAM label keeps the whole GPU. An N above a GPU's budget takes + that whole GPU. +- **Budget.** Per GPU, `floor(vram_total_gib * (1 - reserve / 100))`: + 25 GiB on an RTX 5090 (32607 MiB) and 12 GiB on an RTX 2000 Ada (16380 MiB) + at reserve 20. A zero budget admits no jobs. +- **Admission.** The listener picks the lowest-index GPU where the VRAM + committed to running jobs plus the job's declaration fits the budget AND the + live free VRAM (`nvidia-smi`) is still at least `reserve`. The live check + counts processes the listener did not start. One GPU hosts several jobs + while their declarations fit. While no GPU fits, admission waits the settle + window and re-probes (ADR-0005). +- **Charge.** VRAM is charged after the worker slot is acquired and the + context checked (the #177 ordering), and released when the job exits or on + any failure path before it starts. +- **Pinning.** The job is handed only the chosen GPU’s `/dev/nvidia` (plus + the shared control nodes such as `nvidiactl` and `nvidia-uvm`) and + `--env NVIDIA_VISIBLE_DEVICES=`. The probe reports both values. The + environment override is required because the GPU image defaults to + `NVIDIA_VISIBLE_DEVICES=all`. +- **Fail-safe.** If the probe fails, admission falls back to whole-GPU, one job + per GPU, over the last good GPU list: only a GPU with nothing committed takes + a job, charged its whole budget. With no reading ever, one job runs on the + host at a time, unpinned. It retains the host-wide reservation until exit, + including if the probe recovers. +- **Peak VRAM.** `provision-job.sh` samples the chosen GPU's used VRAM while + the job runs and writes `gpu_index`, `vram_charged_gb`, + `gpu_used_peak_mib` and `vram_peak_scope=whole_gpu` to the job's ledger + record (ADR-0002). The sampler leaves the peak empty if no sample succeeds. + Unpinned fallback jobs record `vram_peak_scope=unavailable`. +- **Boundary.** `listener/gpu-probe.sh` only reads + GPU index, device minor and memory counters via `nvidia-smi`. Go computes + budgets and selects devices (ADR-0003). + +## Alternatives + +- **Keep one job per GPU (`mode: auto`).** Safe, but wastes most of a large + GPU on small jobs; it remains available. +- **Live free VRAM alone, no declaration (#104's first shape).** VRAM is + allocated after a job starts, so a burst of jobs admitted against an idle + GPU would all fit the reading and then OOM together. Declarations charged + at dispatch close that window; the live check stays as the second guard. +- **Hard limits (MIG, MPS, HAMi).** No MIG on the fleet's GPUs, and MPS/HAMi + limit only CUDA, not Vulkan rendering. Rejected for now. +- **Per-process VRAM attribution for the peak.** `--query-compute-apps` misses + Vulkan/graphics contexts and container PIDs would need mapping to jobs, so + the recorded peak is the whole GPU's. + +## Consequences + +- Workflows own their VRAM declaration, and nothing enforces it: a job using + more than it declared can push a neighbour into OOM. The live reserve check + catches drift before the next job starts, not during a running one. +- Jobs on one GPU share its compute, so each runs slower than alone. +- Isaac Sim jobs still need `pid: host` (#80), which this does not provide. +- `gpu_used_peak_mib` is the peak for the whole GPU while the job ran. Even an + otherwise idle GPU can have driver or display usage. +- The vram-gb labels are part of the gpu scale set's routing contract, so + adding them means recreating each host's gpu set while it is idle + (ADR-0006). +- A spare runner with no assignment yet is charged the whole GPU, because its + labels are unknown until GitHub assigns a job. + +## References + +- #180 (this change); #104 (reactive GPU/VRAM admission); #80 (several + runners on one GPU); ADR-0005; ADR-0006; ADR-0002; ADR-0003. +- `listener/gpuprobe.go` (`CommandGPUProbe`, `jobVRAM`, `vramBudget`, + `pickGPU`, `gpuDevices`), `listener/listener.go` (`reconcile`, `admitGPU`, + `chargeGPU`, `releaseGPU`, `vramCapacity`), `listener/gpu-probe.sh`, + `listener/provision-job.sh`, `lib/runner-container.sh`. diff --git a/doc/changelog/CHANGELOG.md b/doc/changelog/CHANGELOG.md index cdd949e..fb2d45a 100644 --- a/doc/changelog/CHANGELOG.md +++ b/doc/changelog/CHANGELOG.md @@ -8,6 +8,17 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Added +- **GPU jobs declare their VRAM and share a GPU** (ADR-0007, #180): a gpu type + with `concurrency: mode: vram` admits a job that adds `vram-gb-` or + `vram-gb-all` to `runs-on` on the first GPU where the committed VRAM plus its + declaration fits `floor(vram_gib * (1 - reserve / 100))` and the live free VRAM is + still at least `reserve` (default and minimum 20). Jobs without a VRAM label hold + the whole GPU. Pinning uses the NVIDIA device minor and runtime index. If `nvidia-smi` fails, + the listener admits one whole-GPU job per previously detected GPU or one + unpinned job if no GPU has been detected. The ledger records the charged + GiB and the sampled whole-GPU peak for pinned jobs. The gpu sample uses + `mode: vram` and lists powers of two from `vram-gb-1` through + `vram-gb-128` and `vram-gb-all`. `mode: auto` remains available. - **CPU jobs declare RAM too** (ADR-0006 amended, #175): RAM defaults to 4 GB per declared core, and `ram-gb-` or `ram-gb-all` sets it. The listener charges both cores and GB against per-host budgets. The cpu sample type now diff --git a/justfile b/justfile index 2c4c2b8..f4a4177 100644 --- a/justfile +++ b/justfile @@ -21,7 +21,7 @@ TEST_TOOLS_IMAGE := env_var_or_default('TEST_TOOLS_IMAGE', 'ghcr.io/ycpss91255-l # recipe below. Override with COVERAGE_IMAGE=... if you want to pin a tag. COVERAGE_IMAGE := env_var_or_default('COVERAGE_IMAGE', 'kcov/kcov:latest') -SCRIPTS := 'script/install-deps.sh script/init.sh script/add-runner.sh script/remove-runner.sh script/status.sh script/update.sh script/uninstall.sh script/cleanup.sh script/schedule-cleanup.sh script/configure.sh script/set-labels.sh script/check-token.sh lib/common.sh lib/runner-layout.sh lib/runner-service.sh lib/runner-release.sh lib/runner-config.sh lib/runner-container.sh lib/runner-build.sh lib/runner-reaper.sh lib/runner-history.sh script/history.sh listener/provision-job.sh listener/reap.sh listener/host-probe.sh listener/docker-gc.sh lib/docker-gc.sh images/build-runner-image.sh script/lint-adr.sh script/fetch-bats.sh script/coverage-gate.sh script/lint-changelog.sh script/lint-readme-sync.sh script/lint-doc-citations.sh script/deploy-listener.sh script/teardown-listener.sh lib/listener-deploy.sh' +SCRIPTS := 'script/install-deps.sh script/init.sh script/add-runner.sh script/remove-runner.sh script/status.sh script/update.sh script/uninstall.sh script/cleanup.sh script/schedule-cleanup.sh script/configure.sh script/set-labels.sh script/check-token.sh lib/common.sh lib/runner-layout.sh lib/runner-service.sh lib/runner-release.sh lib/runner-config.sh lib/runner-container.sh lib/runner-build.sh lib/runner-reaper.sh lib/runner-history.sh script/history.sh listener/provision-job.sh listener/reap.sh listener/host-probe.sh listener/gpu-probe.sh listener/docker-gc.sh lib/docker-gc.sh images/build-runner-image.sh script/lint-adr.sh script/fetch-bats.sh script/coverage-gate.sh script/lint-changelog.sh script/lint-readme-sync.sh script/lint-doc-citations.sh script/deploy-listener.sh script/teardown-listener.sh lib/listener-deploy.sh' # Self-built runner-image Dockerfiles (#120/#121/#122), hadolint-checked. The # test-tools image ships hadolint, so this needs no extra dependency. @@ -250,6 +250,7 @@ install-listener: build-listener build-admin install -m 0755 listener/provision-job.sh "{{DESTDIR}}{{PREFIX}}/listener/provision-job.sh" install -m 0755 listener/reap.sh "{{DESTDIR}}{{PREFIX}}/listener/reap.sh" install -m 0755 listener/host-probe.sh "{{DESTDIR}}{{PREFIX}}/listener/host-probe.sh" + install -m 0755 listener/gpu-probe.sh "{{DESTDIR}}{{PREFIX}}/listener/gpu-probe.sh" install -m 0755 listener/docker-gc.sh "{{DESTDIR}}{{PREFIX}}/listener/docker-gc.sh" install -d "{{DESTDIR}}{{PREFIX}}/lib" install -m 0644 lib/*.sh "{{DESTDIR}}{{PREFIX}}/lib/" diff --git a/lib/runner-container.sh b/lib/runner-container.sh index b37b375..535f4c1 100644 --- a/lib/runner-container.sh +++ b/lib/runner-container.sh @@ -66,6 +66,13 @@ # dropping a runtime the operator asked for. : "${RUNNER_RUNTIME:=}" +# GPU pin (#180, ADR-0007): the index of the one GPU a shared-GPU (mode: vram) +# job was admitted to. The gpu image sets NVIDIA_VISIBLE_DEVICES=all, so the +# nvidia runtime would hand the job every GPU whatever --device says; a +# non-empty value adds `--env NVIDIA_VISIBLE_DEVICES=` to override it. +# EMPTY (every cpu job, and the GPU fail-safe) adds nothing. +: "${RUNNER_GPU:=}" + # The runner's home INSIDE the image: where the bundled actions/runner (run.sh, # config.sh, bin/) lives and where the job runs from. Both the self-built images # (images/runner-base.Dockerfile: WORKDIR /home/runner, USER runner) and the @@ -232,6 +239,12 @@ runner_container_run() { if [[ -n "${RUNNER_RUNTIME}" ]]; then runtime_args=(--runtime "${RUNNER_RUNTIME}") fi + # GPU pin: an engine flag on the argv (an index, not a secret), never part of + # the credential env-file below. + local -a gpu_args=() + if [[ -n "${RUNNER_GPU}" ]]; then + gpu_args=(--env "NVIDIA_VISIBLE_DEVICES=${RUNNER_GPU}") + fi # Deliver the single-use JIT credential to the container OFF the host argv # (#136, restores the ADR-0003 invariant). Splicing `--jitconfig "${encoded}"` # directly onto the host ` run ...` argv put the credential in the HOST @@ -313,6 +326,7 @@ runner_container_run() { "${socket_args[@]}" \ "${device_args[@]}" \ "${runtime_args[@]}" \ + "${gpu_args[@]}" \ "${id_args[@]}" \ --env-file "${env_file}" \ -w "${RUNNER_CONTAINER_HOME}" \ diff --git a/listener/README.md b/listener/README.md index e3c6b8d..6338c7b 100644 --- a/listener/README.md +++ b/listener/README.md @@ -132,6 +132,7 @@ docker run --rm -e GITHUB_CONFIG_URL -e GITHUB_TOKEN -e SCALE_SET_NAME \ | `RUNNER_IMAGE` | per-job container image (default `ghcr.io/actions/actions-runner:latest`) | | `AUTO_SIZE_DEVICES` | when set, size the pool to the detected device count (#103) instead of reactive live-admission | | `DEVICE_DETECT_CMD` | device-enumeration command for auto-sizing (default `nvidia-smi`, one device per output line) | +| `GPU_PROBE_CMD` | per-GPU index, device minor and VRAM reader for `mode: vram` (default installed `listener/gpu-probe.sh`; ADR-0007, #180) | | `HOST_PROBE_CMD` | host reader for reactive live-admission (default installed `listener/host-probe.sh`; ADR-0005, #163) | | `PROVISION_SCRIPT` | default installed `listener/provision-job.sh` | | `REAP_SCRIPT` | orphan-sweep entrypoint (default installed `listener/reap.sh`) | @@ -251,6 +252,9 @@ Pin the builder images by digest in production via `RUNNER_KANIKO_IMAGE` / record admission headroom. A batch that would breach the reserve parks and re-probes. The host reading is `host-probe.sh` (`HOST_PROBE_CMD`). +- **GPU VRAM admission (ADR-0007, #180):** `mode: vram` gates dispatch on + declared per-GPU VRAM and live reserve. Capacity snapshots estimate how + many GPUs can take another 1 GiB job, limited by free worker slots. - **Auto-sizing (#103):** with `AUTO_SIZE_DEVICES` (or `mode: auto`), the bound follows the detected device count instead of reactive admission; otherwise a sane default. The internal semaphore is only a goroutine safety ceiling. diff --git a/listener/cmd/scaleset-listener/main.go b/listener/cmd/scaleset-listener/main.go index d8070f0..ff1b866 100644 --- a/listener/cmd/scaleset-listener/main.go +++ b/listener/cmd/scaleset-listener/main.go @@ -89,11 +89,14 @@ func main() { // - the GPU/device detector (#103/#113): one line per device from the // enumeration command (default nvidia-smi -L), sizing a mode: auto type; // - the reactive host probe (ADR-0005, #163): live per-resource headroom - // from host-probe.sh, driving reactive live-admission for the default types. + // from host-probe.sh, driving reactive live-admission for the default types; + // - the GPU VRAM probe (#180): per-GPU memory from gpu-probe.sh, driving + // shared-GPU admission for a mode: vram type. // A missing tool falls back to the listener's conservative default bound. detector := listener.DeviceDetector(listener.CommandDeviceDetector{Name: envOr("DEVICE_DETECT_CMD", "nvidia-smi")}) hostProbe := listener.HostProbe(listener.CommandHostProbe{Name: resolveScriptPath(exe, "HOST_PROBE_CMD", "host-probe.sh")}) - deps := listener.InstanceDeps{Detector: detector, HostProbe: hostProbe} + gpuProbe := listener.GPUProbe(listener.CommandGPUProbe{Name: resolveScriptPath(exe, "GPU_PROBE_CMD", "gpu-probe.sh")}) + deps := listener.InstanceDeps{Detector: detector, HostProbe: hostProbe, GPUProbe: gpuProbe} // Per-runner-type config (#110/#112): when RUNNER_TYPES_CONFIG is set, the Go // loader is the authoritative parser (ADR-0003). The selected runner type @@ -142,9 +145,10 @@ func main() { reserve = inst.Config.Reserve // Carry exactly the seam this type resolved to: a device-sized (GPU) type // gets the detector and no probe; a reactive type gets the probe and no - // detector. + // detector; a vram type gets only the GPU probe. detector = inst.Config.DeviceDetector hostProbe = inst.Config.HostProbe + gpuProbe = inst.Config.GPUProbe log.Printf("runner type %q -> scale set %q in runner group %q (labels=%v)", inst.Name, inst.ScaleSet, inst.RunnerGroup, inst.Labels) } else { // The scale set's IDENTIFIER, not the runs-on target (see above). @@ -152,6 +156,8 @@ func main() { runnerGroup = envOr("RUNNER_GROUP", listener.DefaultRunnerGroup) image = envOr("RUNNER_IMAGE", "ghcr.io/actions/actions-runner:latest") // Reactive by default; AUTO_SIZE_DEVICES opts into device sizing instead. + // Shared-GPU admission needs a runner-type config (mode: vram). + gpuProbe = nil if os.Getenv("AUTO_SIZE_DEVICES") != "" { hostProbe = nil } else { @@ -201,6 +207,7 @@ func main() { Image: image, DeviceDetector: detector, HostProbe: hostProbe, + GPUProbe: gpuProbe, Reserve: reserve, Reaper: reaper, Devices: devices, diff --git a/listener/cmd/scaleset-listener/main_test.go b/listener/cmd/scaleset-listener/main_test.go index bba3bf0..b2e73cb 100644 --- a/listener/cmd/scaleset-listener/main_test.go +++ b/listener/cmd/scaleset-listener/main_test.go @@ -44,6 +44,7 @@ func TestResolveScriptPath(t *testing.T) { name string }{ {key: "HOST_PROBE_CMD", name: "host-probe.sh"}, + {key: "GPU_PROBE_CMD", name: "gpu-probe.sh"}, {key: "PROVISION_SCRIPT", name: "provision-job.sh"}, {key: "REAP_SCRIPT", name: "reap.sh"}, } { diff --git a/listener/config.go b/listener/config.go index b3ff64e..69b050f 100644 --- a/listener/config.go +++ b/listener/config.go @@ -76,16 +76,18 @@ type RunnerType struct { // reactive live-admission (ADR-0005, #163): the listener admits each job // against live per-resource headroom, keeping Reserve percent free, so the // concurrent-runner count emerges rather than being configured. A GPU type opts -// into device-count sizing with an explicit mode: auto (#164 covers reactive -// GPU/VRAM). +// into device-count sizing with an explicit mode: auto, or into shared-GPU +// admission by declared VRAM with mode: vram (#180, ADR-0007). type Concurrency struct { - // Mode is "auto" (size from a detected host device count -- GPU) or empty + // Mode is "auto" (size from a detected host device count -- GPU), "vram" + // (admit gpu jobs by the VRAM they declare, per GPU -- #180), or empty // (reactive CPU/RAM live-admission, the default). Mode string `yaml:"mode"` // Reserve is the percent of each resource to keep free under reactive - // admission. Zero means the default (defaultReservePercent); it is - // upward-only -- an operator raises it to leave more headroom for co-tenant - // work, and values 1..9 are rejected. + // admission. Zero means the default (defaultReservePercent, or + // defaultVRAMReservePercent for mode: vram); it is upward-only -- an + // operator raises it to leave more headroom for co-tenant work, and values + // below the mode's floor (10, or 20 for vram) are rejected. Reserve int `yaml:"reserve"` } @@ -106,14 +108,35 @@ func (c Concurrency) DeviceSized() bool { return c.Mode == concurrencyAuto } +// VRAMShared reports whether this type admits gpu jobs by the VRAM they +// declare, several to a GPU when their declarations fit (mode: vram, #180). +func (c Concurrency) VRAMShared() bool { + return c.Mode == concurrencyVRAM +} + +// reserveFloor is the lowest explicit Reserve this mode accepts: the stricter +// VRAM floor for mode: vram, the cpu/RAM floor otherwise. +func (c Concurrency) reserveFloor() int { + if c.VRAMShared() { + return minVRAMReservePercent + } + return minReservePercent +} + const ( concurrencyAuto = "auto" + concurrencyVRAM = "vram" // defaultReservePercent is the per-resource headroom kept free when a // reactive type does not set Reserve; minReservePercent is the floor an // explicit Reserve may not go below (Reserve is upward-only). defaultReservePercent = 10 minReservePercent = 10 + + // The same for VRAM under mode: vram (#180). Stricter than the cpu floor: + // a VRAM overshoot is an OOM, not a slowdown. + defaultVRAMReservePercent = 20 + minVRAMReservePercent = 20 ) // config is the on-disk YAML document: a single top-level runner_types list. @@ -259,15 +282,18 @@ func validateBuildTool(tool string) error { } // validateConcurrency checks the per-type concurrency block: the mode must be -// recognised (empty = reactive, or "auto" = device-sized), and an explicit -// reserve must be at or above the upward-only minimum. The removed "fixed" mode +// recognised (empty = reactive, "auto" = device-sized, or "vram" = shared-GPU +// admission), and an explicit reserve must be at or above the mode's +// upward-only minimum. The removed "fixed" mode // now fails closed, so a stale config surfaces a clear migration error. func validateConcurrency(c Concurrency) error { - if c.Mode != "" && c.Mode != concurrencyAuto { - return fmt.Errorf("unknown concurrency mode %q (want auto, or empty for reactive live-admission)", c.Mode) + switch c.Mode { + case "", concurrencyAuto, concurrencyVRAM: + default: + return fmt.Errorf("unknown concurrency mode %q (want auto, vram, or empty for reactive live-admission)", c.Mode) } - if c.Reserve != 0 && c.Reserve < minReservePercent { - return fmt.Errorf("concurrency reserve is upward-only, minimum %d (got %d)", minReservePercent, c.Reserve) + if floor := c.reserveFloor(); c.Reserve != 0 && c.Reserve < floor { + return fmt.Errorf("concurrency reserve is upward-only, minimum %d for mode %q (got %d)", floor, c.Mode, c.Reserve) } return nil } diff --git a/listener/config_test.go b/listener/config_test.go index d00f638..bb5cb85 100644 --- a/listener/config_test.go +++ b/listener/config_test.go @@ -1,6 +1,7 @@ package listener import ( + "fmt" "os" "path/filepath" "strings" @@ -392,3 +393,71 @@ func TestLoadConfigRejectsInvalidRunnerGroup(t *testing.T) { }) } } + +// mode: vram (#180) admits gpu jobs by the VRAM they declare. It loads, is +// neither device-sized nor reactive-cpu, and an omitted reserve stays 0 (New +// applies the 20% GPU default). +func TestLoadConfigConcurrencyVRAM(t *testing.T) { + path := writeConfig(t, ` +runner_types: + - name: gpu + scale_set: gpu + labels: [self-hosted, gpu, vram-gb-8, vram-gb-all] + image: ghcr.io/acme/gpu-runner@sha256:abc + runtime: nvidia + concurrency: + mode: vram +`) + types, err := LoadConfig(path) + if err != nil { + t.Fatalf("LoadConfig: %v", err) + } + c := types[0].Concurrency + if !c.VRAMShared() { + t.Error("mode: vram should be VRAM-shared") + } + if c.DeviceSized() { + t.Error("mode: vram must not be device-sized") + } + if c.Reserve != 0 { + t.Errorf("omitted reserve = %d, want 0 (New applies the GPU default)", c.Reserve) + } +} + +// The other modes are not VRAM-shared. +func TestOtherModesAreNotVRAMShared(t *testing.T) { + for _, c := range []Concurrency{{}, {Reserve: 30}, {Mode: "auto"}} { + if c.VRAMShared() { + t.Errorf("concurrency %+v reported VRAM-shared", c) + } + } +} + +// The GPU reserve is upward-only with a floor of 20 (a VRAM overshoot is an +// OOM, so it is stricter than the cpu floor of 10, which does not change). +func TestVRAMReserveFloor(t *testing.T) { + body := func(mode string, reserve int) string { + return fmt.Sprintf("runner_types:\n - name: t\n scale_set: s\n labels: [a]\n image: i@sha256:1\n concurrency:\n mode: %q\n reserve: %d\n", mode, reserve) + } + cases := []struct { + mode string + reserve int + wantErr bool + }{ + {"vram", 10, true}, + {"vram", 19, true}, + {"vram", 20, false}, + {"vram", 35, false}, + {"", 10, false}, + {"", 9, true}, + } + for _, c := range cases { + _, err := LoadConfig(writeConfig(t, body(c.mode, c.reserve))) + if (err != nil) != c.wantErr { + t.Errorf("mode %q reserve %d: err = %v, wantErr %v", c.mode, c.reserve, err, c.wantErr) + } + if err != nil && !strings.Contains(err.Error(), "reserve") { + t.Errorf("mode %q reserve %d: error %q should name the reserve", c.mode, c.reserve, err) + } + } +} diff --git a/listener/gpu-probe.sh b/listener/gpu-probe.sh new file mode 100755 index 0000000..1655f26 --- /dev/null +++ b/listener/gpu-probe.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# gpu-probe.sh -- per-GPU VRAM reading for shared-GPU admission (#180, ADR-0007). +# +# Emits one line per GPU on stdout for the Go listener's CommandGPUProbe, which +# derives each GPU's budget and runs the admission arithmetic. Host inspection +# is bash's job (ADR-0003); Go holds only the numbers. +# +# Contract (MiB, as nvidia-smi reports them): +# gpu +# +# A failing or missing nvidia-smi exits non-zero with nothing on stdout, so the +# Go side errors and falls back to whole-GPU admission. +set -euo pipefail + +csv=$(timeout -k 1s 4s nvidia-smi --query-gpu=index,minor_number,memory.total,memory.used,memory.free \ + --format=csv,noheader,nounits) + +while IFS=', ' read -r index minor total used free; do + [[ -n "${index}" ]] || continue + printf 'gpu %s %s %s %s %s\n' "${index}" "${minor}" "${total}" "${used}" "${free}" +done <<<"${csv}" diff --git a/listener/gpuprobe.go b/listener/gpuprobe.go new file mode 100644 index 0000000..14ac7bc --- /dev/null +++ b/listener/gpuprobe.go @@ -0,0 +1,186 @@ +package listener + +import ( + "context" + "fmt" + "math" + "os/exec" + "regexp" + "sort" + "strconv" + "strings" + "time" +) + +// GPU is one live reading of a single GPU's memory, in MiB, as nvidia-smi +// reports it (#180). Index is the nvidia-smi index used for +// NVIDIA_VISIBLE_DEVICES. Minor identifies the /dev/nvidia node. +type GPU struct { + Index int + Minor int + TotalMiB int64 + UsedMiB int64 + FreeMiB int64 +} + +// GPUProbe reads every GPU's live memory. Like HostProbe it is called once per +// admission decision. The production implementation is a thin shell-out; +// tests inject a stub. +type GPUProbe interface { + Probe(ctx context.Context) ([]GPU, error) +} + +// CommandGPUProbe is the production GPUProbe: it reads raw per-GPU figures from +// a thin shell-out (listener/gpu-probe.sh, ADR-0003 -- host inspection is +// bash's job) and does the math in Go. The command prints one line per GPU: +// +// gpu +// +// Any line Go cannot trust, or no GPU at all, is an error, so the listener +// falls back to whole-GPU admission rather than packing jobs on a misread +// budget. +type CommandGPUProbe struct { + // Name is the probe command; there is no default (wired to gpu-probe.sh). + Name string + // Args are its arguments. + Args []string + // Timeout bounds the probe call; defaults to 5s. + Timeout time.Duration +} + +// Probe runs the probe command once and returns the current per-GPU reading. +func (p CommandGPUProbe) Probe(ctx context.Context) ([]GPU, error) { + timeout := p.Timeout + if timeout <= 0 { + timeout = 5 * time.Second + } + cctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + cmd := exec.CommandContext(cctx, p.Name, p.Args...) + cmd.WaitDelay = time.Second + out, err := cmd.Output() + if err != nil { + return nil, err + } + var gpus []GPU + indices, minors := make(map[int]bool), make(map[int]bool) + for _, line := range strings.Split(string(out), "\n") { + if strings.TrimSpace(line) == "" { + continue + } + fields := strings.Fields(line) + if len(fields) != 6 || fields[0] != "gpu" { + return nil, fmt.Errorf("gpu-probe: malformed line %q", line) + } + var nums [5]int64 + for i, f := range fields[1:] { + v, perr := strconv.ParseInt(f, 10, 64) + if perr != nil { + return nil, fmt.Errorf("gpu-probe: non-numeric value %q in line %q", f, line) + } + nums[i] = v + } + index, minor := int(nums[0]), int(nums[1]) + total, used, free := nums[2], nums[3], nums[4] + if nums[0] < 0 || nums[1] < 0 || int64(index) != nums[0] || int64(minor) != nums[1] || + total <= 0 || used < 0 || used > total || free < 0 || free > total { + return nil, fmt.Errorf("gpu-probe: invalid GPU reading %q", line) + } + if indices[index] || minors[minor] { + return nil, fmt.Errorf("gpu-probe: duplicate GPU index or minor in line %q", line) + } + indices[index], minors[minor] = true, true + gpus = append(gpus, GPU{Index: index, Minor: minor, TotalMiB: total, UsedMiB: used, FreeMiB: free}) + } + if len(gpus) == 0 { + return nil, fmt.Errorf("gpu-probe: no GPUs reported") + } + return gpus, nil +} + +// vramLabelPrefix is the runs-on label a gpu job declares its VRAM with +// (#180): vram-gb- or vram-gb-all. +const vramLabelPrefix = "vram-gb-" + +// wholeGPU is the declaration of a job that holds a whole GPU: no vram-gb +// label, or vram-gb-all, before any GPU's budget clamps it. +const wholeGPU = int64(math.MaxInt32) + +// jobVRAM is the VRAM, in GiB, a job declares, clamped to budget. Unlike +// cpu-cores-*, NO declaration holds the whole budget: an undeclared gpu job +// keeps today's one-job-per-GPU behaviour. +func jobVRAM(labels []string, budget int) int { + var largest int + for _, label := range labels { + value, ok := strings.CutPrefix(strings.ToLower(label), vramLabelPrefix) + if !ok { + continue + } + switch value { + case "all": + return budget + case "1", "2", "4", "8", "16", "32", "64", "128": + gb, _ := strconv.Atoi(value) + largest = max(largest, gb) + } + } + if largest == 0 { + return budget + } + return min(largest, budget) +} + +// floatSlack absorbs rounding at a reserve boundary. +const floatSlack = 1e-9 + +// vramBudget is the whole GiB left after keeping the reserve free. +func vramBudget(g GPU, reserve float64) int { + return max(0, int(math.Floor(float64(g.TotalMiB)/1024*(1-reserve)+floatSlack))) +} + +// pickGPU returns the lowest-index GPU that can take a job declaring declared +// GiB (clamped to that GPU's budget) beside what is committed there, and the +// GiB to charge on it. A GPU fits when committed plus the clamped declaration +// stays within its budget AND its live free VRAM still keeps the reserve -- +// the live check counts processes the listener did not start. +func pickGPU(gpus []GPU, committed map[int]int64, declared int64, reserve float64) (gpu GPU, gb int64, ok bool) { + sorted := append([]GPU(nil), gpus...) + sort.Slice(sorted, func(i, j int) bool { return sorted[i].Index < sorted[j].Index }) + for _, g := range sorted { + budget := int64(vramBudget(g, reserve)) + cost := min(declared, budget) + if budget == 0 || committed[g.Index]+cost > budget { + continue + } + if float64(g.FreeMiB)/float64(g.TotalMiB)+floatSlack < reserve { + continue + } + return g, cost, true + } + return GPU{}, 0, false +} + +// gpuNodePattern matches a per-GPU device node (/dev/nvidia), as opposed to +// the shared control nodes (nvidiactl, nvidia-uvm, nvidia-modeset, ...). +var gpuNodePattern = regexp.MustCompile(`^/dev/nvidia([0-9]+)$`) + +// gpuDevices returns devices with every per-GPU node other than /dev/nvidia +// dropped, so a pinned job is handed only its own GPU (least privilege). An +// minor below zero (not pinned) returns the list unchanged. The input is never +// modified: it is the type's shared Config.Devices. +func gpuDevices(devices []string, minor int) []string { + if minor < 0 { + return devices + } + keep := strconv.Itoa(minor) + out := make([]string, 0, len(devices)) + for _, d := range devices { + hostPath, _, _ := strings.Cut(d, ":") + if m := gpuNodePattern.FindStringSubmatch(hostPath); m != nil && m[1] != keep { + continue + } + out = append(out, d) + } + return out +} diff --git a/listener/gpuprobe_test.go b/listener/gpuprobe_test.go new file mode 100644 index 0000000..2e69902 --- /dev/null +++ b/listener/gpuprobe_test.go @@ -0,0 +1,232 @@ +package listener + +import ( + "context" + "math" + "sync" + "testing" +) + +// stubGPUProbe injects a fixed per-GPU VRAM reading (or error), the GPUProbe +// analog of stubProbe. +type stubGPUProbe struct { + gpus []GPU + err error +} + +func (s stubGPUProbe) Probe(context.Context) ([]GPU, error) { return s.gpus, s.err } + +// switchGPUProbe returns whatever reading it currently holds; a test swaps it +// to make a probe that worked start failing (the fail-safe path). +type switchGPUProbe struct { + mu sync.Mutex + gpus []GPU + err error +} + +func (p *switchGPUProbe) Probe(context.Context) ([]GPU, error) { + p.mu.Lock() + defer p.mu.Unlock() + return p.gpus, p.err +} + +func (p *switchGPUProbe) set(gpus []GPU, err error) { + p.mu.Lock() + p.gpus, p.err = gpus, err + p.mu.Unlock() +} + +// Worked literals for the two GPU models in the fleet (#180): an RTX 5090 +// reports 32607 MiB, an RTX 2000 Ada 16380 MiB. +func rtx5090(index int, usedMiB int64) GPU { + return GPU{Index: index, Minor: index, TotalMiB: 32607, UsedMiB: usedMiB, FreeMiB: 32607 - usedMiB} +} + +func rtx2000(index int, usedMiB int64) GPU { + return GPU{Index: index, Minor: index, TotalMiB: 16380, UsedMiB: usedMiB, FreeMiB: 16380 - usedMiB} +} + +// CommandGPUProbe reads one `gpu ` +// line per GPU from a thin shell-out (listener/gpu-probe.sh, ADR-0003) and +// returns them as GPUs; Go does the math. +func TestCommandGPUProbeParsesPerGPULines(t *testing.T) { + stub := writeExec(t, "#!/usr/bin/env bash\nprintf 'gpu 0 4 32607 1024 31583\\ngpu 1 0 16380 0 16380\\n'\n") + gpus, err := CommandGPUProbe{Name: stub}.Probe(context.Background()) + if err != nil { + t.Fatalf("Probe error: %v", err) + } + want := []GPU{ + {Index: 0, Minor: 4, TotalMiB: 32607, UsedMiB: 1024, FreeMiB: 31583}, + {Index: 1, TotalMiB: 16380, UsedMiB: 0, FreeMiB: 16380}, + } + if len(gpus) != len(want) { + t.Fatalf("got %d GPUs, want %d: %+v", len(gpus), len(want), gpus) + } + for i := range want { + if gpus[i] != want[i] { + t.Errorf("gpus[%d] = %+v, want %+v", i, gpus[i], want[i]) + } + } +} + +// Anything the Go side cannot trust is an error, so the listener falls back to +// whole-GPU admission rather than packing jobs on a misread budget. +func TestCommandGPUProbeErrors(t *testing.T) { + cases := map[string]string{ + "command fails": "#!/usr/bin/env bash\nexit 1\n", + "no GPUs": "#!/usr/bin/env bash\nexit 0\n", + "too few fields": "#!/usr/bin/env bash\nprintf 'gpu 0 4 32607 1024\\n'\n", + "too many fields": "#!/usr/bin/env bash\nprintf 'gpu 0 4 32607 1024 31583 9\\n'\n", + "wrong tag": "#!/usr/bin/env bash\nprintf 'cpu 0 32607 1024 31583\\n'\n", + "non-numeric value": "#!/usr/bin/env bash\nprintf 'gpu 0 4 32607 N/A 31583\\n'\n", + "non-numeric index": "#!/usr/bin/env bash\nprintf 'gpu x 4 32607 1024 31583\\n'\n", + "zero total": "#!/usr/bin/env bash\nprintf 'gpu 0 4 0 0 0\\n'\n", + "negative total": "#!/usr/bin/env bash\nprintf 'gpu 0 4 -1 0 0\\n'\n", + "negative used": "#!/usr/bin/env bash\nprintf 'gpu 0 4 32607 -1 31583\\n'\n", + "oversized free": "#!/usr/bin/env bash\nprintf 'gpu 0 4 32607 0 40000\\n'\n", + "duplicate index": "#!/usr/bin/env bash\nprintf 'gpu 0 4 32607 0 32607\\ngpu 0 0 16380 0 16380\\n'\n", + "duplicate minor": "#!/usr/bin/env bash\nprintf 'gpu 0 4 32607 0 32607\\ngpu 1 4 16380 0 16380\\n'\n", + "one bad of two": "#!/usr/bin/env bash\nprintf 'gpu 0 4 32607 1024 31583\\ngpu 1 0 16380 x 16380\\n'\n", + } + for name, body := range cases { + t.Run(name, func(t *testing.T) { + stub := writeExec(t, body) + if gpus, err := (CommandGPUProbe{Name: stub}).Probe(context.Background()); err == nil { + t.Errorf("expected an error for %s, got %+v", name, gpus) + } + }) + } +} + +// A job declares its VRAM with one runs-on label (#180): vram-gb- or +// vram-gb-all. Unlike cpu-cores-*, NO declaration holds the whole GPU (today's +// one-job-per-GPU behaviour). "all" and any N above the budget are the budget, +// several labels take the largest, and matching is case-insensitive. +func TestJobVRAMFromLabels(t *testing.T) { + const budget = 25 + cases := []struct { + name string + labels []string + want int + }{ + {"no label holds the whole GPU", []string{"self-hosted", "linux", "x64", "gpu", "cuda"}, budget}, + {"declared GiB", []string{"gpu", "vram-gb-8"}, 8}, + {"case-insensitive", []string{"VRAM-GB-4"}, 4}, + {"all takes the budget", []string{"vram-gb-all"}, budget}, + {"above the budget clamps", []string{"vram-gb-64"}, budget}, + {"largest declaration wins", []string{"vram-gb-2", "vram-gb-8", "vram-gb-4"}, 8}, + {"zero is ignored", []string{"vram-gb-0"}, budget}, + {"garbage is ignored", []string{"vram-gb-eight", "vram-gb-", "vram-gb-2x"}, budget}, + {"unsupported sizes are ignored", []string{"vram-gb-3", "vram-gb-12", "vram-gb-2"}, 2}, + {"all wins over a numeric label", []string{"vram-gb-8", "VRAM-GB-ALL"}, budget}, + {"garbage beside a value", []string{"vram-gb-x", "vram-gb-2"}, 2}, + {"cpu size labels do not count", []string{"cpu-cores-4", "ram-gb-8"}, budget}, + } + for _, c := range cases { + if got := jobVRAM(c.labels, budget); got != c.want { + t.Errorf("%s: jobVRAM(%v) = %d, want %d", c.name, c.labels, got, c.want) + } + } +} + +// The VRAM budget of one GPU is its total less the reserve, floored to whole GiB. +func TestVRAMBudget(t *testing.T) { + cases := []struct { + name string + g GPU + reserve float64 + want int + }{ + {"RTX 5090 at 20%", rtx5090(0, 0), 0.20, 25}, // 31.84 GiB * 0.8 = 25.47 + {"RTX 2000 Ada at 20%", rtx2000(0, 0), 0.20, 12}, // 15.996 GiB * 0.8 = 12.79 + {"RTX 5090 at 30%", rtx5090(0, 0), 0.30, 22}, // 31.84 * 0.7 = 22.29 + {"exact 10 GiB at 20%", GPU{TotalMiB: 10240}, 0.20, 8}, + {"tiny GPU floors to zero", GPU{TotalMiB: 1024}, 0.20, 0}, + } + for _, c := range cases { + if got := vramBudget(c.g, c.reserve); got != c.want { + t.Errorf("%s: vramBudget = %d, want %d", c.name, got, c.want) + } + } +} + +// pickGPU returns the first GPU, by index, whose committed VRAM plus the job's +// declaration (clamped to that GPU's budget) fits the budget, and whose live +// free VRAM still keeps the reserve. It returns the GPU index and the GiB to +// charge there. +func TestPickGPU(t *testing.T) { + const reserve = 0.20 + whole := int64(math.MaxInt32) // what no label / vram-gb-all declares before clamping + cases := []struct { + name string + gpus []GPU + committed map[int]int64 + declared int64 + wantOK bool + wantGPU int + wantGB int64 + }{ + {"idle GPU admits a small job", []GPU{rtx5090(0, 0)}, nil, 8, true, 0, 8}, + {"several jobs share one GPU", []GPU{rtx5090(0, 0)}, map[int]int64{0: 16}, 8, true, 0, 8}, + {"the budget refuses the next", []GPU{rtx5090(0, 0)}, map[int]int64{0: 24}, 8, false, 0, 0}, + {"whole GPU on an idle GPU", []GPU{rtx5090(0, 0)}, nil, whole, true, 0, 25}, + {"whole GPU needs an empty GPU", []GPU{rtx5090(0, 0)}, map[int]int64{0: 1}, whole, false, 0, 0}, + {"live free below the reserve refuses", []GPU{rtx5090(0, 30000)}, nil, 1, false, 0, 0}, + {"live free at the reserve admits", []GPU{{Index: 0, TotalMiB: 10000, UsedMiB: 8000, FreeMiB: 2000}}, nil, 1, true, 0, 1}, + {"the second GPU takes what the first cannot", []GPU{rtx5090(0, 0), rtx5090(1, 0)}, map[int]int64{0: 20}, 8, true, 1, 8}, + {"a busy first GPU is skipped", []GPU{rtx5090(0, 30000), rtx5090(1, 0)}, nil, 4, true, 1, 4}, + {"lowest index first, whatever the order", []GPU{rtx5090(1, 0), rtx5090(0, 0)}, nil, 4, true, 0, 4}, + {"above one GPU's budget is that whole GPU", []GPU{rtx2000(0, 0), rtx5090(1, 0)}, nil, 16, true, 0, 12}, + {"falls through to the larger GPU", []GPU{rtx2000(0, 0), rtx5090(1, 0)}, map[int]int64{0: 4}, 16, true, 1, 16}, + {"zero budget refuses even a whole GPU job", []GPU{{TotalMiB: 1024, FreeMiB: 1024}}, nil, whole, false, 0, 0}, + {"no GPUs", nil, nil, 1, false, 0, 0}, + } + for _, c := range cases { + gpu, gb, ok := pickGPU(c.gpus, c.committed, c.declared, reserve) + if ok != c.wantOK { + t.Errorf("%s: ok = %v, want %v (gpu %d, gb %d)", c.name, ok, c.wantOK, gpu.Index, gb) + continue + } + if ok && (gpu.Index != c.wantGPU || gb != c.wantGB) { + t.Errorf("%s: pickGPU = (gpu %d, %d GiB), want (gpu %d, %d GiB)", c.name, gpu.Index, gb, c.wantGPU, c.wantGB) + } + } +} + +// A job pinned to one GPU gets only that GPU's /dev/nvidia node (least +// privilege); the shared control nodes and anything else stay. -1 (not pinned) +// leaves the list untouched. +func TestGPUDevicesKeepsOnlyTheChosenGPU(t *testing.T) { + devices := []string{ + "/dev/nvidia0", "/dev/nvidia1:/dev/nvidia1:r", "/dev/nvidia10:/dev/nvidia10:r", + "/dev/nvidiactl", "/dev/nvidia-uvm", "/dev/nvidia-uvm-tools", "/dev/nvidia-modeset", + "/dev/dri/card0", + } + got := gpuDevices(devices, 1) + want := []string{"/dev/nvidia1:/dev/nvidia1:r", "/dev/nvidiactl", "/dev/nvidia-uvm", "/dev/nvidia-uvm-tools", "/dev/nvidia-modeset", "/dev/dri/card0"} + if !equalStrings(got, want) { + t.Errorf("gpuDevices(.., 1) = %v, want %v", got, want) + } + if got := gpuDevices(devices, 0); !equalStrings(got, []string{"/dev/nvidia0", "/dev/nvidiactl", "/dev/nvidia-uvm", "/dev/nvidia-uvm-tools", "/dev/nvidia-modeset", "/dev/dri/card0"}) { + t.Errorf("gpuDevices(.., 0) = %v", got) + } + if got := gpuDevices(devices, -1); !equalStrings(got, devices) { + t.Errorf("gpuDevices(.., -1) = %v, want the list unchanged", got) + } + // The input must not be modified: it is the type's shared Config.Devices. + if devices[0] != "/dev/nvidia0" || len(devices) != 8 { + t.Errorf("gpuDevices modified its input: %v", devices) + } +} + +func equalStrings(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} diff --git a/listener/listener.go b/listener/listener.go index ed6ccad..c754ca7 100644 --- a/listener/listener.go +++ b/listener/listener.go @@ -99,6 +99,16 @@ type ProvisionRequest struct { DockerSocket string // JobWorkDir is the absolute same-path work folder for socket jobs. JobWorkDir string + // GPU is the index of the GPU a vram-mode job is pinned to (#180), or -1 + // when the job is not pinned (a cpu job, or the GPU fail-safe with no + // reading). A pinned job sees only this GPU (NVIDIA_VISIBLE_DEVICES and + // its device node alone). + GPU int + // GPUFallback reports an unpinned job in VRAM mode. + GPUFallback bool + // VRAMGB is the VRAM, in GiB, charged for the job on that GPU; 0 when + // not pinned. Recorded in the job's ledger record. + VRAMGB int64 } // Provisioner runs one ephemeral job in a throwaway container. The production @@ -164,8 +174,15 @@ type Config struct { // free. Mutually exclusive with DeviceDetector (a type is reactive OR // device-sized). Nil = no reactive gate. HostProbe HostProbe + // GPUProbe, when set, drives shared-GPU admission by declared VRAM (#180, + // ADR-0007): each job declares vram-gb- (none = the whole GPU) and is + // pinned to a GPU whose committed VRAM plus its declaration fits the + // budget and whose live free VRAM keeps Reserve. Takes precedence over + // HostProbe; a type sets one or the other. + GPUProbe GPUProbe // Reserve is the percent of each resource reactive admission keeps free. - // Zero falls back to defaultReservePercent. Ignored when HostProbe is nil. + // Zero falls back to defaultReservePercent (defaultVRAMReservePercent with + // a GPUProbe). Ignored when neither probe is set. Reserve int // SettleWindow is how long admission waits before re-probing when the host is // at/over the reserve line (near-line serialization, #163). Zero falls back @@ -248,6 +265,15 @@ type Listener struct { reserve float64 // fraction in [0,1]; the per-resource headroom kept free settle time.Duration + // Shared-GPU admission (#180): gpuProbe reads per-GPU VRAM; committedVRAM + // sums, per GPU index, the GiB running jobs were charged at dispatch, and + // lastGPUs is the latest good reading, the fail-safe's GPU list when the + // probe errors. All guarded by vramMu. + gpuProbe GPUProbe + vramMu sync.Mutex + committedVRAM map[int]int64 + lastGPUs []GPU + reapMu sync.Mutex // keeps new socket workdirs out of a sweep with an older tracked snapshot trackedMu sync.Mutex // guards tracked tracked map[string]int // canonical job id -> count of in-flight jobs sharing it (spared by the reaper, #105/#147) @@ -266,25 +292,33 @@ func New(session Session, minter JITConfigMinter, prov Provisioner, cfg Config) cfg.RequestTimeout = 30 * time.Second } reserve := float64(defaultReservePercent) / 100 + if cfg.GPUProbe != nil { + reserve = float64(defaultVRAMReservePercent) / 100 + } if cfg.Reserve > 0 { reserve = float64(cfg.Reserve) / 100 + if cfg.GPUProbe != nil { + reserve = max(reserve, float64(minVRAMReservePercent)/100) + } } settle := cfg.SettleWindow if settle <= 0 { settle = defaultSettleWindow } return &Listener{ - session: session, - minter: minter, - prov: prov, - cfg: cfg, - bound: bound, - sem: make(chan struct{}, bound), - probe: cfg.HostProbe, - reserve: reserve, - settle: settle, - tracked: make(map[string]int), - assigned: make(map[string]struct{}), + session: session, + minter: minter, + prov: prov, + cfg: cfg, + bound: bound, + sem: make(chan struct{}, bound), + probe: cfg.HostProbe, + gpuProbe: cfg.GPUProbe, + committedVRAM: make(map[int]int64), + reserve: reserve, + settle: settle, + tracked: make(map[string]int), + assigned: make(map[string]struct{}), } } @@ -293,8 +327,9 @@ func New(session Session, minter JITConfigMinter, prov Provisioner, cfg Config) // 1. an explicit Config.MaxRunners (> 0) -- an operator override always wins; // 2. otherwise the auto-detected host device count, when a DeviceDetector is // supplied and reports a positive count; -// 3. a reactive type (HostProbe set) sizes the SAFETY ceiling from the host CPU -// count -- the reactive gate is the real limiter, this only bounds goroutines; +// 3. a reactive type (HostProbe set) or a vram type (GPUProbe set, #180) sizes +// the SAFETY ceiling from the host CPU count -- the reactive or VRAM gate +// is the real limiter, this only bounds goroutines; // 4. otherwise defaultPoolBound -- the sane fallback when detection is absent, // errors, or reports a non-positive count (a zero bound would offer no // capacity and never run a job). @@ -307,7 +342,7 @@ func resolveBound(cfg Config) int { return n } } - if cfg.HostProbe != nil { + if cfg.HostProbe != nil || cfg.GPUProbe != nil { if n := runtime.NumCPU(); n > 0 { return n } @@ -475,8 +510,7 @@ func (l *Listener) reconcile(ctx context.Context, stats *scaleset.RunnerScaleSet labels = pending[0].RequestLabels } cost := jobSizeOf(labels) - // Wait for local reserve headroom before starting each runner. - if l.probe != nil && !l.admitOne(ctx, cost) { + if l.gpuProbe == nil && l.probe != nil && !l.admitOne(ctx, cost) { return nil } // Acquire a worker slot (back-pressure when the pool is full). Honour @@ -491,8 +525,22 @@ func (l *Listener) reconcile(ctx context.Context, stats *scaleset.RunnerScaleSet return nil } + gpu, minor, vramGB := -1, -1, int64(0) + if l.gpuProbe != nil { + var ok bool + gpu, minor, vramGB, ok = l.admitGPU(ctx, labels) + if !ok || ctx.Err() != nil { + <-l.sem + return nil + } + } + + // Charge only now, after the slot and the ctx check (#177), so a + // cancelled admission never holds a size or VRAM. var charged jobSize - if l.probe != nil { + if l.gpuProbe != nil { + l.chargeGPU(gpu, vramGB) + } else if l.probe != nil { charged = l.charge(cost) } @@ -511,10 +559,13 @@ func (l *Listener) reconcile(ctx context.Context, stats *scaleset.RunnerScaleSet RequestID: job.RunnerRequestID, Labels: job.RequestLabels, Image: l.cfg.Image, - Devices: l.cfg.Devices, + Devices: gpuDevices(l.cfg.Devices, minor), Runtime: l.cfg.Runtime, BuildTool: l.cfg.BuildTool, DockerSocket: l.cfg.DockerSocket, + GPU: gpu, + GPUFallback: l.gpuProbe != nil && gpu < 0, + VRAMGB: vramGB, }, } if l.cfg.DockerSocket != "" { @@ -522,6 +573,9 @@ func (l *Listener) reconcile(ctx context.Context, stats *scaleset.RunnerScaleSet if err != nil { <-l.sem l.release(charged) + if l.gpuProbe != nil { + l.releaseGPU(gpu, vramGB) + } if hasAssignment { pending = pending[1:] l.releaseAssignment(req.rawJobID) @@ -539,6 +593,9 @@ func (l *Listener) reconcile(ctx context.Context, stats *scaleset.RunnerScaleSet if err != nil { <-l.sem l.release(charged) + if l.gpuProbe != nil { + l.releaseGPU(gpu, vramGB) + } return err } req.EncodedJITConfig = jit @@ -553,6 +610,9 @@ func (l *Listener) reconcile(ctx context.Context, stats *scaleset.RunnerScaleSet defer l.inFlight.Add(-1) defer func() { <-l.sem }() defer l.release(charged) + if l.gpuProbe != nil { + defer l.releaseGPU(req.GPU, req.VRAMGB) + } if hasAssignment { defer l.releaseAssignment(req.rawJobID) } @@ -788,6 +848,9 @@ func (l *Listener) startReaper(ctx context.Context) (stop func()) { // is the pool bound less the local in-flight count (#102), clamped to [0, bound], // computed purely from local occupancy -- never the server's TotalAssignedJobs. func (l *Listener) capacityFor(inFlight int) int { + if l.gpuProbe != nil { + return l.vramCapacity(context.Background(), inFlight) + } if l.probe != nil { return l.reactiveCapacity(context.Background()) } @@ -857,3 +920,117 @@ func (l *Listener) release(charged jobSize) { func (l *Listener) committedSize() jobSize { return jobSize{cores: l.committedCores.Load(), gb: l.committedGB.Load()} } + +// admitGPU is the per-job shared-GPU gate (#180, ADR-0007): it blocks until a +// GPU can take the job's declared VRAM (pickGPU), re-probing after the settle +// window while none can, and returns the GPU index, device minor and GiB to +// charge there. It returns false only when the context is cancelled. +// +// It fails safe when the probe errors: whole-GPU, one job per GPU, over the +// last good GPU list (only a GPU with nothing committed takes a job, charged +// its whole budget). With no reading ever, it admits only while nothing is in +// flight, and the unpinned job holds the host until it exits. +// Run serializes dispatch, so only releases can change commitments between +// this selection and chargeGPU. +func (l *Listener) admitGPU(ctx context.Context, labels []string) (gpu, minor int, gb int64, ok bool) { + for { + want := int64(jobVRAM(labels, int(wholeGPU))) + gpus, err := l.gpuProbe.Probe(ctx) + l.vramMu.Lock() + if err == nil && len(gpus) > 0 { + l.lastGPUs = gpus + } else { + gpus, want = idleReadings(l.lastGPUs), wholeGPU + } + if l.committedVRAM[-1] == 0 { + switch { + case len(gpus) > 0: + selected, cost, fits := pickGPU(gpus, l.committedVRAM, want, l.reserve) + gpu, minor, gb, ok = selected.Index, selected.Minor, cost, fits + case l.inFlight.Load() == 0: + gpu, minor, ok = -1, -1, true + } + } + l.vramMu.Unlock() + if ok { + return gpu, minor, gb, true + } + select { + case <-time.After(l.settle): + case <-ctx.Done(): + return 0, 0, 0, false + } + } +} + +// idleReadings returns the GPUs with their stale live usage dropped, for the +// fail-safe: without a fresh reading only the committed VRAM is known. +func idleReadings(gpus []GPU) []GPU { + out := make([]GPU, len(gpus)) + for i, g := range gpus { + g.UsedMiB, g.FreeMiB = 0, g.TotalMiB + out[i] = g + } + return out +} + +// chargeGPU commits gb GiB on GPU gpu at dispatch. An unpinned job (gpu < 0) +// holds every GPU until it exits, even if the probe recovers. +func (l *Listener) chargeGPU(gpu int, gb int64) { + if gpu < 0 { + gb = 1 + } + l.vramMu.Lock() + l.committedVRAM[gpu] += gb + l.vramMu.Unlock() +} + +// releaseGPU returns a job's charged VRAM when it exits or fails to start. +func (l *Listener) releaseGPU(gpu int, gb int64) { + if gpu < 0 { + gb = 1 + } + l.vramMu.Lock() + if l.committedVRAM[gpu] -= gb; l.committedVRAM[gpu] <= 0 { + delete(l.committedVRAM, gpu) + } + l.vramMu.Unlock() +} + +// vramCommitted is the VRAM, in GiB, committed to running jobs on GPU gpu. +func (l *Listener) vramCommitted(gpu int) int64 { + l.vramMu.Lock() + defer l.vramMu.Unlock() + return l.committedVRAM[gpu] +} + +// vramCapacity estimates how many GPUs can take another minimum-size job, +// constrained by free worker slots and the same fallback as admission. +func (l *Listener) vramCapacity(ctx context.Context, inFlight int) int { + slots := l.bound - inFlight + if slots <= 0 { + return 0 + } + gpus, err := l.gpuProbe.Probe(ctx) + l.vramMu.Lock() + defer l.vramMu.Unlock() + want := int64(1) + if err != nil || len(gpus) == 0 { + gpus, want = idleReadings(l.lastGPUs), wholeGPU + } else { + l.lastGPUs = gpus + } + if l.committedVRAM[-1] != 0 { + return 0 + } + if len(gpus) == 0 && inFlight == 0 { + return 1 + } + n := 0 + for _, g := range gpus { + if _, _, ok := pickGPU([]GPU{g}, l.committedVRAM, want, l.reserve); ok { + n++ + } + } + return min(n, slots) +} diff --git a/listener/provision-job.sh b/listener/provision-job.sh index e2af1d0..28c3c07 100755 --- a/listener/provision-job.sh +++ b/listener/provision-job.sh @@ -24,6 +24,10 @@ # RUNNER_BUILD_TOOL daemonless image builder (kaniko/buildkit), #119 # RUNNER_DOCKER_SOCKET opt-in host Docker socket path (empty = off), #116 # RUNNER_JOB_WORKDIR absolute same-path work folder for socket jobs +# RUNNER_GPU index of the GPU a vram job is pinned to (#180); +# empty = not pinned +# RUNNER_VRAM_GB VRAM GiB charged, or "unknown" for an unpinned +# vram-mode job # # Each invocation runs EXACTLY ONE ephemeral job in a throwaway container that # is torn down on exit (--rm), then returns the in-container job's exit status @@ -101,11 +105,31 @@ fi # (.jitconfig.env) and removes it with a RETURN trap. That trap does # not run when this script is terminated mid-job (e.g. SIGTERM on a listener # restart), so the EXIT trap removes the env file too. -# Quote the cleanup arguments for the trap's second parse (#142). -printf -v purge_args '%q %q' "${runner_dir}" "${image}" -printf -v env_file_q '%q' "${runner_dir%/}.jitconfig.env" -# shellcheck disable=SC2064 # expand now using %q -trap "rm -f -- ${env_file_q}; runner_workdir_purge ${purge_args}" EXIT +# Peak VRAM sampler state (#180): a pinned job's peak is kept in a private +# sibling of the runner dir (never inside it: a socket job's runner dir is +# mounted into the job), removed with the rest on exit. +vram_peak_file="" +vram_sampler_pid="" +vram_sampler_stop() { + if [[ -n "${vram_sampler_pid}" ]]; then + kill "${vram_sampler_pid}" 2>/dev/null || : + wait "${vram_sampler_pid}" 2>/dev/null || : + vram_sampler_pid="" + fi +} +# shellcheck disable=SC2317 # called by the EXIT trap +cleanup() { + vram_sampler_stop + if [[ -n "${vram_peak_file}" ]]; then + rm -f -- "${vram_peak_file}" || : + fi + rm -f -- "${runner_dir%/}.jitconfig.env" + runner_workdir_purge "${runner_dir}" "${image}" +} +trap cleanup EXIT +if [[ -n "${RUNNER_GPU}" ]]; then + vram_peak_file=$(mktemp "${runner_dir%/}.vram.XXXXXX" 2>/dev/null) || vram_peak_file="" +fi if [[ -n "${RUNNER_DOCKER_SOCKET}" ]]; then chmod 0777 -- "${runner_dir}" fi @@ -131,10 +155,71 @@ fi # listener still gets the job's outcome via the exit status below and its own # structured per-job record (#131). provision-job's OWN diagnostics (FAIL lines) # remain on its stderr, unaffected by this redirect of the container run. +# +# A job pinned to a GPU (#180) has that GPU's used VRAM sampled while it runs +# (once before, every RUNNER_VRAM_SAMPLE_INTERVAL seconds, once after) and the +# peak recorded in its ledger record, so repos can choose vram-gb- from data. +# The peak is for the WHOLE GPU, not this job alone: nvidia-smi's per-process +# view misses Vulkan/graphics contexts (Isaac/Kit), and container PIDs would +# need mapping (ADR-0007). Best-effort: a failing nvidia-smi records no peak +# and never fails the job. +vram_sample() { + local used prev="" + used=$(timeout -k 1s 2s nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits \ + -i "${RUNNER_GPU}" 2>/dev/null) || return 0 + used=${used//[[:space:]]/} + [[ ${used} =~ ^[0-9]{1,9}$ ]] || return 0 + prev=$(cat -- "${vram_peak_file}" 2>/dev/null) || return 0 + if [[ -z "${prev}" ]] || (( 10#${used} > 10#${prev} )); then + { printf '%d\n' "$((10#${used}))" >"${vram_peak_file}"; } 2>/dev/null || : + fi + return 0 +} +if [[ -n "${vram_peak_file}" ]]; then + vram_sample + # The TERM trap kills the pending sleep too, so stopping the sampler leaves + # no orphaned sleep behind. + sampler_parent=$BASHPID + ( + sleep_pid="" + trap '[[ -z "${sleep_pid}" ]] || kill "${sleep_pid}" 2>/dev/null; exit 0' TERM + while kill -0 "${sampler_parent}" 2>/dev/null; do + sleep "${RUNNER_VRAM_SAMPLE_INTERVAL:-5}" & + sleep_pid=$! + wait "${sleep_pid}" || break + sleep_pid="" + if kill -0 "${sampler_parent}" 2>/dev/null; then + vram_sample + fi + done + if ! kill -0 "${sampler_parent}" 2>/dev/null; then + rm -f -- "${vram_peak_file}" + fi + ) /dev/null 2>&1 & + vram_sampler_pid=$! +fi status=0 runner_container_run_bounded "${runner_dir}" "${encoded}" "${image}" "${job_id}" \ >/dev/null 2>&1 || status=$? +gpu_fields=() +if [[ -n "${RUNNER_GPU}" ]]; then + peak="" + if [[ -n "${vram_peak_file}" ]]; then + vram_sampler_stop + vram_sample + peak=$(cat -- "${vram_peak_file}" 2>/dev/null) || peak="" + fi + gpu_fields=( + "gpu_index=${RUNNER_GPU}" + "vram_charged_gb=${RUNNER_VRAM_GB:-}" + "gpu_used_peak_mib=${peak}" + "vram_peak_scope=whole_gpu" + ) +elif [[ "${RUNNER_VRAM_GB:-}" == unknown ]]; then + gpu_fields=("gpu_used_peak_mib=" "vram_peak_scope=unavailable") +fi + # Capture-before-teardown hook (ADR-0002, #123/#154): write ONLY the trusted # ledger record (#124, secrets redacted; mirrored per-job) and run the # external-push seam (#128) -- BEST-EFFORT, so a capture failure is logged and @@ -154,7 +239,8 @@ runner_history_capture "${job_id}" "${status}" \ "trigger_repo=${RUNNER_TRIGGER_REPO:-}" \ "trigger_workflow=${RUNNER_TRIGGER_WORKFLOW:-}" \ "trigger_commit=${RUNNER_TRIGGER_COMMIT:-}" \ - "trigger_actor=${RUNNER_TRIGGER_ACTOR:-}" + "trigger_actor=${RUNNER_TRIGGER_ACTOR:-}" \ + "${gpu_fields[@]}" # Propagate the in-container job's exit status so the listener can surface a # failed job and tear its session down. The EXIT trap now removes the runner dir diff --git a/listener/provisioner.go b/listener/provisioner.go index ce64e8b..2d6fb2c 100644 --- a/listener/provisioner.go +++ b/listener/provisioner.go @@ -6,6 +6,7 @@ import ( "os" "os/exec" "path/filepath" + "strconv" "strings" ) @@ -44,6 +45,8 @@ type ContainerProvisioner struct { // RUNNER_BUILD_TOOL daemonless builder (kaniko/buildkit) or empty // RUNNER_DOCKER_SOCKET host Docker socket path or explicit empty (off) // RUNNER_JOB_WORKDIR absolute same-path work folder or explicit empty (off) +// RUNNER_GPU GPU index a vram job is pinned to, or explicit empty +// RUNNER_VRAM_GB VRAM GiB charged for the pinned job, "unknown" for unpinned VRAM mode, or empty // // The script's stdout/stderr are inherited so the container's job log streams // straight through, and a non-zero exit becomes a non-nil error so the listener @@ -89,8 +92,18 @@ func (c *ContainerProvisioner) Provision(ctx context.Context, req ProvisionReque if req.DockerSocket != "" { workDir = req.JobWorkDir } + // A job pinned to a GPU (#180) passes its index and charged VRAM; an + // unpinned one exports both EMPTY so nothing inherited pins it. + gpu, vram := "", "" + if req.VRAMGB > 0 && req.GPU >= 0 { + gpu, vram = strconv.Itoa(req.GPU), strconv.FormatInt(req.VRAMGB, 10) + } else if req.GPUFallback { + vram = "unknown" + } cmd.Env = append(os.Environ(), "RUNNER_DEVICES="+strings.Join(req.Devices, " "), + "RUNNER_GPU="+gpu, + "RUNNER_VRAM_GB="+vram, "RUNNER_RUNTIME="+req.Runtime, "RUNNER_BUILD_TOOL="+req.BuildTool, "RUNNER_DOCKER_SOCKET="+req.DockerSocket, diff --git a/listener/provisioner_test.go b/listener/provisioner_test.go index 51ee504..fd0d59b 100644 --- a/listener/provisioner_test.go +++ b/listener/provisioner_test.go @@ -287,3 +287,58 @@ func TestContainerProvisionerDockerSocketEnv(t *testing.T) { }) } } + +// A job pinned to a GPU (#180) passes the GPU index and its charged VRAM as +// explicit environment: RUNNER_GPU makes the bash seam set +// NVIDIA_VISIBLE_DEVICES to that GPU only, and RUNNER_VRAM_GB goes into the +// job's ledger record. +func TestContainerProvisionerPassesGPUAsEnv(t *testing.T) { + capFile := filepath.Join(t.TempDir(), "env") + script := writeScript(t, "#!/usr/bin/env bash\n"+ + "printf 'GPU=[%s] VRAM=[%s]\\n' \"${RUNNER_GPU-}\" \"${RUNNER_VRAM_GB-}\" > '"+capFile+"'\n") + p := &ContainerProvisioner{Script: script} + if err := p.Provision(context.Background(), ProvisionRequest{ + JobID: "job-gpu", Image: "img", EncodedJITConfig: "ENC", GPU: 1, VRAMGB: 8, + }); err != nil { + t.Fatalf("Provision: %v", err) + } + got, _ := os.ReadFile(capFile) + if strings.TrimSpace(string(got)) != "GPU=[1] VRAM=[8]" { + t.Errorf("GPU env = %q, want GPU=[1] VRAM=[8]", string(got)) + } +} + +// CPU jobs clear inherited GPU settings. An unpinned VRAM job clears the +// pin and tells the provisioner that its charge and peak are unavailable. +func TestContainerProvisionerUnpinnedGPUEnv(t *testing.T) { + t.Setenv("RUNNER_GPU", "7") + t.Setenv("RUNNER_VRAM_GB", "99") + capFile := filepath.Join(t.TempDir(), "env") + script := writeScript(t, "#!/usr/bin/env bash\n"+ + "printf 'GPU=[%s] VRAM=[%s]\\n' \"${RUNNER_GPU-}\" \"${RUNNER_VRAM_GB-}\" > '"+capFile+"'\n") + p := &ContainerProvisioner{Script: script} + for _, tc := range []struct { + name string + request ProvisionRequest + wantVRAM string + }{ + {name: "CPU", request: ProvisionRequest{GPU: -1}}, + {name: "zero-value CPU request"}, + {name: "VRAM fallback", request: ProvisionRequest{GPU: -1, GPUFallback: true}, wantVRAM: "unknown"}, + } { + t.Run(tc.name, func(t *testing.T) { + req := tc.request + req.JobID, req.Image, req.EncodedJITConfig = "job", "img", "ENC" + if err := p.Provision(context.Background(), req); err != nil { + t.Fatalf("Provision: %v", err) + } + got, err := os.ReadFile(capFile) + if err != nil { + t.Fatal(err) + } + if want := "GPU=[] VRAM=[" + tc.wantVRAM + "]"; strings.TrimSpace(string(got)) != want { + t.Errorf("GPU env = %q, want %q", got, want) + } + }) + } +} diff --git a/listener/reactive_test.go b/listener/reactive_test.go index 383d9aa..0263000 100644 --- a/listener/reactive_test.go +++ b/listener/reactive_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "runtime" "sync" "testing" "time" @@ -333,3 +334,459 @@ func TestDeclaredRAMBindsBeforeCores(t *testing.T) { t.Fatalf("job %s started although 32 of 57 GB were committed and it declares 32", id) } } + +// --- shared-GPU admission by declared VRAM (#180) --------------------------- + +// gpuHoldProvisioner records each ProvisionRequest as it starts and holds the +// job until release is closed, so a test can see which GPU jobs ran together +// and where each was pinned. +type gpuHoldProvisioner struct { + started chan ProvisionRequest + release chan struct{} + once sync.Once +} + +func (p *gpuHoldProvisioner) Provision(ctx context.Context, req ProvisionRequest) error { + p.started <- req + select { + case <-p.release: + case <-ctx.Done(): + } + return nil +} + +func (p *gpuHoldProvisioner) releaseAll() { p.once.Do(func() { close(p.release) }) } + +func (p *gpuHoldProvisioner) next(t *testing.T, within time.Duration) (ProvisionRequest, bool) { + t.Helper() + select { + case req := <-p.started: + return req, true + case <-time.After(within): + return ProvisionRequest{}, false + } +} + +// gpuDevicesAll is a type's device list on a two-GPU host. +var gpuDevicesAll = []string{"/dev/nvidia0", "/dev/nvidia1", "/dev/nvidiactl", "/dev/nvidia-uvm"} + +// heldGPUListen runs one message of assigned jobs against a vram-mode listener +// over the given GPUs (reserve 20) and returns the holding provisioner. +func heldGPUListen(t *testing.T, gpus []GPU, jobs ...*scaleset.JobAssigned) (*gpuHoldProvisioner, func()) { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + sess := &fakeSession{ + messages: []*scaleset.RunnerScaleSetMessage{msgWithAssigned(1, len(jobs), jobs...)}, + cancel: cancel, + } + prov := &gpuHoldProvisioner{started: make(chan ProvisionRequest, len(jobs)), release: make(chan struct{})} + l := New(sess, &recordingMinter{config: "jit"}, prov, Config{ + Image: "img-gpu", + Devices: gpuDevicesAll, + Runtime: "nvidia", + GPUProbe: stubGPUProbe{gpus: gpus}, + Reserve: 20, + SettleWindow: time.Millisecond, + MaxRunners: 100, + }) + done := make(chan struct{}) + go func() { _ = l.Listen(ctx); close(done) }() + return prov, func() { cancel(); prov.releaseAll(); <-done } +} + +// Jobs whose declarations fit share one GPU: 8 + 8 of a 25 GiB budget run +// together on GPU 0, and a further 16 waits. +func TestVRAMJobsShareOneGPU(t *testing.T) { + prov, stop := heldGPUListen(t, []GPU{rtx5090(0, 0)}, + assigned(1, "eight-a", "gpu", "vram-gb-8"), + assigned(2, "eight-b", "gpu", "vram-gb-8"), + assigned(3, "sixteen", "gpu", "vram-gb-16"), + ) + defer stop() + for i := 0; i < 2; i++ { + req, ok := prov.next(t, 2*time.Second) + if !ok { + t.Fatalf("only %d of the 2 vram-gb-8 jobs that fit a 25 GiB budget started", i) + } + if req.GPU != 0 || req.VRAMGB != 8 { + t.Errorf("job %s pinned to GPU %d with %d GiB, want GPU 0 with 8", req.JobID, req.GPU, req.VRAMGB) + } + } + if req, ok := prov.next(t, 150*time.Millisecond); ok { + t.Fatalf("job %s started although 16 of 25 GiB were committed and it declares 16", req.JobID) + } +} + +// A job with no vram-gb label holds the whole GPU, so a second one waits for +// the first to finish: today's one-job-per-GPU behaviour is the default. +func TestUndeclaredGPUJobsRunOnePerGPU(t *testing.T) { + prov, stop := heldGPUListen(t, []GPU{rtx5090(0, 0)}, + assigned(1, "plain-a", "self-hosted", "gpu"), + assigned(2, "plain-b", "self-hosted", "gpu"), + ) + defer stop() + req, ok := prov.next(t, 2*time.Second) + if !ok { + t.Fatal("the first undeclared GPU job never started on an idle GPU") + } + if req.VRAMGB != 25 { + t.Errorf("undeclared job charged %d GiB, want the whole 25 GiB budget", req.VRAMGB) + } + if req, ok := prov.next(t, 150*time.Millisecond); ok { + t.Fatalf("job %s started beside a whole-GPU job", req.JobID) + } + prov.releaseAll() + if _, ok := prov.next(t, 2*time.Second); !ok { + t.Fatal("the parked whole-GPU job never started after the first finished") + } +} + +// On a host with two GPUs, two whole-GPU jobs run at once, each pinned to its +// own GPU and handed only that GPU's device node. +func TestGPUJobsPinnedToDistinctGPUs(t *testing.T) { + prov, stop := heldGPUListen(t, []GPU{rtx5090(0, 0), rtx5090(1, 0)}, + assigned(1, "plain-a", "gpu"), + assigned(2, "plain-b", "gpu"), + ) + defer stop() + seen := map[int]ProvisionRequest{} + for i := 0; i < 2; i++ { + req, ok := prov.next(t, 2*time.Second) + if !ok { + t.Fatalf("only %d of 2 whole-GPU jobs started on a two-GPU host", i) + } + seen[req.GPU] = req + } + for _, idx := range []int{0, 1} { + req, ok := seen[idx] + if !ok { + t.Fatalf("no job pinned to GPU %d; got %v", idx, seen) + } + want := []string{fmt.Sprintf("/dev/nvidia%d", idx), "/dev/nvidiactl", "/dev/nvidia-uvm"} + if !equalStrings(req.Devices, want) { + t.Errorf("GPU %d job devices = %v, want %v", idx, req.Devices, want) + } + if req.Runtime != "nvidia" { + t.Errorf("GPU %d job runtime = %q, want nvidia", idx, req.Runtime) + } + } +} + +// A GPU listener re-probes after the settle window while no GPU has room, and +// admits once one does. +func TestAdmitGPUSettlesThenAdmits(t *testing.T) { + p := &countingGPUProbe{overUntil: 2, over: []GPU{rtx5090(0, 30000)}, ok: []GPU{rtx5090(0, 0)}} + l := New(&fakeSession{}, &recordingMinter{}, &recordingProvisioner{}, + Config{GPUProbe: p, Reserve: 20, SettleWindow: time.Millisecond, MaxRunners: 100}) + gpu, _, gb, ok := l.admitGPU(context.Background(), []string{"vram-gb-4"}) + if !ok || gpu != 0 || gb != 4 { + t.Fatalf("admitGPU = (%d, %d, %v), want (0, 4, true) once the GPU frees", gpu, gb, ok) + } + if p.callCount() < 3 { + t.Errorf("expected re-probing after settle, calls = %d, want >= 3", p.callCount()) + } +} + +// A context cancelled while no GPU has room unblocks admission. +func TestAdmitGPUCtxCancelUnblocks(t *testing.T) { + l := New(&fakeSession{}, &recordingMinter{}, &recordingProvisioner{}, + Config{GPUProbe: stubGPUProbe{gpus: []GPU{rtx5090(0, 30000)}}, Reserve: 20, SettleWindow: time.Hour, MaxRunners: 100}) + ctx, cancel := context.WithCancel(context.Background()) + go func() { + time.Sleep(10 * time.Millisecond) + cancel() + }() + if _, _, _, ok := l.admitGPU(ctx, []string{"vram-gb-1"}); ok { + t.Fatal("admitGPU must return false when cancelled while no GPU has room") + } +} + +type countingGPUProbe struct { + mu sync.Mutex + calls int + overUntil int + over, ok []GPU +} + +func (p *countingGPUProbe) Probe(context.Context) ([]GPU, error) { + p.mu.Lock() + defer p.mu.Unlock() + p.calls++ + if p.calls <= p.overUntil { + return p.over, nil + } + return p.ok, nil +} + +func (p *countingGPUProbe) callCount() int { + p.mu.Lock() + defer p.mu.Unlock() + return p.calls +} + +// VRAM is charged at dispatch and released when the job exits. +func TestVRAMChargedWhileRunningAndReleasedOnExit(t *testing.T) { + release := make(chan struct{}) + l := New(&fakeSession{}, &recordingMinter{config: "jit"}, &recordingProvisioner{block: release}, + Config{GPUProbe: stubGPUProbe{gpus: []GPU{rtx5090(0, 0)}}, Reserve: 20, MaxRunners: 10}) + stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1} + if err := l.reconcile(context.Background(), stats, []*scaleset.JobAssigned{assigned(1, "eight", "vram-gb-8")}); err != nil { + t.Fatal(err) + } + if got := l.vramCommitted(0); got != 8 { + t.Errorf("committed on GPU 0 while running = %d, want 8", got) + } + close(release) + l.wg.Wait() + if got := l.vramCommitted(0); got != 0 { + t.Errorf("committed on GPU 0 after exit = %d, want 0", got) + } +} + +// A mint failure after admission returns the job's VRAM. +func TestVRAMReleasedOnMintError(t *testing.T) { + boom := errors.New("mint failed") + minter := &recordingMinter{onMint: func(context.Context, string) error { return boom }} + l := New(&fakeSession{}, minter, &recordingProvisioner{}, + Config{GPUProbe: stubGPUProbe{gpus: []GPU{rtx5090(0, 0)}}, Reserve: 20, MaxRunners: 10}) + stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1} + if err := l.reconcile(context.Background(), stats, []*scaleset.JobAssigned{assigned(1, "eight", "vram-gb-8")}); !errors.Is(err, boom) { + t.Fatalf("reconcile error = %v, want the mint error", err) + } + if got := l.vramCommitted(0); got != 0 { + t.Errorf("committed on GPU 0 after a mint failure = %d, want 0", got) + } +} + +// A socket workdir failure after admission returns the job's VRAM. +func TestVRAMReleasedOnWorkdirError(t *testing.T) { + prov := &recordingProvisioner{} + l := New(&fakeSession{}, &recordingMinter{config: "jit"}, prov, Config{ + GPUProbe: stubGPUProbe{gpus: []GPU{rtx5090(0, 0)}}, Reserve: 20, MaxRunners: 10, + DockerSocket: "/var/run/docker.sock", OnJobErr: func(ProvisionRequest, error) {}, + }) + stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1} + if err := l.reconcile(context.Background(), stats, []*scaleset.JobAssigned{assigned(1, "bad/id", "vram-gb-8")}); err != nil { + t.Fatal(err) + } + if got := prov.jobCount(); got != 0 { + t.Fatalf("a job with an unsafe socket job id was provisioned (%d)", got) + } + if got := l.vramCommitted(0); got != 0 { + t.Errorf("committed on GPU 0 after a workdir failure = %d, want 0", got) + } +} + +// Cancellation while waiting for the slot or during the GPU probe never charges VRAM. +func TestReconcileCancellationDoesNotChargeVRAM(t *testing.T) { + for _, slotFull := range []bool{false, true} { + t.Run(fmt.Sprintf("slot full=%t", slotFull), func(t *testing.T) { + // The timeout only stops a wrong implementation from hanging the suite. + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + probe := cancelOnGPUProbe{cancel: cancel, gpus: []GPU{rtx5090(0, 0)}} + l := New(&fakeSession{}, &recordingMinter{config: "jit"}, &recordingProvisioner{}, + Config{GPUProbe: probe, Reserve: 20, MaxRunners: 1}) + if slotFull { + l.sem <- struct{}{} + } + stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1} + if err := l.reconcile(ctx, stats, []*scaleset.JobAssigned{assigned(1, "job", "vram-gb-all")}); err != nil { + t.Fatal(err) + } + if got := l.vramCommitted(0); got != 0 { + t.Errorf("committed after cancellation = %d, want 0", got) + } + }) + } +} + +type cancelOnGPUProbe struct { + cancel context.CancelFunc + gpus []GPU +} + +func (p cancelOnGPUProbe) Probe(context.Context) ([]GPU, error) { + p.cancel() + return p.gpus, nil +} + +// When the probe fails after a good reading, admission falls back to whole-GPU, +// one job per GPU, over the last known GPUs: only a GPU with nothing committed +// takes a job, and it is charged that GPU's whole budget. +func TestGPUAdmissionFailSafeUsesLastKnownGPUs(t *testing.T) { + p := &switchGPUProbe{gpus: []GPU{rtx5090(0, 0), rtx5090(1, 0)}} + l := New(&fakeSession{}, &recordingMinter{}, &recordingProvisioner{}, + Config{GPUProbe: p, Reserve: 20, SettleWindow: time.Millisecond, MaxRunners: 100}) + ctx := context.Background() + + gpu, _, gb, ok := l.admitGPU(ctx, []string{"vram-gb-4"}) + if !ok || gpu != 0 || gb != 4 { + t.Fatalf("healthy admitGPU = (%d, %d, %v), want (0, 4, true)", gpu, gb, ok) + } + l.chargeGPU(gpu, gb) + + p.set(nil, errors.New("nvidia-smi failed")) + gpu, _, gb, ok = l.admitGPU(ctx, []string{"vram-gb-1"}) + if !ok || gpu != 1 || gb != 25 { + t.Fatalf("fail-safe admitGPU = (%d, %d, %v), want (1, 25, true): the empty GPU, whole", gpu, gb, ok) + } + l.chargeGPU(gpu, gb) + + short, cancel := context.WithTimeout(ctx, 50*time.Millisecond) + defer cancel() + if gpu, _, gb, ok := l.admitGPU(short, []string{"vram-gb-1"}); ok { + t.Fatalf("fail-safe admitted (%d, %d) although every known GPU holds a job", gpu, gb) + } + + l.releaseGPU(0, 4) + gpu, _, gb, ok = l.admitGPU(ctx, []string{"vram-gb-1"}) + if !ok || gpu != 0 || gb != 25 { + t.Fatalf("fail-safe admitGPU after release = (%d, %d, %v), want (0, 25, true)", gpu, gb, ok) + } +} + +// With no GPU reading ever, admission runs one job at a time on the host, not +// pinned to any GPU (-1). +func TestGPUAdmissionFailSafeWithoutAnyReading(t *testing.T) { + l := New(&fakeSession{}, &recordingMinter{}, &recordingProvisioner{}, + Config{GPUProbe: stubGPUProbe{err: errors.New("no nvidia-smi")}, Reserve: 20, SettleWindow: time.Millisecond, MaxRunners: 100}) + gpu, _, _, ok := l.admitGPU(context.Background(), []string{"vram-gb-1"}) + if !ok || gpu != -1 { + t.Fatalf("admitGPU on an idle listener = (gpu %d, %v), want (-1, true)", gpu, ok) + } + l.inFlight.Store(1) + short, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + if _, _, _, ok := l.admitGPU(short, []string{"vram-gb-1"}); ok { + t.Fatal("admitGPU without any reading admitted a second job beside a running one") + } +} + +// An unpinned fail-safe job keeps the type's devices as configured and sets no +// GPU index or VRAM on the request. +func TestGPUFailSafeJobIsNotPinned(t *testing.T) { + prov := &recordingProvisioner{} + l := New(&fakeSession{}, &recordingMinter{config: "jit"}, prov, Config{ + Devices: gpuDevicesAll, GPUProbe: stubGPUProbe{err: errors.New("no nvidia-smi")}, Reserve: 20, MaxRunners: 10, + }) + stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1} + if err := l.reconcile(context.Background(), stats, []*scaleset.JobAssigned{assigned(1, "job", "gpu")}); err != nil { + t.Fatal(err) + } + l.wg.Wait() + if prov.jobCount() != 1 { + t.Fatalf("provisioned %d jobs, want 1", prov.jobCount()) + } + req := prov.jobs[0] + if req.GPU != -1 || req.VRAMGB != 0 || !req.GPUFallback { + t.Errorf("fail-safe request GPU=%d VRAMGB=%d, want -1 and 0", req.GPU, req.VRAMGB) + } + if !equalStrings(req.Devices, gpuDevicesAll) { + t.Errorf("fail-safe request devices = %v, want %v unchanged", req.Devices, gpuDevicesAll) + } +} + +// A cpu job is never pinned to a GPU: the request carries GPU -1 and no VRAM. +func TestCPUJobsAreNotPinnedToAGPU(t *testing.T) { + prov := &recordingProvisioner{} + l := New(&fakeSession{}, &recordingMinter{config: "jit"}, prov, Config{ + HostProbe: stubProbe{res: HostResources{Free: map[Resource]float64{ResourceCPU: 1, ResourceMem: 1}, Cores: 8, MemGB: 64}}, + MaxRunners: 10, + }) + stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1} + if err := l.reconcile(context.Background(), stats, []*scaleset.JobAssigned{assigned(1, "cpu-job", "cpu")}); err != nil { + t.Fatal(err) + } + l.wg.Wait() + if prov.jobCount() != 1 { + t.Fatalf("provisioned %d jobs, want 1", prov.jobCount()) + } + if req := prov.jobs[0]; req.GPU != -1 || req.VRAMGB != 0 { + t.Errorf("cpu request GPU=%d VRAMGB=%d, want -1 and 0", req.GPU, req.VRAMGB) + } +} + +// The snapshot capacity of a vram type is how many GPUs can still take a 1 GiB +// job, capped by the bound; a probe failure reports a conservative 1. +func TestVRAMCapacity(t *testing.T) { + newL := func(p GPUProbe, bound int) *Listener { + return New(&fakeSession{}, &recordingMinter{}, &recordingProvisioner{}, + Config{GPUProbe: p, Reserve: 20, MaxRunners: bound}) + } + two := []GPU{rtx5090(0, 0), rtx5090(1, 0)} + if got := newL(stubGPUProbe{gpus: two}, 100).capacityFor(0); got != 2 { + t.Errorf("two idle GPUs: capacity = %d, want 2", got) + } + full := newL(stubGPUProbe{gpus: two}, 100) + full.chargeGPU(0, 25) + if got := full.capacityFor(1); got != 1 { + t.Errorf("one GPU full: capacity = %d, want 1", got) + } + if got := newL(stubGPUProbe{gpus: two}, 1).capacityFor(0); got != 1 { + t.Errorf("bound 1: capacity = %d, want 1", got) + } + busy := []GPU{rtx5090(0, 30000), rtx5090(1, 30000)} + if got := newL(stubGPUProbe{gpus: busy}, 100).capacityFor(0); got != 0 { + t.Errorf("both GPUs below the live reserve: capacity = %d, want 0", got) + } + if got := newL(stubGPUProbe{err: errors.New("boom")}, 100).capacityFor(0); got != 1 { + t.Errorf("probe failure: capacity = %d, want 1 (conservative)", got) + } +} + +// A vram type keeps 20% of each GPU free unless it asks for more, and its +// goroutine safety ceiling is the host CPU count (the VRAM gate is the real +// limiter, as the cpu gate is for a reactive type). +func TestVRAMModeReserveAndBoundDefaults(t *testing.T) { + l := New(nil, nil, nil, Config{GPUProbe: stubGPUProbe{gpus: []GPU{rtx5090(0, 0)}}}) + if !approxEqual(l.reserve, 0.20) { + t.Errorf("default vram reserve = %v, want 0.20", l.reserve) + } + if l.bound != runtime.NumCPU() { + t.Errorf("vram bound = %d, want runtime.NumCPU() = %d", l.bound, runtime.NumCPU()) + } + l = New(nil, nil, nil, Config{GPUProbe: stubGPUProbe{}, Reserve: 30}) + if !approxEqual(l.reserve, 0.30) { + t.Errorf("explicit vram reserve = %v, want 0.30", l.reserve) + } +} + +func TestGPUFailSafeRecoveryWaitsForUnpinnedJob(t *testing.T) { + probe := &switchGPUProbe{err: errors.New("no nvidia-smi")} + release := make(chan struct{}) + l := New(&fakeSession{}, &recordingMinter{config: "jit"}, &recordingProvisioner{block: release}, + Config{GPUProbe: probe, SettleWindow: time.Millisecond, MaxRunners: 2}) + defer l.wg.Wait() + defer close(release) + stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1} + if err := l.reconcile(context.Background(), stats, nil); err != nil { + t.Fatal(err) + } + probe.set([]GPU{rtx5090(0, 0)}, nil) + if got := l.capacityFor(1); got != 0 { + t.Errorf("capacity with an unpinned job = %d, want 0", got) + } + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + if _, _, _, ok := l.admitGPU(ctx, []string{"vram-gb-1"}); ok { + t.Fatal("probe recovery admitted work beside an unpinned job") + } +} + +func TestGPUSelectionUsesMinorForDeviceFiltering(t *testing.T) { + gpu := rtx5090(0, 0) + gpu.Minor = 1 + prov := &recordingProvisioner{} + l := New(&fakeSession{}, &recordingMinter{config: "jit"}, prov, + Config{GPUProbe: stubGPUProbe{gpus: []GPU{gpu}}, Devices: gpuDevicesAll}) + stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1} + if err := l.reconcile(context.Background(), stats, nil); err != nil { + t.Fatal(err) + } + l.wg.Wait() + req := prov.jobs[0] + if req.GPU != 0 || !equalStrings(req.Devices, []string{"/dev/nvidia1", "/dev/nvidiactl", "/dev/nvidia-uvm"}) { + t.Fatalf("request GPU=%d devices=%v, want index 0 and minor 1", req.GPU, req.Devices) + } +} diff --git a/listener/sample_config_test.go b/listener/sample_config_test.go index 9353a94..b196a12 100644 --- a/listener/sample_config_test.go +++ b/listener/sample_config_test.go @@ -2,6 +2,7 @@ package listener import ( "path/filepath" + "runtime" "strings" "testing" ) @@ -39,8 +40,11 @@ func TestSampleConfigLoads(t *testing.T) { if gpu.ScaleSet == "" || len(gpu.Devices) == 0 || gpu.Image == "" { t.Errorf("gpu type under-specified: %+v", gpu) } - if !gpu.Concurrency.DeviceSized() { - t.Error("gpu type should use device-sized concurrency (= GPU count, #113)") + if !gpu.Concurrency.VRAMShared() { + t.Error("gpu type should admit jobs by declared VRAM (mode: vram, #180)") + } + if gpu.Concurrency.Reserve != 20 { + t.Errorf("gpu reserve = %d, want 20 (#180)", gpu.Concurrency.Reserve) } } @@ -71,12 +75,10 @@ func TestCPUTypeImageIsDigestPinned(t *testing.T) { } } -// The GPU type's auto concurrency derives the worker-pool bound from the GPU -// count (#113): with the GPU detector stubbed to report 2 GPUs, the listener -// sizes its pool to 2 -- no real hardware needed. This is the AFK proof that the -// concrete GPU config's auto-concurrency works end to end (config -> instance -> -// resolved bound); a live GPU job actually running is the operator step. -func TestGPUTypeAutoConcurrencyFromGPUCount(t *testing.T) { +// The GPU type admits jobs by declared VRAM (#180): it attaches the GPU probe, +// not the device detector, so with two GPUs stubbed two whole-GPU jobs fit, and +// the pool's safety ceiling is the host CPU count. No real hardware needed. +func TestGPUTypeVRAMConcurrency(t *testing.T) { types, err := LoadConfig(sampleConfigPath(t)) if err != nil { t.Fatalf("load sample: %v", err) @@ -87,12 +89,48 @@ func TestGPUTypeAutoConcurrencyFromGPUCount(t *testing.T) { gpu = rt } } - // Stub the GPU detector at 2 GPUs. - inst := gpu.Instance(InstanceDeps{Detector: stubDetector{count: 2}}) + gp := stubGPUProbe{gpus: []GPU{rtx5090(0, 0), rtx5090(1, 0)}} + inst := gpu.Instance(InstanceDeps{Detector: stubDetector{count: 2}, GPUProbe: gp}) + if inst.Config.GPUProbe == nil || inst.Config.DeviceDetector != nil { + t.Fatalf("gpu instance should attach the GPU probe only, got %+v", inst.Config) + } l := New(nil, nil, nil, inst.Config) - if l.bound != 2 { - t.Errorf("GPU pool bound = %d, want 2 (one slot per detected GPU)", l.bound) + if l.bound != runtime.NumCPU() { + t.Errorf("GPU pool bound = %d, want runtime.NumCPU() = %d", l.bound, runtime.NumCPU()) + } + if got := l.capacityFor(0); got != 2 { + t.Errorf("capacity over two idle GPUs = %d, want 2", got) + } +} + +// A job's runs-on labels must be a subset of the scale set's, so the gpu sample +// lists every allowed vram-gb-* value (#180). +func TestGPUTypeListsVRAMLabels(t *testing.T) { + types, err := LoadConfig(sampleConfigPath(t)) + if err != nil { + t.Fatalf("load sample: %v", err) } + for _, rt := range types { + if rt.Name != "gpu" { + continue + } + have := map[string]bool{} + for _, l := range rt.Labels { + have[l] = true + } + for _, v := range []string{"1", "2", "4", "8", "16", "32", "64", "128", "all"} { + if !have["vram-gb-"+v] { + t.Errorf("gpu labels %v miss vram-gb-%s", rt.Labels, v) + } + } + for _, l := range []string{"self-hosted", "linux", "x64", "gpu", "cuda"} { + if !have[l] { + t.Errorf("gpu labels %v lost the routing label %q", rt.Labels, l) + } + } + return + } + t.Fatal("sample config is missing the gpu runner type") } // GitHub stops dispatching jobs to runners with auto-update disabled once a diff --git a/listener/testdata/runner-types.sample.yaml b/listener/testdata/runner-types.sample.yaml index da12f43..b1ff271 100644 --- a/listener/testdata/runner-types.sample.yaml +++ b/listener/testdata/runner-types.sample.yaml @@ -70,15 +70,27 @@ # not configured (ADR-0005, #163) # reserve: N reactive, keep N% free # (upward-only, minimum 10) -# mode: auto size from detected GPU -# count (#113; reactive -# GPU/VRAM is #164) +# mode: vram shared GPU: admit gpu +# jobs by the VRAM they +# declare (vram-gb-), +# several per GPU when +# they fit (ADR-0007, #180) +# reserve: N (vram) keep N% of each GPU free +# (upward-only, minimum 20) +# The older device-count mode (auto, one job per +# detected GPU, #113) stays valid. # There is no fixed operator count. runner_types: - # --- First concrete type: GPU (#113) ------------------------------------- - # Auto concurrency = detected GPU count (the listener runs nvidia-smi -L and - # sizes its worker pool to one slot per GPU). Devices are passed through + # --- First concrete type: GPU (#113, #180) ------------------------------- + # Shared-GPU concurrency (ADR-0007): a job declares the VRAM it needs with + # one runs-on label, vram-gb- or vram-gb-all; several jobs share a GPU + # while their declarations fit the GPU's VRAM less the reserve, and the + # live free VRAM (nvidia-smi, which also counts work the listener did not + # start) still keeps the reserve. A job with no vram-gb label holds the + # whole GPU, so undeclared jobs still run one per GPU. Nothing caps a job's + # real VRAM use: declare honestly, using the gpu_used_peak_mib the job + # history ledger records. Devices are passed through # precisely (no --privileged); the baseline container hardening + the ADR-0011 # approval gate keep unapproved untrusted code off this rootful device host. - name: gpu @@ -88,7 +100,9 @@ runner_types: scale_set: gpu # This host's runner group. Omitted = Default. # runner_group: ci- - labels: [self-hosted, linux, x64, gpu, cuda] + # Every vram-gb-* value a job may declare must be a scale-set label, since + # a job's runs-on labels must all be on the scale set. + labels: [self-hosted, linux, x64, gpu, cuda, vram-gb-1, vram-gb-2, vram-gb-4, vram-gb-8, vram-gb-16, vram-gb-32, vram-gb-64, vram-gb-128, vram-gb-all] # Self-built GPU image (#121): the CUDA/device stack layered on the SEC-5 # base (images/runner-gpu.Dockerfile -> images/runner-base.Dockerfile, whose # runner tarball passed verify_runner_tarball before being baked in). It @@ -99,6 +113,9 @@ runner_types: # and pin that digest instead. # actions-runner 2.338.2 image: ghcr.io/ycpss91255-lab/gpu-runner@sha256:2846d90a90e9e9bc7b4baecd856600445786d9bd2af63297ebd167910e467cd8 + # List every /dev/nvidia on the host. A pinned job receives the + # node matching its GPU minor, plus the shared control nodes. + # NVIDIA_VISIBLE_DEVICES is set to the GPU index. devices: - /dev/nvidia0 - /dev/nvidiactl @@ -108,8 +125,11 @@ runner_types: # sets no daemonless build_tool. Enabling the socket is ROOT-EQUIVALENT on # the host: enable only for trusted jobs (ADR-0011 approval gate). # docker_socket: /var/run/docker.sock + # If nvidia-smi fails, admit one whole-GPU job per known GPU, or one + # unpinned job total before the first good reading. concurrency: - mode: auto + mode: vram + reserve: 20 # --- A second type, shown to prove "two types, no code change" (#112) ----- # The CPU sample pins the published ghcr.io/ycpss91255-lab/runner-cpu image diff --git a/listener/wiring.go b/listener/wiring.go index cdeb2c4..eb7529b 100644 --- a/listener/wiring.go +++ b/listener/wiring.go @@ -29,12 +29,14 @@ type Instance struct { } // InstanceDeps are the shared host-inspection seams wired into every instance: -// the GPU device detector for mode: auto types, and the reactive host probe for -// the default (reactive live-admission) types. Either may be nil, in which case -// the listener falls back to its conservative default bound. +// the GPU device detector for mode: auto types, the per-GPU VRAM probe for +// mode: vram types (#180), and the reactive host probe for the default +// (reactive live-admission) types. Any may be nil, in which case the listener +// falls back to its conservative default bound. type InstanceDeps struct { Detector DeviceDetector HostProbe HostProbe + GPUProbe GPUProbe } // Instance maps this runner type to its scale-set listener inputs. Concurrency @@ -51,9 +53,13 @@ func (rt RunnerType) Instance(deps InstanceDeps) Instance { BuildTool: rt.BuildTool, DockerSocket: rt.DockerSocket, } - if rt.Concurrency.DeviceSized() { + switch { + case rt.Concurrency.VRAMShared(): + cfg.GPUProbe = deps.GPUProbe + cfg.Reserve = rt.Concurrency.Reserve + case rt.Concurrency.DeviceSized(): cfg.DeviceDetector = deps.Detector - } else { + default: cfg.HostProbe = deps.HostProbe cfg.Reserve = rt.Concurrency.Reserve } diff --git a/listener/wiring_test.go b/listener/wiring_test.go index c85fae7..0a2b5d5 100644 --- a/listener/wiring_test.go +++ b/listener/wiring_test.go @@ -127,3 +127,46 @@ func TestRunnerTypeInstanceCarriesRunnerGroup(t *testing.T) { t.Errorf("RunnerGroup = %q, want %q", got, DefaultRunnerGroup) } } + +// mode: vram (#180) attaches the GPU probe and carries the reserve; it attaches +// neither the cpu host probe nor the device detector, so the cpu path and the +// device-count path are untouched. +func TestRunnerTypeVRAMAttachesGPUProbe(t *testing.T) { + rt := RunnerType{ + Name: "gpu", + ScaleSet: "gpu", + Labels: []string{"self-hosted", "gpu", "vram-gb-8"}, + Image: "img-gpu@sha256:1", + Devices: []string{"/dev/nvidia0"}, + Runtime: "nvidia", + Concurrency: Concurrency{Mode: "vram", Reserve: 25}, + } + gp := stubGPUProbe{gpus: []GPU{rtx5090(0, 0)}} + inst := rt.Instance(InstanceDeps{Detector: stubDetector{count: 3}, HostProbe: stubProbe{}, GPUProbe: gp}) + if inst.Config.GPUProbe == nil { + t.Fatal("mode: vram should attach the GPU probe") + } + if inst.Config.HostProbe != nil { + t.Error("mode: vram must not attach the cpu host probe") + } + if inst.Config.DeviceDetector != nil { + t.Error("mode: vram must not attach the device detector") + } + if inst.Config.Reserve != 25 { + t.Errorf("Config.Reserve = %d, want 25", inst.Config.Reserve) + } + if inst.Config.Runtime != "nvidia" || len(inst.Config.Devices) != 1 { + t.Errorf("runtime/devices not carried: %+v", inst.Config) + } +} + +// The other modes never pick up the GPU probe. +func TestNonVRAMTypesDoNotAttachGPUProbe(t *testing.T) { + deps := InstanceDeps{Detector: stubDetector{count: 1}, HostProbe: stubProbe{}, GPUProbe: stubGPUProbe{}} + for _, c := range []Concurrency{{}, {Reserve: 20}, {Mode: "auto"}} { + rt := RunnerType{Name: "t", ScaleSet: "t", Labels: []string{"t"}, Image: "i@sha256:1", Concurrency: c} + if rt.Instance(deps).Config.GPUProbe != nil { + t.Errorf("concurrency %+v attached the GPU probe", c) + } + } +} diff --git a/test/bats/integration/listener_provision.bats b/test/bats/integration/listener_provision.bats index 2bb8356..257da4e 100644 --- a/test/bats/integration/listener_provision.bats +++ b/test/bats/integration/listener_provision.bats @@ -231,7 +231,7 @@ teardown() { rm -rf "${WORK}" "${STUB}"; } done } -@test "provision-job.sh removes the JIT credential env file when it is terminated mid-job" { +@test "provision-job.sh removes the JIT credential and VRAM sample files when terminated mid-job" { # A listener restart sends SIGTERM while the container is still running. The # RETURN trap inside the container seam never fires on that path, so the # script's own EXIT trap must remove the 0600 credential env file. @@ -244,14 +244,17 @@ echo \$\$ > "${STARTED}" exec sleep 30 EOF chmod +x "${STUB}/docker" - "${SCRIPT}" job-term "$(jit_file ENC)" img >/dev/null 2>&1 & + make_nvidia_smi 0 + RUNNER_GPU=0 RUNNER_VRAM_GB=4 "${SCRIPT}" job-term "$(jit_file ENC)" img >/dev/null 2>&1 & pid=$! for _ in $(seq 1 100); do [ -s "${STARTED}" ] && break; sleep 0.1; done [ -s "${STARTED}" ] [ -s "${STARTED}.env" ] # the env file existed while the job ran + grep -qx 0 "${RUNNER_WORK_ROOT}"/jit-job-term.*.vram.* kill -TERM "${pid}" wait "${pid}" || : kill "$(cat "${STARTED}")" 2>/dev/null || : + [ -z "$(find "${RUNNER_WORK_ROOT}" -name '*.vram.*' -print)" ] run bash -c "ls '${RUNNER_WORK_ROOT}'/*.jitconfig.env 2>/dev/null | wc -l" [ "${output}" = "0" ] } @@ -547,3 +550,118 @@ assert_invalid_workdir() { [ "$(stat -c %a -- "${RUNNER_WORK_ROOT}")" = 700 ] [ ! -e "${RUNNER_JOB_WORKDIR}" ] } + +# --- #180 peak VRAM in the ledger ------------------------------------------- +# A job pinned to a GPU records that GPU's index, the VRAM it was charged, and the +# peak VRAM in use on that GPU while it ran. The peak is for the WHOLE GPU (a +# per-job figure is not attributable: Vulkan/graphics contexts such as +# Isaac/Kit do not show in --query-compute-apps). nvidia-smi is a PATH stub. + +make_nvidia_smi() { + cat >"${STUB}/nvidia-smi" <> "${WORK}/nvidia-smi.args" +printf '%s\n' "${1}" +exit ${2:-0} +EOF2 + chmod +x "${STUB}/nvidia-smi" +} + +@test "provision-job.sh records the GPU, charged VRAM and GPU peak VRAM in the ledger (#180)" { + make_nvidia_smi 4096 + jf=$(jit_file ENC) + RUNNER_GPU=1 RUNNER_VRAM_GB=8 run "${SCRIPT}" job-vram "${jf}" img + [ "${status}" -eq 0 ] + grep -q 'job_id=job-vram' "${RUNNER_HISTORY_LEDGER}" + grep -q 'gpu_index=1' "${RUNNER_HISTORY_LEDGER}" + grep -q 'vram_charged_gb=8' "${RUNNER_HISTORY_LEDGER}" + grep -q 'gpu_used_peak_mib=4096' "${RUNNER_HISTORY_LEDGER}" + # The sampler reads the chosen GPU only. + grep -qxF -- '--query-gpu=memory.used' "${WORK}/nvidia-smi.args" + grep -A1 -xF -- '-i' "${WORK}/nvidia-smi.args" | grep -qxF -- '1' +} + +@test "provision-job.sh records no GPU fields and never runs nvidia-smi for a CPU job (#180)" { + make_nvidia_smi 4096 + jf=$(jit_file ENC) + RUNNER_GPU='' run "${SCRIPT}" job-cpu "${jf}" img + [ "${status}" -eq 0 ] + grep -q 'job_id=job-cpu' "${RUNNER_HISTORY_LEDGER}" + ! grep -q 'gpu_index=' "${RUNNER_HISTORY_LEDGER}" || return 1 + ! grep -q 'gpu_used_peak_mib=' "${RUNNER_HISTORY_LEDGER}" || return 1 + [ ! -e "${WORK}/nvidia-smi.args" ] +} + +@test "provision-job.sh still runs and records the job when the VRAM sampler fails (#180)" { + make_nvidia_smi 'NVIDIA-SMI has failed' 9 + jf=$(jit_file ENC) + RUNNER_GPU=0 RUNNER_VRAM_GB=4 run "${SCRIPT}" job-nosmi "${jf}" img + [ "${status}" -eq 0 ] + grep -q 'job_id=job-nosmi' "${RUNNER_HISTORY_LEDGER}" + grep -q 'gpu_index=0' "${RUNNER_HISTORY_LEDGER}" + grep -q $'gpu_used_peak_mib=\tvram_peak_scope=whole_gpu' "${RUNNER_HISTORY_LEDGER}" + # Teardown still happened. + run bash -c "ls -d '${RUNNER_WORK_ROOT}'/jit-job-nosmi.* 2>/dev/null | wc -l" + [ "${output}" = "0" ] +} + +@test "provision-job.sh keeps the job's exit status when it records GPU fields (#180)" { + make_nvidia_smi 2048 + export CLI_RC=5 + jf=$(jit_file ENC) + RUNNER_GPU=0 RUNNER_VRAM_GB=2 run "${SCRIPT}" job-vfail "${jf}" img + [ "${status}" -eq 5 ] + grep -q 'exit_status=5' "${RUNNER_HISTORY_LEDGER}" + grep -q 'gpu_used_peak_mib=2048' "${RUNNER_HISTORY_LEDGER}" +} + +@test "provision-job.sh keeps the peak observed during a GPU job" { + cat >"${STUB}/nvidia-smi" <"${STUB}/docker" </dev/null; then + rm "${WORK}/running" + exit 0 + fi + sleep 0.02 +done +exit 1 +EOF2 + chmod +x "${STUB}/nvidia-smi" "${STUB}/docker" + export RUNNER_VRAM_SAMPLE_INTERVAL=0.01 + RUNNER_GPU=0 RUNNER_VRAM_GB=4 run "${SCRIPT}" job-peak "$(jit_file ENC)" img + [ "${status}" -eq 0 ] + grep -q $'gpu_used_peak_mib=4096\tvram_peak_scope=whole_gpu' "${RUNNER_HISTORY_LEDGER}" + [ -z "$(find "${RUNNER_WORK_ROOT}" -name '*.vram.*' -print)" ] +} + +@test "provision-job.sh still runs if the VRAM sample file cannot be created" { + local real_mktemp + real_mktemp=$(command -v mktemp) + cat >"${STUB}/mktemp" < +# ` line per GPU for the Go CommandGPUProbe, which does the math +# (ADR-0003). nvidia-smi is a PATH stub, so no GPU is needed. + +setup() { + SCRIPT="${BATS_TEST_DIRNAME}/../../../listener/gpu-probe.sh" + STUB=$(mktemp -d) + ARGS="${STUB}/nvidia-smi.args" + PATH="${STUB}:/bin:/usr/bin" +} + +teardown() { rm -rf "${STUB}"; } + +# make_nvidia_smi : a stub that records its argv and +# prints the CSV the real nvidia-smi query prints. +make_nvidia_smi() { + cat >"${STUB}/nvidia-smi" <> "${ARGS}" +printf '%b' '$2' +exit $1 +EOF2 + chmod +x "${STUB}/nvidia-smi" +} + +@test "gpu-probe prints one gpu line per GPU from the nvidia-smi query" { + make_nvidia_smi 0 '0, 4, 32607, 1024, 31583\n1, 0, 16380, 0, 16380\n' + run bash "${SCRIPT}" + [ "${status}" -eq 0 ] + [ "${lines[0]}" = "gpu 0 4 32607 1024 31583" ] + [ "${lines[1]}" = "gpu 1 0 16380 0 16380" ] + [ "${#lines[@]}" -eq 2 ] +} + +@test "gpu-probe queries index and memory in csv without header or units" { + make_nvidia_smi 0 '0, 4, 32607, 1024, 31583\n' + run bash "${SCRIPT}" + [ "${status}" -eq 0 ] + grep -qxF -- '--query-gpu=index,minor_number,memory.total,memory.used,memory.free' "${ARGS}" + grep -qxF -- '--format=csv,noheader,nounits' "${ARGS}" +} + +@test "gpu-probe exits non-zero when nvidia-smi fails" { + [ -f "${SCRIPT}" ] + make_nvidia_smi 9 'NVIDIA-SMI has failed\n' + run bash "${SCRIPT}" + [ "${status}" -ne 0 ] + [[ "${output}" != *"gpu "* ]] +} + +@test "gpu-probe exits non-zero when nvidia-smi is absent" { + [ -f "${SCRIPT}" ] + run bash "${SCRIPT}" + [ "${status}" -ne 0 ] +} diff --git a/test/bats/unit/justfile.bats b/test/bats/unit/justfile.bats index a3fd8fc..7943265 100644 --- a/test/bats/unit/justfile.bats +++ b/test/bats/unit/justfile.bats @@ -326,3 +326,8 @@ EOF return 1 fi } + +@test "SCRIPTS enumerates listener/gpu-probe.sh so shellcheck covers it (#180)" { + run bash -c "grep -E '^SCRIPTS :=' '${JUSTFILE}' | grep -F 'listener/gpu-probe.sh'" + [ "${status}" -eq 0 ] +}