Skip to content

Studio: trim serving-log noise and surface llama-server engine stats - #6377

Merged
danielhanchen merged 2 commits into
mainfrom
studio-serving-log-improvements
Jun 17, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-serving-log-improvements

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jun 16, 2026 •

Copy link
Copy Markdown
Member

Summary

A few changes to how Unsloth Studio logs while it is serving, so the terminal shows serving health instead of polling noise.

  1. Stop the duplicate access-log spam. The chat frontend fans a single cache invalidation into many identical list fetches (for example ~10 GET /api/chat/projects within about 100ms on each lifecycle event), so the terminal was dominated by repeats that carry no new information.
  2. Collapse high-frequency liveness polls to a heartbeat. Pure-liveness endpoints (/api/health, /api/auth/status, /api/inference/status) and the API monitor console poll (/api/inference/monitor, hit every 1.5s while the console is open) carry no signal in their access line, so they collapse to one line per longer window.
  3. Surface the serving signal that was missing. llama-server already computes throughput, but it only landed in a side log file; this lifts a vLLM-style engine summary into the main terminal.

Changes

  • loggers/handlers.py (LoggingMiddleware):
    • Drop a duplicate successful-GET access log when the same (method, path, query, status) was already logged within a short window. Default 300ms via UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS (set 0 to log everything). The query string is part of the key, so distinct query-driven GETs (for example browse-folders?path=a vs ?path=b) are not collapsed.
    • Collapse a small set of pure-liveness poll paths to a longer heartbeat window. Default 10s via UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS. The first hit and any non-2xx still log, so a stuck or unauthorized client stays visible.
    • Mutations (POST/PUT/PATCH/DELETE), any non-2xx, and progress polls such as /api/inference/load-progress are never affected. The check runs after the response has already been sent and is an O(1) dict lookup, so it adds no latency to API calls.
  • core/inference/llama_cpp.py plus new core/inference/llama_stats.py: a background daemon polls llama-server /metrics and emits a periodic engine_stats line with generation tok/s, prompt tok/s, requests running, and requests waiting. Throughput uses llama-server's documented predicted_tokens_seconds / prompt_tokens_seconds gauges, falling back to a tokens_predicted_total / prompt_tokens_total counter delta; it does not use n_decode_total, which counts llama_decode() calls rather than tokens. No KV field is emitted because current llama.cpp does not expose kv_cache_usage_ratio. --metrics is appended (and the poller started) only when probe_server_capabilities() reports the binary advertises it, so older or custom binaries still load. The poller keeps retrying through transient /metrics stalls (shutdown is driven by stop() on unload), a malformed sample cannot crash its thread, and it stays off the request path. Disable with UNSLOTH_STUDIO_ENGINE_STATS=0; tune the cadence with UNSLOTH_STUDIO_ENGINE_STATS_INTERVAL_S (default 10s).
  • core/inference/api_monitor.py (append_reply): the monitor preview is capped at 12000 chars, but it was re-concatenating the whole string on every streamed chunk even after the cap. Skip the re-concat once the cap is reached. This removes O(n^2) copying on long generations and preserves the existing behavior, including the ... truncation marker for a reply that lands exactly on the cap.
  • unsloth_cli/commands/studio.py: add --verbose / -v to re-enable every per-request log (both the burst dedup and the liveness heartbeat). It works on both unsloth studio and the one-liner unsloth studio run; passing it before a subcommand is rejected with guidance, matching how --secure / --parallel are handled. Because run historically passed an unrecognized --verbose through to llama-server, run --verbose still forwards --log-verbose to llama-server so that pass-through verbosity is preserved.

Relationship to #5558

#5558 (merged) adds an in-app API monitor console that shows recent per-request activity (prompt and reply previews, token usage, status). This PR is the terminal-side counterpart: aggregate engine throughput plus access-log trimming. They touch no shared files. One interaction worth noting: that console polls /api/inference/monitor every 1.5s while open, which this PR's liveness heartbeat collapses (18 polls over 26s became 3 terminal lines in testing).

Impact (one realistic 10s request timeline, true cadence)

policy access-log lines
no dedup (--verbose) 59
burst dedup only 41
burst + liveness heartbeat 25

