"""Conservative cgroup-v2 admission; reservations include model loading/offload. Working memory excludes reclaimable inactive file cache. Without reliable per-job attribution, observed memory cannot be credited against model reservations: other container-local workloads may grow during execution. Add active reservations in full to observed working memory, then reserve the next job and global headroom. This deliberately overcounts already-loaded model memory and can reduce slots. SHM pages are already charged to memory.current, but full SHM independently blocks admission. Unreadable/unlimited production budgets fail closed. """ from pathlib import Path import shutil GIB = 1024 ** 3 class MemoryAdmission: def __init__(self, settings, *, cgroup=Path('/sys/fs/cgroup'), shm_usage=None): self.settings = settings self.cgroup = Path(cgroup) self.last_sample = None self.shm_usage = shm_usage or self._shm @staticmethod def _shm(): usage = shutil.disk_usage('/dev/shm') return usage.used, usage.total def check(self, task_type, reservations): try: maximum = int((self.cgroup / 'memory.max').read_text().strip()) current = int((self.cgroup / 'memory.current').read_text().strip()) stats = dict(line.split() for line in (self.cgroup / 'memory.stat').read_text().splitlines()) working = max(0, current - int(stats.get('inactive_file', 0))) used, total = self.shm_usage() events_path = self.cgroup / 'memory.events' events = dict(line.split() for line in events_path.read_text().splitlines()) if events_path.exists() else {} required = (working + sum(reservations) * GIB + (self.settings.memory_estimates_gib[task_type] + self.settings.memory_headroom_gib) * GIB) self.last_sample = {'memory_current_bytes': current, 'memory_max_bytes': maximum, 'working_bytes': working, 'reserved_bytes': sum(reservations) * GIB, 'admission_required_bytes': required, 'shm_used_bytes': used, 'shm_total_bytes': total, 'memory_events': {name: int(value) for name, value in events.items()}} if total <= 0 or total - used < min(GIB, total * .05): return 'Shared memory pressure; waiting for /dev/shm capacity' if required > maximum: return 'Container memory budget insufficient; FIFO head waiting' except (OSError, ValueError, KeyError, TypeError): return 'Container memory budget unavailable; dispatch blocked' return None