From b600e8cb23ea2a497a652ae423ad6676888d2281 Mon Sep 17 00:00:00 2001 From: Keerthirajan Senthilkumar Date: Thu, 3 Sep 2026 23:57:55 -0700 Subject: [PATCH 1/8] feat: configure shared memory for singleuser pods --- config/jupyterhub/01-spawner.py | 133 +++++++++++++- docs/src/content/docs/server-profiles.md | 31 ++++ docs/src/content/docs/values-reference.md | 9 + templates/hub-config.yaml | 5 + tests/e2e/test_shared_memory.py | 63 +++++++ tests/unit/test_chart_derived.py | 7 + tests/unit/test_spawner_shared_memory.py | 214 ++++++++++++++++++++++ values.yaml | 12 ++ 8 files changed, 469 insertions(+), 5 deletions(-) create mode 100644 tests/e2e/test_shared_memory.py create mode 100644 tests/unit/test_spawner_shared_memory.py diff --git a/config/jupyterhub/01-spawner.py b/config/jupyterhub/01-spawner.py index 917ee4b..83169f0 100644 --- a/config/jupyterhub/01-spawner.py +++ b/config/jupyterhub/01-spawner.py @@ -2,6 +2,7 @@ # ruff: noqa: F821 - `c` is a magic global provided by JupyterHub import asyncio +import copy import json import logging import os @@ -32,6 +33,79 @@ # KubeSpawner (escaped slug) vs base Spawner traits like notebook_dir (raw username), # causing a path mismatch when usernames contain special characters (e.g. emails). # Each user still gets an isolated PVC via claim-{username}. + +_DSHM_NAME = "dshm" +_DSHM_PATH = "/dev/shm" +_MISSING_OVERRIDE = object() + + +def _normalize_shared_memory_size_limit(value): + """Return a non-empty Kubernetes quantity string.""" + if not isinstance(value, str) or not value.strip(): + raise ValueError("shared-memory sizeLimit must be a non-empty string") + return value.strip() + + +def _upsert_named(entries, addition): + """Return entries with exactly one item bearing ``addition``'s name.""" + retained = [ + entry + for entry in list(entries or []) + if entry.get("name") != addition["name"] + ] + return [*retained, addition] + + +def _with_shared_memory_volume(volumes, size_limit): + return _upsert_named( + volumes, + { + "name": _DSHM_NAME, + "emptyDir": {"medium": "Memory", "sizeLimit": size_limit}, + }, + ) + + +def _with_shared_memory_mount(volume_mounts): + retained = [ + mount + for mount in list(volume_mounts or []) + if mount.get("name") != _DSHM_NAME and mount.get("mountPath") != _DSHM_PATH + ] + return [*retained, {"name": _DSHM_NAME, "mountPath": _DSHM_PATH}] + + +def _resolve_list_override(spawner, trait_name, configured): + if configured is _MISSING_OVERRIDE: + return getattr(spawner, trait_name, []) + if callable(configured): + return configured(spawner) + return configured + + +def _profile_volumes_override(configured, size_limit): + def apply(spawner): + volumes = _resolve_list_override(spawner, "volumes", configured) + return _with_shared_memory_volume(volumes, size_limit) + + return apply + + +def _profile_volume_mounts_override(configured): + def apply(spawner): + mounts = _resolve_list_override(spawner, "volume_mounts", configured) + return _with_shared_memory_mount(mounts) + + return apply + + +_shared_memory_enabled = bool(get_chart_config("shared-memory-enabled", True)) +_shared_memory_size_limit = get_chart_config("shared-memory-size-limit", "8Gi") +if _shared_memory_enabled: + _shared_memory_size_limit = _normalize_shared_memory_size_limit( + _shared_memory_size_limit + ) + c.KubeSpawner.storage_pvc_ensure = True c.KubeSpawner.storage_capacity = get_config("custom.storage-capacity", "20Gi") c.KubeSpawner.storage_access_modes = ["ReadWriteOnce"] @@ -47,7 +121,8 @@ # the template to `{username}` makes ensure + mount converge on the same # RWO claim, which the pod-affinity rule below keeps to a single node. c.KubeSpawner.pvc_name_template = "claim-{username}" -c.KubeSpawner.volumes = [ +c.KubeSpawner.volumes = list(get_config("singleuser.extraVolumes", []) or []) +for _volume in [ { "name": "home", "persistentVolumeClaim": { @@ -60,8 +135,11 @@ "name": "__SINGLEUSER_CONFIG_CM__", # replaced by Helm template }, }, -] -c.KubeSpawner.volume_mounts = [ +]: + c.KubeSpawner.volumes = _upsert_named(c.KubeSpawner.volumes, _volume) + +c.KubeSpawner.volume_mounts = list(get_config("singleuser.extraVolumeMounts", []) or []) +for _volume_mount in [ { "name": "home", "mountPath": "/home/jovyan", @@ -71,7 +149,16 @@ "mountPath": "/etc/jupyter/jupyter_server_config.py", "subPath": "jupyter_server_config.py", }, -] +]: + c.KubeSpawner.volume_mounts = _upsert_named( + c.KubeSpawner.volume_mounts, _volume_mount + ) + +if _shared_memory_enabled: + c.KubeSpawner.volumes = _with_shared_memory_volume( + c.KubeSpawner.volumes, _shared_memory_size_limit + ) + c.KubeSpawner.volume_mounts = _with_shared_memory_mount(c.KubeSpawner.volume_mounts) # --------------------------------------------------------------------------- # Admin-provisioned nebi config (OCI registries, default-registry seed flag). @@ -334,6 +421,42 @@ def _setup_trust_bundle(spawner): _PROFILE_GATING_KEYS = ("access", "groups", "users") +def _translate_profile_shared_memory(profile): + """Translate the chart-owned profile key into valid KubeSpawner traits.""" + translated = copy.deepcopy(profile) + overrides = translated.get("kubespawner_override") + if not isinstance(overrides, dict): + return translated + + requested_size = overrides.pop("shm_size_limit", _MISSING_OVERRIDE) + if not _shared_memory_enabled: + if requested_size is not _MISSING_OVERRIDE: + log.warning( + "profiles: ignoring shm_size_limit for %r because shared memory is disabled", + translated.get("slug") or translated.get("display_name"), + ) + return translated + + overrides_shared_memory = ( + requested_size is not _MISSING_OVERRIDE + or "volumes" in overrides + or "volume_mounts" in overrides + ) + if not overrides_shared_memory: + return translated + + size_limit = ( + _shared_memory_size_limit + if requested_size is _MISSING_OVERRIDE + else _normalize_shared_memory_size_limit(requested_size) + ) + configured_volumes = overrides.get("volumes", _MISSING_OVERRIDE) + configured_mounts = overrides.get("volume_mounts", _MISSING_OVERRIDE) + overrides["volumes"] = _profile_volumes_override(configured_volumes, size_limit) + overrides["volume_mounts"] = _profile_volume_mounts_override(configured_mounts) + return translated + + def _get_profile_groups(auth_state): """Resolve the user's full Keycloak group list for profile gating. @@ -417,7 +540,7 @@ def _filter_profiles(profiles, groups, username, keycloak_profile_slugs=()): ) continue clean = {k: v for k, v in profile.items() if k not in _PROFILE_GATING_KEYS} - visible.append(clean) + visible.append(_translate_profile_shared_memory(clean)) return visible diff --git a/docs/src/content/docs/server-profiles.md b/docs/src/content/docs/server-profiles.md index 6c9c2a8..dd674c3 100644 --- a/docs/src/content/docs/server-profiles.md +++ b/docs/src/content/docs/server-profiles.md @@ -48,6 +48,37 @@ satisfy leaves the server `Pending` forever with no message in the UI. `kubespawner_override` accepts any KubeSpawner trait — `node_selector`, `image`, `extra_resource_limits`, `tolerations`, `environment`, and the rest. +## Shared memory + +The chart mounts a memory-backed `emptyDir` at `/dev/shm` in every singleuser pod. +The chart-wide default is controlled by `singleuser.sharedMemory`: + +```yaml +singleuser: + sharedMemory: + enabled: true + sizeLimit: 8Gi +``` + +Profiles inherit that size. Use the chart-specific `shm_size_limit` override when a +larger profile needs a different limit: + +```yaml +jupyterhub: + custom: + profiles: + - slug: gpu-instance + display_name: "GPU Instance" + kubespawner_override: + mem_limit: "32G" + shm_size_limit: "16Gi" +``` + +`sizeLimit` caps tmpfs consumption; it does not reserve memory. Pages written to +`/dev/shm` count against the pod's memory cgroup, so leave enough memory for the +notebook and its worker processes. Ray commonly targets about 30% of available +memory for its object store. + ## Image choices within a profile `profile_options` adds a second dropdown under the selected profile: diff --git a/docs/src/content/docs/values-reference.md b/docs/src/content/docs/values-reference.md index 64b0d8a..84f5d9b 100644 --- a/docs/src/content/docs/values-reference.md +++ b/docs/src/content/docs/values-reference.md @@ -80,6 +80,8 @@ Not to be confused with `jupyterhub.singleuser`, which is the upstream passthrou | Field | Default | What it does | |---|---|---| +| `singleuser.sharedMemory.enabled` | `true` | Mount a memory-backed `emptyDir` at `/dev/shm` in singleuser pods. | +| `singleuser.sharedMemory.sizeLimit` | `8Gi` | Maximum tmpfs consumption; used pages count against the pod memory limit. | | `singleuser.networkPolicy.allowEgressToGateway` | `true` | Renders a NetworkPolicy letting user pods reach the Envoy Gateway pod. | | `singleuser.networkPolicy.gatewayNamespace` | `envoy-gateway-system` | Where the gateway runs. | | `singleuser.networkPolicy.gatewayName` | `nebari-gateway` | Gateway name, matched on `gateway.envoyproxy.io/owning-gateway-name`. | @@ -90,6 +92,13 @@ proxy pod IP *before* the subchart's pod-level policy is evaluated — without i cannot reach `https:///services/japps` or the Nebi host. Kubernetes unions egress rules across policies selecting the same pod, so it is harmless where it is not needed. +Profiles inherit the chart-wide shared-memory size. Set +`kubespawner_override.shm_size_limit` on a profile to replace only that profile's +limit. Setting `singleuser.sharedMemory.enabled: false` disables the mount for all +profiles. The size limit caps tmpfs usage but does not reserve memory; only pages +written to `/dev/shm` count against the pod's memory cgroup. Keep the pod memory +limit large enough for both shared memory and the notebook processes. + ## `singleuserCuller` In-pod idle culling, separate from the hub-level `jupyterhub.cull`. This one fires even when diff --git a/templates/hub-config.yaml b/templates/hub-config.yaml index 7a3ebc2..fe8a4cc 100644 --- a/templates/hub-config.yaml +++ b/templates/hub-config.yaml @@ -54,6 +54,11 @@ data: # both. Deployer override via jupyterhub.custom.shared-storage-enabled # still wins via z2jh. "shared-storage-enabled": {{ ternary "True" "False" .Values.sharedStorage.enabled }}, + # Shared-memory defaults are chart-level values because the spawner + # owns the volume list. Profile-specific size overrides are translated + # in 01-spawner.py before KubeSpawner applies them. + "shared-memory-enabled": {{ ternary "True" "False" .Values.singleuser.sharedMemory.enabled }}, + "shared-memory-size-limit": {{ .Values.singleuser.sharedMemory.sizeLimit | quote }}, } diff --git a/tests/e2e/test_shared_memory.py b/tests/e2e/test_shared_memory.py new file mode 100644 index 0000000..df47e23 --- /dev/null +++ b/tests/e2e/test_shared_memory.py @@ -0,0 +1,63 @@ +"""Live singleuser shared-memory verification.""" + +import json + +from _process import kctl_out + +EIGHT_GIBIBYTES = 8 * 1024**3 +SHARED_MEMORY_PROBE_BYTES = 128 * 1024**2 +SHARED_MEMORY_PROBE = f""" +from multiprocessing import shared_memory + +size = {SHARED_MEMORY_PROBE_BYTES} +chunk = b"\\x01" * (1024**2) +segment = shared_memory.SharedMemory(create=True, size=size) +try: + for offset in range(0, size, len(chunk)): + segment.buf[offset : offset + len(chunk)] = chunk + print(len(segment.buf)) +finally: + segment.close() + segment.unlink() +""".strip() + + +def _get_pod(user): + returncode, pod_json, error = kctl_out("get", "pod", user.pod, "-o", "json") + assert returncode == 0, error + return json.loads(pod_json) + + +def _shared_memory_capacity(user): + returncode, output = user.exec( + "python", + "-c", + "import os; s = os.statvfs('/dev/shm'); print(s.f_frsize * s.f_blocks)", + ) + assert returncode == 0, output + return int(output) + + +def _write_shared_memory_above_runtime_default(user): + returncode, output = user.exec("python", "-c", SHARED_MEMORY_PROBE) + assert returncode == 0, output + assert output.splitlines()[-1] == str(SHARED_MEMORY_PROBE_BYTES) + + +def test_singleuser_has_memory_backed_shared_memory(spawn_user): + user = spawn_user("alice-data") + pod = _get_pod(user) + + dshm = next(volume for volume in pod["spec"]["volumes"] if volume["name"] == "dshm") + assert dshm["emptyDir"] == {"medium": "Memory", "sizeLimit": "8Gi"} + + notebook = next( + container + for container in pod["spec"]["containers"] + if container["name"] == "notebook" + ) + mount = next(item for item in notebook["volumeMounts"] if item["name"] == "dshm") + assert mount["mountPath"] == "/dev/shm" + + assert _shared_memory_capacity(user) == EIGHT_GIBIBYTES + _write_shared_memory_above_runtime_default(user) diff --git a/tests/unit/test_chart_derived.py b/tests/unit/test_chart_derived.py index fe94183..6d62913 100644 --- a/tests/unit/test_chart_derived.py +++ b/tests/unit/test_chart_derived.py @@ -148,3 +148,10 @@ def test_get_chart_config_explicit_override_wins(rendered_chart_derived): ) got = ns["get_chart_config"]("external-url") assert got == "explicit.example.com" + + +def test_shared_memory_defaults_are_available_to_spawner(rendered_chart_derived): + ns = _exec_chart_derived(rendered_chart_derived, z2jh_values={}) + + assert ns["get_chart_config"]("shared-memory-enabled") is True + assert ns["get_chart_config"]("shared-memory-size-limit") == "8Gi" diff --git a/tests/unit/test_spawner_shared_memory.py b/tests/unit/test_spawner_shared_memory.py new file mode 100644 index 0000000..6a5e10b --- /dev/null +++ b/tests/unit/test_spawner_shared_memory.py @@ -0,0 +1,214 @@ +"""Regression tests for singleuser ``/dev/shm`` configuration.""" + +from __future__ import annotations + +import copy +import sys +import types +from pathlib import Path + +import pytest +import yaml +from kubespawner import KubeSpawner + +sys.modules.setdefault("z2jh", types.ModuleType("z2jh")) + +from conftest import FakeConfig, load_config_module + +REPO_ROOT = Path(__file__).resolve().parents[2] +DSHM_NAME = "dshm" +DSHM_PATH = "/dev/shm" + + +def _load(values=None): + values = values or {} + z2jh = sys.modules["z2jh"] + previous = getattr(z2jh, "get_config", None) + z2jh.get_config = lambda key, default=None: values.get(key, default) + try: + config = FakeConfig() + module = load_config_module("01-spawner.py", inject_c=config) + finally: + if previous is None: + delattr(z2jh, "get_config") + else: + z2jh.get_config = previous + return module, config + + +def _named(entries, name): + return next((entry for entry in entries if entry.get("name") == name), None) + + +def _count(entries, key, value): + return sum(entry.get(key) == value for entry in entries) + + +def test_values_enable_eight_gibibytes_by_default(): + values = yaml.safe_load((REPO_ROOT / "values.yaml").read_text()) + + assert values["singleuser"]["sharedMemory"] == { + "enabled": True, + "sizeLimit": "8Gi", + } + + +def test_global_default_adds_memory_backed_volume_and_mount(): + _, config = _load() + + volume = _named(config.KubeSpawner.volumes, DSHM_NAME) + mount = _named(config.KubeSpawner.volume_mounts, DSHM_NAME) + + assert volume == { + "name": DSHM_NAME, + "emptyDir": {"medium": "Memory", "sizeLimit": "8Gi"}, + } + assert mount == {"name": DSHM_NAME, "mountPath": DSHM_PATH} + assert _named(config.KubeSpawner.volumes, "home") is not None + assert _named(config.KubeSpawner.volume_mounts, "home") is not None + + +def test_standard_extra_volumes_and_mounts_are_preserved(): + _, config = _load( + { + "singleuser.extraVolumes": [ + {"name": "scratch", "emptyDir": {}}, + ], + "singleuser.extraVolumeMounts": [ + {"name": "scratch", "mountPath": "/scratch"}, + ], + } + ) + + assert _named(config.KubeSpawner.volumes, "scratch") is not None + assert _named(config.KubeSpawner.volume_mounts, "scratch") is not None + assert _named(config.KubeSpawner.volumes, DSHM_NAME) is not None + + +def test_disabled_global_setting_adds_no_shared_memory_entries(): + _, config = _load({"custom.shared-memory-enabled": False}) + + assert _named(config.KubeSpawner.volumes, DSHM_NAME) is None + assert _named(config.KubeSpawner.volume_mounts, DSHM_NAME) is None + + +def test_profile_override_is_translated_without_mutating_input(): + module, _ = _load() + profile = { + "slug": "gpu", + "display_name": "GPU", + "kubespawner_override": { + "image": "example.invalid/notebook:test", + "shm_size_limit": "16Gi", + }, + } + original = copy.deepcopy(profile) + + visible = module._filter_profiles([profile], groups=[], username="alice") + overrides = visible[0]["kubespawner_override"] + + assert profile == original + assert "shm_size_limit" not in overrides + assert overrides["image"] == "example.invalid/notebook:test" + + spawner = types.SimpleNamespace( + volumes=[{"name": "home"}], + volume_mounts=[{"name": "home", "mountPath": "/home/jovyan"}], + ) + volumes = overrides["volumes"](spawner) + mounts = overrides["volume_mounts"](spawner) + + assert _named(volumes, "home") is not None + assert _named(mounts, "home") is not None + assert _named(volumes, DSHM_NAME)["emptyDir"] == { + "medium": "Memory", + "sizeLimit": "16Gi", + } + assert _named(mounts, DSHM_NAME)["mountPath"] == DSHM_PATH + + +def test_profile_volume_overrides_preserve_global_shared_memory(): + module, _ = _load() + profile = { + "slug": "scratch", + "display_name": "Scratch storage", + "kubespawner_override": { + "volumes": [{"name": "scratch", "emptyDir": {}}], + "volume_mounts": [{"name": "scratch", "mountPath": "/scratch"}], + }, + } + + overrides = module._filter_profiles([profile], groups=[], username="alice")[0][ + "kubespawner_override" + ] + spawner = types.SimpleNamespace(volumes=[], volume_mounts=[]) + + volumes = overrides["volumes"](spawner) + mounts = overrides["volume_mounts"](spawner) + + assert _named(volumes, "scratch") is not None + assert _named(mounts, "scratch") is not None + assert _named(volumes, DSHM_NAME)["emptyDir"]["sizeLimit"] == "8Gi" + assert _named(mounts, DSHM_NAME)["mountPath"] == DSHM_PATH + + +def test_profile_override_replaces_conflicts_without_duplicates(): + module, _ = _load() + profile = { + "slug": "large", + "display_name": "Large", + "kubespawner_override": {"shm_size_limit": "12Gi"}, + } + overrides = module._filter_profiles([profile], groups=[], username="alice")[0][ + "kubespawner_override" + ] + spawner = types.SimpleNamespace( + volumes=[ + {"name": DSHM_NAME, "emptyDir": {"medium": "Memory", "sizeLimit": "1Gi"}}, + ], + volume_mounts=[ + {"name": "legacy-shm", "mountPath": DSHM_PATH}, + ], + log=types.SimpleNamespace(debug=lambda *args: None), + ) + + KubeSpawner._apply_overrides(spawner, overrides) + + assert _count(spawner.volumes, "name", DSHM_NAME) == 1 + assert _named(spawner.volumes, DSHM_NAME)["emptyDir"]["sizeLimit"] == "12Gi" + assert _count(spawner.volume_mounts, "mountPath", DSHM_PATH) == 1 + assert _named(spawner.volume_mounts, DSHM_NAME) is not None + + # JupyterHub and KubeSpawner can each apply user options during one spawn. + # Reapplying the callable must update, not duplicate, the generated entries. + KubeSpawner._apply_overrides(spawner, overrides) + + assert _count(spawner.volumes, "name", DSHM_NAME) == 1 + assert _count(spawner.volume_mounts, "mountPath", DSHM_PATH) == 1 + + +def test_disabled_setting_strips_profile_pseudo_trait(): + module, _ = _load({"custom.shared-memory-enabled": False}) + profile = { + "slug": "gpu", + "display_name": "GPU", + "kubespawner_override": {"shm_size_limit": "16Gi"}, + } + + visible = module._filter_profiles([profile], groups=[], username="alice") + + assert "shm_size_limit" not in visible[0]["kubespawner_override"] + assert "volumes" not in visible[0]["kubespawner_override"] + assert "volume_mounts" not in visible[0]["kubespawner_override"] + + +def test_profile_override_rejects_empty_size_limit(): + module, _ = _load() + profile = { + "slug": "gpu", + "display_name": "GPU", + "kubespawner_override": {"shm_size_limit": ""}, + } + + with pytest.raises(ValueError, match="must be a non-empty string"): + module._filter_profiles([profile], groups=[], username="alice") diff --git a/values.yaml b/values.yaml index d6a549c..b789694 100644 --- a/values.yaml +++ b/values.yaml @@ -145,6 +145,16 @@ nebariapp: # NetworkPolicy and unioned with the subchart's policy (Kubernetes # NetworkPolicy semantics). singleuser: + # Mount a memory-backed emptyDir at /dev/shm in every JupyterLab pod. This + # avoids the container runtime's 64 MiB default, which can make Ray fall back + # to disk and can crash multiprocessing PyTorch DataLoader workers. + sharedMemory: + enabled: true + # This is a consumption cap, not a reservation. Used tmpfs pages count + # against the pod's memory limit. Size it for the workload and keep total + # pod memory high enough for both shared memory and application processes. + # Ray commonly targets about 30% of available memory for its object store. + sizeLimit: "8Gi" networkPolicy: # Lets singleuser pods reach the Nebari gateway pod (Envoy Gateway proxy) # in its own namespace. Required on Hetzner k3s + any cluster where @@ -493,6 +503,8 @@ jupyterhub: # kubespawner_override: # extra_resource_limits: # nvidia.com/gpu: 1 + # # Optional per-profile override for the /dev/shm emptyDir above. + # shm_size_limit: "16Gi" # NOTE: when bumping singleuser.image.tag below, also bump — in EACH # profile — the outer ``kubespawner_override.image``, the ``image: ...`` # line inside profile_options.image.choices.default, and that choice's From 0258ce9c12770410ecafc9faaaaee3420367e477 Mon Sep 17 00:00:00 2001 From: Keerthirajan Senthilkumar Date: Mon, 9 Nov 2026 13:26:35 -0800 Subject: [PATCH 2/8] fix: render a null shared-memory sizeLimit safely Sprig's quote renders nil as nothing, so `sizeLimit: null` left `"shared-memory-size-limit": ,` in 00-chart-derived.py and the hub failed with a SyntaxError, even with shared memory disabled. Default it to "" like the neighbouring shutdown-no-activity-timeout key. When enabled, the spawner now stops with its own "must be a non-empty string" error; when disabled, the hub loads normally. --- templates/hub-config.yaml | 5 +++-- tests/unit/test_shared_memory_rendering.py | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/templates/hub-config.yaml b/templates/hub-config.yaml index d502113..40c7d35 100644 --- a/templates/hub-config.yaml +++ b/templates/hub-config.yaml @@ -66,9 +66,10 @@ data: "shutdown-no-activity-timeout": {{ .Values.singleuserCuller.server.shutdownNoActivityTimeout | default 0 | quote }}, # Shared-memory defaults are chart-level values because the spawner # owns the volume list. Profile-specific size overrides are translated - # in 01-spawner.py before KubeSpawner applies them. + # in 01-spawner.py before KubeSpawner applies them. `default ""` is the + # same nil-safety as above; the spawner rejects an empty size when enabled. "shared-memory-enabled": {{ ternary "True" "False" .Values.singleuser.sharedMemory.enabled }}, - "shared-memory-size-limit": {{ .Values.singleuser.sharedMemory.sizeLimit | quote }}, + "shared-memory-size-limit": {{ .Values.singleuser.sharedMemory.sizeLimit | default "" | quote }}, } diff --git a/tests/unit/test_shared_memory_rendering.py b/tests/unit/test_shared_memory_rendering.py index 4f09cd0..5226a53 100644 --- a/tests/unit/test_shared_memory_rendering.py +++ b/tests/unit/test_shared_memory_rendering.py @@ -143,6 +143,27 @@ def test_chart_shared_memory_reaches_pod( _assert_shared_memory(pod, expected_size) +def test_null_size_limit_stops_hub_with_clear_error(helm, monkeypatch): + # Sprig's quote renders nil as nothing, which is a syntax error in + # 00-chart-derived.py. The spawner's own validation should report it instead. + source, hub_values = _render_chart( + helm, {"singleuser": {"sharedMemory": {"sizeLimit": None}}} + ) + + with pytest.raises(ValueError, match="must be a non-empty string"): + _load_rendered_config(source, hub_values, monkeypatch) + + +def test_null_size_limit_is_ignored_when_disabled(helm, monkeypatch): + pod = _render_pod( + helm, + monkeypatch, + {"singleuser": {"sharedMemory": {"enabled": False, "sizeLimit": None}}}, + ) + + _assert_shared_memory(pod, None) + + @pytest.mark.parametrize("enabled", [True, False], ids=["enabled", "disabled"]) def test_profile_shared_memory_preserves_gpu_image_variant(helm, monkeypatch, enabled): values = { From 08814a4fc9085fbf8a6fdb65008a48ebb69348f7 Mon Sep 17 00:00:00 2001 From: Keerthirajan Senthilkumar Date: Mon, 9 Nov 2026 13:28:21 -0800 Subject: [PATCH 3/8] fix: check profile shm_size_limit once at load and warn on bad values An invalid per-profile shm_size_limit raised inside _filter_profiles, which runs on every profile-list render. One bad value broke the spawn page and spawns for every user who could see that profile, and the translation and its warnings repeated on each render. Translate profiles once when _profiles is built, next to _resolve_image_variants, and follow that function's rule: a bad value logs a warning naming the profile and falls back to the chart-wide size. Also drop a test for singleuser.extraVolumes, a key 01-spawner.py never reads, and stop a test comment from claiming when overrides are reapplied. --- config/jupyterhub/01-spawner.py | 36 ++++++--- docs/src/content/docs/server-profiles.md | 3 + tests/unit/test_spawner_shared_memory.py | 95 ++++++++++++++---------- 3 files changed, 85 insertions(+), 49 deletions(-) diff --git a/config/jupyterhub/01-spawner.py b/config/jupyterhub/01-spawner.py index d65d175..df855bb 100644 --- a/config/jupyterhub/01-spawner.py +++ b/config/jupyterhub/01-spawner.py @@ -457,26 +457,47 @@ def _setup_trust_bundle(spawner): # code changes. Empty list = no profile selector (single-instance mode). # Keys used only for group gating; KubeSpawner must never see them. They are # stripped per user in _filter_profiles because gating is a per-user decision. -# ``image-variant`` is the other chart-only key — it is stripped once at load +# ``image-variant`` is another chart-only key — it is stripped once at load # in _resolve_image_variants because its effect (image injection) is the same # for every user and jhub-apps reads the resolved list too. A future custom key # belongs in whichever of the two matches how it is evaluated. _PROFILE_GATING_KEYS = ("access", "groups", "users") +def _profile_shared_memory_size(name, requested_size): + """Return a profile's valid size limit, or the chart-wide one.""" + if requested_size is _MISSING_OVERRIDE: + return _shared_memory_size_limit + try: + return _normalize_shared_memory_size_limit(requested_size) + except ValueError: + log.warning( + "profiles: %r has shm_size_limit %r, expected a non-empty string; " + "using the chart-wide %s", + name, requested_size, _shared_memory_size_limit, + ) + return _shared_memory_size_limit + + def _translate_profile_shared_memory(profile): - """Translate the chart-owned profile key into valid KubeSpawner traits.""" + """Translate the chart-owned ``shm_size_limit`` into KubeSpawner traits. + + Like ``image-variant``, this runs once at load because the result is the + same for every user. A bad size only warns and falls back to the + chart-wide size, because raising here would stop the hub for every user. + """ translated = copy.deepcopy(profile) overrides = translated.get("kubespawner_override") if not isinstance(overrides, dict): return translated + name = translated.get("slug") or translated.get("display_name") requested_size = overrides.pop("shm_size_limit", _MISSING_OVERRIDE) if not _shared_memory_enabled: if requested_size is not _MISSING_OVERRIDE: log.warning( "profiles: ignoring shm_size_limit for %r because shared memory is disabled", - translated.get("slug") or translated.get("display_name"), + name, ) return translated @@ -488,11 +509,7 @@ def _translate_profile_shared_memory(profile): if not overrides_shared_memory: return translated - size_limit = ( - _shared_memory_size_limit - if requested_size is _MISSING_OVERRIDE - else _normalize_shared_memory_size_limit(requested_size) - ) + size_limit = _profile_shared_memory_size(name, requested_size) configured_volumes = overrides.get("volumes", _MISSING_OVERRIDE) configured_mounts = overrides.get("volume_mounts", _MISSING_OVERRIDE) overrides["volumes"] = _profile_volumes_override(configured_volumes, size_limit) @@ -583,7 +600,7 @@ def _filter_profiles(profiles, groups, username, keycloak_profile_slugs=()): ) continue clean = {k: v for k, v in profile.items() if k not in _PROFILE_GATING_KEYS} - visible.append(_translate_profile_shared_memory(clean)) + visible.append(clean) return visible @@ -712,6 +729,7 @@ def _resolve_image_variants(profiles, base_name, base_tag, overrides): get_config("singleuser.image.tag", ""), get_config("custom.image-variants", {}), ) +_profiles = [_translate_profile_shared_memory(profile) for profile in _profiles] if _profiles: c.KubeSpawner.profile_list = _render_profile_list log.info( diff --git a/docs/src/content/docs/server-profiles.md b/docs/src/content/docs/server-profiles.md index e27c7fa..44a7ae6 100644 --- a/docs/src/content/docs/server-profiles.md +++ b/docs/src/content/docs/server-profiles.md @@ -74,6 +74,9 @@ jupyterhub: shm_size_limit: "16Gi" ``` +If a profile's `shm_size_limit` is empty or not a string, the hub logs a warning +and that profile uses the chart-wide size. + `sizeLimit` caps tmpfs consumption; it does not reserve memory. Pages written to `/dev/shm` count against the writing container's memory limit, so leave enough memory for the notebook and its worker processes. The effective filesystem diff --git a/tests/unit/test_spawner_shared_memory.py b/tests/unit/test_spawner_shared_memory.py index be745a6..daaaee4 100644 --- a/tests/unit/test_spawner_shared_memory.py +++ b/tests/unit/test_spawner_shared_memory.py @@ -2,10 +2,12 @@ from __future__ import annotations +import asyncio import copy import sys import types from pathlib import Path +from unittest.mock import AsyncMock import pytest import yaml @@ -36,6 +38,11 @@ def _load(values=None): return module, config +def _load_profile(profile, values=None): + module, _ = _load({**(values or {}), "custom.profiles": [profile]}) + return module._profiles[0] + + def _named(entries, name): return next((entry for entry in entries if entry.get("name") == name), None) @@ -68,23 +75,6 @@ def test_global_default_adds_memory_backed_volume_and_mount(): assert _named(config.KubeSpawner.volume_mounts, "home") is not None -def test_unsupported_extra_volume_keys_do_not_change_storage(): - _, config = _load( - { - "singleuser.extraVolumes": [ - {"name": "scratch", "emptyDir": {}}, - ], - "singleuser.extraVolumeMounts": [ - {"name": "scratch", "mountPath": "/scratch"}, - ], - } - ) - - assert _named(config.KubeSpawner.volumes, "scratch") is None - assert _named(config.KubeSpawner.volume_mounts, "scratch") is None - assert _named(config.KubeSpawner.volumes, DSHM_NAME) is not None - - def test_disabled_global_setting_adds_no_shared_memory_entries(): _, config = _load({"custom.shared-memory-enabled": False}) @@ -140,8 +130,7 @@ def test_profiles_without_storage_overrides_are_unchanged(profile): assert module._translate_profile_shared_memory(profile) == profile -def test_profile_override_is_translated_without_mutating_input(): - module, _ = _load() +def test_profile_override_is_translated_at_load_without_mutating_input(): profile = { "slug": "gpu", "display_name": "GPU", @@ -152,8 +141,7 @@ def test_profile_override_is_translated_without_mutating_input(): } original = copy.deepcopy(profile) - visible = module._filter_profiles([profile], groups=[], username="alice") - overrides = visible[0]["kubespawner_override"] + overrides = _load_profile(profile)["kubespawner_override"] assert profile == original assert "shm_size_limit" not in overrides @@ -176,7 +164,6 @@ def test_profile_override_is_translated_without_mutating_input(): def test_profile_volume_overrides_preserve_global_shared_memory(): - module, _ = _load() profile = { "slug": "scratch", "display_name": "Scratch storage", @@ -186,9 +173,7 @@ def test_profile_volume_overrides_preserve_global_shared_memory(): }, } - overrides = module._filter_profiles([profile], groups=[], username="alice")[0][ - "kubespawner_override" - ] + overrides = _load_profile(profile)["kubespawner_override"] spawner = types.SimpleNamespace(volumes=[], volume_mounts=[]) volumes = overrides["volumes"](spawner) @@ -201,15 +186,12 @@ def test_profile_volume_overrides_preserve_global_shared_memory(): def test_profile_override_replaces_conflicts_without_duplicates(): - module, _ = _load() profile = { "slug": "large", "display_name": "Large", "kubespawner_override": {"shm_size_limit": "12Gi"}, } - overrides = module._filter_profiles([profile], groups=[], username="alice")[0][ - "kubespawner_override" - ] + overrides = _load_profile(profile)["kubespawner_override"] spawner = types.SimpleNamespace( volumes=[ {"name": DSHM_NAME, "emptyDir": {"medium": "Memory", "sizeLimit": "1Gi"}}, @@ -227,8 +209,8 @@ def test_profile_override_replaces_conflicts_without_duplicates(): assert _count(spawner.volume_mounts, "mountPath", DSHM_PATH) == 1 assert _named(spawner.volume_mounts, DSHM_NAME) is not None - # JupyterHub and KubeSpawner can each apply user options during one spawn. - # Reapplying the callable must update, not duplicate, the generated entries. + # Applying the same overrides to this spawner again must update, not + # duplicate, the generated entries. KubeSpawner._apply_overrides(spawner, overrides) assert _count(spawner.volumes, "name", DSHM_NAME) == 1 @@ -236,18 +218,19 @@ def test_profile_override_replaces_conflicts_without_duplicates(): def test_disabled_setting_strips_profile_pseudo_trait(): - module, _ = _load({"custom.shared-memory-enabled": False}) profile = { "slug": "gpu", "display_name": "GPU", "kubespawner_override": {"shm_size_limit": "16Gi"}, } - visible = module._filter_profiles([profile], groups=[], username="alice") + overrides = _load_profile(profile, {"custom.shared-memory-enabled": False})[ + "kubespawner_override" + ] - assert "shm_size_limit" not in visible[0]["kubespawner_override"] - assert "volumes" not in visible[0]["kubespawner_override"] - assert "volume_mounts" not in visible[0]["kubespawner_override"] + assert "shm_size_limit" not in overrides + assert "volumes" not in overrides + assert "volume_mounts" not in overrides @pytest.mark.parametrize("include_size", [True, False]) @@ -308,13 +291,45 @@ def configured_mounts(current): @pytest.mark.parametrize("size", ["", " ", None, 8]) -def test_profile_override_rejects_invalid_size_type_or_empty_string(size): - module, _ = _load() +def test_invalid_profile_size_warns_and_uses_chart_size(size, caplog): profile = { "slug": "gpu", "display_name": "GPU", "kubespawner_override": {"shm_size_limit": size}, } - with pytest.raises(ValueError, match="must be a non-empty string"): - module._filter_profiles([profile], groups=[], username="alice") + with caplog.at_level("WARNING"): + overrides = _load_profile(profile)["kubespawner_override"] + spawner = types.SimpleNamespace(volumes=[], volume_mounts=[]) + + assert "shm_size_limit" not in overrides + assert _named(overrides["volumes"](spawner), DSHM_NAME)["emptyDir"] == { + "medium": "Memory", + "sizeLimit": "8Gi", + } + warnings = [r.getMessage() for r in caplog.records if r.levelname == "WARNING"] + assert any("'gpu'" in w and "shm_size_limit" in w for w in warnings), warnings + + +def test_invalid_profile_size_does_not_break_profile_list(caplog): + profiles = [ + { + "slug": "gpu", + "display_name": "GPU", + "kubespawner_override": {"shm_size_limit": ""}, + }, + {"slug": "cpu", "display_name": "CPU"}, + ] + module, _ = _load({"custom.profiles": profiles}) + spawner = types.SimpleNamespace( + user=types.SimpleNamespace(get_auth_state=AsyncMock(return_value={})) + ) + caplog.clear() + + # The size is checked once at load, not again on every profile-list render. + with caplog.at_level("WARNING"): + for _ in range(2): + visible = asyncio.run(module._render_profile_list(spawner)) + assert [profile["slug"] for profile in visible] == ["gpu", "cpu"] + + assert not [r for r in caplog.records if r.levelname == "WARNING"] From f5545530c365f96a2bba04823cc272a7df818ad7 Mon Sep 17 00:00:00 2001 From: Keerthirajan Senthilkumar Date: Mon, 9 Nov 2026 13:29:14 -0800 Subject: [PATCH 4/8] refactor: give the shared-memory spawner code its own section The shared-memory constants, helpers and settings sat between the Storage comment and the storage code it explains. Move them into a "Shared memory" section after the base volume lists, next to the append that uses them. Build the dshm volume and mount in one place so the base append and the profile overrides share the same definition. No behavior change. --- config/jupyterhub/01-spawner.py | 120 +++++++++++++++++--------------- 1 file changed, 62 insertions(+), 58 deletions(-) diff --git a/config/jupyterhub/01-spawner.py b/config/jupyterhub/01-spawner.py index df855bb..ea0ca0a 100644 --- a/config/jupyterhub/01-spawner.py +++ b/config/jupyterhub/01-spawner.py @@ -34,7 +34,54 @@ # KubeSpawner (escaped slug) vs base Spawner traits like notebook_dir (raw username), # causing a path mismatch when usernames contain special characters (e.g. emails). # Each user still gets an isolated PVC via claim-{username}. +c.KubeSpawner.storage_pvc_ensure = True +c.KubeSpawner.storage_capacity = get_config("custom.storage-capacity", "20Gi") +c.KubeSpawner.storage_access_modes = ["ReadWriteOnce"] +# KubeSpawner 7 defaults to slug_scheme="safe". Keep the old escaped slug +# behavior until PVC names and affinity labels are intentionally migrated. +c.KubeSpawner.slug_scheme = "escape" +# Without this override, KubeSpawner's default template is +# `claim-{username}--{servername}`, so for jhub-apps named servers it ensures +# a per-server PVC — while the `volumes` block below mounts the per-user +# `claim-{username}`. Users with a pre-existing per-user PVC (legacy +# JupyterLab launch) survived this mismatch; fresh users hit +# FailedScheduling because the per-user PVC is never auto-created. Forcing +# the template to `{username}` makes ensure + mount converge on the same +# RWO claim, which the pod-affinity rule below keeps to a single node. +c.KubeSpawner.pvc_name_template = "claim-{username}" +c.KubeSpawner.volumes = [ + { + "name": "home", + "persistentVolumeClaim": { + "claimName": "claim-{username}", + }, + }, + { + "name": "singleuser-config", + "configMap": { + "name": "__SINGLEUSER_CONFIG_CM__", # replaced by Helm template + }, + }, +] +c.KubeSpawner.volume_mounts = [ + { + "name": "home", + "mountPath": "/home/jovyan", + }, + { + "name": "singleuser-config", + "mountPath": "/etc/jupyter/jupyter_server_config.py", + "subPath": "jupyter_server_config.py", + }, +] +# --------------------------------------------------------------------------- +# Shared memory (/dev/shm) +# --------------------------------------------------------------------------- +# Container runtimes default /dev/shm to 64 MiB, which is too small for PyTorch +# DataLoader workers and Ray's object store. Mount a memory-backed emptyDir +# instead. Profiles can resize it with the chart-only ``shm_size_limit`` key, +# translated in _translate_profile_shared_memory. _DSHM_NAME = "dshm" _DSHM_PATH = "/dev/shm" _MISSING_OVERRIDE = object() @@ -47,6 +94,17 @@ def _normalize_shared_memory_size_limit(value): return value.strip() +def _shared_memory_volume(size_limit): + return { + "name": _DSHM_NAME, + "emptyDir": {"medium": "Memory", "sizeLimit": size_limit}, + } + + +def _shared_memory_mount(): + return {"name": _DSHM_NAME, "mountPath": _DSHM_PATH} + + def _upsert_named(entries, addition): """Return entries with exactly one item bearing ``addition``'s name.""" retained = [ @@ -58,13 +116,7 @@ def _upsert_named(entries, addition): def _with_shared_memory_volume(volumes, size_limit): - return _upsert_named( - volumes, - { - "name": _DSHM_NAME, - "emptyDir": {"medium": "Memory", "sizeLimit": size_limit}, - }, - ) + return _upsert_named(volumes, _shared_memory_volume(size_limit)) def _with_shared_memory_mount(volume_mounts): @@ -73,7 +125,7 @@ def _with_shared_memory_mount(volume_mounts): for mount in list(volume_mounts or []) if mount.get("name") != _DSHM_NAME and mount.get("mountPath") != _DSHM_PATH ] - return [*retained, {"name": _DSHM_NAME, "mountPath": _DSHM_PATH}] + return [*retained, _shared_memory_mount()] def _resolve_list_override(spawner, trait_name, configured): @@ -106,56 +158,8 @@ def apply(spawner): _shared_memory_size_limit = _normalize_shared_memory_size_limit( _shared_memory_size_limit ) - -c.KubeSpawner.storage_pvc_ensure = True -c.KubeSpawner.storage_capacity = get_config("custom.storage-capacity", "20Gi") -c.KubeSpawner.storage_access_modes = ["ReadWriteOnce"] -# KubeSpawner 7 defaults to slug_scheme="safe". Keep the old escaped slug -# behavior until PVC names and affinity labels are intentionally migrated. -c.KubeSpawner.slug_scheme = "escape" -# Without this override, KubeSpawner's default template is -# `claim-{username}--{servername}`, so for jhub-apps named servers it ensures -# a per-server PVC — while the `volumes` block below mounts the per-user -# `claim-{username}`. Users with a pre-existing per-user PVC (legacy -# JupyterLab launch) survived this mismatch; fresh users hit -# FailedScheduling because the per-user PVC is never auto-created. Forcing -# the template to `{username}` makes ensure + mount converge on the same -# RWO claim, which the pod-affinity rule below keeps to a single node. -c.KubeSpawner.pvc_name_template = "claim-{username}" -c.KubeSpawner.volumes = [ - { - "name": "home", - "persistentVolumeClaim": { - "claimName": "claim-{username}", - }, - }, - { - "name": "singleuser-config", - "configMap": { - "name": "__SINGLEUSER_CONFIG_CM__", # replaced by Helm template - }, - }, -] -c.KubeSpawner.volume_mounts = [ - { - "name": "home", - "mountPath": "/home/jovyan", - }, - { - "name": "singleuser-config", - "mountPath": "/etc/jupyter/jupyter_server_config.py", - "subPath": "jupyter_server_config.py", - }, -] - -if _shared_memory_enabled: - c.KubeSpawner.volumes.append( - { - "name": _DSHM_NAME, - "emptyDir": {"medium": "Memory", "sizeLimit": _shared_memory_size_limit}, - } - ) - c.KubeSpawner.volume_mounts.append({"name": _DSHM_NAME, "mountPath": _DSHM_PATH}) + c.KubeSpawner.volumes.append(_shared_memory_volume(_shared_memory_size_limit)) + c.KubeSpawner.volume_mounts.append(_shared_memory_mount()) # --------------------------------------------------------------------------- # Admin-provisioned nebi config (OCI registries, default-registry seed flag). From 519ff7dcd33b748a749b5695dbd5d80460f075bf Mon Sep 17 00:00:00 2001 From: Keerthirajan Senthilkumar Date: Mon, 9 Nov 2026 13:29:37 -0800 Subject: [PATCH 5/8] docs: tidy the shared-memory values reference List sharedMemory after networkPolicy in values.yaml so the block's network-access header stays next to the entries it describes, and replace the long values-reference paragraph with a link to the Shared memory section of server-profiles.md, which already covers it. --- docs/src/content/docs/values-reference.md | 13 +++--------- values.yaml | 24 +++++++++++------------ 2 files changed, 15 insertions(+), 22 deletions(-) diff --git a/docs/src/content/docs/values-reference.md b/docs/src/content/docs/values-reference.md index 18f881d..eb9ae12 100644 --- a/docs/src/content/docs/values-reference.md +++ b/docs/src/content/docs/values-reference.md @@ -104,16 +104,9 @@ proxy pod IP *before* the subchart's pod-level policy is evaluated — without i cannot reach `https:///services/japps` or the Nebi host. Kubernetes unions egress rules across policies selecting the same pod, so it is harmless where it is not needed. -Profiles inherit the chart-wide shared-memory size. Set -`kubespawner_override.shm_size_limit` on a profile to replace only that profile's -limit. Set `singleuser.sharedMemory.enabled: false` to disable the chart-managed -mount and retain the runtime default, or to manage `/dev/shm` through explicit -profile volume overrides. Those overrides remain unchanged when disabled; -`shm_size_limit` is ignored. The size limit caps tmpfs usage but does not reserve -memory; only pages written to `/dev/shm` count against the writing container's -memory limit. Keep that limit large enough for both shared memory and the notebook -processes. Node or pod memory constraints can reduce the effective filesystem -capacity below the configured cap. +Profiles can set their own shared-memory size with `kubespawner_override.shm_size_limit`. +See [Shared memory](/server-profiles/#shared-memory) for how the size counts against +memory limits and how it works with profile volume overrides. ## `singleuserCuller` diff --git a/values.yaml b/values.yaml index 4d94d60..c7fae9c 100644 --- a/values.yaml +++ b/values.yaml @@ -145,18 +145,6 @@ nebariapp: # NetworkPolicy and unioned with the subchart's policy (Kubernetes # NetworkPolicy semantics). singleuser: - # Mount a memory-backed emptyDir at /dev/shm in every JupyterLab pod. This - # avoids the container runtime's 64 MiB default, which can make Ray fall back - # to disk and can crash multiprocessing PyTorch DataLoader workers. - sharedMemory: - # Disable to retain the runtime default or manage /dev/shm through - # explicit profile volume overrides instead of this chart-managed mount. - enabled: true - # This is a consumption cap, not a reservation. Used tmpfs pages count - # against the writing container's memory limit. Leave room for both - # shared memory and application processes within that limit. - # Ray commonly targets about 30% of available memory for its object store. - sizeLimit: "8Gi" networkPolicy: # Lets singleuser pods reach the Nebari gateway pod (Envoy Gateway proxy) # in its own namespace. Required on Hetzner k3s + any cluster where @@ -171,6 +159,18 @@ singleuser: gatewayNamespace: envoy-gateway-system gatewayName: nebari-gateway gatewayPort: 10443 + # Mount a memory-backed emptyDir at /dev/shm in every JupyterLab pod. This + # avoids the container runtime's 64 MiB default, which can make Ray fall back + # to disk and can crash multiprocessing PyTorch DataLoader workers. + sharedMemory: + # Disable to retain the runtime default or manage /dev/shm through + # explicit profile volume overrides instead of this chart-managed mount. + enabled: true + # This is a consumption cap, not a reservation. Used tmpfs pages count + # against the writing container's memory limit. Leave room for both + # shared memory and application processes within that limit. + # Ray commonly targets about 30% of available memory for its object store. + sizeLimit: "8Gi" # ============================================================================= # Singleuser Idle Culler From d8132431bdfc52d5ce86a327eae2ec54e6f11c23 Mon Sep 17 00:00:00 2001 From: Keerthirajan Senthilkumar Date: Mon, 9 Nov 2026 13:59:24 -0800 Subject: [PATCH 6/8] fix: warn and use 8Gi for an invalid chart-wide shared-memory size An empty, null or non-string singleuser.sharedMemory.sizeLimit raised ValueError when 01-spawner.py loaded, which stopped the hub. Other bad deployer values in this file only warn: the code-server idle timeout, _resolve_image_variants, and a profile's shm_size_limit. Do the same for the chart-wide size: log a warning that names singleuser.sharedMemory.sizeLimit and use the chart default of 8Gi. One helper now checks both the chart-wide size and a profile's shm_size_limit, so the two paths follow the same rule. A null sizeLimit is still ignored when shared memory is disabled. --- config/jupyterhub/01-spawner.py | 42 +++++++++++++--------- templates/hub-config.yaml | 3 +- tests/unit/test_shared_memory_rendering.py | 16 +++++---- tests/unit/test_spawner_shared_memory.py | 38 +++++++++++++++++--- 4 files changed, 70 insertions(+), 29 deletions(-) diff --git a/config/jupyterhub/01-spawner.py b/config/jupyterhub/01-spawner.py index ea0ca0a..045fdc9 100644 --- a/config/jupyterhub/01-spawner.py +++ b/config/jupyterhub/01-spawner.py @@ -84,14 +84,22 @@ # translated in _translate_profile_shared_memory. _DSHM_NAME = "dshm" _DSHM_PATH = "/dev/shm" +_DEFAULT_SHM_SIZE_LIMIT = "8Gi" _MISSING_OVERRIDE = object() -def _normalize_shared_memory_size_limit(value): - """Require a non-empty size limit and strip surrounding whitespace.""" - if not isinstance(value, str) or not value.strip(): - raise ValueError("shared-memory sizeLimit must be a non-empty string") - return value.strip() +def _shared_memory_size_or(value, setting, fallback): + """Return ``value`` stripped, or warn and return ``fallback``. + + A bad size only warns, because raising at load would stop the hub. + """ + if isinstance(value, str) and value.strip(): + return value.strip() + log.warning( + "%s is %r, expected a non-empty string; using %s", + setting, value, fallback, + ) + return fallback def _shared_memory_volume(size_limit): @@ -153,10 +161,14 @@ def apply(spawner): _shared_memory_enabled = bool(get_chart_config("shared-memory-enabled", True)) -_shared_memory_size_limit = get_chart_config("shared-memory-size-limit", "8Gi") +_shared_memory_size_limit = get_chart_config( + "shared-memory-size-limit", _DEFAULT_SHM_SIZE_LIMIT +) if _shared_memory_enabled: - _shared_memory_size_limit = _normalize_shared_memory_size_limit( - _shared_memory_size_limit + _shared_memory_size_limit = _shared_memory_size_or( + _shared_memory_size_limit, + "singleuser.sharedMemory.sizeLimit", + _DEFAULT_SHM_SIZE_LIMIT, ) c.KubeSpawner.volumes.append(_shared_memory_volume(_shared_memory_size_limit)) c.KubeSpawner.volume_mounts.append(_shared_memory_mount()) @@ -472,15 +484,11 @@ def _profile_shared_memory_size(name, requested_size): """Return a profile's valid size limit, or the chart-wide one.""" if requested_size is _MISSING_OVERRIDE: return _shared_memory_size_limit - try: - return _normalize_shared_memory_size_limit(requested_size) - except ValueError: - log.warning( - "profiles: %r has shm_size_limit %r, expected a non-empty string; " - "using the chart-wide %s", - name, requested_size, _shared_memory_size_limit, - ) - return _shared_memory_size_limit + return _shared_memory_size_or( + requested_size, + f"profiles: {name!r} shm_size_limit", + _shared_memory_size_limit, + ) def _translate_profile_shared_memory(profile): diff --git a/templates/hub-config.yaml b/templates/hub-config.yaml index 40c7d35..824ed6d 100644 --- a/templates/hub-config.yaml +++ b/templates/hub-config.yaml @@ -67,7 +67,8 @@ data: # Shared-memory defaults are chart-level values because the spawner # owns the volume list. Profile-specific size overrides are translated # in 01-spawner.py before KubeSpawner applies them. `default ""` is the - # same nil-safety as above; the spawner rejects an empty size when enabled. + # same nil-safety as above; when enabled, the spawner warns about an + # empty size and uses 8Gi. "shared-memory-enabled": {{ ternary "True" "False" .Values.singleuser.sharedMemory.enabled }}, "shared-memory-size-limit": {{ .Values.singleuser.sharedMemory.sizeLimit | default "" | quote }}, } diff --git a/tests/unit/test_shared_memory_rendering.py b/tests/unit/test_shared_memory_rendering.py index 5226a53..782e744 100644 --- a/tests/unit/test_shared_memory_rendering.py +++ b/tests/unit/test_shared_memory_rendering.py @@ -143,15 +143,17 @@ def test_chart_shared_memory_reaches_pod( _assert_shared_memory(pod, expected_size) -def test_null_size_limit_stops_hub_with_clear_error(helm, monkeypatch): +def test_null_size_limit_warns_and_uses_chart_default(helm, monkeypatch, caplog): # Sprig's quote renders nil as nothing, which is a syntax error in - # 00-chart-derived.py. The spawner's own validation should report it instead. - source, hub_values = _render_chart( - helm, {"singleuser": {"sharedMemory": {"sizeLimit": None}}} - ) + # 00-chart-derived.py, so the template renders "" and the spawner falls back. + with caplog.at_level("WARNING"): + pod = _render_pod( + helm, monkeypatch, {"singleuser": {"sharedMemory": {"sizeLimit": None}}} + ) - with pytest.raises(ValueError, match="must be a non-empty string"): - _load_rendered_config(source, hub_values, monkeypatch) + _assert_shared_memory(pod, "8Gi") + warnings = [r.getMessage() for r in caplog.records if r.levelname == "WARNING"] + assert any("singleuser.sharedMemory.sizeLimit" in w for w in warnings), warnings def test_null_size_limit_is_ignored_when_disabled(helm, monkeypatch): diff --git a/tests/unit/test_spawner_shared_memory.py b/tests/unit/test_spawner_shared_memory.py index daaaee4..ada32bc 100644 --- a/tests/unit/test_spawner_shared_memory.py +++ b/tests/unit/test_spawner_shared_memory.py @@ -51,6 +51,10 @@ def _count(entries, key, value): return sum(entry.get(key) == value for entry in entries) +def _warnings(caplog): + return [r.getMessage() for r in caplog.records if r.levelname == "WARNING"] + + def test_values_enable_eight_gibibytes_by_default(): values = yaml.safe_load((REPO_ROOT / "values.yaml").read_text()) @@ -106,9 +110,35 @@ def test_chart_storage_is_unchanged(enabled): @pytest.mark.parametrize("size", ["", " ", None, 8]) -def test_global_setting_rejects_invalid_size_type_or_empty_string(size): - with pytest.raises(ValueError, match="must be a non-empty string"): - _load({"custom.shared-memory-size-limit": size}) +def test_invalid_global_size_warns_and_uses_chart_default(size, caplog): + with caplog.at_level("WARNING"): + _, config = _load({"custom.shared-memory-size-limit": size}) + + assert _named(config.KubeSpawner.volumes, DSHM_NAME)["emptyDir"] == { + "medium": "Memory", + "sizeLimit": "8Gi", + } + assert _named(config.KubeSpawner.volume_mounts, DSHM_NAME) is not None + warnings = _warnings(caplog) + assert any("singleuser.sharedMemory.sizeLimit" in w for w in warnings), warnings + + +def test_invalid_global_size_falls_back_for_profiles(): + profile = { + "slug": "scratch", + "display_name": "Scratch storage", + "kubespawner_override": {"volumes": [{"name": "scratch", "emptyDir": {}}]}, + } + + overrides = _load_profile(profile, {"custom.shared-memory-size-limit": ""})[ + "kubespawner_override" + ] + spawner = types.SimpleNamespace(volumes=[], volume_mounts=[]) + + assert _named(overrides["volumes"](spawner), DSHM_NAME)["emptyDir"] == { + "medium": "Memory", + "sizeLimit": "8Gi", + } def test_global_size_is_trimmed(): @@ -307,7 +337,7 @@ def test_invalid_profile_size_warns_and_uses_chart_size(size, caplog): "medium": "Memory", "sizeLimit": "8Gi", } - warnings = [r.getMessage() for r in caplog.records if r.levelname == "WARNING"] + warnings = _warnings(caplog) assert any("'gpu'" in w and "shm_size_limit" in w for w in warnings), warnings From e2c77506b0f8db3191b66484130cc888c0584c7f Mon Sep 17 00:00:00 2001 From: Keerthirajan Senthilkumar Date: Mon, 9 Nov 2026 14:01:17 -0800 Subject: [PATCH 7/8] test: check shm_size_limit warnings and the chart-wide fallback Assert that a disabled chart still warns when a profile sets shm_size_limit, and run the invalid profile size test with a chart-wide size other than 8Gi so it shows the profile falls back to that size rather than the chart default. Also name shm_size_limit and _translate_profile_shared_memory in the comment that lists the chart-only profile keys. --- config/jupyterhub/01-spawner.py | 4 +++- tests/unit/test_spawner_shared_memory.py | 18 ++++++++++++------ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/config/jupyterhub/01-spawner.py b/config/jupyterhub/01-spawner.py index 045fdc9..9951b88 100644 --- a/config/jupyterhub/01-spawner.py +++ b/config/jupyterhub/01-spawner.py @@ -475,7 +475,9 @@ def _setup_trust_bundle(spawner): # stripped per user in _filter_profiles because gating is a per-user decision. # ``image-variant`` is another chart-only key — it is stripped once at load # in _resolve_image_variants because its effect (image injection) is the same -# for every user and jhub-apps reads the resolved list too. A future custom key +# for every user and jhub-apps reads the resolved list too. +# ``shm_size_limit`` is translated once at load in +# _translate_profile_shared_memory for the same reason. A future custom key # belongs in whichever of the two matches how it is evaluated. _PROFILE_GATING_KEYS = ("access", "groups", "users") diff --git a/tests/unit/test_spawner_shared_memory.py b/tests/unit/test_spawner_shared_memory.py index ada32bc..0d9a3ff 100644 --- a/tests/unit/test_spawner_shared_memory.py +++ b/tests/unit/test_spawner_shared_memory.py @@ -247,20 +247,23 @@ def test_profile_override_replaces_conflicts_without_duplicates(): assert _count(spawner.volume_mounts, "mountPath", DSHM_PATH) == 1 -def test_disabled_setting_strips_profile_pseudo_trait(): +def test_disabled_setting_strips_profile_pseudo_trait(caplog): profile = { "slug": "gpu", "display_name": "GPU", "kubespawner_override": {"shm_size_limit": "16Gi"}, } - overrides = _load_profile(profile, {"custom.shared-memory-enabled": False})[ - "kubespawner_override" - ] + with caplog.at_level("WARNING"): + overrides = _load_profile(profile, {"custom.shared-memory-enabled": False})[ + "kubespawner_override" + ] assert "shm_size_limit" not in overrides assert "volumes" not in overrides assert "volume_mounts" not in overrides + warnings = _warnings(caplog) + assert any("'gpu'" in w and "shm_size_limit" in w for w in warnings), warnings @pytest.mark.parametrize("include_size", [True, False]) @@ -329,13 +332,16 @@ def test_invalid_profile_size_warns_and_uses_chart_size(size, caplog): } with caplog.at_level("WARNING"): - overrides = _load_profile(profile)["kubespawner_override"] + overrides = _load_profile( + profile, {"custom.shared-memory-size-limit": "2Gi"} + )["kubespawner_override"] spawner = types.SimpleNamespace(volumes=[], volume_mounts=[]) assert "shm_size_limit" not in overrides + # A non-default chart-wide size shows the fallback is not just 8Gi. assert _named(overrides["volumes"](spawner), DSHM_NAME)["emptyDir"] == { "medium": "Memory", - "sizeLimit": "8Gi", + "sizeLimit": "2Gi", } warnings = _warnings(caplog) assert any("'gpu'" in w and "shm_size_limit" in w for w in warnings), warnings From 19ab643f4b5260abd8b9e76429d34c5e01da8e02 Mon Sep 17 00:00:00 2001 From: Keerthirajan Senthilkumar Date: Mon, 9 Nov 2026 14:12:19 -0800 Subject: [PATCH 8/8] test: check a disabled chart does not warn about a null sizeLimit The chart-wide size is only validated when shared memory is enabled. Assert that a disabled chart with sizeLimit null logs no sizeLimit warning, so moving the validation outside that check fails a test. --- tests/unit/test_shared_memory_rendering.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/tests/unit/test_shared_memory_rendering.py b/tests/unit/test_shared_memory_rendering.py index 782e744..af9459b 100644 --- a/tests/unit/test_shared_memory_rendering.py +++ b/tests/unit/test_shared_memory_rendering.py @@ -156,14 +156,17 @@ def test_null_size_limit_warns_and_uses_chart_default(helm, monkeypatch, caplog) assert any("singleuser.sharedMemory.sizeLimit" in w for w in warnings), warnings -def test_null_size_limit_is_ignored_when_disabled(helm, monkeypatch): - pod = _render_pod( - helm, - monkeypatch, - {"singleuser": {"sharedMemory": {"enabled": False, "sizeLimit": None}}}, - ) +def test_null_size_limit_is_ignored_when_disabled(helm, monkeypatch, caplog): + with caplog.at_level("WARNING"): + pod = _render_pod( + helm, + monkeypatch, + {"singleuser": {"sharedMemory": {"enabled": False, "sizeLimit": None}}}, + ) _assert_shared_memory(pod, None) + warnings = [r.getMessage() for r in caplog.records if r.levelname == "WARNING"] + assert not any("singleuser.sharedMemory.sizeLimit" in w for w in warnings), warnings @pytest.mark.parametrize("enabled", [True, False], ids=["enabled", "disabled"])