Every signal is preserved under the new policy: chat completions, load-progress polls, mutations, and 4xx all log; only redundant liveness polls collapse. Example engine line:

{"event": "engine_stats", "gen_tok_s": 110.3, "prompt_tok_s": 270.1, "running": 1, "waiting": 0}

Verification

  • Unit tests: tests/test_logging_middleware.py (burst collapses to one line; distinct query strings are not deduped; mutations and errors never deduped; liveness paths use the longer heartbeat), tests/test_api_monitor.py (capped reply does not regrow, and an exact-cap reply still records ...), tests/test_llama_stats.py (throughput uses token metrics not decode calls, no fabricated KV, counter-delta fallback), and unsloth_cli/tests/test_studio_verbose_flag.py (option registration on both paths, re-exec forwarding, env override, llama-server --log-verbose preserved, and rejection before a subcommand). The probe_server_capabilities() detection tests pass with the new supports_metrics key.
  • Live end to end on unsloth/gemma-4-E2B-it-GGUF:UD-Q4_K_XL with the Add API server monitor in Studio #5558 monitor present: the monitor endpoint and UI console rendered all captured requests correctly, the console's 1.5s polling collapsed to a 10s heartbeat, engine_stats reported live throughput, and 10 concurrent external /v1/chat/completions ran at full speed with request latency unchanged.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a vLLM-style engine-stats logger for llama-server by polling its Prometheus /metrics endpoint, and implements deduplication for high-frequency successful GET access logs (with a --verbose flag to disable it). The review feedback highlights two key reliability improvements for the stats logger: moving the metric parsing inside the try-except block to prevent potential ValueError crashes, and removing the self-termination logic after three failures to avoid permanent shutdown during transient timeouts under heavy load.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +44 to +52
self._thread.start()

def stop(self):
self._stop.set()

def _scrape(self):
try:
with urllib.request.urlopen(self._url, timeout = 3) as r:
if r.status != 200:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The dictionary comprehension parsing the metrics is located outside of the try...except block. If float(v) raises a ValueError (e.g., due to unexpected or malformed metric values), the exception will propagate uncaught and permanently crash the background daemon thread. Moving the parsing inside the try block ensures any parsing errors are safely caught. Additionally, avoid silent exception handlers; log the exception at least at a debug level to aid in future troubleshooting.

Suggested change
self._thread.start()
def stop(self):
self._stop.set()
def _scrape(self):
try:
with urllib.request.urlopen(self._url, timeout = 3) as r:
if r.status != 200:
def _scrape(self):
try:
with urllib.request.urlopen(self._url, timeout=3) as r:
if r.status != 200:
return None
body = r.read().decode("utf-8", "replace")
return {k: float(v) for k, v in _METRIC_RE.findall(body)}
except Exception as e:
logger.debug("Failed to scrape metrics: %s", e)
return None
References
  1. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

Comment on lines +54 to +64
body = r.read().decode("utf-8", "replace")
except Exception:
return None
return {k: float(v) for k, v in _METRIC_RE.findall(body)}

def _run(self):
misses = 0
prev = None # (monotonic_t, n_decode_total, prompt_tokens_total)
while not self._stop.wait(self._interval):
m = self._scrape()
if not m:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Self-terminating the stats logger after only 3 consecutive scrape failures is highly risky. During heavy model load or long prefill phases, llama-server can become temporarily unresponsive or slow to respond to /metrics, leading to transient timeouts. If this happens 3 times in a row, the stats logger will permanently terminate and never restart for the remainder of the server's lifetime.

Since the stats logger is a daemon thread and is explicitly stopped by _kill_process anyway, it is safer to remove the self-termination logic entirely and simply continue retrying on failures.

