Skip to content

fix(logs): quiet the polls and drop the duplicated access lines - #8763

Merged
danielhanchen merged 15 commits into
unslothai:mainfrom
LeoBorcherding:fix/studio-log-volume
Aug 25, 2026
Merged

danielhanchen merged 15 commits into
unslothai:mainfrom
LeoBorcherding:fix/studio-log-volume

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator

Follow-on to #8690, now merged. With the logs readable from Settings > Debugging, what is in
them matters a good deal more.

Why

Measured on an idle 4h desktop session, tauri.log was 5308 lines / 1.14 MB, of which 4056
(76%) were request_completed access records and 3355 (63%) came from six polling endpoints.
At ~216 bytes a line the 5 MiB cap fills in about 18 hours, so a failure from the day before
had already rotated out by the time anyone asked for it.

Follows #7087 and #7869, which trimmed the middleware suppressors but not the fan-out.

Polls

/api/liveness is the desktop watchdog's own probe and was in no suppressor at all: 760
lines, 14% of the file. Its sibling /api/health was already quiet.

It does not join /api/health in _QUIET_POLL_PATHS, because that window is narrower than
the poll it would have to collapse. The watchdog runs HEALTH_WATCHDOG_INTERVAL (15s)
between rounds plus up to HEALTH_PROBE_TIMEOUT (10s) inside one -- 19s apart in the sample
-- while _QUIET_POLL_DEDUP_MS is 10s and stamps only on emit, so no two probes ever land in
one window and every one would still log. It gets its own _WATCHDOG_POLL_DEDUP_MS (60s,
UNSLOTH_STUDIO_ACCESS_LOG_WATCHDOG_DEDUP_MS) instead: ~240 lines over that 4h sample rather
than 760. The other quiet polls keep their 10s window, because the download and load-progress
ones are the only signal a long operation is still alive.

Non-2xx still logs every time, which is the case that matters for a watchdog, and --verbose
zeroes this window along with the other two. /api/settings/remote-access is a plain read of
a toggle and does join the ordinary quiet polls (116 lines).

Duplication

Every backend stdout line is written to disk three times: the backend's own session log, the
diagnostics phase log (stream-tagged and stamped), and tauri.log. The successful access
records carry nothing in the third copy that the first two lack, so they log at debug!,
below the file target's INFO filter.

The 2xx test is the point: the backend's heartbeat suppressor deliberately exempts non-2xx so
a failing poll logs every time, and tauri.log is exactly where a watchdog going red gets
read, so those keep INFO. A record with no status_code is one we cannot vouch for and keeps
INFO too. Non-JSON output -- startup banner, Hardware detected:, stderr, tracebacks -- keeps
INFO, which is what anyone opening tauri.log is there for. The phase log still gets the
unfiltered stream, so the Debugging tab and the support report both lose nothing.

Progress bars

A tqdm bar redraws by writing \r<frame> tens of times. A terminal overwrites in place; a
file keeps every one, and a single "Loading weights" bar landed as 5086 bytes on one line,
across three sinks. Both sides now keep the final frame, and tauri.log lines are capped at
16 KiB, the limit the phase log already used.

The Python tee withholds frames and nothing else: an unterminated chunk containing \r is a
redraw and is held until the next supersedes it, while one without a \r -- a prompt, or a
traceback torn by a hang -- is written the moment it arrives. So nothing diagnostic waits on a
newline that may never come. A held frame is closed off on its own line as soon as anything
but its own redraw or terminator follows, so it can never be prefixed onto the record after it
(a structlog record arriving mid-redraw has to stay parseable), and one still held at
close() is landed rather than dropped. The console still sees every frame, which is the
whole point of a progress bar.

Startup logging order

run_server now installs the session tee first, configures structlog second, and logs third.

structlog was configured on import of main.py, which happens several seconds into
run_server -- after its first line. That line rendered through structlog's defaults
(ConsoleRenderer, local time) and everything after it as JSON in UTC, so the clock appeared to
jump hours between line one and line two of one stream.

Configuring earlier fixes that but cannot be done before the tee: LogConfig.setup_logging
hands structlog a PrintLoggerFactory(file = sys.stdout), which snapshots the stream it is
given, and cache_logger_on_first_use then freezes that snapshot into any logger that has
already emitted a line. Configure before _setup_server_disk_logging() swaps sys.stdout and
run.py's module logger is pinned to the console for the rest of the process, so every
subsequent run.py line goes missing from the session log -- and main.py's later
configure() does not rescue it. Ordering the two the other way round fixes both. It also
moves the orphan-sweep warnings inside the tee's window, where they were console-only before.

Also

  • Bounds logs/llama-server and logs/diffusion-server, created per model load and never
    pruned (319 files going back two months here). Lifts run.py's keep-newest-20 into
    utils/log_retention.prune_log_dir and calls it from all three. This is the "Nothing prunes
    logs/llama-server and one file is written per load" note in debug_log_sources.py; the
    MAX_SOURCES_PER_FAMILY * 3 pre-slice still earns its keep, since pruning only runs on the
    next model load and existing installs have a backlog already.
  • Logs the top-models catalog at debug. Two lists of 40 repo names, one line each, every boot,
    to say a fetch succeeded. The counts say that.

Testing

pytest tests/test_logging_middleware.py tests/test_tee_progress_frames.py -- 50 passed, 14
new. The tee tests pin the behaviour that decides whether this is safe: a bar collapses, a
prompt after a bar is not withheld, a record after a held frame is still one JSON object on
one line, and a hang mid-bar still writes the real partial line.
test_watchdog_window_outlasts_the_probe_interval reads both watchdog constants out of
commands.rs, so the heartbeat cannot silently go back to being a no-op if the watchdog is
retuned. test_server_disk_logging.py pins the tee/structlog/first-line order.

cargo test backend_log_line_tests -- 6 passed.

Not exercised: the Colab/embedded path. The one change I could not test there is
run_server's setup_logging call, which now runs at the same point in the sequence as the
tee it follows rather than at import.

Measured on an idle 4h desktop session, tauri.log was 5308 lines / 1.14 MB,
of which 4056 (76%) were request_completed access records and 3355 (63%)
came from six polling endpoints. At ~216 bytes a line the 5 MiB cap fills
in about 18 hours, so a failure from the day before had already rotated
out by the time anyone asked for it.

/api/liveness is the desktop watchdog's own probe, roughly every 19s, and
was in no suppressor at all: 760 lines, 14% of the file, saying the
process is still up. Its sibling /api/health was already quiet. Put it in
_QUIET_POLL_PATHS so it heartbeats; non-2xx still logs every time, which
is the case that matters for a watchdog.

Every backend stdout line is written to disk three times: the backend's
own session log, the diagnostics phase log (stream-tagged and stamped),
and tauri.log. The access records carry nothing in the third copy that
the first two lack, so log them at debug!, below the file target's INFO
filter. Non-JSON output -- the startup banner, "Hardware detected:",
stderr, tracebacks -- keeps INFO, which is what anyone opening tauri.log
is there for. The phase log still gets the unfiltered stream, so the
support report loses nothing.

Also:

- Collapse carriage-return progress frames. Reading to \n means a tqdm bar
  arrives as every frame it drew concatenated onto one line; a single
  "Loading weights" bar measured 5086 bytes across three sinks. Keep the
  final frame, which is the one showing 100% and the elapsed total. Cap
  what reaches tauri.log at 16 KiB, the limit the phase log already used.

- Bound logs/llama-server and logs/diffusion-server. Both directories are
  created per model load and were never pruned (319 files going back two
  months here). The server session log has capped itself since it was
  added, so lift that into utils/log_retention.prune_log_dir and call it
  from all three rather than write the loop a third time.

- Log the top-models catalog at debug. Two lists of 40 repo names, one
  line each, on every boot to say a fetch succeeded; the counts say that.

- Configure structlog in run.py before the first line it logs. main.py
  configures on import, several seconds later, so "run_server startup
  begin" rendered through the defaults (console, local time) and
  everything after it as JSON in UTC -- the clock appeared to jump hours
  between the first and second line of one stream.

Not included: the same carriage-return collapse on the Python tee. Doing
it there means line-buffering the file copy, which would withhold a
partial line from server-*.log exactly when the server hangs mid-write.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@LeoBorcherding LeoBorcherding changed the title Studio: quiet the liveness poll and keep access lines out of tauri.log Unsloth Studio logs: quiet the liveness poll and keep access lines out of tauri.log Aug 14, 2026
LeoBorcherding and others added 2 commits August 13, 2026 22:25
The first pass collapsed carriage-return redraws on the Rust side only. It
left the Python tee alone because doing it there seemed to mean buffering
the file copy until a newline, which would withhold a partial line from
server-*.log exactly when the server hangs mid-write.

It does not have to. Hold back a frame, never a line: an unterminated chunk
containing "\r" is a redraw and is kept until the next one supersedes it,
while an unterminated chunk without one -- a prompt, or a traceback torn by
a hang -- is written the moment it arrives. So the session log gets one
line per bar instead of one per frame, and nothing diagnostic waits on a
newline that may never come.

The console side is untouched: it still sees every frame, which is the
whole point of a progress bar.

Also adds /api/settings/remote-access to the quiet polls (116 lines in the
same 4h sample), for the same reason as the others: it is a plain read of a
toggle, re-read whenever the settings dialog is open.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@LeoBorcherding LeoBorcherding changed the title Unsloth Studio logs: quiet the liveness poll and keep access lines out of tauri.log Unsloth Studio logs: quiet the polls and drop the duplicated access lines Aug 14, 2026
@LeoBorcherding LeoBorcherding changed the title Unsloth Studio logs: quiet the polls and drop the duplicated access lines fix(logs): quiet the polls and drop the duplicated access lines Aug 18, 2026
…hing

Four review findings, all real.

