feat(hub): the hardware chart marks a blocked queue head and suspect-hung jobs

Each resources sample runs queue.py list --json once (the installed kvb-org-queue script, --queue in the unit, AGENTS_COUNCIL_ROOT set to the council) and keeps queue.head, {id, kind, waited_s, reason} of the first waiting row, and queue.hung, the ids of active rows whose reason says suspect hung; both are left out without one or while that run fails or prints no JSON list, and id, kind and reason are cut to 64 and 240 characters. Folded 15-minute and daily rows keep the last head and every hung id. The hardware chart draws a red band where the queue head waited blocked and a violet dashed band for suspect-hung jobs, each clickable for its job. MB becomes MEGABYTE.

The unit takes --queue /kvb-org-queue/scripts/queue.py; the install writes KVB_ORCHESTRATOR_SKILLS into the hub's .env (scripts/orchestrator.sh), which the offices unit already uses.

Applied cleanly onto motion (86a60c7); none of the 7 files changed on master since its base 2aea6d1.

Tests: test_hub_resources and test_resources_sample. Written, not run: the full suite runs once on master after all bundles (operator order).

Security: MEDUSA over the staged tree on master: 100, no findings over 5 files; kvb-orchestrator-resources.service (one added --queue argument) and style-resources.css (four style rules) are not covered and were read by hand.

🎯 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-22 19:34:32 +00:00
1 parent 86a60c7998
commit 9d313f227d
7 files changed
+370 -36

No files matched your search