Suggested change
body = r.read().decode("utf-8", "replace")
except Exception:
return None
return {k: float(v) for k, v in _METRIC_RE.findall(body)}
def _run(self):
misses = 0
prev = None # (monotonic_t, n_decode_total, prompt_tokens_total)
while not self._stop.wait(self._interval):
m = self._scrape()
if not m:
def _run(self):
prev = None # (monotonic_t, n_decode_total, prompt_tokens_total)
while not self._stop.wait(self._interval):
m = self._scrape()
if not m:
continue

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 706b00166f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth_cli/commands/studio.py Resolved
@danielhanchen
danielhanchen force-pushed the studio-serving-log-improvements branch from 8412589 to 8b76d29 Compare June 17, 2026 01:01
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@danielhanchen danielhanchen changed the title Studio: dedup access-log spam and surface llama-server engine stats Studio: trim serving-log noise and surface llama-server engine stats Jun 17, 2026
@danielhanchen
danielhanchen force-pushed the studio-serving-log-improvements branch from 038226a to 1a17ddb Compare June 17, 2026 10:02
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@danielhanchen
danielhanchen force-pushed the studio-serving-log-improvements branch from 3e535f7 to e5d050b Compare June 17, 2026 10:16
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@danielhanchen
danielhanchen force-pushed the studio-serving-log-improvements branch from e5d050b to 544b78a Compare June 17, 2026 10:32
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@danielhanchen
danielhanchen force-pushed the studio-serving-log-improvements branch from 1f47222 to b302ee6 Compare June 17, 2026 11:16
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

Studio prints one structured line per HTTP request, so the SPA's polling and
per-invalidation fan-out bury the lines that matter.

- Dedup identical successful GETs within a short window (default 300ms,
  UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS) so a burst logs once. The dedup key
  includes the query string, so distinct query-driven GETs are not collapsed.
  Runs after the response is sent, so it adds no request latency; mutations,
  non-2xx, and loading polls are untouched.
- Collapse pure-liveness polls (/api/health, /api/auth/status,
  /api/inference/status, /api/inference/monitor) to a longer heartbeat
  (default 10s, UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS). The API monitor
  console polls /monitor every 1.5s while open.
- Translate llama-server's Prometheus /metrics into a periodic vLLM-style
  engine_stats line (generation/prompt throughput and requests in flight) from
  a daemon poller, gated on UNSLOTH_STUDIO_ENGINE_STATS. Throughput uses
  llama-server's predicted_tokens_seconds / prompt_tokens_seconds gauges, with
  a tokens_predicted_total / prompt_tokens_total counter-delta fallback; it does
  not use n_decode_total (which counts llama_decode() calls, not tokens). No KV
  field is emitted, since llama.cpp does not expose kv_cache_usage_ratio.
  --metrics is added only when probe_server_capabilities reports the binary
  supports it, so older/custom binaries still load. The poller keeps retrying
  through transient scrape failures (stop() drives shutdown) and a malformed
  sample cannot crash its thread.
- api_monitor.append_reply: once the preview cap is reached, skip the per-chunk
  re-concat (avoids O(n^2) on long generations) while still recording the "..."
  truncation marker for a reply that lands exactly on the cap.
- unsloth studio --verbose and unsloth studio run --verbose both restore every
  per-request log; --verbose before a subcommand is rejected with guidance
  (matching --secure / --parallel). run --verbose still forwards --log-verbose
  to llama-server, preserving the pre-existing pass-through verbosity.
@danielhanchen
danielhanchen force-pushed the studio-serving-log-improvements branch from 83b41c7 to e4788ce Compare June 17, 2026 12:02
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@Imagineer99 Imagineer99 self-assigned this Jun 17, 2026
@danielhanchen
danielhanchen merged commit 9a966ad into main Jun 17, 2026
31 of 36 checks passed
@danielhanchen
danielhanchen deleted the studio-serving-log-improvements branch June 17, 2026 12:38
danielhanchen added a commit that referenced this pull request Jun 18, 2026
…errides, UI re-login) (#6419)

* studio: set _stats_logger in kill-process test backend

#6377 added a self._stats_logger cleanup step to _kill_process's finally block.
test_kill_process_records_timestamp_on_actual_kill (added in #6400) builds the
backend via __new__, which bypasses __init__ where _stats_logger is set, so once
both landed on main the test raised AttributeError: 'LlamaCppBackend' object has
no attribute '_stats_logger'. Set _stats_logger on the hand-built backend,
mirroring __init__, so the kill path's finally has the attribute it expects.

* test: assert torchao override step on normal Linux, not overrides.txt

#6400 moved the torchao dependency override from a fixed pin in overrides.txt to
a torch-matched spec installed via --force-reinstall (_select_torchao_spec), and
turned overrides.txt into a comment-only pointer. It updated the Windows variant
(test_windows_only_includes_overrides) to check for --reinstall, but left
test_normal_linux_includes_overrides asserting overrides.txt is installed, which
no longer happens. Check for the override step (--reinstall) instead, matching
the Windows test.

* test(ui): tolerate ERR_ABORTED on /login re-login in shutdown step

The Shutdown step re-logs in after a CLI password rotation that revoked the prior
token. The SPA auth guard can client-side-redirect mid-navigation against the
stale token, aborting page.goto("/login") with net::ERR_ABORTED. It is a race
(passes on main most of the time). Resolve on domcontentloaded and tolerate the
abort, relying on the password-field wait that follows to confirm we reached
/login, matching the wait_until used by the other navigations in this file.
danielhanchen added a commit that referenced this pull request Aug 25, 2026
Log reduction in Studio is several PRs deep (#6377, #7087, #8310, #8311)
and every round started the same way: someone noticed a log was huge,
measured it, and trimmed it. Nothing stopped the next chatty endpoint,
and nothing told the author they had added one.

Five guards, all CPU-only, no network, no sleeping. A 30 minute idle
session and a 5 minute in-flight session are replayed through the real
LoggingMiddleware against a virtual clock, so a thirty minute scenario
runs in a second and lands identically on a loaded runner.

  budget       lines per class against a formula of the poll period and
               the dedup window, plus an envelope on the whole scenario
  classify     a path cannot be quieted without recording how often it
               is polled, and cannot be polled without being classified
  signal       failures and mutations log at every interval, and the
               scenario is proved to have exercised the real middleware
               before any count from it is trusted
  parity       one JSON fixture defines a successful access record for
               both the backend and the desktop shell
  bounds       every log family prunes, and the two line caps agree

The signal guard is the point. An upper bound on log lines is satisfied
just as well by a middleware that was never mounted, a logger replaced
with a no-op, a scenario that stopped issuing requests, or an error log
someone deleted to get under the number. Each of those now fails.

Two ledgers record what is already broken rather than weakening the
rules to accommodate it: /api/settings/remote-access and /api/liveness
sit in the 300ms burst class and write a line per poll, and the
llama-server and diffusion-server directories never prune. Both ledgers
are self-expiring, so fixing an entry forces its removal.

Verified by mutation: eight deliberate breakages, each turning exactly
the intended guard red.
danielhanchen added a commit that referenced this pull request Aug 25, 2026
* Studio: guard log volume in CI so it cannot regress unnoticed

Log reduction in Studio is several PRs deep (#6377, #7087, #8310, #8311)
and every round started the same way: someone noticed a log was huge,
measured it, and trimmed it. Nothing stopped the next chatty endpoint,
and nothing told the author they had added one.

Five guards, all CPU-only, no network, no sleeping. A 30 minute idle
session and a 5 minute in-flight session are replayed through the real
LoggingMiddleware against a virtual clock, so a thirty minute scenario
runs in a second and lands identically on a loaded runner.

  budget       lines per class against a formula of the poll period and
               the dedup window, plus an envelope on the whole scenario
  classify     a path cannot be quieted without recording how often it
               is polled, and cannot be polled without being classified
  signal       failures and mutations log at every interval, and the
               scenario is proved to have exercised the real middleware
               before any count from it is trusted
  parity       one JSON fixture defines a successful access record for
               both the backend and the desktop shell
  bounds       every log family prunes, and the two line caps agree

The signal guard is the point. An upper bound on log lines is satisfied
just as well by a middleware that was never mounted, a logger replaced
with a no-op, a scenario that stopped issuing requests, or an error log
someone deleted to get under the number. Each of those now fails.

Two ledgers record what is already broken rather than weakening the
rules to accommodate it: /api/settings/remote-access and /api/liveness
sit in the 300ms burst class and write a line per poll, and the
llama-server and diffusion-server directories never prune. Both ledgers
are self-expiring, so fixing an entry forces its removal.

Verified by mutation: eight deliberate breakages, each turning exactly
the intended guard red.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: fail CI when the app polls a path the log budget never declared

The budget suite compares two backend files against each other: the suppression
sets in loggers/handlers.py and the poll cadences in log_budget/session.py. A
pull request that adds a polling call site in the frontend edits neither, so
nothing fails, the endpoint lands in the normal class on a 300 ms window, and
the access log grows by lines nobody chose.

Static analysis does not close it. Polling here is 53 setInterval call sites,
most of them UI timers rather than fetches, plus 257 setTimeout of which an
unknown number are recursive poll loops, and the fetch usually sits several
helper layers below the timer.

So watch the browser. Walk the sidebar sections, count API requests per dwell
rather than across the walk (a timer repeats within one dwell, a per-view fetch
fires once and stops, and summing the two is what makes navigation look like
polling), and fail on any path repeated inside a single dwell that is absent
from the budget.

Measured on a runner with no GPU and no model, two paths qualify. The floor is
set there so a run that observed nothing fails instead of reporting green, and
the docstring states plainly that polls gated behind a loaded model are outside
what this can see.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Run the declared-polls guard where a backend actually exists

The step landed in studio-frontend-ci's build job, which drives Playwright
against a vite dev server: no backend, no BASE_URL, no auth. The suite reads
BASE_URL at import, so it would have failed on a KeyError every run rather than
guarding anything.

Move it to studio-ui-smoke's ui-indicator job, which installs Studio with
--local --no-torch and already boots an authenticated server per engine, and
reuse that job's boot/rotate/teardown script instead of duplicating it. The
script's suite path becomes STUDIO_PW_SUITE with its current value as the
default, so every existing caller is unchanged.

Own port and home, for the reason the three engines get one each: a shared home
races on the bootstrap password. tests/studio/** is already in this workflow's
paths filter, so no trigger change is needed.

* Ratchet the log budget onto a main that has #8763

Rebasing onto the merge turned three of these guards red, which is what they are
for: each one refuses to let a ledger outlive the problem it records.

  KNOWN_UNCLASSIFIED_POLLS  /api/liveness and /api/settings/remote-access now
                            have heartbeat classes, so both entries went stale.
  KNOWN_UNBOUNDED_FAMILIES  llama-server and diffusion-server now prune.
  the Rust parity check     process.rs implements the success rule but no Rust
                            test read the shared fixture, so the corpus was only
                            ever checked from Python.

Both ledgers are now empty. Added the shared_access_log_fixture_tests module the
fixture names, which asserts all 14 cases against is_backend_access_log_line;
verified green with cargo test.

Idle envelope ratcheted 1450 -> 1170 against a re-measured 1110. The old note
predicted the fix would take idle to roughly 930 and that was wrong: a 10s
heartbeat against a 5s poll still emits half of /api/settings/remote-access, 180
lines over 30 minutes, now the joint-largest contributor. Left at 1450 there
would have been 340 lines of slack, enough for a new 10s endpoint to land
unnoticed; at 1170 that same endpoint trips the envelope.

* Name the declared-polls suite where CI can see it

test_every_playwright_driver_is_invoked_by_ci caught this, and it was right on
both counts.

Routing the suite through STUDIO_PW_SUITE meant the only place its path appeared
was an env: block, and that guard reads run:, uses: and with:, never env:. Worse,
wrapping the script's invocation in ${STUDIO_PW_SUITE:-...} hid the suite that
was already there: the guard reported TWO orphans, mine and
playwright_loaded_models_indicator.py, which had been named literally since it
was written. A parameterisation that makes an existing suite invisible is a bad
trade even when it saves duplication.

So drop the indirection. The script goes back untouched, and the step moves to
the ui-smoke extra shard, which already boots a Studio on 18894 and already mints
the credentials, so every sibling step there is just 'python tests/studio/<driver>.py' against
it. Mine now reads the same, needs no second
boot, and the guard matches it the ordinary way.

Placed last in the shard: it dwells for two minutes and rotates the bootstrap
password, so a step after it would wait, then meet a password it did not mint.

Verified locally: the full Workflow guard suites step, 698 passed.

* Let the replay model a slow request

The harness could not express the case the suppressors are blindest to. Both of
them key on the status code and neither reads how long the request took, so a
200 that took a minute is indistinguishable from a 200 that took a millisecond
-- and _app_returning sent its response without touching the clock, so every
replayed request cost zero virtual time. A budget cannot bound what its harness
cannot express.

Request grows a duration_ms, defaulting to 0 so every existing scenario is
unchanged, and the poll loop now reads the clock instead of its own counter so
time spent inside a slow handler counts against the session rather than
extending it. Idle stays at 1110 and busy at 239, measured, and all 93 tests
pass.

The two new tests assert TODAY's behaviour, not the desired behaviour: a slow
success on a quiet-success path still writes nothing. The gap is worth closing,
but a guard that tolerated either answer would let an exemption be added and
then removed again unnoticed, so closing it should flip these deliberately and
budget the new volume. Measured, an unbounded exemption emits one line per
request on a sustained degradation, which is the growth these budgets exist to
stop; it needs a heartbeat of its own.

The third test guards the other two. If duration_ms ever stopped reaching the
middleware, every "slow" assertion here would silently be testing a fast
request. Verified by breaking the advance on purpose: that test, and only that
test, goes red.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Aug 25, 2026
* Studio: guard log volume in CI so it cannot regress unnoticed

Log reduction in Studio is several PRs deep (#6377, #7087, #8310, #8311)
and every round started the same way: someone noticed a log was huge,
measured it, and trimmed it. Nothing stopped the next chatty endpoint,
and nothing told the author they had added one.

Five guards, all CPU-only, no network, no sleeping. A 30 minute idle
session and a 5 minute in-flight session are replayed through the real
LoggingMiddleware against a virtual clock, so a thirty minute scenario
runs in a second and lands identically on a loaded runner.

  budget       lines per class against a formula of the poll period and
               the dedup window, plus an envelope on the whole scenario
  classify     a path cannot be quieted without recording how often it
               is polled, and cannot be polled without being classified
  signal       failures and mutations log at every interval, and the
               scenario is proved to have exercised the real middleware
               before any count from it is trusted
  parity       one JSON fixture defines a successful access record for
               both the backend and the desktop shell
  bounds       every log family prunes, and the two line caps agree

The signal guard is the point. An upper bound on log lines is satisfied
just as well by a middleware that was never mounted, a logger replaced
with a no-op, a scenario that stopped issuing requests, or an error log
someone deleted to get under the number. Each of those now fails.

Two ledgers record what is already broken rather than weakening the
rules to accommodate it: /api/settings/remote-access and /api/liveness
sit in the 300ms burst class and write a line per poll, and the
llama-server and diffusion-server directories never prune. Both ledgers
are self-expiring, so fixing an entry forces its removal.

Verified by mutation: eight deliberate breakages, each turning exactly
the intended guard red.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: fail CI when the app polls a path the log budget never declared

The budget suite compares two backend files against each other: the suppression
sets in loggers/handlers.py and the poll cadences in log_budget/session.py. A
pull request that adds a polling call site in the frontend edits neither, so
nothing fails, the endpoint lands in the normal class on a 300 ms window, and
the access log grows by lines nobody chose.

Static analysis does not close it. Polling here is 53 setInterval call sites,
most of them UI timers rather than fetches, plus 257 setTimeout of which an
unknown number are recursive poll loops, and the fetch usually sits several
helper layers below the timer.

So watch the browser. Walk the sidebar sections, count API requests per dwell
rather than across the walk (a timer repeats within one dwell, a per-view fetch
fires once and stops, and summing the two is what makes navigation look like
polling), and fail on any path repeated inside a single dwell that is absent
from the budget.

Measured on a runner with no GPU and no model, two paths qualify. The floor is
set there so a run that observed nothing fails instead of reporting green, and
the docstring states plainly that polls gated behind a loaded model are outside
what this can see.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Run the declared-polls guard where a backend actually exists

The step landed in studio-frontend-ci's build job, which drives Playwright
against a vite dev server: no backend, no BASE_URL, no auth. The suite reads
BASE_URL at import, so it would have failed on a KeyError every run rather than
guarding anything.

Move it to studio-ui-smoke's ui-indicator job, which installs Studio with
--local --no-torch and already boots an authenticated server per engine, and
reuse that job's boot/rotate/teardown script instead of duplicating it. The
script's suite path becomes STUDIO_PW_SUITE with its current value as the
default, so every existing caller is unchanged.

Own port and home, for the reason the three engines get one each: a shared home
races on the bootstrap password. tests/studio/** is already in this workflow's
paths filter, so no trigger change is needed.

* Ratchet the log budget onto a main that has #8763

Rebasing onto the merge turned three of these guards red, which is what they are
for: each one refuses to let a ledger outlive the problem it records.

  KNOWN_UNCLASSIFIED_POLLS  /api/liveness and /api/settings/remote-access now
                            have heartbeat classes, so both entries went stale.
  KNOWN_UNBOUNDED_FAMILIES  llama-server and diffusion-server now prune.
  the Rust parity check     process.rs implements the success rule but no Rust
                            test read the shared fixture, so the corpus was only
                            ever checked from Python.

Both ledgers are now empty. Added the shared_access_log_fixture_tests module the
fixture names, which asserts all 14 cases against is_backend_access_log_line;
verified green with cargo test.

Idle envelope ratcheted 1450 -> 1170 against a re-measured 1110. The old note
predicted the fix would take idle to roughly 930 and that was wrong: a 10s
heartbeat against a 5s poll still emits half of /api/settings/remote-access, 180
lines over 30 minutes, now the joint-largest contributor. Left at 1450 there
would have been 340 lines of slack, enough for a new 10s endpoint to land
unnoticed; at 1170 that same endpoint trips the envelope.

* Name the declared-polls suite where CI can see it

test_every_playwright_driver_is_invoked_by_ci caught this, and it was right on
both counts.

Routing the suite through STUDIO_PW_SUITE meant the only place its path appeared
was an env: block, and that guard reads run:, uses: and with:, never env:. Worse,
wrapping the script's invocation in ${STUDIO_PW_SUITE:-...} hid the suite that
was already there: the guard reported TWO orphans, mine and
playwright_loaded_models_indicator.py, which had been named literally since it
was written. A parameterisation that makes an existing suite invisible is a bad
trade even when it saves duplication.

So drop the indirection. The script goes back untouched, and the step moves to
the ui-smoke extra shard, which already boots a Studio on 18894 and already mints
the credentials, so every sibling step there is just 'python tests/studio/<driver>.py' against
it. Mine now reads the same, needs no second
boot, and the guard matches it the ordinary way.

Placed last in the shard: it dwells for two minutes and rotates the bootstrap
password, so a step after it would wait, then meet a password it did not mint.

Verified locally: the full Workflow guard suites step, 698 passed.

* Let the replay model a slow request

The harness could not express the case the suppressors are blindest to. Both of
them key on the status code and neither reads how long the request took, so a
200 that took a minute is indistinguishable from a 200 that took a millisecond
-- and _app_returning sent its response without touching the clock, so every
replayed request cost zero virtual time. A budget cannot bound what its harness
cannot express.

Request grows a duration_ms, defaulting to 0 so every existing scenario is
unchanged, and the poll loop now reads the clock instead of its own counter so
time spent inside a slow handler counts against the session rather than
extending it. Idle stays at 1110 and busy at 239, measured, and all 93 tests
pass.

The two new tests assert TODAY's behaviour, not the desired behaviour: a slow
success on a quiet-success path still writes nothing. The gap is worth closing,
but a guard that tolerated either answer would let an exemption be added and
then removed again unnoticed, so closing it should flip these deliberately and
budget the new volume. Measured, an unbounded exemption emits one line per
request on a sustained degradation, which is the growth these budgets exist to
stop; it needs a heartbeat of its own.

The third test guards the other two. If duration_ms ever stopped reaching the
middleware, every "slow" assertion here would silently be testing a fast
request. Verified by breaking the advance on purpose: that test, and only that
test, goes red.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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