structlog was configured at import, and PrintLoggerFactory snapshots sys.stdout
while cache_logger_on_first_use freezes that snapshot into any logger that has
already logged. run_server's own logger logs at line one and the tee is not
installed until 45 lines later, so every subsequent run.py line -- the orphan
sweep warnings, the whole rest of startup -- was pinned to the console and never
reached the session log. Configure inside run_server instead, after the tee:
the ordering bug the change set out to fix (line one rendering through
structlog's defaults while line two rendered as JSON in UTC) is still fixed,
and the file gets everything from line one. Moving the tee up also means the
orphan sweep now lands on disk, where it was console-only before.

A withheld progress frame was concatenated onto whatever came next, so a
structlog record arriving mid-redraw landed as Loading 47%{"event": ...} and
stopped being parseable. Close the frame off on its own line unless the next
write is its own redraw or its terminator, and land a frame still held at
close() rather than dropping it.

The desktop watchdog polls every 15s (HEALTH_WATCHDOG_INTERVAL) plus up to a
10s probe budget, so _QUIET_POLL_DEDUP_MS at 10s could never close over two
probes and putting /api/liveness in _QUIET_POLL_PATHS collapsed nothing. Give
it its own 60s window, zeroed alongside the quiet window so --verbose still
logs every probe, and pin the floor with a test that reads both constants out
of commands.rs.

is_backend_access_log_line matched on the event name alone, so it also dropped
non-2xx records to debug! -- below tauri.log's INFO filter. Those are the ones
the backend's heartbeat suppressor deliberately exempts, and a watchdog going
red is what tauri.log is read for. Match only 2xx; a record with no status_code
keeps its INFO line too.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Merged latest main (clean) and pushed fixes for all four findings from c748825. All confirmed; none were false positives.

  • run.py structlog caching -- moved LogConfig.setup_logging() out of import scope into run_server, after _setup_server_disk_logging(). PrintLoggerFactory snapshots sys.stdout at configure time, so configuring first pinned the factory and the cached module logger to the pre-tee console and every run.py line after the first went missing from the session log.
  • Held progress frames -- closed off on their own line instead of being prefixed onto the next record, plus flushed at close().
  • Watchdog heartbeat -- /api/liveness gets its own 60s window; the 10s quiet window was narrower than the 15s+ poll and collapsed nothing.
  • Failed access records -- the tauri.log downgrade is now 2xx-only.

Testing: pytest tests/test_logging_middleware.py tests/test_tee_progress_frames.py -- 50 passed (+4), plus 1 new test in test_server_disk_logging.py. cargo test backend_log_line_tests -- 6 passed (+1). The three CI failures on the last run were on a stale base; re-running against the merge.

PR description updated: the "Polls" section described the old /api/liveness mechanism.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed /api/liveness is in none of the suppressor sets in studio/backend/loggers/handlers.py on main, and the unbounded llama-server log directory is real, so the direction here is right. The branch also bundles the tee progress-frame rewrite, the startup logging order change and the retention helper, so could you split those out and land the poll and access-line quieting on its own first? Rust unit tests (windows) in Unsloth Tauri CI is red here and green on main, worth a look.

@danielhanchen

Copy link
Copy Markdown
Member

Went through the head (55c0f66df) properly. The four threads you answered on 08-18 all check out, I found the cause of both red jobs, and there are two things in the tee that are the same class of bug as the one you fixed.

The red CI, both answered

The original run logs have expired (the API 410s on them now), so I replicated the head merged onto current main and ran the full suite there.

Rust unit tests (windows) was the stale base. Green on a current base, along with the macOS and Linux Rust jobs. Nothing to do.

Repo tests (CPU) is real and it is this PR. 15 failures, all the same:

tests/studio/install/test_selection_logic.py::TestStudioLocalhostIpv6Warning
ModuleNotFoundError: No module named 'loggers.config'; 'loggers' is not a package

load_studio_run_module installs a stub loggers as a plain types.ModuleType, so it has no __path__ and cannot satisfy a submodule import. The new from loggers.config import LogConfig at run.py:154 is at module scope, so it blows up at exec_module before any test body runs. That fixture's own comment calls the shape out: "run.py imports this at module scope, so the stub has to carry it or the import of run fails before any test body runs."

LogConfig is used in exactly one place, so the fix is to import it where you use it rather than at module scope:

    from loggers.config import LogConfig

    LogConfig.setup_logging(
        service_name = "unsloth-studio-backend",
        env = os.getenv("ENVIRONMENT_TYPE", "production"),
    )

That is better than widening the stub, which would make run.py's import surface a maintenance burden for a test three directories away. Confirmed locally: 15 failed -> 15 passed, and your 61 backend tests stay green, test_structlog_is_configured_after_the_tee_and_before_the_first_line included.

(The two test_rdna1_unsupported_message_8529.py README failures in that run are staging-repo artifacts, not yours.)

The two open Codex findings

Both still stand on the head.

run.py:2302, the stream leak. Reproduced:

SystemExit: --secure requires the Cloudflare tunnel; do not combine it with --no-cloudflare.
stdout restored: False
stdout type    : _TeeStream
log handle open: True
nested tee     : _TeeStream          <- second run_server() call

On main the same script prints stdout restored: True, so this is a regression from the reorder. Hoisting the if secure and cloudflare is False block to the top of run_server is enough; it reads only the two parameters and nothing before it.

Retention off by one. Measured with 25 pre-existing files and 10 loads: the PR ordering settles at 21, pruning after creation settles at 20. It is bounded either way, so this is an off-by-one rather than the leak it replaces, but the cap should mean what it says. Pruning after the open also lets you protect the file you just created, which matters more than the count: the third call site is inside the spawn-retry loop, and per #8690 the log that explains a failure is often not the newest one.

Two new ones in the tee

Both are the "frame gets glued onto the next record" failure you fixed on 08-18, reached by inputs that round did not cover. Verified against the real _TeeStream.

A zero-length write reopens it.

_tee(["\rLoading weights:  47%", "", '{"event": "model_loaded"}\n'])
# -> 'Loading weights:  47%{"event": "model_loaded"}\n'

data[:1] not in ("", "\r", "\n") reads write("") as a continuation, so the close-off is skipped; the frame then falls through to if tail:, gets written with no newline, and _pending_frame is cleared. print("", end = "") is enough to reach it. Dropping "" from that tuple and returning early on empty data fixes it.

A bar that signs off with a bare \r loses its final frame.

_tee(["Map:  50%\rMap: 100%\r\n", "next\n"])
# -> '\nnext\n'

_last_frame takes rpartition("\r")[2] unconditionally, so an empty trailing frame wins and the whole bar becomes a blank line. The Rust side deliberately does not do this: collapse_progress_frames picks the last non-empty frame and you pinned it with trailing_blank_frame_falls_back_to_the_last_real_one. So the two sinks disagree today, and "Both sides now keep the final frame" in the description is true only for tauri.log. Giving _last_frame the same last-non-empty fallback makes them match.

I checked both fixes together: the two cases pass and all 61 of your tests stay green.

The parts that are right

Worth saying plainly, since the fix round did what it claimed. Driving the middleware with a controlled clock over the PR's own 4h sample at 19s:

probes lines
/api/liveness 2xx, 60s watchdog window 757 190
same with a 10s _QUIET_POLL_DEDUP_MS 757 757
/api/liveness 503 757 757
--verbose 757 757

So the window genuinely collapses the probe, the _QUIET_POLL_PATHS version you rejected really would have been a literal no-op, and failures and --verbose both survive. is_backend_access_log_line is 2xx-only as described, and a record with no status_code keeps INFO.

Two nits: the new backend_log_line_tests module landed between the C:\Windows\system32 comment and the managed_cli_working_dir_tests module it describes, and test_watchdog_window_outlasts_the_probe_interval reads the module-level _WATCHDOG_POLL_DEDUP_MS, so it fails for anyone with UNSLOTH_STUDIO_ACCESS_LOG_WATCHDOG_DEDUP_MS exported.

On the split

Still the ask, and the two tee bugs are the argument for it rather than just my preference. The watchdog window, the /api/settings/remote-access quieting and the Rust 2xx downgrade are measured, well tested and I would take them now. The tee rewrite is the piece where inputs nobody thought of keep turning up, and it is sitting behind them. Land the first group on current main with the lazy LogConfig import, and let the tee, the startup reorder, the 16 KiB cap and the retention helper come separately where each can get the attention it needs.

Three defects in the same file, all found while checking this branch against
main. Tests for each alongside.

1. The tee destroyed every CRLF-terminated line.

_last_frame took rpartition("\r")[2] unconditionally, so the "\r" of a CRLF read
as a redraw boundary whose final frame was empty, and the payload went with it:

    "Hardware detected: NVIDIA GeForce RTX 4090\r\n"          -> "\n"
    "Traceback...\r\n  File \"run.py\"...\r\nRuntimeError\r\n" -> "\n\n\n"

On Windows that is every line a child process relays, so a relayed traceback
landed in the session log as blank lines. It is also exactly the artifact unslothai#8690
added a UI for. The desktop reader already gets this right: trim_line_endings
strips every trailing \r and \n before collapse_progress_frames sees the text.
Mirror it here so the two sinks stay interchangeable for a reader, and fall back
to the last non-blank frame the same way, so a bar that signs off with a bare \r
keeps its 100% frame instead of writing a blank line.

Also: a "\r" must never reach the file. The handle appends the platform
terminator itself, so one that survives lands as "\r\r\n" on Windows.

2. A zero-length write reopened the record corruption fixed on 08-18.

`data[:1] not in ("", "\r", "\n")` read write("") as a continuation of the held
frame, so the close-off was skipped, the frame fell through to the unterminated
branch, and the next record was glued onto it:

    ["\rLoading weights:  47%", "", '{"event": "model_loaded"}\n']
    -> 'Loading weights:  47%{"event": "model_loaded"}'

print("", end = "") is enough to reach it. Return early on empty data instead.

3. A rejected flag combination left the streams swapped.

--secure --no-cloudflare is a deterministic preflight failure, but it now runs
after _setup_server_disk_logging() has replaced sys.stdout and sys.stderr and
opened a log handle, and nothing unwinds either. An embedder that catches the
SystemExit keeps the tee, and its next run_server() call nests a second one, so
every line is written twice. main does not do this. Validate before the tee.

4. `from loggers.config import LogConfig` at module scope broke Repo tests (CPU).

15 failures in tests/studio/install/test_selection_logic.py, all
"No module named 'loggers.config'; 'loggers' is not a package".
load_studio_run_module stands a bare types.ModuleType in for `loggers` before
exec'ing run.py; a bare module has no __path__, so the import fails during
collection and takes every test in the file with it. That fixture's own comment
names the hazard. LogConfig has one use, inside run_server, so import it there
rather than widening a stub three directories away.
Two problems with prune_log_dir as it stands.

The cap never held. All three call sites prune before creating the log, so with
keep=20 the directory settles at 21 and every load repeats the prune-to-20,
create-the-21st cycle. Measured with 25 seeded files and 10 loads: 21 with this
ordering, 20 when the prune runs after the open.

And one odd directory entry disabled retention entirely. The mtime sort ran
inside a single try/except, so a dangling symlink matching the glob raised on
stat() and the whole call returned having deleted nothing. Seeded with 30 files
plus one broken link, keep=5 left all 30. That is the unbounded growth this
helper exists to stop, reintroduced by one bad name. Stat failures are now
per-entry.

Only regular files count now, too: a directory that happens to match the glob
was taking one of the kept slots (25 files plus one such directory, keep=5, left
4 real logs).

prune_log_dir grows a `protect` argument, and the call sites move to after the
open. `protect` is never deleted and counts as one of the `keep`, so the total
stays at keep. It is not enough to trust the new file to sort newest: two loads
in the same second, or a clock that steps back, and it does not.

The retry call site benefits most. The comment right above it explains that the
-try{n} suffix exists so a respawn within the same second cannot truncate the
crash log a retry warning just pointed the user at; pruning before the open on
every attempt worked against that.

New tests cover keep values, the protected file counting toward the cap and
surviving even when it sorts oldest, dangling symlinks, symlinks pointing
outside the directory, directories matching the glob, identical mtimes, family
isolation, and a writer appending across a prune.
collapse_progress_frames is correct on CRLF because trim_line_endings runs
first, but nothing pinned that, and the Python tee that writes the backend's own
session log got it wrong. Add the cases that hold the two implementations
together: a CRLF payload keeps its text, a CRLF-terminated bar still collapses, a
CRLF JSON record stays parseable and still classifies, a TAURI_PORT marker
survives the collapse whether or not it shares its line with a redraw, and an
all-blank line never keeps a carriage return. Plus the 16 KiB truncation landing
on a character boundary for multi-byte text.

The fallback for an all-blank line returned the whole text, which still holds the
\r the caller asked to collapse away. Return the last frame instead.

Two comment fixes. The new test module had been inserted between the
C:\Windows\system32 comment and the managed_cli_working_dir_tests module it
describes; move it back. And record what debug! actually does for a matched
record: setup_logging in main.rs builds every logger at LevelFilter::Info and
there is no RUST_LOG or any other way to raise it, so log::max_level() is Info
and a matched record is dropped outright rather than demoted, including under
backend --verbose, which makes it emit more of them. That is fine, but it is not
obvious from the call site, and the surrounding comment argued the opposite case
for non-2xx. The records are still written verbatim to the diagnostics phase log
(append_phase_line runs before this decision) and to the backend session log,
both of which the support report and Settings > Logs already offer.

Separately, test_watchdog_window_outlasts_the_probe_interval read the module
global, so it failed for anyone with UNSLOTH_STUDIO_ACCESS_LOG_WATCHDOG_DEDUP_MS
exported; read the default instead. Its two regex lookups now report what moved
in commands.rs rather than raising AttributeError on .group(1).
@danielhanchen

Copy link
Copy Markdown
Member

Pushed three commits to this branch (26cbb966c). Both red jobs are accounted for, and I found one more defect in the tee that is worse than the two I reported last time. Details below, including what I could and could not establish from a Linux host.

Before and after, measured

Driving the real LoggingMiddleware with a controlled clock over a 4h idle session, main vs this branch:

path cadence main this PR
/api/liveness 19s 757 190
/api/settings/remote-access 3s 4800 1200
the other ten polls 3-10s 14400 14400
total 19957 15790

So the access-log change is a 21% cut and all of it comes from those two paths. Everything already in _QUIET_POLL_PATHS is untouched, which is worth saying because the raw poll counts make the reduction look bigger than it is. On top of that, tauri.log separately loses the successful request_completed records, which on your sample were 4056 of 5308 lines. That is the larger effect on the desktop log.

The problem is real on all three counts I checked. /api/liveness is in no suppressor on main. logs/llama-server has no pruning on main at all. And structlog's PrintLoggerFactory(file = sys.stdout) does snapshot the stream at configure() time, which is what the startup reorder fixes.

Both red jobs, resolved

Rust unit tests (windows): green. It was the stale base. macOS and Linux Rust are green too. I also added CRLF and marker tests to process.rs so those runners now actually exercise the frame logic.

Repo tests (CPU): the PR's share is fixed. The Repo tests (CPU, auto-discovered) step went from 17 failed / 10649 passed to 10668 passed, 0 failed, and loggers.config appears zero times in the log.

The job is still red, at a later step, and that one is not yours. Shell installer tests fails on:

FAIL: README: Launch section documents -H 0.0.0.0 opt-in (expected to find '0.0.0.0')

tests/sh/test_install_host_defaults.sh:102 asserts the README's #### Launch section mentions 0.0.0.0. It does not, on main, today. Repo tests (CPU) has failed on that exact step on the last six consecutive main runs. Separate fix, and it is currently red for every open PR. Chat UI Tests (banner) is red on main too.

The new defect: the tee destroyed CRLF lines

_last_frame took rpartition("\r")[2] unconditionally, so the \r of a CRLF read as a redraw boundary whose final frame was empty, and the payload went with it. Against the real class:

"Hardware detected: NVIDIA GeForce RTX 4090\r\n"                -> "\n"
'Traceback...\r\n  File "run.py"...\r\nRuntimeError: boom\r\n'  -> "\n\n\n"

On Windows that is every line a child process relays. A relayed traceback landed in the session log as blank lines, which is precisely the artifact #8690 added a UI for. The desktop reader already gets this right, because trim_line_endings strips every trailing \r and \n before collapse_progress_frames sees the text. I mirrored that here, with the same last-non-blank-frame fallback, so the two sinks stay interchangeable for a reader. There is now a parity suite over ~23 inputs asserting the Python tee and a port of the Rust pipeline agree line for line.

The zero-length-write case and the bare-\r sign-off case from my last comment are fixed in the same commit.

The two Codex findings

Both fixed, both reproduced first.

Stream leak. --secure --no-cloudflare now prints stdout restored: True where it printed False, and a second run_server() no longer nests a _TeeStream inside a _TeeStream. main never did this, so it was a regression from the reorder. The validation now runs before anything touches a process global.

Retention. Prunes after the open, with the new file passed as protect, so it counts toward the cap and can never be deleted. 319 seeded files plus 5 loads now settles at 20 rather than 21.

While testing that I found two more things in the same helper. A dangling symlink matching the glob raised inside the mtime sort, and the single wrapping except OSError turned that into "this directory is never pruned again" - 30 files, keep=5, 30 left. That is the unbounded growth the helper exists to stop, reintroduced by one bad name. And a directory matching the glob was taking one of the kept slots. Stat failures are per-entry now and only regular files count.

The retry call site benefits most from the reorder: the comment above it explains that the -try{n} suffix exists so a respawn within the same second cannot truncate the crash log a retry warning just pointed the user at, and pruning before the open on every attempt worked against that.

Does it break anything

I traced every consumer. Nothing anywhere reads, parses, counts or asserts on request_completed lines in tauri.log - not the support report, not debug_log_sources.py, not the Settings > Logs viewer, not the frontend, not the CI greps in desktop-app-clean-machine-ci.yml, no test. The records are still written verbatim to the diagnostics phase log (append_phase_line runs before the level decision) and to the backend session log, both of which the support report and the log picker already offer. Nothing is lost; it moves one source over in the picker.

One thing worth knowing rather than fixing: setup_logging in main.rs builds every logger at LevelFilter::Info and there is no RUST_LOG or any other way to raise it, so log::max_level() is Info and a matched record is dropped outright rather than demoted, including under backend --verbose, which makes the backend emit more of them. I put that in the comment at the call site, since the surrounding text argued the opposite case for non-2xx and now read as self-contradictory.

Old installs are fine. Simulated a two-month home: 319 llama-*.log, an old session log, a tauri.log, none of the new env vars set. The viewer enumerates before and after the first prune, the newest previous attempt survives, default_source_id still resolves, a source the prune removed comes back as None rather than a traceback, and the diffusion and llama families do not prune each other. The new env var is optional and a malformed value falls back rather than crashing.

main.py:816 still configures structlog at import scope, so the import-only entry points (uvicorn main:app, scripts/profile_startup.py, colab.py:77) are unaffected by the reorder.

Testing

I built a simulation harness of 576 cases in a clean uv venv: the tee write matrix (terminator x content x chunking x stream x ending), Rust/Python frame parity, an OS matrix, the retention matrix, an old-install upgrade sim, the access-log volume table, an entry-point matrix, and an import guard.

44 failed on the branch as it stood. 576 pass now.

Regression, attributed against the unmodified head rather than assumed:

  • studio/backend/tests: 209 failures before, 209 after, and the two that differ pass 3/3 in isolation on both trees. Load-dependent flakes under -n 4, not the fixes. (One of them, test_a_failing_warm_stage_is_reported_not_swallowed, also flaked in CI.)
  • tests/studio at the repo root: 72 failures before, 57 after. Exactly the 15 loggers.config tests, zero new.
  • The four directly affected backend test files: 90 passed.

The PR now carries its own regression tests for each fix: CRLF, parity, zero-length write and blank-frame cases in test_tee_progress_frames.py; a new test_log_retention.py covering keep values, the protected file counting toward the cap and surviving when it sorts oldest, dangling symlinks, symlinks pointing outside the directory, directories matching the glob, identical mtimes and a writer appending across a prune; an AST guard and two stream-leak tests in test_server_disk_logging.py; and the CRLF/marker/truncation cases in process.rs.

Platforms and browsers

I ran the branch merged onto current main through Windows, macOS and Linux runners. startup and parity pass on all three, setup.ps1 passes on Windows, Rust passes on Windows and macOS, and the cross-browser Playwright job passes. The PR touches no frontend file, so the browser surface is limited to the Logs viewer still rendering, which that job covers.

Being straight about the limits. The five desktop * jobs fail at "Download the shipped bundle", because a staging fork has no release artifacts; that is the harness, not the code. test_watchdog_window_outlasts_the_probe_interval also now reads the default rather than the module global, so it stops failing for anyone with UNSLOTH_STUDIO_ACCESS_LOG_WATCHDOG_DEDUP_MS exported.

There is no hardware axis here to test. I checked mechanically: the diff contains no CUDA, ROCm, Metal, XPU or device-count branch, and its only platform branch is the sys.platform == "win32" stdout reconfigure. The three prune call sites behave identically whichever runtime opened the log. So the [Windows, Linux, WSL, macOS] x [NVIDIA, AMD, CPU-only] product collapses to the OS axis above, and I did not pretend to run the rest.

Still worth splitting

The four answered threads hold up, and with these fixes I would take the whole thing. But the tee is still the piece where inputs nobody considered keep turning up: three separate defects in it now, two of them the same corruption reopened by a different input. Landing the watchdog window, the /api/settings/remote-access quieting and the Rust 2xx downgrade first, and letting the tee, the startup reorder, the 16 KiB cap and the retention helper follow separately, would give the risky half the attention it has been earning. Your call, and it is not a blocker from me.

Comment-only pass over the 10 files the PR touches. No code change: the AST gate
(comment_tools.py check --strip-docstrings) reports 9/9 files comments-only, the
Rust file has no non-comment line in the diff, and no docstring was dropped.

114 insertions, 142 deletions. Heaviest in run.py and process.rs, where the same
explanation was being given twice, once in a doc comment and again at the call
site. Every load-bearing why is kept: the structlog factory/cache ordering, why a
CRLF terminator is not a redraw, why the watchdog window has to outlast the poll,
why prune runs after the open, and what debug! means for a matched record.
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 24, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 24, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: d2b64c363c

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from LeoBorcherding Aug 24, 2026
@unslothai unslothai deleted a comment from LeoBorcherding Aug 24, 2026
@unslothai unslothai deleted a comment from LeoBorcherding Aug 24, 2026
@unslothai unslothai deleted a comment from LeoBorcherding Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 24, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Verified this on top of the Codex pass. Summary for anyone picking it up.

Codex approved d2b64c363c. The only commit after that is a pre-commit-ci formatting commit (64f39eec8), so the approval still stands on the current head, with no open review items.

What was checked beyond the review:

  • Before and after on the access log, driving the real middleware over the PR's own 4h sample: /api/liveness goes 757 to 190 lines, /api/settings/remote-access 4800 to 1200. Mutations, non-2xx responses and --verbose are untouched.
  • The 2xx request_completed records that stop reaching tauri.log still land in the diagnostics phase log and the backend session log, both already surfaced by the support report and by Settings > Logs. Nothing parses or asserts on them.
  • No hardware path is involved. The diff has no CUDA, ROCm, Metal or XPU branch; the only platform branch is the win32 stdout reconfigure.
  • Cross-platform: the backend log suites were run on Windows, macOS and Linux runners in a staging replica, and the Rust unit tests are green on windows and macos here.

Fixes pushed to the branch during the review, each with tests alongside:

  • _TeeStream._last_frame destroyed any CRLF terminated payload, so a relayed Windows subprocess traceback became blank lines in the session log.
  • A zero-length write (print("", end = "")) flushed a held progress frame without a newline, splicing it into the next JSON record.
  • A module-scope from loggers.config import LogConfig in run.py broke 15 tests in tests/studio/install/test_selection_logic.py, whose fixture stubs loggers as a bare module.
  • run_server left sys.stdout and sys.stderr swapped when the --secure / --no-cloudflare check raised SystemExit.
  • prune_log_dir pruned before creating the new file, so the directory settled at keep+1, and one dangling symlink matching the glob aborted the entire prune.

Two findings that are not this PR's and are deliberately left alone:

  1. studio/backend/tests/test_server_disk_logging.py::TestNormalizeStandardStreams::test_missing_streams_become_usable_text_streams asserts stream.isatty() is False and fails on Windows. The identical assertion is present unchanged at the merge base, so it predates this branch. On Windows isatty() goes to the MSVCRT _isatty, which reports true for any character device, and NUL is one (https://bugs.python.org/issue28654). Worth fixing separately.
  2. Chat UI Tests (banner) is red on three consecutive runs with the same sh: 1: vite: not found and vite exited with code 127 in the Playwright step, while the banner assertions themselves pass (1433 and 221 checks, 0 failed). A staging run of the same commit names the cause outright: the frontend dev dependencies are not installed at studio/frontend/node_modules. This PR touches no frontend or node files.

@danielhanchen
danielhanchen merged commit 7a48774 into unslothai:main Aug 25, 2026
69 of 72 checks passed
danielhanchen added a commit that referenced this pull request Aug 25, 2026
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.
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: quiet the liveness poll and keep access lines out of tauri.log

Measured on an idle 4h desktop session, tauri.log was 5308 lines / 1.14 MB,
of which 4056 (76%) were request_completed access records and 3355 (63%)
came from six polling endpoints. At ~216 bytes a line the 5 MiB cap fills
in about 18 hours, so a failure from the day before had already rotated
out by the time anyone asked for it.

/api/liveness is the desktop watchdog's own probe, roughly every 19s, and
was in no suppressor at all: 760 lines, 14% of the file, saying the
process is still up. Its sibling /api/health was already quiet. Put it in
_QUIET_POLL_PATHS so it heartbeats; non-2xx still logs every time, which
is the case that matters for a watchdog.

Every backend stdout line is written to disk three times: the backend's
own session log, the diagnostics phase log (stream-tagged and stamped),
and tauri.log. The access records carry nothing in the third copy that
the first two lack, so log them at debug!, below the file target's INFO
filter. Non-JSON output -- the startup banner, "Hardware detected:",
stderr, tracebacks -- keeps INFO, which is what anyone opening tauri.log
is there for. The phase log still gets the unfiltered stream, so the
support report loses nothing.

Also:

- Collapse carriage-return progress frames. Reading to \n means a tqdm bar
  arrives as every frame it drew concatenated onto one line; a single
  "Loading weights" bar measured 5086 bytes across three sinks. Keep the
  final frame, which is the one showing 100% and the elapsed total. Cap
  what reaches tauri.log at 16 KiB, the limit the phase log already used.

- Bound logs/llama-server and logs/diffusion-server. Both directories are
  created per model load and were never pruned (319 files going back two
  months here). The server session log has capped itself since it was
  added, so lift that into utils/log_retention.prune_log_dir and call it
  from all three rather than write the loop a third time.

- Log the top-models catalog at debug. Two lists of 40 repo names, one
  line each, on every boot to say a fetch succeeded; the counts say that.

- Configure structlog in run.py before the first line it logs. main.py
  configures on import, several seconds later, so "run_server startup
  begin" rendered through the defaults (console, local time) and
  everything after it as JSON in UTC -- the clock appeared to jump hours
  between the first and second line of one stream.

Not included: the same carriage-return collapse on the Python tee. Doing
it there means line-buffering the file copy, which would withhold a
partial line from server-*.log exactly when the server hangs mid-write.

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

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

* Collapse progress frames in the session log too, and quiet remote-access

The first pass collapsed carriage-return redraws on the Rust side only. It
left the Python tee alone because doing it there seemed to mean buffering
the file copy until a newline, which would withhold a partial line from
server-*.log exactly when the server hangs mid-write.

It does not have to. Hold back a frame, never a line: an unterminated chunk
containing "\r" is a redraw and is kept until the next one supersedes it,
while an unterminated chunk without one -- a prompt, or a traceback torn by
a hang -- is written the moment it arrives. So the session log gets one
line per bar instead of one per frame, and nothing diagnostic waits on a
newline that may never come.

The console side is untouched: it still sees every frame, which is the
whole point of a progress bar.

Also adds /api/settings/remote-access to the quiet polls (116 lines in the
same 4h sample), for the same reason as the others: it is a plain read of a
toggle, re-read whenever the settings dialog is open.

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

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

* Install the tee before structlog, and stop three suppressors overreaching

Four review findings, all real.

structlog was configured at import, and PrintLoggerFactory snapshots sys.stdout
while cache_logger_on_first_use freezes that snapshot into any logger that has
already logged. run_server's own logger logs at line one and the tee is not
installed until 45 lines later, so every subsequent run.py line -- the orphan
sweep warnings, the whole rest of startup -- was pinned to the console and never
reached the session log. Configure inside run_server instead, after the tee:
the ordering bug the change set out to fix (line one rendering through
structlog's defaults while line two rendered as JSON in UTC) is still fixed,
and the file gets everything from line one. Moving the tee up also means the
orphan sweep now lands on disk, where it was console-only before.

A withheld progress frame was concatenated onto whatever came next, so a
structlog record arriving mid-redraw landed as Loading 47%{"event": ...} and
stopped being parseable. Close the frame off on its own line unless the next
write is its own redraw or its terminator, and land a frame still held at
close() rather than dropping it.

The desktop watchdog polls every 15s (HEALTH_WATCHDOG_INTERVAL) plus up to a
10s probe budget, so _QUIET_POLL_DEDUP_MS at 10s could never close over two
probes and putting /api/liveness in _QUIET_POLL_PATHS collapsed nothing. Give
it its own 60s window, zeroed alongside the quiet window so --verbose still
logs every probe, and pin the floor with a test that reads both constants out
of commands.rs.

is_backend_access_log_line matched on the event name alone, so it also dropped
non-2xx records to debug! -- below tauri.log's INFO filter. Those are the ones
the backend's heartbeat suppressor deliberately exempts, and a watchdog going
red is what tauri.log is read for. Match only 2xx; a record with no status_code
keeps its INFO line too.

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

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

* run.py: keep CRLF lines, stop leaking the tee, import LogConfig lazily

Three defects in the same file, all found while checking this branch against
main. Tests for each alongside.

1. The tee destroyed every CRLF-terminated line.

_last_frame took rpartition("\r")[2] unconditionally, so the "\r" of a CRLF read
as a redraw boundary whose final frame was empty, and the payload went with it:

    "Hardware detected: NVIDIA GeForce RTX 4090\r\n"          -> "\n"
    "Traceback...\r\n  File \"run.py\"...\r\nRuntimeError\r\n" -> "\n\n\n"

On Windows that is every line a child process relays, so a relayed traceback
landed in the session log as blank lines. It is also exactly the artifact #8690
added a UI for. The desktop reader already gets this right: trim_line_endings
strips every trailing \r and \n before collapse_progress_frames sees the text.
Mirror it here so the two sinks stay interchangeable for a reader, and fall back
to the last non-blank frame the same way, so a bar that signs off with a bare \r
keeps its 100% frame instead of writing a blank line.

Also: a "\r" must never reach the file. The handle appends the platform
terminator itself, so one that survives lands as "\r\r\n" on Windows.

2. A zero-length write reopened the record corruption fixed on 08-18.

`data[:1] not in ("", "\r", "\n")` read write("") as a continuation of the held
frame, so the close-off was skipped, the frame fell through to the unterminated
branch, and the next record was glued onto it:

    ["\rLoading weights:  47%", "", '{"event": "model_loaded"}\n']
    -> 'Loading weights:  47%{"event": "model_loaded"}'

print("", end = "") is enough to reach it. Return early on empty data instead.

3. A rejected flag combination left the streams swapped.

--secure --no-cloudflare is a deterministic preflight failure, but it now runs
after _setup_server_disk_logging() has replaced sys.stdout and sys.stderr and
opened a log handle, and nothing unwinds either. An embedder that catches the
SystemExit keeps the tee, and its next run_server() call nests a second one, so
every line is written twice. main does not do this. Validate before the tee.

4. `from loggers.config import LogConfig` at module scope broke Repo tests (CPU).

15 failures in tests/studio/install/test_selection_logic.py, all
"No module named 'loggers.config'; 'loggers' is not a package".
load_studio_run_module stands a bare types.ModuleType in for `loggers` before
exec'ing run.py; a bare module has no __path__, so the import fails during
collection and takes every test in the file with it. That fixture's own comment
names the hazard. LogConfig has one use, inside run_server, so import it there
rather than widening a stub three directories away.

* Prune the log directories after opening the new file, and protect it

Two problems with prune_log_dir as it stands.

The cap never held. All three call sites prune before creating the log, so with
keep=20 the directory settles at 21 and every load repeats the prune-to-20,
create-the-21st cycle. Measured with 25 seeded files and 10 loads: 21 with this
ordering, 20 when the prune runs after the open.

And one odd directory entry disabled retention entirely. The mtime sort ran
inside a single try/except, so a dangling symlink matching the glob raised on
stat() and the whole call returned having deleted nothing. Seeded with 30 files
plus one broken link, keep=5 left all 30. That is the unbounded growth this
helper exists to stop, reintroduced by one bad name. Stat failures are now
per-entry.

Only regular files count now, too: a directory that happens to match the glob
was taking one of the kept slots (25 files plus one such directory, keep=5, left
4 real logs).

prune_log_dir grows a `protect` argument, and the call sites move to after the
open. `protect` is never deleted and counts as one of the `keep`, so the total
stays at keep. It is not enough to trust the new file to sort newest: two loads
in the same second, or a clock that steps back, and it does not.

The retry call site benefits most. The comment right above it explains that the
-try{n} suffix exists so a respawn within the same second cannot truncate the
crash log a retry warning just pointed the user at; pruning before the open on
every attempt worked against that.

New tests cover keep values, the protected file counting toward the cap and
surviving even when it sorts oldest, dangling symlinks, symlinks pointing
outside the directory, directories matching the glob, identical mtimes, family
isolation, and a writer appending across a prune.

* process.rs: CRLF and marker tests, and say what debug! means here

collapse_progress_frames is correct on CRLF because trim_line_endings runs
first, but nothing pinned that, and the Python tee that writes the backend's own
session log got it wrong. Add the cases that hold the two implementations
together: a CRLF payload keeps its text, a CRLF-terminated bar still collapses, a
CRLF JSON record stays parseable and still classifies, a TAURI_PORT marker
survives the collapse whether or not it shares its line with a redraw, and an
all-blank line never keeps a carriage return. Plus the 16 KiB truncation landing
on a character boundary for multi-byte text.

The fallback for an all-blank line returned the whole text, which still holds the
\r the caller asked to collapse away. Return the last frame instead.

Two comment fixes. The new test module had been inserted between the
C:\Windows\system32 comment and the managed_cli_working_dir_tests module it
describes; move it back. And record what debug! actually does for a matched
record: setup_logging in main.rs builds every logger at LevelFilter::Info and
there is no RUST_LOG or any other way to raise it, so log::max_level() is Info
and a matched record is dropped outright rather than demoted, including under
backend --verbose, which makes it emit more of them. That is fine, but it is not
obvious from the call site, and the surrounding comment argued the opposite case
for non-2xx. The records are still written verbatim to the diagnostics phase log
(append_phase_line runs before this decision) and to the backend session log,
both of which the support report and Settings > Logs already offer.

Separately, test_watchdog_window_outlasts_the_probe_interval read the module
global, so it failed for anyone with UNSLOTH_STUDIO_ACCESS_LOG_WATCHDOG_DEDUP_MS
exported; read the default instead. Its two regex lookups now report what moved
in commands.rs rather than raising AttributeError on .group(1).

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

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

* Tighten the comments this PR adds

Comment-only pass over the 10 files the PR touches. No code change: the AST gate
(comment_tools.py check --strip-docstrings) reports 9/9 files comments-only, the
Rust file has no non-comment line in the diff, and no docstring was dropped.

114 insertions, 142 deletions. Heaviest in run.py and process.rs, where the same
explanation was being given twice, once in a doc comment and again at the call
site. Every load-bearing why is kept: the structlog factory/cache ordering, why a
CRLF terminator is not a redraw, why the watchdog window has to outlast the poll,
why prune runs after the open, and what debug! means for a matched record.

* [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>
Co-authored-by: Daniel Han <[email protected]>
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 26, 2026
…ys on the GPU (#9675)

* studio: placement planner that spills weights with -ot, never the cache

llama.cpp's --fit spills whole layers through n_gpu_layers, and a layer's KV
cache is allocated on model.dev_layer(il), so spilling a layer takes its cache
to host RAM with it. Measured at 128K on one B200: weights spilled with the
cache resident runs 71.63 t/s, the reverse runs 3.24. -ot overrides tensor
buffer types without touching layer assignment, so the cache stays put, and
that is what this plans.

Three pieces:

- offload_layout.py reads a GGUF into the buckets that decide placement:
  spillable per block, resident per block, lm_head, token_embd (which llama.cpp
  pins to the CPU unconditionally and so is never VRAM), the attention cache
  per token over the attention layers only, and the Mamba recurrent state.

- offload_planner.py picks the placement: nothing spilled if it fits, then the
  minimum set of blocks, then lm_head. Never -ngl and never --no-kv-offload.

- offload_cost_model.py prices a candidate in milliseconds per token, and the
  planner reports that on every plan. Time, not percentages: lm_head reads as
  43 percent alone and 16 percent on top of FFN, which looks sub-additive,
  while the same bytes cost 10.206 ms alone and 14.428 on top.

The cost model takes a host profile because spilled decode runs on the CPU
backend: ggml migrates an op to the GPU only at batch >= 32 and decode is batch
1, so the penalty tracks core count (2.42 / 5.83 / 11.82 / 14.94 t/s at 4 / 16
/ 64 / 192 threads). A planner blind to that gives desktop users server advice.

Unified memory hosts abstain outright, since there spilling moves bytes between
two names for the same chips.

* studio: wire the spill planner into the launch path, gated and off by default

The seam is the elif use_fit: arm and nothing else. That arm is entered because
_select_gpus already gave up, so it is the one place Studio has admitted it
cannot place the model; the manual and proved arms have placement decided and
must not be re-placed.

It emits -ngl -1 --fit off plus one -ot per pattern. Each token is load bearing:

- --fit off is required, not tidiness. The fitter aborts only on an
  n_gpu_layers the user really set (common/fit.cpp), and -1 is llama.cpp's own
  default (llama-model.cpp), so -ngl -1 does not hold it off. Left enabled it
  would re-place layers over the plan and put the cache back on the host, which
  is the thing this exists to prevent.
- -ngl -1 keeps every layer assigned to a GPU, so dev_layer stays a GPU and the
  cache is allocated there.
- One flag per pattern. llama-server accumulates repeated -ot and splits an -ot
  VALUE on a comma. Joining with a semicolon is llama-bench syntax and would be
  read as a single pattern.

The planner declines whenever anything else owns placement: a user -ot or
--cpu-moe, a layer count, a device list, any explicit --fit, or the env twin of
each. Declining reproduces today's argv byte for byte, which is the safety
argument: pricing a placement the child will not get is the bug class behind
most of the load-mode review traffic.

Shared devices are dropped from the credit rather than summed, since an APU or
iGPU reports host RAM as its VRAM and crediting both counts one pool twice.
Host threads are read from the machine, because spilled decode runs on the CPU
backend and its cost tracks core count.

The plan is revoked once, inside _spawn_and_wait, rather than at each retry
site, so a recovery path added later is covered without anyone remembering.

Gated behind UNSLOTH_SMART_OFFLOAD, default off.

* studio: do not count the MTP block as spillable

Caught running the planner's own output against llama-server rather than
against the unit tests. The plan for a 16 GiB budget named 16 blocks totalling
2.8378 GiB, and the child moved 2.633 GiB. The 209 MiB gap is exactly the three
FFN tensors of blk.64, the nextn/MTP block.

Confirmed directly: spilling ONLY that block leaves the host buffer at exactly
token_embd (682.03 MiB) and the device buffer unchanged at 15718.48 MiB. Those
tensors are not part of the target model and llama.cpp does not load them unless
a draft is engaged, so an -ot pattern naming them moves nothing.

The direction is the dangerous one. The planner believed it had freed 209 MiB
more than it did, which is how a load that does not fit gets planned as one that
does. Studio prices the drafter separately, so dropping the trailing nextn
blocks from the block list is the whole fix.

The measured-bucket test pinned the pre-fix totals, since the earlier hand
arithmetic also counted all 65 blocks. Corrected to the real numbers: Q4
spillable 9.888 and block-resident 4.491 GiB, Q2 5.291 and 2.471.

* Drop workspace design notes from the branch

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

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

* studio: stop the cost model under-pricing spills on small hosts

Measured against real hardware rather than the one machine the model was fitted
on. 70 runs on T4, L4, A100 and RTX PRO 6000 at 2, 8, 12 and 48 vCPU, over
Qwen3.8-27B and Qwen3.6-35B-A3B at Q2_K_XL, Q4_K_XL and Q8_K_XL, comparing the
predicted generation penalty against the measured one:

  48 cpu   1.09 median      12 cpu   0.59 median
   8 cpu   0.24 median       2 cpu   0.24 median

Accurate on a big host, optimistic by up to four times on a small one, and
optimistic is the direction that quotes a spill which then runs several times
slower than promised.

The cause is that the shipped fit varies THREADS ON ONE MACHINE. Twelve cloud
vCPUs are roughly six physical cores sharing one memory controller, not twelve
threads of a 192 core server, so the slope across machines is steeper. Fitting
dense Q4 on the 12 and 48 vCPU hosts gives a = 278.2 and b = 1.03 against the
shipped 138.4 and 5.57.

Neither fit dominates. At 192 threads the cross-machine line predicts 2.48 ms
per GiB against 5.498 measured, and at 12 the one-machine line predicts 17.1
against 24.21 measured, so the rate now takes whichever is more expensive. That
keeps the reference host's own validated numbers (1.01 at 192, 1.09 at 48) and
lifts 12 vCPU from 0.59 to 0.88.

One residual is left in place and named rather than tuned away. Cost per spilled
GiB is ordered by dequant complexity, not by byte count: at 12 vCPU the measured
rates are Q2_K 84.17, Q4_K 24.21 and Q8 19.96 ms per GiB, so Q8 is the cheapest
per GiB despite being the largest format. A quant multiplier is the obvious next
step, but the multiplier itself moves with core count, 3.5x at 12 vCPU against
1.3x at 48, and fitting that from two core counts would be overfitting. Dense
Q2_K on a very small host therefore remains under-priced, and the comment says
so.

test_a_smaller_host_makes_every_spill_worse asserted the old shortfall, that the
model under-warns at 16 threads by about 22 percent. It now predicts 2.93x
against a measured 2.885x, so the assertion is inverted to require no
under-warning and bounded at 10 percent over, which is the side worth being on.

* studio: do not emit spill flags for a plan that spills nothing

Four defects from the first review round, all in the optimistic direction.

The seam gated on `if _spill:`. Plan is a dataclass with no __bool__ or
__len__, so every instance is truthy, including the ones plan_placement returns
to say it could NOT place the load. There are six such returns: incomplete
layout, unified memory, no creditable VRAM, no usable context, insufficient, and
the rung where the load already fits. Each of those appended
-ngl -1 --fit off with no -ot at all, which switches llama.cpp's fitter off and
pins every layer to the GPU on exactly the loads the planner had just declined.
On a host that cannot fit, that is an OOM where --fit on would have placed the
model. It also made the PR's compatibility claim false: declining did not
reproduce the previous argv. Now gated on a plan that actually spills something.

The measured KV cache size was computed and never used. layout.kv_bytes
under-estimates on an f32 cache, on flash-attn-off V padding, and worst on MLA,
where the estimate prices a K-only latent against the layout's full K+V pair.
The measured value is now a floor under the estimate, taken as a max rather than
an equality because cell padding rounds to 256 and the two will not agree
exactly.

A startup failure on the first spawn had no recovery. The revocation at the top
of _spawn_and_wait needs a label, which is empty on the first spawn;
fully_gpu_offloaded is only set in the gpu_indices arm; and
_fit_off_retry_eligible returns False on use_fit, which is this arm's own
condition. All three miss, so the loop fell through to the terminal fallbacks
with the plan still applied. A third recovery now shares the existing retry slot.

A split GGUF was planned from one shard. GGUFReader memory-maps a single file
and has no split handling, while llama.cpp reads split.count and loads every
sibling, so the layout saw a fraction of the tensors. Studio passes the main
shard and already sums all siblings for the model size, so the two disagreed
silently. The planner now abstains when split.count says there are siblings.

One item was rejected. Emitting the planner's chosen load mode is real but
pessimistic: mmap costs throughput and cannot turn a fit into an OOM. It is also
not a one-line change, since --load-mode is owned by the memory policy on this
path and a bare extend would overturn a user's keep-resident setting.

Two test-quality problems came out of this. test_a_floor_that_does_not_fit
asserted insufficient on the returned plan, which is true with or without the
bug, so it passed while the seam was broken. And the test that was supposed to
defend the compatibility claim asserted the SOURCE TEXT of the else branch,
which is why it also passed while the abstain path was emitting --fit off. Both
now drive the real flag builder. A third test pinned a multi-token argv literal
through inspect.getsource, the same shape that broke CI on the sibling PR when
the formatter rewrapped it; it is now behavioural too.

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

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

* studio: raise the per-device overhead reserve to cover the prefill buffer

Measured on Colab A100 and RTX PRO 6000. At depth 32768 the dense 27B failed to
load on every budget with the plan reporting insufficient=False:

  ggml_backend_cuda_buffer_type_alloc_buffer: allocating 594.16 MiB on
  device 0: cudaMalloc failed: out of memory
  llama_init_from_model: failed to allocate compute pp buffers

It failed consistently rather than randomly, which is what made it easy to miss.
The planner fills to budget minus the reserve, so whenever it spills it leaves
exactly the reserve free WHATEVER the budget is, and 6, 7, 8 and 10 GiB budgets
therefore died with the identical shortfall.

The child needs the prefill compute buffer, 594 MiB there, plus its own CUDA
primary context, which is what consumed the rest of the old 1 GiB. That puts the
requirement just over 1.07 GiB. 1.5 GiB covers it with margin.

Ruled out first: this is not fragmentation from the benchmark pinning VRAM to
force a smaller card. Rerunning the same case with 16, 64 and 1024 MiB hog
blocks reproduced the identical 594.16 MiB failure, so the hog's block size is
not what runs out. The native runs that passed did so only because the model
fitted whole and left real headroom, which is not a test of the spilling path.

It is a measured floor, not a fitted curve. The steady-state compute buffer is
flat in context, 493 to 509 MiB from depth 4096 to 32768, but the prefill
graph's reservation is not, and two depths do not justify fitting a slope.
Erring high costs some spill at the measured 5.544 ms/GiB; erring low costs the
whole load.

Moving the constant broke 19 tests whose expected values are arithmetic against
it rather than independent measurements. Rather than rewrite the expectations,
which would bake the new constant in just as hard, those tests now pin the
reserve they were computed for, and the constant itself is pinned once with the
evidence above.

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

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

* studio: tell the planner when the host is a unified-memory APU

The planner abstains on unified memory, since there an -ot spill moves bytes
between two names for one pool: it frees no device memory and buys only the CPU
backend's slower read path. But it abstains solely on HostProfile.unified_memory,
and the seam never set it, so the default False meant that abstain could not fire
in production at all.

The neighbouring shared_gpu_ids guard does not cover this. It is populated only
when is_vulkan_backend is true, because Vulkan reports total VRAM 0 for an
integrated GPU, and is an empty set on every other backend. A Strix Halo
(gfx1151) running ROCm, which is what scripts/install_rocm_wsl_strixhalo.sh
installs, therefore arrived with its APU "VRAM" credited AND host RAM credited,
counting one pool twice, and the planner would then spill to free memory it
cannot free.

Studio already classifies these devices: _amd_apu_wants_unified_memory reads the
driver's own integrated flag first, then gcnArchName, then the device-name
substrings the AMD wheels leave behind when both are absent, covering gfx1150
Strix Point, gfx1151 Strix Halo, gfx1152 Krackan Point and the gfx1103 Phoenix
iGPUs. It is scoped by the selected GPU ids, so a discrete card on a mixed host
is not treated as unified. The seam now passes it through.

Verified no regression across the AMD and ROCm suites: 328 passed over
test_amd_apu_unified_memory, the two amd-smi inventory suites, the five rocm
guards and the Vulkan probe. tests/sh/test_strixhalo_wsl_reroute.sh, the shell
coverage of the ROCm WSL reroute, is 53 passed 0 failed.

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

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

* studio: plan against the budget the fit actually tested

Five defects from the second review round, all optimistic.

The seam credited raw free VRAM. Every other placement decision in this file
goes through _gpu_usable, which subtracts the user's VRAM-budget fraction and
the per-card reserve floor, and the planner was handed the unreduced number. It
bites at the 0.97 default, not just at the 0.80 floor, and it makes the plan
spill too little and then pin that result with --fit off.

The projector and the MTP reserve were missing from the deficit. Studio's own
model_size_fit carries the GGUF, the projector at its safety multiple and the
MTP reserve; the planner rebuilds the model from the target GGUF's tensor table,
so neither is visible to it. Both are passed in now. The compute buffer is
deliberately NOT passed: soft_overhead plus the per-device pipeline reserve
already stands in for it, and charging it twice would only spill more.

Split mode and tensor split are placement, and they were not in _DEVICE_FLAGS.
-sm none is the dangerous one: llama.cpp clears model->devices and pushes back
only devices[main_gpu] (llama.cpp:288-299), so the child runs on one card while
the planner had credited the sum of every selected card. -ts replaces the
free-memory proportional split (llama-model.cpp:1417-1447), so one device can
overflow while the pool total still fits. Both now abstain, argv and env alike.

The MTP blocks were reachable through the -ot patterns. block_count is
n_layer_all (llama-model.cpp:1206) while n_layer() subtracts the nextn blocks
(llama-hparams.cpp:301-303), and those trailing blocks are full decoder blocks
carrying ffn_down_exps and gate_up (models/qwen35moe.cpp). Since -ot is matched
with std::regex_search (llama-model-loader.cpp:1182), an unbounded \d+ pattern
reached them once a draft was loaded. Harmless for VRAM but it inflates
host_bytes, which is what gates --load-mode none.

The layout cache was keyed on pathname alone, on an instance that outlives a
load, so a GGUF replaced in place kept the old tensor table.

Three items were rejected. The spill-order counterexample is real and the
docstring's byte-minimality claim is wrong, but the overshoot is bounded by one
block and errs toward spilling more. plan_to_args has no non-test caller and the
seam leaves context_policy at NEVER_REDUCE. And the recurrent-state double count
is real but is tens of MiB in the safe direction, and removing it honestly needs
a new flag threaded through three functions.

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

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

* fix(logs): quiet the polls and drop the duplicated access lines (#8763)

* Studio: quiet the liveness poll and keep access lines out of tauri.log

Measured on an idle 4h desktop session, tauri.log was 5308 lines / 1.14 MB,
of which 4056 (76%) were request_completed access records and 3355 (63%)
came from six polling endpoints. At ~216 bytes a line the 5 MiB cap fills
in about 18 hours, so a failure from the day before had already rotated
out by the time anyone asked for it.

/api/liveness is the desktop watchdog's own probe, roughly every 19s, and
was in no suppressor at all: 760 lines, 14% of the file, saying the
process is still up. Its sibling /api/health was already quiet. Put it in
_QUIET_POLL_PATHS so it heartbeats; non-2xx still logs every time, which
is the case that matters for a watchdog.

Every backend stdout line is written to disk three times: the backend's
own session log, the diagnostics phase log (stream-tagged and stamped),
and tauri.log. The access records carry nothing in the third copy that
the first two lack, so log them at debug!, below the file target's INFO
filter. Non-JSON output -- the startup banner, "Hardware detected:",
stderr, tracebacks -- keeps INFO, which is what anyone opening tauri.log
is there for. The phase log still gets the unfiltered stream, so the
support report loses nothing.

Also:

- Collapse carriage-return progress frames. Reading to \n means a tqdm bar
  arrives as every frame it drew concatenated onto one line; a single
  "Loading weights" bar measured 5086 bytes across three sinks. Keep the
  final frame, which is the one showing 100% and the elapsed total. Cap
  what reaches tauri.log at 16 KiB, the limit the phase log already used.

- Bound logs/llama-server and logs/diffusion-server. Both directories are
  created per model load and were never pruned (319 files going back two
  months here). The server session log has capped itself since it was
  added, so lift that into utils/log_retention.prune_log_dir and call it
  from all three rather than write the loop a third time.

- Log the top-models catalog at debug. Two lists of 40 repo names, one
  line each, on every boot to say a fetch succeeded; the counts say that.

- Configure structlog in run.py before the first line it logs. main.py
  configures on import, several seconds later, so "run_server startup
  begin" rendered through the defaults (console, local time) and
  everything after it as JSON in UTC -- the clock appeared to jump hours
  between the first and second line of one stream.

Not included: the same carriage-return collapse on the Python tee. Doing
it there means line-buffering the file copy, which would withhold a
partial line from server-*.log exactly when the server hangs mid-write.

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

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

* Collapse progress frames in the session log too, and quiet remote-access

The first pass collapsed carriage-return redraws on the Rust side only. It
left the Python tee alone because doing it there seemed to mean buffering
the file copy until a newline, which would withhold a partial line from
server-*.log exactly when the server hangs mid-write.

It does not have to. Hold back a frame, never a line: an unterminated chunk
containing "\r" is a redraw and is kept until the next one supersedes it,
while an unterminated chunk without one -- a prompt, or a traceback torn by
a hang -- is written the moment it arrives. So the session log gets one
line per bar instead of one per frame, and nothing diagnostic waits on a
newline that may never come.

The console side is untouched: it still sees every frame, which is the
whole point of a progress bar.

Also adds /api/settings/remote-access to the quiet polls (116 lines in the
same 4h sample), for the same reason as the others: it is a plain read of a
toggle, re-read whenever the settings dialog is open.

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

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

* Install the tee before structlog, and stop three suppressors overreaching

Four review findings, all real.

structlog was configured at import, and PrintLoggerFactory snapshots sys.stdout
while cache_logger_on_first_use freezes that snapshot into any logger that has
already logged. run_server's own logger logs at line one and the tee is not
installed until 45 lines later, so every subsequent run.py line -- the orphan
sweep warnings, the whole rest of startup -- was pinned to the console and never
reached the session log. Configure inside run_server instead, after the tee:
the ordering bug the change set out to fix (line one rendering through
structlog's defaults while line two rendered as JSON in UTC) is still fixed,
and the file gets everything from line one. Moving the tee up also means the
orphan sweep now lands on disk, where it was console-only before.

A withheld progress frame was concatenated onto whatever came next, so a
structlog record arriving mid-redraw landed as Loading 47%{"event": ...} and
stopped being parseable. Close the frame off on its own line unless the next
write is its own redraw or its terminator, and land a frame still held at
close() rather than dropping it.

The desktop watchdog polls every 15s (HEALTH_WATCHDOG_INTERVAL) plus up to a
10s probe budget, so _QUIET_POLL_DEDUP_MS at 10s could never close over two
probes and putting /api/liveness in _QUIET_POLL_PATHS collapsed nothing. Give
it its own 60s window, zeroed alongside the quiet window so --verbose still
logs every probe, and pin the floor with a test that reads both constants out
of commands.rs.

is_backend_access_log_line matched on the event name alone, so it also dropped
non-2xx records to debug! -- below tauri.log's INFO filter. Those are the ones
the backend's heartbeat suppressor deliberately exempts, and a watchdog going
red is what tauri.log is read for. Match only 2xx; a record with no status_code
keeps its INFO line too.

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

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

* run.py: keep CRLF lines, stop leaking the tee, import LogConfig lazily

Three defects in the same file, all found while checking this branch against
main. Tests for each alongside.

1. The tee destroyed every CRLF-terminated line.

_last_frame took rpartition("\r")[2] unconditionally, so the "\r" of a CRLF read
as a redraw boundary whose final frame was empty, and the payload went with it:

    "Hardware detected: NVIDIA GeForce RTX 4090\r\n"          -> "\n"
    "Traceback...\r\n  File \"run.py\"...\r\nRuntimeError\r\n" -> "\n\n\n"

On Windows that is every line a child process relays, so a relayed traceback
landed in the session log as blank lines. It is also exactly the artifact #8690
added a UI for. The desktop reader already gets this right: trim_line_endings
strips every trailing \r and \n before collapse_progress_frames sees the text.
Mirror it here so the two sinks stay interchangeable for a reader, and fall back
to the last non-blank frame the same way, so a bar that signs off with a bare \r
keeps its 100% frame instead of writing a blank line.

Also: a "\r" must never reach the file. The handle appends the platform
terminator itself, so one that survives lands as "\r\r\n" on Windows.

2. A zero-length write reopened the record corruption fixed on 08-18.

`data[:1] not in ("", "\r", "\n")` read write("") as a continuation of the held
frame, so the close-off was skipped, the frame fell through to the unterminated
branch, and the next record was glued onto it:

    ["\rLoading weights:  47%", "", '{"event": "model_loaded"}\n']
    -> 'Loading weights:  47%{"event": "model_loaded"}'

print("", end = "") is enough to reach it. Return early on empty data instead.

3. A rejected flag combination left the streams swapped.

--secure --no-cloudflare is a deterministic preflight failure, but it now runs
after _setup_server_disk_logging() has replaced sys.stdout and sys.stderr and
opened a log handle, and nothing unwinds either. An embedder that catches the
SystemExit keeps the tee, and its next run_server() call nests a second one, so
every line is written twice. main does not do this. Validate before the tee.

4. `from loggers.config import LogConfig` at module scope broke Repo tests (CPU).

15 failures in tests/studio/install/test_selection_logic.py, all
"No module named 'loggers.config'; 'loggers' is not a package".
load_studio_run_module stands a bare types.ModuleType in for `loggers` before
exec'ing run.py; a bare module has no __path__, so the import fails during
collection and takes every test in the file with it. That fixture's own comment
names the hazard. LogConfig has one use, inside run_server, so import it there
rather than widening a stub three directories away.

* Prune the log directories after opening the new file, and protect it

Two problems with prune_log_dir as it stands.

The cap never held. All three call sites prune before creating the log, so with
keep=20 the directory settles at 21 and every load repeats the prune-to-20,
create-the-21st cycle. Measured with 25 seeded files and 10 loads: 21 with this
ordering, 20 when the prune runs after the open.

And one odd directory entry disabled retention entirely. The mtime sort ran
inside a single try/except, so a dangling symlink matching the glob raised on
stat() and the whole call returned having deleted nothing. Seeded with 30 files
plus one broken link, keep=5 left all 30. That is the unbounded growth this
helper exists to stop, reintroduced by one bad name. Stat failures are now
per-entry.

Only regular files count now, too: a directory that happens to match the glob
was taking one of the kept slots (25 files plus one such directory, keep=5, left
4 real logs).

prune_log_dir grows a `protect` argument, and the call sites move to after the
open. `protect` is never deleted and counts as one of the `keep`, so the total
stays at keep. It is not enough to trust the new file to sort newest: two loads
in the same second, or a clock that steps back, and it does not.

The retry call site benefits most. The comment right above it explains that the
-try{n} suffix exists so a respawn within the same second cannot truncate the
crash log a retry warning just pointed the user at; pruning before the open on
every attempt worked against that.

New tests cover keep values, the protected file counting toward the cap and
surviving even when it sorts oldest, dangling symlinks, symlinks pointing
outside the directory, directories matching the glob, identical mtimes, family
isolation, and a writer appending across a prune.

* process.rs: CRLF and marker tests, and say what debug! means here

collapse_progress_frames is correct on CRLF because trim_line_endings runs
first, but nothing pinned that, and the Python tee that writes the backend's own
session log got it wrong. Add the cases that hold the two implementations
together: a CRLF payload keeps its text, a CRLF-terminated bar still collapses, a
CRLF JSON record stays parseable and still classifies, a TAURI_PORT marker
survives the collapse whether or not it shares its line with a redraw, and an
all-blank line never keeps a carriage return. Plus the 16 KiB truncation landing
on a character boundary for multi-byte text.

The fallback for an all-blank line returned the whole text, which still holds the
\r the caller asked to collapse away. Return the last frame instead.

Two comment fixes. The new test module had been inserted between the
C:\Windows\system32 comment and the managed_cli_working_dir_tests module it
describes; move it back. And record what debug! actually does for a matched
record: setup_logging in main.rs builds every logger at LevelFilter::Info and
there is no RUST_LOG or any other way to raise it, so log::max_level() is Info
and a matched record is dropped outright rather than demoted, including under
backend --verbose, which makes it emit more of them. That is fine, but it is not
obvious from the call site, and the surrounding comment argued the opposite case
for non-2xx. The records are still written verbatim to the diagnostics phase log
(append_phase_line runs before this decision) and to the backend session log,
both of which the support report and Settings > Logs already offer.

Separately, test_watchdog_window_outlasts_the_probe_interval read the module
global, so it failed for anyone with UNSLOTH_STUDIO_ACCESS_LOG_WATCHDOG_DEDUP_MS
exported; read the default instead. Its two regex lookups now report what moved
in commands.rs rather than raising AttributeError on .group(1).

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

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

* Tighten the comments this PR adds

Comment-only pass over the 10 files the PR touches. No code change: the AST gate
(comment_tools.py check --strip-docstrings) reports 9/9 files comments-only, the
Rust file has no non-comment line in the diff, and no docstring was dropped.

114 insertions, 142 deletions. Heaviest in run.py and process.rs, where the same
explanation was being given twice, once in a doc comment and again at the call
site. Every load-bearing why is kept: the structlog factory/cache ordering, why a
CRLF terminator is not a redraw, why the watchdog window has to outlast the poll,
why prune runs after the open, and what debug! means for a matched record.

* [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>
Co-authored-by: Daniel Han <[email protected]>

* Xet notice: one toast carrying both messages, three times per install, gone when the download is (#9660)

* One start, one toast: let the Xet notice yield to a caller that already explained

Picking a model in chat raised two toasts stacked in the same corner: the
Xet notice, and chat's own "Downloading model / It'll load automatically
once the download finishes". Both are true, both say the same thing in
different words, and the user is told twice for a single start.

DownloadRequest gains callerExplainsWait, set by the two chat-page paths
that toast about the start themselves. startJob passes it to
shouldShowXetNotice, which now returns false for those, so the notice
stays quiet and does not spend one of its three doing so. The Hub
download card sets nothing and is unaffected: it has no start toast of
its own, which is why the notice exists.

The UI evidence for #9658 missed this because the scene drove the Hub
download card, and only chat's picker raises a start toast. The unit test
added here covers the predicate directly.

* Fold the caller's line into the notice, count on the server, dismiss when done

Three separate reports, one feature.

ONE TOAST, CARRYING BOTH MESSAGES. #9660 suppressed the Xet notice whenever
chat had its own toast, which removed the 0%-explanation exactly where a
first big download makes it most useful. The caller now states its message
and the download manager decides how to say it: folded into the notice when
that fires, on its own when it does not. DownloadRequest.callerExplainsWait
becomes callerToast. transport-conflict's early return also announces, since
it reports "started" without ever reaching startJob and used to rely on
callers toasting for themselves.

The composed sentence is chat-only. A Hub download does not auto-load, so
"It'll load automatically" would be false there, and the Hub variant is also
the one that renders over the hub toolbar, which is what the character budget
in the tests protects.

THREE TIMES FOR THE LIFE OF THE INSTALL. The count lived in localStorage,
which is per-origin, and a Studio origin is not stable: run.py falls back past
port 8888 when Jupyter has it, and Colab and the tunnel are different origins
again. Each of those handed out a fresh three, so the notice never actually
stopped. It moves to app_settings behind a reserve endpoint that does the read
and the write in one transaction, which also retires the Web Locks dance that
existed to narrow the same race in the browser. Fails closed: an unreachable
endpoint shows nothing rather than falling back to a count that resets.

GONE WHEN THE DOWNLOAD IS. The 8s duration is a cap, not a description of the
transfer, so a small model finished, auto-loaded, and the toast was still
saying the download was running. finalize() now dismisses it.

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

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

* Drop the unused xet-notice GET route

Added alongside the reserve endpoint out of symmetry with /helper-precache,
but nothing calls it: the frontend only ever POSTs a reservation. It also had
an awkward shape, always reporting granted=false because it reused the reserve
response model. An endpoint with no caller is surface to maintain and review
for no benefit.

get_xet_notice_count stays. It is the read half of the module and the tests
assert stored state through it; the alternative is tests poking sqlite
directly, which is worse.

* Tighten the comments on PR #9660

Comment-only. Cuts about 120 lines of prose without losing the reasons: why
the copy has a character budget, why the reserve is one transaction, why the
count moved off localStorage, and why the reservation fails closed.

No code changed: the diff for this commit has zero non-comment lines in the
TypeScript, and the Python edits are docstring bodies only.

* Fix the start-toast lifetime, surface and reservation for PR #9660

- keep chat's auto-load sentence for the Xet notice to fold in, but never raise it
  on its own: #9663 removed that standalone toast as a duplicate of the panel
- drop the caller's line from a request deferred by a transport conflict; it is
  resumed from the Hub, where 'it'll load automatically' is not true
- do not announce a start the user already cancelled, and re-check the job before
  publishing a toast the reservation round trip outlived
- dismiss a start toast when its surface is left: the composed form measures 167px
  against a hub filter row at 158px
- keep the legacy notice count until the server confirms it, and stop the Tauri
  network retry from spending a second notice on this non-idempotent POST

* Hold a start toast against the route it started on for PR #9660

- the Xet reservation is a round trip, so the raise can land after the user has
  navigated; capture the route at the start and drop a raise that arrives once
  that surface is gone, instead of recording the destination as its origin
- drop the toast for a pending auto-load that a newer selection replaced: its
  completion no longer loads anything, so the promise is stale
- type the toast stub so tests/download-start-toast.test.ts typechecks

* Take the start route before the preflight, and validate the reservation for PR #9660

- capture the origin route in requestStart, before the transport preflight and
  apiStart; reading it afterwards named whatever page the user had moved to
- a 200 carrying some other JSON is not proof the backend stored the legacy hint,
  so require a reply that reports the cap it enforced before ending the migration
- dismiss the auto-load toast when the chat context changes: switching thread or
  project keeps the pathname, and onComplete refuses to load into a new context

* Don't spend a notice, or a promise, that has already gone stale for PR #9660

- check the origin route before reserving, not only when the toast is raised: the
  preflight and apiStart are round trips long enough to navigate during, and a
  reservation is one of three for the life of the install
- let a caller's line declare when it is still true; chat ties its auto-load
  sentence to the context it was staged for, so a raise landing after a thread
  switch keeps the Xet explanation and drops the promise

* Tighten the comments on PR #9660 after convergence

---------

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

* fix chat search dialog stutter on open (#8514)

* fix chat search dialog stutter on open

The dialog is centred with `top-1/2 -translate-y-1/2`, so any height change
moves both edges. `CommandList` was sized with `max-h-[420px]`, which meant it
opened at the height of the "Loading…" row and grew to full height the moment
`buildIndex()` resolved, re-laying out and re-centring the surface in the middle
of the 100ms zoom. In the Tauri WebKit view that reads as a visible stutter; in
the browser it is mostly hidden by faster compositing.

Changes in `chat-search-dialog.tsx`:

- pin `CommandList` to `h-[420px] max-h-[60dvh]` whenever a chat exists, so
  loading, arriving results and filtering never resize the surface. The list
  only collapses in the genuinely empty "No chats yet." case.
- mount `INITIAL_ROW_COUNT` (24) rows first and the remainder at 220ms, after
  the open animation, so a 200 thread history does not lay out every row
  mid-transition.
- run filtering through `useDeferredValue`, keeping `selectVisibleChats` off the
  keystroke path. It scans `searchText` for every conversation, which includes
  tool call output.
- ease the open and close at 180ms with `cubic-bezier(0.16, 1, 0.3, 1)`.

`use-chat-search-index.ts` keeps the last built index in a module-level
`cachedIndex`, so reopening paints the previous rows immediately and revalidates
in place instead of falling back to the empty state. When the dialog is closed
the hook listens for `CHAT_HISTORY_UPDATED_EVENT` and drops the cache, so a chat
deleted while search is closed cannot reappear on the next open.

`index.css` adds `will-change: transform, opacity` to `.chat-search-surface`.
The surface carries a 70px blur shadow that WebKit otherwise repaints on every
frame of the zoom.

Verified in the Tauri dev build against the same chat history that reproduced the
stutter, and in the browser at localhost:5173. `tsc -b` clean, 1960 frontend
tests pass. No GPU checks apply.

* address codex review on chat search dialog

Four items from the round one review, all reproduced against head first.

`use-chat-search-index.ts`:

- `cachedIndex` is now assigned after the cancellation and sequence checks. A
  rebuild that resolved late could otherwise overwrite a newer snapshot, or
  repopulate the cache after the closed-dialog listener invalidated it, which put
  deleted chats back on the next open with the loading state suppressed.
- the closed-dialog invalidation returns early when nothing is cached.
  `CHAT_HISTORY_UPDATED_EVENT` fires per streaming chunk, so the previous version
  allocated a new array and re-rendered on each one throughout generation.

`chat-search-dialog.tsx`:

- the query and row-limit reset moved from close to open, in a layout effect.
  Radix keeps the surface mounted for the 180ms exit animation, so trimming back
  to 24 rows on close tore down the DOM mid-transition. Resetting before the
  reopened dialog paints keeps the exit untouched and avoids a flash of the
  previous query's results.
- `matchesChatQuery` gates activation. The list trails the input by a render
  while the deferred filter catches up, so Enter could open a chat that no longer
  matches what the input shows. Re-checking the row against the live query keeps
  clicks on visible rows working while dropping the stale activation.

`tsc -b` clean, 1960 frontend tests pass. UI behaviour verified in the Tauri dev
build: open, type, close, reopen, and delete-then-open.

* address codex round two on chat search dialog

`chat-search-dialog.tsx`:

- reserve the fixed list height from `ready` rather than `loading`. `run()` calls
  `setLoading(true)` from a passive effect, so on the first open of a session the
  opening render still saw `loading === false` with no items and picked the
  compact branch, then jumped to 420px during the animation. The hook now
  reports whether an index exists, which is known on the first render.
- reset the query and row cap during the opening render instead of in a layout
  effect. Radix mounts the portal as that render commits, so a layout effect
  trimmed rows only after React had already built the previous result set into
  the DOM.
- filter on `activeQuery`, which bypasses `useDeferredValue` for an empty query.
  The deferred value keeps returning the previous query during the urgent reset,
  so a reopened dialog could paint the old filtered subset next to an empty
  input.
- validate selection against `selectVisibleChats(items, query)` rather than a
  per-item match. The per-item check ignored the two-tier rule, where a global
  `userSearchText` hit suppresses `searchText` matches, so a row outside the live
  result set could still be activated. The scan runs on activation only.

`use-chat-search-index.ts`:

- `rebuildPending` tracks a history change whose debounced rebuild has not landed.
  Closing the dialog in that window cancelled the rebuild and left a snapshot
  already known to be out of date, which the next open then showed. The cleanup
  now drops the cache in that case.
- `ready` is exported alongside `items` and `loading`, cleared wherever the cache
  is invalidated.

`tsc -b` clean, 1960 frontend tests pass.

* keep the search rebuild flag set while a rebuild is queued

* control the chat search input so a fast reopen clears its text

* decide the chat search list height once per open

The empty-history first open reserved 420px while the index was still building, then collapsed to the compact branch as soon as the empty build resolved, so the centered dialog shrank mid-animation. The height now comes from what the cache already knows at the opening render and is held for that whole open.

Closing within 300ms of a history event also cleared the rendered items from the effect cleanup, tearing every row out of the list while Radix kept the surface mounted for its 180ms exit. That path and the closed-dialog listener now drop only the module cache; the reopening render discards the stale rows before they can paint.

* scope the chat search cache to the auth session

The index cache sits at module scope so it survives the sidebar unmount, and a web logout only runs navigate({ to: "/login" }) with no reload. A second account logging in on the same page therefore opened the search dialog onto the previous user's rows until the rebuild landed.

Reads and writes now go through readCachedIndex/writeCachedIndex, stamped with getAuthSessionEpoch(), the same session marker features/credentials/bootstrap.ts uses. A build that straddles a logout is discarded rather than stamped onto the new session.

* Keep the search dialog compact before the index is built for PR #8514

* Tell an unread chat history from an empty one when sizing the search dialog for PR #8514

* Distinguish an unknown history, invalidate across tabs and bound the cache for PR #8514

* studio: drop will-change from the chat search surface

The property was applied by a permanent class rule, so the dialog kept its
own compositing layer for its whole life rather than just the open zoom. In
WebView2 that disables subpixel text antialiasing, leaving the search rows
visibly soft on Windows.

Both Blink and WebKit already promote an element while a transform/opacity
animation is actually running, so the zoom keeps its layer without the hint.

* studio: finish the chat search cross-tab and hint edges

Four review findings on the search index cache.

The storage listener dropped the module cache but told no one, so a dialog
already open kept rendering rows built before another tab's change, with
nothing scheduled to replace them. It now re-raises the change as the same
same-document event a local change fires, which every in-tab listener
already handles. Tabs only learn of a change through localStorage, so the
re-raise cannot echo back.

That write sat on the streaming path, where the history event fires per
chunk, and a synchronous setItem there blocks the producing tab and wakes
every other one. It is coalesced to at most one write per quiet window.

Releasing uncached rows happened in the closing render, inside the portal
Radix keeps mounted for the exit animation, which is the teardown the rest
of this change avoids. It waits for the exit instead.

The persisted row hint outlives the page but was not cleared on logout, so
after a reload on the login screen the next account sized its first open
from the previous one's history. It now clears when the auth session does.

* studio: close the chat search cross-tab and lifetime gaps

Four more review findings on the search index cache.

An account switch performed in another tab reached this one as a token
write and nothing else: the session epoch lives in this document's memory
and its events are same-document, so the cached rows still matched their
epoch and the next open showed the previous account's titles while the
rebuild already used the new account's token. The storage listener now
treats a token write as an invalidation, and the shared row hint goes with
it. A routine refresh writes that key too and costs one rebuild, which is
the safe way to be wrong.

The revision write was throttled rather than coalesced, so a long
generation wrote once per debounce period instead of once when it went
quiet. The timer is rescheduled on each update, and a pagehide flush keeps
a delete that is followed by closing the tab from being lost with the page.

Releasing rows was one-shot: a history event arriving after it had already
run left the hook holding the conversation text until the dialog was
reopened. Invalidation reschedules it, which moves a timer rather than
rendering, so a stream still costs nothing until it stops.

* studio: separate the cross-tab channels for chat search

Three review findings.

An account switch made elsewhere reached this document as a token write, so
a build already in flight had been started for the account that just went
away. Its epoch check could not catch that, because the epoch is this
document's and this document never signed out: the result would have been
written back to the cache and the UI as the previous account's titles. The
storage listener now raises a distinct session event, and an open dialog
answers it by dropping its rows and rebuilding at once, which advances the
request sequence and retires the older build.

The cross-tab write shared one quiet window with the per-chunk streaming
path, so a delete during a long generation stayed unannounced until the
generation finished and other tabs went on offering the deleted chat as a
live row. Only the message-write path coalesces now; everything else
publishes immediately. That logic moves to its own module so it can be
tested, the same way the row hint was.

Releasing rows restarted its countdown on each invalidation, so a stream
with the dialog closed could hold an oversized index for the whole
generation. A pending release is left to run.

* studio: key the search cache off a session mark, not the token

Two review findings.

Keying the cross-tab account check off the token meant an hourly refresh
read as an account switch: refreshSession rewrites that key with the same
session in place, so every rotation would have thrown away another tab's
warm cache and emptied an open dialog for nothing. Sessions now leave a
mark in storage, written where storeAuthTokens already detects a session
starting and removed where clearAuthTokens ends one. It moves on a session
boundary and never on a rotation, which is the question the search cache
was really asking. Nothing reads the value; only that it changed.

Pruning is how a message is deleted, and syncChatMessages was coalescing
that alongside the streaming autosave it shares an endpoint with, so an
explicit deletion could wait out an unrelated generation before other tabs
heard about it. It takes the immediate channel when pruneMissing is set.

* studio: tighten the chat search comments

Comments only, no code touched. The explanations had grown longer than the
code they sat above, several of them restating the same constraint in two
or three places. Same points, shorter, across the 13 files this branch adds
or changes: 126 lines in, 172 out.

* studio: address the codex review on the chat search index

- a manual message edit publishes its revision at once instead of sharing the
  streaming autosave's coalescing window
- Archive All emits one cross-tab revision for the batch, not one per thread
- a session predating the session marker backfills it on its next token refresh,
  so a later sign-out is visible to the other tabs
- a failed rebuild drops the snapshot it was replacing rather than restoring it
- a persisted empty history answer ages out, since chats made elsewhere never
  reach this tab

* Announce a partially failed Archive All for PR #8514

* wait for every Archive All write before announcing a partial failure

* drop the unused AUTH_TOKEN_KEY re-export and correct the storage guard comments

* retire an in-flight search build when the history changes under it

* keep the search index building through a streaming response

* Fix chat search rebuild priority and failed-read hints

* Fix structural rebuild release and partial hints

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: LeoBorcherding <[email protected]>
Co-authored-by: Etherll <[email protected]>

* Studio: scale, crop and trim MiniMax-H3 reference media (#9631)

* Studio: scale, crop and trim MiniMax-H3 reference media

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

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

* Clamp a reference soundtrack to its video rather than refusing it

An untrimmed reference whose embedded audio ran past its video was refused with "The
reference soundtrack extends past the video". Before this branch the same file decoded
fine, since the only audio bound was the 15 second one, so the check turns media that
already worked into a 400.

The allowance is two codec frames, about 43ms at 48kHz for AAC, and ordinary encoder
padding clears that on its own. An A/B over synthetic pairs decoded on main and here has
a 5s video with a 6s track, and the same video with tracks 50ms, 100ms, 1s and 9s long,
accepted on main and refused on this branch.

The untrimmed path already sets end_sample to the video's own duration, so it was
clamping the track and then refusing it anyway. Dropping the raise leaves the clamp, and
the stop condition now covers the untrimmed case too, so the tail no engine receives is
no longer decoded either. Trimmed behaviour is untouched, including the 15s pair that
main refused over padding and this branch correctly accepts.

Also floor the ordinal fallback's start frame. The frame on screen at t is the last one
that started at or before it, so the start floors where the exclusive end ceils; ceiling
both skipped the frame straddling a fractional start and shifted the selection forward by
up to one frame against the timestamp path on identical media. Nothing reached that
fallback in the suite, so it also gains the two tests that would have caught this: one
driving it against a clip whose frames encode their own index, and one proving the
dispatcher reaches it at all when timestamps are stripped.

* Export a crop at the size the model will use

The crop editor rasterized at full source resolution, so a lossless PNG of the crop had to
fit the same 32 MiB field cap this module enforces. Driving the real module through
chromium, firefox and webkit shows it usually does not: the 5712x4284 photo from the issue
serializes to 36-42 MiB with photographic content, and an ordinary 12MP phone photo to
about 52 MiB. Every engine refused the issue's own example with "The cropped picture is too
large. Select a smaller area and try again.", and the advice does not help, because the
picture was already the whole selection.

Those pixels were never going to reach the model. fit_h3_reference_image bounds a reference
at a 2048px short edge under "max", and fits to the generation area under "match", which is
far smaller, so anything above that is encoded, base64'd and shipped only to be resized away
on arrival. Bounding the export at a 2048px short edge and a 4096px long edge takes the
issue's photo to 9.6 MiB and the phone photo to 23.8 MiB, both well inside the cap, and the
long edge is bounded as well so an extreme aspect cannot keep a huge dimension just because
its short edge already fits.

It also unblocks the main thread. The synchronous toDataURL held webkit for 6.1s on the
24MP photo and produced no decodable PNG at all for high-entropy content at that size;
after the bound the same case takes 1.3s and comes back intact. images-page.tsx already
carries this guard for outpaint, with the same reasoning.

The stored crop rect stays in original source pixels, so reopening the editor still
restores the selection against the full picture. A crop already inside the bounds is
untouched, so the existing raster test passes unchanged.

* Bound the wait for a reference video's duration

readVideoDuration waits for loadedmetadata or error and has no other way to finish. An
element that fires neither leaves the promise pending for good, and the picker slot behind
it, because the staged entry is only published from the .then.

The duration is what decides whether an overlong clip gets its automatic first fifteen
seconds, so losing it sends the whole clip and earns exactly the refusal this page set out
to avoid. A timeout resolves undefined instead, which the caller already handles as "no
automatic trim", and the element is told to load() after its src is cleared so it drops
what it was decoding.

An object URL was the obvious source to probe from, and it is measurably better on chromium,
4ms against 461ms. It is not portable: webkit reports no metadata for one at all and only
times out, while it reads the data URL in 2.5s. Keeping the data URL costs a parse and keeps
the duration on every engine, which is the side worth being on.

* Agree with the backend on which trim intervals are valid

referenceVideoTrimError compared durations exactly while validate_h3_reference_trim allows
1e-6 of slack, so the form refused intervals the server would have taken. The 0.1-step
inputs reach them easily: 2.3 - 0.3 is 1.9999999999999998 and 16.1 - 1.1 is
15.000000000000002, so 0.3 to 2.3 and 1.1 to 16.1 both read as out of range. Sharing the
tolerance settles it.

Also refuse a source shorter than the two second minimum up front. No interval inside a
1.5s clip can reach 2s, so the trim fields were a dead end on one, and the feedback line
called the trim optional while the decoder was always going to refuse the clip. Saying so
at the picker turns a late 400 into an answer the user can act on.

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

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

* Shorten the comments added by the review fixes

Comment and docstring wording only. Verified comment-only against the previous commit by
AST comparison of all seven touched files.

* Keep a trim whose embedded soundtrack runs out, padding the rest with silence

A trim the embedded audio does not fully cover was refused with "Reference video trim ends
after the source soundtrack", even though the video covered the range. A 10 second video
whose track ends at 6 seconds, trimmed 2 to 8, was rejected outright.

Embedded audio is optional here: a video carrying no track at all is accepted, and the
untrimmed path clamps a mismatched track rather than refusing it, so treating the track
length as the source boundary only for a trim was inconsistent. The output buffer is
already zero-filled, so the interval past the track is silence with nothing further to do,
and a trim starting entirely after the track still returns no soundtrack as before.

Same change in the sample-counting fallback, which had the identical check.

* Shorten the comment on the short-soundtrack path

Comment text only; AST-verified as comment-only against the previous commit.

* Let a trim reach a little past the video track before refusing it

A container reports the duration of its longest track, so a file whose audio outruns its
video reads as longer than it can show. Studio takes its automatic interval from exactly
that number, HTMLMediaElement.duration, so a 14.9 second video carrying a 15.2 second
soundtrack reads as 15.2, auto-trims to 0 to 15, and is then refused with "Reference video
trim ends after the source video" even though the same file decodes fine untrimmed.

Measured on that fixture: the video track covers 14.917s in 358 frames while the container
declares 15.2s, and chromium, firefox and webkit all report 15.2.

A trim may now fall up to half a second short of the video track, holding the last frame
across the gap, which is what both trim decoders already do at their own endpoint. Past
that the range really was not there and the error stands, so a 2 to 10 second trim of a 6
second clip still fails.

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

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

* Shorten the trim coverage slack comment

Comment text only; AST-verified as comment-only against the previous commit.

* Drop the soundtrack when none of it falls inside the trim for PR #9631

An embedded track starting after the selected interval was decoded, advanced the
timeline past the interval and copied no samples, so the guard that returns None
did not fire and a target-length silent waveform was returned instead. The model
then received a fabricated soundtrack, and the positional pairing in
stage_h3_references treated the reference as having audio, so the gap it exists to
catch went unreported. A track ending before the interval already returned None;
this makes the two agree by keying on whether any sample was copied.

* Shorten the comments added by the soundtrack-gap fix

Comment and docstring text only; AST-verified as comment-only against 11f80b4f4.

* Start a replacement soundtrack at its own zero for PR #9631

A separate uploaded soundtrack was decoded with the video's absolute trim
coordinates, so an 8s replacement for a clip trimmed 5s to 13s kept only its
seconds 5 to 7 and ran silent for the rest, and a replacement shorter than the
trim start was refused outright with "That reference audio decoded to no
samples". The file is independent, the picker offers no way to offset it, and
the standalone reference audios already decode from their own zero, so it now
plays the clip from its own start, bounded to the clip length. Embedded audio
still uses the video's timeline.

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

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

* Shorten the comments added by the replacement-soundtrack fix

Comment and docstring text only; AST-verified as comment-only against 63def5d74.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>

* fix(amd): report AMD VRAM on Windows by joining the adapter counters on LUID (#8863)

* Join the Windows GPU adapter counters to torch devices on the adapter LUID

Windows ROCm has no amd-smi and hipMemGetInfo does not see other processes, so
used VRAM comes from the per-adapter "GPU Adapter Memory\Dedicated Usage"
counter. Nothing keyed that counter to a torch device, so it was attributed by
ranking usages against device capacities, and a value was emitted only when
capacity FORCED the pairing. One visible GPU forces nothing -- there is no
smaller card for its usage to exceed -- so the single-GPU host, the common AMD
Windows case, always read Unknown. The host aggregate needed the counters to
number the visible devices exactly, which the Basic Render Driver and an idle
iGPU break, so it was unknown too.

Windows names each counter instance after the adapter LUID, and DirectX keeps a
record per LUID under HKLM\SOFTWARE\Microsoft\DirectX carrying the same
Description string torch reports as props.name. Join on that instead: identity
needs no disambiguation, so a lone card resolves exactly, and a busy foreign
adapter beside an idle Radeon no longer blocks the read. Every case the join
cannot establish falls back to the capacity ranking unchanged.

* Decline the DirectX adapter map when a record will not read

Reading an adapter subkey could fail and leave the rest of the map
standing. A partial map is indistinguishable from a complete one at the
join, so a visible card whose own record was unreadable could be handed a
hidden same-named card's counter. Adapter records are GUID-named, which
tells them from ShaderCache without inferring it from a missing VendorId,
and any read failure past that point now empties the map, which falls
back to capacity ranking.

The join itself now tries two keys. DirectX takes the Description from
the driver INF and HIP fills props.name from the ASIC record, so one card
can reach the two sides spelled differently: the trademark marks and the
spacing around them are normalized away, and when the names still
disagree the gfx target both sides also carry settles it
(AdapterFamily=AMD_NAVI44:gfx1200 against gcnArchName=gfx1200). That is
what an iGPU beside a dGPU needs, where the archs differ but the
marketing names may not resolve. Name first, because it separates a 9070
from a 9070 XT where the shared arch cannot. The arch pass runs only when
every AMD record has a family, so a driver too old to write one cannot
let the records that have it answer for the adapter that does not.

Verified live on Windows 11 / RX 9060 XT: the walk skips ShaderCache and
the Basic Render Driver and resolves the card's own counter.

* Bound the LUID join by the carve-out, not the displayed total (#8863)

Forward guard for the interaction with #9314, which widens total_bytes to the
whole driver pool on a unified APU. _attribute_adapter_useds_by_key reads
total_bytes as the capacity a Dedicated Usage counter can fill, both to rank
positions and to reject a usage no card could hold. That counter measures the
dedicated segment, so its ceiling is the carve-out and never the pool: against a
128 GB ceiling a 9 GB counter belonging to no visible card passes the check and
gets published on a card that never held it.

Neither PR does this alone. #8863 has no widened total and #9314 has no LUID
join, so it only appears once both are in, whichever order they land.

_adapter_counter_capacity() prefers dedicated_bytes and falls back to
total_bytes, so this is correct on this branch, where dedicated_bytes does not
exist yet and the fallback makes it a no-op, and correct the moment #9314
rebases on top. The capacity-ranking fallback path takes it too, so both
consumers of a counter agree on what bounds it.

Two tests: the helper's preference either way round, and the join declining an
impossible counter against a widened total while still attributing one that
fits.

150 pass in the ROCm/VRAM files, 1768 across the backend gpu, hardware, vram,
rocm, amd, system and cuda tests.

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

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

* Do not stop the LUID join at a pass that answered nothing (#8863)

Two defects in _match_adapter_used_by_luid, both found by review.

A pass can succeed while naming no device: several cards under one key leave
per-device unknown and contribute only to the aggregate. Returning on the first
non-None result therefore ends the search on a vacuous success, and two cards
sharing a Description but differing in gcnArchName stay unknown even though the
gfx pass would separate them. The docstring already promised that a declined
name join falls through to gfx; it now covers a vacuous one too. The first such
result is kept for its aggregate and returned only if no later pass attributes.

And a key that leaves AMD usage unplaced is not identifying reliably. A visible
card whose Description differs from its props.name puts its own counter under a
key no device claims, while a hidden card wearing the device's name sits under
the one that is claimed, and the pairing hands the hidden card's bytes to the
visible device. Measured on the added case: 17 GiB belonging to a masked card
reported as the visible card's. The pass now declines, which costs a masked
second AMD card its join and falls back to capacity ranking, where that case
already was.

Both tests fail on the parent: [None, None] instead of [9.0, 3.0], and 17.0
instead of None.

1810 pass across the backend gpu, hardware, vram, rocm, amd, system and cuda
tests.

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

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

* Tighten the comments this PR adds

Comment-only pass at convergence. Three blocks trimmed wi…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants