feat(queue): admit by a self-tuning load band from one limits file

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.
<council root>/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 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-27 19:02:06 +00:00
1 parent c4975d8246
commit a3e1fda7e8
17 files changed
+1708 -184

No files matched your search

+1 -1
View File
@@ -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}
+158
View File
@@ -0,0 +1,158 @@
"""Read and check the resource limits file of the agents council (requirement 083).
<root>/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 <root>/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
+35 -6
View File
@@ -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: <root>/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
+18 -17
View File
@@ -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 <id>
```
`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.
+48
View File
@@ -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
<head>`, and `drained for <head>` only when the head cannot fit even alone.
Keep the live guard
`mem_percent` above `band_high`, or it holds jobs first.
## Limits file
`<council root>/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.
+32
View File
@@ -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 <id>` 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 <key> <value>` 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.<kind>` and `ram_cap_percent.<kind>` (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 <argv>` and refuses every other argv. The
hub reads the config through a read-only mount and never writes it.
+12 -7
View File
@@ -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 `<repo>: <command
signature>`, 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
+91
View File
@@ -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 <root>/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}
+67 -18
View File
@@ -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 = []
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -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}
]
+185
View File
@@ -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()
+125 -35
View File
@@ -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"
+167
View File
@@ -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()
+105
View File
@@ -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()
+3 -1
View File
@@ -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)
+91
View File
@@ -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()