Skip to content

api: GET /v1/status and Prometheus /metrics, opt-in size_snap with per-tool size grids, per-tool log rotation - #160

Open
smfworks wants to merge 26 commits into
jayleaton:mainfrom
smfworks:upstream/observe-snap-logs
Open

smfworks wants to merge 26 commits into
jayleaton:mainfrom
smfworks:upstream/observe-snap-logs

Conversation

@smfworks

Copy link
Copy Markdown
Contributor

Stacked on the scheduler PR (#159), which is stacked on #156. Until those merge, the diff here includes them. Review the 4 commits after "scheduler: do not evict a tool that is loading or committing". /v1/status reads the scheduler state that PR adds (loading/committing phases, last load, evictions). The size grids use #156's engine size options and ComfyUI size_multiple.

Four commits, one concern each:

  1. GET /v1/status and GET /metrics. For each tool: state, resident bytes, queue depth, last successful load time, and the last job error ({type, code, time}). The states are idle, loading, committing, busy and unloaded; idle is what GET /v1/tools calls ready. Also the memory budget (ceiling, used, free) and an eviction counter. An idle-TTL unload or an explicit unload doesn't count as an eviction. /metrics gives the same figures as Prometheus text (localrouter_tool_*, localrouter_memory_bytes, localrouter_evictions_total). Neither output includes a path, a hostname, a secret or a log line. /health stays {"ok":true}. /v1/status uses scope read.
  2. Opt-in size_snap. "size_snap": true rounds width and height to the nearest size the model accepts: its multiple, inside its limits, with ties going to the lower multiple. For example, 1280x720 becomes 1280x704 on a 32 grid. The response's size is the size actually used. The default (false) still refuses an off-grid size. GET /v1/tools now lists each image or video tool's size grid (multiple, min_/max_width, min_/max_height, max_pixels). New file src/tool/size.zig.
  3. Per-tool log rotation. <data_dir>/logs/<id>.log rotates once it reaches log_max_bytes (default 8 MiB) and keeps log_keep older files (default 3). Setting log_max_bytes to 0 turns rotation off. Rotation works across worker reloads. New file src/tool/logrotate.zig.
  4. Off-grid errors name the tool's own grid. A 32-pixel tool no longer answers "multiples of 16". A cmd tool that declares size_multiple (or the side and pixel limits) is refused before its worker loads.

Checks run locally (Zig 0.17.0, x86_64 Linux, no GPU):

  • zig build
  • zig build test --summary all: 604/607 passed, 3 skipped. The scheduler PR gives 594/597, so this adds 10 tests, including the new tests/observe.zig integration checks (status, metrics and /health; size_snap and the /v1/tools grid).
  • zig fmt --check on the touched Zig files
  • git diff --check

Hardware: deployed on AMD Strix Halo (gfx1151), 128 GB unified memory.

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.

@jayleaton jayleaton left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. Both endpoints return 401 without credentials, 403 with the media scope and 200 with read, and Randy found nothing leaking (no prompts, paths or tokens) and no unbounded labels. The docs cover the change. One blocker:

Blocking: src/tool/process.zig:463. joinLog() waits forever if a descendant of the worker starts its own session and keeps stderr open. Unload holds the scheduler gate while it waits, so unload and status requests both time out. On #159, the same scenario unloads fine. Fix: after the worker ends, make the log draining cancellable with a time limit. Please add a test with a surviving descendant holding stderr.

This one also needs #159's fix, since it's stacked on #159.

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.
ci.yml: main's openai_audio step, then this branch's ComfyUI worker step.
@smfworks

Copy link
Copy Markdown
Contributor Author

Fixed in ac1a0fb: after a worker exits, the log copier stops at its first quiet read or after 1 s, so a child that keeps stderr open no longer hangs unload (test with a detached child, fails without the fix). Also renamed to last_load_unix_s / last_load_ms, the eviction line now reports budget free plus host and reserve, and f17e48e carries #159's scheduler fix.

@jayleaton jayleaton left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 2: the stderr fix works. Unload and concurrent status requests return 200 in 0.19 s with a quiet descendant and in 1.02 s with one that keeps writing. Cancel completes in 1.25 s, and normal shutdown keeps all 24,002 lines byte for byte, across 30 rotations.

  1. Blocking, inherited from #159: src/sched/scheduler.zig:1481. A missing MemAvailable reading evicts a healthy worker. See the #159 review.
  2. Nit: scheduler.zig:1305. Evicting between two valid 100-character tool IDs logs a blank journal entry. Fix: format the message directly with std.log.info, which avoids the 256-byte limit.
  3. Nit: src/tool/process.zig:720. The reload test overwrites the PID file and only cleans up the first detached child. Fix: register cleanup for each child after it loads.

…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.
smfworks added a commit to smfworks/localrouter that referenced this pull request Nov 19, 2026
…is branch

# Conflicts:
#	src/sched/scheduler.zig
smfworks added a commit to smfworks/localrouter that referenced this pull request Nov 19, 2026
@smfworks

Copy link
Copy Markdown
Contributor Author

Thanks for the round 2 run. Changes, all new commits:

  1. The MemAvailable blocker: scheduler: never evict a tool that is loading, committing or running a job; refuse fast with 503 insufficient_memory #159's fix is merged in at b0b7099 (48b4e34).
  2. The eviction line now goes straight through std.log.info(eviction_fmt, evictionArgs(...)), with no 256-byte buffer (71e83dc). New test: "the eviction line between two 100-character tool ids is whole, not blank".
  3. The reload test reads the descendant's pid after each load and registers cleanup for that child, and it also checks that the second unload is quick (7c04262).
    scheduler: retry_after estimates when the blocking tool will free its memory #163, status: count loads and memory refusals per tool, and log both in the journal #164 and models: list a cmd tool's request fields, from its bindings #165 have these merged in too.

@jayleaton jayleaton left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 3: the missing-memory replay passes here too, and both nits are fixed. The eviction line now logs both full IDs, and cleanup is registered for each load. One blocker:

Blocking: src/engine/engine.zig:794. This inherits #159's conflicts and adds a conflict in the engine. Please restack after #159, and keep #156's sizing behaviour when you reconcile the engine changes.

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.

2 participants