Skip to content

status: count loads and memory refusals per tool, and log both in the journal - #164

Draft
smfworks wants to merge 29 commits into
jayleaton:mainfrom
smfworks:upstream/metrics-journal
Draft

smfworks wants to merge 29 commits into
jayleaton:mainfrom
smfworks:upstream/metrics-journal

Conversation

@smfworks

Copy link
Copy Markdown
Contributor

Stacked on #160 (it extends #160's /v1/status and /metrics). Draft: review #160 first.

Problem

On a unified-memory box, an agent's night of video work reloaded its chat model about 20 times beside the video model, and its requests were refused with 503 insufficient_memory again and again. The router recorded evictions only. Loads and refusals appeared only in the client's own log.

Change

  • /v1/status: tools[].loads (successful loads since start) and tools[].refusals (requests refused for memory).
  • /metrics: localrouter_tool_loads_total, localrouter_tool_refusals_total, localrouter_tool_last_load_duration_seconds.
  • Journal, next to the existing eviction line:
    • loaded <id> in <ms> ms: <MiB> MiB booked, <MiB> MiB free in the budget (load <n> since start)
    • refused <id>: it needs <MiB> MiB, <MiB> MiB free in the budget, held by <ids>; retry_after <s> s, where held by lists the tools that cannot be evicted (loading, committing, or running a job).
  • The output has tool ids and numbers only, with no paths, prompts, or messages. Labels are escaped as before.
  • docs/AGENTS.md lists the new fields, series, and lines.

Tests

  • Scheduler: a load counts once. A request refused while another tool runs a job counts one refusal and no load. holders names the running tool, or none. refusalLine formats as documented and returns an empty line, without crashing, when the buffer is too small.
  • status.zig: the Prometheus text has the three new series, with escaped labels.
  • zig build test passes (33/33 steps); zig fmt --check is clean.

tools/comfyui/worker.py starts its own ComfyUI (options.comfy_dir/python/args/env,
loopback, a private output directory) or uses options.url, fills an API-format
workflow from the request through explicit bindings (node.input), queues it,
reports progress from /ws, waits on /history and fetches 0.png.. or video.mp4
through /view. Unbound fields (negative prompt, steps, guidance), edits and
image-to-video are refused, never ignored; sizes, frame grids (frame_multiple /
frame_offset) and fps are checked; audio off removes a bound input. Cancel is
SIGUSR1 (/queue delete + /interrupt), and the worker stays loaded. Standard
library only; test_worker.py runs it against a fake ComfyUI (16 checks).

engine.fill: a video tool's options may name default_width/default_height for
requests without a size (a cmd model's own size); else 1344x768 as before.
options.modes.image_edit / image_to_video give requests with input images
their own workflow and bindings, merged over the tool's. references, mask
and first_frame are uploaded to ComfyUI (/upload/image, into the worker's
private input directory, cleaned per job) and wired in through added
LoadImage nodes (IMAGE, or MASK for a mask). Requests a tool cannot honour
are still refused. Tests: 24 checks against a fake ComfyUI.
image_edit may set defaults and an unmasked overlay (workflow, bindings,
defaults) used when a request has input images but no mask; request fields
still override. Masked edits keep the tool's fast defaults. Tests cover the
auto-select and the overrides.
worker.py had grown to 662 lines with edits and image to video, past the
600-line convention; the RFC 6455 client moves to comfy_events.py (76 lines) and
worker.py is 596. No behaviour change: the 29 worker checks pass.
…ts code

A job, video or 3D asset object's error now has type (the value an HTTP error
for the same failure carries, e.g. insufficient_memory), code (the same value,
as before) and message. A client matching the HTTP type in a job's message
missed jobs refused for room (the message reads "insufficient memory: ...")
and gave up instead of retrying. docs/AGENTS.md: match type or code, never
the message. Test: the error object's JSON.
A video job holds its model while it runs; a chat request (or an API load)
that needs the room is refused at once with 503 insufficient_memory, and loads
once the job is done. The scheduler already does this (in_use); the test pins
it, and fails if admit may take a slot in use.
ComfyUI no longer gets a session of its own (start_new_session): it stays in
the worker's process group, so the daemon's SIGKILL of that group on abort or
timeout takes it down too, and PR_SET_PDEATHSIG (SIGTERM) covers the worker
dying alone. Before, a hard kill left ComfyUI holding the GPU. An unload now
signals ComfyUI and every process below it instead of its group; SIGUSR1
(cancel) still goes to the worker alone.

Test: SIGKILL of the worker's group mid-render, the fake ComfyUI is gone
(fails on the old worker). The worker tests start the worker in its own group,
as the daemon does.
Expose each tool's state, resident bytes, queue depth, last load and last
error, plus the memory budget and eviction count. /health stays {"ok":true}.
The output has no paths, secrets or log text.
size_snap rounds width and height to the nearest multiple inside the model's
limits (1280x720 becomes 1280x704 on a 32 grid) and the response names the
size used. The default still refuses an off-grid size. GET /v1/tools lists
each tool's size constraints.
Tool logs under data/logs rotate by size and keep N older files, both
configurable (8 MiB and 3 by default).
A 32-pixel tool no longer answers "multiples of 16". The error names that
tool's limits, and a cmd tool that declares them is refused before it loads.
A chat request could unload a model that was still loading or committing
memory for a job (minimax-h3, priority 10, for qwen3.8-flash-next). A tool
in that state, or running a job, is not a victim. A request that fits by
unloading an idle model still does. One that cannot fit while a
non-evictable job holds the memory is refused at once with 503
insufficient_memory (type and code) and retry_after, also sent as
Retry-After, instead of sitting until the client times out. One that will
fit once a load's temporary overshoot settles waits for that load.

