Skip to content

Commit 085f509

Browse files
authored
feat(profiles): auto-inject variant jupyterlab image for image-variant: gpu profiles (#237)
* docs: design spec for GPU profile image auto-derivation (#230) * feat(profiles): auto-inject GPU jupyterlab image for gpu: true profiles Profiles marked gpu: true in jupyterhub.custom.profiles get kubespawner_override.image set to the chart-derived GPU image (<singleuser.image.name>-gpu:<singleuser.image.tag>) unless an explicit image is present. Both jupyterlab images are built from the same commit with the same sha tag, so GPU profiles now track pack updates automatically instead of pinning a -gpu SHA in the deployer overlay. Deployers can override the injected ref chart-wide via jupyterhub.custom.gpu-image. The gpu key is stripped before profiles reach KubeSpawner. Closes #230 * fix(profiles): address review on GPU image injection - warn when a gpu: true profile declares profile_options.image, since the selected choice's image replaces the injected one at spawn time - strip the gpu key whatever its value (gpu: false was leaking through) - warn when no GPU image can be derived and custom.gpu-image is unset - log the injected ref per profile and the chart-wide gpu-image at load - document the gpu strip mechanism next to _PROFILE_GATING_KEYS - _helpers.tpl: move gpuJupyterlabImage below nebiImage so nebiImage keeps its doc comment; add the numbered precedence list - docs/values: drop 'always valid'; mirrored-registry + amd64-only notes; explicit pins are never bumped by bump_image_tags.py; profile_options caveat - spec: add Why this approach / Rejected alternatives - tests: docstrings + assert messages, cover the new warnings and logs * refactor(profiles): image-variant: <name> instead of boolean gpu: true Per review: a string key generalises to future -rocm/arm64 variants without carrying a boolean alongside it. The derivation moves from Helm into 01-spawner.py (<singleuser.image.name>-<variant>:<tag>) because only the profile knows the variant name; custom.gpu-image becomes the custom.image-variants map of per-variant full-ref overrides. Drops the gpuJupyterlabImage helper and the _CHART_DERIVED entry. * fix(profiles): harden custom.image-variants against bad shapes and typos Address review on the image-variant resolution: - A non-mapping custom.image-variants (e.g. `image-variants: gpu`) reached .get at module import and CrashLooped the hub. It now warns and is ignored; bare `image-variants:` (null) stays silent. - A non-string override value ({gpu: 123}) warns and falls back to the derived ref instead of injecting image: 123. - An image-variants key no profile claims (gpus vs gpu) warns, since it otherwise silently replaces the deployer's mirror ref with the derived one. - An empty `image-variant:` value now warns like precedence case 4 does. - Docstring: variant profiles are rebuilt, others pass through by reference. - Tests: fixtures use a slug distinct from the variant so the warning assertions actually check the profile name (both fail on a mutated message now); caplog scoped to the resolve call in the no-warning test; seven new tests for the cases above including the import-time repro. - Spec: correct the reason Helm derivation was rejected (_CHART_DERIVED is scalar-only, not that Helm cannot see the profile list). - Docs/values.yaml: note that a misspelled variant fails loud at spawn rather than closed, and what the hub warns about for image-variants. - Drop stray trailing blank line in test_chart_derived.py.
1 parent 4f80d9d commit 085f509

6 files changed

Lines changed: 701 additions & 2 deletions

File tree

‎config/jupyterhub/01-spawner.py‎

Lines changed: 110 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -330,7 +330,12 @@ def _setup_trust_bundle(spawner):
330330
# ``kubespawner_override`` accepts any valid KubeSpawner trait so deployers
331331
# can add node_selector, image, extra_resource_limits (GPU), etc. without
332332
# code changes. Empty list = no profile selector (single-instance mode).
333-
# Keys used only for group gating; KubeSpawner must never see them.
333+
# Keys used only for group gating; KubeSpawner must never see them. They are
334+
# stripped per user in _filter_profiles because gating is a per-user decision.
335+
# ``image-variant`` is the other chart-only key — it is stripped once at load
336+
# in _resolve_image_variants because its effect (image injection) is the same
337+
# for every user and jhub-apps reads the resolved list too. A future custom key
338+
# belongs in whichever of the two matches how it is evaluated.
334339
_PROFILE_GATING_KEYS = ("access", "groups", "users")
335340

336341

@@ -442,7 +447,110 @@ async def _render_profile_list(spawner):
442447
return visible
443448

444449

445-
_profiles = get_config("custom.profiles", [])
450+
def _resolve_image_variants(profiles, base_name, base_tag, overrides):
451+
"""Inject a variant of the singleuser image into ``image-variant`` profiles.
452+
453+
Every jupyterlab image variant (today only ``gpu``) is built from the same
454+
commit as the CPU image and shares its ``sha-<short>`` tag, so a profile
455+
marked ``image-variant: gpu`` resolves to
456+
``<singleuser.image.name>-gpu:<singleuser.image.tag>`` and stays current
457+
across pack updates without a hardcoded SHA in the overlay (issue #230).
458+
459+
Order of precedence for the injected image:
460+
1. the profile's own ``kubespawner_override.image`` — never touched
461+
2. ``custom.image-variants.<variant>`` — deployer override, full ref
462+
(mirrored registries, a variant published elsewhere)
463+
3. ``<base_name>-<variant>:<base_tag>`` — derived
464+
4. nothing — ``base_name``/``base_tag`` empty (schema-valid in z2jh);
465+
the profile falls back to the CPU default image and the hub warns.
466+
An empty ``image-variant:`` value is stripped without injecting anything
467+
and warns, since it is almost certainly a mistake.
468+
469+
The ``image-variant`` key is stripped whatever its value — KubeSpawner
470+
must never see it. Variant profiles are rebuilt as new dicts; the rest pass
471+
through by reference. Nothing is mutated — the input list and its dicts are
472+
left untouched.
473+
474+
Every degraded path only warns, because raising here would break hub
475+
startup (and therefore login) for every user. Besides the empty-ref
476+
fallback above, this covers: ``custom.image-variants`` that is not a
477+
mapping, or maps a variant to something other than a non-empty string
478+
(both ignored); an ``image-variants`` key no profile claims (a likely typo
479+
that would otherwise silently hand the mirrored-registry deployer the
480+
derived ref); and a profile that also declares ``profile_options.image`` —
481+
KubeSpawner applies the selected choice's ``kubespawner_override`` AFTER
482+
the profile-level one and replaces rather than merges, so the choice's
483+
image silently wins over the injected one at spawn time (while jhub-apps
484+
still displays the injected one).
485+
"""
486+
if overrides and not isinstance(overrides, dict):
487+
log.warning(
488+
"profiles: custom.image-variants is %s, expected a mapping of "
489+
"variant -> image ref — ignoring it",
490+
type(overrides).__name__,
491+
)
492+
overrides = {}
493+
overrides = overrides or {}
494+
claimed_variants = set()
495+
resolved = []
496+
for profile in profiles:
497+
if "image-variant" not in profile:
498+
resolved.append(profile)
499+
continue
500+
name = profile.get("slug") or profile.get("display_name")
501+
variant = profile["image-variant"]
502+
profile = {k: v for k, v in profile.items() if k != "image-variant"}
503+
if not variant:
504+
log.warning("profiles: %r has an empty image-variant — no image injected", name)
505+
resolved.append(profile)
506+
continue
507+
claimed_variants.add(variant)
508+
override = dict(profile.get("kubespawner_override") or {})
509+
if not override.get("image"):
510+
image = overrides.get(variant)
511+
if image and not isinstance(image, str):
512+
log.warning(
513+
"profiles: custom.image-variants.%s is %r, expected an image ref "
514+
"string — ignoring it",
515+
variant, image,
516+
)
517+
image = None
518+
if not image and base_name and base_tag:
519+
image = f"{base_name}-{variant}:{base_tag}"
520+
if image:
521+
override["image"] = image
522+
log.info("profiles: %r image-variant %r — injected image %s", name, variant, image)
523+
else:
524+
log.warning(
525+
"profiles: %r has image-variant %r but no image could be derived "
526+
"(singleuser.image.name/tag empty?) and custom.image-variants.%s is "
527+
"unset — the profile will spawn the CPU default image",
528+
name, variant, variant,
529+
)
530+
if "image" in (profile.get("profile_options") or {}):
531+
log.warning(
532+
"profiles: %r has image-variant %r but declares profile_options.image; "
533+
"the selected choice's image overrides the injected one at spawn time — "
534+
"drop the option or point its choices at the variant image",
535+
name, variant,
536+
)
537+
profile["kubespawner_override"] = override
538+
resolved.append(profile)
539+
for unclaimed in sorted(set(overrides) - claimed_variants, key=str):
540+
log.warning(
541+
"profiles: custom.image-variants.%s matches no profile's image-variant "
542+
"(typo?) — variant profiles use the derived ref instead",
543+
unclaimed,
544+
)
545+
return resolved
546+
547+
548+
_profiles = _resolve_image_variants(
549+
get_config("custom.profiles", []),
550+
get_config("singleuser.image.name", ""),
551+
get_config("singleuser.image.tag", ""),
552+
get_config("custom.image-variants", {}),
553+
)
446554
if _profiles:
447555
c.KubeSpawner.profile_list = _render_profile_list
448556
log.info(

‎docs/src/content/docs/server-profiles.md‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,78 @@ kubectl -n data-science logs deploy/hub | grep -i "profiles:\|groups"
152152

153153
## GPU profiles
154154

155+
### The GPU image, without hardcoding a SHA
156+
157+
Mark a profile `image-variant: gpu` and the chart injects the matching GPU JupyterLab image
158+
(`nebari-data-science-pack-jupyterlab-gpu`) at the chart's current tag:
159+
160+
```yaml
161+
- slug: gpu-instance
162+
display_name: "G4 GPU Instance"
163+
image-variant: gpu
164+
access: yaml
165+
groups:
166+
- gpu-access
167+
kubespawner_override:
168+
# no image needed — the -gpu image is injected automatically
169+
node_selector:
170+
node.kubernetes.io/instance-type: g4dn.xlarge
171+
extra_resource_limits:
172+
nvidia.com/gpu: 1
173+
```
174+
175+
Both JupyterLab images are built from the same commit and share the same `sha-` tag, so
176+
the derived ref (`<singleuser.image.name>-gpu:<singleuser.image.tag>`) exists on
177+
`quay.io/nebari` for every release and GPU profiles track pack updates exactly like CPU
178+
profiles — no more stale SHAs in the overlay
179+
([issue #230](https://github.com/nebari-dev/data-science-pack/issues/230)).
180+
181+
The derivation is generic — `image-variant: <name>` resolves to
182+
`<singleuser.image.name>-<name>:<singleuser.image.tag>` — but `gpu` is the only variant
183+
published today. Like the gating keys, `image-variant` is stripped (whatever its value) before
184+
the profile reaches KubeSpawner. The hub logs the injected ref at startup:
185+
186+
```bash
187+
kubectl -n data-science logs deploy/hub | grep "profiles:.*gpu"
188+
```
189+
190+
:::caution[Mirrored registries]
191+
The derivation only rewrites the image *name*. If you point `jupyterhub.singleuser.image.name`
192+
at a mirror (ECR, an airgapped registry), the chart derives `<mirror>-gpu:<tag>`, which does
193+
not exist unless you mirrored it too. Nothing validates the ref at `helm upgrade` time — the
194+
first GPU spawn fails with `ImagePullBackOff`. Either mirror the `-gpu` image under that name
195+
or map it under `jupyterhub.custom.image-variants`:
196+
197+
```yaml
198+
image-variants:
199+
gpu: 123456789012.dkr.ecr.us-east-1.amazonaws.com/lab-gpu:sha-abc1234
200+
```
201+
202+
The `-gpu` image is built for `linux/amd64` only; the CPU image is multi-arch.
203+
204+
The same applies to a misspelled variant: unlike a typo in a gating key, which fails closed,
205+
`image-variant: gup` does not fail at all. It derives `<name>-gup:<tag>`, which the startup log
206+
shows and the first spawn rejects with `ImagePullBackOff`. A misspelled key under
207+
`image-variants` (say `gpus:`) is different: it matches no profile, so the derived ref is used
208+
instead of your override, and the hub logs a warning naming the unclaimed key.
209+
:::
210+
211+
Two things override the injection:
212+
213+
- **An explicit `kubespawner_override.image`** always wins. Note that
214+
`scripts/bump_image_tags.py` only rewrites the CPU image ref, so a hand-pinned `-gpu`
215+
image stays frozen across releases — the exact problem `image-variant` exists to solve. Prefer
216+
the key over pinning.
217+
- **`profile_options.image`.** KubeSpawner applies the selected choice's
218+
`kubespawner_override` *after* the profile-level one and replaces rather than merges, so
219+
an image choice silently puts the CPU image on the GPU node (while jhub-apps' Create App
220+
still displays the injected GPU image). The shipped CPU profiles carry such an option —
221+
do not copy it onto an `image-variant` profile. The hub logs a warning if you do.
222+
223+
`jupyterhub.custom.image-variants.<name>` changes which image gets injected for a variant chart-wide.
224+
225+
### Scheduling onto GPU nodes
226+
155227
A GPU profile requests the resource through `extra_resource_limits`, but scheduling onto a
156228
tainted GPU node group also needs a toleration — whether you must add it yourself depends on
157229
whether the cluster runs the `ExtendedResourceToleration` admission controller (EKS and GKE

‎docs/src/content/docs/values-reference.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@ always win.
202202
| `external-url` | `""` *(derived)* | Hub bind hostname. |
203203
| `nebi-image` | `""` *(derived)* | `repository:tag` copied into user pods. |
204204
| `nebi-image-pull-policy` | `IfNotPresent` | — |
205+
| `image-variants` | `{}` | Per-variant image overrides for `image-variant: <name>` profiles. Default derivation is `<singleuser.image.name>-<name>:<tag>` — see [Server profiles](/server-profiles/#gpu-profiles). |
205206
| `jhub-app-proxy-version` | `v0.2.3` | Installed at app-spawn time. Must be ≥ v0.2.3 for apps to run inside a Nebi (pixi) environment; older versions only activate conda and fall back to the base env. |
206207
| `nebi-remote-url` | `""` *(derived)* | Browser-facing Nebi URL. |
207208
| `nebi-internal-url` | `""` *(derived)* | In-cluster Nebi URL. |
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# GPU profile image auto-derivation
2+
3+
Issue: https://github.com/nebari-dev/data-science-pack/issues/230
4+
5+
## Problem
6+
7+
Deployers who add GPU JupyterLab profiles must hardcode
8+
`quay.io/nebari/nebari-data-science-pack-jupyterlab-gpu:sha-<short>` in their
9+
overlay. CPU profiles inherit the chart's image tag on every pack update; GPU
10+
profiles silently fall behind until someone remembers to bump the SHA.
11+
12+
Both `nebari-data-science-pack-jupyterlab` and
13+
`nebari-data-science-pack-jupyterlab-gpu` are built by the same
14+
`build-images.yaml` workflow from the same commit, so they always share the
15+
same `sha-<short>` tag. The chart therefore already knows the correct GPU
16+
image ref: `<singleuser.image.name>-gpu:<singleuser.image.tag>`.
17+
18+
## Design
19+
20+
A new per-profile key `image-variant: <name>` in `jupyterhub.custom.profiles`:
21+
22+
```yaml
23+
- slug: gpu
24+
display_name: "GPU Access"
25+
image-variant: gpu
26+
access: yaml
27+
groups: [gpu-access]
28+
kubespawner_override:
29+
# no image needed — injected automatically
30+
node_selector: {node.kubernetes.io/instance-type: g4dn.xlarge}
31+
extra_resource_limits: {nvidia.com/gpu: 1}
32+
```
33+
34+
### Components
35+
36+
1. **Spawner config** (`config/jupyterhub/01-spawner.py`): at load,
37+
`_resolve_image_variants(profiles, base_name, base_tag, overrides)`
38+
walks `custom.profiles`, reading `singleuser.image.name`/`.tag` and
39+
`custom.image-variants` from z2jh. For each `image-variant: <name>`:
40+
* no `kubespawner_override.image` → inject, in order of precedence,
41+
`custom.image-variants.<name>` if set, else
42+
`<base_name>-<name>:<base_tag>`; if neither can be produced
43+
(`singleuser.image.name`/`tag` empty, schema-valid in z2jh) warn and
44+
fall back to the CPU default image
45+
* explicit image → leave it alone (explicit wins)
46+
* the key is always stripped so KubeSpawner never sees it
47+
* `profile_options.image` present → warn (see Rejected alternatives)
48+
49+
Resolution happens once at module load, before `_render_profile_list`
50+
filtering, so jhub-apps' server-types endpoint sees the same image.
51+
52+
2. **Override map** `jupyterhub.custom.image-variants: {}` in `values.yaml`
53+
— full refs per variant, for mirrored registries or a variant published
54+
elsewhere. Read directly via z2jh `get_config` (it is a mapping, so the
55+
`get_chart_config` empty-string convention does not apply).
56+
57+
No Helm-side change: the derivation needs the variant name, which only the
58+
profile knows, so it lives in Python where both inputs are available.
59+
60+
### Why `image-variant: <name>` rather than a boolean `gpu: true`
61+
62+
* The image naming already has a variant axis (`-gpu`), and a `-rocm` or
63+
arm64 runtime image is plausible. A boolean would have to coexist with a
64+
string key forever once it shipped in `values.yaml`.
65+
* Same amount of code today; the derivation string is the only place the
66+
variant name appears.
67+
* Cost: `image-variant: gpu` reads slightly less naturally than `gpu: true`
68+
in an overlay. Mitigated by the example in `values.yaml` and the docs.
69+
70+
### Rejected alternatives
71+
72+
* **Boolean `gpu: true`.** The first draft of this PR. Rejected in review
73+
for the reason above: it is an API surface we cannot drop without a
74+
deprecation cycle, and the string key costs nothing extra.
75+
* **Deriving in Helm (`_CHART_DERIVED["gpu-image"]`).** Also the first
76+
draft. Works for one hardcoded variant but cannot be generic. Helm *can*
77+
read the profile list (`jupyterhub` is a subchart and `_helpers.tpl`
78+
already indexes `.Values.jupyterhub.custom`), but `_CHART_DERIVED` carries
79+
scalars only — its `""`-means-unset sentinel has no map equivalent, so a
80+
variant map cannot round-trip through it: there is no way to tell
81+
"deployer set `{}`" from "chart baked `{}`".
82+
* **Injecting into `profile_options.image.choices` too.** Choices always
83+
carry an explicit image (that is their purpose), so injecting there
84+
would overwrite explicit deployer values and contradict "explicit wins".
85+
Instead the hub warns when a variant profile declares
86+
`profile_options.image`, and the docs say not to combine them.
87+
* **Raising on an empty derived image.** Would break hub startup, and
88+
therefore login, for every user. A warning plus fallback to the CPU
89+
default image is the right level.
90+
91+
### Automatic tag currency
92+
93+
`scripts/bump_image_tags.py` already bumps `jupyterhub.singleuser.image.tag`
94+
every release; the derived GPU ref follows with zero script changes.
95+
96+
### Out of scope (YAGNI)
97+
98+
* Auto-injecting `extra_resource_limits` / tolerations — cluster-specific,
99+
already documented.
100+
* Rewriting `profile_options.image.choices` for GPU profiles — explicit
101+
choices keep winning at spawn time; the hub warns when a variant profile
102+
declares that option (see Rejected alternatives).
103+
* Teaching `scripts/bump_image_tags.py` to bump explicitly pinned `-gpu`
104+
refs, and recording the build invariant (both jupyterlab images from one
105+
`build-images.yaml` run) — follow-ups.
106+
107+
## Testing
108+
109+
* Unit (`tests/unit/test_spawner_profiles.py`): derivation, generic
110+
variant names, override map, explicit-image precedence, key stripping
111+
(including empty variant), empty-base fallback + warning,
112+
`profile_options.image` warning (+ negative), input non-mutation,
113+
load-time wiring from z2jh keys, load-time log naming the injected ref.
114+
115+
## Docs
116+
117+
* `docs/src/content/docs/server-profiles.md` GPU section: document `image-variant`.
118+
* `docs/src/content/docs/values-reference.md`: `image-variants` row.
119+
* `values.yaml` comments for `image-variants` + profile example.

0 commit comments

Comments
 (0)