+92 -12
View File
@@ -2,10 +2,14 @@
"""Args: """Args:
sample: append one row to <state>/samples.jsonl: {t, disks: [{mount, sample: append one row to <state>/samples.jsonl: {t, disks: [{mount,
used, total}], cpu, ram, swap, load, gpus: [{name, util, vram_used, used, total}], cpu, ram, swap, load, gpus: [{name, util, vram_used,
vram_total} | {name, asleep: true}], queue: {waiting, active}, vram_total} | {name, asleep: true}], queue: {waiting, active, head,
psi_some, psi_full, swap_out_mb_min}; t in epoch seconds, used, total hung}, psi_some, psi_full, swap_out_mb_min}; t in epoch seconds, used,
and vram in bytes, cpu, ram, swap and util in percent, load the total and vram in bytes, cpu, ram, swap and util in percent, load the
1-minute load average, a GPU named by its PCI address. cpu is the 1-minute load average, a GPU named by its PCI address. head is {id,
kind, waited_s, reason} of the first waiting row of one `queue.py
list --json` run per sample, hung the ids of its active rows whose
reason says suspect hung; each is left out without one, and both
while that run fails or prints no JSON list. cpu is the
busy share of the /proc/stat ticks since those the run before kept in busy share of the /proc/stat ticks since those the run before kept in
<state>/cpu.json as [t, idle, total], None on the first run and after <state>/cpu.json as [t, idle, total], None on the first run and after
a gap of more than 15 minutes. psi_some and psi_full are the avg10 of a gap of more than 15 minutes. psi_some and psi_full are the avg10 of
@@ -19,8 +23,9 @@
and vram None. In the first minute of a 15-minute bucket, rows older and vram None. In the first minute of a 15-minute bucket, rows older
than 7 days fold into 15-minute means and means older than 90 days than 7 days fold into 15-minute means and means older than 90 days
into one mean per day, kept forever, each row weighted by the seconds into one mean per day, kept forever, each row weighted by the seconds
it sampled; a folded row carries span, the seconds its rows sampled it sampled, the queue keeping the last head and every hung id; a
(60 per raw row), and width, the seconds of its bucket. folded row carries span, the seconds its rows sampled (60 per raw
row), and width, the seconds of its bucket.
tokens: add the input, output, cache-read and cache-write tokens of the tokens: add the input, output, cache-read and cache-write tokens of the
usage fields in the Claude Code transcripts under --transcripts since usage fields in the Claude Code transcripts under --transcripts since
each file's byte offset to <state>/tokens.jsonl as {t, agent, model, each file's byte offset to <state>/tokens.jsonl as {t, agent, model,
@@ -37,6 +42,8 @@
--state: the directory of these files, the unit passes --state: the directory of these files, the unit passes
~/.local/state/agents-council/resources. ~/.local/state/agents-council/resources.
--council: the council directory with queue.json and the claims. --council: the council directory with queue.json and the claims.
--queue (sample): the installed kvb-org-queue queue.py, run with
AGENTS_COUNCIL_ROOT set to --council.
--transcripts (tokens): Claude Code's projects directory. --transcripts (tokens): Claude Code's projects directory.
--proc, --sys (sample): where /proc and /sys are mounted. --proc, --sys (sample): where /proc and /sys are mounted.
@@ -61,6 +68,7 @@ import os
import shutil import shutil
import stat import stat
import subprocess import subprocess
import sys
import time import time
from collections.abc import Callable from collections.abc import Callable
from pathlib import Path from pathlib import Path
@@ -93,7 +101,11 @@ OFFSETS = "offsets.json"
TICKS = "cpu.json" TICKS = "cpu.json"
SWAPPED = "swap.json" SWAPPED = "swap.json"
PAGE_BYTES = os.sysconf("SC_PAGE_SIZE") PAGE_BYTES = os.sysconf("SC_PAGE_SIZE")
MB = 1_000_000 MEGABYTE = 1_000_000
QUEUE_ARGS = ("list", "--json")
ID_TEXT = 64
REASON_TEXT = 240
HUNG = "suspect hung ("
def read_text(path: Path) -> str: def read_text(path: Path) -> str:
@@ -258,6 +270,56 @@ def queue(council: Path) -> dict:
return {"waiting": statuses.count("waiting"), "active": statuses.count("active")} return {"waiting": statuses.count("waiting"), "active": statuses.count("active")}
def string_of(value: object) -> str:
return value if isinstance(value, str) else ""
def queue_rows(text: str | None) -> list[dict] | None:
"""Returns:
The objects of the JSON list `queue.py list --json` printed as text;
None when text holds no JSON list.
"""
try:
data = json.loads(text) if text else None
except (ValueError, RecursionError):
return None
return [row for row in data if isinstance(row, dict)] if isinstance(data, list) else None
def head_of(rows: list[dict]) -> dict | None:
"""Returns:
{id, kind, waited_s, reason} of the first waiting row, id and kind cut
to ID_TEXT characters, reason to REASON_TEXT; None without a waiting
row or when it lacks a string id or a number waited_s.
"""
first = next((row for row in rows if row.get("status") == "waiting"), None)
if first is None or not isinstance(first.get("id"), str) or not is_number(first.get("waited_s")):
return None
return {"id": first["id"][:ID_TEXT], "kind": string_of(first.get("kind"))[:ID_TEXT], "waited_s": first["waited_s"], "reason": string_of(first.get("reason"))[:REASON_TEXT]}
def hung_ids(rows: list[dict]) -> list[str]:
return [row["id"][:ID_TEXT] for row in rows if row.get("status") == "active" and isinstance(row.get("id"), str) and HUNG in string_of(row.get("reason"))]
def queue_view(council: Path, script: Path, run: Callable[[list[str]], str | None]) -> dict:
"""Returns:
{head, hung} of one `queue.py list --json` run of script through run
with AGENTS_COUNCIL_ROOT set to council, head as head_of() gives it,
hung as hung_ids(), each left out without one; {} when the run fails
or prints no JSON list.
"""
rows = queue_rows(run(["env", f"AGENTS_COUNCIL_ROOT={council}", sys.executable, "-I", "-B", str(script), *QUEUE_ARGS]))
if rows is None:
return {}
head, hung = head_of(rows), hung_ids(rows)
return {**({"head": head} if head else {}), **({"hung": hung} if hung else {})}
def queue_state(council: Path, script: Path, run: Callable[[list[str]], str | None]) -> dict:
return {**queue(council), **queue_view(council, script, run)}
def integers(value: object, size: int) -> bool: def integers(value: object, size: int) -> bool:
return isinstance(value, list) and len(value) == size and all(isinstance(item, int) and not isinstance(item, bool) for item in value) return isinstance(value, list) and len(value) == size and all(isinstance(item, int) and not isinstance(item, bool) for item in value)
@@ -306,10 +368,10 @@ def swap_out_since(proc: Path, state: Path, t: int) -> float | None:
replace(state / SWAPPED, json.dumps([t, pages])) replace(state / SWAPPED, json.dumps([t, pages]))
if not integers(stored, 2) or not t - BUCKET <= stored[0] < t or stored[1] > pages: if not integers(stored, 2) or not t - BUCKET <= stored[0] < t or stored[1] > pages:
return None return None
return round((pages - stored[1]) * PAGE_BYTES / MB * 60 / (t - stored[0]), 1) return round((pages - stored[1]) * PAGE_BYTES / MEGABYTE * 60 / (t - stored[0]), 1)
def sample(proc: Path, sys_root: Path, council: Path, run: Callable[[list[str]], str | None], state: Path) -> dict: def sample(proc: Path, sys_root: Path, queued: Callable[[], dict], run: Callable[[list[str]], str | None], state: Path) -> dict:
t = int(time.time()) t = int(time.time())
ram, swap = memory(parse_meminfo(read_text(proc / "meminfo"))) ram, swap = memory(parse_meminfo(read_text(proc / "meminfo")))
pressure = read_text(proc / "pressure" / "memory") pressure = read_text(proc / "pressure" / "memory")
@@ -321,7 +383,7 @@ def sample(proc: Path, sys_root: Path, council: Path, run: Callable[[list[str]],
"swap": swap, "swap": swap,
"load": parse_loadavg(read_text(proc / "loadavg")), "load": parse_loadavg(read_text(proc / "loadavg")),
"gpus": gpus(sys_root, run), "gpus": gpus(sys_root, run),
"queue": queue(council), "queue": queued(),
"psi_some": psi_avg10(pressure, "some"), "psi_some": psi_avg10(pressure, "some"),
"psi_full": psi_avg10(pressure, "full"), "psi_full": psi_avg10(pressure, "full"),
"swap_out_mb_min": swap_out_since(proc, state, t), "swap_out_mb_min": swap_out_since(proc, state, t),
@@ -381,9 +443,26 @@ def disk_means(rows: list[dict]) -> list[dict]:
return [{"mount": mount, "used": whole(means(disks, "used")), "total": whole(means(disks, "total"))} for mount, disks in grouped(listed(rows, "disks"), "mount").items()] return [{"mount": mount, "used": whole(means(disks, "used")), "total": whole(means(disks, "total"))} for mount, disks in grouped(listed(rows, "disks"), "mount").items()]
def queue_marks(queues: list[dict]) -> dict:
"""Returns:
{head, hung} of a bucket's queue entries: the head of the last entry
that carries one and the hung ids of every entry, each once in the
order first seen; each left out without one.
"""
heads = [entry["head"] for entry in queues if isinstance(entry.get("head"), dict)]
lists = [entry["hung"] for entry in queues if isinstance(entry.get("hung"), list)]
hung = list(dict.fromkeys(item for found in lists for item in found if isinstance(item, str)))
return {**({"head": heads[-1]} if heads else {}), **({"hung": hung} if hung else {})}
def queue_mean(rows: list[dict]) -> dict: def queue_mean(rows: list[dict]) -> dict:
"""Returns:
The weighted means of waiting and active with queue_marks() of the
bucket.
"""
queues = [(weight(row), row["queue"]) for row in rows if isinstance(row.get("queue"), dict)] queues = [(weight(row), row["queue"]) for row in rows if isinstance(row.get("queue"), dict)]
return {key: average(means(queues, key), 2) for key in ("waiting", "active")} found = {key: average(means(queues, key), 2) for key in ("waiting", "active")}
return {**found, **queue_marks([entry for _, entry in queues])}
def mean_row(start: int, width: int, rows: list[dict]) -> dict: def mean_row(start: int, width: int, rows: list[dict]) -> dict:
@@ -732,11 +811,12 @@ def main() -> int:
sub.add_argument("--council", type=Path, required=True) sub.add_argument("--council", type=Path, required=True)
sampling.add_argument("--proc", type=Path, required=True) sampling.add_argument("--proc", type=Path, required=True)
sampling.add_argument("--sys", type=Path, required=True) sampling.add_argument("--sys", type=Path, required=True)
sampling.add_argument("--queue", type=Path, required=True)
counting.add_argument("--transcripts", type=Path, required=True) counting.add_argument("--transcripts", type=Path, required=True)
args = parser.parse_args() args = parser.parse_args()
args.state.mkdir(parents=True, exist_ok=True) args.state.mkdir(parents=True, exist_ok=True)
if args.command == "sample": if args.command == "sample":
row = sample(args.proc, args.sys, args.council, command, args.state) row = sample(args.proc, args.sys, functools.partial(queue_state, args.council, args.queue, command), command, args.state)
record(args.state, row, row["t"]) record(args.state, row, row["t"])
else: else:
count_tokens(args.transcripts, args.council, args.state, time.time(), BUDGET) count_tokens(args.transcripts, args.council, args.state, time.time(), BUDGET)
@@ -5,7 +5,7 @@ Description=Agent Orchestrator resources: disks, CPU, RAM, swap, load, GPU, the
Type=oneshot Type=oneshot
Environment=PATH=/usr/bin:/bin Environment=PATH=/usr/bin:/bin
EnvironmentFile=%h/.local/share/kvb-orchestrator/.env EnvironmentFile=%h/.local/share/kvb-orchestrator/.env
ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/resources.py sample --state ${KVB_ORCHESTRATOR_KEPT}/resources --council ${KVB_ORCHESTRATOR_COUNCIL} --proc /proc --sys /sys ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/resources.py sample --state ${KVB_ORCHESTRATOR_KEPT}/resources --council ${KVB_ORCHESTRATOR_COUNCIL} --proc /proc --sys /sys --queue ${KVB_ORCHESTRATOR_SKILLS}/kvb-org-queue/scripts/queue.py
ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/resources.py tokens --state ${KVB_ORCHESTRATOR_KEPT}/resources --council ${KVB_ORCHESTRATOR_COUNCIL} --transcripts ${KVB_ORCHESTRATOR_PROJECTS} ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/resources.py tokens --state ${KVB_ORCHESTRATOR_KEPT}/resources --council ${KVB_ORCHESTRATOR_COUNCIL} --transcripts ${KVB_ORCHESTRATOR_PROJECTS}
Nice=10 Nice=10
IOSchedulingClass=idle IOSchedulingClass=idle
+37 -7
View File
@@ -1,10 +1,12 @@
const RESOURCE = {left: 46, right: 10, wide: 50, top: 6, bottom: 6, axis: 18, poll: 5000, stale: 60, tones: 6, glyph: 6.5, shown: 100}; const RESOURCE = {left: 46, right: 10, wide: 50, top: 6, bottom: 6, axis: 18, poll: 5000, stale: 60, tones: 6, glyph: 6.5, shown: 100, lane: 13};
const RESOURCE_PANELS = [["hardware", "bi-cpu", "Hardware: disks, CPU, RAM, swap, GPU and VRAM"], ["tokens", "bi-coin", "Tokens per agent"], ["combined", "bi-layers", "Hardware, tokens and burnup"]]; const RESOURCE_PANELS = [["hardware", "bi-cpu", "Hardware: disks, CPU, RAM, swap, GPU and VRAM"], ["tokens", "bi-coin", "Tokens per agent"], ["combined", "bi-layers", "Hardware, tokens and burnup"]];
const RESOURCE_ZONES = {idle: "Idle: below 30 %", saturated: "Saturated: above 90 %"}; const RESOURCE_ZONES = {idle: "Idle: below 30 %", saturated: "Saturated: above 90 %"};
const RESOURCE_MARKS = { const RESOURCE_MARKS = {
wait: ["#bi-hourglass-split", (mark) => `${mark.peak} jobs waited while CPU and RAM stayed under 50 %`], wait: ["#bi-hourglass-split", (mark) => `Idle waiting: ${mark.peak} jobs waited while CPU and RAM stayed under 50 %`, 0],
asleep: ["#bi-moon", (mark) => `${mark.name} asleep`], blocked: ["#bi-sign-stop", (mark) => revealed(`${mark.head} waited ${Math.round(mark.peak / 60)} min: ${mark.reason}`), 1],
unknown: ["#bi-question-circle", (mark) => `${mark.name} unknown: no reading`], hung: ["#bi-pause-circle", (mark) => revealed(`suspect hung: ${mark.hung.join(", ")}`), 2],
asleep: ["#bi-moon", (mark) => `${mark.name} asleep`, 0],
unknown: ["#bi-question-circle", (mark) => `${mark.name} unknown: no reading`, 0],
}; };
const RESOURCE_BURN = {done: "Done", scope: "Scope"}; const RESOURCE_BURN = {done: "Done", scope: "Scope"};
const resourceView = {data: null, dom: null, busy: false, key: "", at: 0, timer: 0, series: {}}; const resourceView = {data: null, dom: null, busy: false, key: "", at: 0, timer: 0, series: {}};
@@ -130,12 +132,38 @@
if (right <= left) { if (right <= left) {
continue; continue;
} }
const [href, words] = RESOURCE_MARKS[mark.kind]; const [href, words, lane] = RESOURCE_MARKS[mark.kind];
frame.svg.append(s("rect", {class: `res-mark ${mark.kind}`, "data-from": mark.from, "data-to": mark.to, "data-peak": mark.peak, x: fixed(left), width: fixed(Math.max(right - left, 2)), y: frame.top, height: fixed(frame.bottom - frame.top)}, s("title", {}, words(mark)))); const press = (event) => {
frame.svg.append(s("use", {class: `res-icon ${mark.kind}`, href, x: fixed(left + 2), y: frame.top + 2, width: 11, height: 11})); if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
resourceQueueSheet(mark);
}
};
const open = mark.steps ? {role: "button", tabindex: 0, "aria-label": words(mark), on: {click: () => resourceQueueSheet(mark), keydown: press}} : {};
frame.svg.append(s("rect", {class: `res-mark ${mark.kind}`, "data-from": mark.from, "data-to": mark.to, "data-peak": mark.peak, x: fixed(left), width: fixed(Math.max(right - left, 2)), y: frame.top, height: fixed(frame.bottom - frame.top), ...open}, s("title", {}, words(mark))));
frame.svg.append(s("use", {class: `res-icon ${mark.kind}`, href, x: fixed(left + 2), y: frame.top + 2 + lane * RESOURCE.lane, width: 11, height: 11}));
} }
} }
/**
* @param mark - a blocked or hung mark: {kind, from, to, peak, steps, hung} and for blocked head.
*/
function resourceQueueSheet(mark) {
const time = (t) => absolute.format(stampOf(t));
const title = mark.kind === "blocked" ? `${mark.head} waited ${Math.round(mark.peak / 60)} min` : `Suspect hung: ${mark.hung.join(", ")}`;
const steps = mark.steps.map((step) => h("li", {"data-head": step.id, "data-from": step.from, "data-to": step.to},
h("div", {class: "row"}, h("code", {}, revealed(step.id)), h("span", {class: "muted"}, `${time(step.from)} to ${time(step.to)}`)),
h("p", {class: "text"}, revealed(step.reason === "" ? "no reason given" : step.reason))));
const hung = mark.hung.map((id) => h("li", {"data-hung": id}, h("code", {}, revealed(id))));
openSheet(title, [
h("p", {class: "muted"}, `${time(mark.from)} to ${time(mark.to)}`),
h("h3", {}, "Queue head", counter(steps.length)),
steps.length ? h("ul", {class: "mini"}, steps) : h("p", {class: "muted"}, "No job waited at the head of the queue."),
h("h3", {}, "Suspect hung", counter(hung.length)),
hung.length ? h("ul", {class: "mini"}, hung) : h("p", {class: "muted"}, "No active job was suspect hung."),
], false);
}
function resourceLines(frame, y, list) { function resourceLines(frame, y, list) {
for (const line of list) { for (const line of list) {
for (const part of Resources.segments(line.points)) { for (const part of Resources.segments(line.points)) {
@@ -311,6 +339,8 @@
burn: view.combined ? burnSeries(span) : [], burn: view.combined ? burnSeries(span) : [],
marks: [ marks: [
...Resources.waits(data.samples).map((mark) => ({...mark, kind: "wait"})), ...Resources.waits(data.samples).map((mark) => ({...mark, kind: "wait"})),
...Resources.blocked(data.samples).map((mark) => ({...mark, kind: "blocked"})),
...Resources.hung(data.samples).map((mark) => ({...mark, kind: "hung"})),
...["asleep", "unknown"].flatMap((kind) => Resources[kind](data.samples).flatMap((gpu) => gpu.spans.map((mark) => ({...mark, kind, name: gpu.name})))), ...["asleep", "unknown"].flatMap((kind) => Resources[kind](data.samples).flatMap((gpu) => gpu.spans.map((mark) => ({...mark, kind, name: gpu.name})))),
], ],
}; };
+69 -1
View File
@@ -3,6 +3,7 @@ const Resources = (() => {
const IDLE = 30; const IDLE = 30;
const SATURATED = 90; const SATURATED = 90;
const CALM = 50; const CALM = 50;
const BLOCKED = 600;
const GAP = 1800; const GAP = 1800;
const STEP = 60; const STEP = 60;
const HOUR = 3600; const HOUR = 3600;
@@ -98,6 +99,73 @@ const Resources = (() => {
return spans(samples, (row) => waiting(row) > 0 && finite(row.cpu) && finite(row.ram) && row.cpu < CALM && row.ram < CALM, waiting); return spans(samples, (row) => waiting(row) > 0 && finite(row.cpu) && finite(row.ram) && row.cpu < CALM && row.ram < CALM, waiting);
} }
function headOf(row) {
const head = row.queue && row.queue.head;
if (!head || typeof head !== "object" || typeof head.id !== "string" || !finite(head.waited_s)) {
return null;
}
return {id: head.id, waited: head.waited_s, reason: typeof head.reason === "string" ? head.reason : ""};
}
const hungOf = (row) => (row.queue && Array.isArray(row.queue.hung) ? row.queue.hung.filter((id) => typeof id === "string") : []);
function headSteps(rows) {
const found = [];
for (const row of rows) {
const head = headOf(row);
if (!head) {
continue;
}
const last = found[found.length - 1];
if (last && last.id === head.id && last.reason === head.reason) {
last.to = row.t;
} else {
found.push({id: head.id, reason: head.reason, from: row.t, to: row.t});
}
}
return found;
}
/**
* @param samples - sampler rows.
* @param test - whether a row belongs to a span.
* @param value - the number of a row its span's peak is the largest of.
* @param more - the extra keys of a span from the rows in it.
* @returns spans() of test and value, each with more() of its rows, steps (per run of one head with one reason
* its id, reason and first and last row time) and hung, every id suspect hung in it, once.
*/
function queueSpans(samples, test, value, more) {
const rows = timed(samples).filter(test);
return spans(samples, test, value).map((span) => {
const inside = rows.filter((row) => row.t === span.from || (row.t > span.from && row.t < span.to));
return {...span, ...more(inside), steps: headSteps(inside), hung: [...new Set(inside.flatMap(hungOf))]};
});
}
/**
* @param samples - sampler rows.
* @returns queueSpans() where the queue head had waited at least BLOCKED seconds, peak the longest wait in
* seconds, head and reason those of the span's last row.
*/
function blocked(samples) {
const waited = (row) => {
const head = headOf(row);
return head === null ? 0 : head.waited;
};
return queueSpans(samples, (row) => waited(row) >= BLOCKED, waited, (inside) => {
const last = headOf(inside[inside.length - 1]);
return {head: last.id, reason: last.reason};
});
}
/**
* @param samples - sampler rows.
* @returns queueSpans() where the queue listed an active job as suspect hung, peak the most such jobs at once.
*/
function hung(samples) {
return queueSpans(samples, (row) => hungOf(row).length > 0, (row) => hungOf(row).length, () => ({}));
}
function gpuSpans(samples, test) { function gpuSpans(samples, test) {
const names = [...new Set(timed(samples).flatMap((row) => listOf(row, "gpus").filter(test).map((gpu) => String(gpu.name))))]; const names = [...new Set(timed(samples).flatMap((row) => listOf(row, "gpus").filter(test).map((gpu) => String(gpu.name))))];
return names.map((name) => ({name, spans: spans(samples, (row) => listOf(row, "gpus").some((gpu) => String(gpu.name) === name && test(gpu)), () => 1)})); return names.map((name) => ({name, spans: spans(samples, (row) => listOf(row, "gpus").some((gpu) => String(gpu.name) === name && test(gpu)), () => 1)}));
@@ -190,7 +258,7 @@ const Resources = (() => {
return unit ? `${(value / unit[0]).toFixed(1)}${unit[1]}` : String(Math.round(value)); return unit ? `${(value / unit[0]).toFixed(1)}${unit[1]}` : String(Math.round(value));
} }
return {IDLE, SATURATED, CALM, GAP, HOUR, COUNTS, ZONES, lines, hardware, segments, spans, waits, asleep, unknown, stack, accumulate, burnup, compact}; return {IDLE, SATURATED, CALM, BLOCKED, GAP, HOUR, COUNTS, ZONES, lines, hardware, segments, spans, waits, blocked, hung, asleep, unknown, stack, accumulate, burnup, compact};
})(); })();
if (typeof module === "object" && module.exports) { if (typeof module === "object" && module.exports) {
module.exports = Resources; module.exports = Resources;
@@ -16,9 +16,13 @@ svg .res-sum { fill: none; stroke: var(--c); stroke-width: 2; stroke-linejoin: r
svg .res-burn { fill: none; stroke: var(--c); stroke-width: 2.4; stroke-linejoin: round; } svg .res-burn { fill: none; stroke: var(--c); stroke-width: 2.4; stroke-linejoin: round; }
svg .res-burn.k-scope { stroke-dasharray: 7 4; } svg .res-burn.k-scope { stroke-dasharray: 7 4; }
svg .res-mark.wait { fill: var(--warn-soft); stroke: var(--warn); stroke-dasharray: 3 3; } svg .res-mark.wait { fill: var(--warn-soft); stroke: var(--warn); stroke-dasharray: 3 3; }
svg .res-mark.blocked { fill: var(--bad-soft); stroke: var(--bad); cursor: pointer; }
svg .res-mark.hung { fill: var(--violet-soft); stroke: var(--violet); stroke-dasharray: 1 3; cursor: pointer; }
svg .res-mark.asleep { fill: var(--neutral-soft); } svg .res-mark.asleep { fill: var(--neutral-soft); }
svg .res-mark.unknown { fill: var(--neutral-soft); stroke: var(--muted); stroke-dasharray: 2 3; } svg .res-mark.unknown { fill: var(--neutral-soft); stroke: var(--muted); stroke-dasharray: 2 3; }
svg .res-icon.wait { fill: var(--warn); } svg .res-icon.wait { fill: var(--warn); }
svg .res-icon.blocked { fill: var(--bad); pointer-events: none; }
svg .res-icon.hung { fill: var(--violet); pointer-events: none; }
svg .res-icon.asleep, svg .res-icon.unknown { fill: var(--muted); } svg .res-icon.asleep, svg .res-icon.unknown { fill: var(--muted); }
svg .res-bar { fill: var(--c); } svg .res-bar { fill: var(--c); }
svg .res-bar.faint { opacity: 0.35; } svg .res-bar.faint { opacity: 0.35; }
+81 -8
View File
@@ -17,17 +17,18 @@ FIXTURE = """
const asleep = {name: "0000:01:00.0", asleep: true}; const asleep = {name: "0000:01:00.0", asleep: true};
const awake = (util, used) => ({name: "0000:01:00.0", util, vram_used: used, vram_total: 1000}); const awake = (util, used) => ({name: "0000:01:00.0", util, vram_used: used, vram_total: 1000});
const unread = {name: "0000:01:00.0", util: null, vram_used: null, vram_total: null}; const unread = {name: "0000:01:00.0", util: null, vram_used: null, vram_total: null};
const row = (t, cpu, ram, waiting, gpu, disks) => ({t, cpu, ram, swap: 0, load: 1, disks, gpus: [gpu], queue: {waiting, active: 1}}); const row = (t, cpu, ram, waiting, gpu, disks, queued) => ({t, cpu, ram, swap: 0, load: 1, disks, gpus: [gpu], queue: {waiting, active: 1, ...queued}});
const head = (id, waited_s, reason) => ({id, kind: "job", waited_s, reason});
const root = [{mount: "/", used: 250, total: 1000}]; const root = [{mount: "/", used: 250, total: 1000}];
const samples = [ const samples = [
row(T, 20, 30, 0, asleep, root), row(T, 20, 30, 0, asleep, root),
row(T + 60, 40, 45, 2, asleep, root), row(T + 60, 40, 45, 2, asleep, root),
row(T + 120, 45, 40, 3, awake(80, 500), [...root, {mount: "/mnt", used: 1, total: 4}]), row(T + 120, 45, 40, 3, awake(80, 500), [...root, {mount: "/mnt", used: 1, total: 4}]),
row(T + 180, 70, 40, 3, awake(90, 600), root), row(T + 180, 70, 40, 3, awake(90, 600), root, {head: head("quality-high-1002", 599, "@BESIDE@")}),
row(T + 240, 30, 30, 1, awake(10, 100), root), row(T + 240, 30, 30, 1, awake(10, 100), root, {head: head("quality-high-1002", 600, "@ESCALATED@")}),
row(T + 300, 35, 30, 0, unread, root), row(T + 300, 35, 30, 0, unread, root, {head: head("quality-high-1002", 660, "@RAM@"), hung: ["test-1001"]}),
row(T + 5000, 10, 10, 1, asleep, root), row(T + 5000, 10, 10, 1, asleep, root, {hung: ["test-1001"]}),
row(T + 5060, 10, 10, 0, asleep, root), row(T + 5060, 10, 10, 0, asleep, root, {head: head("deploy-1003", 1200, "@BEHIND@")}),
]; ];
const tokens = [ const tokens = [
{t: T, agent: "Skills", model: "opus", input: 10, output: 20, cache_read: 300, cache_write: 40}, {t: T, agent: "Skills", model: "opus", input: 10, output: 20, cache_read: 300, cache_write: 40},
@@ -37,6 +38,12 @@ const tokens = [
{t: "x", agent: "Bad", model: "opus", input: 1, output: 0, cache_read: 0, cache_write: 0}, {t: "x", agent: "Bad", model: "opus", input: 1, output: 0, cache_read: 0, cache_write: 0},
]; ];
""" """
BESIDE = "quality-high runs only beside test-nostack, but test runs"
ESCALATED = f"escalated post: {BESIDE}"
RAM = "RAM 56 % used + 37 % still to come reach the limit 85 %"
BEHIND = "waits in line behind test-1001"
FIXTURE = FIXTURE.replace("@BESIDE@", BESIDE).replace("@ESCALATED@", ESCALATED).replace("@RAM@", RAM).replace("@BEHIND@", BEHIND)
QH = "quality-high-1002"
PROBE = """ PROBE = """
const R = require(process.argv[1]); const R = require(process.argv[1]);
const T = Number(process.argv[2]); const T = Number(process.argv[2]);
@@ -50,6 +57,11 @@ console.log(JSON.stringify({
gpu: pick(lines.gpu), gpu: pick(lines.gpu),
segments: R.segments([[T, 1], [T + 60, null], [T + 120, 3], [T + 180, 4], [T + 4000, 5]]), segments: R.segments([[T, 1], [T + 60, null], [T + 120, 3], [T + 180, 4], [T + 4000, 5]]),
waits: R.waits(samples), waits: R.waits(samples),
blocked: R.blocked(samples),
hung: R.hung(samples),
threshold: R.BLOCKED,
under: R.blocked([...samples.slice(0, 4), row(T + 240, 1, 1, 1, asleep, root, {head: {id: 5, waited_s: 9000}}), row(T + 300, 1, 1, 1, asleep, root, {head: {id: "x", waited_s: "900"}, hung: "test-1"})]),
quiet: R.hung(samples.slice(0, 5)),
asleep: R.asleep(samples), asleep: R.asleep(samples),
unknown: R.unknown(samples), unknown: R.unknown(samples),
stack: R.stack(tokens), stack: R.stack(tokens),
@@ -106,6 +118,7 @@ const icon = (name) => make("svg", {class: "bi", "data-icon": name}, []);
const view = {resources: {hidden: [], tokens: "interval", combined: false, combinedHidden: []}, burn: {overlays: []}, home: {pins: []}}; const view = {resources: {hidden: [], tokens: "interval", combined: false, combinedHidden: []}, burn: {overlays: []}, home: {pins: []}};
const served = JSON.parse(JSON.stringify(view)); const served = JSON.parse(JSON.stringify(view));
const fetched = []; const fetched = [];
const sheets = [];
const tasks = [ const tasks = [
{task: "a", kind: "task", status: "done", start: T - 300, end: T + 600, points: 0}, {task: "a", kind: "task", status: "done", start: T - 300, end: T + 600, points: 0},
{task: "b", kind: "task", status: "running", start: T + 1000, end: null, points: 0}, {task: "b", kind: "task", status: "running", start: T + 1000, end: null, points: 0},
@@ -118,6 +131,7 @@ const context = {
named: (label, hint) => ({title: hint || label, "aria-label": label}), named: (label, hint) => ({title: hint || label, "aria-label": label}),
iconBtn: (name, label, cls, run, hint) => make("button", {title: hint, "aria-label": label}, [icon(name)]), iconBtn: (name, label, cls, run, hint) => make("button", {title: hint, "aria-label": label}, [icon(name)]),
fixed: (value) => value.toFixed(1), dash: (value) => (value === null ? "–" : value), absolute: {format: () => "d"}, clock: {format: () => "c"}, stampOf: (t) => new Date(t * 1000), fixed: (value) => value.toFixed(1), dash: (value) => (value === null ? "–" : value), absolute: {format: () => "d"}, clock: {format: () => "c"}, stampOf: (t) => new Date(t * 1000),
revealed: (text) => String(text), counter: (value) => make("span", {class: "count"}, [String(value)]), openSheet: (title, body, wide) => sheets.push({title, body, wide}),
window: {setTimeout: (run) => run(), setInterval: () => 1, addEventListener: () => null}, window: {setTimeout: (run) => run(), setInterval: () => 1, addEventListener: () => null},
document: { document: {
hidden: false, activeElement: null, createElement: (tag) => make(tag, {}, []), getElementById: (name) => (name === "view" ? {textContent: JSON.stringify(view)} : null), hidden: false, activeElement: null, createElement: (tag) => make(tag, {}, []), getElementById: (name) => (name === "view" ? {textContent: JSON.stringify(view)} : null),
@@ -164,9 +178,14 @@ const read = () => {
lines: [...new Set(all.filter((node) => has(node, "res-line")).map((node) => `${node.attrs["data-series"]}|${node.attrs["data-kind"]}`))], lines: [...new Set(all.filter((node) => has(node, "res-line")).map((node) => `${node.attrs["data-series"]}|${node.attrs["data-kind"]}`))],
ids: [...new Set(all.filter((node) => has(node, "res-line")).map((node) => node.attrs["data-id"]))], ids: [...new Set(all.filter((node) => has(node, "res-line")).map((node) => node.attrs["data-id"]))],
waits: marks("wait"), waits: marks("wait"),
blocked: marks("blocked"),
hung: marks("hung"),
asleep: marks("asleep"), asleep: marks("asleep"),
unknown: marks("unknown"), unknown: marks("unknown"),
words: all.filter((node) => has(node, "res-mark") && has(node, "unknown")).map((node) => node.children[0].children.join("")), words: all.filter((node) => has(node, "res-mark") && has(node, "unknown")).map((node) => node.children[0].children.join("")),
queueWords: all.filter((node) => has(node, "res-mark") && ["wait", "blocked", "hung"].some((kind) => has(node, kind))).map((node) => node.children[0].children.join("")),
clickable: all.filter((node) => has(node, "res-mark") && node.listeners.click).map((node) => node.attrs.class),
lanes: [...new Set(all.filter((node) => node.tag === "use" && has(node, "res-icon")).map((node) => [node.attrs.class, node.attrs.href, Number(node.attrs.y)].join("|")))],
bars: all.filter((node) => has(node, "res-bar")).map((node) => [node.attrs["data-agent"], Number(node.attrs["data-t"]), has(node, "faint")]), bars: all.filter((node) => has(node, "res-bar")).map((node) => [node.attrs["data-agent"], Number(node.attrs["data-t"]), has(node, "faint")]),
sums: all.filter((node) => has(node, "res-sum")).map((node) => [node.attrs["data-agent"], JSON.parse(node.attrs["data-points"])]), sums: all.filter((node) => has(node, "res-sum")).map((node) => [node.attrs["data-agent"], JSON.parse(node.attrs["data-points"])]),
burn: all.filter((node) => node.tag === "path" && has(node, "res-burn")).map((node) => [node.attrs["data-series"], Number(node.attrs["data-last"]), Number(node.attrs["data-top"])]), burn: all.filter((node) => node.tag === "path" && has(node, "res-burn")).map((node) => [node.attrs["data-series"], Number(node.attrs["data-last"]), Number(node.attrs["data-top"])]),
@@ -177,9 +196,23 @@ const read = () => {
}; };
}; };
const press = (selector) => walk(context.screen, []).find(selector).listeners.click(); const press = (selector) => walk(context.screen, []).find(selector).listeners.click();
const textOf = (node) => node.children.map((child) => (typeof child === "object" ? textOf(child) : String(child))).join("");
const sheetOf = ({title, body, wide}) => {
const nodes = body.flatMap((node) => walk(node, []));
return {
title, wide,
heads: nodes.filter((node) => node.attrs["data-head"]).map((node) => [node.attrs["data-head"], Number(node.attrs["data-from"]), Number(node.attrs["data-to"]), textOf(node.children[1])]),
hung: nodes.filter((node) => node.attrs["data-hung"]).map((node) => node.attrs["data-hung"]),
counts: nodes.filter((node) => has(node, "count")).map(textOf),
};
};
(async () => { (async () => {
await settle(); await settle();
const normal = read(); const normal = read();
press((node) => has(node, "res-mark") && has(node, "blocked"));
press((node) => has(node, "res-mark") && has(node, "hung"));
press((node) => has(node, "res-mark") && has(node, "hung") && node.attrs["data-from"] === String(T + 5000));
normal.sheets = sheets.map(sheetOf);
press((node) => node.attrs["data-chip"] === "host:CPU"); press((node) => node.attrs["data-chip"] === "host:CPU");
press((node) => node.attrs["data-chip"] === "agent:Stage"); press((node) => node.attrs["data-chip"] === "agent:Stage");
const hidden = read(); const hidden = read();
@@ -222,8 +255,29 @@ class TestResourcesModule(unittest.TestCase):
def test_a_marker_spans_rows_where_jobs_waited_while_cpu_and_ram_stayed_under_half(self): def test_a_marker_spans_rows_where_jobs_waited_while_cpu_and_ram_stayed_under_half(self):
self.assertEqual(self.data["waits"], [{"from": T + 60, "to": T + 180, "peak": 3}, {"from": T + 240, "to": T + 300, "peak": 1}, {"from": T + 5000, "to": T + 5060, "peak": 1}]) self.assertEqual(self.data["waits"], [{"from": T + 60, "to": T + 180, "peak": 3}, {"from": T + 240, "to": T + 300, "peak": 1}, {"from": T + 5000, "to": T + 5060, "peak": 1}])
def test_a_blocked_span_needs_a_head_that_waited_ten_minutes_and_keeps_its_last_reason_and_steps(self):
self.assertEqual(self.data["threshold"], 600)
self.assertEqual(self.data["blocked"], [
{
"from": T + 240, "to": T + 360, "peak": 660, "head": QH, "reason": RAM,
"steps": [{"id": QH, "reason": ESCALATED, "from": T + 240, "to": T + 240}, {"id": QH, "reason": RAM, "from": T + 300, "to": T + 300}],
"hung": ["test-1001"],
},
{"from": T + 5060, "to": T + 5120, "peak": 1200, "head": "deploy-1003", "reason": BEHIND, "steps": [{"id": "deploy-1003", "reason": BEHIND, "from": T + 5060, "to": T + 5060}], "hung": []},
])
def test_a_head_under_ten_minutes_or_without_an_id_or_a_numeric_wait_is_not_blocked(self):
self.assertEqual(self.data["under"], [])
def test_a_hung_span_marks_rows_listing_a_suspect_hung_job_independent_of_the_head(self):
self.assertEqual(self.data["hung"], [
{"from": T + 300, "to": T + 360, "peak": 1, "steps": [{"id": QH, "reason": RAM, "from": T + 300, "to": T + 300}], "hung": ["test-1001"]},
{"from": T + 5000, "to": T + 5060, "peak": 1, "steps": [], "hung": ["test-1001"]},
])
self.assertEqual(self.data["quiet"], [])
def test_an_asleep_gpu_gets_its_own_spans(self): def test_an_asleep_gpu_gets_its_own_spans(self):
self.assertEqual(self.data["asleep"], [{"name": "0000:01:00.0", "spans": [{"from": T, "to": T + 120, "peak": 1}, {"from": T + 5000, "to": T + 5120, "peak": 1}]}]) self.assertEqual(self.data["asleep"],[{"name": "0000:01:00.0", "spans": [{"from": T, "to": T + 120, "peak": 1}, {"from": T + 5000, "to": T + 5120, "peak": 1}]}])
def test_an_awake_gpu_without_a_reading_gets_unknown_spans_apart_from_asleep_ones(self): def test_an_awake_gpu_without_a_reading_gets_unknown_spans_apart_from_asleep_ones(self):
self.assertEqual(self.data["unknown"], [{"name": "0000:01:00.0", "spans": [{"from": T + 300, "to": T + 360, "peak": 1}]}]) self.assertEqual(self.data["unknown"], [{"name": "0000:01:00.0", "spans": [{"from": T + 300, "to": T + 360, "peak": 1}]}])
@@ -294,6 +348,25 @@ class TestResourcesPage(unittest.TestCase):
names = [("Hardware: disks, CPU, RAM, swap, GPU and VRAM", "bi-cpu"), ("Tokens per agent", "bi-coin"), ("Hardware, tokens and burnup", "bi-layers")] names = [("Hardware: disks, CPU, RAM, swap, GPU and VRAM", "bi-cpu"), ("Tokens per agent", "bi-coin"), ("Hardware, tokens and burnup", "bi-layers")]
self.assertEqual(found["titles"], [[name, name, icon] for name, icon in names]) self.assertEqual(found["titles"], [[name, name, icon] for name, icon in names])
def test_blocked_and_hung_marks_sit_in_lanes_of_their_own_and_name_head_wait_reason_and_ids(self):
found = self.found["normal"]
self.assertEqual((found["blocked"], found["hung"]), ([[T + 240, T + 360], [T + 5060, T + 5120]], [[T + 300, T + 360], [T + 5000, T + 5060]]))
idle = "jobs waited while CPU and RAM stayed under 50 %"
self.assertEqual(found["queueWords"], [
f"Idle waiting: 3 {idle}", f"Idle waiting: 1 {idle}", f"Idle waiting: 1 {idle}",
f"{QH} waited 11 min: {RAM}", f"deploy-1003 waited 20 min: {BEHIND}", "suspect hung: test-1001", "suspect hung: test-1001",
])
self.assertEqual(found["clickable"], ["res-mark blocked"] * 2 + ["res-mark hung"] * 2)
self.assertEqual(found["lanes"], [
"res-icon wait|#bi-hourglass-split|8", "res-icon blocked|#bi-sign-stop|21", "res-icon hung|#bi-pause-circle|34", "res-icon asleep|#bi-moon|8", "res-icon unknown|#bi-question-circle|8",
])
def test_a_click_on_a_blocked_or_hung_mark_opens_a_sheet_of_each_head_reason_with_its_first_and_last_time_and_the_hung_ids(self):
blocked, hung, alone = self.found["normal"]["sheets"]
self.assertEqual(blocked, {"title": f"{QH} waited 11 min", "wide": False, "heads": [[QH, T + 240, T + 240, ESCALATED], [QH, T + 300, T + 300, RAM]], "hung": ["test-1001"], "counts": ["2", "1"]})
self.assertEqual(hung, {"title": "Suspect hung: test-1001", "wide": False, "heads": [[QH, T + 300, T + 300, RAM]], "hung": ["test-1001"], "counts": ["1", "1"]})
self.assertEqual(alone, {"title": "Suspect hung: test-1001", "wide": False, "heads": [], "hung": ["test-1001"], "counts": ["0", "1"]})
def test_hiding_a_chip_removes_its_line_or_its_agent_and_stores_the_list(self): def test_hiding_a_chip_removes_its_line_or_its_agent_and_stores_the_list(self):
found = self.found["hidden"] found = self.found["hidden"]
self.assertEqual(found["lines"], [line for line in LINES if line != "CPU|host"]) self.assertEqual(found["lines"], [line for line in LINES if line != "CPU|host"])
@@ -392,7 +465,7 @@ class TestHubResources(HubCase):
self.assertIn(MODULE.read_text(encoding="utf-8").strip(), html) self.assertIn(MODULE.read_text(encoding="utf-8").strip(), html)
self.assertIn(PAGE.read_text(encoding="utf-8").strip(), html) self.assertIn(PAGE.read_text(encoding="utf-8").strip(), html)
self.assertIn(STYLE.read_text(encoding="utf-8").strip(), html) self.assertIn(STYLE.read_text(encoding="utf-8").strip(), html)
for name in ("speedometer2", "cpu", "coin", "layers", "graph-up-arrow", "hourglass-split", "moon", "question-circle"): for name in ("speedometer2", "cpu", "coin", "layers", "graph-up-arrow", "hourglass-split", "sign-stop", "pause-circle", "moon", "question-circle"):
with self.subTest(icon=name): with self.subTest(icon=name):
self.assertIn(f'<symbol id="bi-{name}"', html) self.assertIn(f'<symbol id="bi-{name}"', html)
done = subprocess.run(["node", "-e", "const N = require(process.argv[1]); console.log(JSON.stringify([N.TABS.at(-1), N.ICONS.resources, N.route('#resources')]));", str(NAV)], capture_output=True, text=True, timeout=60, check=True) done = subprocess.run(["node", "-e", "const N = require(process.argv[1]); console.log(JSON.stringify([N.TABS.at(-1), N.ICONS.resources, N.route('#resources')]));", str(NAV)], capture_output=True, text=True, timeout=60, check=True)
+86 -7
View File
@@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
import fcntl import fcntl
import functools
import json import json
import os import os
import subprocess import subprocess
@@ -54,6 +55,20 @@ with Path(os.environ["STUB_LOG"]).open("a", encoding="utf-8") as handle:
handle.write(json.dumps([Path(sys.argv[0]).name, *sys.argv[1:]]) + "\\n") handle.write(json.dumps([Path(sys.argv[0]).name, *sys.argv[1:]]) + "\\n")
sys.stdout.write(os.environ["STUB_" + Path(sys.argv[0]).name.replace("-", "_").upper()]) sys.stdout.write(os.environ["STUB_" + Path(sys.argv[0]).name.replace("-", "_").upper()])
""" """
QUEUE_STUB = """import json, os, sys
from pathlib import Path
with Path(os.environ["STUB_LOG"]).open("a", encoding="utf-8") as handle:
handle.write(json.dumps([Path(sys.argv[0]).name, *sys.argv[1:], os.environ["AGENTS_COUNCIL_ROOT"]]) + "\\n")
sys.stdout.write(os.environ["STUB_QUEUE"])
"""
REASON = "escalated post: quality-high runs only beside test-nostack, but test runs"
QUEUE_ROWS = [
{"position": None, "id": "test-1001", "status": "active", "kind": "test", "task": "t", "waited_s": 30, "eta_s": None, "reason": "suspect hung (95 min); granted beside deploy-1000", "trace": []},
{"position": None, "id": "deploy-1000", "status": "active", "kind": "deploy", "task": "t", "waited_s": 0, "eta_s": 600, "reason": "-", "trace": []},
{"position": 1, "id": "quality-high-1002", "status": "waiting", "kind": "quality-high", "task": "t", "waited_s": 2880, "eta_s": None, "reason": REASON, "trace": ["step"]},
{"position": 2, "id": "build-1004", "status": "waiting", "kind": "build", "task": "t", "waited_s": 60, "eta_s": None, "reason": "waits in line behind quality-high-1002", "trace": []},
]
HEAD = {"id": "quality-high-1002", "kind": "quality-high", "waited_s": 2880, "reason": REASON}
def device(root: Path, address: str, vendor: str, kind: str, status: str | None) -> None: def device(root: Path, address: str, vendor: str, kind: str, status: str | None) -> None:
@@ -136,6 +151,65 @@ class TestParsing(unittest.TestCase):
self.assertEqual(sampler.queue(council), {"waiting": 1, "active": 1}) self.assertEqual(sampler.queue(council), {"waiting": 1, "active": 1})
class TestQueueView(unittest.TestCase):
def setUp(self):
self.calls = []
def answer(self, output: str | None):
def run(argv: list[str]) -> str | None:
self.calls.append(argv)
return output
return run
def test_the_head_is_the_first_waiting_row_and_hung_the_active_rows_queue_py_suspects(self):
found = sampler.queue_view(Path("/council"), Path("/skills/kvb-org-queue/scripts/queue.py"), self.answer(json.dumps(QUEUE_ROWS, indent=1)))
self.assertEqual(found, {"head": HEAD, "hung": ["test-1001"]})
self.assertEqual(self.calls, [["env", "AGENTS_COUNCIL_ROOT=/council", sys.executable, "-I", "-B", "/skills/kvb-org-queue/scripts/queue.py", "list", "--json"]])
def test_a_stamped_reason_still_says_suspect_hung_and_long_texts_are_cut(self):
rows = [
{"id": "test-7", "status": "active", "reason": "queue code abc, the host runs def: suspect hung (12 min)"},
{"id": "test-8", "status": "active", "reason": "granted; not suspect hung yet"},
{"id": "x" * 100, "status": "waiting", "kind": "k" * 100, "waited_s": 700.5, "reason": "r" * 1000},
]
found = sampler.queue_view(Path("/council"), Path("/queue.py"), self.answer(json.dumps(rows)))
self.assertEqual(found, {"head": {"id": "x" * sampler.ID_TEXT, "kind": "k" * sampler.ID_TEXT, "waited_s": 700.5, "reason": "r" * sampler.REASON_TEXT}, "hung": ["test-7"]})
def test_a_head_without_an_id_or_a_wait_is_no_head_and_a_quiet_queue_adds_nothing(self):
for rows in ([{"status": "waiting", "waited_s": 900}, {"id": "next", "status": "waiting", "waited_s": 900}], [{"id": "w", "status": "waiting", "waited_s": True}], [QUEUE_ROWS[1]], []):
with self.subTest(rows=rows):
self.assertEqual(sampler.queue_view(Path("/council"), Path("/queue.py"), self.answer(json.dumps(rows))), {})
def test_a_failing_or_silent_queue_py_leaves_the_counts_alone(self):
for output in (None, "", "Traceback (most recent call last):", '{"entries": []}', "[1, 2"):
with self.subTest(output=output):
self.assertEqual(sampler.queue_view(Path("/council"), Path("/queue.py"), self.answer(output)), {})
with tempfile.TemporaryDirectory() as tmp:
council, state = Path(tmp), Path(tmp) / "state"
state.mkdir()
(council / "queue.json").write_text(json.dumps({"entries": [{"status": "waiting", "enqueued": NOW}]}), encoding="utf-8")
self.calls.clear()
silent = self.answer(None)
found = sampler.sample(council, council / "sys", functools.partial(sampler.queue_state, council, council / "missing.py", silent), silent, state)
self.assertEqual(found["queue"], {"waiting": 1, "active": 0})
self.assertEqual([argv[0] for argv in self.calls], ["df", "env"])
def test_the_bucket_mean_keeps_the_last_head_and_every_hung_id_once(self):
asleep = {"name": ASLEEP, "asleep": True}
first = {**HEAD, "waited_s": 600, "reason": "quality-high runs only beside test-nostack, but test runs"}
last = {**HEAD, "waited_s": 660, "reason": "RAM 56 % used + 37 % still to come reach the limit 85 %"}
rows = [
row(NOW + 60, 1.0, 1, 1, asleep) | {"queue": {"waiting": 1, "active": 1, "head": first, "hung": ["test-1001"]}},
row(NOW + 120, 1.0, 1, 1, asleep) | {"queue": {"waiting": 1, "active": 1, "head": last, "hung": ["deploy-1003", "test-1001"]}},
row(NOW + 180, 1.0, 1, 0, asleep),
]
self.assertEqual(sampler.mean_row(NOW, sampler.BUCKET, rows)["queue"], {"waiting": 0.67, "active": 1.0, "head": last, "hung": ["test-1001", "deploy-1003"]})
day = sampler.mean_row(NOW - NOW % DAY, DAY, [sampler.mean_row(NOW, sampler.BUCKET, rows), row(NOW + sampler.BUCKET, 1.0, 1, 0, asleep)])
self.assertEqual((day["queue"]["head"], day["queue"]["hung"]), (last, ["test-1001", "deploy-1003"]))
self.assertEqual(sampler.queue_mean(rows[2:]), {"waiting": 0.0, "active": 1.0})
class TestCpu(unittest.TestCase): class TestCpu(unittest.TestCase):
def test_cpu_is_the_busy_share_since_the_ticks_the_run_before_kept_and_the_sampler_never_sleeps(self): def test_cpu_is_the_busy_share_since_the_ticks_the_run_before_kept_and_the_sampler_never_sleeps(self):
with tempfile.TemporaryDirectory() as tmp: with tempfile.TemporaryDirectory() as tmp:
@@ -144,7 +218,7 @@ class TestCpu(unittest.TestCase):
state.mkdir() state.mkdir()
(proc / "stat").write_text(STAT_BEFORE, encoding="utf-8") (proc / "stat").write_text(STAT_BEFORE, encoding="utf-8")
with mock.patch.object(sampler.time, "sleep", side_effect=AssertionError("slept")), mock.patch.object(sampler.time, "time", return_value=NOW - 60): with mock.patch.object(sampler.time, "sleep", side_effect=AssertionError("slept")), mock.patch.object(sampler.time, "time", return_value=NOW - 60):
self.assertIsNone(sampler.sample(proc, Path(tmp) / "sys", Path(tmp), lambda argv: None, state)["cpu"]) self.assertIsNone(sampler.sample(proc, Path(tmp) / "sys", functools.partial(sampler.queue_state, Path(tmp), Path(tmp) / "queue.py", lambda _argv: None), lambda _argv: None, state)["cpu"])
(proc / "stat").write_text(STAT_AFTER, encoding="utf-8") (proc / "stat").write_text(STAT_AFTER, encoding="utf-8")
self.assertEqual(sampler.cpu_since(proc, state, NOW), 61.5) self.assertEqual(sampler.cpu_since(proc, state, NOW), 61.5)
(proc / "stat").write_text(STAT_LATER, encoding="utf-8") (proc / "stat").write_text(STAT_LATER, encoding="utf-8")
@@ -185,7 +259,7 @@ class TestPressure(unittest.TestCase):
def test_a_sample_row_adds_the_pressure_keys_and_keeps_every_other_key(self): def test_a_sample_row_adds_the_pressure_keys_and_keeps_every_other_key(self):
(self.proc / "pressure" / "memory").write_text("some avg10=3.00 avg60=0 avg300=0 total=1\n", encoding="utf-8") (self.proc / "pressure" / "memory").write_text("some avg10=3.00 avg60=0 avg300=0 total=1\n", encoding="utf-8")
found = sampler.sample(self.proc, self.proc / "sys", self.proc, lambda argv: None, self.state) found = sampler.sample(self.proc, self.proc / "sys", functools.partial(sampler.queue_state, self.proc, self.proc / "queue.py", lambda _argv: None), lambda _argv: None, self.state)
self.assertEqual(sorted(found), ["cpu", "disks", "gpus", "load", "psi_full", "psi_some", "queue", "ram", "swap", "swap_out_mb_min", "t"]) self.assertEqual(sorted(found), ["cpu", "disks", "gpus", "load", "psi_full", "psi_some", "queue", "ram", "swap", "swap_out_mb_min", "t"])
self.assertEqual((found["psi_some"], found["psi_full"], found["swap_out_mb_min"]), (3.0, None, None)) self.assertEqual((found["psi_some"], found["psi_full"], found["swap_out_mb_min"]), (3.0, None, None))
@@ -324,17 +398,20 @@ class TestSamplerInScratchHome(unittest.TestCase):
for tool in ("df", "nvidia-smi"): for tool in ("df", "nvidia-smi"):
(stubs / tool).write_text(STUB, encoding="utf-8") (stubs / tool).write_text(STUB, encoding="utf-8")
(stubs / tool).chmod(0o755) (stubs / tool).chmod(0o755)
self.queue = base / "skills" / "kvb-org-queue" / "scripts" / "queue.py"
self.queue.parent.mkdir(parents=True)
self.queue.write_text(QUEUE_STUB, encoding="utf-8")
self.sys = host_sys(base / "sys") self.sys = host_sys(base / "sys")
self.log = base / "calls.jsonl" self.log = base / "calls.jsonl"
(self.council / "queue.json").write_text(json.dumps({"entries": [{"status": status, "enqueued": NOW} for status in ("waiting", "active", "active")]}), encoding="utf-8") (self.council / "queue.json").write_text(json.dumps({"entries": [{"status": status, "enqueued": NOW} for status in ("waiting", "active", "active")]}), encoding="utf-8")
self.env = { self.env = {
**os.environ, "HOME": str(self.home), "PATH": f"{stubs}:/usr/bin:/bin", **os.environ, "HOME": str(self.home), "PATH": f"{stubs}:/usr/bin:/bin",
"STUB_LOG": str(self.log), "STUB_DF": DF, "STUB_NVIDIA_SMI": NVIDIA_SMI.splitlines()[0] + "\n", "STUB_LOG": str(self.log), "STUB_DF": DF, "STUB_NVIDIA_SMI": NVIDIA_SMI.splitlines()[0] + "\n", "STUB_QUEUE": json.dumps(QUEUE_ROWS, indent=1),
} }
self.resources = self.home / ".local" / "state" / "agents-council" / "resources" self.resources = self.home / ".local" / "state" / "agents-council" / "resources"
def sample(self) -> None: def sample(self) -> None:
argv = [sys.executable, str(SCRIPT), "sample", "--state", str(self.resources), "--council", str(self.council), "--proc", str(self.proc), "--sys", str(self.sys)] argv = [sys.executable, str(SCRIPT), "sample", "--state", str(self.resources), "--council", str(self.council), "--proc", str(self.proc), "--sys", str(self.sys), "--queue", str(self.queue)]
done = subprocess.run(argv, env=self.env, capture_output=True, text=True, timeout=60, check=False) done = subprocess.run(argv, env=self.env, capture_output=True, text=True, timeout=60, check=False)
self.assertEqual(done.returncode, 0, done.stderr) self.assertEqual(done.returncode, 0, done.stderr)
@@ -350,12 +427,13 @@ class TestSamplerInScratchHome(unittest.TestCase):
self.assertEqual(sorted(found), ["cpu", "disks", "gpus", "load", "psi_full", "psi_some", "queue", "ram", "swap", "swap_out_mb_min", "t"]) self.assertEqual(sorted(found), ["cpu", "disks", "gpus", "load", "psi_full", "psi_some", "queue", "ram", "swap", "swap_out_mb_min", "t"])
self.assertEqual(found["disks"], DISKS) self.assertEqual(found["disks"], DISKS)
self.assertEqual(found["gpus"], [{"name": AWAKE, "util": 37.0, "vram_used": 2048 * MIB, "vram_total": 8188 * MIB}, {"name": ASLEEP, "asleep": True}]) self.assertEqual(found["gpus"], [{"name": AWAKE, "util": 37.0, "vram_used": 2048 * MIB, "vram_total": 8188 * MIB}, {"name": ASLEEP, "asleep": True}])
self.assertEqual(found["queue"], {"waiting": 1, "active": 2}) self.assertEqual(found["queue"], {"waiting": 1, "active": 2, "head": HEAD, "hung": ["test-1001"]})
self.assertEqual((found["ram"], found["swap"], found["load"]), (25.0, 25.0, 1.25)) self.assertEqual((found["ram"], found["swap"], found["load"]), (25.0, 25.0, 1.25))
self.assertEqual([found["cpu"] for found in rows], [None, 61.5]) self.assertEqual([found["cpu"] for found in rows], [None, 61.5])
self.assertLessEqual(rows[0]["t"], rows[1]["t"]) self.assertLessEqual(rows[0]["t"], rows[1]["t"])
calls = [json.loads(line) for line in self.log.read_text(encoding="utf-8").splitlines()] calls = [json.loads(line) for line in self.log.read_text(encoding="utf-8").splitlines()]
self.assertEqual([call[0] for call in calls], ["df", "nvidia-smi"] * 2) self.assertEqual([call[0] for call in calls], ["df", "nvidia-smi", "queue.py"] * 2)
self.assertEqual(calls[2], ["queue.py", "list", "--json", str(self.council)])
self.assertTrue(all(ASLEEP not in " ".join(call) for call in calls), calls) self.assertTrue(all(ASLEEP not in " ".join(call) for call in calls), calls)
self.assertEqual(sorted(path.name for path in samples.parent.iterdir()), ["cpu.json", "samples.jsonl"]) self.assertEqual(sorted(path.name for path in samples.parent.iterdir()), ["cpu.json", "samples.jsonl"])
@@ -369,7 +447,7 @@ class TestTimer(unittest.TestCase):
script = "/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/resources.py" script = "/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/resources.py"
shared = "--state ${KVB_ORCHESTRATOR_KEPT}/resources --council ${KVB_ORCHESTRATOR_COUNCIL}" shared = "--state ${KVB_ORCHESTRATOR_KEPT}/resources --council ${KVB_ORCHESTRATOR_COUNCIL}"
self.assertEqual([line for line in service if line.startswith("ExecStart=")], [ self.assertEqual([line for line in service if line.startswith("ExecStart=")], [
f"ExecStart={script} sample {shared} --proc /proc --sys /sys", f"ExecStart={script} sample {shared} --proc /proc --sys /sys --queue ${{KVB_ORCHESTRATOR_SKILLS}}/kvb-org-queue/scripts/queue.py",
f"ExecStart={script} tokens {shared} --transcripts ${{KVB_ORCHESTRATOR_PROJECTS}}", f"ExecStart={script} tokens {shared} --transcripts ${{KVB_ORCHESTRATOR_PROJECTS}}",
]) ])
self.assertIn("EnvironmentFile=%h/.local/share/kvb-orchestrator/.env", service) self.assertIn("EnvironmentFile=%h/.local/share/kvb-orchestrator/.env", service)
@@ -381,6 +459,7 @@ class TestTimer(unittest.TestCase):
self.assertIn('RESOURCES_UNIT="${NAME}-resources"', script) self.assertIn('RESOURCES_UNIT="${NAME}-resources"', script)
self.assertIn('systemctl --user enable --now "${RESOURCES_UNIT}.timer"', script) self.assertIn('systemctl --user enable --now "${RESOURCES_UNIT}.timer"', script)
self.assertIn('"${HUB}/client/resources.py"', script) self.assertIn('"${HUB}/client/resources.py"', script)
self.assertIn("KVB_ORCHESTRATOR_SKILLS=%s", script)
if __name__ == "__main__": if __name__ == "__main__":