Repository navigation
Studio: guard log volume in CI so it cannot regress unnoticed - #9665
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0d82f36c4c
ℹ️ 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".
| ): | ||
| classified |= set(getattr(hmod, attr, ()) or ()) | ||
|
|
||
| missing = sorted(classified - set(session.ALL_POLLS)) |
There was a problem hiding this comment.
Validate the registry against the actual pollers
Because classified is assembled only from backend suppression sets and compared with the hand-maintained session.ALL_POLLS, adding a frontend or Tauri timer for an otherwise normal endpoint changes neither side of this subtraction. For example, a new one-second GET /api/foo poll would remain in the normal 300 ms class and log every request, while both this closure check and the envelope replay—which also drives only ALL_POLLS—continue to pass. Derive or validate the registry from the actual polling call sites, or require pollers to register centrally, so the intended “cannot start polling without classifying it” guarantee holds.
Useful? React with 👍 / 👎.
| actual = set(debug_log_sources.FAMILIES) | ||
| added = sorted(actual - reviewed) |
There was a problem hiding this comment.
Reject removed log families as well as additions
This one-sided comparison allows any reviewed family to disappear from debug_log_sources.FAMILIES without failing. If, for example, server is accidentally removed while run.py still writes server-*.log, added remains empty and the retention checks also stop examining that family because they iterate the reduced mapping; the Logs viewer and the disk-bound guard therefore both silently lose it. Compare the sets for equality, or explicitly fail on reviewed - actual too.
Useful? React with 👍 / 👎.
| while elapsed < duration_s: | ||
| for path, (period, _provenance) in polled.items(): | ||
| if elapsed + 1e-9 >= next_due[path]: | ||
| send_request(Request(method = "GET", path = path, status = 200)) | ||
| next_due[path] = elapsed + period |
There was a problem hiding this comment.
Schedule requests at their declared poll times
For any declared period that is not a multiple of the fixed 0.5-second tick, setting next_due from the current rounded elapsed value permanently slows the simulated poller, while expected_emissions continues to use the unrounded period. For example, replaying the existing quiet /api/health class at a legitimate 0.7-second period for 300 seconds sends 300 requests and emits 30 records, but the formula expects 29 from 429 polls, so an otherwise correct middleware change fails this guard. Advance virtual time directly to due events, or at least increment deadlines from their previous due time rather than the rounded tick.
Useful? React with 👍 / 👎.
| actual = set(hmod._EXCLUDED_PATHS) | ||
| assert actual == reviewed, ( |
There was a problem hiding this comment.
Pin every exclusion mechanism that can hide failures
This safety check pins only _EXCLUDED_PATHS, although LoggingMiddleware also drops every response—including 4xx and 5xx—for paths matching _EXCLUDED_SUFFIXES or /assets/. Adding a broad suffix such as .json would therefore make matching API failures invisible while all signal-floor tests still pass, because their generated paths have none of those suffixes. Assert the reviewed suffix exclusions as well, and exercise a failing request through each exclusion mechanism.
Useful? React with 👍 / 👎.
| "revision; this check activates when that lands" | ||
| ) | ||
|
|
||
| match = re.search(r"Some\((\d+)\.\.=(\d+)\)", source) |
There was a problem hiding this comment.
Scope the Rust parity match to the filter implementation
Once is_backend_access_log_line exists, this regex takes the first Some(n..=m) anywhere in the entire process.rs, not the range used by that function. An unrelated Some(200..=299) elsewhere can therefore keep the Python-only parity job green after the filter changes to a different success range; the subsequent event-name and fixture checks are likewise whole-file substring checks. Parse or isolate the function/test body before checking these expressions so the asserted literals are actually tied to the implementation.
Useful? React with 👍 / 👎.
| # A single middleware object shared by every status, so its dedup map is the real one. | ||
| shared_state = LoggingMiddleware(_app_returning(200)) |
There was a problem hiding this comment.
Verify that the production app mounts the middleware
The replay always constructs LoggingMiddleware directly, so the non-vacuity assertions do not verify the production wiring they claim to protect. Removing app.add_middleware(LoggingMiddleware) from main.py would eliminate request logging in Studio while every new budget and signal-floor test still exercises this privately constructed instance and passes. Assert the middleware is present in the assembled application stack, or drive the replay through that stack rather than instantiating it here.
Useful? React with 👍 / 👎.
| def window_ms(handlers, cls: str) -> Optional[int]: | ||
| """The de-duplication window for a class, or None when 2xx never logs at all.""" | ||
| if cls in NEVER_LOGGED_ON_SUCCESS: | ||
| return None |
There was a problem hiding this comment.
Account for verbose mode in quiet-success budgets
Returning None for every quiet-success class assumes those successful requests are always dropped, but the production suppressor deliberately restores _QUIET_SUCCESS_PATHS and _CHAT_LIST_PATHS when both deduplication windows are nonpositive (--verbose); only _SELF_READ_PATHS remain suppressed. Under that supported environment, a ten-second replay of /api/export/status emits 10 records while this policy expects zero, causing the budget suite to fail for configuration rather than a regression. Either normalize the environment for this non-verbose budget or distinguish the self-read class and calculate verbose expectations correctly.
Useful? React with 👍 / 👎.
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.
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.
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.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d84785cb63
ℹ️ 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".
| try: | ||
| page.get_by_text(label, exact = True).first.click(timeout = 8_000) | ||
| except Exception: | ||
| info(f"note: could not reach {label!r}") | ||
| continue |
There was a problem hiding this comment.
Fail when the route walk reaches no sections
If every sidebar click fails—for example after a label or navigation change—this catch merely prints notes and the suite still passes: the comments above establish that the default screen already supplies the two globally polled paths needed by MIN_POLLED_PATHS. Consequently, the run can remain on one screen and miss every route-scoped timer it was added to validate. Require successful navigation to the reachable sections, rather than using the global two-path floor as evidence that the walk occurred.
Useful? React with 👍 / 👎.
| # two paths. Most timers belong to a section, so walk the sidebar and dwell on each | ||
| # long enough for a 5s poll to fire several times. Without this the suite passes by | ||
| # watching a screen where nothing could have regressed. | ||
| dwell = max(int(WATCH_S * 1000 / (len(SECTIONS) + 1)), 20_000) |
There was a problem hiding this comment.
Watch long enough to detect slower polling loops
With the defaults, this expression produces a 20-second dwell while POLL_THRESHOLD requires three requests. A global or route-scoped 15-second timer therefore produces at most two requests per dwell (even with an immediate first request), so it is omitted from polled; an undeclared endpoint at that cadence remains in the normal logging class and can add 120 lines per idle half-hour while both the browser check and backend registry tests pass. The newly added browser check exposes this fresh blind spot through its 20-second dwell/three-hit combination; size the dwell from the slowest cadence the guard intends to catch or detect periodicity without requiring three hits inside one dwell.
Useful? React with 👍 / 👎.
| "/api/inference/monitor": (5.0, "measured"), | ||
| "/api/inference/images/status": (5.0, "measured"), | ||
| "/api/inference/video/status": (5.0, "measured"), | ||
| "/api/inference/audio/stt/status": (5.0, "measured"), |
There was a problem hiding this comment.
Model the queried STT download poll separately
During a Transformers STT download, stt-download-mirror.ts polls this endpoint every 750 ms as /api/inference/audio/stt/status?model=..., not as the queryless five-second idle request recorded here. Production explicitly excludes queried liveness requests from the shared liveness bucket, so this supported flow gets its own roughly ten-second heartbeat, while bucket_of() treats the registered path as shared and the busy replay omits it entirely. That undercounts about 29 lines in the five-minute busy scenario—enough to exceed the current 260-line envelope—so represent the queried busy form and its actual cadence rather than collapsing both request modes into this idle entry.
Useful? React with 👍 / 👎.
| if glob not in source: | ||
| unbounded.append(f"{family} ({glob})") |
There was a problem hiding this comment.
Require size bounds for Python log families
This check treats the mere presence of a family's glob in a retention source as proof that the family is bounded, but run.py opens one server-*.log for the process lifetime and only deletes old files once at startup; it never rotates or caps the active file. A Studio instance left running can therefore grow that file without limit while this test remains green, despite the same file explicitly motivating the size-rotation assertion for tauri.log below. Verify a per-file size bound or rotation mechanism for Python families instead of equating file-count pruning with a disk bound.
Useful? React with 👍 / 👎.
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.
d84785c to
a575659
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a575659621
ℹ️ 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".
| while elapsed < duration_s: | ||
| for path, (period, _provenance) in polled.items(): | ||
| if elapsed + 1e-9 >= next_due[path]: | ||
| send_request(Request(method = "GET", path = path, status = 200)) |
There was a problem hiding this comment.
Record request methods in the poll registry
For a periodic non-GET request, the browser guard records only its path and this replay unconditionally converts it to GET. Production LoggingMiddleware._is_redundant_repeat explicitly never deduplicates mutations, so adding such a path to the registry and a quiet class as the browser failure instructs can make the replay predict heartbeat suppression while the real POST/PUT/PATCH/DELETE logs every request. Preserve the observed method in the registry and replay it so mutation-heavy polling is charged against the envelope correctly.
Useful? React with 👍 / 👎.
| offenders = { | ||
| path | ||
| for path, (period, _provenance) in session.ALL_POLLS.items() | ||
| if policy.classify(hmod, path) == policy.NORMAL | ||
| and period * 1000.0 > hmod._ACCESS_LOG_DEDUP_MS |
There was a problem hiding this comment.
Reject unintended suppression-class overlaps
This test checks only the single value returned by the first-match classify() function, so it does not establish the advertised “exactly one class” invariant. If a heartbeat path is accidentally added to _QUIET_SUCCESS_PATHS while remaining in _QUIET_POLL_PATHS, classification resolves it as quiet_success, the replay expects zero emissions, and every budget test passes even though the successful heartbeat has disappeared entirely. Count memberships directly and permit only the intentional _LIVENESS_POLL_PATHS subset overlap.
Useful? React with 👍 / 👎.
| @pytest.mark.parametrize("status", FAILURE_STATUSES) | ||
| def test_repeated_failures_all_log_on_every_classified_path(self, status, monkeypatch): |
There was a problem hiding this comment.
Exercise unhandled exceptions in the signal floor
The failure floor covers only applications that return an HTTP error response; it never drives the middleware's except branch. If request_failed logging is removed or broken for an unhandled route exception, all of these status-based checks and the volume ceilings still pass even though the structured traceback and request record disappear—the exact silent-deletion failure this file is intended to prevent. Add a terminal ASGI app that raises and assert that every occurrence emits request_failed before being re-raised.
Useful? React with 👍 / 👎.
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.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5d73d03532
ℹ️ 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".
| polled = {path: n for path, n in per_dwell_max.items() if n >= POLL_THRESHOLD} | ||
| undeclared = sorted(set(polled) - declared) |
There was a problem hiding this comment.
Compare observed cadence with the declared period
When an existing poll interval changes, this check compares only path membership and ignores the observed request count. For example, changing /api/models/local from its declared 20-second interval to 5 seconds leaves it in declared, while the backend replay still models 20 seconds; with the 10-second quiet window that raises its real idle contribution from 90 to 180 lines and can exceed the 1170-line envelope while every guard remains green. Validate the per-dwell cadence against the period stored in ALL_POLLS, with enough tolerance for runner timing.
Useful? React with 👍 / 👎.
| @pytest.mark.parametrize("case", _cases(), ids = lambda c: c["name"]) | ||
| def test_python_side_matches_the_shared_fixture(case): | ||
| dropped = is_successful_access_record(case["line"]) |
There was a problem hiding this comment.
Exercise the production backend rule with the fixture
If the backend changes the event name or its definition of a successful response, this test still passes because it evaluates a test-local reimplementation rather than LoggingMiddleware or its serialized output. The Rust side therefore remains checked against this duplicate Python rule, not against the backend behavior whose drift the fixture is intended to detect. Drive these cases through the production logging path or otherwise bind the assertion to the implementation in loggers/handlers.py.
Useful? React with 👍 / 👎.
| # Training panels, live only while a run is going. | ||
| "/api/train/status": (2.0, "declared"), | ||
| "/api/train/metrics": (2.0, "declared"), | ||
| "/api/train/hardware": (2.0, "declared"), | ||
| } |
There was a problem hiding this comment.
Budget the dynamic RAG job pollers
The current frontend contains concrete busy pollers missing from this registry: watchIngestion requests /api/rag/jobs/{job_id} every 2 seconds for up to 150 attempts, while watchProjectFolderJob and the linked-folder fallback request /api/rag/linked-folder-jobs/{job_id} every 3 or 1.5 seconds for up to 600 attempts. These ID-bearing paths match none of the exact suppression sets in loggers/handlers.py, so every successful request remains in the 300 ms normal class, yet neither busy replay includes them and the bare browser walk cannot enter these operation-gated flows. Add pattern-aware classification and representative busy scenarios so hundreds of lines from one RAG operation count against the envelope.
Useful? React with 👍 / 👎.
| # After a refresh succeeds, a 401 is real. | ||
| middleware._auth_refreshed = True | ||
| send(401) |
There was a problem hiding this comment.
Drive the auth refresh through the middleware
If the production /api/auth/refresh transition stops setting _auth_refreshed—for example because _AUTH_REFRESH_PATH drifts or the assignment is removed—this test still passes because it flips the private flag directly. In that failure mode every later chat-list 401 remains classified as pre-auth and is silently suppressed for the rest of the session, despite this test claiming to protect the post-refresh boundary. Send a successful refresh request through the same middleware instance before the final 401 instead of mutating its state.
Useful? React with 👍 / 👎.
| for family, (_subdir, glob) in debug_log_sources.FAMILIES.items(): | ||
| if family in _DESKTOP_FAMILIES: | ||
| continue |
There was a problem hiding this comment.
Verify retention for desktop phase-log families
If cross-group retention is removed or broken for backend, install, update, or repair phase logs, this suite remains green because all four families are skipped unconditionally; the later Rust-source checks cover only line-cap parity and tauri.log rotation. The existing PhaseLogWriter unit test creates a single install group and therefore verifies per-group segment rotation, not cleanup_retention across the successive groups that accumulate over an installation's lifetime. Exercise keep-newest-group retention for these desktop families instead of treating membership in _DESKTOP_FAMILIES as proof that they are bounded.
Useful? React with 👍 / 👎.
| let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) | ||
| .join("../backend/tests/fixtures/access_log_records.json"); | ||
| let raw = std::fs::read_to_string(&path) | ||
| .unwrap_or_else(|e| panic!("cannot read the shared fixture at {path:?}: {e}")); |
There was a problem hiding this comment.
Trigger the Rust consumer when the shared fixture changes
A backend-only change to this shared contract does not run the consumer added here: studio-tauri-smoke.yml triggers on studio/frontend/** and studio/src-tauri/**, but not studio/backend/**, while Backend CI never invokes Cargo. Consequently, a PR can update the backend rule and access_log_records.json together, pass the Python checks, and merge without executing this Rust agreement test; the same push filter also prevents detection on main. Add the fixture/backend parity paths to Tauri CI or run this targeted Cargo test from a workflow that those paths trigger.
Useful? React with 👍 / 👎.
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.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 517c3eb99a
ℹ️ 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".
| POLL_THRESHOLD = 3 | ||
|
|
||
| # Sidebar sections to walk, so section-scoped timers get a chance to run. | ||
| SECTIONS = ("Model hub", "Projects", "Images", "Train", "New chat") |
There was a problem hiding this comment.
Include the LAN-access poll in the settings walk
This route list never opens Settings, so it cannot observe the existing LanAccessSection loop: lan-access-section.tsx:221-241 requests /api/settings/lan-access every five seconds (lan-access-state.ts:58-59). That path is absent from ALL_POLLS and every suppression set, meaning an idle LAN settings pane writes 360 unbudgeted access records per half-hour while this browser guard and the 1170-line replay both remain green. Visit the relevant Settings tab and add the observed path and cadence to the registry so this existing blind spot is covered.
Useful? React with 👍 / 👎.
| from log_budget import policy, replay, session # noqa: E402 | ||
|
|
||
| # Every way a request can fail that a user or a support engineer would go looking for. | ||
| FAILURE_STATUSES = (400, 401, 403, 404, 409, 422, 429, 500, 502, 503) |
There was a problem hiding this comment.
Exercise redirect responses in the signal floor
This status corpus skips the entire 3xx class even though the shared access-log contract explicitly treats 300 as a non-success record that must remain visible. If either production suppressor broadens its success condition from 2xx to < 400, every test here still passes because it drives only 2xx successes and statuses of 400 or greater, while repeated redirects disappear from the backend log. Add a representative redirect boundary such as 300 or 307 to this floor.
Useful? React with 👍 / 👎.
| f" localStorage.setItem('unsloth_refresh_token', " | ||
| f"{json.dumps(session.get('refresh_token', ''))});" |
There was a problem hiding this comment.
Store the refresh token under the frontend's actual key
The frontend reads refresh credentials exclusively from unsloth_auth_refresh_token (features/auth/session.ts:13-48), while this initialization writes unsloth_refresh_token, which no frontend code reads. If a watched request receives a 401—for example during an extended local run whose access token expires—authFetch therefore cannot refresh the otherwise valid session, clears authentication, and the poll guard fails or abandons the route walk for an auth problem. Seed unsloth_auth_refresh_token so the browser session matches a real login.
Useful? React with 👍 / 👎.
Not from this PR. tests/studio/playwright_declared_polls.py came in with #9665 and the repo's own guard rejects it: a checked-in file read or written with the platform default encoding breaks on Windows the moment it gains a non-ASCII byte. It reached this branch through the merge with main and is the only red check here, so it is fixed rather than left blocking.
* 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>
Not from this PR. The file arrived with #9665 and the repo's own guard rejects a checked-in file written with the platform default encoding, since it breaks on Windows the moment that file gains a non-ASCII byte. It reaches this branch through main and is the only red check here.
The declared-polls probe writes observed_polls.json with the platform default encoding, so it breaks on Windows the moment that file gains a non-ASCII byte. tests/test_source_read_encoding.py catches exactly this and has been failing on main since #9665 landed, which blocks every open PR that merges main in. Pass encoding = "utf-8", matching every other checked-in file write in the test trees.
* Use --load-mode none when the model fits without paging llama.cpp builds its async pinned-buffer upload path only when mmap is off (llama-model-loader.cpp, upload_backend). With mmap on and a discrete GPU, buffer_from_host_ptr is unsupported, so every tensor takes a synchronous copy out of a page-faulting mapping instead. mmap earns its keep by demand-paging a footprint the machine cannot hold, so a load that fits does not need it. Pick --load-mode none whenever the whole load fits in VRAM, or in VRAM plus host RAM, and leave llama.cpp's own auto in place for anything larger, where the mapping is what stops an over-committed load from being killed outright. _fits_without_paging prices weights + projector + KV + MTP reserve + compute buffers + soft overhead against free VRAM on the devices the launch actually pins, then against available RAM less the same headroom the host-offload guard keeps free. Shared iGPU memory is dropped from the VRAM term and carried by the RAM term so it is never counted twice. An unsized KV or unreadable host RAM abstains and keeps auto, since an understated footprint would claim a fit that is not there and hand the load a loader that cannot page. Precedence is unchanged: the fit only fills in for a model with no pick of its own, an explicit per-model mode beats it, the Model Memory settings beat both, and a hand-typed flag in the extras still wins by last-arg. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Harden the fit-derived load mode against every path that voids the fit Five real holes found by walking the launch paths and the OS/GPU matrix: Unified memory was counted twice. A ROCm APU reports free "VRAM" out of the same pool the host-RAM term prices, so a 40 GB load against a 32 GB APU and 32 GB of RAM added up to 64 GB and "fit". Only Vulkan iGPUs were dropped from the VRAM term; the ROCm ones are now dropped too, off the same predicate the rest of the launch uses, and both end up priced against host RAM alone. An unreadable model size fell through as 0, so a load whose weights could not be sized was judged on its KV and buffers alone and could "fit". It abstains now, as does an engaged but unsized drafter, which the placement itself covers with a flat cushion rather than a number. Apple Silicon abstains outright. Metal is the one backend where buffer_from_host_ptr is supported, so mmap wraps the weights in a Metal buffer in place, zero copy and file backed; none would allocate the same bytes anonymously, and an evictable 30 GB mapping on a 32 GB machine is the difference between working and being jetsammed. MemAvailable is the wrong ceiling there anyway, per _apple_metal_memory_budget_bytes. The --fit on retry kept the flag. That retry exists precisely because the full-offload prediction did NOT hold, so the conclusion drawn from it cannot ride along into a launch that is about to offload to the CPU. It is dropped there now, mirroring how the page-lock is re-armed. The CPU fallback kept it too. That replay runs with --device none, so the VRAM half of the fit is void and the whole model has to come out of host RAM, which is exactly where mmap is what makes it survivable. Only Unsloth's own tokens are stripped in either place: _fit_load_mode_flags records the flag solely when the FIT chose it, so a mode the user asked for is theirs and survives every fallback. The verdict moves into _fit_derived_load_mode so the matrix can drive it directly. No behaviour change from the move. Tests: test_load_mode_fit_matrix.py walks [Linux, Windows, WSL, macOS] x [NVIDIA, NVIDIA multi, AMD discrete, AMD APU, Vulkan iGPU, CPU only] x [fits in VRAM, fits in VRAM plus RAM, fits nowhere], the whole policy chain over toggles x user pick x fit pick x build capability x host residency, and both fallback paths. The upgrade-safety case is checked against a literal copy of the pre-change chain: wherever the fit abstains, the argv is byte-identical. Also corrects the frontend note on what a null loadMode means, and records that "auto" is a value the b10360 line Studio ships today rejects outright, which is why it is never sent verbatim. * Measure the load modes end to end and name the picked one Ran every mode Studio can emit against a real llama-server (b10360, the build Studio ships today) on a B200 over local NVMe: 4 placements x 6 modes, each launched, timed to /health, and asked for a completion. All 20 valid combinations serve. The 4 that fail are --load-mode auto, which that build rejects outright; Studio never sends it, which the matrix test now pins. Load-to-ready, median of 3, full offload: Qwen3-4B Q4_K_M (2.5 GB) cold warm mmap (no flag) 1.81 1.42 none 2.04 1.49 dio 2.05 1.69 Qwen3-30B-A3B UD-Q4_K_XL (17 GB) cold warm mmap (no flag) 5.43 2.81 none 5.49 3.21 dio 2.26 2.30 That does not say what the first commit assumed. Dropping mmap does unlock llama.cpp's async pinned-buffer uploader, but "none" still reads through the page cache and pays that copy, and on this storage the copy costs more than the uploader wins: "none" is consistently a little SLOWER than plain mmap. "dio" takes the same uploader and skips the page cache, and on the model big enough for load time to matter it is 2.4x faster cold. So the picked mode is now a single named constant, _FIT_LOAD_MODE, with the measurements recorded beside it. It stays "none" because that is what was asked for, and the tests read the constant rather than the literal so flipping it moves the matrix with it. Also checked the MoE case from llama.cpp issue 14999, which reported memory errors with --no-mmap on MoE models and named unsloth dynamic quants. It does not reproduce on b10360: the UD-Q4_K_XL above loads and answers correctly under none, dio and mmap alike. * Void the fit's VRAM credit when something else owns the placement Three paths where the load-mode fit's proof stops holding but the flag it derived from that proof survives anyway. All three are the same shape as the --fit on retry and the CPU fallback this PR already handles. Pass-through placement overrides. The extras are appended AFTER this launch's own -ngl and llama.cpp assigns n_gpu_layers and devices on every occurrence, so a hand-typed -ngl 0, a --device naming no GPU, or a CPU tensor override runs the weights out of host RAM the planner had just credited to a card. The Model Memory host-residency gate already carries exactly this guard for the page-lock decision, with the same last-wins reasoning; the load-mode decision was the one sibling without it. The VRAM credit is dropped rather than abstaining, because a load host RAM holds whole is still safe wherever those flags put it. The mass case is not a hand-typed -ngl but the common MoE paste, --n-cpu-moe N or -ot ".ffn_.*_exps.=CPU". A CPU-pinned separate drafter. Dropping it from the VRAM budget is right, none of it is on the GPU, but the bytes did not go anywhere, they moved to host RAM, and llama.cpp carries the process-wide load mode into the draft model (common_base_params_to_speculative starts from result = params and overrides only devices, model and n_gpu_layers), so none de-mmaps the draft GGUF too. Charging it is the same reasoning that already keeps a CPU-pinned projector in the footprint. Unpriceable means abstain, like every other unreadable term. Only reachable when the target keeps recurrent rollback state, since otherwise the replaced overhead callback goes None and the fit abstains already. The arch-crash retry. It replaces the pinned device set with the survivors, a set the fit never priced, and respawns from cmd. Its two host guards are weights-only floors by design, so they cannot re-establish a whole-footprint proof, and host-resident weights without mmap are anonymous rather than file-backed, which is an OOM where the mapping would only have paged. Only Unsloth's own tokens are stripped, so a mode the user asked for still survives every fallback. * Stop VRAM paying for host-only bytes, and for the fitter's own margin Three follow-ups on last round's fixes. A CPU-pinned drafter was pooled into the aggregate footprint, so the free-VRAM fast path could satisfy bytes the child only ever allocates on the host. -ngld 0 is not in _GPU_LAYER_FLAGS either, so the pass-through override guard never voids the VRAM credit for it. It becomes host_only_bytes: counted in the whole footprint, charged to the RAM term alone. The spill is now one expression rather than a fast path plus a subtraction, and is bit-identical when the new terms are zero. Under --fit on, llama.cpp's fitter keeps --fit-target free on every device it uses (default 1024 MiB, common/common.h fit_params_target) and spills weights to host RAM rather than dip into it, so that margin is not VRAM this fit may spend. It is now subtracted per device. Zero on the proved path, which emits -ngl -1 --fit off and runs no fitter at all. _fit_target_margin_mib is the one reader for both the emitted flag and the fit, so the margin the child is told to keep and the margin the fit refuses to spend cannot drift. The --fit on retry cleared the recorded tokens after stripping them from its own argv, but that record describes cmd, which the retry never rewrites. A kernel-image crash reaches that arm first, since it excludes only the split-axis and HIP/ROCr cases, so the arch-crash and CPU fallbacks that respawn from cmd were left carrying a mode they could no longer name. The record is kept until a retry rewrites cmd itself; stripping an already stripped argv is a no-op. * studio: read device env and effective fit state when deriving load mode Three narrow corrections to the fit-derived --load-mode none decision: - The guard that voids the VRAM credit now passes the launch env into _device_selection_is_cpu and _env_places_tensors_on_cpu. It was the only caller omitting it, so an inherited LLAMA_ARG_DEVICE=none ran the model on CPU while the fit still credited every card. It also counts an explicit --device narrowing against the number of devices the fit credited, since --device is opt-in under auto GPU selection and never stripped there. - The fitter margin is charged from the effective --fit state rather than Studio's own use_fit. -ngl -1 is llama.cpp's own default, and the fitter aborts only on a value that differs from the default, so a pass-through --fit on still rewrites the layer split. A pass-through --fit-target is now read as well, via fit_target_margin_in. - The no-flash-attention retries drop the derived load mode at both sites (startup crash and MTP first decode). The MLA KV estimate prices only bpe_k and ignores flash_attn, so the f16 K upcast on that retry is unpriced. Adds coverage for inherited LLAMA_ARG_DEVICE, --device narrowing including last-wins, fit_target_margin_in, effective fitter state, and both no-flash strip sites. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: close four gaps in the load-mode footprint - Void the VRAM credit on an inherited LLAMA_ARG_N_GPU_LAYERS. It is the env twin of the layer flags, and it bites harder than the tokens: the fitting arm emits --fit on and no -ngl, so an inherited count is the only layer policy the child sees, and llama.cpp refuses to fit a count it did not set, downgrading the refusal to a warning rather than aborting. auto and -1 are the default and still leave the fitter free, so they do not void it. - Abstain on an engaged but unsized MTP draft cache. The condition re-derived a weaker predicate from _flat_mtp_engages, which dropped the case where the overhead callback exists but prices no draft KV. Use the predicate whole. - Charge the fixed per-device pipeline overhead. A layer split puts a CUDA context and scratch on every device; the flat compute buffer covers one and the CUDA reserve is charged once, so the extra devices were free in the footprint but not in reality. Zero on a single GPU. - Charge the CPU drafter's decode graph to host RAM. _soft_overhead adds that constant only while the drafter reserves GPU memory, which is false for exactly the placement _cpu_resident_draft_bytes describes, so it was in neither budget. All four made the footprint read smaller than the load, so each could turn a no-fit into a claimed fit. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: void the pooled fit when the split or the device pin changes - A pass-through --split-mode or --tensor-split survives into the child on an automatic load and lands after Studio's own placement flags. --split-mode none puts the whole model on the main GPU, and a --tensor-split that zeroes a device (explicitly, or by being short, since upstream zero-fills the tail) leaves that card holding nothing, while the fit still credits the pool. New split_policy_starves_devices reads the effective policy, argv last-wins over the env twin, and is value-aware: layer, row and tensor keep every device, so a restatement is not treated as an override. - Vulkan is the one backend whose device names can be checked exactly, because the pin Studio emits is built from the credited ordinals as Vulkan<i>. Hold a surviving --device to that set rather than to a count, which catches a same-sized list naming different cards and a longer one adding a device the footprint charged no compute or overhead for. CUDA and ROCm stay on the count, since their ordinals are assigned after a visibility mask this launch has not written yet. - A CPU-pinned projector is host-resident, so it is charged to host RAM rather than left for surplus VRAM to cover. Otherwise a model comfortably inside the card could answer yes without consulting RAM at all, on a host too small to hold the projector. All three let the footprint be paid for by memory the child will not use. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: price KV offload, split policy and replicated buffers in the fit - Charge a CPU-only KV cache to host RAM. --no-kv-offload puts the whole cache in system memory whatever the layer placement does, and the fit had never consulted it. Charged on the host-only side of the predicate alone, the way the pinned projector already is, so the footprint does not count it twice. - Read slash-separated --fit-target values. Upstream splits that flag on both , and / with the same regex --tensor-split uses, so 4096/4096 parsed as nothing and the launch fell back to a smaller managed margin while llama.cpp kept 4 GiB free per device. - Charge the replicated compute buffer when tensor parallelism is planned. That split reserves a per-device buffer, and the fit was charging the layer-split lump, which at one slot drops the vocab-width output buffer entirely. - Abstain when a drafter is split across host and device. -ngld 1 is not -ngld 0, so the CPU-drafter path did not fire and the whole drafter was priced as GPU-eligible. Scoped by the drafter's own layer count so a full offload is not mistaken for a split. - Count distinct devices when deciding whether --device narrows. llama.cpp does not dedup an explicit device list, so CUDA0,CUDA0 is one pool listed twice and its free VRAM is counted twice downstream. - Keep discrete ROCm cards in the credit. The unified-memory union was blanket over every row, so one APU beside a discrete card marked the discrete card shared, against this helper's own contract. Manual placement was raised as a seventh item and is not a bug: every manual branch sets gpus = [], so the VRAM credit is already zero there. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: price checkpoints, inherited projectors and loader modes in the fit - Strip the fit's load mode on the CPU-projector retry. That respawn builds from the last argv and only appends --no-mmproj-offload, so it was the one recovery path still carrying --load-mode none. The retry moves the projector bytes to the host, which is exactly what the proof had counted against VRAM. - Pass the effective context-checkpoint count into the fit's KV estimate. The estimator already charges the snapshots and every placement route passes the count; the closure the fit consumed did not. On an SWA model at 8192 context eight snapshots take the cache from 1.49 to 4.43 GiB, so the footprint was short by nearly 3 GiB. - Price a projector inherited through LLAMA_ARG_MMPROJ. The vision gate keys on Studio's own resolved path, so an env-only projector contributed nothing to the footprint while still being loaded by the child. Charged to host RAM when it is pinned to the CPU and to VRAM otherwise; a URL or an unreadable path abstains, since neither can be sized here. - Let an inherited loader mode win over the derived one. LLAMA_ARG_LOAD_MODE and the mmap and mlock env twins are read before argv and assign the same field, so the managed flag silently beat an operator's explicit choice. This PR already gives a hand-typed --load-mode the last word; the env twin now gets the same treatment, as it does for device, layers, split and fit-target. Constrained tensor-split ratios were raised as a fifth item and are not a bug here: the fitter refuses to run at all once the user has set a split, so no weights spill to host RAM and the load fails identically under either mode. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Assert the guard's clauses rather than one rendering of them The source-text pin added last round matched a single-line if. The formatter wrapped it, which inserts a paren, so the pin failed on a change that altered no behaviour. Each clause is now asserted separately, which still fails if the guard loses one. * studio: three placement fixes found in round 8 review Draft block-count threshold. _draft_is_split_across_host treated -ngld equal to the draft's block count as a whole-drafter placement. llama.cpp computes i_gpu_start = max(n_layer_all + 1 - n_gpu_layers, 0) (llama-model.cpp), so the count has to clear the block count by one to reach zero. With 28 blocks and -ngld 28 the start is 1, and block 0 plus its KV stay on the host. The review that raised this said the output layer was stranded; it is not, output sits at il = n_layer_all and lands on the GPU. Block 0 is what stays behind, and the threshold conclusion is right either way. This was the lone outlier in the tree: _partially_offloads_layers already uses requested <= n_layers and the pipelining check already uses 0 <= gpu_layers <= n_layers. Direction is the usual dangerous one, VRAM credited for a block that never reaches the card. Pass-through adapter weights. --lora, --lora-scaled, --control-vector and --control-vector-scaled all clear the pass-through denylist, and the fit sized itself from the base GGUF alone. llama.cpp allocates adapter tensors on the base tensor's own buffer type (llama-adapter.cpp) with no mmap on that path, so the bytes are resident whatever --load-mode says, on top of a placement the fitter never accounted for. Now priced, with an abstain when an adapter cannot be sized. User load mode across chained retries. _without_subsequence removes the first value match, so a user who typed the same --load-mode none the fit derived left two identical pairs in the argv: one rung removed the fit's and recorded the stripped argv in _last_spawn_cmd, and the next rung removed theirs. This one was introduced by this PR, since before it the fit never populated _fit_load_mode_flags. The tree already stands the fit's mode down when the environment selects one; the extras now get the same treatment. Their pair already governed by last-arg, so emitting the fit's was inert noise and standing aside costs nothing while making every downstream strip the no-op its docstring claims. A fourth item, on --mmproj-auto, was rejected. That flag only sets params.no_mmproj, consumed solely in the Hugging Face download plan behind if (!params.model.hf_repo.empty()) (common/arg.cpp). There is no local adjacent-file discovery, Studio launches from a local -m path, and -hf is rejected by the pass-through validator, so the flag is inert here. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: price legacy scaled adapters, record the fit's loader Legacy two-token scaled adapters. _sidecar_adapter_paths read only today's colon syntax, so --lora-scaled /m/a.gguf 0.5 priced zero bytes. Builds up to the turn of the year declared the flag as {"--lora-scaled"}, "FNAME", "SCALE" and took the scale as a second token, and Studio runs whatever llama-server it is pointed at. The tree was already inconsistent about this: the pass-through validator deliberately admits the shape via _OPTIONAL_SECOND_VALUE_FLAGS and _sidecar_weight_files already reads it as a file, so only the pricer disagreed. Colon is still read first, and the operand is priced whole only when the colon parse found nothing and the next token is a bare number, which is also the reading that survives a Windows drive letter. Measured before the fix: an 18 GiB model with a 3 GiB adapter on a 20 GiB card returned none. The launched loader is now in the memory state record. cmd carries the load-mode pair between the Model Memory block and the extras, but the record was rebuilt from those two parts alone, so the pair was dropped. "none" holds a full anonymous host copy, so the omission is the difference between recording a launch as reserving and as not, and a later "Don't reserve system RAM" is then judged already satisfied by both the settings route and the duplicate-load comparator, keeping the reservation instead of relaunching with mmap. The two retry paths re-record over the whole argv and always captured it; only the initial record reconstructed from parts. The arch-crash retry needs the mirror of this: it strips the pair from cmd and then restores a snapshot taken while cmd still carried it, so that restore is re-derived. Worth stating plainly: the record omission is older than this PR. The merge base has the same expression and it equally hid an explicit per-model --load-mode none. What this PR adds is a path that reaches it with no user pick at all, which is why it is fixed here. Two review items were rejected. --mmproj-auto only sets params.no_mmproj, whose sole consumer sits inside the Hugging Face download plan behind if (!params.model.hf_repo.empty()), and -hf is denied by the pass-through validator, so the term is zero on every reachable launch. Context checkpoints are created lazily during decode rather than allocated at load, the default 32 is unreachable below roughly a 262144 context because checkpoint_min_step is 8192, and charging them to the KV pool would put a host-only copy in VRAM. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: charge an inherited projector the same safety allowance A projector resolved for the launch is priced at file size plus 40 percent (_MMPROJ_VRAM_SAFETY), because the runtime buffer runs about 1.3x the file. One inherited from LLAMA_ARG_MMPROJ was priced at raw file size with no allowance at all. The gate is effective_is_vision, which is itself gated on launch_mmproj_path, and the inherited arm is reached only when that path is empty, so the allowance could never apply there. Direction is the dangerous one: the footprint comes out 40 percent of a projector short, which is how a load that does not fit gets a --load-mode none that leaves it unable to page. Charged on the VRAM arm only. When the resolved offload says CPU the bytes are host-resident and the resolved projector is charged raw there too, so both arms keep the same split. Two review items were rejected. Letting an explicit --mlock stand the fit down is a no-op twice over: --mlock sets LLAMA_LOAD_MODE_MLOCK (common/arg.cpp) and use_mmap is only set for mmap, mmap+mlock and auto (llama-model-loader.cpp), so a bare --mlock is already a no-mmap full host copy rather than the mmap-plus-lock the item assumes; and the managed block is appended before the user extras, which llama.cpp resolves last-wins, so their flag already governs. The environment case genuinely does need its own check, because llama.cpp reads LLAMA_ARG_* before argv, which is why the two are treated differently. The other item asks for user-facing help text describing Auto as fit-derived; the premise is right but it is documentation rather than a correctness defect. * studio: recompute the memory record on every rung that strips the loader Three rungs already re-recorded the effective memory state after dropping the fit's --load-mode none, and three did not. Without "none" the child is back on llama.cpp's auto, which maps (common.h defaults load_mode to auto and llama-model-loader derives use_mmap from mmap, mmap+mlock and auto), so a record still saying the launch reserves RAM makes memory_state_satisfies_settings answer a later "Don't reserve system RAM" with a full reload the running server already satisfies, and the settings route hint agrees with it. Pessimistic rather than dangerous, but wrong, and the invariant was already kept elsewhere. Two of the three were the no-flash and CPU-projector rungs, raised in review. The third I found while checking the remedy the review proposed. The arch-crash rung rebuilt the record from _mem_managed + _mem_extras, and its comment claimed that was what remained after removing the pair. It is not: by that point cmd may have been reassigned to the CPU, device-gated, no-tensor-split or arch-retry argv, so the parts no longer add up to it and anything memory-relevant those paths added is dropped. That direction is the opposite one, recording an unlocked child that is in fact locked, which is why it is worth fixing rather than leaving. All three now recompute from the stripped argv, which is what the --fit on and --fit off rungs already did. * studio: honour the negative KV-offload env alias, and one more record rung LLAMA_ARG_NO_KV_OFFLOAD was ignored. common/arg.cpp registers -kvo with args_neg -nkvo and set_env("LLAMA_ARG_KV_OFFLOAD"), and get_value_from_env rewrites LLAMA_ARG_ to LLAMA_ARG_NO_ and, when that variable EXISTS, sets the value to "0" and returns before it ever reads the affirmative one. So presence decides, not truth: LLAMA_ARG_NO_KV_OFFLOAD=0 or an empty value disables offload just as well, and it beats LLAMA_ARG_KV_OFFLOAD=1. Environment is processed before argv. Missing it left _kv_on_host False, which keeps the cache bytes in the pooled term free VRAM may pay for, so the fit could answer "fits" on a load whose cache is entirely host-resident and hand it --load-mode none. That is an OOM where llama.cpp's auto would have paged. The same negative-alias rule is already documented and implemented in this tree for the mmap and direct-IO pairs; this helper was simply not updated. The argv loop is untouched, so a command line -kvo still takes it back. The CPU fallback is the fourth rung that strips the fit's --load-mode none without recomputing the memory record, after the three fixed last round. Same pessimistic consequence: the record still says the launch reserves RAM while the stripped child is back on auto and maps, so a later "Don't reserve system RAM" spends a full reload the running server already satisfies. Both entry points are covered, the crash path and the replayed request. The crash path recomputes from _last_spawn_cmd rather than from the parts, since the --fit retries append a page-lock to their own argv and rebuilding would record it away. * Pass encoding=utf-8 in the declared-polls artefact write Not from this PR. tests/studio/playwright_declared_polls.py came in with #9665 and the repo's own guard rejects it: a checked-in file read or written with the platform default encoding breaks on Windows the moment it gains a non-ASCII byte. It reached this branch through the merge with main and is the only red check here, so it is fixed rather than left blocking. * Describe what Auto actually does now in the load-mode hint The hint still said Auto memory-maps unless a device cannot, which was true before this PR. Auto now runs the fit first and picks None when the model is proved to fit without paging, falling back to llama.cpp's own choice otherwise, so the text described behaviour the option no longer has. Raised in review and initially declined as documentation rather than a defect, which was the wrong call for the one string a user actually reads before choosing. The API docstring for the same field is left alone: it describes the wire contract, where omitting the field really does mean the llama.cpp default. * Tighten the comments around the fit-driven load mode --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Log reduction in Studio is several PRs deep (#6377, #7087, #8310, #8311, and #8763 open) and every round started the same way: someone noticed a log was huge, measured it, and trimmed it. Nothing stops the next chatty endpoint, and nothing tells the author they added one. This adds the guard.
Five checks, all CPU-only, no network, no sleeping. A 30 minute idle session and a 5 minute in-flight session are replayed through the real
LoggingMiddlewareagainst a virtual clock, so a thirty minute scenario runs in about a second and lands identically on a loaded runner. Real sleeps would put every assertion within scheduler noise of a window boundary, which is how a guard like this gets flaky and then deleted.Why the signal guard exists
An upper bound on log lines, on its own, is a dangerous test. It passes just as well when the middleware was never mounted, when the logger got replaced with a no-op, when the scenario stopped issuing requests, or when someone deleted an error log to get under the number. Every one of those is a worse outcome than the regression the cap is there to catch. So the floor is asserted too: repeated 4xx and 5xx on every classified path, repeated mutations, a healthy poll that starts failing mid-window, and explicit lower-bound sentinels on the boot scenario.
The counts are derived, not recorded. Widening a dedup window moves the expectation with it, so only a genuine rule violation fails rather than every deliberate tuning change.
Two ledgers, both self-expiring
Introducing a guard to a codebase that already has violations means either recording them or weakening the rule. Weakening it would defeat the point, so they are recorded:
KNOWN_UNCLASSIFIED_POLLS:/api/settings/remote-access(360 lines per idle half hour) and/api/liveness(120) sit in the 300 ms burst class and write a line per poll. Both are fixed by fix(logs): quiet the polls and drop the duplicated access lines #8763.KNOWN_UNBOUNDED_FAMILIES:llama-serveranddiffusion-serverwrite one file per load attempt and never prune. Also fixed by fix(logs): quiet the polls and drop the duplicated access lines #8763.Both are self-expiring. The tests fail if an entry is no longer a violation, so fixing one forces its removal and neither list can quietly become permanent.
Sharp edges this pinned rather than papered over
_EXCLUDED_PATHSis the one suppressor not gated on a 2xx: the check runs before the status is known, so a 500 on/api/train/statusis invisible in the access log. That may be the right trade for a metrics endpoint polled twice a second, but the set should not grow by accident, so its exact contents are now asserted.Verification
Verified by mutation. Eight deliberate breakages, each turning exactly the intended guard red and nothing else: an unclassified new poll, a widened window, ungating suppression from the status, dropping a member out of the shared liveness bucket, growing the excluded set, widening the 401 exemption past bootstrap, and both directions of the self-expiring ledger.
No workflow changes:
studio-backend-ci.yml's "Repo tests (CPU)" already auto-discoversstudio/backend/tests.Three checks skip on this revision and activate when the desktop-side filter from #8763 lands: the Rust success range, the shared-fixture Rust test, and the mirrored-line cap.