From a3e1fda7e83eef75bedab810a981900e7ed956ae Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 27 Nov 2026 19:02:06 +0000 Subject: [PATCH] feat(queue): admit by a self-tuning load band from one limits file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Requirements 072, 073 and 083. The fixed per-kind test slot count gives way to a utilization band: a job starts while CPU and RAM sit below the lower limit and its learned footprint keeps them at or below the upper one; smaller jobs backfill around a waiting head without starving it. An AIMD target between the limits rises by 2 per poll while the host idles and falls to the middle on overload, rising memory PSI or swap-out, with one grant per settle window. RAM footprints are the command's p95 times a margin learned from past prediction errors, CPU keeps the median. /limits.json holds lower, upper, STOP and MAYDAY per CPU, RAM, swap, disk and PSI for queue and watch (limits.py validates the order and keeps the last valid copy). Queue override and settings commands for the hub's Controls tab come along. MEDUSA: 65 reviewed false positives accepted across the open bundles (pattern hits such as .key attribute access, PLA in replace, ]]] in nested type hints, rewrite( of the atomic writers). 🎯 Fix: 90 % 💥 Break: 5 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 86 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- skills/kvb-org-organize/config.default.json | 2 +- skills/kvb-org-organize/scripts/limits.py | 158 +++++ skills/kvb-org-organize/scripts/watch.py | 41 +- skills/kvb-org-queue/SKILL.md | 35 +- skills/kvb-org-queue/band.md | 48 ++ skills/kvb-org-queue/controls.md | 32 + skills/kvb-org-queue/learning.md | 19 +- skills/kvb-org-queue/scripts/aimd.py | 91 +++ skills/kvb-org-queue/scripts/history.py | 85 ++- skills/kvb-org-queue/scripts/queue.py | 661 +++++++++++++++++--- tests/queue-list.json | 8 +- tests/test_limits.py | 185 ++++++ tests/test_queue.py | 160 +++-- tests/test_queue_aimd.py | 167 +++++ tests/test_queue_override.py | 105 ++++ tests/test_queue_replay.py | 4 +- tests/test_queue_settings.py | 91 +++ 17 files changed, 1708 insertions(+), 184 deletions(-) create mode 100644 skills/kvb-org-organize/scripts/limits.py create mode 100644 skills/kvb-org-queue/band.md create mode 100644 skills/kvb-org-queue/controls.md create mode 100644 skills/kvb-org-queue/scripts/aimd.py create mode 100644 tests/test_limits.py create mode 100644 tests/test_queue_aimd.py create mode 100644 tests/test_queue_override.py create mode 100644 tests/test_queue_settings.py diff --git a/skills/kvb-org-organize/config.default.json b/skills/kvb-org-organize/config.default.json index 5adda74..a464ed3 100644 --- a/skills/kvb-org-organize/config.default.json +++ b/skills/kvb-org-organize/config.default.json @@ -25,7 +25,7 @@ "cache_budget_percent": 3, "slot_need_gb": {"quality-high": 15, "test": 15, "test-nostack": 0, "iteration": 20, "swarm": 30, "gui-dind": 65, "operator": 10}, "notify": ["notify-send", "-u", "critical", "Agents council"], - "load_limits": {"cpu_percent": 90, "mem_percent": 85, "sample_seconds": 5, "kinds": ["test", "test-nostack", "quality-high"]}, + "load_limits": {"cpu_percent": 90, "mem_percent": 85, "sample_seconds": 5, "band_low": 70, "band_high": 90, "kinds": ["test", "test-nostack", "quality-high"]}, "memory_limits": { "warn": {"available": 15, "swap_free": 40, "psi_some": 10, "psi_full": 5, "swap_out_mb_min": 64, "container_swap_gb": 4}, "stop": {"available": 8, "swap_free": 10, "psi_full": 5, "swap_out_mb_min": 256, "container_swap_gb": 16} diff --git a/skills/kvb-org-organize/scripts/limits.py b/skills/kvb-org-organize/scripts/limits.py new file mode 100644 index 0000000..70e1efd --- /dev/null +++ b/skills/kvb-org-organize/scripts/limits.py @@ -0,0 +1,158 @@ +"""Read and check the resource limits file of the agents council (requirement 083). + +/limits.json (root: councilroot.py) is the one source of the load limits +queue.py and watch.py apply over their config, and of the lines the hub draws +(requirement 084). One JSON object holding every metric with its four levels: + + {"cpu": {"lower": 70, "upper": 90, "stop": 95, "mayday": 99}, + "ram": {"lower": 70, "upper": 85, "stop": 92, "mayday": 97}, + "swap": {"lower": 20, "upper": 60, "stop": 90, "mayday": 97}, + "disk": {"lower": 70, "upper": 85, "stop": 95, "mayday": 98}, + "psi": {"lower": 1, "upper": 10, "stop": 30, "mayday": 60}} + +Every value is a percent from 0 to 100: cpu is CPU busy, ram RAM used (100 +less MemAvailable), swap swap used, disk the used share of the watch disk, +psi the memory PSI some avg10; per metric lower < upper < stop < mayday. +applied() maps them onto the config keys their readers use: the queue band +from cpu and ram lower and upper, its AIMD target between them with psi +lower as its calm bound, the live guard load_limits cpu_percent and +mem_percent from cpu and ram stop; the watch memory stage warn from ram, +swap and psi upper, stop from their stop; the disk stages warn, stop and +critical (thresholds_gb, whose stop is the queue's floor) from disk upper, +stop and mayday. A valid file is kept as /limits.last.json; a file +that breaks the checks is refused and that copy stays in force; without +the file the config applies. +""" + +from __future__ import annotations + +import contextlib +import importlib.util +import itertools +import json +import math +import os +from pathlib import Path + +METRICS = ("cpu", "ram", "swap", "disk", "psi") +LEVELS = ("lower", "upper", "stop", "mayday") +NAME = "limits.json" +LAST = "limits.last.json" +KEY = "limits" +MEMORY_STAGES = {"warn": "upper", "stop": "stop"} +DISK_STAGES = {"warn": "upper", "stop": "stop", "critical": "mayday"} +UNREADABLE = (OSError, ValueError, RecursionError) + + +def _nofollow(): + spec = importlib.util.spec_from_file_location("kvb_limits_nofollow", Path(__file__).resolve().parent / "nofollow.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +nofollow = _nofollow() + + +def percent(value: object) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and 0 <= value <= 100 + + +def problem(data: object) -> str | None: + """Returns: + Why data is no limits object (exactly METRICS, each with exactly + LEVELS, every value a percent from 0 to 100, lower < upper < stop < + mayday), None when it is one. + """ + if not isinstance(data, dict) or set(data) != set(METRICS): + return f"the limits are no object of exactly {', '.join(METRICS)}" + for metric in METRICS: + levels = data[metric] + if not isinstance(levels, dict) or set(levels) != set(LEVELS): + return f"{metric} holds not exactly {', '.join(LEVELS)}" + values = [levels[level] for level in LEVELS] + if not all(percent(value) for value in values): + return f"{metric} holds a value that is no percent from 0 to 100" + if not all(low < high for low, high in itertools.pairwise(values)): + return f"{metric} breaks lower < upper < stop < mayday" + return None + + +def parsed(root: Path, path: Path) -> object: + return json.loads(nofollow.read_text(root, path)) + + +def keep(root: Path, last: Path, data: dict) -> None: + with contextlib.suppress(*UNREADABLE): + if parsed(root, last) == data: + return + with contextlib.suppress(OSError): + nofollow.replace(root, last, json.dumps(data, indent=1, sort_keys=True) + "\n", 0o600) + + +def read(root: Path) -> tuple[dict | None, str | None]: + """Args: + root: the council directory. + + Returns: + (the limits in force, None while the config applies; why NAME was + refused, None when it was not): NAME when it passes problem(), kept + as LAST; else LAST while that passes, else None. Without NAME the + config applies and LAST stays as it is. + """ + path, last = root / NAME, root / LAST + if not os.path.lexists(path): + return None, None + try: + data = parsed(root, path) + except UNREADABLE as error: + why = f"{path} is unreadable ({error})" + else: + why = problem(data) + if why is None: + keep(root, last, data) + return data, None + why = f"{path} is refused: {why}" + try: + kept = parsed(root, last) + except UNREADABLE: + kept = None + if problem(kept) is None: + return kept, f"{why}; the last valid copy {last} stays in force" + return None, f"{why}; no valid copy is kept, so the config applies" + + +def memory_bounds(held: dict, level: str) -> dict[str, float]: + return {"available": 100 - held["ram"][level], "swap_free": 100 - held["swap"][level], "psi_some": held["psi"][level]} + + +def applied(cfg: dict, held: dict | None, total_gb: float | None) -> dict: + """Args: + cfg: the config. + held: the limits in force (read()), None for none. + total_gb: the size of cfg's disk in GB, None when unknown; the disk + stages then stay the config's. + + Returns: + cfg itself without limits, else a copy holding them under KEY with + load_limits cpu_percent and mem_percent, memory_limits warn and stop + (available, swap_free, psi_some) and thresholds_gb (GB left free at + each disk level) taken from them; a section cfg lacks or holds as no + object stays as it is, so the config check still names it. + """ + if held is None: + return cfg + out = {**cfg, KEY: held} + if isinstance(cfg.get("load_limits"), dict): + out["load_limits"] = {**cfg["load_limits"], "cpu_percent": held["cpu"]["stop"], "mem_percent": held["ram"]["stop"]} + memory = cfg.get("memory_limits") + if isinstance(memory, dict) and all(isinstance(memory.get(stage), dict) for stage in MEMORY_STAGES): + out["memory_limits"] = { + **memory, **{stage: {**memory[stage], **memory_bounds(held, level)} for stage, level in MEMORY_STAGES.items()}, + } + if total_gb is not None and isinstance(cfg.get("thresholds_gb"), dict): + out["thresholds_gb"] = { + **cfg["thresholds_gb"], + **{stage: round(total_gb * (100 - held["disk"][level]) / 100, 1) for stage, level in DISK_STAGES.items()}, + } + return out diff --git a/skills/kvb-org-organize/scripts/watch.py b/skills/kvb-org-organize/scripts/watch.py index 0da1150..140e04e 100755 --- a/skills/kvb-org-organize/scripts/watch.py +++ b/skills/kvb-org-organize/scripts/watch.py @@ -92,6 +92,12 @@ bound, or where one container (a docker-*.scope cgroup under system.slice, nested groups counted) holds at least container_swap_gb GB of swap, else ok; a host without swap, PSI or such a reading skips that bound. heavy_commands extend the built-in rules of heavy(). + +Limits file: /limits.json (limits.py documents its format and checks) +overrides load_limits cpu_percent and mem_percent, memory_limits warn and +stop (available, swap_free, psi_some; stop then also bounds psi_some) and +thresholds_gb from its levels for every command; a refused file keeps the +last valid copy in force and the watch hook names it to each session. """ from __future__ import annotations @@ -135,6 +141,7 @@ nofollow = sibling("nofollow") hookpath = sibling("hookpath") councilroot = sibling("councilroot") popups = sibling("popups") +limit_file = sibling("limits") QUEUE = Path(__file__).resolve().parents[2] / "kvb-org-queue" / "scripts" / "queue.py" ROOT = councilroot.root() CONFIG = Path( @@ -451,21 +458,36 @@ def settled_config() -> tuple[dict | None, str | None]: command stays off); the SHIPPED config and one warning naming the file when it cannot be read or checked (checked_config()); REFUSE_ALL, which counts every command heavy, when SHIPPED cannot be - read or checked either. + read or checked either. The config and SHIPPED come under the + limits file in force (with_limits()). """ try: cfg = load_config() - return (None if cfg is None else checked_config(cfg)), None + return (None if cfg is None else with_limits(checked_config(cfg))[0]), None except UNUSABLE as error: problem = f"agents council: {CONFIG} is unusable ({error})" try: - return checked_config(read_regular(SHIPPED)), ( + return with_limits(checked_config(read_regular(SHIPPED)))[0], ( f"{problem}; the built-in defaults of {SHIPPED} apply until it is fixed: light commands pass, heavy ones are refused" ) except UNUSABLE as error: return dict(REFUSE_ALL), f"{problem} and so is {SHIPPED} ({error}); every command is refused until one is fixed" +def with_limits(cfg: dict) -> tuple[dict, str | None]: + """Returns: + (cfg under the limits file in force (limit_file.read() below ROOT, + limit_file.applied(), the disk stages over the size of cfg's disk), + why the file was refused or None). + """ + held, why = limit_file.read(ROOT) + total = None + if held is not None: + with contextlib.suppress(OSError, KeyError, TypeError, ValueError): + total = disk(cfg)[1] + return limit_file.applied(cfg, held, total), why + + def absent_part(cfg: dict, key: str) -> str | None: node: object = cfg parts = key.split(".") @@ -834,7 +856,8 @@ def cmd_watch(cfg: dict, problem: str | None, unsettled: bool) -> int: if not unsettled and stale(state, cfg, now): measure_and_act(cfg, state, now, problem) keep_history() - texts = unseen_alerts(payload["session_id"]) + ([] if problem is None else [problem]) + refused = limit_file.read(ROOT)[1] + texts = unseen_alerts(payload["session_id"]) + [text for text in (problem, refused) if text is not None] if texts: print(json.dumps({"hookSpecificOutput": { "hookEventName": payload["hook_event_name"], @@ -2370,12 +2393,18 @@ def memory() -> dict[str, float | None]: def memory_stage(sample: dict[str, float | None], cfg: dict) -> str: + """Returns: + The first of stop and warn whose memory_limits bound the sample + reaches, else ok; under the limits file (limit_file.KEY) stop also + bounds psi_some by the file's psi stop. + """ for name in ("stop", "warn"): bound = cfg["memory_limits"][name] + pressures = (*PRESSURES[name], *(("psi_some",) if name == "stop" and limit_file.KEY in cfg else ())) if ( sample["available"] < bound["available"] or (sample["swap_free"] is not None and sample["swap_free"] < bound["swap_free"]) - or any(sample[key] is not None and sample[key] >= bound[key] for key in PRESSURES[name]) + or any(sample[key] is not None and sample[key] >= bound[key] for key in pressures) or sample["container_swap_gb"] >= bound["container_swap_gb"] ): return name @@ -2929,7 +2958,7 @@ def main() -> int: return run() try: return run() - except Exception as error: + except Exception as error: # noqa: BLE001 print(f"kvb-org-organize: the block hook failed ({error!r}), so the command counts as heavy and is refused.", file=sys.stderr) return 2 diff --git a/skills/kvb-org-queue/SKILL.md b/skills/kvb-org-queue/SKILL.md index 5608f8d..c9f2afe 100644 --- a/skills/kvb-org-queue/SKILL.md +++ b/skills/kvb-org-queue/SKILL.md @@ -39,28 +39,29 @@ Every 20 s each waiting hold evaluates the queue, locked: job. Main first needs Main in `rasci.py agents` (else no tiebreak); a job aged an hour still passes Main's. 2. A job waits at disk stage stop or critical, at warn when it needs disk, - at memory stage stop, during a radio-silence mayday, while its kind's - slots are taken, or behind an earlier job of its worktree, compose stack + at memory stage stop, during a radio-silence mayday, while a + configured `slot_limits` cap of its kind is reached, + or behind an earlier job of its worktree, compose stack or `INFINITO_INSTANCE` slot; a job passes one that can never start, a light job one awaiting only the machine, a hotfix all but hotfixes and running jobs; `exclusive_kinds` run only beside `light_kinds`. -3. A job fits if its disk need keeps the stop threshold free and its - footprint the running ones within `budget_percent` (alone always), and - passes blocked jobs, but the head (a blocked hotfix, an exclusive job - running jobs keep out, one stuck a minute or an hour old, or for other - lines a Main job whose line runs or awaits the machine) only taking - nothing it lacks, its last slot included, and only light while it is a - hotfix, exclusive or held by queue load. +3. A job fits if its disk need keeps the stop threshold free and the load + band and target admit it (alone always; `band.md` before changing a + limit or reading a band, target or settles reason), and passes blocked + jobs, but the head (a blocked hotfix, an exclusive job running jobs keep + out, one stuck a minute or an hour old, or for other lines a Main job + whose line runs or awaits the machine) only taking nothing it lacks, and + only light while it is a hotfix, exclusive or held by queue load. 4. An unblocked job counts as granted for the jobs behind it. 5. Every job, alone too, needs CPU, and RAM used plus what it and the - running jobs may still take, below `load_limits`; outside load makes no + running jobs may still take, below the live guard `load_limits`; outside load makes no head and holds no line. 6. A stall escalates itself (`ESCALATION` in queue.py). ## History and learning -Finished jobs teach disk need, slot limits and footprints via +Finished jobs teach disk need and footprints via `queue-history.jsonl`; read `learning.md` before changing a seed or limit. ## Inspect and cancel @@ -71,18 +72,18 @@ queue.py history queue.py cancel ``` -`list` shows position, ETA and blocking reason (`--json`: rule trace), `history` the learned values, `cancel` removes your waiting job. +`list`: position, ETA, reason (`--json`: trace); `history`: learned values; +`cancel`: drops your job. Operator commands: `controls.md`. ## Rules -- Never ask the chair for a heavy slot or announce a grant; the chair handles - only a stuck queue or hung job (`capacity.md` of `kvb-org-organize`). +- Never ask the chair for a slot or announce a grant; it handles only a + stuck queue or hung job (`capacity.md`, `kvb-org-organize`). - Only the operator, a `kvb-git-hotfix` gate void, or hold after 60 minutes of tree standstill (exit 124) cut a job short. `kvb-org-queue-cleanup` deletes only entries whose lock no living process holds. - With `queue_enforce: true`, the `block` hook (PreToolUse on Bash) refuses `heavy_commands`, image builds, `make install|test*|quality*|verify-*`, tests beyond one unit file and `gate.py run|hold` outside `queue.py hold`. -- Without the config, hold exits 2: tell the operator, ask the chair - (`kvb-org-organize`). Waiting holds reread it every poll, keeping the - last good one. +- Without the config, hold exits 2: tell the operator, ask the chair. + Holds reread it each poll, keeping the last good one. diff --git a/skills/kvb-org-queue/band.md b/skills/kvb-org-queue/band.md new file mode 100644 index 0000000..055c223 --- /dev/null +++ b/skills/kvb-org-queue/band.md @@ -0,0 +1,48 @@ +# Utilization band, limits file and self-tuning + +## Utilization band + +`load_limits.band_low` and `band_high` (default 70 and 90) steer the +queue's concurrency: while a queue job runs, a job starts only while +measured CPU and RAM (plus young jobs' ramp and this pass's grants) lie +below `band_low` (`load 72 % RAM >= 70 % band`) and stay at or below +`band_high` with its learned footprint (`would reach 93 % RAM > 90 %`); +an unlearned kind books `budget_percent`. Behind a reserving head a job +starts only while load plus the head's and its own footprint stays within +`band_high`, its last capped slot included; else it waits `reserved for +`, and `drained for ` only when the head cannot fit even alone. +Keep the live guard +`mem_percent` above `band_high`, or it holds jobs first. + +## Limits file + +`/limits.json` (the `AGENTS_COUNCIL_ROOT` directory) is the +one source of the limits for queue, watch and hub: + +```json +{"cpu": {"lower": 70, "upper": 90, "stop": 95, "mayday": 99}, + "ram": {"lower": 70, "upper": 85, "stop": 92, "mayday": 97}, + "swap": {"lower": 20, "upper": 60, "stop": 90, "mayday": 97}, + "disk": {"lower": 70, "upper": 85, "stop": 95, "mayday": 98}, + "psi": {"lower": 1, "upper": 10, "stop": 30, "mayday": 60}} +``` + +All five metrics with all four levels, each a percent 0 to 100 (CPU busy, +RAM, swap and disk used, memory PSI some avg10), lower < upper < stop < +mayday per metric. Readers: queue band = cpu/ram lower and upper, live +guard = their stop; watch memory warn = ram/swap/psi upper, stop = their +stop; disk warn, stop (the queue floor) and critical = disk upper, stop and +mayday. A refused file keeps `limits.last.json`, the last valid copy, in +force; without the file the config applies (`kvb-org-organize/scripts/limits.py`). + +## Self-tuning target + +Each poll steps a target per CPU and RAM in `limits-target.json`, starting +at upper: +2 while the 10-minute average lies below lower and PSI is calm +(below psi lower, else 1), down to the middle of lower and itself at once +when load passes upper, PSI rises or swap goes out. A job fits only while +load plus its footprint stays within the target (`would reach 88 % RAM > +target 84.0 %`); while a job runs, one grant per `sample_seconds` +(`settles: ...`). Footprints are the command's RAM p95 and CPU median, +times its learned margin (`learning.md`). The `list` header names target, +band and limits source. diff --git a/skills/kvb-org-queue/controls.md b/skills/kvb-org-queue/controls.md new file mode 100644 index 0000000..e4761bc --- /dev/null +++ b/skills/kvb-org-queue/controls.md @@ -0,0 +1,32 @@ +# Queue controls + +The operator steers the queue from the hub's Controls tab Queue; agents never +run these commands. + +## Start now + +`queue.py override ` marks a waiting job. Its next poll grants it ahead +of rank, past the utilization band, slot limits, reservations and `after` waits, +while the live guard (`load_limits` CPU and RAM), the memory stage, radio +silence, the disk stage and floor and a running job of its worktree, stack +or slot allow; otherwise its reason starts with `override held by`. Its +history row records `override: true`. An unknown or running id exits 2. + +## Learnings and settings + +`queue.py learned --json` prints per kind the runs, shares, slot limit and +caps, per signature the learned values, the settings and the last 20 history +rows; it writes nothing. + +`queue.py config set ` changes one of `budget_percent.ram|cpu`, +`load_limits.cpu_percent|mem_percent|sample_seconds|band_low|band_high` +(band_low below band_high), +`slot_limits.` and `ram_cap_percent.` (a kind of +`slot_need_gb`). A bad value exits 2 and leaves the file byte-identical; a +good one rewrites the file atomically, every other key kept. + +## Hub path + +The hub stages the changes and one passkey signs the batch; the host runner +(`--queue`) runs each as `queue.py ` and refuses every other argv. The +hub reads the config through a read-only mount and never writes it. diff --git a/skills/kvb-org-queue/learning.md b/skills/kvb-org-queue/learning.md index 2aa56d1..524e2ea 100644 --- a/skills/kvb-org-queue/learning.md +++ b/skills/kvb-org-queue/learning.md @@ -10,11 +10,16 @@ From the last 30 days, once 5 runs exist: - per job, the disk need is p90 disk taken plus 1 GB over the runs of its signature and kind; until 5 exist there, the largest such need its signature and the command's older signature learned over every kind; -- per kind, the slot limit is how many p90 RAM and median CPU shares fit - between the median load at the grant and `load_limits`, at least 1; +- per kind, the reported slot limit is how many p90 RAM and median CPU + shares fit between the median load at the grant and `load_limits`, at + least 1; it blocks nothing, the utilization band admits; - per job, the footprint is its signature's share over the runs of its - kind; until 5 exist there, the largest of its kind's share and what its - signature and the command's older signature learned over every kind. + kind, the p95 of the peak RAM and CPU taken times its margin; until 5 + exist there, the largest of its kind's share and what its signature and + the command's older signature learned over every kind; +- per signature, the margin starts at 1.0, grows by the overshoot ratio + after a run that took more than its grant booked (`predicted` on the + row) and shrinks by 0.05 after one that took less, always 1.0 to 2.0. A job of a kind outside `light_kinds` never books less than the queue before the per-kind learning: at least the share its older signature learned over @@ -27,9 +32,9 @@ never learns from a suite; the older signature is `: `, which older rows carry. A granted job keeps the footprint it was granted on. -Until then the seeds hold: `slot_need_gb[kind]` for disk, 1 slot per kind, -the whole budget as footprint. -The optional `slot_limits {kind: N}` only caps a limit from above. +Until then the seeds hold: `slot_need_gb[kind]` for disk, the whole +`budget_percent` as footprint. +The optional `slot_limits {kind: N}` is the operator's hard cap per kind. The optional `ram_cap_percent {kind: percent}` caps the RAM share a job of that kind books, its footprint and its ceiling, while the learned shares and the history rows stay raw; keep it truthful by limiting the job's own memory diff --git a/skills/kvb-org-queue/scripts/aimd.py b/skills/kvb-org-queue/scripts/aimd.py new file mode 100644 index 0000000..7346b21 --- /dev/null +++ b/skills/kvb-org-queue/scripts/aimd.py @@ -0,0 +1,91 @@ +"""The self-tuning admission target of kvb-org-queue (requirement 083): additive increase, multiplicative decrease. + +queue.py keeps the state in /NAME, next to the kvb-org-organize limits +file: {ram, cpu: the target in percent, psi: the PSI some avg10 at the last +step or None, stepped: that step's epoch seconds, samples: [[epoch seconds, +CPU busy, RAM used], ...] of the last WINDOW_SECONDS}. Pure functions. +STEP and WINDOW_SECONDS are the 2 points and 10 minutes requirement 083 +fixes; PSI_CALM is the calm bound while no limits file names psi lower: +below 1 % some avg10 no task waits on memory long enough to slow a job. +""" + +from __future__ import annotations + +import math + +NAME = "limits-target.json" +RESOURCES = ("ram", "cpu") +STEP = 2 +WINDOW_SECONDS = 600 +PSI_CALM = 1.0 + + +def number(value: object) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def target(state: dict, band: dict[str, dict[str, float]]) -> dict[str, float]: + """Args: + state: the stored state, {} for none. + band: {low, high} per resource: the lower and the upper limit. + + Returns: + {ram, cpu}: the stored target kept between low and high, high where + none is stored, so a fresh queue admits up to the upper limit until + the host shows pressure. + """ + return {r: min(band["high"][r], max(band["low"][r], state[r])) if number(state.get(r)) else band["high"][r] for r in RESOURCES} + + +def kept(samples: object, now: float) -> list[list[float]]: + rows = samples if isinstance(samples, list) else [] + return [ + row for row in rows + if isinstance(row, list) and len(row) == 3 and all(number(v) for v in row) and 0 <= now - row[0] <= WINDOW_SECONDS + ] + + +def average(samples: list[list[float]]) -> dict[str, float]: + return {"cpu": sum(row[1] for row in samples) / len(samples), "ram": sum(row[2] for row in samples) / len(samples)} + + +def stepped(state: dict, band: dict[str, dict[str, float]], load: dict[str, float], pressure: dict[str, float | None], + psi_calm: float, now: float, every: float) -> dict: + """Args: + state: the stored state, {} for none. + band: {low, high} per resource: the lower and the upper limit. + load: {ram, cpu} measured now, in percent. + pressure: the watch memory sample: psi_some (PSI some avg10, None + without PSI) and swap_out_mb_min (None without a rate). + psi_calm: the PSI some avg10 below which memory counts as calm (the + limits file's psi lower, else PSI_CALM). + now: epoch seconds. + every: seconds from one step to the next; a pass sooner only adds + its sample. + + Returns: + The new state: this sample added, those older than WINDOW_SECONDS + dropped. Once every seconds passed since the last step, per + resource the target falls at once to the middle of low and itself + when the load now passes high, PSI rises (at or above psi_calm and + above the last step's, or without one) or swap goes out; else it + rises by STEP, at most to high, while the WINDOW_SECONDS average + lies below low and PSI is calm. + """ + samples = [*kept(state.get("samples"), now), [now, load["cpu"], load["ram"]]] + aim = target(state, band) + last = state.get("stepped") + if number(last) and 0 <= now - last < every: + return {**state, **aim, "samples": samples} + psi, before = pressure.get("psi_some"), state.get("psi") + calm = psi is None or psi < psi_calm + rising = not calm and (not number(before) or psi > before) + swapping = (pressure.get("swap_out_mb_min") or 0) > 0 + mean = average(samples) + for r in RESOURCES: + low, high = band["low"][r], band["high"][r] + if load[r] > high or rising or swapping: + aim[r] = (low + aim[r]) / 2 + elif mean[r] < low and calm: + aim[r] = min(high, aim[r] + STEP) + return {**state, **aim, "samples": samples, "psi": psi, "stepped": now} diff --git a/skills/kvb-org-queue/scripts/history.py b/skills/kvb-org-queue/scripts/history.py index e05e1b6..2b7f708 100644 --- a/skills/kvb-org-queue/scripts/history.py +++ b/skills/kvb-org-queue/scripts/history.py @@ -6,9 +6,12 @@ and the copy the kvb-org-organize watch hook keeps in ~/.local/state. A row: id, kind, signature, workdir, start, end (epoch seconds), minutes, exit, free_before_gb, min_free_gb, disk_gb (free_before_gb - min_free_gb, at least 0), mem_before, mem_max, cpu_before, cpu_max (percent), concurrent (other -active jobs at the grant), and HUNG ({cpu_s, read_bytes, written_bytes, -still_min, members, tree}, the report of standstill.py) only on a run hold -ended for standing still, whose exit is 124. +active jobs at the grant), PREDICTED ({ram, cpu}, the footprint the grant +booked) only on a run granted on a learned footprint, and HUNG ({cpu_s, +read_bytes, written_bytes, still_min, members, tree}, the report of +standstill.py) only on a run hold ended for standing still, whose exit is +124, and override (true) only on a run `queue.py override` started past the +budget; learn() counts it like every other run. """ from __future__ import annotations @@ -35,7 +38,11 @@ KIND_KEY = operator.itemgetter("kind") ANY_KIND = "*" RAM_CAP = "ram_cap_percent" HUNG = "hung" -SIGNATURE_HEADER = ("Signature", "Kind", "Runs", "Median min", "p90 disk GB", "p90 RAM %", "Need GB") +PREDICTED = "predicted" +MARGIN = (1.0, 2.0) +MARGIN_SHRINK = 0.05 +SHARE_SOURCES = {"ram": "mem", "cpu": "cpu"} +SIGNATURE_HEADER = ("Signature", "Kind", "Runs", "Median min", "p90 disk GB", "p95 RAM %", "Margin", "Need GB") KIND_HEADER = ("Kind", "Runs", "p90 RAM share %", "Median CPU share %", "Slot limit", "Source") def first_operand(tokens: Iterable[str]) -> list[str]: @@ -86,7 +93,8 @@ def row(job: dict, start: float, end: float, code: int, samples: list[dict[str, """Build the history row of a finished job. Args: - job: its id, kind, signature and workdir. + job: its id, kind, signature and workdir, with HUNG and override when + set. start: epoch seconds the command started. end: epoch seconds it ended. code: its exit code. @@ -148,6 +156,12 @@ def p90(values: list[float]) -> float: return statistics.quantiles(values, n=10, method="inclusive")[-1] +def p95(values: list[float]) -> float: + import statistics + + return statistics.quantiles(values, n=20, method="inclusive")[-1] + + def median(values: Iterable[float]) -> float: import statistics @@ -167,17 +181,42 @@ def grouped(rows: list[dict], key: Callable[[dict], Hashable]) -> dict[Hashable, def command_stats(rows: list[dict]) -> dict: stats = {"runs": len(rows), "minutes": None, "longest": None, "disk_gb": None, "ram_share": None, "cpu_share": None, - "need_gb": None} + "need_gb": None, "margin": margin(rows)} if len(rows) >= MIN_RUNS: disk = p90([r["disk_gb"] for r in rows]) stats.update( minutes=median(r["minutes"] for r in rows), longest=max(r["minutes"] for r in rows), disk_gb=disk, - ram_share=p90(shares(rows, "mem")), cpu_share=median(shares(rows, "cpu")), + ram_share=p95(shares(rows, "mem")), cpu_share=median(shares(rows, "cpu")), need_gb=math.ceil(disk + DISK_MARGIN_GB), ) return stats +def margin(rows: list[dict]) -> float: + """Returns: + The factor a command's learned shares are booked with, replayed + over its rows by end: from MARGIN[0], a row whose share (max minus + before) passed what its grant booked (PREDICTED) on a resource + multiplies it by the largest such ratio, any other row with + PREDICTED lowers it by MARGIN_SHRINK; always within MARGIN. Rows + without PREDICTED leave it as it is. + """ + value = MARGIN[0] + for row in sorted(rows, key=lambda r: r["end"]): + booked = row.get(PREDICTED) + if not isinstance(booked, dict): + continue + ratios = [ + (row[f"{source}_max"] - row[f"{source}_before"]) / booked[resource] + for resource, source in SHARE_SOURCES.items() + if isinstance(booked.get(resource), (int, float)) and not isinstance(booked[resource], bool) and booked[resource] > 0 + ] + if ratios: + worst = max(ratios) + value = min(MARGIN[1], max(MARGIN[0], value * worst if worst > 1 else value - MARGIN_SHRINK)) + return value + + def fit(ceiling: float, rows: list[dict], resource: str, share: float) -> int: before = median(r[f"{resource}_before"] for r in rows) return math.floor((ceiling - before) / max(share, MIN_SHARE_PERCENT)) @@ -207,16 +246,17 @@ def learn(rows: list[dict], now: float, cfg: dict) -> tuple[dict[tuple[str, str] Returns: (signatures, kinds). signatures: {(kind, signature): {runs, minutes, - longest, disk_gb, ram_share, cpu_share, need_gb}}, and {(ANY_KIND, signature): + longest, disk_gb, ram_share, cpu_share, need_gb, margin}}, and {(ANY_KIND, signature): ...} over the rows of every kind with that signature, which is what a queue before the per-kind learning booked; kinds: {kind: {runs, ram_share, cpu_share, limit, light, ram_cap}}, ram_cap None without a - cap. With fewer than MIN_RUNS rows every value but runs, light and - ram_cap is None. - minutes is the median and longest the largest minutes, disk_gb and - ram_share the p90 of the disk taken - and of max minus before in percentage points, cpu_share the median of - max minus before; need_gb is ceil(disk_gb + DISK_MARGIN_GB); limit is + cap. With fewer than MIN_RUNS rows every value but runs, margin, light + and ram_cap is None. + minutes is the median and longest the largest minutes, disk_gb the + p90 of the disk taken; a signature's ram_share and cpu_share are the + p95 of max minus before in percentage points, its margin margin(); + a kind's ram_share is the p90 and its cpu_share the median of max + minus before; need_gb is ceil(disk_gb + DISK_MARGIN_GB); limit is max(1, min over RAM and CPU of floor((load limit - median before) / max(share, MIN_SHARE_PERCENT))). """ @@ -255,7 +295,8 @@ def footprint(kind: str, aliases: tuple[str, ...], signatures: dict[tuple[str, s Returns: {ram, cpu}: the signature's share under kind once MIN_RUNS rows exist - there, for a kind not light at least booked_before(); else the + there, each share times its margin (largest()), for a kind not light + at least booked_before(); else the largest of the kind's share and each alias's share over every kind, so a shape without runs of its own never books less than its kind or the runs it was learned from; at least MIN_SHARE_PERCENT; RAM at most @@ -296,7 +337,14 @@ def ceiling(kind: str, aliases: tuple[str, ...], signatures: dict[tuple[str, str def largest(sources: list[dict]) -> dict[str, float]: - return {resource: max(MIN_SHARE_PERCENT, *(s[f"{resource}_share"] for s in sources)) for resource in RESOURCES} + """Returns: + {ram, cpu}: the largest share of sources, each times its margin + (1.0 for a kind's stats), at least MIN_SHARE_PERCENT. + """ + return { + resource: max(MIN_SHARE_PERCENT, *(s[f"{resource}_share"] * s.get("margin", MARGIN[0]) for s in sources)) + for resource in RESOURCES + } def capped(stats: dict, shares: dict[str, float]) -> dict[str, float]: @@ -339,7 +387,8 @@ def need_gb(signatures: dict[tuple[str, str], dict], kinds: dict[str, dict], kin def slot_limits(kinds: dict[str, dict], caps: dict[str, int], names: Iterable[str]) -> dict[str, tuple[int, str]]: - """Decide the slot limit of every kind. + """Report the slot limit history fits for every kind; queue.py admits by + its utilization band, and only the config caps bind there. Args: kinds: the kind map of learn(). @@ -411,7 +460,7 @@ def report(signatures: dict[tuple[str, str], dict], kinds: dict[str, dict], limi """ commands = [ [name, kind, str(s["runs"]), cell(s["minutes"]), cell(s["disk_gb"]), - cell(s["ram_share"]), "-" if s["need_gb"] is None else str(s["need_gb"])] + cell(s["ram_share"]), f"{s.get('margin', MARGIN[0]):.2f}", "-" if s["need_gb"] is None else str(s["need_gb"])] for (kind, name), s in sorted(signatures.items(), key=lambda item: item[0][::-1]) if kind != ANY_KIND ] per_kind = [] diff --git a/skills/kvb-org-queue/scripts/queue.py b/skills/kvb-org-queue/scripts/queue.py index ba4ad74..25eb1b7 100755 --- a/skills/kvb-org-queue/scripts/queue.py +++ b/skills/kvb-org-queue/scripts/queue.py @@ -7,6 +7,9 @@ Usage: queue.py list [--json] queue.py history queue.py cancel ID [--session ID] + queue.py override ID + queue.py learned --json + queue.py config set KEY VALUE queue.py block hook (PreToolUse on Bash through hooks.py pre-bash) Environment: @@ -68,12 +71,15 @@ Args: exits 0 on the tree it started on (gates.py tree of the workdir before and after) hold records a receipt for that tree, level and log, with INFINITO_TEST_GPU of its environment. - list: a header, then one line per entry: position (run for active jobs), + list: a header whose reason column names the AIMD target, the band and + the limits source (targets()), then one line per entry: position (run for active jobs), id, status, kind, task, need GB, minutes waited, ETA minutes (until a running job ends or a waiting one starts, from learned medians; - while one is unknown), workdir, reason (the one the holder saw at its last - poll, host load included, such as `waits in line behind ` or - `drained for `, the head's after `escalated : ` once the + poll, host load included, such as `waits in line behind `, + `load 72 % RAM >= 70 % band`, `would reach 93 % RAM > target 84.0 %`, + `settles: the last grant was 2 s ago, one grant per 5 s`, + `reserved for ` or `drained for `, the head's after `escalated : ` once the stall reached it; `backfilled` for a job started past a blocked one; led by `suspect hung ( min)` for an active job past standstill.suspect_seconds() (suspected()); prefixed when the entry @@ -84,6 +90,20 @@ Args: history: a markdown table per command signature and one per kind of what the last 30 days of history teach, with each slot limit's source. cancel ID: remove the caller's waiting entry ID; its hold exits 3. + override ID: mark the waiting entry ID, of any session, with OVERRIDE + {ts}; every pass grants the marked entries first, oldest mark + first, skipping the band, slot limits, reservations, rank and + `after` waits, while the live guard (load_limits), the memory + stage, radio silence, the disk stage and floor and the lines of + running jobs allow (forced()); else its reason starts with + `override held by`. Its history row carries override true. The + operator runs it, through the hub's signed Start now. + learned --json: print what learnings() lists, writing nothing. + config set KEY VALUE: set one setting of the config file (SETTINGS, + KIND_SETTINGS) to the number VALUE after the config check + (config_problem(), bound_problem()), rewriting the file atomically + as indented JSON in its mode, every other key kept; a link or an + unusable file is refused. block: read the hook payload on stdin. The permission matcher sees only `queue.py hold`, so every hold in the command is parsed like hold itself, and a held command any of whose word-started tails meets a @@ -94,11 +114,17 @@ Args: `gate.py run|hold`, unless it matches never_block or runs `queue.py hold`. -Config keys: budget_percent {ram, cpu}, required: the active and granted jobs' -learned footprints (history.footprint, the whole budget for a kind not learned -yet) may sum to at most these percentage points, a job alone always fits; -slot_limits {kind: N}, optional, caps the learned slot limit of a kind from -above (history.slot_limits); ram_cap_percent {kind: percent above 0 up to +Config keys: budget_percent {ram, cpu}, required: the footprint booked for a +job whose kind is not learned yet (history.footprint); load_limits.band_low +and band_high, optional (BAND: 70 and 90), percentages above 0 with band_low +below band_high: while a queue job runs or was granted in the pass, a job +starts only while the live load (measured, plus what young jobs and admits +still add, plus the pass's grants; live_load()) lies below band_low on CPU +and RAM and, with the job's learned footprint added, stays at or below +band_high (band_reason()), a job alone always fits; slot_limits {kind: N}, +optional, the operator's hard cap of concurrent jobs of a kind, a kind +missing there has no count cap (history.slot_limits only reports what +history would fit); ram_cap_percent {kind: percent above 0 up to 100}, optional, caps the RAM share history.footprint and history.ceiling book for a job of that kind, the learned shares stay raw; exclusive_kinds [kind] and light_kinds [kind], optional: a job of an exclusive kind runs only beside jobs of light kinds, and @@ -106,11 +132,22 @@ no job of another kind starts beside it; queue_enforce (bool), optional, read by disk, thresholds_gb (stop is the floor every grant leaves free), slot_need_gb (the disk seed per kind), load_limits (every grant also needs CPU busy below cpu_percent and RAM used plus the job's learned RAM share, the live admit records (admit()) and the young jobs' ramp -(ramping_ram()) below mem_percent; both bound the learned slot limits), memory_limits (no +(ramping_ram()) below mem_percent, the live guard above the band), memory_limits (no grant at memory stage stop), heavy_commands and never_block are used as watch.py documents them. A signature is `: ` (aliases()). +Self-tuning (requirement 083): the limits file /limits.json of the +kvb-org-organize limits.py, while in force, sets the band from cpu and ram +lower and upper and the live guard from their stop. Every poll steps the +AIMD target (aimd.py, at most once per POLL_SECONDS, kept in +/limits-target.json): a job starts only while the load plus its +footprint stays at or below the target (`would reach % RAM > target + %`), and while a queue job runs at most one grant lands per +load_limits.sample_seconds after the last (settle_reason()). The footprint +is history.footprint: the p95 of the command's shares times its learned +margin. + Exit codes: hold: the command's exit code unchanged, 128+N when signal N ended it, standstill.HUNG_EXIT (124) when hold ended it for standing still; @@ -122,9 +159,15 @@ Exit codes: the installed hold's exit code. list, history: 0 done, 2 config error. cancel: 0 removed, 2 no waiting entry of the caller with that id. + override: 0 marked, 2 no waiting entry with that id; the queue stays + unchanged. + learned: 0 done, 2 config error. + config set: 0 written, 2 an unknown key, a value the config check + refuses or a config it cannot read; the file stays byte-identical. block: 0 allow, or ask when it prints an ask decision, or a council root that watch.py refuses; 2 refuse the tool call; every other error allows. - list, history, cancel, hold: 2 on a council root that watch.py refuses. + list, history, cancel, override, learned, config, hold: 2 on a council + root that watch.py refuses. """ from __future__ import annotations @@ -138,6 +181,7 @@ import functools import hashlib import importlib.util import json +import math import os import re import select @@ -162,6 +206,8 @@ SIBLINGS = { "standstill": Path(__file__).resolve().parent / "standstill.py", "nofollow": SKILLS / "kvb-org-organize" / "scripts" / "nofollow.py", "councilroot": SKILLS / "kvb-org-organize" / "scripts" / "councilroot.py", + "limits": SKILLS / "kvb-org-organize" / "scripts" / "limits.py", + "aimd": Path(__file__).resolve().parent / "aimd.py", } TOOLS = {"gates": SKILLS / "kvb-check-gate" / "scripts" / "gates.py"} HOST_SKILLS = Path.home() / ".agents" / "skills" @@ -180,6 +226,16 @@ THROUGH_QUEUE = re.compile(r"\bqueue\.py\s+hold\b") BASH_RULE = re.compile(r"Bash(?:\((.*)\))?", re.DOTALL) RULE_PART = re.compile(r"( \*|\*)") BUDGET_KEYS = ("budget_percent.ram", "budget_percent.cpu") +OVERRIDE = "override" +SETTINGS = { + "budget_percent": ("ram", "cpu"), "load_limits": ("cpu_percent", "mem_percent", "sample_seconds", "band_low", "band_high"), +} +PERCENT_KEYS = ("load_limits.cpu_percent", "load_limits.mem_percent", "load_limits.band_low", "load_limits.band_high") +BAND = {"band_low": 70, "band_high": 90} +GRANTED_CPU = "granted_cpu" +SLOT_LIMITS = "slot_limits" +NUMBER = re.compile(r"(0|[1-9][0-9]{0,5})(\.[0-9]{1,3})?") +HISTORY_SHOWN = 20 HOTFIX = "hotfix/" PYTEST = frozenset({"pytest", "py.test"}) XDIST = frozenset({"-n", "--numprocesses"}) @@ -235,12 +291,16 @@ watch = sibling("watch") history = sibling("history") standstill = sibling("standstill") nofollow = sibling("nofollow") +limit_file = sibling("limits") +aimd = sibling("aimd") STORE = watch.ROOT / "queue.json" +TARGET = watch.ROOT / aimd.NAME LOCK = watch.ROOT / "queue.lock" HOLDS = watch.ROOT / "holds" TAG = re.compile(r"\d+-\d+") SILENCE = watch.ROOT / "radio-silence.json" HISTORIES = (watch.HISTORY, watch.KEPT_HISTORY) +KIND_SETTINGS = (SLOT_LIMITS, history.RAM_CAP) LEARNED: dict[str, tuple[dict, dict]] = {} @@ -275,12 +335,44 @@ def config() -> dict: cfg, _ = watch.announced_config() if cfg is None: fail(f"no config at {watch.CONFIG}; the queue reads the kvb-org-organize watch config") - problem = watch.missing(cfg, (*BUDGET_KEYS, *watch.MEMORY_KEYS)) or cap_problem(cfg) + problem = config_problem(cfg) if problem is not None: fail(problem) return cfg +def config_problem(cfg: dict) -> str | None: + return watch.missing(cfg, (*BUDGET_KEYS, *watch.MEMORY_KEYS)) or cap_problem(cfg) or band_problem(cfg) + + +def band_problem(cfg: dict) -> str | None: + """Returns: + Why load_limits.band_low and band_high (BAND where unset) are no + finite numbers above 0 with band_low below band_high, None when + they are. + """ + limits = cfg.get("load_limits") + values = [limits.get(key, BAND[key]) if isinstance(limits, dict) else None for key in BAND] + if all(isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) and v > 0 for v in values) and values[0] < values[1]: + return None + return "load_limits.band_low and load_limits.band_high are percentages above 0, band_low below band_high" + + +def band(cfg: dict) -> dict[str, dict[str, float]]: + """Returns: + {low: {ram, cpu}, high: {ram, cpu}}: the lower and upper limit of + cpu and ram under the limits file in force (limit_file.KEY), else + load_limits.band_low and band_high of the config, BAND where unset, + for both resources. + """ + held = cfg.get(limit_file.KEY) + if held is not None: + return {"low": {r: held[r]["lower"] for r in history.RESOURCES}, "high": {r: held[r]["upper"] for r in history.RESOURCES}} + limits = cfg["load_limits"] + low, high = (limits.get(key, BAND[key]) for key in BAND) + return {"low": dict.fromkeys(history.RESOURCES, low), "high": dict.fromkeys(history.RESOURCES, high)} + + def cap_problem(cfg: dict) -> str | None: """Returns: Why history.RAM_CAP is no {kind: percent above 0 up to 100} map, None @@ -296,21 +388,22 @@ def cap_problem(cfg: dict) -> str | None: def fresh(cfg: dict) -> dict: """Returns: - The config as it stands now, else cfg while the file is missing, - unusable (watch.checked_config()) or incomplete, so a half-saved - edit never ends a wait. + The config as it stands now under the limits file in force + (watch.with_limits()), else cfg while the file is missing, unusable + (watch.checked_config()) or incomplete, so a half-saved edit never + ends a wait. """ try: - now = watch.checked_config(watch.load_config()) + now = watch.with_limits(watch.checked_config(watch.load_config()))[0] except watch.UNUSABLE: return cfg - if (watch.missing(now, (*BUDGET_KEYS, *watch.MEMORY_KEYS)) or cap_problem(now)) is not None: + if config_problem(now) is not None: return cfg return now def caps(cfg: dict) -> dict[str, int]: - return cfg.get("slot_limits", {}) + return cfg.get(SLOT_LIMITS, {}) def marks(paths: tuple[Path, ...]) -> tuple[tuple[int, int, int] | None, ...]: @@ -662,21 +755,58 @@ def in_lines(order: list[dict]) -> list[dict]: return list(placed.values()) -def over_budget(used: dict[str, float], share: dict[str, float], budget: dict[str, float]) -> str | None: - over = [resource for resource in budget if used[resource] + share[resource] > budget[resource]] +def band_reason(used: dict[str, float], share: dict[str, float], band: dict[str, dict[str, float]]) -> str | None: + """Args: + used: the load per resource in percent: measured, still to come and + granted earlier in the pass. + share: the job's footprint in percentage points. + band: {low, high} per resource (band()), with target per resource + when the AIMD target binds (aimed()). + + Returns: + None when every resource lies below low and stays at or below + ceiling() with share added, else why not: `load % >= + % band`, else `would reach % > %`, or + `> target %` while the target binds. + """ + hot = [resource for resource in used if used[resource] >= band["low"][resource]] + if hot: + return ", ".join(f"load {used[r]:.0f} % {r.upper()} >= {band['low'][r]:g} % band" for r in hot) + limit = ceiling(band) + over = [resource for resource in used if used[resource] + share[resource] > limit[resource]] if not over: return None - return ", ".join( - f"{resource.upper()} {used[resource]:.0f} % in use or reserved + {share[resource]:.0f} % > budget {budget[resource]:g} %" - for resource in over - ) + named = {r: f"target {limit[r]:.1f}" if "target" in band else f"{limit[r]:g}" for r in over} + return ", ".join(f"would reach {used[r] + share[r]:.0f} % {r.upper()} > {named[r]} %" for r in over) + + +def ceiling(band: dict[str, dict[str, float]]) -> dict[str, float]: + return band.get("target", band["high"]) + + +def settle_reason(settle: tuple[float, float | None] | None, now: float) -> str | None: + """Args: + settle: (the settle window in seconds, load_limits.sample_seconds; + epoch seconds of the last grant or None), None for no window. + now: epoch seconds. + + Returns: + `settles: the last grant was s ago, one grant per s` while + the window since the last grant is open, else None. + """ + if settle is None or settle[1] is None: + return None + window, last = settle + waited = now - last + return f"settles: the last grant was {waited:.0f} s ago, one grant per {window:g} s" if 0 <= waited < window else None def evaluate(entries: list[dict], free_gb: float, floor: float, stage: str, memory: str, silenced: bool, - slot_limits: dict[str, int], footprints: dict[str, dict[str, float]], budget: dict[str, float], - ranks: dict[str, int], agents: dict[str, int], loaded: dict[str, str], + slot_limits: dict[str, int], footprints: dict[str, dict[str, float]], band: dict[str, dict[str, float]], + load: dict[str, float], ranks: dict[str, int], agents: dict[str, int], loaded: dict[str, str], exclusive: set[str], light: set[str], drain: str | None, - now: float, *, trace: dict[str, list[str]] | None = None) -> tuple[dict[str, str | None], str | None, list[dict]]: + now: float, *, trace: dict[str, list[str]] | None = None, + settle: tuple[float, float | None] | None = None) -> tuple[dict[str, str | None], str | None, list[dict]]: """Decide every waiting entry in grant order, without disk or processes. Args: @@ -686,11 +816,19 @@ def evaluate(entries: list[dict], free_gb: float, floor: float, stage: str, memo stage: the watch disk stage: ok, warn, stop or critical. memory: the watch memory stage: ok, warn or stop. silenced: whether a radio-silence mayday holds. - slot_limits: {kind: max concurrent jobs}, an upper cap beside the budget. + slot_limits: {kind: max concurrent jobs}, the operator's hard caps of + the config (slot_limits); a kind missing there has no count cap. footprints: {entry id: {ram, cpu}}, the learned share of every entry (footprint(), an active one's as granted), in percentage points. - budget: {ram, cpu}: the sum of the footprints of active and granted - entries may not pass it; a job alone always fits. + band: {low, high} per resource (band()), with the AIMD target per + resource when one binds (aimed()): while a queue job runs or was + granted in the pass, a job starts only while the load lies below + low on every resource and with its footprint added stays at or + below the target, else high (ceiling(), band_reason()); a job alone + always fits. + load: {ram, cpu}: the host load in percent the band starts from: + measured plus what young jobs and admits still add (live_load()); + each grant of the pass, overridden ones first, adds its footprint. ranks: {task: index in the register's ranking}; a task missing there ranks after all of them. agents: {agent name: index in the operator's agent order}; it breaks @@ -709,21 +847,32 @@ def evaluate(entries: list[dict], free_gb: float, floor: float, stage: str, memo `) per entry it passes, then the rule that blocked it, or `takes nothing lacks`, the fit and `backfilled past ` for a granted one. + settle: (window seconds, the last grant's epoch seconds or None): + while a queue job runs or was granted in the pass and the window + since the last grant is open, every entry that would start waits + with settle_reason(), so at most one grant lands per window; None + checks no window. Returns: ({entry id: None when granted, else the blocking reason, a Disk when the disk stage or the floor alone blocks it} in grant order, the entry the next pass drains for (drained()), the polling waiting entries in - grant order). A granted entry counts against the disk, budget and + grant order). A granted entry counts against the disk, band and slots of the entries after it, whoever holds it. A blocked entry reserves nothing, so a later entry that fits starts past it (backfill), except the head: drain, or before it a blocked hotfix that is the first blocked entry not unstartable() or an exclusive entry that only running jobs of other kinds keep out (alone_reason()). Behind the head every later entry, light ones too, starts only when it takes - nothing the head still lacks, the last slot of its kind included + nothing the head still lacks: the load plus the head's footprint + plus its own stays at or below the band's high, the disk after both + needs above floor, the last capped slot of its kind included (takes(); beside a head that is - exclusive or waits for an exclusive job only light jobs count); every + exclusive or waits for an exclusive job only light jobs count, the + load less the footprints of the other running jobs); one that takes + what the head lacks waits `reserved for `, or `drained for + ` when the head cannot fit even with nothing backfilled (live + load holds it or its own footprint breaks the band); every later one but light ones waits behind a hotfix head, and behind any head whose kind is exclusive or that live load holds while queue jobs run; light ones wait too while load the @@ -743,20 +892,28 @@ def evaluate(entries: list[dict], free_gb: float, floor: float, stage: str, memo entry of the session Main that could start, whose line only runs, waits for the machine or is the head, reserves like a head against the later entries of other claims: its slot, its exclusive room and its - budget (held_for()). + band room (held_for()). An entry that could not start with no queue job running (its disk - need cuts into floor, its kind has no slot, or load holds it that no + need cuts into floor, its kind is capped at 0 slots, or load holds it that no queue job causes: an Outside reason, or no queue job active) is no head; one with an Outside reason holds no line either. A waiting entry whose holder has not polled for CLAIM_SECONDS reserves nothing and comes last. An entry passes a waiting entry of its line that never could start (unstartable()) and takes its place in that line. + Before all of it every overridden entry the live guard, the host and + the disk let start is granted (forced()) and counts as active; an + overridden entry held back keeps its place, its reason the override's. """ + entries, overrides = forced(entries, free_gb, floor, stage, memory, silenced, loaded, now) active = [e for e in entries if e["status"] == "active"] - used = {resource: sum(footprints[e["id"]][resource] for e in active) for resource in budget} + started = [e for e in active if e["id"] in overrides] + used = {resource: load[resource] + sum(footprints[e["id"]][resource] for e in started) for resource in load} available = free_gb - sum(e["need_gb"] for e in active) lit = [e for e in active if e["kind"] in light] - beside = {resource: sum(footprints[e["id"]][resource] for e in lit) for resource in budget} + beside = { + resource: max(0.0, used[resource] - sum(footprints[e["id"]][resource] for e in active if e["kind"] not in light)) + for resource in load + } room = free_gb - sum(e["need_gb"] for e in lit) counts = Counter(e["kind"] for e in active) lines = {claim: e["id"] for e in active for claim in claims(e)} @@ -788,18 +945,18 @@ def evaluate(entries: list[dict], free_gb: float, floor: float, stage: str, memo alone, slot = alone_reason(kind, counts, exclusive, light), slot_reason(kind, slot_limits, counts) reason = blocking( lead and lead[0], disk_reason(stage, need), - host_reason(memory, silenced) or slot or alone or (over_budget(used, share, budget) if taken else None), + host_reason(memory, silenced) or slot or alone or (band_reason(used, share, band) or settle_reason(settle, now) if taken else None), None if available - need >= floor else floor_reason(need, floor), loaded.get(entry["id"]), ) step = lead[1] if lead else reason if reason is None and reserve is not None: - slotted = reserve[5] if kind == reserve[5] and counts[kind] + 1 >= slot_limits.get(kind, 0) else None - short = takes(need, share, *((beside, room) if reserve[2] else (used, available)), floor, budget, reserve[:2], slotted) + slotted = reserve[5] if kind == reserve[5] and last_slot(kind, slot_limits, counts) else None + short = takes(need, share, *((beside, room) if reserve[2] else (used, available)), floor, ceiling(band), reserve[:2], slotted) reason = reserve[3] if short else None step = f"{reserve[3]}: takes {short}" if short else f"takes nothing {reserve[4]} lacks" pools = used, available, beside, room why = None if reason is not None else next(((h[2], s) for h in holds if not h[4] & set(mine) and ( - s := held_for(kind, need, share, h, counts, slot_limits, exclusive, light, pools, floor, budget))), None) + s := held_for(kind, need, share, h, counts, slot_limits, exclusive, light, pools, floor, ceiling(band)))), None) if why: reason, step = f"reserved for {why[0]}", f"reserved for {why[0]}: {why[1]}" gate = None if reason is not None or kind in light else loaded_exclusive(able, verdicts, loaded, exclusive) @@ -826,8 +983,10 @@ def evaluate(entries: list[dict], free_gb: float, floor: float, stage: str, memo able += [] if never[entry["id"]] else [entry] first = entry["hotfix"] and able == [entry] or kind in exclusive and reason == alone if reserve is None and (entry["id"] == drain or entry["id"] in could and first): - held = f"waits behind hotfix {entry['id']}" if entry["hotfix"] else f"drained for {entry['id']}" - reserve = share, need, kind in exclusive or reason == alone, held, entry["id"], kind + apart = kind in exclusive or reason == alone + crowded = entry["id"] in loaded or bool(taken) and band_reason(beside if apart else used, share, band) is not None + held = f"waits behind hotfix {entry['id']}" if entry["hotfix"] else f"{'drained' if crowded else 'reserved'} for {entry['id']}" + reserve = share, need, apart, held, entry["id"], kind if not entry["hotfix"] and not lined and (lead or reason in (alone, slot)): machine.add(entry["id"]) settled = running | machine | {i for i, v in verdicts.items() if v is None} | {reserve[4] if reserve else None} @@ -838,7 +997,68 @@ def evaluate(entries: list[dict], free_gb: float, floor: float, stage: str, memo if entry["status"] == "waiting" and silent(entry, now): verdicts[entry["id"]] = f"no poll for {now - entry['polled']:.0f} s; reserves nothing until it polls again" steps[entry["id"]] = [verdicts[entry["id"]]] - return verdicts, drained(order, verdicts, drain, could, now), order + return overridden(verdicts, overrides, steps), drained(order, verdicts, drain, could, now), order + + +def forced(entries: list[dict], free_gb: float, floor: float, stage: str, memory: str, silenced: bool, + loaded: dict[str, str], now: float) -> tuple[list[dict], dict[str, str | None]]: + """Returns: + (entries with every overridden polling entry that may start marked + active, {overridden polling entry id: None when it starts, else + override_reason()} in the order of their OVERRIDE ts); each start + counts against the disk and the lines of the ones after it. + """ + active = [e for e in entries if e["status"] == "active"] + available = free_gb - sum(e["need_gb"] for e in active) + lines = {claim: e["id"] for e in active for claim in claims(e)} + asked = sorted((e for e in entries if OVERRIDE in e and e["status"] == "waiting" and not silent(e, now)), + key=lambda e: e[OVERRIDE]["ts"]) + verdicts: dict[str, str | None] = {} + for entry in asked: + verdicts[entry["id"]] = override_reason(entry, available, floor, stage, (memory, silenced), loaded, lines) + if verdicts[entry["id"]] is None: + available -= entry["need_gb"] + lines.update((claim, entry["id"]) for claim in claims(entry)) + started = {entry_id for entry_id, reason in verdicts.items() if reason is None} + return [{**e, "status": "active"} if e["id"] in started else e for e in entries], verdicts + + +def override_reason(entry: dict, available: float, floor: float, stage: str, host: tuple[str, bool], + loaded: dict[str, str], lines: dict[str, str]) -> str | None: + """Args: + entry: an overridden waiting entry. + available: free GB less the need of the active and forced entries. + floor: GB every grant must leave free. + stage: the watch disk stage. + host: (the watch memory stage, whether a radio-silence mayday holds). + loaded: held_back() of the pass. + lines: {claim: the active or forced entry holding it}. + + Returns: + None when the override starts entry, else `override held by` the live + guard load_limits (load_reason()), the host, the disk or the running + job of one of its claims. + """ + if entry["id"] in loaded: + return f"override held by the live guard load_limits: {loaded[entry['id']]}" + need = entry["need_gb"] + line = next((lines[claim] for claim in claims(entry) if claim in lines), None) + reason = (host_reason(*host) or disk_reason(stage, need) or (None if available - need >= floor else floor_reason(need, floor)) + or (None if line is None else f"its line runs {line}")) + return None if reason is None else f"override held by {reason}" + + +def overridden(verdicts: dict[str, str | None], overrides: dict[str, str | None], + steps: dict[str, list[str]]) -> dict[str, str | None]: + """Returns: + verdicts led by the overrides forced() granted, each overridden entry + held back with its override reason; steps gets the override step of + each. + """ + for entry_id, reason in overrides.items(): + steps[entry_id] = ["override: skips the band, slots, reservations and rank", *([] if reason is None else [reason])] + granted = {entry_id: None for entry_id, reason in overrides.items() if reason is None} + return granted | {entry_id: overrides.get(entry_id) or reason for entry_id, reason in verdicts.items()} def fitted(step: str | None, used: dict[str, float], share: dict[str, float], need: float, available: float, @@ -934,18 +1154,18 @@ def plus(used: dict[str, float], share: dict[str, float]) -> dict[str, float]: def takes(need: float, share: dict[str, float], used: dict[str, float], available: float, floor: float, - budget: dict[str, float], reserve: tuple[dict[str, float], float], slotted: str | None) -> str | None: + limit: dict[str, float], reserve: tuple[dict[str, float], float], slotted: str | None) -> str | None: """Returns: - What a job of disk need and footprint share, beside jobs that use - used and leave available GB, takes that the head's reserve - (footprint, disk need) leaves too short: `its slot` when - slotted names the head's kind whose last free slot it takes, the - budget resources it pushes past, or disk; None when it takes none of - a short resource. + What a job of disk need and footprint share, beside a load of used + and available GB, takes that the head's reserve (footprint, disk + need) leaves too short: `its slot` when slotted names the + head's kind whose last capped slot it takes, the resources whose + load plus both footprints passes limit (the band's high), or disk; + None when it takes none of a short resource. """ held, held_need = reserve over = plus(plus(used, held), share) - short = [r.upper() for r in budget if share[r] > 0 and over[r] > budget[r]] + short = [r.upper() for r in limit if share[r] > 0 and over[r] > limit[r]] if slotted: return f"its {slotted} slot" if short: @@ -955,33 +1175,39 @@ def takes(need: float, share: dict[str, float], used: dict[str, float], availabl def held_for(kind: str, need: float, share: dict[str, float], hold: tuple[dict[str, float], float, str, str, set[str]], counts: Counter, slot_limits: dict[str, int], exclusive: set[str], light: set[str], - pools: tuple[dict[str, float], float, dict[str, float], float], floor: float, budget: dict[str, float]) -> str | None: + pools: tuple[dict[str, float], float, dict[str, float], float], floor: float, limit: dict[str, float]) -> str | None: """Returns: Why a job of kind, disk need and footprint share takes what hold (footprint, disk need, id, kind, claims), a job whose line only runs or waits for the machine, lacks: ` is exclusive` when one of the two is exclusive and the other not light, else `takes` what takes() finds beside pools (used, available, then the light jobs' - beside and room, which count when hold's kind is exclusive), its last - free slot of hold's kind included; None when it takes nothing. + beside and room, which count when hold's kind is exclusive) under + limit, the band's high, its last capped slot of hold's kind + included; None when it takes nothing. """ held = hold[3] if held in exclusive and kind not in light or kind in exclusive and held not in light: return f"{held if held in exclusive else kind} is exclusive" used, available, beside, room = pools - slotted = held if kind == held and counts[kind] + 1 >= slot_limits.get(kind, 0) else None - short = takes(need, share, *((beside, room) if held in exclusive else (used, available)), floor, budget, hold[:2], slotted) + slotted = held if kind == held and last_slot(kind, slot_limits, counts) else None + short = takes(need, share, *((beside, room) if held in exclusive else (used, available)), floor, limit, hold[:2], slotted) return f"takes {short}" if short else None +def last_slot(kind: str, slot_limits: dict[str, int], counts: Counter) -> bool: + return kind in slot_limits and counts[kind] + 1 >= slot_limits[kind] + + def unstartable(entry: dict, free_gb: float, floor: float, slot_limits: dict[str, int]) -> str | None: """Returns: Why entry could not start even with no queue job running: ` - slots` when its kind's cap is 0 or missing, floor_reason() - when its disk need cuts into floor of free_gb; else None. + slots` when the config caps its kind at 0 or below, + floor_reason() when its disk need cuts into floor of free_gb; else + None. """ - cap = slot_limits.get(entry["kind"], 0) - if cap <= 0: + cap = slot_limits.get(entry["kind"]) + if cap is not None and cap <= 0: return f"{cap} {entry['kind']} slots" return floor_reason(entry["need_gb"], floor) if free_gb - entry["need_gb"] < floor else None @@ -1007,9 +1233,7 @@ def host_reason(memory: str, silenced: bool) -> str | None: def slot_reason(kind: str, slot_limits: dict[str, int], counts: Counter) -> str | None: - if kind not in slot_limits: - return f"slot_limits has no {kind}" - if counts[kind] >= slot_limits[kind]: + if kind in slot_limits and counts[kind] >= slot_limits[kind]: return f"all {slot_limits[kind]} {kind} slots taken" return None @@ -1045,7 +1269,7 @@ def after_waits(entries: list[dict]) -> dict[str, str]: other for other in register.get(task, {}).get("after", []) if other in register and register[other].get("status") not in rasci.ENDED ] - if entry["status"] == "waiting" and ahead: + if entry["status"] == "waiting" and ahead and OVERRIDE not in entry: lift = shlex.join(["rasci.py", "set", task, "--drop-after", ahead[0]]) waits[entry["id"]] = f"waits for {ahead[0]}, an after task of {task} not yet done or stopped; {lift} lifts it" return waits @@ -1098,26 +1322,81 @@ def held_back(cfg: dict, entries: list[dict], now: float, signatures: dict[str, def decide(cfg: dict, entries: list[dict], free_gb: float, now: float, signatures: dict[str, dict], - kinds: dict[str, dict], loaded: dict[str, str], drain: str | None, *, - trace: dict[str, list[str]] | None = None) -> tuple[dict[str, str | None], str | None, list[dict]]: - slots = {kind: limit for kind, (limit, _) in limits(cfg, kinds, entries).items()} + kinds: dict[str, dict], loaded: dict[str, str], load: dict[str, float] | None, drain: str | None, *, + trace: dict[str, list[str]] | None = None, target: dict[str, float] | None, + memory: dict[str, float | None] | None, granted: float | None) -> tuple[dict[str, str | None], str | None, list[dict]]: + """Args: + cfg: the config; slot_limits caps kinds, budget_percent is the + footprint of a job whose kind is not learned yet, band() the band, + load_limits.sample_seconds the settle window after a grant. + entries: the queue's entries. + free_gb: free disk in GB. + now: epoch seconds. + signatures: the signature map of history.learn(). + kinds: the kind map of history.learn(). + loaded: held_back() of the pass. + load: live_load() of the pass; None books the active jobs' + footprints instead, for a caller that samples no load (list). + drain: the entry the previous pass drained for. + trace: filled as evaluate() fills it. + target: {ram, cpu}, the AIMD target the band's footprints must stay + within (aimed(), stored_target()); None admits up to the band's + high. + memory: the watch memory sample of the pass; None samples it. + granted: epoch seconds of the last grant (GRANTED), None for none. + + Returns: + evaluate() over the entries no `after` task holds, those led by + their wait. + """ budget = cfg["budget_percent"] footprints = {} for entry in entries: share = footprint(entry, signatures, kinds) footprints[entry["id"]] = dict(budget) if share is None else share + if load is None: + load = {r: sum(footprints[e["id"]][r] for e in entries if e["status"] == "active") for r in history.RESOURCES} waits = after_waits(entries) steps = {} if trace is None else trace verdicts, drain, order = evaluate( [e for e in entries if e["id"] not in waits], free_gb, cfg["thresholds_gb"]["stop"], stage(cfg, free_gb, now), - watch.memory_stage(watch.memory(), cfg), silenced(now), slots, footprints, budget, - register_ranks(), agent_ranks(), loaded, + watch.memory_stage(watch.memory() if memory is None else memory, cfg), silenced(now), caps(cfg), footprints, + band(cfg) | ({} if target is None else {"target": target}), load, register_ranks(), agent_ranks(), loaded, set(cfg.get("exclusive_kinds", [])), set(cfg.get("light_kinds", [])), drain, now, trace=steps, + settle=(cfg["load_limits"]["sample_seconds"], granted), ) steps.update({entry_id: [reason] for entry_id, reason in waits.items()}) return verdicts | waits, drain, order +def psi_calm(cfg: dict) -> float: + held = cfg.get(limit_file.KEY) + return aimd.PSI_CALM if held is None else held["psi"]["lower"] + + +def aimed(cfg: dict, load: dict[str, float], pressure: dict[str, float | None], now: float) -> dict[str, float]: + """Args: + cfg: the config under the limits file in force. + load: {ram, cpu} measured this poll, in percent. + pressure: the watch memory sample of this poll. + now: epoch seconds. + + Returns: + {ram, cpu}: the AIMD target after this poll's step (aimd.stepped() + over the band(), at most one step per POLL_SECONDS however many + holds poll), the state written back to TARGET; called under the + store lock, so polls never interleave. + """ + state = aimd.stepped(watch.read_json(TARGET), band(cfg), load, pressure, psi_calm(cfg), now, POLL_SECONDS) + with contextlib.suppress(OSError): + nofollow.replace(watch.ROOT, TARGET, json.dumps(state), 0o600) + return aimd.target(state, band(cfg)) + + +def stored_target(cfg: dict) -> dict[str, float]: + return aimd.target(watch.read_json(TARGET), band(cfg)) + + def latched(data: dict, drain: str | None, now: float) -> str | None: """Returns: drain when the store data drains for it already, or once a new drain @@ -1346,11 +1625,38 @@ def ramping_ram(entries: list[dict], now: float, signatures: dict[str, dict], ki others. An older job counts as ramped, its RAM inside the RAM used; one that peaks later is bounded by the memory stage only. """ + return ramping(entries, now, mem, GRANTED_MEM, lambda e: ram_share(e, signatures, kinds)) + + +def ramping_cpu(entries: list[dict], now: float, signatures: dict[str, dict], kinds: dict[str, dict], + cpu: float) -> float: + """Returns: + ramping_ram() for CPU busy cpu: the young jobs' CPU shares (0 for a + kind not learned yet) less what CPU busy gained since the earliest + grant that recorded it (GRANTED_CPU). + """ + return ramping(entries, now, cpu, GRANTED_CPU, lambda e: (footprint(e, signatures, kinds) or {"cpu": 0.0})["cpu"]) + + +def ramping(entries: list[dict], now: float, measured: float, mark: str, share: Callable[[dict], float]) -> float: young = [e for e in entries if e["status"] == "active" and now - e.get("granted", now) < RAMP_SECONDS] - dated = [e for e in young if GRANTED_MEM in e] - gained = max(0.0, mem - min((e[GRANTED_MEM] for e in dated), default=mem)) - ramp = max(0.0, sum(ram_share(e, signatures, kinds) for e in dated) - gained) - return ramp + sum(ram_share(e, signatures, kinds) for e in young if GRANTED_MEM not in e) + dated = [e for e in young if mark in e] + gained = max(0.0, measured - min((e[mark] for e in dated), default=measured)) + ramp = max(0.0, sum(share(e) for e in dated) - gained) + return ramp + sum(share(e) for e in young if mark not in e) + + +def live_load(entries: list[dict], now: float, signatures: dict[str, dict], kinds: dict[str, dict], + cpu: float, mem: float, admitted: float) -> dict[str, float]: + """Returns: + {ram, cpu}, the load the band starts from: RAM used mem plus + admitted (admitted_ram()) and ramping_ram(), CPU busy cpu plus + ramping_cpu(). + """ + return { + "ram": mem + admitted + ramping_ram(entries, now, signatures, kinds, mem), + "cpu": cpu + ramping_cpu(entries, now, signatures, kinds, cpu), + } def pending_ram(entries: list[dict], entry_id: str, now: float, signatures: dict[str, dict], @@ -1382,13 +1688,13 @@ def enqueue(fields: dict) -> dict: """Returns: The entry of fields; a hold that hand_over() left for the installed code at most CLAIM_SECONDS before, of the same pid, session and - command, keeps its id, seq and enqueue time. + command, keeps its id, seq, enqueue time and override. """ with store() as data: kept = {pid: h for pid, h in data.get(HANDOVER, {}).items() if fields["enqueued"] - h["at"] <= CLAIM_SECONDS} mine = kept.pop(str(fields["pid"]), None) if mine is not None and (mine["session"], mine["cmd"]) == (fields["session"], fields["cmd"]): - entry = {**fields, "id": mine["id"], "seq": mine["seq"], "enqueued": mine["enqueued"]} + entry = {**fields, **{key: mine[key] for key in ("id", "seq", "enqueued", OVERRIDE) if key in mine}} else: data["seq"] += 1 entry = {"id": f"{fields['kind']}-{data['seq']}", "seq": data["seq"], **fields} @@ -1402,7 +1708,7 @@ def hand_over(entry_id: str) -> None: for entry in [e for e in data["entries"] if e["id"] == entry_id]: data["entries"].remove(entry) data.setdefault(HANDOVER, {})[str(entry["pid"])] = { - **{key: entry[key] for key in ("id", "seq", "enqueued", "session", "cmd")}, "at": time.time(), + **{key: entry[key] for key in ("id", "seq", "enqueued", "session", "cmd", OVERRIDE) if key in entry}, "at": time.time(), } @@ -1422,7 +1728,7 @@ def pause(wake: int) -> None: select.select([wake], [], [], POLL_SECONDS) -def wait(cfg: dict, entry_id: str, caught: list[int], wake: int) -> tuple[int | None, int]: +def wait(cfg: dict, entry_id: str, caught: list[int], wake: int) -> tuple[int | None, int, bool]: """Poll until the grant. Args: @@ -1433,8 +1739,10 @@ def wait(cfg: dict, entry_id: str, caught: list[int], wake: int) -> tuple[int | readable, so a pause between polls ends at once. Returns: - (None, other active jobs at the grant) once granted, else (the exit - code, 0). + (None, other active jobs at the grant, whether the entry carries + OVERRIDE, the footprint the grant booked or None) once granted, else + (the exit code, 0, False, None). Each poll steps the AIMD target + (aimed()) and decides under it. """ shown = None while not caught: @@ -1443,6 +1751,7 @@ def wait(cfg: dict, entry_id: str, caught: list[int], wake: int) -> tuple[int | raise Stale(host, caught) cfg = fresh(cfg) cpu, mem = watch.load(cfg) + pressure = watch.memory() free, _ = watch.disk(cfg) now = time.time() signatures, kinds = learned(cfg, now) @@ -1451,22 +1760,28 @@ def wait(cfg: dict, entry_id: str, caught: list[int], wake: int) -> tuple[int | mine = [e for e in data["entries"] if e["id"] == entry_id] if not mine: print(f"queue: {entry_id} was cancelled", file=sys.stderr) - return CANCELLED, 0 + return CANCELLED, 0, False, None rejoin(data, mine[0], now) - loaded = held_back(cfg, data["entries"], now, signatures, kinds, cpu, mem, admitted_ram(data, now)) + admitted = admitted_ram(data, now) + loaded = held_back(cfg, data["entries"], now, signatures, kinds, cpu, mem, admitted) + load = live_load(data["entries"], now, signatures, kinds, cpu, mem, admitted) steps: dict[str, list[str]] = {} - verdicts, drain, order = decide(cfg, data["entries"], free, now, signatures, kinds, loaded, data.get(DRAIN), trace=steps) + verdicts, drain, order = decide( + cfg, data["entries"], free, now, signatures, kinds, loaded, load, data.get(DRAIN), trace=steps, + target=aimed(cfg, {"cpu": cpu, "ram": mem}, pressure, now), memory=pressure, granted=data.get(GRANTED), + ) data[DRAIN] = latched(data, drain, now) mine[0]["trace"] = steps[entry_id] if verdicts[entry_id] is None: concurrent = sum(e["status"] == "active" for e in data["entries"]) + booked = footprint(mine[0], signatures, kinds) mine[0].update(status="active", granted=now, reason=labelled(verdicts, [])[entry_id], - **{GRANTED_MEM: mem, FROZEN: footprint(mine[0], signatures, kinds)}) + **{GRANTED_MEM: mem, GRANTED_CPU: cpu, FROZEN: booked}) data[GRANTED] = now data.pop(STALL, None) if shown is not None: print(f"queue: {entry_id} granted after waiting; running {mine[0]['cmd']}", file=sys.stderr, flush=True) - return None, concurrent + return None, concurrent, OVERRIDE in mine[0], booked sends, clean, log = stalled(data, order, verdicts, cfg["thresholds_gb"]["stop"], free, functools.partial(cleanup_outcome, now), now) logs = [] if log is None else [log] @@ -1481,7 +1796,7 @@ def wait(cfg: dict, entry_id: str, caught: list[int], wake: int) -> tuple[int | print(f"queue: {entry_id} waits at position {position}: {reason}", file=sys.stderr, flush=True) shown = (position, reason) pause(wake) - return 128 + caught[0], 0 + return 128 + caught[0], 0, False, None def send(child: subprocess.Popen, signum: int) -> None: @@ -1554,6 +1869,19 @@ def keep(row: dict) -> None: print(f"queue: no history row for {row['id']}: {error.strerror}", file=sys.stderr) +def finished(entry: dict, name: str, hung: dict | None, overridden: bool, booked: dict | None) -> dict: + """Returns: + The job record() keeps for entry under its signature name: HUNG + with standstill's report when hold ended it, OVERRIDE true when + `queue.py override` started it, history.PREDICTED the footprint + booked, the margin's prediction, when the grant booked a learned + one. + """ + return {"id": f"{entry['id']}-{time.time_ns()}", "kind": entry["kind"], "signature": name, "workdir": entry["workdir"], + **({} if hung is None else {history.HUNG: hung}), **({OVERRIDE: True} if overridden else {}), + **({history.PREDICTED: booked} if isinstance(booked, dict) else {})} + + def record(job: dict, start: float, code: int, samples: list[dict[str, float]], concurrent: int) -> None: if code != NOT_RUN: keep(history.row(job, start, time.time(), code, samples, concurrent)) @@ -1647,7 +1975,7 @@ def cmd_hold(args: argparse.Namespace) -> int: }) try: try: - code, concurrent = wait(cfg, entry["id"], caught, wake) + code, concurrent, overridden, booked = wait(cfg, entry["id"], caught, wake) except Stale: hand_over(entry["id"]) raise @@ -1670,9 +1998,7 @@ def cmd_hold(args: argparse.Namespace) -> int: update(entry["id"], child=child.pid, child_start=identity(child.pid)) code, hung = supervise(cfg, child, samples) code = code if code >= 0 else 128 - code - job = {"id": f"{entry['id']}-{time.time_ns()}", "kind": args.kind, "signature": names[0], - "workdir": entry["workdir"], **({} if hung is None else {history.HUNG: hung})} - record(job, start, code, samples, concurrent) + record(finished(entry, names[0], hung, overridden, booked), start, code, samples, concurrent) keep_receipt(gates, args, here, before, code) return code finally: @@ -1685,10 +2011,12 @@ def cmd_list(args: argparse.Namespace) -> int: now = time.time() signatures, kinds = learned(cfg, now) steps: dict[str, list[str]] = {} + aim = stored_target(cfg) with store() as data: data["entries"] = prune(data["entries"]) entries = list(data["entries"]) - verdicts, _, _ = decide(cfg, entries, free, now, signatures, kinds, {}, data.get(DRAIN), trace=steps) + verdicts, _, _ = decide(cfg, entries, free, now, signatures, kinds, {}, None, data.get(DRAIN), trace=steps, + target=aim, memory=None, granted=data.get(GRANTED)) verdicts = labelled(verdicts, (data.get(STALL) or {}).get("fired", [])) by_id = {e["id"]: e for e in entries} running = [(key_of(e), e["granted"]) for e in entries if e["status"] == "active"] @@ -1710,7 +2038,7 @@ def cmd_list(args: argparse.Namespace) -> int: rasci = sibling("rasci") print(json.dumps(listed(rows, rasci.merged(False), rasci.wsjf, now), indent=1)) return 0 - print("position\tid\tstatus\tkind\ttask\tneed_gb\twaited_min\teta_min\tworkdir\treason") + print(f"position\tid\tstatus\tkind\ttask\tneed_gb\twaited_min\teta_min\tworkdir\treason ({targets(cfg, aim)})") for position, e, eta, reason, _ in rows: waited = ((e["granted"] or now) - e["enqueued"]) / 60 print(tab_line( @@ -1720,6 +2048,21 @@ def cmd_list(args: argparse.Namespace) -> int: return 0 +def targets(cfg: dict, aim: dict[str, float]) -> str: + """Returns: + `target CPU % RAM % in band CPU - % RAM + - %, limits `: the source is the limits file + under watch.ROOT in force, its last valid copy while the file is + refused, else config; a refusal follows, naming why. + """ + edges = band(cfg) + shown = " ".join(f"{r.upper()} {aim[r]:.1f} %" for r in ("cpu", "ram")) + span = " ".join(f"{r.upper()} {edges['low'][r]:g}-{edges['high'][r]:g} %" for r in ("cpu", "ram")) + refused = limit_file.read(watch.ROOT)[1] + source = watch.ROOT / (limit_file.NAME if refused is None else limit_file.LAST) if limit_file.KEY in cfg else "config" + return f"target {shown} in band {span}, limits {source}" + ("" if refused is None else f"; {refused}") + + def suspected(entry: dict, reason: str | None, signatures: dict[tuple[str, str], dict], now: float) -> str | None: """Returns: reason led by `suspect hung ( min)` once the active entry @@ -1765,8 +2108,9 @@ def listed(rows: list[tuple], register: dict[str, dict], score: Callable[[dict], Returns: One object per row: position, id, status, kind, task, session, agent, class (job_class()), prio (the task's pin or None), wsjf (or - None), waited_s, eta_s (or None), reason and trace, the steps of - evaluate() that decided the entry at the poll that set its reason. + None), waited_s, eta_s (or None), reason, trace, the steps of + evaluate() that decided the entry at the poll that set its reason, + and override, whether `queue.py override` marked it. """ shown = [] for position, e, eta, reason, trace in rows: @@ -1776,7 +2120,7 @@ def listed(rows: list[tuple], register: dict[str, dict], score: Callable[[dict], "position": position, "id": e["id"], "status": e["status"], "kind": e["kind"], "task": e["task"], "session": e.get("session"), "agent": e["name"], "class": job_class(e, row.get("prio")), "prio": row.get("prio"), "wsjf": None if wsjf is None else wsjf[2], "waited_s": round((e["granted"] or now) - e["enqueued"]), - "eta_s": None if eta is None else round(eta * 60), "reason": reason, "trace": trace, + "eta_s": None if eta is None else round(eta * 60), "reason": reason, "trace": trace, OVERRIDE: OVERRIDE in e, }) return shown @@ -1806,6 +2150,125 @@ def cmd_cancel(args: argparse.Namespace) -> int: return 0 +def cmd_override(args: argparse.Namespace) -> int: + with store() as data: + waiting = [e for e in data["entries"] if e["id"] == args.id and e["status"] == "waiting"] + if not waiting: + fail(f"no waiting entry {args.id}; `queue.py list` shows the ids") + waiting[0].setdefault(OVERRIDE, {"ts": time.time()}) + print(f"override {args.id}: it starts at its next poll while the live guard and the disk allow") + return 0 + + +def learnings(cfg: dict, signatures: dict[tuple[str, str], dict], kinds: dict[str, dict], rows: list[dict]) -> dict: + """Args: + cfg: the config. + signatures: the signature map of history.learn(). + kinds: the kind map of history.learn(). + rows: the history rows (history.read()). + + Returns: + kinds: {kind: its learned values (history.kind_stats() with light + and ram_cap, runs 0 for a kind without rows), slot_limit and + slot_source (history.slot_limits())}; signatures: one object per + learned kind and signature with its values; budget_percent, + ram_cap_percent, load_limits and slot_limits of the config; history: + the last HISTORY_SHOWN rows by end. + """ + light, ram_caps = set(cfg.get("light_kinds", [])), cfg.get(history.RAM_CAP, {}) + unknown = history.kind_stats([], cfg["load_limits"]) + return { + "kinds": { + kind: {**(kinds.get(kind) or {**unknown, "light": kind in light, "ram_cap": ram_caps.get(kind)}), "slot_limit": limit, "slot_source": source} + for kind, (limit, source) in limits(cfg, kinds, []).items() + }, + "signatures": [ + {"kind": kind, "signature": name, **stats} + for (kind, name), stats in sorted(signatures.items(), key=lambda item: item[0][::-1]) if kind != history.ANY_KIND + ], + "budget_percent": cfg["budget_percent"], history.RAM_CAP: ram_caps, "load_limits": cfg["load_limits"], SLOT_LIMITS: caps(cfg), + "history": sorted(rows, key=lambda row: row["end"])[-HISTORY_SHOWN:], + } + + +def cmd_learned(_: argparse.Namespace) -> int: + cfg = config() + signatures, kinds = learned(cfg, time.time()) + print(json.dumps(learnings(cfg, signatures, kinds, history.read(HISTORIES)), indent=1)) + return 0 + + +def stored_config() -> dict: + """Returns: + The config file as it stands, checked like every reader checks it; + fail() on a missing, linked, unusable or incomplete file, so a + change never builds on the SHIPPED fallback. + """ + if watch.CONFIG.is_symlink(): + fail(f"{watch.CONFIG} is a link; change its target by hand") + try: + cfg = watch.load_config() + checked = None if cfg is None else watch.checked_config(cfg) + except watch.UNUSABLE as error: + fail(f"{watch.CONFIG} is unusable ({error}); fix it by hand first") + if checked is None: + fail(f"no config at {watch.CONFIG}") + problem = config_problem(checked) + if problem is not None: + fail(problem) + return checked + + +def setting_keys(cfg: dict) -> list[str]: + return [*(f"{section}.{name}" for section, names in SETTINGS.items() for name in names), + *(f"{section}.{kind}" for section in KIND_SETTINGS for kind in cfg["slot_need_gb"])] + + +def bound_problem(key: str, value: float) -> str | None: + """Returns: + Why value does not fit key beyond config_problem(): a slot limit is + a whole number, every other setting lies above 0 and a load limit + percentage at most 100; None when it fits. + """ + if key.startswith(f"{SLOT_LIMITS}."): + return None if isinstance(value, int) else f"{key} takes a whole number of slots" + if value <= 0: + return f"{key} must lie above 0" + return f"{key} is a percentage up to 100" if key in PERCENT_KEYS and value > 100 else None + + +def changed_config(cfg: dict, key: str, text: str) -> dict: + """Args: + cfg: the config file's content. + key: `
.`, one of setting_keys(). + text: the new value, a plain decimal number. + + Returns: + cfg with key set to the number; fail() on an unknown key, a value + that is no number or one the config check refuses. + """ + if key not in setting_keys(cfg): + fail(f"{key} is no setting config set changes; one of {', '.join(setting_keys(cfg))}") + if not NUMBER.fullmatch(text): + fail(f"{text!r} is no plain decimal number") + value = float(text) if "." in text else int(text) + section, _, name = key.partition(".") + changed = {**cfg, section: {**cfg.get(section, {}), name: value}} + problem = config_problem(changed) or bound_problem(key, value) + if problem is not None: + fail(problem) + return changed + + +def cmd_config(args: argparse.Namespace) -> int: + cfg = stored_config() + changed = changed_config(cfg, args.key, args.value) + mode = stat.S_IMODE(os.lstat(watch.CONFIG).st_mode) + nofollow.rewrite(watch.CONFIG.parent, watch.CONFIG, json.dumps(changed, indent=2) + "\n", mode) + print(f"config {args.key} = {args.value}") + return 0 + + def settings_files(project: Path) -> list[Path]: return sibling("councilroot").settings_files(project) @@ -1943,6 +2406,11 @@ def cli() -> argparse.ArgumentParser: cancel = sub.add_parser("cancel") cancel.add_argument("id") cancel.add_argument("--session") + sub.add_parser("override").add_argument("id") + sub.add_parser("learned").add_argument("--json", action="store_true", required=True) + setter = sub.add_parser("config").add_subparsers(dest="action", required=True).add_parser("set") + setter.add_argument("key") + setter.add_argument("value") sub.add_parser("block") return parser @@ -1959,7 +2427,10 @@ def main() -> int: print(f"kvb-org-queue: the block hook failed ({error!r}), so the command counts as heavy and is refused.", file=sys.stderr) return 2 - commands = {"hold": cmd_hold, "list": cmd_list, "history": cmd_history, "cancel": cmd_cancel} + commands = { + "hold": cmd_hold, "list": cmd_list, "history": cmd_history, "cancel": cmd_cancel, "override": cmd_override, + "learned": cmd_learned, "config": cmd_config, + } try: return commands[args.cmd](args) except Stale as stale: diff --git a/tests/queue-list.json b/tests/queue-list.json index a2c015a..70454ee 100644 --- a/tests/queue-list.json +++ b/tests/queue-list.json @@ -1,6 +1,6 @@ [ - {"position": "run", "id": "q-1", "kind": "test", "task": "work/bravo", "session": "s-docs", "agent": "Docs", "class": "fix", "prio": 2, "wsjf": null, "waited_s": 95, "eta_s": 240, "reason": "granted on its last poll", "trace": ["granted at its last poll", "slot test:1 of 2"]}, - {"position": 1, "id": "q-2", "kind": "quality-high", "task": "work/alpha", "session": "s-stage", "agent": "Stage", "class": "hotfix", "prio": 1, "wsjf": 2.6667, "waited_s": 1260, "eta_s": 480, "reason": "RAM 61 % used + 15 % still to come reach the limit 75 %", "trace": ["hotfix first", "rank 0", "line slot:2 behind q-1", "RAM 61 % + 15 % reaches 75 %"]}, - {"position": 2, "id": "q-4", "kind": "deploy", "task": "work/delta", "session": "s-skills", "agent": "Skills", "class": "main", "prio": null, "wsjf": null, "waited_s": 4000, "eta_s": null, "reason": "waits behind q-2", "trace": []}, - {"position": 3, "id": "q-3", "kind": "test", "task": "work/charlie", "session": "s-stage", "agent": "Stage", "class": "feature", "prio": null, "wsjf": 1.5, "waited_s": 30, "eta_s": 3900, "reason": "all 1 test slots taken", "trace": ["rank 7", "waited 0 h", "line slot:2 behind q-2", "RAM 52 % + 15 GB fits"]} + {"position": "run", "id": "q-1", "kind": "test", "task": "work/bravo", "session": "s-docs", "agent": "Docs", "class": "fix", "prio": 2, "wsjf": null, "waited_s": 95, "eta_s": 240, "reason": "granted on its last poll", "trace": ["granted at its last poll", "slot test:1 of 2"], "status": "active", "override": false}, + {"position": 1, "id": "q-2", "kind": "quality-high", "task": "work/alpha", "session": "s-stage", "agent": "Stage", "class": "hotfix", "prio": 1, "wsjf": 2.6667, "waited_s": 1260, "eta_s": 480, "reason": "RAM 61 % used + 15 % still to come reach the limit 75 %", "trace": ["hotfix first", "rank 0", "line slot:2 behind q-1", "RAM 61 % + 15 % reaches 75 %"], "status": "waiting", "override": false}, + {"position": 2, "id": "q-4", "kind": "deploy", "task": "work/delta", "session": "s-skills", "agent": "Skills", "class": "main", "prio": null, "wsjf": null, "waited_s": 4000, "eta_s": null, "reason": "waits behind q-2", "trace": [], "status": "waiting", "override": true}, + {"position": 3, "id": "q-3", "kind": "test", "task": "work/charlie", "session": "s-stage", "agent": "Stage", "class": "feature", "prio": null, "wsjf": 1.5, "waited_s": 30, "eta_s": 3900, "reason": "all 1 test slots taken", "trace": ["rank 7", "waited 0 h", "line slot:2 behind q-2", "RAM 52 % + 15 GB fits"], "status": "waiting", "override": false} ] diff --git a/tests/test_limits.py b/tests/test_limits.py new file mode 100644 index 0000000..085fb39 --- /dev/null +++ b/tests/test_limits.py @@ -0,0 +1,185 @@ +"""Exercise the council limits file of requirement 083: its checks, the last valid copy, and queue and watch reading it.""" + +from __future__ import annotations + +import copy +import json +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import test_queue as fixtures + +LIMITS_PY = fixtures.REPO_ROOT / "skills" / "kvb-org-organize" / "scripts" / "limits.py" +WATCH = fixtures.REPO_ROOT / "skills" / "kvb-org-organize" / "scripts" / "watch.py" +SHIPPED = fixtures.REPO_ROOT / "skills" / "kvb-org-organize" / "config.default.json" +LIMITS = { + "cpu": {"lower": 60, "upper": 80, "stop": 95, "mayday": 99}, + "ram": {"lower": 65, "upper": 70, "stop": 80, "mayday": 95}, + "swap": {"lower": 20, "upper": 50, "stop": 75, "mayday": 90}, + "disk": {"lower": 50, "upper": 80, "stop": 90, "mayday": 95}, + "psi": {"lower": 2, "upper": 10, "stop": 30, "mayday": 60}, +} +CALM = {"available": 50.0, "swap_free": 80.0, "psi_some": 1.0, "psi_full": 0.0, "swap_out_mb_min": None, "container_swap_gb": 0.0} + + +def broken(metric: str, level: str, value: object) -> dict: + data = copy.deepcopy(LIMITS) + data[metric][level] = value + return data + + +class Council(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name).resolve() + self.file = self.root / "limits.json" + self.last = self.root / "limits.last.json" + + def write(self, data: object) -> None: + self.file.write_text(json.dumps(data), encoding="utf-8") + + +class TestLimitsFile(Council): + @classmethod + def setUpClass(cls): + cls.limits = fixtures._load(LIMITS_PY) + + def test_every_metric_needs_its_four_levels_as_percents_in_strict_order(self): + self.assertIsNone(self.limits.problem(LIMITS)) + order = "breaks lower < upper < stop < mayday" + cases = { + "ram upper at its lower": (broken("ram", "upper", 65), f"ram {order}"), + "psi stop above mayday": (broken("psi", "stop", 61), f"psi {order}"), + "disk above 100": (broken("disk", "mayday", 101), "disk holds a value that is no percent from 0 to 100"), + "cpu below 0": (broken("cpu", "lower", -1), "cpu holds a value that is no percent from 0 to 100"), + "swap as text": (broken("swap", "upper", "50"), "swap holds a value that is no percent from 0 to 100"), + "swap as bool": (broken("swap", "lower", True), "swap holds a value that is no percent from 0 to 100"), + "cpu nan": (broken("cpu", "upper", float("nan")), "cpu holds a value that is no percent from 0 to 100"), + } + for name, (data, why) in cases.items(): + with self.subTest(name): + self.assertEqual(self.limits.problem(data), why) + shape = "the limits are no object of exactly cpu, ram, swap, disk, psi" + self.assertEqual(self.limits.problem({k: v for k, v in LIMITS.items() if k != "psi"}), shape) + self.assertEqual(self.limits.problem({**LIMITS, "gpu": LIMITS["cpu"]}), shape) + self.assertEqual(self.limits.problem([LIMITS]), shape) + self.assertEqual(self.limits.problem({**LIMITS, "ram": {**LIMITS["ram"], "uper": 70}}), "ram holds not exactly lower, upper, stop, mayday") + + def test_without_the_file_the_config_applies_and_a_valid_one_is_kept_as_the_last_copy(self): + self.assertEqual(self.limits.read(self.root), (None, None)) + self.assertFalse(self.last.exists()) + self.write(LIMITS) + self.assertEqual(self.limits.read(self.root), (LIMITS, None)) + self.assertEqual(json.loads(self.last.read_text(encoding="utf-8")), LIMITS) + self.file.unlink() + self.assertEqual(self.limits.read(self.root), (None, None)) + self.assertTrue(self.last.exists()) + + def test_a_refused_file_keeps_the_previous_valid_limits_in_force(self): + self.write(LIMITS) + self.limits.read(self.root) + self.write(broken("ram", "lower", 75)) + held, why = self.limits.read(self.root) + self.assertEqual(held, LIMITS) + self.assertEqual(why, f"{self.file} is refused: ram breaks lower < upper < stop < mayday; " + f"the last valid copy {self.last} stays in force") + self.assertEqual(json.loads(self.last.read_text(encoding="utf-8")), LIMITS) + self.file.write_text("{half", encoding="utf-8") + held, why = self.limits.read(self.root) + self.assertEqual(held, LIMITS) + self.assertTrue(why.startswith(f"{self.file} is unreadable ("), why) + tighter = broken("ram", "upper", 68) + self.write(tighter) + self.assertEqual(self.limits.read(self.root), (tighter, None)) + self.assertEqual(json.loads(self.last.read_text(encoding="utf-8")), tighter) + + def test_a_refused_file_without_a_valid_copy_leaves_the_config_in_force(self): + self.write(broken("cpu", "stop", 100.5)) + held, why = self.limits.read(self.root) + self.assertIsNone(held) + self.assertTrue(why.endswith("; no valid copy is kept, so the config applies"), why) + self.last.write_text(json.dumps(broken("cpu", "stop", 50)), encoding="utf-8") + self.assertIsNone(self.limits.read(self.root)[0]) + + def test_applied_maps_the_levels_onto_the_config_keys_their_readers_use(self): + cfg = json.loads(SHIPPED.read_text(encoding="utf-8")) + self.assertIs(self.limits.applied(cfg, None, 1000.0), cfg) + out = self.limits.applied(cfg, LIMITS, 1000.0) + self.assertEqual(out[self.limits.KEY], LIMITS) + self.assertEqual((out["load_limits"]["cpu_percent"], out["load_limits"]["mem_percent"]), (95, 80)) + self.assertEqual(out["load_limits"]["sample_seconds"], cfg["load_limits"]["sample_seconds"]) + self.assertEqual(out["memory_limits"]["warn"], {**cfg["memory_limits"]["warn"], "available": 30, "swap_free": 50, "psi_some": 10}) + self.assertEqual(out["memory_limits"]["stop"], {**cfg["memory_limits"]["stop"], "available": 20, "swap_free": 25, "psi_some": 30}) + self.assertEqual(out["thresholds_gb"], {"warn": 200.0, "stop": 100.0, "critical": 50.0}) + self.assertEqual(self.limits.applied(cfg, LIMITS, None)["thresholds_gb"], cfg["thresholds_gb"]) + self.assertEqual(self.limits.applied({"memory_limits": "x"}, LIMITS, None), {"memory_limits": "x", self.limits.KEY: LIMITS}) + + +class TestReaders(Council): + def setUp(self): + super().setUp() + self.watch = fixtures._load(WATCH) + self.watch.ROOT = self.root + self.cfg = {**json.loads(SHIPPED.read_text(encoding="utf-8")), "disk": str(self.root)} + + def test_watch_reads_its_memory_stages_and_disk_stages_from_the_file(self): + self.assertEqual(self.watch.memory_stage(CALM | {"available": 25.0}, self.cfg), "ok") + self.assertEqual(self.watch.memory_stage(CALM | {"psi_some": 35.0}, self.cfg), "warn") + self.write(LIMITS) + cfg, why = self.watch.with_limits(self.cfg) + self.assertIsNone(why) + self.assertEqual(self.watch.memory_stage(CALM | {"available": 25.0}, cfg), "warn") + self.assertEqual(self.watch.memory_stage(CALM | {"available": 15.0}, cfg), "stop") + self.assertEqual(self.watch.memory_stage(CALM | {"swap_free": 45.0}, cfg), "warn") + self.assertEqual(self.watch.memory_stage(CALM | {"psi_some": 35.0}, cfg), "stop") + total = self.watch.disk(self.cfg)[1] + self.assertEqual(cfg["thresholds_gb"]["stop"], round(total * 10 / 100, 1)) + free = cfg["thresholds_gb"]["warn"] - 0.5 + self.assertEqual(self.watch.stage_for(free, [], cfg, fixtures.NOW), "warn") + + def test_watch_names_a_refused_file_and_keeps_the_last_valid_limits(self): + self.write(LIMITS) + self.watch.with_limits(self.cfg) + self.write(broken("swap", "stop", 40)) + cfg, why = self.watch.with_limits(self.cfg) + self.assertIn("swap breaks lower < upper < stop < mayday", why) + self.assertEqual(cfg["memory_limits"]["stop"]["available"], 20) + + def test_the_settled_config_of_every_command_comes_under_the_file(self): + config = self.root / "config.json" + config.write_text(json.dumps(self.cfg), encoding="utf-8") + self.watch.CONFIG = config + self.assertNotIn("limits", self.watch.settled_config()[0]) + self.write(LIMITS) + cfg, warning = self.watch.settled_config() + self.assertIsNone(warning) + self.assertEqual((cfg["limits"], cfg["load_limits"]["mem_percent"]), (LIMITS, 80)) + + def test_the_queue_takes_its_band_and_live_guard_from_the_file_and_the_list_header_names_them(self): + queue = fixtures._load(fixtures.QUEUE) + config = self.root / "config.json" + config.write_text(json.dumps(self.cfg), encoding="utf-8") + aim = {"cpu": 78.0, "ram": 68.5} + with mock.patch.object(queue.watch, "ROOT", self.root), mock.patch.object(queue.watch, "CONFIG", config): + plain = queue.fresh({}) + self.assertEqual(queue.band(plain), {"low": {"ram": 70, "cpu": 70}, "high": {"ram": 90, "cpu": 90}}) + self.assertEqual(queue.targets(plain, aim), "target CPU 78.0 % RAM 68.5 % in band CPU 70-90 % RAM 70-90 %, limits config") + self.write(LIMITS) + cfg = queue.fresh({}) + self.assertEqual(queue.band(cfg), {"low": {"ram": 65, "cpu": 60}, "high": {"ram": 70, "cpu": 80}}) + self.assertEqual(queue.load_reason(cfg["load_limits"], 10.0, 75.0, 5.0), + "RAM 75 % used + 5 % still to come reach the limit 80 %") + self.assertEqual(queue.psi_calm(cfg), 2) + self.assertEqual(queue.targets(cfg, aim), + f"target CPU 78.0 % RAM 68.5 % in band CPU 60-80 % RAM 65-70 %, limits {self.file}") + self.write(broken("cpu", "lower", 85)) + header = queue.targets(queue.fresh({}), aim) + self.assertTrue(header.startswith(f"target CPU 78.0 % RAM 68.5 % in band CPU 60-80 % RAM 65-70 %, limits {self.last}; " + f"{self.file} is refused: cpu breaks"), header) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_queue.py b/tests/test_queue.py index cdc8a84..14348fd 100644 --- a/tests/test_queue.py +++ b/tests/test_queue.py @@ -35,7 +35,7 @@ BASE = { "memory": "ok", "silenced": False, "slot_limits": {"test": 5, "deploy": 1}, - "budget": {"ram": 75, "cpu": 100}, + "band": {"low": {"ram": 75, "cpu": 100}, "high": {"ram": 75, "cpu": 100}}, "ranks": {"work/a": 0, "work/b": 1, "work/c": 2}, "agents": {}, "loaded": {}, @@ -102,27 +102,29 @@ class Passes: def run_pass(self, entries: list[dict], **overrides: object) -> tuple[dict, str | None, list[dict]]: footprints = {e["id"]: {"ram": 0, "cpu": 0} for e in entries} | overrides.pop("footprints", {}) - return self.queue.evaluate(entries, **{**BASE, "footprints": footprints, **overrides}) + load = {r: sum(footprints[e["id"]][r] for e in entries if e["status"] == "active") for r in ("ram", "cpu")} + return self.queue.evaluate(entries, **{**BASE, "footprints": footprints, "load": load, **overrides}) def decide(self, entries: list[dict], **overrides: object) -> dict: return self.run_pass(entries, **overrides)[0] class TestEvaluate(Passes, unittest.TestCase): - def test_the_budget_refuses_a_job_whose_share_would_pass_it_and_a_smaller_one_backfills(self): + def test_the_band_refuses_a_job_whose_share_would_pass_its_high_and_a_smaller_one_backfills(self): running = job(1, kind="test", status="active") candidate = job(2, kind="gui-dind", workdir="/x") small = job(3, task="work/b", workdir="/y") shares = {"j1": {"ram": 60, "cpu": 40}, "j2": {"ram": 30, "cpu": 20}, "j3": {"ram": 10, "cpu": 5}} verdicts = self.decide([running, candidate, small], slot_limits={"test": 5, "gui-dind": 1}, footprints=shares) - self.assertEqual(verdicts["j2"], "RAM 60 % in use or reserved + 30 % > budget 75 %") + self.assertEqual(verdicts["j2"], "would reach 90 % RAM > 75 %") self.assertIsNone(verdicts["j3"]) fat = {**shares, "j3": {"ram": 16, "cpu": 5}} verdicts = self.decide([running, candidate, small], slot_limits={"test": 5, "gui-dind": 1}, footprints=fat) - self.assertEqual(verdicts["j3"], "RAM 60 % in use or reserved + 16 % > budget 75 %") + self.assertEqual(verdicts["j3"], "would reach 76 % RAM > 75 %") unbounded = {"ram": 1000, "cpu": 1000} self.assertEqual( - self.decide([running, candidate, small], slot_limits={"test": 5, "gui-dind": 1}, footprints=shares, budget=unbounded), + self.decide([running, candidate, small], slot_limits={"test": 5, "gui-dind": 1}, footprints=shares, + band={"low": unbounded, "high": unbounded}), {"j2": None, "j3": None}, ) @@ -130,14 +132,81 @@ class TestEvaluate(Passes, unittest.TestCase): alone = self.decide([job(1)], footprints={"j1": {"ram": 90, "cpu": 150}}) self.assertEqual(alone, {"j1": None}) busy = self.decide([job(1, status="active"), job(2)], footprints={"j1": {"ram": 1, "cpu": 70}, "j2": {"ram": 1, "cpu": 40}}) - self.assertEqual(busy, {"j2": "CPU 70 % in use or reserved + 40 % > budget 100 %"}) + self.assertEqual(busy, {"j2": "would reach 110 % CPU > 100 %"}) - def test_a_share_beyond_the_budget_runs_only_alone_even_beside_a_job_of_no_share(self): + def test_a_share_beyond_the_band_runs_only_alone_even_beside_a_job_of_no_share(self): whole = {"ram": 80, "cpu": 1} beside = self.decide([job(1, status="active"), job(2)], footprints={"j1": {"ram": 0, "cpu": 0}, "j2": whole}) - self.assertEqual(beside, {"j2": "RAM 0 % in use or reserved + 80 % > budget 75 %"}) + self.assertEqual(beside, {"j2": "would reach 80 % RAM > 75 %"}) self.assertEqual(self.decide([job(2)], footprints={"j2": whole}), {"j2": None}) + def test_below_the_low_band_jobs_start_until_the_load_reaches_it_and_none_passes_the_high_band(self): + band = {"low": {"ram": 70, "cpu": 70}, "high": {"ram": 90, "cpu": 90}} + running = job(1, status="active") + waiting = [job(n, task="work/b", workdir=f"/b{n}") for n in (2, 3, 4, 5)] + shares = {f"j{n}": {"ram": 15, "cpu": 10} for n in (1, 2, 3, 4, 5)} + idle = {"ram": 36.0, "cpu": 30.0} + self.assertEqual(self.decide([running, *waiting], footprints=shares, band=band, load=idle), + {"j2": None, "j3": None, "j4": None, "j5": "load 81 % RAM >= 70 % band"}) + self.assertEqual(self.decide([running, *waiting], footprints=shares, band=band, load={"ram": 72.0, "cpu": 30.0}), + dict.fromkeys(("j2", "j3", "j4", "j5"), "load 72 % RAM >= 70 % band")) + self.assertEqual(self.decide([running, *waiting], footprints=shares, band=band, load={"ram": 70.0, "cpu": 71.0}), + dict.fromkeys(("j2", "j3", "j4", "j5"), "load 70 % RAM >= 70 % band, load 71 % CPU >= 70 % band")) + big = {**shares, "j2": {"ram": 30, "cpu": 10}} + self.assertEqual(self.decide([running, *waiting], footprints=big, band=band, load={"ram": 63.0, "cpu": 30.0}), + {"j2": "would reach 93 % RAM > 90 %", "j3": None, "j4": "load 78 % RAM >= 70 % band", + "j5": "load 78 % RAM >= 70 % band"}) + self.assertIsNone(self.decide([running, *waiting], footprints=big, band=band, load={"ram": 60.0, "cpu": 30.0})["j2"]) + + def test_backfill_around_a_big_head_keeps_its_room_and_never_starves_it(self): + band = {"low": {"ram": 70, "cpu": 70}, "high": {"ram": 90, "cpu": 90}} + rules = {"band": band, "free_gb": 70.0, "drain": "j1"} + running = job(9, status="active", need_gb=40, workdir="/r") + head, small, greedy = job(1, need_gb=50), job(2, task="work/b", workdir="/s", need_gb=0), job(3, task="work/c", workdir="/t", need_gb=0) + shares = {"j9": {"ram": 30, "cpu": 20}, "j1": {"ram": 30, "cpu": 20}, "j2": {"ram": 10, "cpu": 5}, "j3": {"ram": 25, "cpu": 5}} + load = {"ram": 40.0, "cpu": 20.0} + trace: dict[str, list[str]] = {} + verdicts = self.run_pass([running, head, small, greedy], footprints=shares, load=load, trace=trace, **rules)[0] + self.assertEqual(verdicts, {"j1": "50 GB would cut into the 10 GB floor", "j2": None, "j3": "reserved for j1"}) + self.assertIn("takes nothing j1 lacks", trace["j2"]) + self.assertEqual(trace["j3"][-1], "reserved for j1: takes RAM") + self.assertIsNone(self.decide([running, head, greedy], footprints=shares, load=load, **{**rules, "drain": None})["j3"]) + freed = self.decide([head, small, greedy], footprints=shares, load={"ram": 10.0, "cpu": 5.0}, **rules) + self.assertEqual(freed["j1"], None) + + def test_the_drain_blocks_backfill_only_when_the_head_cannot_fit_even_with_nothing_backfilled(self): + band = {"low": {"ram": 70, "cpu": 70}, "high": {"ram": 90, "cpu": 90}} + running = job(9, status="active", workdir="/r") + head, small = job(1), job(2, kind="iteration", task="work/b", workdir="/s") + shares = {"j9": {"ram": 20, "cpu": 10}, "j1": {"ram": 40, "cpu": 10}, "j2": {"ram": 6, "cpu": 5}} + crowded = self.decide([running, head, small], footprints=shares, band=band, load={"ram": 55.0, "cpu": 20.0}, drain="j1") + self.assertEqual(crowded, {"j1": "would reach 95 % RAM > 90 %", "j2": "drained for j1"}) + capped = {"band": band, "load": {"ram": 45.0, "cpu": 20.0}, "drain": "j1", "slot_limits": {"test": 1}} + self.assertEqual(self.decide([running, head, small], footprints=shares, **capped), + {"j1": "all 1 test slots taken", "j2": "reserved for j1"}) + fits = {**shares, "j2": {"ram": 5, "cpu": 5}} + self.assertEqual(self.decide([running, head, small], footprints=fits, **capped), {"j1": "all 1 test slots taken", "j2": None}) + + def test_the_band_comes_from_load_limits_with_defaults_70_and_90_and_low_below_high(self): + limits = {"cpu_percent": 90, "mem_percent": 85, "sample_seconds": 5} + self.assertEqual(self.queue.band({"load_limits": limits}), {"low": {"ram": 70, "cpu": 70}, "high": {"ram": 90, "cpu": 90}}) + self.assertEqual(self.queue.band({"load_limits": {**limits, "band_low": 60, "band_high": 80}}), + {"low": {"ram": 60, "cpu": 60}, "high": {"ram": 80, "cpu": 80}}) + self.assertIsNone(self.queue.band_problem({"load_limits": limits})) + self.assertIsNone(self.queue.band_problem({"load_limits": {**limits, "band_low": 50.5, "band_high": 95}})) + problem = "load_limits.band_low and load_limits.band_high are percentages above 0, band_low below band_high" + for bad in ({"band_low": 90, "band_high": 90}, {"band_low": 95}, {"band_high": 60}, {"band_low": 0}, {"band_low": -5}, + {"band_low": "70"}, {"band_low": True}, {"band_high": float("nan")}): + with self.subTest(bad=bad): + self.assertEqual(self.queue.band_problem({"load_limits": {**limits, **bad}}), problem) + self.assertEqual(self.queue.band_problem({"load_limits": [70, 90]}), problem) + + def test_a_kind_without_a_configured_cap_has_no_slot_limit_and_a_cap_of_0_never_starts(self): + many = [job(n, status="active", workdir=f"/a{n}") for n in range(1, 8)] + self.assertEqual(self.decide([*many, job(8, kind="gui-dind")], slot_limits={}), {"j8": None}) + self.assertEqual(self.decide([*many, job(8)], slot_limits={"test": 7}), {"j8": "all 7 test slots taken"}) + self.assertEqual(self.decide([job(8, kind="swarm")], slot_limits={"swarm": 0}), {"j8": "all 0 swarm slots taken"}) + def test_load_counts_the_ram_in_use_plus_what_is_still_to_come(self): limits = {"cpu_percent": 90, "mem_percent": 90} reason = self.queue.load_reason @@ -191,6 +260,14 @@ class TestEvaluate(Passes, unittest.TestCase): self.assertEqual(self.queue.admitted_ram({"admits": [{"ram": 7, "expires": NOW + 1}, {"ram": 9, "expires": NOW}]}, NOW), 7) self.assertEqual(self.queue.admitted_ram({"entries": []}, NOW), 0) + def test_the_live_load_adds_the_young_jobs_ramp_on_ram_and_cpu_and_the_admits(self): + gate = {**job(1, kind="g", status="active", granted=NOW - 60), "workdir": "/w", "cmd": "g", + "footprint": {"ram": 40, "cpu": 30}, "granted_mem": 10, "granted_cpu": 20} + ramped = {**gate, "id": "j2", "granted": NOW - self.queue.RAMP_SECONDS} + self.assertEqual(self.queue.live_load([gate, ramped], NOW, {}, {}, 30.0, 20.0, 5.0), {"ram": 20 + 5 + 30, "cpu": 30 + 20}) + undated = {k: v for k, v in gate.items() if k != "granted_cpu"} + self.assertEqual(self.queue.live_load([undated], NOW, {}, {}, 30.0, 20.0, 0.0), {"ram": 20 + 30, "cpu": 30 + 30}) + def test_a_signature_names_the_repository_every_worktree_shares(self): with tempfile.TemporaryDirectory() as tmp: base = Path(tmp).resolve() @@ -367,7 +444,7 @@ class TestEvaluate(Passes, unittest.TestCase): greedy = {"j1": {"ram": 30, "cpu": 30}, "j2": {"ram": 40, "cpu": 40}, "j3": {"ram": 5, "cpu": 5}, "j4": {"ram": 30, "cpu": 5}} self.assertEqual(self.decide([running, gate, deploy, light], footprints=greedy, **gates)["j4"], None) self.assertEqual(self.decide([running, gate, deploy, light], footprints=greedy | {"j4": {"ram": 40, "cpu": 70}}, **gates)["j4"], - "drained for j2") + "reserved for j2") self.assertEqual( self.decide([gate, deploy, light], **gates), {"j2": None, "j3": "quality-high runs only beside test-nostack", "j4": None}, @@ -450,7 +527,7 @@ class TestEvaluate(Passes, unittest.TestCase): def test_a_blocked_entry_reserves_nothing_for_light_and_heavy_kinds_alike(self): rules = {"slot_limits": {"test": 5, "test-nostack": 5, "deploy": 1}, "light": {"test-nostack"}} - with self.subTest("budget"): + with self.subTest("band"): running, head, twin = job(1, status="active"), job(2), job(3, task="work/b") light, heavy = job(4, kind="test-nostack", task="work/c", need_gb=0), job(5, task="work/c") shares = { @@ -458,8 +535,8 @@ class TestEvaluate(Passes, unittest.TestCase): "j4": {"ram": 6, "cpu": 11}, "j5": {"ram": 5, "cpu": 5}, } self.assertEqual(self.decide([running, head, twin, light, heavy], footprints=shares, **rules), { - "j2": "RAM 30 % in use or reserved + 50 % > budget 75 %, CPU 50 % in use or reserved + 60 % > budget 100 %", - "j3": "RAM 30 % in use or reserved + 50 % > budget 75 %, CPU 50 % in use or reserved + 60 % > budget 100 %", + "j2": "would reach 80 % RAM > 75 %, would reach 110 % CPU > 100 %", + "j3": "would reach 80 % RAM > 75 %, would reach 110 % CPU > 100 %", "j4": None, "j5": None, }) @@ -474,7 +551,7 @@ class TestEvaluate(Passes, unittest.TestCase): heavy = job(4, task="work/c") shares = {"j1": {"ram": 10, "cpu": 60}, "j2": {"ram": 0, "cpu": 30}, "j3": {"ram": 0, "cpu": 30}, "j4": {"ram": 5, "cpu": 5}} self.assertEqual(self.decide([running, first, second, heavy], footprints=shares, **rules), { - "j2": None, "j3": "CPU 90 % in use or reserved + 30 % > budget 100 %", "j4": None, + "j2": None, "j3": "would reach 120 % CPU > 100 %", "j4": None, }) with self.subTest("a head the host load keeps out while a job runs"): load = "RAM 55 % used + 41 % still to come reach the limit 90 %" @@ -516,7 +593,7 @@ class TestBackfill(Passes, unittest.TestCase): self.assertEqual(drain, "j1926") backfill = self.decide(queue({2, 3, 4, 5}, [6, 7, 8]), free_gb=85.0, **rules) drained = self.decide(queue({2, 3, 4, 5}, [6, 7, 8]), free_gb=85.0, drain="j1926", **rules) - self.assertEqual((backfill["j8"], drained["j8"]), (None, "drained for j1926")) + self.assertEqual((backfill["j8"], drained["j8"]), (None, "reserved for j1926")) self.assertEqual(drained["j6"], "18 GB would cut into the 15 GB floor") verdicts, _, order = self.run_pass(queue(set(), [6, 7, 8]), free_gb=85.0, drain="j1926", **rules) self.assertEqual((order[0]["id"], verdicts["j1926"]), ("j1926", None)) @@ -552,7 +629,7 @@ class TestBackfill(Passes, unittest.TestCase): running, fixing = job(9, status="active", workdir="/r"), job(1, hotfix="main-red") shares = {"j9": {"ram": 50, "cpu": 10}, "j1": {"ram": 30, "cpu": 10}, "j2": {"ram": 5, "cpu": 5}, "j3": {"ram": 10, "cpu": 5}} self.assertEqual(self.decide([running, fixing, small, light], footprints=shares, **rules), { - "j1": "RAM 50 % in use or reserved + 30 % > budget 75 %", "j2": "waits behind hotfix j1", "j3": "waits behind hotfix j1", + "j1": "would reach 80 % RAM > 75 %", "j2": "waits behind hotfix j1", "j3": "waits behind hotfix j1", }) self.assertEqual(self.decide([running, fixing, light], footprints=shares | {"j3": {"ram": 0, "cpu": 5}}, **rules)["j3"], None) pressed = self.decide([running, fixing, light], loaded={"j1": "CPU 95 % busy reaches the limit 90 %"}, **rules) @@ -571,7 +648,7 @@ class TestBackfill(Passes, unittest.TestCase): self.assertEqual(self.run_pass([running, big, small], **rules)[1], "j1") self.assertEqual(self.decide([running, big, small, late, light], drain="j1", **rules), { "j1": "50 GB would cut into the 10 GB floor", "j2": "25 GB would cut into the 10 GB floor", - "j3": "drained for j1", "j4": None, + "j3": "reserved for j1", "j4": None, }) self.assertEqual(self.run_pass([running, big, small, late], drain="j1", **rules)[1], "j1") self.assertEqual(self.decide([big, small, late], drain="j1", **rules), { @@ -583,7 +660,7 @@ class TestBackfill(Passes, unittest.TestCase): fits, wide = job(3, task="work/c", need_gb=5, workdir="/t"), job(5, task="work/c", need_gb=45, workdir="/u") slots = {**rules, "slot_limits": {"test": 5, "deploy": 1}} self.assertEqual(self.decide([deploying, head, fits, wide], drain="j1", **slots), { - "j1": "all 1 deploy slots taken", "j3": None, "j5": "drained for j1", + "j1": "all 1 deploy slots taken", "j3": None, "j5": "reserved for j1", }) def test_claims_name_the_worktree_and_the_compose_stack_its_directory_derives(self): @@ -689,7 +766,7 @@ class TestBackfill(Passes, unittest.TestCase): light = job(2, kind="test-nostack", task="work/b", workdir="/l") shares = {"j9": {"ram": 40, "cpu": 0}, "j1": {"ram": 45, "cpu": 0}, "j2": {"ram": 35, "cpu": 0}} self.assertEqual(self.decide([running, head, light], footprints=shares, **rules), { - "j1": "RAM 40 % in use or reserved + 45 % > budget 75 %", "j2": "drained for j1", + "j1": "would reach 85 % RAM > 75 %", "j2": "drained for j1", }) self.assertIsNone(self.decide([running, head, light], footprints={**shares, "j2": {"ram": 0, "cpu": 0}}, **rules)["j2"]) @@ -760,7 +837,7 @@ class TestBackfill(Passes, unittest.TestCase): {"quality-high-1060": None, "test-1008": "quality-high runs only beside test-nostack", "test-nostack-1": None}) def test_r4_a_head_aged_out_waiting_only_for_an_exclusive_job_holds_back_no_light_job(self): - rules = {"exclusive": {"quality-high", "test"}, "light": {"test-nostack"}, "budget": {"ram": 75, "cpu": 100}, + rules = {"exclusive": {"quality-high", "test"}, "light": {"test-nostack"}, "band": BASE["band"], "slot_limits": {"quality-high": 1, "test": 1, "test-nostack": 4}} running = job(9, kind="test", status="active", workdir="/r", granted=NOW - 300) head, light = job(1, kind="quality-high", enqueued=NOW - 3700), job(2, kind="test-nostack", task="work/b", workdir="/l") @@ -768,7 +845,7 @@ class TestBackfill(Passes, unittest.TestCase): verdicts, drain, _ = self.run_pass([running, head, light], footprints=shares, drain="j1", **rules) self.assertEqual((verdicts, drain), ({"j1": "quality-high runs only beside test-nostack, but test runs", "j2": None}, "j1")) greedy = {**shares, "j2": {"ram": 40.0, "cpu": 9.8}} - self.assertEqual(self.decide([running, head, light], footprints=greedy, drain="j1", **rules)["j2"], "drained for j1") + self.assertEqual(self.decide([running, head, light], footprints=greedy, drain="j1", **rules)["j2"], "reserved for j1") class TestTrace(Passes, unittest.TestCase): @@ -811,13 +888,13 @@ class TestTrace(Passes, unittest.TestCase): "load head": ([running, job(1), job(2, task="work/b")], {"loaded": {"j1": load}, "drain": "j1"}, "j2", "drained for j1: load holds it"), "takes what the head lacks": ([*machine[:2], job(2, kind="test-nostack", task="work/b")], {"footprints": greedy, **gates}, "j2", - "drained for j1: takes RAM and CPU"), + "reserved for j1: takes RAM and CPU"), "disk stage": ([job(1)], {"stage": "stop"}, "j1", "disk stage stop"), "memory stage": ([job(1)], {"memory": "stop"}, "j1", "memory stage stop"), "slot": ([job(1, kind="deploy", status="active"), job(2, kind="deploy", task="work/b")], {}, "j2", "all 1 deploy slots taken"), "alone": (machine, gates, "j1", "quality-high runs only beside test-nostack, but iteration runs"), - "budget": ([running, job(1)], {"footprints": {"j9": {"ram": 50, "cpu": 0}, "j1": {"ram": 30, "cpu": 0}}}, "j1", - "RAM 50 % in use or reserved + 30 % > budget 75 %"), + "band": ([running, job(1)], {"footprints": {"j9": {"ram": 50, "cpu": 0}, "j1": {"ram": 30, "cpu": 0}}}, "j1", + "would reach 80 % RAM > 75 %"), "floor": ([job(1, need_gb=95)], {}, "j1", "95 GB would cut into the 10 GB floor"), "load": ([job(1)], {"loaded": {"j1": load}}, "j1", load), } @@ -858,7 +935,7 @@ class TestTrace(Passes, unittest.TestCase): self.assertEqual(verdicts["j2"], None) self.assertIn("takes nothing j1 lacks", trace["j2"]) greedy = shares | {"j2": {"ram": 7.2, "cpu": 40.0}} - self.assertEqual(self.decide([gate, head, light], footprints=greedy, drain="j1", **gates)["j2"], "drained for j1") + self.assertEqual(self.decide([gate, head, light], footprints=greedy, drain="j1", **gates)["j2"], "reserved for j1") def test_r7_a_hotfix_never_waits_in_line_behind_an_older_waiting_entry_that_is_no_hotfix(self): gates = {"exclusive": {"quality-high"}, "light": {"test-nostack"}, @@ -884,8 +961,8 @@ class TestTrace(Passes, unittest.TestCase): rival = job(2, id="I2", kind="iteration", workdir="/v", enqueued=NOW - 4000) running = job(9, id="L1", kind="test-nostack", status="active", workdir="/h") verdicts, trace = self.traced([*busy, running, head, rival], drain="H", **gates) - self.assertEqual(verdicts, {"H": "waits in line behind L1", "I2": "drained for H"}) - self.assertEqual(trace["I2"][-1], "drained for H: takes its iteration slot") + self.assertEqual(verdicts, {"H": "waits in line behind L1", "I2": "reserved for H"}) + self.assertEqual(trace["I2"][-1], "reserved for H: takes its iteration slot") later = job(3, id="L2", kind="test-nostack", workdir="/h", enqueued=NOW - 100) elsewhere = job(4, id="L3", kind="test-nostack", workdir="/z", enqueued=NOW - 50) verdicts, trace = self.traced([*busy, {**rival, "status": "active"}, head, later, elsewhere], drain="H", **gates) @@ -895,7 +972,7 @@ class TestTrace(Passes, unittest.TestCase): next_one = job(5, id="L4", kind="test-nostack", workdir="/h", enqueued=NOW - 20) third = job(6, id="I3", kind="iteration", workdir="/w", enqueued=NOW - 10) freed = [busy[0], {**rival, "status": "active"}, {**later, "status": "active"}, head, next_one, third] - self.assertEqual(self.decide(freed, drain="H", **gates), {"H": "waits in line behind L2", "L4": "waits in line behind L2", "I3": "drained for H"}) + self.assertEqual(self.decide(freed, drain="H", **gates), {"H": "waits in line behind L2", "L4": "waits in line behind L2", "I3": "reserved for H"}) self.assertEqual(self.decide([busy[0], {**rival, "status": "active"}, head, next_one, third], drain="H", **gates), {"H": None, "L4": "waits in line behind H", "I3": "all 3 iteration slots taken"}) @@ -1314,6 +1391,8 @@ class TestHistory(unittest.TestCase): signatures, kinds = self.learn(rows) self.assertEqual((signatures["test", "make test"]["cpu_share"], kinds["test"]["cpu_share"]), (2, 2)) self.assertEqual(kinds["test"]["ram_share"], 10) + ram = [history_row(n, mem_before=20, mem_max=20 + share) for n, share in enumerate((5, 5, 10, 15, 15))] + self.assertAlmostEqual(self.learn(ram)[0]["test", "make test"]["ram_share"], 15) def test_learn_fits_the_slot_limit_between_the_median_load_and_the_load_limits(self): loads = ((10, 5), (20, 5), (20, 10), (30, 15), (40, 15)) @@ -1431,7 +1510,7 @@ class TestQueueCommands(unittest.TestCase): "projection_minutes": 30, "slot_need_gb": {"test": 0.001, "deploy": 0}, "slot_limits": {"test": 1, "deploy": 1}, - "load_limits": {"cpu_percent": 101, "mem_percent": 101, "sample_seconds": 0.1}, + "load_limits": {"cpu_percent": 101, "mem_percent": 101, "sample_seconds": 0.1, "band_low": 99, "band_high": 100}, "budget_percent": {"ram": 75, "cpu": 100}, "memory_limits": {stage: OPEN_MEMORY for stage in ("warn", "stop")}, "heavy_commands": ["^make compose-deploy"], @@ -1540,7 +1619,7 @@ class TestQueueCommands(unittest.TestCase): self.assertEqual(self.run_queue("hold", "--kind", "test", "--task", "work/a", "--session", "s1", "--", "false").returncode, 1) self.assertEqual(len(self.history_file.read_text(encoding="utf-8").splitlines()), 1) - def test_hold_runs_without_slot_limits_on_the_seed_limit(self): + def test_hold_runs_without_slot_limits_uncapped(self): del self.cfg["slot_limits"] self.write_config() result = self.run_queue("hold", "--kind", "test", "--task", "work/a", "--session", "s1", "--", "true") @@ -1662,7 +1741,7 @@ class TestQueueCommands(unittest.TestCase): self.assertEqual(listing.returncode, 0, listing.stderr) rows = json.loads(listing.stdout) self.assertEqual([list(row) for row in rows], [[ - "position", "id", "status", "kind", "task", "session", "agent", "class", "prio", "wsjf", "waited_s", "eta_s", "reason", "trace", + "position", "id", "status", "kind", "task", "session", "agent", "class", "prio", "wsjf", "waited_s", "eta_s", "reason", "trace", "override", ]] * 3) shown = {row["id"]: row for row in rows} self.assertEqual([(row["position"], row["id"]) for row in rows], [(None, "test-3"), (1, "deploy-1"), (2, "test-2")]) @@ -1855,6 +1934,17 @@ class TestQueueCommands(unittest.TestCase): self.assertIn("ram_cap_percent is no {kind: percent above 0 up to 100} map", result.stderr) self.assertFalse((self.root / "queue.json").exists()) + def test_a_band_whose_low_is_not_below_its_high_keeps_the_last_good_config_and_a_hold_refuses_it(self): + queue = _load(QUEUE) + inverted = {**self.cfg, "load_limits": {**self.cfg["load_limits"], "band_low": 90, "band_high": 80}} + with mock.patch.object(queue.watch, "load_config", return_value=inverted): + self.assertEqual(queue.fresh(self.cfg), self.cfg) + self.config.write_text(json.dumps(inverted), encoding="utf-8") + result = self.run_queue("hold", "--kind", "test", "--task", "work/a", "--session", "s1", "--", "true") + self.assertEqual(result.returncode, 2) + self.assertIn("band_low below band_high", result.stderr) + self.assertFalse((self.root / "queue.json").exists()) + def test_hold_takes_the_need_learned_for_its_command_from_both_history_files(self): self.cfg["slot_limits"]["deploy"] = 0 self.write_config() @@ -1907,10 +1997,10 @@ class TestQueueCommands(unittest.TestCase): result = self.run_queue("history") self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(result.stdout, ( - "| Signature | Kind | Runs | Median min | p90 disk GB | p90 RAM % | Need GB |\n" - "| --- | --- | --- | --- | --- | --- | --- |\n" - "| make compose-deploy | deploy | 5 | 12.0 | 4.6 | 10.0 | 6 |\n" - "| true | test | 2 | - | - | - | - |\n" + "| Signature | Kind | Runs | Median min | p90 disk GB | p95 RAM % | Margin | Need GB |\n" + "| --- | --- | --- | --- | --- | --- | --- | --- |\n" + "| make compose-deploy | deploy | 5 | 12.0 | 4.6 | 10.0 | 1.00 | 6 |\n" + "| true | test | 2 | - | - | - | 1.00 | - |\n" "\n" "| Kind | Runs | p90 RAM share % | Median CPU share % | Slot limit | Source |\n" "| --- | --- | --- | --- | --- | --- |\n" diff --git a/tests/test_queue_aimd.py b/tests/test_queue_aimd.py new file mode 100644 index 0000000..f3a2c9a --- /dev/null +++ b/tests/test_queue_aimd.py @@ -0,0 +1,167 @@ +"""Exercise the self-tuning queue of requirement 083: the AIMD target, the settle window and the p95 footprints with their margin.""" + +from __future__ import annotations + +import unittest + +import test_queue as fixtures + +AIMD = fixtures.REPO_ROOT / "skills" / "kvb-org-queue" / "scripts" / "aimd.py" +NOW = fixtures.NOW +BAND = {"low": {"ram": 70, "cpu": 70}, "high": {"ram": 90, "cpu": 90}} +CALM = {"psi_some": 0.2, "swap_out_mb_min": 0.0} +EVERY = 20 + + +def peak(seq: int, ram: float, cpu: float, **fields: object) -> dict: + return fixtures.history_row(seq, mem_before=20, mem_max=20 + ram, cpu_before=10, cpu_max=10 + cpu, end=NOW - 100 + seq, **fields) + + +class TestTarget(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.aimd = fixtures._load(AIMD) + + def poll(self, state: dict, at: float, load: dict[str, float], pressure: dict[str, float | None]) -> tuple[dict, dict]: + state = self.aimd.stepped(state, BAND, load, pressure, 1.0, at, EVERY) + return state, self.aimd.target(state, BAND) + + def test_a_fresh_target_starts_at_the_upper_limit_and_a_stored_one_stays_inside_the_band(self): + self.assertEqual(self.aimd.target({}, BAND), {"ram": 90, "cpu": 90}) + self.assertEqual(self.aimd.target({"ram": 50, "cpu": 99}, BAND), {"ram": 70, "cpu": 90}) + self.assertEqual(self.aimd.target({"ram": "80", "cpu": True}, BAND), {"ram": 90, "cpu": 90}) + + def test_below_the_lower_limit_the_target_rises_by_2_per_poll_up_to_the_upper_limit(self): + state, seen = {"ram": 70, "cpu": 76}, [] + for n in range(12): + state, aim = self.poll(state, NOW + n * EVERY, {"ram": 40, "cpu": 30}, CALM) + seen.append(aim) + self.assertEqual([aim["ram"] for aim in seen], [72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 90, 90]) + self.assertEqual([aim["cpu"] for aim in seen[:8]], [78, 80, 82, 84, 86, 88, 90, 90]) + + def test_a_pass_inside_the_step_interval_only_adds_its_sample(self): + state, aim = self.poll({"ram": 70, "cpu": 70}, NOW, {"ram": 40, "cpu": 30}, CALM) + self.assertEqual(aim, {"ram": 72, "cpu": 72}) + state, aim = self.poll(state, NOW + EVERY - 1, {"ram": 95, "cpu": 95}, {"psi_some": 50.0, "swap_out_mb_min": 900.0}) + self.assertEqual(aim, {"ram": 72, "cpu": 72}) + self.assertEqual((len(state["samples"]), state["stepped"]), (2, NOW)) + state, aim = self.poll(state, NOW + EVERY, {"ram": 40, "cpu": 30}, CALM) + self.assertEqual(aim, {"ram": 74, "cpu": 74}) + + def test_load_above_the_upper_limit_rising_psi_and_swap_out_drop_it_at_once_to_the_middle(self): + state = {"ram": 90, "cpu": 90, "psi": 0.5, "stepped": NOW - EVERY} + state, aim = self.poll(state, NOW, {"ram": 95, "cpu": 50}, CALM) + self.assertEqual(aim, {"ram": 80, "cpu": 90}) + state, aim = self.poll(state, NOW + EVERY, {"ram": 50, "cpu": 50}, {"psi_some": 4.0, "swap_out_mb_min": 0.0}) + self.assertEqual(aim, {"ram": 75, "cpu": 80}) + state, aim = self.poll(state, NOW + 2 * EVERY, {"ram": 50, "cpu": 50}, {"psi_some": 4.0, "swap_out_mb_min": 0.0}) + self.assertEqual(aim, {"ram": 75, "cpu": 80}) + state, aim = self.poll(state, NOW + 3 * EVERY, {"ram": 50, "cpu": 50}, {"psi_some": 0.3, "swap_out_mb_min": 12.0}) + self.assertEqual(aim, {"ram": 72.5, "cpu": 75}) + state, aim = self.poll(state, NOW + 4 * EVERY, {"ram": 50, "cpu": 50}, {"psi_some": None, "swap_out_mb_min": None}) + self.assertEqual(aim, {"ram": 74.5, "cpu": 77}) + + def test_the_rise_follows_the_10_minute_average_not_the_last_sample(self): + busy = [[NOW - 500 + 20 * k, 80.0, 80.0] for k in range(25)] + state = {"ram": 80, "cpu": 80, "stepped": NOW - EVERY, "samples": busy} + state, aim = self.poll(state, NOW, {"ram": 40, "cpu": 40}, CALM) + self.assertEqual(aim, {"ram": 80, "cpu": 80}) + state, aim = self.poll(state, NOW + self.aimd.WINDOW_SECONDS, {"ram": 40, "cpu": 40}, CALM) + self.assertEqual(aim, {"ram": 82, "cpu": 82}) + self.assertEqual([row[0] for row in state["samples"]], [NOW, NOW + self.aimd.WINDOW_SECONDS]) + + +class TestSelfTuningPass(fixtures.Passes, unittest.TestCase): + def test_a_grant_is_refused_while_load_plus_footprint_passes_the_target_and_the_reason_names_it(self): + running, waiting = fixtures.job(1, status="active"), fixtures.job(2, task="work/b", workdir="/b") + shares = {"j1": {"ram": 0, "cpu": 0}, "j2": {"ram": 15, "cpu": 5}} + load = {"ram": 58.0, "cpu": 30.0} + aimed = {**BAND, "target": {"ram": 72.0, "cpu": 90.0}} + self.assertEqual(self.decide([running, waiting], footprints=shares, band=aimed, load=load), + {"j2": "would reach 73 % RAM > target 72.0 %"}) + self.assertIsNone(self.decide([running, waiting], footprints=shares, band={**BAND, "target": {"ram": 73.0, "cpu": 90.0}}, + load=load)["j2"]) + self.assertIsNone(self.decide([running, waiting], footprints=shares, band=BAND, load=load)["j2"]) + + def test_one_queue_pass_per_poll_over_a_load_series_grants_and_refuses_by_the_target(self): + aimd = fixtures._load(AIMD) + running, waiting = fixtures.job(1, status="active"), fixtures.job(2, task="work/b", workdir="/b") + shares = {"j1": {"ram": 0, "cpu": 0}, "j2": {"ram": 15, "cpu": 5}} + series = [ + ({"ram": 58.0, "cpu": 30.0}, CALM, "would reach 73 % RAM > target 72.0 %"), + ({"ram": 58.0, "cpu": 30.0}, CALM, None), + ({"ram": 58.0, "cpu": 30.0}, {"psi_some": 5.0, "swap_out_mb_min": 0.0}, "would reach 73 % RAM > target 72.0 %"), + ({"ram": 92.0, "cpu": 30.0}, CALM, "load 92 % RAM >= 70 % band"), + ] + state = {"ram": 70, "cpu": 90} + for n, (load, pressure, reason) in enumerate(series): + with self.subTest(poll=n): + state = aimd.stepped(state, BAND, load, pressure, 1.0, NOW + n * EVERY, EVERY) + aimed = {**BAND, "target": aimd.target(state, BAND)} + self.assertEqual(self.decide([running, waiting], footprints=shares, band=aimed, load=load), {"j2": reason}) + self.assertEqual(aimd.target(state, BAND)["ram"], 71) + + def test_at_most_one_grant_lands_per_settle_window_while_a_queue_job_runs(self): + running, first, second = fixtures.job(1, status="active"), fixtures.job(2, task="work/b", workdir="/b"), fixtures.job(3, task="work/c", workdir="/c") + settles = "settles: the last grant was 2 s ago, one grant per 5 s" + self.assertEqual(self.decide([running, first], settle=(5, NOW - 2)), {"j2": settles}) + self.assertEqual(self.decide([running, first], settle=(5, NOW - 5)), {"j2": None}) + self.assertEqual(self.decide([running, first], settle=(5, None)), {"j2": None}) + self.assertEqual(self.decide([first], settle=(5, NOW - 2)), {"j2": None}) + granted = {**first, "status": "active"} + self.assertEqual(self.decide([running, granted, second], settle=(5, NOW - 1)), + {"j3": "settles: the last grant was 1 s ago, one grant per 5 s"}) + self.assertEqual(self.decide([running, granted, second], settle=(5, NOW - 5)), {"j3": None}) + self.assertEqual(self.queue.settle_reason((5, NOW + 3), NOW), None) + self.assertEqual(self.queue.settle_reason(None, NOW), None) + + +class TestLearnedSizes(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.history = fixtures._load(fixtures.HISTORY) + cls.queue = fixtures._load(fixtures.QUEUE) + + def learn(self, rows: list[dict]) -> tuple[dict, dict]: + return self.history.learn(rows, NOW, {"load_limits": {"mem_percent": 80, "cpu_percent": 90}}) + + def test_the_margin_grows_by_the_overshoot_shrinks_slowly_and_stays_between_1_and_2(self): + margin, booked = self.history.margin, {"ram": 10, "cpu": 100} + self.assertEqual(margin([peak(1, 12, 30, predicted=booked)]), 1.2) + self.assertAlmostEqual(margin([peak(1, 12, 30, predicted=booked), peak(2, 5, 30, predicted=booked)]), 1.15) + self.assertAlmostEqual(margin([peak(2, 5, 30, predicted=booked), peak(1, 12, 30, predicted=booked)]), 1.15) + self.assertEqual(margin([peak(1, 40, 30, predicted=booked)]), 2.0) + self.assertEqual(margin([peak(n, 5, 30, predicted=booked) for n in range(3)]), 1.0) + self.assertEqual(margin([peak(1, 30, 30, predicted={"ram": 10, "cpu": 20})]), 2.0) + self.assertEqual(margin([peak(1, 40, 30), peak(2, 40, 30, predicted={"ram": 0, "cpu": True})]), 1.0) + shrunk = [peak(1, 20, 30, predicted=booked), *(peak(n + 2, 5, 30, predicted=booked) for n in range(4))] + self.assertAlmostEqual(margin(shrunk), 1.8) + + def test_the_footprint_is_the_p95_of_the_peaks_times_the_learned_margin_and_the_band_refuses_it(self): + shares = (5, 5, 10, 15, 15) + plain = [peak(n, ram, 30) for n, ram in enumerate(shares)] + signatures, kinds = self.learn(plain) + self.assertEqual(self.history.footprint("test", ("make test",), signatures, kinds), {"ram": 15, "cpu": 30}) + predicted = [{"ram": 10, "cpu": 100}] * 4 + [{"ram": 15, "cpu": 100}] + taught = [{**row, "predicted": booked} for row, booked in zip(plain, predicted)] + signatures, kinds = self.learn(taught) + self.assertAlmostEqual(signatures["test", "make test"]["margin"], 1.45) + share = self.history.footprint("test", ("make test",), signatures, kinds) + self.assertAlmostEqual(share["ram"], 21.75) + self.assertAlmostEqual(share["cpu"], 43.5) + running, waiting = fixtures.job(1, status="active"), fixtures.job(2, task="work/b", workdir="/b") + rules = {**fixtures.BASE, "band": {**BAND, "target": {"ram": 70.0, "cpu": 90.0}}, "load": {"ram": 50.0, "cpu": 20.0}} + verdicts = self.queue.evaluate([running, waiting], **{**rules, "footprints": {"j1": {"ram": 0, "cpu": 0}, "j2": share}})[0] + self.assertEqual(verdicts, {"j2": "would reach 72 % RAM > target 70.0 %"}) + verdicts = self.queue.evaluate([running, waiting], **{**rules, "footprints": {"j1": {"ram": 0, "cpu": 0}, "j2": {"ram": 15, "cpu": 30}}})[0] + self.assertEqual(verdicts, {"j2": None}) + + def test_a_finished_job_records_the_footprint_its_grant_booked(self): + entry = fixtures.job(1) + self.assertEqual(self.queue.finished(entry, "make test", None, False, {"ram": 12.0, "cpu": 30.0})["predicted"], + {"ram": 12.0, "cpu": 30.0}) + self.assertNotIn("predicted", self.queue.finished(entry, "make test", None, False, None)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_queue_override.py b/tests/test_queue_override.py new file mode 100644 index 0000000..689afae --- /dev/null +++ b/tests/test_queue_override.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import json +import os +import unittest + +import test_queue as fixtures + +LOAD = "CPU 95 % busy reaches the limit 90 %" +MARK = {"override": {"ts": fixtures.NOW - 30}} + + +class TestOverridePass(fixtures.Passes, unittest.TestCase): + def busy(self, **fields: object) -> list[dict]: + return [fixtures.job(1, status="active"), fixtures.job(2, **fields)] + + def shares(self) -> dict[str, dict[str, float]]: + return {"j1": {"ram": 1, "cpu": 70}, "j2": {"ram": 1, "cpu": 40}} + + def test_the_band_holds_a_job_and_its_override_grants_it_first(self): + held = self.decide(self.busy(), footprints=self.shares()) + self.assertEqual(held["j2"], "would reach 110 % CPU > 100 %") + granted = self.decide(self.busy(**MARK), footprints=self.shares()) + self.assertEqual(granted, {"j2": None}) + + def test_the_override_skips_slots_and_rank_and_counts_against_the_disk_of_the_next(self): + entries = [fixtures.job(1, kind="deploy", status="active"), fixtures.job(2, kind="deploy", task="work/c", **MARK), fixtures.job(3, need_gb=89)] + verdicts = self.decide(entries, free_gb=100.0) + self.assertEqual(next(iter(verdicts)), "j2") + self.assertIsNone(verdicts["j2"]) + self.assertIn("floor", verdicts["j3"]) + + def test_the_live_guard_still_holds_an_overridden_job_and_its_reason_names_it(self): + steps: dict[str, list[str]] = {} + verdicts = self.decide(self.busy(**MARK), footprints=self.shares(), loaded={"j2": LOAD}, trace=steps) + self.assertEqual(verdicts["j2"], f"override held by the live guard load_limits: {LOAD}") + self.assertEqual(steps["j2"][0], "override: skips the band, slots, reservations and rank") + + def test_the_disk_the_memory_stage_and_a_running_job_of_its_line_still_hold_it(self): + cases = { + "floor": ({"free_gb": 12.0}, {"need_gb": 5}, "would cut into the 10 GB floor"), + "stage": ({"stage": "stop"}, {}, "disk stage stop"), + "memory": ({"memory": "stop"}, {}, "memory stage stop"), + "line": ({}, {"workdir": "/w1"}, "its line runs j1"), + } + for name, (rules, fields, reason) in cases.items(): + with self.subTest(case=name): + verdicts = self.decide(self.busy(**MARK, **fields), footprints=self.shares(), **rules) + self.assertTrue(verdicts["j2"].startswith("override held by "), verdicts) + self.assertIn(reason, verdicts["j2"]) + + def test_a_silent_holder_is_never_forced(self): + verdicts = self.decide(self.busy(polled=fixtures.NOW - 120, **MARK), footprints=self.shares()) + self.assertTrue(verdicts["j2"].startswith("no poll for")) + + def test_the_history_row_of_an_overridden_run_carries_override_true(self): + queue, history = self.queue, fixtures._load(fixtures.HISTORY) + entry = fixtures.job(2) + sample = {"free_gb": 50.0, "mem": 20.0, "cpu": 10.0} + row = history.row(queue.finished(entry, "make test", None, True, None), fixtures.NOW - 60, fixtures.NOW, 0, [sample], 1) + self.assertIs(row["override"], True) + self.assertNotIn("override", queue.finished(entry, "make test", None, False, None)) + + +class TestOverrideCommand(unittest.TestCase): + setUp = fixtures.TestQueueCommands.setUp + write_config = fixtures.TestQueueCommands.write_config + write_store = fixtures.TestQueueCommands.write_store + entries = fixtures.TestQueueCommands.entries + run_queue = fixtures.TestQueueCommands.run_queue + + def stored_entries(self) -> list[dict]: + me = os.getpid() + return [fixtures.stored(1, "waiting", me, None, None, None), fixtures.stored(2, "active", me, None, me, None)] + + def test_override_marks_a_waiting_entry_of_any_session(self): + self.write_store(self.stored_entries()) + done = self.run_queue("override", "test-1") + self.assertEqual(done.returncode, 0, done.stderr) + marked = {entry["id"]: entry.get("override") for entry in self.entries()} + self.assertIsInstance(marked["test-1"]["ts"], float) + self.assertIsNone(marked["test-2"]) + + def test_an_unknown_or_running_id_exits_2_and_changes_nothing(self): + self.write_store(self.stored_entries()) + store = self.root / "queue.json" + before = store.read_bytes() + for entry_id in ("test-9", "test-2"): + with self.subTest(id=entry_id): + done = self.run_queue("override", entry_id) + self.assertEqual(done.returncode, 2, done.stderr) + self.assertIn(f"no waiting entry {entry_id}", done.stderr) + self.assertEqual(store.read_bytes(), before) + + def test_list_json_shows_which_entry_is_overridden(self): + me = os.getpid() + mine = fixtures._load(fixtures.QUEUE).identity(me) + self.write_store([{**fixtures.stored(1, "waiting", me, mine, None, None), **MARK}]) + listing = self.run_queue("list", "--json") + self.assertEqual(listing.returncode, 0, listing.stderr) + self.assertEqual([(row["id"], row["override"]) for row in json.loads(listing.stdout)], [("test-1", True)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_queue_replay.py b/tests/test_queue_replay.py index c9fba60..465b422 100644 --- a/tests/test_queue_replay.py +++ b/tests/test_queue_replay.py @@ -20,6 +20,7 @@ FP = { } SLOTS = {"gui-dind": 1, "iteration": 3, "operator": 1, "quality-high": 1, "swarm": 1, "test": 1, "test-nostack": 4} BUDGET = {"ram": 75, "cpu": 100} +BAND = {"low": BUDGET, "high": BUDGET} LIMITS = {"cpu_percent": 101, "mem_percent": 85} EXCLUSIVE = {"quality-high", "test"} LIGHT = {"test-nostack"} @@ -152,8 +153,9 @@ def simulate(queue, jobs: list[dict], name: str, branch: bool, events: list | No j["polled"] = t entries = active + waiting load, free = loaded(queue, active, waiting, host["baseline"], t), host["free"](t) + booked = {r: sum(FP[a["kind"]][r] for a in active) for r in BUDGET} args = (entries, free, FLOOR, "stop" if free < FLOOR else "ok", "ok", False, SLOTS, {j["id"]: FP[j["kind"]] for j in entries}, - BUDGET, host["ranks"], host["agents"], load, EXCLUSIVE, LIGHT) + BAND, booked, host["ranks"], host["agents"], load, EXCLUSIVE, LIGHT) if branch: verdicts, drain, order = queue.evaluate(*args, data["drain"], t) data["drain"] = queue.latched(data, drain, t) diff --git a/tests/test_queue_settings.py b/tests/test_queue_settings.py new file mode 100644 index 0000000..4b7d768 --- /dev/null +++ b/tests/test_queue_settings.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +import json +import unittest + +import test_queue as fixtures + + +class TestQueueSettings(unittest.TestCase): + setUp = fixtures.TestQueueCommands.setUp + write_config = fixtures.TestQueueCommands.write_config + write_history = fixtures.TestQueueCommands.write_history + run_queue = fixtures.TestQueueCommands.run_queue + + def learned(self) -> dict: + done = self.run_queue("learned", "--json") + self.assertEqual(done.returncode, 0, done.stderr) + return json.loads(done.stdout) + + def test_learned_json_lists_kinds_signatures_settings_and_the_last_20_rows_and_writes_nothing(self): + rows = [fixtures.history_row(n, end=fixtures.NOW - n, signature="make test" if n % 2 else "make deploy", kind="test" if n % 2 else "deploy") for n in range(1, 31)] + self.write_history(self.history_file, rows) + self.cfg["ram_cap_percent"] = {"test": 20} + self.write_config() + before = sorted(path.name for path in self.root.iterdir()) + shown = self.learned() + self.assertEqual(sorted(shown), ["budget_percent", "history", "kinds", "load_limits", "ram_cap_percent", "signatures", "slot_limits"]) + self.assertEqual((shown["budget_percent"], shown["ram_cap_percent"], shown["slot_limits"]), (self.cfg["budget_percent"], {"test": 20}, self.cfg["slot_limits"])) + self.assertEqual(shown["load_limits"], self.cfg["load_limits"]) + self.assertEqual(sorted(shown["kinds"]), ["deploy", "test"]) + self.assertEqual({key: shown["kinds"]["test"][key] for key in ("runs", "ram_cap", "slot_limit", "slot_source")}, {"runs": 15, "ram_cap": 20, "slot_limit": 1, "slot_source": "capped by config"}) + self.assertEqual(sorted((row["kind"], row["signature"], row["runs"]) for row in shown["signatures"]), [("deploy", "make deploy", 15), ("test", "make test", 15)]) + self.assertEqual([row["id"] for row in shown["history"]], [f"r{n}" for n in range(20, 0, -1)]) + self.assertEqual(sorted(path.name for path in self.root.iterdir()), before) + + def test_learned_json_lists_a_configured_kind_without_rows_with_runs_0(self): + shown = self.learned() + self.assertEqual(shown["history"], []) + self.assertEqual({kind: (stats["runs"], stats["ram_share"], stats["slot_source"]) for kind, stats in shown["kinds"].items()}, {"deploy": (0, None, "seed"), "test": (0, None, "seed")}) + + def test_a_good_value_changes_only_its_key_and_keeps_unknown_keys_and_the_mode(self): + self.cfg["operator_note"] = {"kept": [1, 2]} + self.write_config() + self.config.chmod(0o640) + for key, value, path, expected in ( + ("budget_percent.cpu", "180", ("budget_percent", "cpu"), 180), + ("ram_cap_percent.test", "35.5", ("ram_cap_percent", "test"), 35.5), + ("slot_limits.deploy", "3", ("slot_limits", "deploy"), 3), + ("load_limits.cpu_percent", "95", ("load_limits", "cpu_percent"), 95), + ("load_limits.band_low", "70", ("load_limits", "band_low"), 70), + ): + with self.subTest(key=key): + before = json.loads(self.config.read_text(encoding="utf-8")) + done = self.run_queue("config", "set", key, value) + self.assertEqual(done.returncode, 0, done.stderr) + after = json.loads(self.config.read_text(encoding="utf-8")) + section, name = path + self.assertEqual(after[section][name], expected) + after[section] = {k: v for k, v in after[section].items() if k != name} + before[section] = {k: v for k, v in before.get(section, {}).items() if k != name} + self.assertEqual(after, before) + self.assertEqual(self.config.stat().st_mode & 0o777, 0o640) + + def test_a_bad_value_or_key_exits_2_and_leaves_the_file_byte_identical(self): + before = self.config.read_bytes() + for key, value in ( + ("budget_percent.cpu", "0"), ("budget_percent.cpu", "-5"), ("budget_percent.cpu", "1e3"), ("budget_percent.cpu", "NaN"), + ("ram_cap_percent.test", "120"), ("ram_cap_percent.ghost", "20"), ("slot_limits.test", "1.5"), ("load_limits.mem_percent", "101"), + ("cpu_cap_percent.test", "50"), ("budget_percent", "50"), ("thresholds_gb.stop", "1"), ("load_limits.kinds", "1"), + ("load_limits.band_high", "101"), ("load_limits.band_low", "100"), ("load_limits.band_low", "0"), ("load_limits.band_high", "98"), + ): + with self.subTest(key=key, value=value): + done = self.run_queue("config", "set", key, value) + self.assertEqual(done.returncode, 2, done.stderr) + self.assertEqual(self.config.read_bytes(), before) + + def test_a_linked_or_broken_config_is_refused_without_a_write(self): + target = self.base / "target.json" + target.write_text(self.config.read_text(encoding="utf-8"), encoding="utf-8") + self.config.unlink() + self.config.symlink_to(target) + self.assertEqual(self.run_queue("config", "set", "budget_percent.cpu", "90").returncode, 2) + self.assertTrue(self.config.is_symlink()) + self.config.unlink() + self.config.write_text("{not json", encoding="utf-8") + self.assertEqual(self.run_queue("config", "set", "budget_percent.cpu", "90").returncode, 2) + self.assertEqual(self.config.read_text(encoding="utf-8"), "{not json") + + +if __name__ == "__main__": + unittest.main()