Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

fix(planner): honor cgroup memory limits

Léon Avic Simmons677b0c5fd20e
diff --git a/c/doctor.py b/c/doctor.py
index 33a8f1eb..fd58b0c9 100644
--- a/c/doctor.py
+++ b/c/doctor.py
@@ -10,8 +10,8 @@ from pathlib import Path
from family_registry import (FamilyConfigError, PlannerUnsupportedError, UnknownFamilyError,
public_metadata, resolve_model)
-from resource_plan import (GB, SSD_PROBE_PENDING, build_plan, discover_gpus, format_plan,
- memory_available)
+from resource_plan import (GB, SSD_PROBE_PENDING, CgroupError, build_plan, discover_gpus,
+ format_plan, memory_available)
SAFETENSORS_MAX_HEADER = 512 << 20
MODEL_INDEX_MAX_BYTES = SAFETENSORS_MAX_HEADER
@@ -622,7 +622,6 @@ def run_doctor(model, ram_gb=0, context=4096, gpu_indices=None, vram_gb=0, *,
else:
checks.append(_check("engine.binary", "fail", "engine is not built", path=str(engine)))
- available_memory = memory_available() if available_memory is None else available_memory
detected_gpus = discover_gpus() if gpus is None else list(gpus)
linkage = cuda_linkage(engine) if linkage is None else linkage
selected_gpus = detected_gpus
@@ -662,6 +661,9 @@ def run_doctor(model, ram_gb=0, context=4096, gpu_indices=None, vram_gb=0, *,
plan = build_plan(model, ram_gb, context, plan_gpu_indices, plan_vram_gb,
available_memory=available_memory, available_disk=available_disk,
gpus=plan_gpus, kv_slots=kv_slots)
+ # build_plan() owns the single memory probe -- min(host MemAvailable,
+ # finite cgroup headroom); 0 means nothing could measure it (T15).
+ available_memory = plan["memory"]["available_bytes"]
model_info = plan["model"]
checks.append(_check("model.shards", "pass", "safetensors headers are valid",
shards=model_info["shards"], model_bytes=model_info["model_bytes"]))
@@ -712,6 +714,15 @@ def run_doctor(model, ram_gb=0, context=4096, gpu_indices=None, vram_gb=0, *,
checks.append(_check("placement.plan", "skip", str(error)))
checks.append(_check("storage.ssd_probe", "skip",
"probe surfacing requires a family planner"))
+ except CgroupError as error:
+ # A present but malformed, incomplete or unreadable cgroup/procfs input
+ # is a refusal with a reason, not "could not be measured" (T15 A1).
+ checks.append(_check("model.shards", "skip", "shard summary requires an admissible memory budget"))
+ checks.append(_check("storage.disk", "skip", "storage check requires an admissible memory budget"))
+ checks.append(_check("memory.ram", "fail", str(error)))
+ checks.append(_check("placement.plan", "skip", "placement requires an admissible memory budget"))
+ checks.append(_check("storage.ssd_probe", "skip",
+ "probe surfacing requires an admissible memory budget"))
except (OSError, ValueError, KeyError, TypeError) as error:
checks.append(_check("model.shards", "fail", str(error)))
checks.append(_check("storage.disk", "skip", "storage check requires a valid model"))
diff --git a/c/resource_plan.py b/c/resource_plan.py
index 7ad1704b..95c3fc0d 100644
--- a/c/resource_plan.py
+++ b/c/resource_plan.py
@@ -10,6 +10,7 @@ import statistics
import subprocess
import sys
import threading
+from dataclasses import dataclass
from pathlib import Path
from family_registry import (expert_contributions, planner_geometry,
@@ -21,6 +22,53 @@ from family_registry import (expert_contributions, planner_geometry,
GB = 1_000_000_000
EXPERT_RE = re.compile(r"(?:model\.)?layers\.(\d+)\.(?:mlp|ffn)\.experts\.(\d+)\.")
+# Cgroup and procfs inputs are tiny kernel-maintained text files. Bound every
+# read anyway: the planner may run in a container with a synthetic or partially
+# mounted cgroup tree, and admission must never turn an unexpected file into an
+# unbounded read or an unbounded hierarchy walk.
+_CGROUP_VALUE_MAX_BYTES = 128
+_CGROUP_STAT_MAX_BYTES = 64 * 1024
+_CGROUP_MEMBERSHIP_MAX_BYTES = 64 * 1024
+_CGROUP_MOUNTINFO_MAX_BYTES = 4 * 1024 * 1024
+_CGROUP_MAX_ANCESTORS = 64
+_MEMINFO_MAX_BYTES = 256 * 1024
+_CGROUP_UINT64_MAX = (1 << 64) - 1
+_CGROUP_UINT64_DIGITS = len(str(_CGROUP_UINT64_MAX))
+# cgroup v1 represents "unlimited" with a page-aligned value just below the
+# signed 64-bit maximum (commonly 9223372036854771712). No consumer host can
+# provide an exbibyte of usable RAM, so this conservative threshold also covers
+# the other kernel sentinel variants without confusing a real finite limit.
+_CGROUP_V1_UNLIMITED_MIN = 1 << 60
+
+
+class CgroupError(ValueError):
+ """A present cgroup or procfs input cannot be trusted for memory admission."""
+
+
+class CgroupFormatError(CgroupError):
+ """A present procfs or cgroup file does not have the kernel's grammar."""
+
+
+class CgroupAccessError(CgroupError):
+ """A present cgroup input cannot be read completely or mapped soundly."""
+
+
+@dataclass(frozen=True)
+class _CgroupMemberships:
+ v2: tuple | None
+ v1_memory: tuple | None
+
+
+@dataclass(frozen=True)
+class _CgroupMount:
+ mount_id: int
+ parent_id: int
+ root: tuple
+ mount_point: Path
+ fs_type: str
+ options: frozenset
+
+
# analyze_model() scans every shard header + regex-matches ~116k tensor names on the
# 372 GB model; it reruns on every `coli plan/doctor/tune/run --auto-tier`. Its output
# is a pure function of each shard's and config.json's (size, mtime), so cache it to a
@@ -272,13 +320,465 @@ def windows_available_bytes(avail_phys, avail_pagefile):
return avail_phys
-def memory_available():
- # Linux (and MSYS2/Git-Bash CPython where /proc exists): MemAvailable.
+def _read_bounded_bytes(path, max_bytes, description):
+ """Return ``(present, raw)`` for one small kernel pseudo-file.
+
+ ``present`` keeps an absent file (that controller or proc path is simply
+ not mounted here) distinct from one that exists but cannot be trusted. Any
+ other read failure, and any file larger than the kernel would ever write,
+ is a typed refusal: it is never evidence that the process is unconstrained.
+ """
+ path = Path(path)
try:
- text = Path("/proc/meminfo").read_text()
- return int(re.search(r"MemAvailable:\s+(\d+)", text).group(1)) * 1024
- except (OSError, AttributeError):
- pass
+ with path.open("rb") as stream:
+ raw = stream.read(max_bytes + 1)
+ except (FileNotFoundError, NotADirectoryError):
+ return (False, None)
+ except OSError as error:
+ raise CgroupAccessError(f"cannot read {description} {path}: {error}") from error
+ if len(raw) > max_bytes:
+ raise CgroupFormatError(f"oversized {description}: {path}")
+ return (True, raw)
+
+
+def _read_bounded_ascii(path, max_bytes, description):
+ present, raw = _read_bounded_bytes(path, max_bytes, description)
+ if not present:
+ return (False, None)
+ try:
+ return (True, raw.decode("ascii"))
+ except UnicodeDecodeError as error:
+ raise CgroupFormatError(f"non-ASCII {description}: {path}") from error
+
+
+def _proc_lines(text, description):
+ """Split one procfs record file; an empty file or a blank record is malformed."""
+ if not text:
+ raise CgroupFormatError(f"empty {description}")
+ newline = b"\n" if isinstance(text, bytes) else "\n"
+ lines = (text[:-1] if text.endswith(newline) else text).split(newline)
+ if any(not line for line in lines):
+ raise CgroupFormatError(f"blank record in {description}")
+ return lines
+
+
+def _parse_bounded_id(field, description, *, allow_zero=True):
+ """Parse one canonical decimal u64 procfs field after a lexical length bound."""
+ if (not field or len(field) > _CGROUP_UINT64_DIGITS or not field.isdigit()
+ or (len(field) > 1 and field.startswith(b"0"))):
+ raise CgroupFormatError(f"malformed {description}: {field!r}")
+ value = int(field)
+ if value > _CGROUP_UINT64_MAX or (value == 0 and not allow_zero):
+ raise CgroupFormatError(f"out-of-range {description}: {field!r}")
+ return value
+
+
+def _path_components(raw, description):
+ """Split one absolute kernel path into components; "", "." and ".." are malformed."""
+ if raw == b"/":
+ return ()
+ if not raw.startswith(b"/"):
+ raise CgroupFormatError(f"{description} is not absolute: {raw!r}")
+ components = raw[1:].split(b"/")
+ if any(component in (b"", b".", b"..") for component in components):
+ raise CgroupFormatError(f"unnormalized {description}: {raw!r}")
+ if len(components) >= _CGROUP_MAX_ANCESTORS:
+ raise CgroupFormatError(
+ f"{description} nesting exceeds {_CGROUP_MAX_ANCESTORS - 1} levels")
+ return tuple(os.fsdecode(component) for component in components)
+
+
+# mountinfo(5) escapes exactly these four bytes as three-digit octal.
+_PROC_PATH_ESCAPES = {b"011": b"\t", b"012": b"\n", b"040": b" ", b"134": b"\\"}
+
+
+def _decode_proc_path(field, description):
+ """Decode one escaped mountinfo path field into normalized components."""
+ decoded = bytearray()
+ index = 0
+ while index < len(field):
+ byte = field[index]
+ if byte == ord("\\"):
+ escape = field[index + 1:index + 4]
+ if escape not in _PROC_PATH_ESCAPES:
+ raise CgroupFormatError(f"malformed escape in {description}: {field!r}")
+ decoded += _PROC_PATH_ESCAPES[escape]
+ index += 4
+ continue
+ if byte in (0, ord(" "), ord("\t"), ord("\n")):
+ raise CgroupFormatError(f"unescaped byte in {description}: {field!r}")
+ decoded.append(byte)
+ index += 1
+ return _path_components(bytes(decoded), description)
+
+
+def _decode_cgroup_membership_path(field, description):
+ """Decode a raw /proc/self/cgroup path (the kernel does not escape it)."""
+ if b"\0" in field:
+ raise CgroupFormatError(f"NUL byte in {description}: {field!r}")
+ return _path_components(field, description)
+
+
+def _parse_cgroup_counter(text):
+ """Parse one non-negative cgroup byte counter under an explicit u64 cap."""
+ match = re.fullmatch(r"(\d+)\n?", text or "")
+ if match is None or len(match.group(1)) > _CGROUP_UINT64_DIGITS:
+ return None
+ value = int(match.group(1))
+ return value if value <= _CGROUP_UINT64_MAX else None
+
+
+def _cgroup_inactive_file(directory, v1=False):
+ """Return the inactive file cache charged to one cgroup, in bytes.
+
+ ``memory.current`` (v1: ``usage_in_bytes``) charges clean page cache -- for
+ this engine, the mmap'd shards a previous run left behind -- while the host
+ half of the minimum, MemAvailable, counts such cache as available. Subtract
+ ``inactive_file`` (v1: ``total_inactive_file``, the hierarchical figure that
+ pairs with the hierarchical usage counter) the way Docker and cAdvisor
+ derive a working set. Absent statistics, or a kernel without the key,
+ subtract nothing; a present but malformed file is a refusal.
+ """
+ stat_path = Path(directory) / "memory.stat"
+ present, text = _read_bounded_ascii(stat_path, _CGROUP_STAT_MAX_BYTES,
+ "cgroup memory statistics")
+ if not present:
+ return 0
+ key = "total_inactive_file" if v1 else "inactive_file"
+ values = []
+ for line in _proc_lines(text, "cgroup memory statistics"):
+ match = re.fullmatch(r"([A-Za-z0-9_]+) (\d+)", line)
+ if match is None:
+ raise CgroupFormatError(f"malformed cgroup memory statistics: {stat_path}")
+ if match.group(1) == key:
+ values.append(match.group(2))
+ if len(values) > 1:
+ raise CgroupFormatError(f"duplicate {key} in cgroup memory statistics: {stat_path}")
+ value = _parse_cgroup_counter(values[0]) if values else 0
+ if value is None:
+ raise CgroupFormatError(f"malformed {key} in cgroup memory statistics: {stat_path}")
+ return value
+
+
+def _cgroup_pair_remaining(directory, limit_name, current_name, v1=False):
+ """Return ``(controls_present, finite_remaining_or_none)`` for one cgroup.
+
+ Present controls with ``None`` remaining are the kernel's unlimited value
+ (v2 ``max``; v1's sentinel just below 2**63). Both files must be present
+ and well-formed together: an incomplete pair or a malformed counter is a
+ refusal, never something a looser ancestor may mask. Headroom is measured
+ against the working set, charged usage less reclaimable inactive file
+ cache, so a previous run's cached model pages do not read as spent budget.
+ """
+ directory = Path(directory)
+ limit_path = directory / limit_name
+ current_path = directory / current_name
+ limit_present, limit_text = _read_bounded_ascii(
+ limit_path, _CGROUP_VALUE_MAX_BYTES, "cgroup memory limit")
+ current_present, current_text = _read_bounded_ascii(
+ current_path, _CGROUP_VALUE_MAX_BYTES, "cgroup memory usage")
+ if not limit_present and not current_present:
+ return (False, None)
+ if not limit_present or not current_present:
+ missing = current_path if limit_present else limit_path
+ raise CgroupAccessError(f"incomplete cgroup memory control pair: {missing}")
+ current = _parse_cgroup_counter(current_text)
+ if current is None:
+ raise CgroupFormatError(f"malformed cgroup memory usage: {current_path}")
+ if not v1 and limit_text in ("max", "max\n"):
+ return (True, None)
+ limit = _parse_cgroup_counter(limit_text)
+ if limit is None:
+ raise CgroupFormatError(f"malformed cgroup memory limit: {limit_path}")
+ if v1 and limit >= _CGROUP_V1_UNLIMITED_MIN:
+ return (True, None)
+ working_set = max(0, current - _cgroup_inactive_file(directory, v1=v1))
+ return (True, max(0, limit - working_set))
+
+
+def _read_cgroup_memberships(proc_cgroup_path):
+ """Strictly parse v2 and v1-memory membership from ``/proc/self/cgroup``.
+
+ ``None`` means the file is absent. Hybrid layouts are ordinary -- a
+ ``0::/...`` v2 record beside v1 records for controllers this planner never
+ consumes, such as ``1:net_cls:/`` from a VPN client -- and must not fail.
+ """
+ present, raw = _read_bounded_bytes(
+ proc_cgroup_path, _CGROUP_MEMBERSHIP_MAX_BYTES, "cgroup membership file")
+ if not present:
+ return None
+ v2_path = None
+ v1_path = None
+ hierarchy_ids = set()
+ for line in _proc_lines(raw, "cgroup membership file"):
+ fields = line.split(b":", 2)
+ if len(fields) != 3:
+ raise CgroupFormatError(f"malformed cgroup membership record: {line!r}")
+ hierarchy, controllers, member_path = fields
+ hierarchy_id = _parse_bounded_id(hierarchy, "cgroup hierarchy id")
+ if hierarchy_id in hierarchy_ids:
+ raise CgroupFormatError(f"duplicate cgroup hierarchy id: {hierarchy!r}")
+ hierarchy_ids.add(hierarchy_id)
+ controller_list = controllers.split(b",") if controllers else []
+ if (any(re.fullmatch(rb"[A-Za-z0-9_.=-]+", item) is None for item in controller_list)
+ or len(set(controller_list)) != len(controller_list)):
+ raise CgroupFormatError(f"malformed cgroup controller list: {controllers!r}")
+ member = _decode_cgroup_membership_path(member_path, "cgroup membership path")
+ if hierarchy_id == 0:
+ if controller_list or v2_path is not None:
+ raise CgroupFormatError("ambiguous cgroup v2 membership")
+ v2_path = member
+ elif not controller_list:
+ raise CgroupFormatError(f"v1 cgroup membership lacks controllers: {line!r}")
+ elif b"memory" in controller_list:
+ if v1_path is not None:
+ raise CgroupFormatError("ambiguous cgroup v1 memory membership")
+ v1_path = member
+ return _CgroupMemberships(v2=v2_path, v1_memory=v1_path)
+
+
+def _parse_mount_options(field, description):
+ try:
+ options = field.decode("ascii").split(",")
+ except UnicodeDecodeError as error:
+ raise CgroupFormatError(f"non-ASCII {description}: {field!r}") from error
+ if any(not option for option in options):
+ raise CgroupFormatError(f"malformed {description}: {field!r}")
+ return frozenset(options)
+
+
+def _read_cgroup_mounts(proc_mountinfo_path):
+ """Return every cgroup/cgroup2 mount from a strict, bounded mountinfo read.
+
+ ``None`` means the file is absent. Every record is held to mountinfo(5)'s
+ grammar so a truncated or synthetic file is a refusal rather than a quiet
+ "no cgroup mounts here"; paths are decoded only for cgroup records, so an
+ unrelated mount with an unusual name cannot block discovery.
+ """
+ present, raw = _read_bounded_bytes(
+ proc_mountinfo_path, _CGROUP_MOUNTINFO_MAX_BYTES, "cgroup mountinfo file")
+ if not present:
+ return None
+ mounts = []
+ mount_ids = set()
+ for line in _proc_lines(raw, "cgroup mountinfo file"):
+ fields = line.split(b" ")
+ if any(not field for field in fields):
+ raise CgroupFormatError(f"malformed mountinfo spacing: {line!r}")
+ try:
+ separator = fields.index(b"-", 6)
+ except ValueError as error:
+ raise CgroupFormatError(f"mountinfo record lacks separator: {line!r}") from error
+ if len(fields) != separator + 4:
+ raise CgroupFormatError(f"malformed mountinfo record: {line!r}")
+ mount_id = _parse_bounded_id(fields[0], "mountinfo mount id", allow_zero=False)
+ parent_id = _parse_bounded_id(fields[1], "mountinfo parent id")
+ device = fields[2].split(b":")
+ if len(device) != 2:
+ raise CgroupFormatError(f"malformed mountinfo device: {line!r}")
+ for number in device:
+ _parse_bounded_id(number, "mountinfo device number")
+ if mount_id in mount_ids:
+ raise CgroupFormatError(f"duplicate mountinfo id: {fields[0]!r}")
+ mount_ids.add(mount_id)
+ fs_type = fields[separator + 1]
+ if fs_type not in (b"cgroup", b"cgroup2"):
+ continue
+ if fields[3].split(b"/")[1:2] == [b".."]:
+ # cgroup_namespaces(7): a cgroupfs mount inherited from outside the
+ # process's cgroup namespace reports its root relative to that
+ # namespace as leading ".." components. Membership is reported
+ # relative to the namespace root, so no sound mapping exists.
+ raise CgroupAccessError(
+ f"unsupported cgroup mount root {fields[3]!r}: remount cgroupfs "
+ "inside the cgroup namespace")
+ root = _decode_proc_path(fields[3], "cgroup mount root")
+ mount_point = Path("/").joinpath(
+ *_decode_proc_path(fields[4], "cgroup mount point"))
+ options = (_parse_mount_options(fields[5], "cgroup mount options")
+ | _parse_mount_options(fields[separator + 3], "cgroup super options"))
+ mounts.append(_CgroupMount(mount_id=mount_id, parent_id=parent_id, root=root,
+ mount_point=mount_point,
+ fs_type=fs_type.decode("ascii"), options=options))
+ return mounts
+
+
+def _resolve_cgroup_hierarchy(mounts, member, *, v1=False):
+ """Return the mounts exposing ``member``, shallowest root first.
+
+ A mount's root is the cgroup its mount point shows; ``member`` maps into
+ it by stripping that root and appending the rest to the mount point. Of
+ several applicable mounts, the one with the shallowest root shows the
+ most ancestors: a deeper bind mount can hide an ancestor's limit, so it
+ must never be preferred. Every view is returned and the caller takes the
+ minimum, which also makes two mounts of one root harmless.
+ """
+ if v1:
+ applicable = [mount for mount in mounts
+ if mount.fs_type == "cgroup" and "memory" in mount.options]
+ else:
+ applicable = [mount for mount in mounts if mount.fs_type == "cgroup2"]
+ views = [mount for mount in applicable if member[:len(mount.root)] == mount.root]
+ return sorted(views, key=lambda mount: len(mount.root))
+
+
+def _cgroup_hierarchy_remaining(views, member, limit_name, current_name, v1=False):
+ """Return ``(controls_seen, tightest finite headroom)`` across every view.
+
+ Each view is walked from the membership leaf up to and including its mount
+ point, so an ancestor's finite limit bounds the result whenever any view
+ exposes it. Missing directories simply contribute nothing.
+ """
+ seen = False
+ remaining = None
+ for mount in views:
+ suffix = member[len(mount.root):]
+ for depth in range(len(suffix), -1, -1):
+ directory = mount.mount_point.joinpath(*suffix[:depth])
+ present, candidate = _cgroup_pair_remaining(
+ directory, limit_name, current_name, v1=v1)
+ seen = seen or present
+ if candidate is not None:
+ remaining = candidate if remaining is None else min(remaining, candidate)
+ return (seen, remaining)
+
+
+_CGROUP_V2_CONTROLS = ("memory.max", "memory.current")
+_CGROUP_V1_CONTROLS = ("memory.limit_in_bytes", "memory.usage_in_bytes")
+
+
+def _fixed_root_view(root, v1=False):
+ """A synthetic whole-hierarchy mount at ``root`` for kernels without mountinfo."""
+ return _CgroupMount(mount_id=0, parent_id=0, root=(), mount_point=Path(root),
+ fs_type="cgroup" if v1 else "cgroup2",
+ options=frozenset({"memory"}) if v1 else frozenset())
+
+
+def _cgroup_memory_remaining(cgroup_root=Path("/sys/fs/cgroup"),
+ proc_cgroup_path=Path("/proc/self/cgroup"),
+ proc_mountinfo_path=Path("/proc/self/mountinfo")):
+ """Return this process's tightest finite cgroup memory headroom, or ``None``.
+
+ Cgroup v2 is authoritative when its memory controls are visible; v1 is
+ consulted through mounts whose options include the memory controller.
+ ``None`` means no finite limit applies (or no cgroupfs is mounted here at
+ all). Present but malformed, incomplete or unreadable inputs raise
+ ``CgroupError`` instead of reading as unconstrained. ``cgroup_root`` is
+ consulted only by the fixed-layout probe used when mountinfo is absent.
+ """
+ memberships = _read_cgroup_memberships(proc_cgroup_path)
+ mounts = _read_cgroup_mounts(proc_mountinfo_path)
+ v2_member = memberships.v2 if memberships else None
+ v1_member = memberships.v1_memory if memberships else None
+ if mounts is None:
+ # No mountinfo: probe the conventional roots. The leaf-to-mount-point
+ # walk also covers runtimes that mount the process's own subgroup at
+ # the root while procfs still reports its host-side path.
+ probes = ((cgroup_root, v2_member, _CGROUP_V2_CONTROLS, False),
+ (Path(cgroup_root) / "memory", v1_member, _CGROUP_V1_CONTROLS, True),
+ (cgroup_root, v1_member, _CGROUP_V1_CONTROLS, True))
+ for root, member, controls, v1 in probes:
+ seen, remaining = _cgroup_hierarchy_remaining(
+ [_fixed_root_view(root, v1=v1)], member or (), *controls, v1=v1)
+ if seen:
+ return remaining
+ return None
+
+ has_v2_mount = any(mount.fs_type == "cgroup2" for mount in mounts)
+ has_v1_memory_mount = any(mount.fs_type == "cgroup" and "memory" in mount.options
+ for mount in mounts)
+ if memberships is None:
+ if has_v2_mount or has_v1_memory_mount:
+ raise CgroupAccessError(
+ "cgroup membership is unavailable for a mounted memory hierarchy")
+ return None
+ if has_v2_mount and v2_member is None:
+ raise CgroupAccessError("cgroup v2 mount has no corresponding membership record")
+ if has_v1_memory_mount and v1_member is None:
+ raise CgroupAccessError(
+ "cgroup v1 memory mount has no corresponding membership record")
+
+ if has_v2_mount:
+ views = _resolve_cgroup_hierarchy(mounts, v2_member)
+ if not views:
+ raise CgroupAccessError(
+ f"no visible cgroup2 mount exposes cgroup /{'/'.join(v2_member)}")
+ seen, remaining = _cgroup_hierarchy_remaining(views, v2_member, *_CGROUP_V2_CONTROLS)
+ if seen:
+ return remaining
+ if has_v1_memory_mount:
+ views = _resolve_cgroup_hierarchy(mounts, v1_member, v1=True)
+ if not views:
+ raise CgroupAccessError(
+ f"no visible cgroup v1 memory mount exposes cgroup /{'/'.join(v1_member)}")
+ seen, remaining = _cgroup_hierarchy_remaining(
+ views, v1_member, *_CGROUP_V1_CONTROLS, v1=True)
+ if not seen:
+ raise CgroupAccessError("cgroup v1 memory mount exposes no memory control files")
+ return remaining
+ return None
+
+
+def _host_memory_available(meminfo_path):
+ """Return strict host MemAvailable bytes, or ``None`` when it is unknown.
+
+ Unknown covers an absent ``/proc/meminfo`` and a kernel that predates
+ MemAvailable (3.14), exactly the cases the planner always fell back on. A
+ present line that is duplicated, not ``<digits> kB``, or beyond a u64 byte
+ counter is a refusal.
+ """
+ meminfo_path = Path(meminfo_path)
+ present, text = _read_bounded_ascii(meminfo_path, _MEMINFO_MAX_BYTES,
+ "memory information file")
+ if not present:
+ return None
+ lines = [line for line in text.split("\n") if line.startswith("MemAvailable")]
+ if not lines:
+ return None
+ match = (re.fullmatch(r"MemAvailable:[ \t]+(\d+)[ \t]+kB[ \t]*", lines[0])
+ if len(lines) == 1 else None)
+ if match is None:
+ raise CgroupFormatError(f"MemAvailable is malformed: {meminfo_path}")
+ kib = _parse_cgroup_counter(match.group(1))
+ if kib is None or kib > _CGROUP_UINT64_MAX // 1024:
+ raise CgroupFormatError(f"MemAvailable overflows a byte counter: {meminfo_path}")
+ return kib * 1024
+
+
+def memory_available(*, meminfo_path=Path("/proc/meminfo"),
+ cgroup_root=Path("/sys/fs/cgroup"),
+ proc_cgroup_path=Path("/proc/self/cgroup"),
+ proc_mountinfo_path=Path("/proc/self/mountinfo")):
+ """Bytes this process may plan to allocate; ``None`` when nothing could measure it.
+
+ On Linux this is ``min(host MemAvailable, remaining finite cgroup budget)``:
+ a container started with a memory limit is killed at that limit however
+ much the host has free, and the cgroup half is what lets the planner refuse
+ an over-budget model before it allocates anything substantial. The result
+ is a tri-state -- an int (including an authoritative 0 when the budget is
+ already exhausted), ``None`` when no probe could measure anything so the
+ planner keeps its historical fallback, or ``CgroupError`` when a present
+ cgroup or procfs input is malformed, incomplete or unreadable. That last
+ case is a refusal with a reason, never permission to assume the process is
+ unconstrained, so it deliberately propagates.
+ """
+ # Linux (and MSYS2/Git-Bash CPython where /proc exists): MemAvailable.
+ host_available = _host_memory_available(meminfo_path)
+ cgroup_remaining = None
+ if sys.platform.startswith("linux"):
+ # Cgroups are a Linux kernel facility; nothing else has a hierarchy to
+ # read. Probed even when the host figure is unknown, because a finite
+ # limit is still a valid conservative bound when a restricted container
+ # hides /proc/meminfo.
+ cgroup_remaining = _cgroup_memory_remaining(
+ cgroup_root=cgroup_root, proc_cgroup_path=proc_cgroup_path,
+ proc_mountinfo_path=proc_mountinfo_path)
+ if host_available is not None and cgroup_remaining is not None:
+ return min(host_available, cgroup_remaining)
+ if host_available is not None:
+ return host_available
+ if cgroup_remaining is not None:
+ return cgroup_remaining
# Windows native CPython: GlobalMemoryStatusEx -> ullAvailPhys.
# Same definition the C engine uses (compat_meminfo in compat.h):
# standby/free/zero pages, i.e. reclaimable without swapping.
@@ -335,7 +835,7 @@ def memory_available():
return int(total)
except (OSError, subprocess.SubprocessError, ValueError):
pass
- return 0
+ return None
def _host_unified_memory():
@@ -498,8 +998,8 @@ def _discover_nvidia_gpus():
try:
meminfo = Path("/proc/meminfo").read_text()
total = int(re.search(r"MemTotal:\s+(\d+)", meminfo).group(1)) // 1024
- free = memory_available() // (1024 * 1024)
- except (OSError, AttributeError):
+ free = (memory_available() or 0) // (1024 * 1024)
+ except (OSError, AttributeError, CgroupError):
total = free = 0
name = fields[1]
unified = any(token in name.lower() for token in ("gb10", "jetson", "grace blackwell"))
@@ -1009,7 +1509,19 @@ def build_plan(model, ram_gb=0, context=4096, gpu_indices=None, vram_gb=0,
if (isinstance(kv_slots, bool) or not isinstance(kv_slots, int) or
not 1 <= kv_slots <= resolved.descriptor.limits.max_kv_slots):
raise ValueError(f"{resolved.descriptor.id}: invalid KV slot count {kv_slots}")
- available_memory = memory_available() if available_memory is None else available_memory
+ automatic_ram = ram_gb <= 0
+ if available_memory is None:
+ available_memory = memory_available()
+ available_memory_known = available_memory is not None
+ if not available_memory_known:
+ # Nothing could measure host memory (no /proc, vm_stat failed). Report
+ # the historical 0 and let the 8 GB compatibility fallback below size
+ # the budget; doctor's "could not be measured" warning keys on it.
+ available_memory = 0
+ elif automatic_ram and available_memory <= 0:
+ raise ValueError(
+ "no available RAM remains for automatic placement "
+ "(host/cgroup memory budget is exhausted)")
if available_disk is None:
try:
usage = shutil.disk_usage(info["path"])
@@ -1078,15 +1590,26 @@ def build_plan(model, ram_gb=0, context=4096, gpu_indices=None, vram_gb=0,
requested_ram_experts = max(0, requested_ram - info["dense_bytes"] - runtime_bytes)
ram_expert_bytes = min(requested_ram_experts,
max(0, unified_pool - vram_budget))
- ram_budget = info["dense_bytes"] + runtime_bytes + ram_expert_bytes
+ # The fixed resident footprint can itself exceed a small requested or
+ # cgroup-derived budget. Keep reporting the actual admission ceiling in
+ # that case; inflating the tier to the fixed footprint would make an
+ # exhausted shared-memory plan look admissible. The zero-cache warning
+ # below still explains that the model cannot retain even one expert.
+ ram_budget = min(requested_ram,
+ info["dense_bytes"] + runtime_bytes + ram_expert_bytes)
if requested_ram_experts > ram_expert_bytes:
warnings.append(
f"RAM budget clamped from {format_bytes(requested_ram)} to "
f"{format_bytes(ram_budget)} because the GPU shares physical memory")
else:
ram_budget = int(ram_gb * GB) if ram_gb > 0 else int(available_memory * 0.88)
- if ram_budget < 4 * GB:
- ram_budget = 8 * GB if not placement_unified else max(0, ram_budget)
+ # Keep the legacy 8 GB fallback only when every host-memory probe failed.
+ # A known small value -- especially finite cgroup headroom -- must retain
+ # the 12% safety reserve and can never be inflated above what is available.
+ # An explicit --ram is an intentional override, but its smaller value must
+ # likewise not be silently raised behind the user's back.
+ if automatic_ram and not available_memory_known and not placement_unified:
+ ram_budget = 8 * GB
cache_bytes = max(0, ram_budget - info["dense_bytes"] - runtime_bytes)
cap = int(cache_bytes // per_cap) if per_cap else 0
if configured_experts:
diff --git a/c/tests/test_cgroup_memory.py b/c/tests/test_cgroup_memory.py
new file mode 100644
index 00000000..1a479a1d
--- /dev/null
+++ b/c/tests/test_cgroup_memory.py
@@ -0,0 +1,917 @@
+"""Container-aware memory admission: min(host MemAvailable, finite cgroup headroom).
+
+Pure fixtures: every kernel input (``/proc/self/cgroup``, ``/proc/self/mountinfo``,
+``/proc/meminfo`` and the cgroup control files) is a file under a temporary
+directory, so the tests run identically on any platform, and every expectation
+is derived from the fixture numbers rather than from the implementation.
+"""
+
+import json
+import struct
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from doctor import run_doctor
+from resource_plan import (
+ GB,
+ CgroupAccessError,
+ CgroupError,
+ CgroupFormatError,
+ _CGROUP_UINT64_MAX,
+ _CGROUP_V1_UNLIMITED_MIN,
+ _MEMINFO_MAX_BYTES,
+ _cgroup_memory_remaining,
+ memory_available,
+)
+
+HOST_AVAILABLE = 16_384 * 1024
+
+
+class CgroupMemoryAdmissionTest(unittest.TestCase):
+ """Fixture-driven checks of the cgroup half of the admission minimum."""
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.base = Path(self.tmp.name)
+ self.root = self.base / "cgroup"
+ self.root.mkdir()
+ self.proc_cgroup = self.base / "proc-self-cgroup"
+ self.proc_mountinfo = self.base / "proc-self-mountinfo"
+ self.meminfo = self.base / "meminfo"
+ self.meminfo.write_text(
+ "MemTotal: 32768 kB\nMemAvailable: 16384 kB\n", encoding="ascii"
+ )
+ # Cgroups are Linux-only and the probe is gated on the platform; pin it
+ # so the fixtures exercise the same code everywhere.
+ platform = mock.patch("resource_plan.sys.platform", "linux")
+ platform.start()
+ self.addCleanup(platform.stop)
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ @staticmethod
+ def _proc_escape(value):
+ escapes = {"\t": r"\011", "\n": r"\012", " ": r"\040", "\\": r"\134"}
+ return "".join(escapes.get(character, character) for character in str(value))
+
+ def _membership(self, *lines):
+ self.proc_cgroup.write_text("\n".join(lines) + "\n", encoding="ascii")
+
+ def _mount_line(
+ self,
+ *,
+ mount_id=30,
+ parent_id=1,
+ root="/",
+ mount_point=None,
+ fs_type="cgroup2",
+ mount_options="rw,nosuid,nodev",
+ optional_fields=(),
+ super_options="rw",
+ ):
+ mount_point = self.root if mount_point is None else Path(mount_point)
+ optional = "".join(f"{field} " for field in optional_fields)
+ return (
+ f"{mount_id} {parent_id} 0:{mount_id} {self._proc_escape(root)} "
+ f"{self._proc_escape(mount_point)} {mount_options} {optional}- "
+ f"{fs_type} {fs_type} {super_options}"
+ )
+
+ def _mounts(self, *lines):
+ self.proc_mountinfo.write_text("\n".join(lines) + "\n", encoding="ascii")
+
+ @staticmethod
+ def _write_pair(directory, limit_name, current_name, limit, current):
+ directory.mkdir(parents=True, exist_ok=True)
+ (directory / limit_name).write_text(f"{limit}\n", encoding="ascii")
+ (directory / current_name).write_text(f"{current}\n", encoding="ascii")
+
+ def _write_v2(self, directory, limit, current):
+ self._write_pair(directory, "memory.max", "memory.current", limit, current)
+
+ def _write_v1(self, directory, limit, current):
+ self._write_pair(
+ directory, "memory.limit_in_bytes", "memory.usage_in_bytes", limit, current
+ )
+
+ @staticmethod
+ def _write_stat(directory, **counters):
+ directory.mkdir(parents=True, exist_ok=True)
+ lines = "".join(f"{key} {value}\n" for key, value in counters.items())
+ (directory / "memory.stat").write_text(lines, encoding="ascii")
+
+ def _remaining(self):
+ return _cgroup_memory_remaining(
+ cgroup_root=self.root,
+ proc_cgroup_path=self.proc_cgroup,
+ proc_mountinfo_path=self.proc_mountinfo,
+ )
+
+ def _available(self):
+ return memory_available(
+ meminfo_path=self.meminfo,
+ cgroup_root=self.root,
+ proc_cgroup_path=self.proc_cgroup,
+ proc_mountinfo_path=self.proc_mountinfo,
+ )
+
+ def _standard_v2(self, member="/tenant/job"):
+ self._membership(f"0::{member}")
+ self._mounts(self._mount_line())
+
+ # -- the admission rule ---------------------------------------------------
+
+ def test_v2_finite_budget_clamps_host_memavailable(self):
+ self._standard_v2()
+ self._write_v2(self.root / "tenant" / "job", 12_000_000, 3_000_000)
+ self.assertEqual(self._remaining(), 9_000_000)
+ self.assertEqual(self._available(), 9_000_000)
+
+ def test_host_memavailable_wins_when_lower_than_cgroup_headroom(self):
+ self._standard_v2()
+ self._write_v2(self.root / "tenant" / "job", 100_000_000, 1)
+ self.assertEqual(self._available(), HOST_AVAILABLE)
+
+ def test_mount_root_is_removed_before_suffix_is_appended_to_mount_point(self):
+ self._membership("0::/tenant/job")
+ self._mounts(self._mount_line(root="/tenant"))
+ self._write_v2(self.root / "job", 12_000_000, 4_000_000)
+ # A naive mount-point + membership join would look under tenant/job.
+ self._write_v2(self.root / "tenant" / "job", 99_000_000, 1)
+ self.assertEqual(self._remaining(), 8_000_000)
+
+ def test_namespaced_mount_root_equal_to_membership_maps_to_mount_point(self):
+ self._membership("0::/host/tenant/job")
+ self._mounts(self._mount_line(root="/host/tenant/job"))
+ self._write_v2(self.root, 10_000_000, 4_000_000)
+ self.assertEqual(self._remaining(), 6_000_000)
+
+ def test_ancestor_limit_hidden_by_deeper_mount_root_still_binds(self):
+ # A3: two cgroup2 mounts expose one kernel tree. The deep one (root
+ # /tenant/job) cannot show /tenant, whose 5 MB limit with 1 MB charged
+ # is the binding 4 MB; preferring it would over-admit by 5 MB.
+ self._membership("0::/tenant/job")
+ broad = self.base / "broad"
+ deep = self.base / "deep"
+ self._write_v2(broad / "tenant", 5_000_000, 1_000_000)
+ self._write_v2(broad / "tenant" / "job", 12_000_000, 3_000_000)
+ self._write_v2(deep, 12_000_000, 3_000_000)
+ broad_line = self._mount_line(mount_id=31, root="/", mount_point=broad)
+ deep_line = self._mount_line(mount_id=32, root="/tenant/job", mount_point=deep)
+ for lines in ((broad_line, deep_line), (deep_line, broad_line)):
+ with self.subTest(first=lines[0].split()[0]):
+ self._mounts(*lines)
+ self.assertEqual(self._remaining(), 4_000_000)
+ self.assertEqual(self._available(), 4_000_000)
+
+ def test_two_mounts_of_one_root_take_the_minimum_instead_of_refusing(self):
+ # Mounting cgroupfs twice is legitimate (a read-only copy for a
+ # sidecar, say) and must not fail closed; the tighter view wins.
+ self._membership("0::/tenant/job", "7:cpu,memory:/tenant/job")
+ for version in ("v2", "v1"):
+ with self.subTest(version=version):
+ first = self.base / f"{version}-first"
+ second = self.base / f"{version}-second"
+ write = self._write_v2 if version == "v2" else self._write_v1
+ write(first / "job", 8_000_000, 1_000_000)
+ write(second / "job", 5_000_000, 1_000_000)
+ fs_type = "cgroup2" if version == "v2" else "cgroup"
+ super_options = "rw" if version == "v2" else "rw,cpu,memory"
+ self._mounts(
+ self._mount_line(
+ mount_id=31,
+ root="/tenant",
+ mount_point=first,
+ fs_type=fs_type,
+ super_options=super_options,
+ ),
+ self._mount_line(
+ mount_id=32,
+ root="/tenant",
+ mount_point=second,
+ fs_type=fs_type,
+ super_options=super_options,
+ ),
+ )
+ self.assertEqual(self._remaining(), 4_000_000)
+
+ def test_hybrid_v1_net_cls_record_beside_v2_membership_is_not_a_refusal(self):
+ # This development host's real layout: a VPN client mounts a v1 net_cls
+ # hierarchy next to the systemd cgroup2 tree, and mountinfo carries
+ # optional "shared:N" fields. Only the memory controller matters; a v1
+ # record for another controller is ignored, never a reason to fail.
+ scope = (
+ "user.slice/user-1000.slice/[email protected]/app.slice/vte-spawn-1.scope"
+ )
+ self._membership("1:net_cls:/", f"0::/{scope}")
+ net_cls = self.base / "net_cls"
+ net_cls.mkdir()
+ self._mounts(
+ self._mount_line(
+ mount_id=38,
+ parent_id=28,
+ mount_options="rw,nosuid,nodev,noexec,relatime",
+ optional_fields=("shared:10",),
+ super_options="rw,nsdelegate,memory_recursiveprot",
+ ),
+ self._mount_line(
+ mount_id=2470,
+ parent_id=34,
+ mount_point=net_cls,
+ fs_type="cgroup",
+ mount_options="rw,relatime",
+ optional_fields=("shared:1651",),
+ super_options="rw,net_cls",
+ ),
+ )
+ self._write_v2(
+ self.root / "user.slice" / "user-1000.slice", 30_000_000, 10_000_000
+ )
+ self._write_v2(self.root.joinpath(*scope.split("/")), "max", 2_000_000)
+ self.assertEqual(self._remaining(), 20_000_000)
+ self.assertEqual(self._available(), HOST_AVAILABLE)
+
+ def test_nested_v2_uses_tightest_visible_ancestor_budget(self):
+ self._standard_v2()
+ self._write_v2(self.root, "max", 9_000_000)
+ self._write_v2(self.root / "tenant", 20_000_000, 14_000_000)
+ self._write_v2(self.root / "tenant" / "job", 12_000_000, 3_000_000)
+ self.assertEqual(self._remaining(), 6_000_000)
+
+ def test_unlimited_v2_leaf_still_honors_finite_parent(self):
+ self._standard_v2()
+ self._write_v2(self.root / "tenant", 9_000_000, 4_000_000)
+ self._write_v2(self.root / "tenant" / "job", "max", 3_000_000)
+ self.assertEqual(self._remaining(), 5_000_000)
+
+ def test_v2_max_is_unlimited_and_does_not_override_host(self):
+ self._standard_v2(member="/")
+ self._write_v2(self.root, "max", 1234)
+ self.assertIsNone(self._remaining())
+ self.assertEqual(self._available(), HOST_AVAILABLE)
+
+ def test_v2_counter_accepts_no_trailing_newline(self):
+ self._standard_v2(member="/")
+ (self.root / "memory.max").write_text("10000", encoding="ascii")
+ (self.root / "memory.current").write_text("4000", encoding="ascii")
+ self.assertEqual(self._remaining(), 6_000)
+
+ def test_v2_current_at_or_above_limit_is_authoritative_zero_headroom(self):
+ self._standard_v2(member="/")
+ for current in (10_000, 10_001):
+ with self.subTest(current=current):
+ self._write_v2(self.root, 10_000, current)
+ self.assertEqual(self._remaining(), 0)
+ self.assertEqual(self._available(), 0)
+
+ def test_v1_combined_controller_mount_is_discovered_from_super_options(self):
+ self._membership("7:cpu,memory,blkio:/tenant/job")
+ self._mounts(
+ self._mount_line(fs_type="cgroup", super_options="rw,cpu,memory,blkio")
+ )
+ self._write_v1(self.root / "tenant" / "job", 11_000_000, 4_000_000)
+ self.assertEqual(self._remaining(), 7_000_000)
+
+ def test_v1_combined_controller_mount_is_discovered_from_mount_options(self):
+ self._membership("7:memory,cpuacct:/tenant/job")
+ self._mounts(
+ self._mount_line(
+ fs_type="cgroup", mount_options="rw,memory,cpuacct", super_options="rw"
+ )
+ )
+ self._write_v1(self.root / "tenant" / "job", 9_000_000, 3_000_000)
+ self.assertEqual(self._remaining(), 6_000_000)
+
+ def test_v1_mount_root_and_parent_minimum_are_honored(self):
+ self._membership("7:memory,blkio:/tenant/job")
+ self._mounts(
+ self._mount_line(
+ root="/tenant", fs_type="cgroup", super_options="rw,memory,blkio"
+ )
+ )
+ self._write_v1(self.root, 10_000_000, 7_000_000)
+ self._write_v1(self.root / "job", 8_000_000, 2_000_000)
+ self.assertEqual(self._remaining(), 3_000_000)
+
+ def test_v1_kernel_unlimited_sentinel_does_not_clamp_host(self):
+ self._membership("7:memory:/")
+ self._mounts(self._mount_line(fs_type="cgroup", super_options="rw,memory"))
+ self._write_v1(self.root, _CGROUP_V1_UNLIMITED_MIN, 1234)
+ self.assertIsNone(self._remaining())
+ self.assertEqual(self._available(), HOST_AVAILABLE)
+
+ def test_v1_current_at_or_above_limit_is_authoritative_zero_headroom(self):
+ self._membership("7:memory:/")
+ self._mounts(self._mount_line(fs_type="cgroup", super_options="rw,memory"))
+ for current in (10_000, 10_001):
+ with self.subTest(current=current):
+ self._write_v1(self.root, 10_000, current)
+ self.assertEqual(self._remaining(), 0)
+ self.assertEqual(self._available(), 0)
+
+ def test_v2_controls_are_authoritative_over_stale_v1_membership(self):
+ v1_root = self.base / "v1"
+ self._membership("0::/", "7:memory:/legacy")
+ self._mounts(
+ self._mount_line(mount_id=30),
+ self._mount_line(
+ mount_id=31,
+ fs_type="cgroup",
+ mount_point=v1_root,
+ super_options="rw,memory",
+ ),
+ )
+ self._write_v2(self.root, "max", 1)
+ self._write_v1(v1_root / "legacy", 4_000_000, 3_000_000)
+ self.assertIsNone(self._remaining())
+
+ def test_v1_is_used_when_v2_mount_has_no_memory_controls(self):
+ v1_root = self.base / "v1"
+ self._membership("0::/unified", "7:memory:/legacy")
+ self._mounts(
+ self._mount_line(mount_id=30),
+ self._mount_line(
+ mount_id=31,
+ fs_type="cgroup",
+ mount_point=v1_root,
+ super_options="rw,cpu,memory",
+ ),
+ )
+ (self.root / "unified").mkdir()
+ self._write_v1(v1_root / "legacy", 8_000_000, 3_000_000)
+ self.assertEqual(self._remaining(), 5_000_000)
+
+ # -- page cache is reclaimable headroom (A2) -----------------------------
+
+ def test_v2_inactive_file_cache_is_not_spent_budget(self):
+ # limit 12 MB, 9 MB charged of which 5 MB is clean file cache: the
+ # kernel reclaims that cache before enforcing the limit, so the working
+ # set is 4 MB and 8 MB remains -- not 3 MB.
+ self._standard_v2(member="/")
+ self._write_v2(self.root, 12_000_000, 9_000_000)
+ self.assertEqual(self._remaining(), 3_000_000)
+ self._write_stat(
+ self.root, anon=4_000_000, file=5_000_000, inactive_file=5_000_000
+ )
+ self.assertEqual(self._remaining(), 8_000_000)
+ self.assertEqual(self._available(), 8_000_000)
+
+ def test_v1_subtracts_hierarchical_total_inactive_file_not_the_local_figure(self):
+ # usage_in_bytes is hierarchical, so it pairs with total_inactive_file
+ # (3 MB), not the cgroup-local inactive_file (1 MB): 10 - (8 - 3) = 5.
+ self._membership("7:memory:/")
+ self._mounts(self._mount_line(fs_type="cgroup", super_options="rw,memory"))
+ self._write_v1(self.root, 10_000_000, 8_000_000)
+ self._write_stat(
+ self.root,
+ cache=3_000_000,
+ inactive_file=1_000_000,
+ total_inactive_file=3_000_000,
+ )
+ self.assertEqual(self._remaining(), 5_000_000)
+
+ def test_inactive_file_beyond_charged_usage_leaves_the_whole_limit(self):
+ self._standard_v2(member="/")
+ self._write_v2(self.root, 12_000_000, 2_000_000)
+ self._write_stat(self.root, inactive_file=5_000_000)
+ self.assertEqual(self._remaining(), 12_000_000)
+
+ def test_page_cache_is_subtracted_per_ancestor_level(self):
+ # Parent: 20 - (15 - 10) = 15 MB; leaf: 12 - 3 = 9 MB. Without the
+ # parent's statistics the parent would bind the result at 5 MB.
+ self._standard_v2()
+ self._write_v2(self.root / "tenant", 20_000_000, 15_000_000)
+ self._write_v2(self.root / "tenant" / "job", 12_000_000, 3_000_000)
+ self.assertEqual(self._remaining(), 5_000_000)
+ self._write_stat(self.root / "tenant", inactive_file=10_000_000)
+ self.assertEqual(self._remaining(), 9_000_000)
+
+ def test_memory_stat_without_the_key_subtracts_nothing(self):
+ self._standard_v2(member="/")
+ self._write_v2(self.root, 12_000_000, 9_000_000)
+ self._write_stat(self.root, anon=9_000_000, file=0)
+ self.assertEqual(self._remaining(), 3_000_000)
+
+ def test_malformed_memory_stat_is_a_typed_refusal(self):
+ self._standard_v2(member="/")
+ self._write_v2(self.root, 12_000_000, 9_000_000)
+ malformed = (
+ "",
+ "inactive_file\n",
+ "inactive_file x\n",
+ "inactive_file 1 2\n",
+ "inactive_file -1\n",
+ "inactive_file 1\ninactive_file 2\n",
+ "inactive_file 1\n\n",
+ f"inactive_file {_CGROUP_UINT64_MAX + 1}\n",
+ "inactive_file 1\n" + "x" * (64 * 1024),
+ )
+ for payload in malformed:
+ with self.subTest(payload=payload[:30]):
+ (self.root / "memory.stat").write_text(payload, encoding="ascii")
+ with self.assertRaises(CgroupFormatError):
+ self._remaining()
+ with self.assertRaises(CgroupFormatError):
+ self._available()
+ (self.root / "memory.stat").write_bytes(b"inactive_file 1\n\xff\n")
+ with self.assertRaises(CgroupFormatError):
+ self._remaining()
+
+ # -- present but untrustworthy controls fail closed ------------------------
+
+ def test_malformed_control_values_raise_typed_errors_and_fail_closed(self):
+ self._standard_v2(member="/")
+ malformed = (
+ "",
+ "-1",
+ "+1",
+ "1.5",
+ "garbage",
+ " 1",
+ "1 ",
+ "\t1",
+ "1\n",
+ "1\r",
+ "max ",
+ str(_CGROUP_UINT64_MAX + 1),
+ )
+ for value in malformed:
+ with self.subTest(limit=value):
+ self._write_v2(self.root, value, 1)
+ with self.assertRaisesRegex(
+ CgroupFormatError, "malformed cgroup memory limit"
+ ):
+ self._remaining()
+ with self.assertRaises(CgroupFormatError):
+ self._available()
+ for value in malformed:
+ with self.subTest(current=value):
+ self._write_v2(self.root, 10_000, value)
+ with self.assertRaisesRegex(
+ CgroupFormatError, "malformed cgroup memory usage"
+ ):
+ self._remaining()
+ with self.assertRaises(CgroupFormatError):
+ self._available()
+
+ def test_max_and_v1_unlimited_still_validate_present_usage(self):
+ cases = (("v2", "max", "bad"), ("v1", _CGROUP_V1_UNLIMITED_MIN, "bad"))
+ for version, limit, current in cases:
+ with self.subTest(version=version):
+ if version == "v2":
+ self._membership("0::/")
+ self._mounts(self._mount_line())
+ self._write_v2(self.root, limit, current)
+ else:
+ self._membership("7:memory:/")
+ self._mounts(
+ self._mount_line(fs_type="cgroup", super_options="rw,memory")
+ )
+ self._write_v1(self.root, limit, current)
+ with self.assertRaisesRegex(
+ CgroupFormatError, "malformed cgroup memory usage"
+ ):
+ self._remaining()
+
+ def test_malformed_leaf_is_not_masked_by_valid_parent(self):
+ self._standard_v2()
+ self._write_v2(self.root / "tenant", 8_000_000, 3_000_000)
+ self._write_v2(self.root / "tenant" / "job", "bad", 1)
+ with self.assertRaisesRegex(CgroupFormatError, "malformed cgroup memory limit"):
+ self._remaining()
+
+ def test_oversized_and_non_ascii_control_values_fail_closed(self):
+ self._standard_v2(member="/")
+ for value in (b"9" * 256, b"10\xff\n"):
+ with self.subTest(value=value[:8]):
+ (self.root / "memory.max").write_bytes(value)
+ (self.root / "memory.current").write_bytes(b"1\n")
+ with self.assertRaises(CgroupFormatError):
+ self._remaining()
+ with self.assertRaises(CgroupFormatError):
+ self._available()
+
+ def test_incomplete_control_pair_fails_closed_in_both_directions(self):
+ self._standard_v2(member="/")
+ for present, missing in (
+ ("memory.max", "memory.current"),
+ ("memory.current", "memory.max"),
+ ):
+ with self.subTest(missing=missing):
+ for name in ("memory.max", "memory.current"):
+ (self.root / name).unlink(missing_ok=True)
+ (self.root / present).write_text("10000\n", encoding="ascii")
+ with self.assertRaisesRegex(CgroupAccessError, "incomplete"):
+ self._remaining()
+ with self.assertRaises(CgroupAccessError):
+ self._available()
+
+ def test_unreadable_present_control_file_fails_closed(self):
+ self._standard_v2(member="/")
+ self._write_v2(self.root, 10_000, 4_000)
+ real_open = Path.open
+
+ def deny_usage(path, *args, **kwargs):
+ if path.name == "memory.current":
+ raise PermissionError("fixture denied")
+ return real_open(path, *args, **kwargs)
+
+ with mock.patch.object(Path, "open", deny_usage):
+ with self.assertRaisesRegex(
+ CgroupAccessError, "cannot read cgroup memory usage"
+ ):
+ self._remaining()
+ with self.assertRaises(CgroupAccessError):
+ self._available()
+
+ # -- present but malformed procfs inputs are refusals, not "unconstrained" -
+
+ def test_malformed_present_membership_is_never_treated_as_unconstrained(self):
+ self._mounts(self._mount_line())
+ malformed = (
+ b"",
+ b"not:a:valid:line\n",
+ b"0::relative\n",
+ b"0::/a/../b\n",
+ b"0::/a/./b\n",
+ b"0::/a//b\n",
+ b"0::/a/\n",
+ b"0:memory:/\n",
+ b"1::/\n",
+ b"1:memory,memory:/\n",
+ b"0::/\n0::/other\n",
+ b"0::/\n0:cpu:/\n",
+ b"\n",
+ b"1:memory:/a\n2:cpu,memory:/b\n",
+ b"0::/ok\n\n",
+ b"0::/bad\x00name\n",
+ b"\xff::/bad-id\n",
+ b"1:memo\xffry:/bad-controller\n",
+ )
+ for payload in malformed:
+ with self.subTest(payload=payload[:30]):
+ self.proc_cgroup.write_bytes(payload)
+ with self.assertRaises(CgroupError):
+ self._remaining()
+ with self.assertRaises(CgroupError):
+ self._available()
+
+ def test_oversized_membership_is_a_format_error(self):
+ self._mounts(self._mount_line())
+ self.proc_cgroup.write_bytes(b"0::/" + b"x" * (64 * 1024) + b"\n")
+ with self.assertRaisesRegex(CgroupFormatError, "oversized"):
+ self._remaining()
+
+ def test_path_depth_limit_is_enforced_before_filesystem_access(self):
+ self._mounts(self._mount_line())
+ member = "/" + "/".join(f"level-{index}" for index in range(64))
+ self._membership(f"0::{member}")
+ with self.assertRaisesRegex(CgroupFormatError, "nesting exceeds"):
+ self._remaining()
+
+ def test_malformed_present_mountinfo_is_never_a_compatibility_signal(self):
+ self._membership("0::/")
+ self._write_v2(self.root, 9_000_000, 2_000_000)
+ valid = self._mount_line()
+ malformed = (
+ "",
+ "garbage",
+ valid.replace(" - ", " "),
+ valid.replace("30 1", "x 1", 1),
+ valid.replace("0:30", "bad-device", 1),
+ valid.replace(" / ", " /root/../escape ", 1),
+ valid.replace(self._proc_escape(self.root), "relative", 1),
+ valid.replace(" rw,nosuid", " rw,nosuid", 1),
+ valid + "\n" + valid,
+ )
+ for payload in malformed:
+ with self.subTest(payload=payload[:40]):
+ self.proc_mountinfo.write_text(payload + "\n", encoding="ascii")
+ with self.assertRaises(CgroupFormatError):
+ self._remaining()
+ with self.assertRaises(CgroupFormatError):
+ self._available()
+
+ def test_inherited_cgroup_namespace_mount_root_is_a_typed_refusal(self):
+ self._membership("0::/job")
+ self._mounts(self._mount_line(root="/../.."))
+ with self.assertRaisesRegex(CgroupAccessError, "remount cgroupfs"):
+ self._remaining()
+
+ def test_mountinfo_accepts_unrelated_non_path_roots(self):
+ self._membership("0::/")
+ unrelated = "29 1 0:5 net:[4026531833] /run/netns rw - nsfs nsfs rw"
+ self._mounts(unrelated, self._mount_line())
+ self._write_v2(self.root, 7_000_000, 2_000_000)
+ self.assertEqual(self._remaining(), 5_000_000)
+
+ def test_unrelated_raw_unicode_mount_does_not_block_cgroup_discovery(self):
+ self._membership("0::/")
+ unrelated = b"29 1 0:5 / /mnt/caf\xc3\xa9-\xff rw - ext4 /dev/example rw\n"
+ cgroup = self._mount_line().encode("ascii") + b"\n"
+ self.proc_mountinfo.write_bytes(unrelated + cgroup)
+ self._write_v2(self.root, 7_000_000, 2_000_000)
+ self.assertEqual(self._remaining(), 5_000_000)
+
+ def test_mountinfo_escapes_are_decoded_for_cgroup_mount_paths(self):
+ # mountinfo(5) escapes space, tab, newline and backslash as octal; the
+ # membership path in /proc/self/cgroup is raw. Both must meet.
+ mount_point = self.base / "mount point\twith\nall\\four"
+ self._membership("0::/sp ace\ttab\\bs/job")
+ self._mounts(self._mount_line(root="/sp ace\ttab\\bs", mount_point=mount_point))
+ self._write_v2(mount_point / "job", 7_000_000, 2_000_000)
+ self.assertEqual(self._remaining(), 5_000_000)
+
+ # -- absent procfs inputs: compatibility, never a refusal -------------------
+
+ def test_mountinfo_absence_alone_enables_fixed_root_compatibility(self):
+ self._membership("0::/tenant/job")
+ self._write_v2(self.root / "tenant" / "job", 9_000_000, 2_000_000)
+ self.assertFalse(self.proc_mountinfo.exists())
+ self.assertEqual(self._remaining(), 7_000_000)
+
+ def test_absent_mountinfo_compatibility_supports_namespaced_root(self):
+ self._membership("0::/host/tenant/job")
+ self._write_v2(self.root, 9_000_000, 2_000_000)
+ self.assertFalse(self.proc_mountinfo.exists())
+ self.assertEqual(self._remaining(), 7_000_000)
+
+ def test_absent_mountinfo_compatibility_supports_v1_fixed_root(self):
+ self._membership("7:cpu,memory:/tenant/job")
+ self._write_v1(self.root / "memory" / "tenant" / "job", 8_000_000, 3_000_000)
+ self.assertFalse(self.proc_mountinfo.exists())
+ self.assertEqual(self._remaining(), 5_000_000)
+
+ def test_absent_membership_and_mountinfo_can_probe_namespaced_root(self):
+ self._write_v2(self.root, 8_000_000, 3_000_000)
+ self.assertFalse(self.proc_cgroup.exists())
+ self.assertFalse(self.proc_mountinfo.exists())
+ self.assertEqual(self._remaining(), 5_000_000)
+
+ def test_absent_membership_with_present_memory_mount_fails_closed(self):
+ self._mounts(self._mount_line())
+ self._write_v2(self.root, 8_000_000, 3_000_000)
+ self.assertFalse(self.proc_cgroup.exists())
+ with self.assertRaisesRegex(CgroupAccessError, "membership is unavailable"):
+ self._remaining()
+ with self.assertRaises(CgroupAccessError):
+ self._available()
+
+ def test_present_membership_missing_record_for_v2_mount_fails_closed(self):
+ self._membership("1:cpu:/")
+ self._mounts(self._mount_line())
+ with self.assertRaisesRegex(CgroupAccessError, "v2 mount.*membership"):
+ self._remaining()
+
+ def test_present_membership_missing_record_for_v1_memory_mount_fails_closed(self):
+ self._membership("1:cpu:/")
+ self._mounts(self._mount_line(fs_type="cgroup", super_options="rw,cpu,memory"))
+ with self.assertRaisesRegex(CgroupAccessError, "v1 memory mount.*membership"):
+ self._remaining()
+
+ def test_membership_hidden_by_every_visible_mount_fails_closed(self):
+ # A cgroup2 mount is present but shows a sibling subtree only: the
+ # process's own limit is unverifiable, which is not "unlimited".
+ self._membership("0::/tenant/job")
+ self._mounts(self._mount_line(root="/other"))
+ with self.assertRaisesRegex(CgroupAccessError, "no visible cgroup2 mount"):
+ self._remaining()
+
+ def test_no_cgroup_mount_at_all_is_host_only_not_a_refusal(self):
+ # A sandbox that mounts no cgroupfs offers nothing to read; that is an
+ # absent input (the host measurement stands), not a malformed one.
+ self._membership("0::/tenant/job")
+ self._mounts("29 1 0:5 / /run rw - tmpfs tmpfs rw")
+ self.assertIsNone(self._remaining())
+ self.assertEqual(self._available(), HOST_AVAILABLE)
+
+ def test_absent_control_files_leave_host_measurement_unchanged(self):
+ self._standard_v2()
+ (self.root / "tenant" / "job").mkdir(parents=True)
+ self.assertIsNone(self._remaining())
+ self.assertEqual(self._available(), HOST_AVAILABLE)
+
+ # -- the host half of the minimum -------------------------------------------
+
+ def test_finite_cgroup_is_upper_bound_when_linux_meminfo_is_hidden(self):
+ self._standard_v2(member="/")
+ self._write_v2(self.root, 7_000_000, 2_000_000)
+ self.meminfo.unlink()
+ self.assertEqual(self._available(), 5_000_000)
+
+ def test_nothing_measurable_is_unknown_not_zero(self):
+ # No /proc/meminfo and no finite cgroup limit is the tri-state's None,
+ # so the planner keeps its historical fallback instead of reading
+ # "exhausted" (A1).
+ self._standard_v2(member="/")
+ self._write_v2(self.root, "max", 1)
+ self.meminfo.unlink()
+ self.assertIsNone(self._available())
+
+ def test_meminfo_without_memavailable_is_unknown_not_malformed(self):
+ # Kernels before 3.14 (and Cygwin's emulation) have no MemAvailable;
+ # that is the pre-existing fallback path, not a corrupt file.
+ self._standard_v2(member="/")
+ self._write_v2(self.root, "max", 1)
+ self.meminfo.write_text(
+ "MemTotal: 32768 kB\nMemFree: 100 kB\n", encoding="ascii"
+ )
+ self.assertIsNone(self._available())
+ self._write_v2(self.root, 7_000_000, 2_000_000)
+ self.assertEqual(self._available(), 5_000_000)
+
+ def test_memavailable_is_parsed_as_one_strict_bounded_u64_field(self):
+ maximum_kib = _CGROUP_UINT64_MAX // 1024
+ for line, expected in (
+ ("MemAvailable:\t16384 kB\t", 16_384 * 1024),
+ (f"MemAvailable: {maximum_kib} kB", maximum_kib * 1024),
+ ):
+ with self.subTest(line=line[:40]):
+ self.meminfo.write_text(
+ f"MemTotal: 32768 kB\n{line}\n", encoding="ascii"
+ )
+ self.assertEqual(self._available(), expected)
+
+ def test_malformed_duplicate_and_overflowing_memavailable_fail_closed(self):
+ overflow = _CGROUP_UINT64_MAX // 1024 + 1
+ malformed = (
+ "MemAvailable: not-a-number kB\n",
+ "MemAvailable: 100 MB\n",
+ "MemAvailable: 100 kB trailing\n",
+ "MemAvailable: 100 kB\nMemAvailable: 200 kB\n",
+ f"MemAvailable: {overflow} kB\n",
+ f"MemAvailable: {'9' * 5000} kB\n",
+ )
+ for text in malformed:
+ with self.subTest(text=text[:50]):
+ self.meminfo.write_text(text, encoding="ascii")
+ with self.assertRaises(CgroupFormatError):
+ self._available()
+
+ def test_oversized_and_non_ascii_meminfo_fail_closed(self):
+ payloads = (
+ b"MemAvailable: 100 kB\n" + b"X" * _MEMINFO_MAX_BYTES,
+ b"MemAvailable: 100 kB\n\xff\n",
+ )
+ for payload in payloads:
+ with self.subTest(size=len(payload)):
+ self.meminfo.write_bytes(payload)
+ with self.assertRaises(CgroupFormatError):
+ self._available()
+
+ def test_cgroup_probe_is_linux_only(self):
+ # A fixture that would refuse on Linux is never consulted on a platform
+ # without cgroups; the host figure stands alone.
+ self._standard_v2(member="/")
+ self._write_v2(self.root, "bad", 1)
+ with mock.patch("resource_plan.sys.platform", "darwin"):
+ self.assertEqual(self._available(), HOST_AVAILABLE)
+
+
+def _write_shard(path, tensors):
+ offset = 0
+ header = {}
+ payload = b""
+ for name, size in tensors:
+ header[name] = {
+ "dtype": "U8",
+ "shape": [size],
+ "data_offsets": [offset, offset + size],
+ }
+ payload += b"\0" * size
+ offset += size
+ raw = json.dumps(header).encode()
+ path.write_bytes(struct.pack("<Q", len(raw)) + raw + payload)
+
+
+class DoctorMemoryAdmissionTest(unittest.TestCase):
+ """The tri-state reaches doctor unchanged (A1).
+
+ unknown (None) is the historical warn + 8 GB fallback; a present but
+ malformed cgroup input is a typed refusal whose reason the user sees under
+ memory.ram; a finite figure is the ceiling the budget is checked against.
+ """
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ root = Path(self.tmp.name)
+ self.model = root / "model"
+ self.model.mkdir()
+ (self.model / "config.json").write_text(
+ json.dumps(
+ {
+ "model_type": "glm_moe_dsa",
+ "num_hidden_layers": 2,
+ "n_routed_experts": 2,
+ "kv_lora_rank": 4,
+ "qk_rope_head_dim": 2,
+ "qk_nope_head_dim": 3,
+ "v_head_dim": 5,
+ "num_attention_heads": 2,
+ }
+ )
+ )
+ (self.model / "tokenizer.json").write_text("{}")
+ _write_shard(
+ self.model / "model.safetensors",
+ [
+ ("model.embed_tokens.weight", 100),
+ ("model.norm.weight", 8),
+ ("lm_head.weight", 100),
+ ("model.layers.0.self_attn.q_a_proj.weight", 200),
+ ("model.layers.1.mlp.experts.0.gate_proj.weight", 30),
+ ("model.layers.1.mlp.experts.0.up_proj.weight", 30),
+ ("model.layers.1.mlp.experts.1.gate_proj.weight", 30),
+ ("model.layers.1.mlp.experts.1.up_proj.weight", 30),
+ ],
+ )
+ self.engine = root / "glm"
+ self.engine.write_text("#!/bin/sh\nexit 0\n")
+ self.engine.chmod(0o755)
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def _doctor(self, probe, **overrides):
+ arguments = {
+ "model": self.model,
+ "ram_gb": 0,
+ "context": 32,
+ "gpu_indices": [],
+ "vram_gb": 0,
+ "engine_path": self.engine,
+ "available_memory": None,
+ "available_disk": 100 * GB,
+ "gpus": [],
+ "linkage": {"linked": False, "missing": False},
+ }
+ arguments.update(overrides)
+ with mock.patch("resource_plan.memory_available", **probe):
+ report = run_doctor(**arguments)
+ return report, {check["id"]: check for check in report["checks"]}
+
+ def test_unknown_measurement_is_a_warning_with_the_legacy_fallback(self):
+ report, checks = self._doctor({"return_value": None})
+ self.assertEqual(checks["memory.ram"]["status"], "warn")
+ self.assertEqual(
+ checks["memory.ram"]["summary"], "available RAM could not be measured"
+ )
+ self.assertEqual(checks["memory.ram"]["details"]["available_bytes"], 0)
+ self.assertEqual(report["plan"]["tiers"]["ram"]["budget_bytes"], 8 * GB)
+ self.assertEqual(report["status"], "warning")
+
+ def test_malformed_cgroup_input_is_a_memory_failure_with_the_reason(self):
+ reason = "malformed cgroup memory limit: /sys/fs/cgroup/memory.max"
+ report, checks = self._doctor({"side_effect": CgroupFormatError(reason)})
+ self.assertEqual(checks["memory.ram"]["status"], "fail")
+ self.assertEqual(checks["memory.ram"]["summary"], reason)
+ self.assertEqual(checks["model.shards"]["status"], "skip")
+ self.assertEqual(checks["placement.plan"]["status"], "skip")
+ self.assertIsNone(report["plan"])
+ self.assertEqual(report["status"], "error")
+
+ def test_finite_headroom_is_the_ceiling_the_budget_is_checked_against(self):
+ report, checks = self._doctor({"return_value": 32 * GB})
+ self.assertEqual(checks["memory.ram"]["status"], "pass")
+ self.assertEqual(checks["memory.ram"]["details"]["available_bytes"], 32 * GB)
+ self.assertEqual(
+ report["plan"]["tiers"]["ram"]["budget_bytes"], int(32 * GB * 0.88)
+ )
+
+ # 2 GB of headroom: the 12% reserve is kept (1.76 GB, never the old
+ # 8 GB floor) and that budget cannot hold the fixed runtime footprint.
+ report, checks = self._doctor({"return_value": 2 * GB})
+ self.assertEqual(checks["memory.ram"]["details"]["available_bytes"], 2 * GB)
+ self.assertEqual(
+ report["plan"]["tiers"]["ram"]["budget_bytes"], int(2 * GB * 0.88)
+ )
+ self.assertEqual(checks["memory.ram"]["status"], "fail")
+ self.assertEqual(
+ checks["memory.ram"]["summary"],
+ "RAM budget cannot hold one expert slot per sparse layer",
+ )
+
+ # An explicit --ram above the finite headroom is the container OOM case.
+ report, checks = self._doctor({"return_value": 2 * GB}, ram_gb=16)
+ self.assertEqual(checks["memory.ram"]["status"], "fail")
+ self.assertEqual(
+ checks["memory.ram"]["summary"],
+ "planned RAM budget exceeds available memory",
+ )
+
+ def test_exhausted_budget_is_a_refusal_not_an_unmeasured_warning(self):
+ # current >= limit is an authoritative 0; the planner refuses (through
+ # doctor's generic planner-error slot) rather than warning "could not
+ # be measured" and launching on the 8 GB fallback.
+ report, checks = self._doctor({"return_value": 0})
+ self.assertEqual(report["status"], "error")
+ self.assertIsNone(report["plan"])
+ self.assertIn("memory budget is exhausted", checks["model.shards"]["summary"])
+ self.assertEqual(checks["memory.ram"]["status"], "skip")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tests/test_resource_plan.py b/c/tests/test_resource_plan.py
index 6307b1a5..7306131d 100644
--- a/c/tests/test_resource_plan.py
+++ b/c/tests/test_resource_plan.py
@@ -10,6 +10,7 @@ from unittest import mock
from resource_plan import (
GB,
+ CgroupFormatError,
analyze_model,
build_plan,
cpu_socket_count,
@@ -359,6 +360,60 @@ class ResourcePlanTest(unittest.TestCase):
self.assertIn("GLM53_EXPERT_GB", env)
self.assertEqual(env["GLM53_EXPERT_GB"], expected)
self.assertNotIn("K3_EXPERT_GB", env)
+ def test_auto_ram_keeps_reserve_below_small_finite_headroom(self):
+ # T15: detecting a 2 GB cgroup budget and later inflating it to the
+ # planner's historical 8 GB floor is still over-admission. Preserve the
+ # ordinary 12% reserve and never export more RAM than the finite value.
+ with mock.patch("resource_plan.memory_available", return_value=2 * GB):
+ plan = build_plan(self.model, available_disk=1, gpus=[])
+ ram = plan["tiers"]["ram"]
+ self.assertEqual(plan["memory"]["available_bytes"], 2 * GB)
+ self.assertEqual(ram["budget_bytes"], int(2 * GB * 0.88))
+ self.assertLessEqual(ram["budget_bytes"], ram["available_bytes"])
+ self.assertEqual(environment_for_plan(plan)["RAM_GB"], "1.760")
+
+ def test_auto_ram_never_exceeds_finite_headroom_on_unified_memory(self):
+ gpu = {"index": 0, "name": "NVIDIA GB10", "total_bytes": 130 * GB,
+ "free_bytes": 128 * GB, "unified_memory": True}
+ with mock.patch("resource_plan.memory_available", return_value=2 * GB):
+ plan = build_plan(self.model, available_disk=1, gpus=[gpu])
+ ram = plan["tiers"]["ram"]
+ self.assertTrue(plan["memory"]["unified"])
+ self.assertEqual(ram["budget_bytes"], int(2 * GB * 0.88))
+ self.assertLessEqual(ram["budget_bytes"], ram["available_bytes"])
+
+ def test_auto_ram_rejects_known_zero_headroom(self):
+ # current >= limit is authoritative exhaustion, not the old
+ # unavailable-probe sentinel. Never turn it into an 8 GB launch --
+ # whether the zero was probed or handed in explicitly.
+ with mock.patch("resource_plan.memory_available", return_value=0), \
+ self.assertRaisesRegex(ValueError, "memory budget is exhausted"):
+ build_plan(self.model, available_disk=1, gpus=[])
+ with self.assertRaisesRegex(ValueError, "memory budget is exhausted"):
+ build_plan(self.model, available_memory=0, available_disk=1, gpus=[])
+
+ def test_auto_ram_retains_legacy_fallback_only_when_probe_is_unknown(self):
+ # None is the tri-state's "nothing could measure it": the historical
+ # 8 GB fallback and the historical 0 in the report, never a refusal.
+ with mock.patch("resource_plan.memory_available", return_value=None):
+ plan = build_plan(self.model, available_disk=1, gpus=[])
+ self.assertEqual(plan["tiers"]["ram"]["budget_bytes"], 8 * GB)
+ self.assertEqual(plan["memory"]["available_bytes"], 0)
+
+ def test_malformed_cgroup_input_is_a_typed_refusal_not_a_fallback(self):
+ # A present but malformed controller reaches the caller with its
+ # reason; it is a ValueError, so existing handlers still catch it.
+ error = CgroupFormatError("malformed cgroup memory limit: /sys/fs/cgroup/memory.max")
+ with mock.patch("resource_plan.memory_available", side_effect=error), \
+ self.assertRaises(CgroupFormatError) as context:
+ build_plan(self.model, available_disk=1, gpus=[])
+ self.assertIsInstance(context.exception, ValueError)
+ self.assertIn("memory.max", str(context.exception))
+
+ def test_explicit_small_ram_budget_is_not_silently_inflated(self):
+ plan = build_plan(self.model, ram_gb=2, available_memory=16 * GB,
+ available_disk=1, gpus=[])
+ self.assertEqual(plan["tiers"]["ram"]["budget_bytes"], 2 * GB)
def test_cpu_socket_count_is_positive(self):
self.assertGreaterEqual(cpu_socket_count(), 1)