retry_after_s in the config (30 when unset) is the hint; a blocker whose
last load took longer raises it.
last_load_s read like a duration but held a unix timestamp. It is now
last_load_unix_s, and last_load_ms (the figure GET /v1/tools already shows)
says how long that load took. The Prometheus series keeps its name
(..._last_load_timestamp_seconds).
The journal line printed the host's MemAvailable as "MiB available",
which reads as the router budget's and can be far from it on a unified
memory machine. It now prints the budget's free bytes (the ceiling less
what is resident and admitted, as /v1/status free_bytes), then the host's
available memory and the reserve, labelled. evictionLine is a pure function
with a test, including an over-budget tool (0 free, no wrap).
…age recovers

roomIfEvicted took the victims' resident bytes off the request
(fits(extra -| freeable)). That clamps at 0 and still asks the current
usage to fit, so once a worker reported more than its estimate and usage
went over the budget, every later load was refused with 503 though the
worker was idle and could be evicted. The check now takes the victims'
bytes off what is held and adds them back to the host's available memory
(fitsFreeing), the state the eviction loop would reach.

Regression test: a 100 MiB budget, a worker estimated at 60 MiB that loads
at 120 MiB, then a 10 MiB load evicts it and loads.
…t keeps it open

A worker's descendant can start its own session, survive the group kill
and keep stderr open. joinLog waited for EOF forever with the scheduler
gate held, so unload and status stopped responding. The log-copy thread
now polls with a stop flag: after the worker is gone it stops at the first
quiet poll (100 ms) or after 1 s if the descendant keeps writing. wait
closes the read end only after the copy thread returns.

Test: a worker starts a descendant in a new session holding stderr, then
exits. Unload returns within 3 s while the descendant is still alive, and
another load/unload works. The test fails without the stop flag.
…age recovers

roomIfEvicted took the victims' resident bytes off the request
(fits(extra -| freeable)). That clamps at 0 and still asks the current
usage to fit, so once a worker reported more than its estimate and usage
went over the budget, every later load was refused with 503 though the
worker was idle and could be evicted. The check now takes the victims'
bytes off what is held and adds them back to the host's available memory
(fitsFreeing), the state the eviction loop would reach.

Regression test: a 100 MiB budget, a worker estimated at 60 MiB that loads
at 120 MiB, then a 10 MiB load evicts it and loads.
An agent's night on a unified-memory box reloaded its chat model 21
times beside a video model and was refused with 503 insufficient_memory
again and again, and neither showed anywhere but the agent's own log.

/v1/status gains tools[].loads (successful loads since start) and
tools[].refusals (its requests refused for memory). /metrics gains
localrouter_tool_loads_total, localrouter_tool_refusals_total and
localrouter_tool_last_load_duration_seconds. The journal gets a line per
load (time, MiB booked, MiB free in the budget, the load count) and per
refusal (MiB needed, MiB free in the budget, the tools holding it, the
retry_after given), beside the existing eviction line. No paths, prompts
or messages: tool ids and numbers only.
ci.yml: main's openai_audio step, then this branch's ComfyUI worker step.
…s' bytes

fitsFreeing added the victims' resident bytes to MemAvailable, read as 0
when unreadable. With a 20 MiB reserve and no reading, an idle 60 MiB
worker alone cleared the reserve, so the room check passed, the eviction
loop unloaded the worker, and the 10 MiB load was still refused with 503.
Before the over-budget fix the same load was refused and the worker stayed.

When the reading is unavailable and the check would count freed bytes, it
now refuses first. With nothing freed the check is unchanged.

memory.test_available lets a test stand in for the host's reading.
Regression test: "no MemAvailable reading: a load is refused and no
healthy worker is evicted for it" (fails without the fix).
…ble reading refuses before counting the victims' bytes) into this branch

# Conflicts:
#	src/sched/scheduler.zig
…ol ids are never blank

The line went through a 256-byte buffer, and bufPrint failed (NoSpaceLeft)
between two valid 100-character tool ids, so the journal got a blank entry.
admit now logs std.log.info(eviction_fmt, evictionArgs(...)) directly.

Test: "the eviction line between two 100-character tool ids is whole, not
blank"; "the eviction line reports the budget's free bytes, not the host's"
now formats through the same eviction_fmt.
The worker writes its detached descendant's pid over the last one on each
load, and the test only killed the first. It now reads the pid after each
load and registers that child's cleanup then, and also checks the second
unload is quick and the two descendants differ.
…is branch

# Conflicts:
#	src/sched/scheduler.zig
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant